static async Task Main() { IList <ConfigItem> configItems; bool trackSpecificVehicles = false; IList <Device> devicesToTrack = null; Common.FeedStartOption feedStartOption = Common.FeedStartOption.CurrentTime; DateTime feedStartSpecificTimeUTC = DateTime.MinValue; int feedIntervalSeconds = 60; IList <Diagnostic> diagnosticsToTrack = null; string parentOutputFolder; string outputFolder; int maximumFileSizeBytes = 1024000; GeotabDataOnlyPlanAPI api; string username = ""; string password = ""; string server = "my.geotab.com"; string database = ""; string title = ""; try { // Set title. title = AppDomain.CurrentDomain.FriendlyName.Replace(".", " "); Console.Title = title; ConsoleUtility.LogUtilityStartup(title); // Request MyGeotab credentials and database name. server = ConsoleUtility.GetUserInput($"MyGeotab server"); database = ConsoleUtility.GetUserInput($"Database to run examples against.").ToLower(); username = ConsoleUtility.GetUserInput($"MyGeotab username"); password = ConsoleUtility.GetUserInputMasked($"MyGeotab password"); // Create Geotab Data-Only Plan API instance and authenticate. api = new GeotabDataOnlyPlanAPI(server, database, username, password); ConsoleUtility.LogInfoStart("Authenticating..."); await api.AuthenticateAsync(); ConsoleUtility.LogOk(); // Load configuration information from the config file. configItems = GetConfigItems("configuration"); // Validate output folder and create subfolder for output files. parentOutputFolder = configItems.Where(configItem => configItem.Key == ArgNameOutputFolder).FirstOrDefault().Value; if (!Directory.Exists(parentOutputFolder)) { throw new ArgumentException($"The specified output folder, '{parentOutputFolder}', does not exist."); } DirectoryInfo directoryInfo = new DirectoryInfo(parentOutputFolder); string subfolderName = $"Output_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}"; directoryInfo.CreateSubdirectory(subfolderName); outputFolder = Path.Combine(directoryInfo.FullName, subfolderName); // Validate and set maximum file size. string maxFileSizeMBString = configItems.Where(configItem => configItem.Key == ArgNameMaximumFileSizeMB).FirstOrDefault().Value; if (int.TryParse(maxFileSizeMBString, out int maxFileSizeMB)) { if (maxFileSizeMB > 0) { maximumFileSizeBytes = maxFileSizeMB * Common.MegabyteToByteMultiplier; } } // Get the vehicle tracking option. string vehicleTrackingOption = configItems.Where(configItem => configItem.Key == ArgNameVehicleTrackingOption).FirstOrDefault().Value; switch (vehicleTrackingOption) { case nameof(Common.VehicleTrackingOption.Reporting): trackSpecificVehicles = false; break; case nameof(Common.VehicleTrackingOption.Specific): trackSpecificVehicles = true; break; default: break; } // If specific vehicles are to be tracked, validate the supplied list of device IDs against the current database. Discard any supplied items that are not valid device IDs. If no valid device IDs are supplied, switch back to tracking vehicles that are currently reporting data. if (trackSpecificVehicles == true) { ConsoleUtility.LogInfo("Validating SpecificVehiclesToTrack..."); string vehicleListSupplied = configItems.Where(configItem => configItem.Key == ArgNameSpecificVehiclesToTrack).FirstOrDefault().Value; string[] vehicleList = vehicleListSupplied.Split(","); devicesToTrack = new List <Device>(); IList <Device> devices = await GetAllDevicesAsync(api); for (int vehicleListIndex = 0; vehicleListIndex < vehicleList.Length; vehicleListIndex++) { string vehicleDeviceId = vehicleList[vehicleListIndex]; Device checkedDevice = devices.Where(device => device.Id.ToString() == vehicleDeviceId).FirstOrDefault(); if (checkedDevice == null) { ConsoleUtility.LogListItem($"Note - The following is not a valid device Id", $"{vehicleDeviceId}", Common.ConsoleColorForUnchangedData, Common.ConsoleColorForErrors); continue; } devicesToTrack.Add(checkedDevice); } if (devicesToTrack.Count == 0) { ConsoleUtility.LogWarning($"No valid device IDs have been entered. Switching to tracking of vehicles that are currently reporting data."); trackSpecificVehicles = false; } } // Get diagnostics to be tracked. ConsoleUtility.LogInfo("Validating DiagnosticsToTrack..."); string diagnosticListSupplied = configItems.Where(configItem => configItem.Key == ArgNameDiagnosticsToTrack).FirstOrDefault().Value; string[] diagnosticList = diagnosticListSupplied.Split(","); diagnosticsToTrack = new List <Diagnostic>(); IList <Diagnostic> diagnostics = await GetAllDiagnosticsAsync(api); for (int diagnosticListIndex = 0; diagnosticListIndex < diagnosticList.Length; diagnosticListIndex++) { string diagnosticId = diagnosticList[diagnosticListIndex]; Diagnostic checkedDiagnostic = diagnostics.Where(diagnostic => diagnostic.Id.ToString() == diagnosticId).FirstOrDefault(); if (checkedDiagnostic == null) { ConsoleUtility.LogListItem($"Note - The following is not a valid diagnostic Id", $"{diagnosticId}", Common.ConsoleColorForUnchangedData, Common.ConsoleColorForErrors); continue; } diagnosticsToTrack.Add(checkedDiagnostic); } if (diagnosticsToTrack.Count == 0) { ConsoleUtility.LogWarning($"No valid diagnostic IDs have been entered. As such, no diagnostics will be tracked."); } // Get the feed start option. string feedStartOptionString = configItems.Where(configItem => configItem.Key == ArgNameFeedStartOption).FirstOrDefault().Value; switch (feedStartOptionString) { case nameof(Common.FeedStartOption.CurrentTime): feedStartOption = Common.FeedStartOption.CurrentTime; break; case nameof(Common.FeedStartOption.FeedResultToken): feedStartOption = Common.FeedStartOption.FeedResultToken; break; case nameof(Common.FeedStartOption.SpecificTime): string feedStartSpecificTimeUTCString = configItems.Where(configItem => configItem.Key == ArgNameFeedStartSpecificTimeUTC).FirstOrDefault().Value; if (DateTime.TryParse(feedStartSpecificTimeUTCString, null, System.Globalization.DateTimeStyles.RoundtripKind, out feedStartSpecificTimeUTC) == false) { ConsoleUtility.LogWarning($"The value of '{feedStartSpecificTimeUTCString}' specified for FeedStartSpecificTimeUTC is invalid. As such, the current date and time will be used instead."); feedStartOption = Common.FeedStartOption.CurrentTime; } else { feedStartOption = Common.FeedStartOption.SpecificTime; } break; default: break; } // Get the feed interval. string feedIntervalSecondsString = configItems.Where(configItem => configItem.Key == ArgNameFeedIntervalSeconds).FirstOrDefault().Value; if (int.TryParse(feedIntervalSecondsString, out int feedIntervalSecondsInt)) { if (feedIntervalSecondsInt < ShortestAllowedFeedIntervalSeconds) { ConsoleUtility.LogListItem($"Note - The specified FeedIntervalSeconds value of '{feedIntervalSecondsString}' is less then the shortest allowed value of '{ShortestAllowedFeedIntervalSeconds.ToString()}'. FeedIntervalSeconds will be set to:", ShortestAllowedFeedIntervalSeconds.ToString(), Common.ConsoleColorForUnchangedData, Common.ConsoleColorForErrors); feedIntervalSeconds = ShortestAllowedFeedIntervalSeconds; } else { feedIntervalSeconds = feedIntervalSecondsInt; } } else { ConsoleUtility.LogListItem($"Note - The specified FeedIntervalSeconds value of '{feedIntervalSecondsString}' is invalid. FeedIntervalSeconds will be set to:", ShortestAllowedFeedIntervalSeconds.ToString(), Common.ConsoleColorForUnchangedData, Common.ConsoleColorForErrors); feedIntervalSeconds = ShortestAllowedFeedIntervalSeconds; } // Instantiate a DatabaseWorker to start processing the data feeds. bool continuous = true; Worker worker = new DatabaseWorker(username, password, database, server, parentOutputFolder, outputFolder, maximumFileSizeBytes, feedIntervalSeconds, feedStartOption, feedStartSpecificTimeUTC, trackSpecificVehicles, devicesToTrack, diagnosticsToTrack); var cancellationToken = new CancellationTokenSource(); Task task = Task.Run(async() => await worker.DoWorkAsync(continuous), cancellationToken.Token); if (continuous && Console.ReadLine() != null) { worker.RequestStop(); cancellationToken.Cancel(); } } catch (Exception ex) { ConsoleUtility.LogError(ex); } finally { ConsoleUtility.LogUtilityShutdown(title); Console.ReadKey(); } }
/// <summary> /// IMPORTANT: This example should be used sparingly - only when a new database is actually required! /// </summary> /// <param name="api"></param> /// <returns></returns> public static async Task <string> Run(GeotabDataOnlyPlanAPI api) { ConsoleUtility.LogExampleStarted(typeof(CreateDatabaseAsyncExample).Name); string createDatabaseResult = ""; try { // Confirm user wishes to proceed with database creation. ConsoleUtility.LogWarning("By proceeding, you will be requesting the creation of a new MyGeotab database."); string input = ConsoleUtility.GetUserInput("'y' to confirm you wish to create a new database, or 'n' to cancel."); if (input != "y") { ConsoleUtility.LogInfo("Cancelled CreateDatabaseAsync example."); return(createDatabaseResult); } // Re-authenticate against "my.geotab.com". ConsoleUtility.LogInfoStart("Reauthenticating against my.geotab.com..."); await api.AuthenticateAsync("my.geotab.com", "", api.Credentials.UserName, api.Credentials.Password); ConsoleUtility.LogComplete(); string database = ""; // Generate a database name and ensure that it is not already used. bool databaseExists = true; while (databaseExists == true) { database = Guid.NewGuid().ToString().Replace("-", ""); databaseExists = await api.DatabaseExistsAsync(database); } ConsoleUtility.LogInfoStartMultiPart($"Creating database named '{database}'.", $"THIS MAY TAKE SEVERAL MINUTES...", Common.ConsoleColorForWarnings); // Set parameter values for CreateDatabaseAsync call. string username = api.Credentials.UserName; string password = api.Credentials.Password; string companyName = "Customer XYZ Ltd."; string firstName = "John"; string lastName = "Smith"; string phoneNumber = "+1 (555) 123-4567"; string resellerName = "Reseller 123 Inc."; int fleetSize = 1; bool signUpForNews = false; string timeZoneId = "America/Toronto"; string comments = "some comments"; // Create database. createDatabaseResult = await api.CreateDatabaseAsync(database, username, password, companyName, firstName, lastName, phoneNumber, resellerName, fleetSize, signUpForNews, timeZoneId, comments); ConsoleUtility.LogComplete(); // Get the server and database information for the new database. string[] serverAndDatabase = (createDatabaseResult).Split('/'); string server = serverAndDatabase.First(); string createdDatabase = serverAndDatabase.Last(); ConsoleUtility.LogInfo($"Created database '{createdDatabase}' on server '{server}'."); // Authenticate against the new database so that additional api calls (the 'Add', 'Set' and 'Remove' ones in particular) can be executed. ConsoleUtility.LogInfoStart($"Authenticating against '{createdDatabase}' database..."); await api.AuthenticateAsync(server, createdDatabase, api.Credentials.UserName, api.Credentials.Password); ConsoleUtility.LogComplete(); } catch (Exception ex) { ConsoleUtility.LogError(ex); } ConsoleUtility.LogExampleFinished(typeof(CreateDatabaseAsyncExample).Name); return(createDatabaseResult); }