### DeviceFileInfo usage example Source: https://github.com/alos-no/dji-mission-installer Shows how to retrieve file info via GetFileInfo and safely access Size and LastModified with null-coalescing. ```csharp DeviceFileInfo? info = deviceOps.GetFileInfo(waypointKmzPath); var size = info?.Size ?? 0; var modified = info?.LastModified ?? DateTime.MinValue; ``` -------------------------------- ### WaypointFileInfo usage example Source: https://github.com/alos-no/dji-mission-installer Constructs a WaypointFileInfo instance with a GUID-like id and device paths for the .kmz and preview .jpg. ```csharp var slot = new WaypointFileInfo( id: "b0f1...", deviceKmzPath: "/storage/emulated/0/Android/data/dji.go.v5/files/waypoint/b0f1.../b0f1....kmz", deviceImagePath: "/storage/emulated/0/Android/data/dji.go.v5/files/waypoint/map_preview/b0f1.../b0f1....jpg", fileSize: 1024, lastModified: DateTime.Now); ``` -------------------------------- ### Clone the DJI Mission Installer repository Source: https://github.com/alos-no/dji-mission-installer/blob/main/README.md Use this command to clone the project source from GitHub before building it in Visual Studio. Requires Git to be installed. ```sh git clone https://github.com/Alos-no/DJI-Mission-Installer.git ``` -------------------------------- ### AppHost basic usage example Source: https://github.com/alos-no/dji-mission-installer Shows how to instantiate AppHost and resolve MainViewModel, IDeviceOperations, and IConfigurationService from its Services property, then construct and show MainWindow. ```csharp var host = new AppHost(); var viewModel = host.Services.GetRequiredService(); var deviceOps = host.Services.GetRequiredService(); var cfg = host.Services.GetRequiredService(); var window = new MainWindow(viewModel, deviceOps, cfg); window.Show(); ``` -------------------------------- ### ConfigurationService reset example Source: https://github.com/alos-no/dji-mission-installer Shows Reset() re-applying all default values (Documents\DJI\KMZ, empty key, UseAdbByDefault=true) and then calling Save(). ```csharp var cfg = new ConfigurationService(); cfg.KmzSourceFolder = @"C:\Custom"; cfg.Reset(); // back to Documents\DJI\KMZ, empty key, UseAdbByDefault=true Console.WriteLine(cfg.UseAdbByDefault); ``` -------------------------------- ### InitializeAsync Source: https://github.com/alos-no/dji-mission-installer Initializes the ADB client by starting the ADB server. Must be called before any other operation. ```APIDOC ## InitializeAsync ### Description Initializes the ADB client by starting the ADB server. Must be called before any other operation. ### Method InitializeAsync ### Parameters None ### Response #### Success Response - No return value #### Error Response - `InvalidOperationException` - If the server fails to start: `"Failed to start ADB server. Result: {result}"` - `FileNotFoundException` - If `adb.exe` is not found ### Request Example ```csharp await adb.InitializeAsync(); ``` ``` -------------------------------- ### Using MissionTransferOutcome with TransferAsync Source: https://github.com/alos-no/dji-mission-installer Example of awaiting TransferAsync and checking outcome.Success to print the preview path. Note that Success is always true on normal completion; the service returns the outcome instead of throwing for preview fallback. ```csharp MissionTransferOutcome outcome = await transferService.TransferAsync( deviceOps, mapService, imageService, kmzReader, sourceKmz, targetSlot, Const.DefaultZoomLevel, Const.DefaultPreviewWidth, Const.DefaultPreviewHeight); if (outcome.Success) Console.WriteLine($"Preview saved to {outcome.LocalPreviewPath}"); ``` -------------------------------- ### MtpDeviceInfo usage example Source: https://github.com/alos-no/dji-mission-installer Creates an MtpDeviceInfo from an existing IDeviceInfo instance using the FromDeviceInfo static method. ```csharp var mtp = MtpDeviceInfo.FromDeviceInfo(adbInfo); ``` -------------------------------- ### ConfigurationService usage example Source: https://github.com/alos-no/dji-mission-installer Shows creating a ConfigurationService, reading and setting properties, and calling Save(). GoogleMapsApiKey is persisted but not read back by any code in the current source. ```csharp var cfg = new ConfigurationService(); string folder = cfg.KmzSourceFolder; // e.g. Documents\DJI\KMZ by default cfg.KmzSourceFolder = @"C:\MyMissions"; cfg.GoogleMapsApiKey = "AIza..."; // persisted but not used by any reader in this version cfg.UseAdbByDefault = true; cfg.Save(); ``` -------------------------------- ### InitializeAsync Source: https://github.com/alos-no/dji-mission-installer Initializes the ADB client by locating adb.exe, starting the ADB server, and creating an AdbClient. This method is idempotent and must be called before any other device operations. ```APIDOC ## InitializeAsync ### Description Initializes the ADB client by locating adb.exe, starting the ADB server, and creating an AdbClient. This method is idempotent and must be called before any other device operations. ### Method InitializeAsync ### Signature `public async Task InitializeAsync()` ### Parameters None ### Returns `Task` - A task representing the asynchronous operation. ``` -------------------------------- ### FileSystemUtils.WatchFolder usage example Source: https://github.com/alos-no/dji-mission-installer Example call to WatchFolder with a filter of "*.kmz" and handlers for changed and renamed events. The returned watcher is owned and disposed by the caller. ```csharp FileSystemWatcher w = FileSystemUtils.WatchFolder(path, "*.kmz", onChanged: (_, e) => Console.WriteLine($"Change: {e.FullPath}"), onRenamed: (_, e) => Console.WriteLine($"Renamed: {e.OldName} -> {e.FullPath}")); // caller owns and disposes the watcher when done ``` -------------------------------- ### FolderPickerService usage example Source: https://github.com/alos-no/dji-mission-installer Shows how to call PickFolder with an initial path and handle the result. Returns null if the user cancels or any COM step fails non-critically. ```csharp var picker = new FolderPickerService(); string? folder = picker.PickFolder(@"C:\Missions"); if (folder is null) Console.WriteLine("Cancelled"); else Console.WriteLine($"Chose: {folder}"); ``` -------------------------------- ### Error handling for missing KmzFile Source: https://github.com/alos-no/dji-mission-installer Guards against a missing underlying file by throwing FileNotFoundException. KmzFile never throws on its own, so check existence before use. ```csharp if (!File.Exists(kmz.FullPath)) throw new FileNotFoundException("Mission source missing.", kmz.FullPath); ``` -------------------------------- ### Basic usage of DeviceOperationsFactory Source: https://github.com/alos-no/dji-mission-installer Shows how to create an IDeviceOperations instance for a specific connection type and initialize it. The example uses DeviceConnectionType.Adb and calls InitializeAsync. ```csharp DeviceConnectionType type = DeviceConnectionType.Adb; IDeviceOperations ops = DeviceOperationsFactory.Create(type); // AdbDeviceOperations await ops.InitializeAsync(); ``` -------------------------------- ### CurrentFolder Property Source: https://github.com/alos-no/dji-mission-installer Gets the current watched folder path. Updated by ChangeKmzFolder. ```APIDOC ## CurrentFolder Property ### Description Gets the current watched folder path. Updated by ChangeKmzFolder. ### Property `string CurrentFolder { get; }` ### Returns - `string` - The current watched folder path. ### Example ```csharp Console.WriteLine(fs.CurrentFolder); ``` ``` -------------------------------- ### IDeviceOperations.InitializeAsync() Source: https://github.com/alos-no/dji-mission-installer Initializes the transport for device operations. For ADB, starts the ADB server; for MTP it is a no-op. Idempotent. ```APIDOC ## InitializeAsync() ### Description Initializes the transport. For ADB, starts the ADB server; for MTP it is a no-op. Idempotent. ### Method InitializeAsync ### Return Type Task ### Parameters None ``` -------------------------------- ### DialogService usage example Source: https://github.com/alos-no/dji-mission-installer Shows how to instantiate DialogService and call its async methods. Both methods are marshalled to the dispatcher and do not throw from user dismissal; behavior is undefined if Application.Current is null (e.g., headless tests). ```csharp IDialogService dialogs = new DialogService(); await dialogs.ShowErrorAsync("Transfer failed", ex.Message); await dialogs.ShowInfoAsync("Success", "Mission uploaded."); ``` -------------------------------- ### Usage of WaypointFileInfoEx extension methods Source: https://github.com/alos-no/dji-mission-installer Shows how to call the extension methods to get the KMZ path, image path, and local preview URI. The local preview URI may be null if construction fails; check for null and file existence before using. ```csharp using DJI_Mission_Installer.Extensions; string kmzPath = slot.GetDeviceKmzPath(deviceInfo); string imgPath = slot.GetDeviceImagePath(deviceInfo); Uri? localPreview = slot.GetLocalImageUri(); if (localPreview != null && File.Exists(localPreview.AbsolutePath)) // preview already downloaded ``` -------------------------------- ### FileListItem usage example Source: https://github.com/alos-no/dji-mission-installer Shows constructing a local row from a KmzFile and a device row from a WaypointFileInfo, then printing DisplayName for each. The local row uses a file path; the device row uses an id, kmz path, image path, size, and timestamp. ```csharp var local = new FileListItem(new KmzFile(new FileInfo(@"C:\Missions\takeoff.kmz"))); var device = new FileListItem(new WaypointFileInfo("id1", kmzPath, imgPath, 0, DateTime.Now)); Console.WriteLine($"{local.DisplayName} ({local.FileItemType})"); Console.WriteLine(device.DisplayName); ``` -------------------------------- ### Basic usage of KmzFile Source: https://github.com/alos-no/dji-mission-installer Constructs a KmzFile from a FileInfo and prints its name and size. Used to access file metadata for a .kmz mission file. ```csharp var kmz = new KmzFile(new FileInfo(@"C:\Missions\takeoff.kmz")); Console.WriteLine($"{kmz.Name} ({kmz.FileSize} bytes)"); ``` -------------------------------- ### ViewModelBase usage example Source: https://github.com/alos-no/dji-mission-installer Shows a derived view model using SetProperty to implement a bindable property with change notification. ```csharp public class MyVm : ViewModelBase { private int _count; public int Count { get => _count; set => SetProperty(ref _count, value); } } ``` -------------------------------- ### IDeviceOperationsSwitcher interface Source: https://github.com/alos-no/dji-mission-installer Allows switching between device connection types. Implemented by SwitchableDeviceOperations. ```csharp public interface IDeviceOperationsSwitcher { DeviceConnectionType CurrentType { get; } Task SwitchToAsync(DeviceConnectionType type, bool initialize = false); } ``` -------------------------------- ### Error handling for InitializeAsync Source: https://github.com/alos-no/dji-mission-installer Catches FileNotFoundException when adb.exe is missing and InvalidOperationException when the server fails to start. Use after calling InitializeAsync to handle common startup failures. ```csharp try { await adb.InitializeAsync(); } catch (FileNotFoundException ex) { // adb.exe missing } catch (InvalidOperationException ex) { // server failed to start } ``` -------------------------------- ### ConfigurationService.UseAdbByDefault Property Source: https://github.com/alos-no/dji-mission-installer Gets or sets whether ADB should be used by default. Reads from or writes to the 'UseAdbByDefault' setting in the application configuration. ```APIDOC ## ConfigurationService.UseAdbByDefault Property ### Description Gets or sets whether ADB should be used by default. Reads from or writes to the 'UseAdbByDefault' setting in the application configuration. ### Type `bool` ### Get Behavior `Convert.ToBoolean` of `"UseAdbByDefault"` via `ConfigurationManager.AppSettings`. ### Set Behavior Writes `value.ToString()` (`"True"`/`"False"`). ### Default Value `"True"` ``` -------------------------------- ### ImageUtils.LoadImageWithCopyOption usage Source: https://github.com/alos-no/dji-mission-installer Example call to LoadImageWithCopyOption with a local preview path. The returned image is Freeze()d, making it safe to use on another thread. ```csharp var img = ImageUtils.LoadImageWithCopyOption(localPreviewPath); // img is Freeze()d — safe on another thread ``` -------------------------------- ### ConfigurationService.KmzSourceFolder Property Source: https://github.com/alos-no/dji-mission-installer Gets or sets the KMZ source folder path. Reads from or writes to the 'KmzSourceFolder' setting in the application configuration. ```APIDOC ## ConfigurationService.KmzSourceFolder Property ### Description Gets or sets the KMZ source folder path. Reads from or writes to the 'KmzSourceFolder' setting in the application configuration. ### Type `string` ### Get Behavior Reads setting `"KmzSourceFolder"` via `ConfigurationManager.AppSettings`. ### Set Behavior Writes setting. ### Default Value `Path.Combine(MyDocuments, "DJI", "KMZ")` ``` -------------------------------- ### AdbDeviceInfo usage example Source: https://github.com/alos-no/dji-mission-installer Creates an AdbDeviceInfo instance from DeviceData and storage path, then prints DisplayName and DeviceId. Expected output: "Samsung S916B (Internal Storage)" and "R58M...". ```csharp var deviceData = new DeviceData { Serial = "R58M...", Model = "SM_S916B" }; var info = new AdbDeviceInfo(deviceData, "/storage/emulated/0"); Console.WriteLine(info.DisplayName); // "Samsung S916B (Internal Storage)" Console.WriteLine(info.DeviceId); // "R58M..." ``` -------------------------------- ### Basic usage of AdbDeviceOperations Source: https://github.com/alos-no/dji-mission-installer Initializes the ADB client, enumerates devices, connects to each, checks for a waypoint file, and disconnects. Dispose with 'using' or 'try/finally' because the class only implements IDisposable; Dispose() stops the ADB server only if this instance started it. ```csharp using var adb = new AdbDeviceOperations(); await adb.InitializeAsync(); foreach (var dev in adb.GetDevices()) { adb.Connect(dev); if (adb.FileExists(@"Android\data\dji.go.v5\files\waypoint\abc123.html")) Console.WriteLine("Waypoint present"); adb.Disconnect(); } ``` -------------------------------- ### IDeviceOperations interface Source: https://github.com/alos-no/dji-mission-installer Defines operations for device communication, including initialization, device enumeration, connection management, file operations, and directory queries. Implemented by AdbDeviceOperations, MtpDeviceOperations, and SwitchableDeviceOperations. Consumed by IMissionTransferService.TransferAsync and MainViewModel. ```csharp public interface IDeviceOperations { Task InitializeAsync(); IEnumerable GetDevices(); void Connect(IDeviceInfo deviceInfo); void Disconnect(); bool IsConnected { get; } IDeviceInfo? CurrentDeviceInfo { get; } string NormalizePath(string path); bool FileExists(string path); void DeleteFile(string path); void UploadFile(Stream sourceStream, string destinationPath); void DownloadFile(string sourcePath, string destinationPath); bool DirectoryExists(string path); IEnumerable GetDirectories(string path, string searchPattern, SearchOption searchOption); DeviceFileInfo? GetFileInfo(string path); } ``` -------------------------------- ### WaypointFileInfo class definition Source: https://github.com/alos-no/dji-mission-installer Immutable descriptor of a destination waypoint slot on the device. Id is typically a GUID (see MainViewModel.GetDeviceWaypoints, which only admits directory names parseable as GUIDs). Returned by MainViewModel.GetDeviceWaypoints and consumed by IMissionTransferService.TransferAsync, WaypointFileInfoEx, and FileListItem. ```csharp public class WaypointFileInfo( string id, string deviceKmzPath, string deviceImagePath, ulong fileSize, DateTime lastModified) { public string Id { get; } = id; public string DeviceKmzPath { get; } = deviceKmzPath; public string DeviceImagePath { get; } = deviceImagePath; public ulong FileSize { get; } = fileSize; public DateTime LastModified { get; } = lastModified; } ``` -------------------------------- ### FolderPickerService error handling example Source: https://github.com/alos-no/dji-mission-installer Treats a null or whitespace result as user cancellation and returns early. The interop throws only if underlying COM calls throw (rare); MainViewModel.BrowseKmzFolder wraps the call in try/catch and reports via IDialogService.ShowErrorAsync. ```csharp string? chosen = picker.PickFolder(initialPath: cfg.KmzSourceFolder); if (string.IsNullOrWhiteSpace(chosen)) return; // user cancelled — no error to report ``` -------------------------------- ### App.config starter appSettings Source: https://github.com/alos-no/dji-mission-installer Starter configuration file for the application. Note: the shipped key is lowercase 'kmzSourceFolder', while ConfigurationService reads/writes camel-case 'KmzSourceFolder'; they do not match, so the seeded starter key is not consulted by the service. ```xml ``` -------------------------------- ### Basic usage of MainWindow Source: https://github.com/alos-no/dji-mission-installer Instantiates MainWindow with viewModel, deviceOps, and configService, then shows it as a modal dialog. ```csharp var window = new MainWindow(viewModel, deviceOps, configService); window.ShowDialog(); ``` -------------------------------- ### App constructor Source: https://github.com/alos-no/dji-mission-installer Constructor for the App class. Initializes ConfigurationService and subscribes to DispatcherUnhandledException. ```csharp public App() { _configurationService = new ConfigurationService(); DispatcherUnhandledException += App_DispatcherUnhandledException; } ``` -------------------------------- ### Basic usage of IDeviceOperations with AdbDeviceOperations Source: https://github.com/alos-no/dji-mission-installer Shows the typical consumer workflow: initialize, enumerate devices, connect, check/delete an existing file, upload a local stream, and disconnect. Uses CurrentDeviceInfo.StoragePath and Const.WaypointFolder to build the destination path. ```csharp IDeviceOperations ops = new AdbDeviceOperations(); await ops.InitializeAsync(); var devices = ops.GetDevices().ToList(); if (devices.Count == 0) return; ops.Connect(devices[0]); var storage = ops.CurrentDeviceInfo!.StoragePath; var kmzPath = Path.Combine(storage, Const.WaypointFolder, slotId, $"{slotId}.kmz"); if (ops.FileExists(kmzPath)) ops.DeleteFile(kmzPath); await using var fs = File.OpenRead(@"C:\Missions\takeoff.kmz"); ops.UploadFile(fs, kmzPath); ops.Disconnect(); ``` -------------------------------- ### Dispose Source: https://github.com/alos-no/dji-mission-installer Stops the ADB server only if this instance started it. Implements IDisposable. ```APIDOC ## Dispose ### Description Stops the ADB server only if this instance started it. Implements IDisposable. ### Method Dispose ### Parameters None ### Response #### Success Response - No return value ### Notes - `AdbDeviceOperations` implements only `IDisposable` (not `IAsyncDisposable`), so dispose with `using` or `try`/`finally`; it cannot be awaited via `await using`. ``` -------------------------------- ### Dispose Source: https://github.com/alos-no/dji-mission-installer Disconnects from the device and, if this instance started the ADB server, kills the server. ```APIDOC ## Dispose ### Description Disconnects from the device and, if this instance started the ADB server, kills the server. ### Method Dispose ### Signature `public void Dispose()` ### Parameters None ### Returns `void` ``` -------------------------------- ### FileSystemService Constructor Source: https://github.com/alos-no/dji-mission-installer Initializes a new instance of the FileSystemService class with the specified KMZ source folder. The folder is watched for .kmz files. ```APIDOC ## FileSystemService Constructor ### Description Initializes a new instance of the FileSystemService class with the specified KMZ source folder. ### Constructor `FileSystemService(string kmzSourceFolder)` ### Parameters - `kmzSourceFolder` (string) - Required - Initial folder to watch/serve. ### Example ```csharp using var fs = new FileSystemService(@"C:\Missions"); ``` ``` -------------------------------- ### Basic usage of FileSystemService Source: https://github.com/alos-no/dji-mission-installer Shows constructing with a folder, subscribing to KmzFilesChanged, watching, listing files, and changing folder. ChangeKmzFolder raises KmzFilesChanged. ```csharp using var fs = new FileSystemService(@"C:\Missions"); fs.KmzFilesChanged += (_, _) => Console.WriteLine("KMZ folder changed"); fs.WatchKmzFolder(); var files = fs.GetKmzFiles(); foreach (var f in files) Console.WriteLine(f.FullName); fs.ChangeKmzFolder(@"D:\OtherMissions"); // raises KmzFilesChanged Console.WriteLine(fs.CurrentFolder); ``` -------------------------------- ### MainWindow constructor declaration Source: https://github.com/alos-no/dji-mission-installer Partial class constructor for MainWindow, taking MainViewModel, IDeviceOperations, and IConfigurationService. Sets DataContext, awaits InitializeAsync on Loaded, and disposes device operations on exit/closing if IDisposable. ```csharp public partial class MainWindow : Window { public MainWindow(MainViewModel viewModel, IDeviceOperations deviceOperations, IConfigurationService configurationService); } ``` -------------------------------- ### ConfigurationService.GoogleMapsApiKey Property Source: https://github.com/alos-no/dji-mission-installer Gets or sets the Google Maps API key. Reads from or writes to the 'GoogleMapsApiKey' setting in the application configuration. ```APIDOC ## ConfigurationService.GoogleMapsApiKey Property ### Description Gets or sets the Google Maps API key. Reads from or writes to the 'GoogleMapsApiKey' setting in the application configuration. ### Type `string` ### Get Behavior Reads `"GoogleMapsApiKey"` via `ConfigurationManager.AppSettings`. ### Set Behavior Writes setting. ### Default Value `string.Empty` ``` -------------------------------- ### Service constructor parameters (with defaults) Source: https://github.com/alos-no/dji-mission-installer Optional constructor parameters for various services, providing composition flexibility with production defaults. ```APIDOC ## Service constructor parameters (with defaults) ### Description Optional constructor parameters for various services, providing composition flexibility with production defaults. ### Constructors #### EsriMapScreenshotService - **httpClient** (HttpClient?) - Optional - New HttpClient (timeout = options). - **logger** (ILogger<...>?) - Optional - NullLogger. - **options** (EsriMapOptions?) - Optional - EsriMapOptions.Default. #### MissionTransferService - **logger** (ILogger?) - Optional - NullLogger. #### SwitchableDeviceOperations - **initialType** (DeviceConnectionType) - Required - Initial device connection type. - **factory** (Func) - Optional - Defaults to DeviceOperationsFactory.Create. #### FileSystemService - **kmzSourceFolder** (string) - Required - The KMZ source folder (no default — supplied by DI from config). #### MainViewModel - 4-param (backward-compatible) vs 11-param (full DI) - The 4-param ctor supplies defaults: new EsriMapScreenshotService(), new ImageService(), new KmzReader(), new MissionTransferService(), new ConfigurationService(), new FolderPickerService(), new SwitchableDeviceOperations(DeviceConnectionType.Adb). ``` -------------------------------- ### WatchKmzFolder() Source: https://github.com/alos-no/dji-mission-installer Creates the folder if missing and sets up a FileSystemWatcher to monitor .kmz files recursively. Subscribes to file events and raises KmzFilesChanged when changes occur. ```APIDOC ## WatchKmzFolder() ### Description Creates the folder if missing and sets up a FileSystemWatcher to monitor .kmz files recursively. Subscribes to file events and raises KmzFilesChanged when changes occur. ### Method `void WatchKmzFolder()` ### Parameters None ### Behavior - Creates the folder if missing. - Creates a FileSystemWatcher with filter `*.kmz`, recursive, 64 KB buffer, and notify filters `FileName|LastWrite|CreationTime|DirectoryName`. - Subscribes to `Created/Deleted/Changed → OnKmzFileEvent` and `Renamed → OnKmzFileRenamed`. - On failure, sets `_watcher = null` (silent) so manual refresh still works. ### Example ```csharp fs.WatchKmzFolder(); ``` ``` -------------------------------- ### EsriMapOptions (constructor options object) Source: https://github.com/alos-no/dji-mission-installer Configuration options for the EsriMapScreenshotService constructor. Provides defaults via EsriMapOptions.Default. ```APIDOC ## EsriMapOptions (constructor options object) ### Description Configuration options for the EsriMapScreenshotService constructor. Provides defaults via EsriMapOptions.Default. ### Options - **BaseUrl** (string) - Optional - ESRI export endpoint. Empty/whitespace falls back to DefaultBaseUrl. - **HttpTimeout** (TimeSpan) - Optional - HTTP client timeout (also applied to the self-created HttpClient). - **MaxRetries** (int) - Optional - Total attempts for transient HTTP failures (retries = attempts - 1). ### Example ```csharp var options = new EsriMapOptions { BaseUrl = "https://services.arcgisonline.com/.../export", HttpTimeout = TimeSpan.FromSeconds(10), MaxRetries = 4 }; var svc = new EsriMapScreenshotService(options: options); ``` ``` -------------------------------- ### FileListViewModel usage example Source: https://github.com/alos-no/dji-mission-installer Creates a FileListViewModel with a title and sorting service, updates items, changes sort method, and subscribes to SelectedItemChanged. ```csharp var list = new FileListViewModel("Device Waypoints", new FileSortingService()); list.UpdateItems(someItems); list.SortMethod = "Name"; list.SelectedItemChanged += (_, _) => Console.WriteLine(list.SelectedItem?.DisplayName); ``` -------------------------------- ### Basic usage of TryGetCenter Source: https://github.com/alos-no/dji-mission-installer Shows how to call TryGetCenter and handle the result. On success, prints the mission center with 6 decimal places; on failure, prints a fallback message. ```csharp var reader = new KmzReader(); if (reader.TryGetCenter(kmzPath, out double lat, out double lon)) { Console.WriteLine($"Mission center: {lat:N6}, {lon:N6}"); } else { // No parseable coordinates; caller should fall back to a default preview. Console.WriteLine("Could not determine mission center."); } ``` -------------------------------- ### MissionTransferOutcome Source: https://github.com/alos-no/dji-mission-installer Immutable result returned by IMissionTransferService.TransferAsync. Contains the local preview path and success flag for a mission transfer operation. ```APIDOC ## MissionTransferOutcome ### Description Immutable result returned by `IMissionTransferService.TransferAsync`. Contains the local preview path and success flag for a mission transfer operation. ### Properties - **LocalPreviewPath** (string) - Local path under `Const.TempPath` of the final generated preview `.jpg`. - **Success** (bool) - Whether the transfer completed successfully. ### Usage ```csharp MissionTransferOutcome outcome = await transferService.TransferAsync( deviceOps, mapService, imageService, kmzReader, sourceKmz, targetSlot, Const.DefaultZoomLevel, Const.DefaultPreviewWidth, Const.DefaultPreviewHeight); if (outcome.Success) Console.WriteLine($"Preview saved to {outcome.LocalPreviewPath}"); ``` ``` -------------------------------- ### ConfigurationService Constructor Source: https://github.com/alos-no/dji-mission-installer Initializes a new instance of the ConfigurationService class. Opens the executable's configuration file, adds any missing default settings, and saves the configuration. ```APIDOC ## ConfigurationService() ### Description Initializes a new instance of the ConfigurationService class. Opens the executable's configuration file, adds any missing default settings, and saves the configuration. ### Method Constructor ### Signature ```csharp public ConfigurationService() ``` ### Behavior - Opens `ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)`; if the file is corrupt (`ConfigurationErrorsException`), deletes and recreates it. - Adds any missing `` keys from `_defaults`. - Saves with `ConfigurationSaveMode.Modified` and calls `RefreshSection("appSettings")`. ``` -------------------------------- ### Switching across providers with using blocks Source: https://github.com/alos-no/dji-mission-installer Demonstrates creating and using MtpDeviceOperations and AdbDeviceOperations instances within using blocks to ensure disposal. Each provider is created fresh and used to enumerate devices. ```csharp // Create-and-connect per transport: using (var mtp = (MtpDeviceOperations)DeviceOperationsFactory.Create(DeviceConnectionType.Mtp)) { foreach (var dev in mtp.GetDevices()) Console.WriteLine(dev.DisplayName); } using (var adb = (AdbDeviceOperations)DeviceOperationsFactory.Create(DeviceConnectionType.Adb)) { await adb.InitializeAsync(); foreach (var dev in adb.GetDevices()) Console.WriteLine(dev.DisplayName); } ``` -------------------------------- ### MissionTransferOutcome model class Source: https://github.com/alos-no/dji-mission-installer Sealed class representing the result of a mission transfer, with a local preview path and success flag. Returned by IMissionTransferService.TransferAsync. File: src/Models/MissionTransferOutcome.cs. ```csharp public sealed class MissionTransferOutcome(string localPreviewPath, bool success) { public string LocalPreviewPath { get; } public bool Success { get; } } ``` -------------------------------- ### FileSystemUtils.WatchFolder Source: https://github.com/alos-no/dji-mission-installer Configures a FileSystemWatcher and returns it ready-to-go with EnableRaisingEvents set to true. The caller owns and disposes the watcher when done. ```APIDOC ## FileSystemUtils.WatchFolder ### Description Configures a `FileSystemWatcher` and returns it ready-to-go with `EnableRaisingEvents = true` already set. The caller owns and disposes the watcher when done. ### Method WatchFolder (static method) ### Signature ```csharp public static FileSystemWatcher WatchFolder(string folderPath, string filter, FileSystemEventHandler onChanged, RenamedEventHandler onRenamed, NotifyFilters notifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName) ``` ### Parameters - **folderPath** (string) - Required - Directory to watch. - **filter** (string) - Required - File filter, e.g. `"*.kmz"`. - **onChanged** (FileSystemEventHandler) - Required - Handler for `Changed`/`Created`/`Deleted`. - **onRenamed** (RenamedEventHandler) - Required - Handler for `Renamed`. - **notifyFilter** (NotifyFilters) - Optional - Watcher notify filters. Default: `LastAccess | LastWrite | FileName | DirectoryName`. ### Returns A `FileSystemWatcher` with `EnableRaisingEvents = true` already set. ### Request Example ```csharp FileSystemWatcher w = FileSystemUtils.WatchFolder(path, "*.kmz", onChanged: (_, e) => Console.WriteLine($"Change: {e.FullPath}"), onRenamed: (_, e) => Console.WriteLine($"Renamed: {e.OldName} -> {e.FullPath}")); // caller owns and disposes the watcher when done ``` ``` -------------------------------- ### DeviceFileInfo class definition Source: https://github.com/alos-no/dji-mission-installer Settable descriptor of a file stored on a connected device. Returned by IDeviceOperations.GetFileInfo (both ADB and MTP implementations) and consumed by MainViewModel.GetDeviceWaypoints. ```csharp public class DeviceFileInfo(string fullPath, DateTime? lastModified, ulong size) { public string FullPath { get; set; } = fullPath; public ulong Size { get; set; } = size; public DateTime? LastModified { get; set; } = lastModified; } ``` -------------------------------- ### ConfigurationService constructor Source: https://github.com/alos-no/dji-mission-installer Opens the executable's .config file, recreates it if corrupt, adds missing appSettings keys from defaults, and saves with ConfigurationSaveMode.Modified. The constant AppRegistryKey is declared but unused. ```csharp public ConfigurationService() ``` -------------------------------- ### Basic usage of SwitchableDeviceOperations Source: https://github.com/alos-no/dji-mission-installer Shows constructing with ADB, switching to MTP with initialization, and then using GetDevices() to iterate devices. After switching, all IDeviceOperations calls target the MtpDeviceOperations instance. ```csharp var switcher = new SwitchableDeviceOperations(DeviceConnectionType.Adb); await switcher.SwitchToAsync(DeviceConnectionType.Mtp, initialize: true); Console.WriteLine(switcher.CurrentType); // Mtp // All IDeviceOperations calls now hit the MtpDeviceOperations instance foreach (var dev in switcher.GetDevices()) Console.WriteLine(dev.DisplayName); ``` -------------------------------- ### Basic usage of MainViewModel Source: https://github.com/alos-no/dji-mission-installer Constructs MainViewModel with a backward-compatible constructor, initializes it (preferred provider or automatic MTP fallback), selects the first available device, and executes the refresh command. ```csharp var vm = new MainViewModel( deviceOps, fileSystem, dialogs, sorter, // backward-compatible ctor used here mapService, imageService, kmzReader, transfer, config, folderPicker, switcher); await vm.InitializeAsync(); // preferred provider or automatic MTP fallback vm.SelectedDevice = vm.AvailableDevices.FirstOrDefault(); vm.RefreshDevicesCommand.Execute(null); ``` -------------------------------- ### WaypointFileInfo model class Source: https://github.com/alos-no/dji-mission-installer Holds waypoint file metadata including device paths for KMZ and image, file size, and last modified time. File: src/Models/WaypointFileInfo.cs. ```csharp public class WaypointFileInfo(string id, string deviceKmzPath, string deviceImagePath, ulong fileSize, DateTime lastModified) { public string Id { get; } public string DeviceKmzPath { get; } public string DeviceImagePath { get; } public ulong FileSize { get; } public DateTime LastModified { get; } } ``` -------------------------------- ### FileListItem class implementing INotifyPropertyChanged Source: https://github.com/alos-no/dji-mission-installer Wraps either a KmzFile (local, Type == LocalKmz) or a WaypointFileInfo (device, Type == DeviceWaypoint) and projects a uniform shape for the UI. The device constructor triggers LoadImage() which reads GetLocalImageUri() temp preview via ImageUtils.LoadImageWithCopyOption. ```csharp public class FileListItem : INotifyPropertyChanged { public FileListItem(KmzFile kmzFile); public FileListItem(WaypointFileInfo waypointFile); public object FileInfo { get; } // KmzFile or WaypointFileInfo public FileItemType Type { get; } public string DisplayName { get; } public string FilePath { get; } public string DirectoryName { get; } public DateTime LastModified { get; } public ulong FileSize { get; } public Uri? ImageUri { get; } public BitmapImage? ImageSource { get; } public bool IsSelected { get; set; } public bool IsHighlighted { get; set; } public event PropertyChangedEventHandler? PropertyChanged; } ``` -------------------------------- ### DeviceConnectionType enum Source: https://github.com/alos-no/dji-mission-installer Defines connection types for devices: Mtp (Media Transfer Protocol) and Adb (Android Debug Bridge). Used by DeviceOperationsFactory.Create, IDeviceOperationsSwitcher.SwitchToAsync, SwitchableDeviceOperations, MainViewModel.SelectedConnection, and ConfigurationService.UseAdbByDefault. ```csharp public enum DeviceConnectionType { Mtp, // Media Transfer Protocol Adb // Android Debug Bridge } ``` -------------------------------- ### Error handling: GetKmzFiles returns empty list Source: https://github.com/alos-no/dji-mission-installer GetKmzFiles returns an empty list when folder is missing or unavailable. Methods are non-throwing by design. ```csharp var files = fs.GetKmzFiles(); if (files.Count == 0) Console.WriteLine("No KMZ files (folder missing or empty)."); ``` -------------------------------- ### InitializeAsync Source: https://github.com/alos-no/dji-mission-installer Initializes the MTP device operations. Returns a completed task as there is nothing to initialize. ```APIDOC ## InitializeAsync ### Description Initializes the MTP device operations. Returns a completed task as there is nothing to initialize. ### Method InitializeAsync ### Signature `public Task InitializeAsync()` ### Returns - `Task` - A completed task. ``` -------------------------------- ### MissionTransferOutcome class definition Source: https://github.com/alos-no/dji-mission-installer Immutable result returned by IMissionTransferService.TransferAsync. Contains LocalPreviewPath (path under Const.TempPath of the generated preview .jpg) and Success (always true in the shipped implementation, present for forward-compatible semantics). ```csharp /// Result of a mission transfer operation. public sealed class MissionTransferOutcome(string localPreviewPath, bool success) { public string LocalPreviewPath { get; } = localPreviewPath; public bool Success { get; } = success; } ``` -------------------------------- ### FileSortingService usage example Source: https://github.com/alos-no/dji-mission-installer Demonstrates sorting a collection of FileListItem by name (ascending) and by size (descending). The natural comparer treats embedded numbers numerically, so "file2" sorts before "file10". ```csharp var sorter = new FileSortingService(); IEnumerable sorted = sorter.SortFiles(items, "Name", ascending: true); IEnumerable desc = sorter.SortFiles(items, "Size", ascending: false); ``` -------------------------------- ### GetKmzFiles() Source: https://github.com/alos-no/dji-mission-installer Recursively returns a list of .kmz files from the watched folder. Returns an empty list if the folder is missing or transiently unavailable. ```APIDOC ## GetKmzFiles() ### Description Recursively returns a list of .kmz files from the watched folder. Returns an empty list if the folder is missing or transiently unavailable. ### Method `List GetKmzFiles()` ### Parameters None ### Returns - `List` - List of .kmz files found recursively. ### Example ```csharp var files = fs.GetKmzFiles(); foreach (var f in files) Console.WriteLine(f.FullName); ``` ``` -------------------------------- ### FileSystemService class declaration Source: https://github.com/alos-no/dji-mission-installer Primary constructor takes kmzSourceFolder. Implements IFileSystemService and IDisposable. Provides members for watching and listing KMZ files. ```csharp public class FileSystemService(string kmzSourceFolder) : IFileSystemService, IDisposable { public void Dispose(); public string CurrentFolder { get; } public void WatchKmzFolder(); public List GetKmzFiles(); public void ChangeKmzFolder(string newFolder); public event EventHandler? KmzFilesChanged; } ``` -------------------------------- ### KmzFile class definition Source: https://github.com/alos-no/dji-mission-installer Read-only wrapper around a local .kmz file, projecting properties from a FileInfo. Constructed with a FileInfo; never throws if the file is missing, but FullPath/FileSize may reflect stale metadata. ```csharp public class KmzFile(FileInfo fileInfo) { public string Name => fileInfo.Name; public string DirectoryName => fileInfo.DirectoryName ?? string.Empty; public DateTime LastWriteTime => fileInfo.LastWriteTime; public string FullPath => fileInfo.FullName; public ulong FileSize => (ulong)fileInfo.Length; } ``` -------------------------------- ### ConfigurationService class declaration Source: https://github.com/alos-no/dji-mission-installer Public class implementing IConfigurationService with properties for KMZ source folder, Google Maps API key, and ADB default usage. Constructor registers defaults so all appSettings keys always exist. ```csharp public class ConfigurationService : IConfigurationService { public ConfigurationService(); public string KmzSourceFolder { get; set; } public string GoogleMapsApiKey { get; set; } public bool UseAdbByDefault { get; set; } public void Save(); public void Reset(); } ``` -------------------------------- ### Non-throwing usage of TryGetCenter Source: https://github.com/alos-no/dji-mission-installer Demonstrates that TryGetCenter never throws, even for missing files or empty paths. It returns false for invalid inputs, so it can be used without try/catch in a pipeline. ```csharp var reader = new KmzReader(); string path = kmzFile.FullPath; reader.TryGetCenter(path, out var lat, out var lon); // safe even if path is missing reader.TryGetCenter("", out _, out _); // false reader.TryGetCenter(@"C:\does_not_exist.kmz", out _, out _); // false ``` -------------------------------- ### Basic usage of EsriMapScreenshotService Source: https://github.com/alos-no/dji-mission-installer Shows the simplest way to use EsriMapScreenshotService: create a default instance and call SaveMapScreenshotAsync with latitude, longitude, zoom level, output path, and optional width/height. The method returns the output path after writing the JPEG bytes. ```csharp var svc = new EsriMapScreenshotService(); string path = await svc.SaveMapScreenshotAsync( latitude: 59.9, longitude: 10.75, zoomLevel: 15, outputPath: @"C:\Temp\map.jpg", width: 1280, height: 720); ``` -------------------------------- ### AdbDeviceOperations class declaration and members Source: https://github.com/alos-no/dji-mission-installer Public class implementing IDeviceOperations and IDisposable. Uses AdvancedSharpAdbClient for ADB operations. Requires InitializeAsync() and Connect() before use; otherwise the private Client property throws InvalidOperationException. Dispose() kills the ADB server only if this instance started it. ```csharp public class AdbDeviceOperations : IDeviceOperations, IDisposable { public async Task InitializeAsync(); public DeviceFileInfo? GetFileInfo(string path); public IEnumerable GetDevices(); public void Connect(IDeviceInfo deviceInfo); public void UploadFile(Stream sourceStream, string destinationPath); public void DownloadFile(string sourcePath, string destinationPath); public bool FileExists(string path); public void DeleteFile(string path); public bool DirectoryExists(string path); public IEnumerable GetDirectories(string path, string searchPattern, SearchOption searchOption); public void Disconnect(); public string NormalizePath(string path); public bool IsConnected { get; } public IDeviceInfo? CurrentDeviceInfo { get; } public void Dispose(); } ``` -------------------------------- ### IDeviceOperations.DownloadFile(string, string) Source: https://github.com/alos-no/dji-mission-installer Copies a device file to a local path. ```APIDOC ## DownloadFile(string, string) ### Description Copies a device file to a local path. ### Method DownloadFile ### Return Type void ### Parameters - **sourcePath** (string) - Required - Device source path. - **destinationPath** (string) - Required - Local destination path. ``` -------------------------------- ### Basic usage of ImageService Source: https://github.com/alos-no/dji-mission-installer Shows how to instantiate ImageService and call both methods. ProcessImageAsync overlays metadata onto a map tile; CreateDefaultImageAsync generates a placeholder directly. Both are async and should be awaited. ```csharp using var img = new ImageService(); // Overlay metadata onto a map tile await img.ProcessImageAsync( inputPath: tempMapPath, outputPath: finalPath, id: kmzName, lastModified: slot.LastModified); // Or generate a default placeholder directly string outPath = await img.CreateDefaultImageAsync( outputPath: @"C:\Temp\preview.jpg", id: "takeoff", lastModified: DateTime.Now, width: 640, height: 480); ``` -------------------------------- ### DownloadFile Source: https://github.com/alos-no/dji-mission-installer Downloads a file from the device to a local destination. Verifies the source exists and creates the local parent directory. ```APIDOC ## DownloadFile ### Description Downloads a file from the device to a local destination. Verifies the source exists and creates the local parent directory. ### Method DownloadFile ### Signature `public void DownloadFile(string sourcePath, string destinationPath)` ### Parameters - `sourcePath` (string) - Required - The device source path. - `destinationPath` (string) - Required - The local destination path; parent directory is created. ### Exceptions - `FileNotFoundException` - Thrown when the source file does not exist. ``` -------------------------------- ### EsriMapScreenshotService Constructor Source: https://github.com/alos-no/dji-mission-installer Initializes a new instance of the EsriMapScreenshotService class with optional HTTP client, logger, and options. The service fetches map tiles from ESRI's ArcGIS World Imagery export endpoint. ```APIDOC ## EsriMapScreenshotService Constructor ### Description Initializes a new instance of the EsriMapScreenshotService class with optional HTTP client, logger, and options. The service fetches map tiles from ESRI's ArcGIS World Imagery export endpoint. ### Method Constructor ### Parameters - `httpClient` (HttpClient?) - Optional - Injected client; otherwise a new `HttpClient` with `Timeout = options.HttpTimeout` is created and its `Accept` header set to `image/jpeg`. - `logger` (ILogger?) - Optional - Used for request/success/failure logging. - `options` (EsriMapOptions?) - Optional - Timeout, retries, base URL (see below). ``` -------------------------------- ### CreateDefaultImageAsync method signature Source: https://github.com/alos-no/dji-mission-installer Creates a white placeholder image with overlay text and saves as JPEG. Default width 800, height 480. Returns outputPath. May throw on I/O errors. ```csharp Task CreateDefaultImageAsync( string outputPath, string id, DateTime lastModified, int width = 800, int height = 480) ``` -------------------------------- ### IFileSystemService interface Source: https://github.com/alos-no/dji-mission-installer Watches a local KMZ folder and lists .kmz files. Implementation: FileSystemService. ```csharp public interface IFileSystemService { event EventHandler KmzFilesChanged; void WatchKmzFolder(); List GetKmzFiles(); void ChangeKmzFolder(string newFolder); string CurrentFolder { get; } } ``` -------------------------------- ### EsriMapOptions constructor options object Source: https://github.com/alos-no/dji-mission-installer Configures the EsriMapScreenshotService with a custom base URL, HTTP timeout, and retry count. Empty or whitespace BaseUrl falls back to DefaultBaseUrl; MaxRetries is total attempts (retries = attempts - 1). ```csharp var options = new EsriMapOptions { BaseUrl = "https://services.arcgisonline.com/.../export", HttpTimeout = TimeSpan.FromSeconds(10), MaxRetries = 4 }; var svc = new EsriMapScreenshotService(options: options); ``` -------------------------------- ### Usage pattern: resolving and using IKmzReader Source: https://github.com/alos-no/dji-mission-installer Shows how consumer code should depend on interfaces resolved through AppHost.Services. IKmzReader.TryGetCenter returns false (never throws) on unreadable/unparseable KMZ. ```csharp var kmzReader = host.Services.GetRequiredService(); if (kmzReader.TryGetCenter(kmzPath, out var lat, out var lon)) Console.WriteLine($"{lat},{lon}"); ```