public void MethodSync()
 {
     for (int i = 0; i < 25; i++)
     {
         ConsoleUtility.WriteLine($"Counter {i}");
     }
 }
Exemplo n.º 2
0
        public void Run()
        {
            BinaryTree binaryTree = new BinaryTree();

            binaryTree.Add(1);
            binaryTree.Add(2);
            binaryTree.Add(7);
            binaryTree.Add(3);
            binaryTree.Add(10);
            binaryTree.Add(5);
            binaryTree.Add(8);

            Node node  = binaryTree.Find(5);
            int  depth = binaryTree.GetTreeDepth();

            ConsoleUtility.WriteLine("PreOrder Traversal:");
            binaryTree.TraversePreOrder(binaryTree.Root);

            ConsoleUtility.WriteLine("InOrder Traversal:");
            binaryTree.TraverseInOrder(binaryTree.Root);

            ConsoleUtility.WriteLine("PostOrder Traversal:");
            binaryTree.TraversePostOrder(binaryTree.Root);

            binaryTree.Remove(7);
            binaryTree.Remove(8);

            ConsoleUtility.WriteLine("PreOrder Traversal After Removing Operation:");
            binaryTree.TraversePreOrder(binaryTree.Root);
        }
Exemplo n.º 3
0
        private static void TryInjectValueInteractive(MemberInfo member, NukeBuild build)
        {
            if (!member.HasCustomAttribute <ParameterAttribute>())
            {
                return;
            }

            if (member is PropertyInfo property && !property.CanWrite)
            {
                return;
            }

            var memberType        = member.GetMemberType();
            var nameOrDescription = ParameterService.GetParameterDescription(member) ??
                                    ParameterService.GetParameterMemberName(member);
            var text = $"{nameOrDescription.TrimEnd('.')}:";

            while (member.GetValue(build) == null)
            {
                var valueSet = ParameterService.GetParameterValueSet(member, build);
                var value    = valueSet == null
                    ? ConsoleUtility.PromptForInput(text, defaultValue : null)
                    : ConsoleUtility.PromptForChoice(text, valueSet.Select(x => (x.Object, x.Text)).ToArray());

                member.SetValue(build, ReflectionService.Convert(value, memberType));
            }
        }
        /// <summary>
        /// Updates the <see cref="Device"/> cache.  All new or changed <see cref="Device"/>s are obtained using a GetFeed() call.  Then, <see cref="Device"/>s that are already in the cache are replaced and any <see cref="Device"/>s not in the cache are added to the cache.
        /// </summary>
        /// <returns></returns>
        async Task UpdateDeviceCacheAsync()
        {
            ConsoleUtility.LogInfoStart("Updating Device cache...");

            // Populate the deviceCache, adding new items and updating existing items with their changed counterparts from the database.  Repeat execution of the GetFeedDeviceAsync method until no more results are returned to ensure that the cache is complete and up-to-date.
            FeedResult <Device> feedResult = null;
            bool keepGoing = true;

            while (keepGoing == true)
            {
                feedResult = await api.GetFeedDeviceAsync(lastDeviceFeedVersion);

                lastDeviceFeedVersion = feedResult.ToVersion;
                foreach (Device feedResultDevice in feedResult.Data)
                {
                    if (deviceCache.ContainsKey(feedResultDevice.Id))
                    {
                        deviceCache[feedResultDevice.Id] = feedResultDevice;
                    }
                    else
                    {
                        deviceCache.Add(feedResultDevice.Id, feedResultDevice);
                    }
                }
                if (feedResult.Data.Count < DefaultFeedResultsLimitDevice)
                {
                    keepGoing = false;
                }
            }

            ConsoleUtility.LogComplete(Common.ConsoleColorForUnchangedData);
            ConsoleUtility.LogListItem($"Device cache records added/updated:", feedResult.Data.Count.ToString(), Common.ConsoleColorForListItems, (feedResult.Data.Count > 0) ? Common.ConsoleColorForChangedData : Common.ConsoleColorForUnchangedData);
        }
Exemplo n.º 5
0
 private void ParseTypeComplete(XmlNode _typeDefinition)
 {
     if (mParseType != null)
     {
         mParseType = SplitReferenceAndPointers(mParseType);
         string[] values = mParseType.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
         foreach (string value in values)
         {
             CompoundTypeModifers modiffer = CompoundTypeModifers.None;
             if (mModiferMap.TryGetValue(value, out modiffer))
             {
                 mModifers.Add(modiffer);
             }
             else if (mFundamentTypeMap.ContainsKey(value))
             {
                 mBaseTypeName = value;
             }
             else
             {
                 if (mBaseTypeName == null)
                 {
                     mBaseTypeName = value;
                 }
                 else
                 {
                     ConsoleUtility.WriteErrorLine("Error parse type {0}", _typeDefinition.InnerXml);
                 }
             }
         }
     }
 }
Exemplo n.º 6
0
        public static void DumpValidationResults(IEnumerable <ValidationResult> results)
        {
            ArgumentUtility.CheckNotNull("results", results);

            foreach (ValidationResult result in results)
            {
                if (result.TotalRulesExecuted == 0)
                {
                    //Console.ForegroundColor = ConsoleColor.DarkGray;
                    //Console.WriteLine ("No rules found for {0} '{1}'", result.Definition.GetType ().Name, result.Definition.FullName);
                }
                else if (result.TotalRulesExecuted != result.Successes.Count)
                {
                    using (ConsoleUtility.EnterColorScope(ConsoleColor.Gray, null))
                    {
                        Console.WriteLine(
                            "{0} '{1}', {2} rules executed",
                            result.ValidatedDefinition.GetType().Name,
                            result.ValidatedDefinition.FullName,
                            result.TotalRulesExecuted);
                        DumpContext(result);
                    }
                }
                DumpResultList("unexpected exceptions", result.Exceptions, ConsoleColor.White, ConsoleColor.DarkRed);
                // DumpResultList ("successes", result.Successes, ConsoleColor.Green, null);
                DumpResultList("warnings", result.Warnings, ConsoleColor.Yellow, null);
                DumpResultList("failures", result.Failures, ConsoleColor.Red, null);
            }
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            new ExpressionTrees().AddTwoNumbersExpression(10, 20);

            ConsoleUtility.PrintInfo(string.Empty);

            new SortUsing_IComparable_Example().Run();
            new SortUsing_IComparer_Example().Run();

            new ProductThatCanBeCompared_net2_Example().Run();
            new SortUsing_IComparer_net2_Example().Run();
            new SortUsing_IComparer_net2_delegate_Example().Run();
            new Sorting_in_net3_5().Run();
            new Looping_in_net1().Run();
            new Delegates_in_net2().Run();
            new Linq_method_extensions_in_net3_5().Run();
            new Linq_query_expressions().Run();
            new Linq_to_xml().Run();
            new Linq_sql().Run();

            new Rx_SubjectSimpleExample().Run();
            new Rx_2_ReplaySubject(cacheSize: 1).Run();
            new Rx_2_ReplaySubject(cacheSize: 10).Run();
            new Rx_3_AsyncSubject().Run();
            new Rx_4_Subscribe_with_error_handling().Run();
            new Rx_5_Unsubsribe_using_dispose().Run();
            new Rx_6_Disposables().Run();
            new Rx_7_Observable_Create().Run();
            new Rx_7_Observable_Create().Run_not_preferred();
            Console.ReadKey();
        }
        public static async Task Run(GeotabDataOnlyPlanAPI api, string userId)
        {
            ConsoleUtility.LogExampleStarted(typeof(SetUserAsyncExample).Name);

            try
            {
                // Update a driver with keys to a NON-driver.
                // Set parameter values to apply when adding device.
                string   id          = userId;
                DateTime activeTo    = new(2037, 1, 31);
                string   comment     = "Driver with keys updated to NON-driver";
                string   designation = "Driver 2 Upd";
                string   employeeNo  = "Employee 2 Upd";
                string   firstName   = "John Upd";
                bool     isDriver    = false;
                string   lastName    = "Smith2 Upd";
                string   name        = "jsmith2Upd";
                string   password2   = "Password1!Upd";

                ConsoleUtility.LogInfoStart($"Updating user '{id}' in database '{api.Credentials.Database}'...");

                await api.SetUserAsync(id, activeTo, comment, designation, employeeNo, firstName, isDriver, lastName, name, password2);

                ConsoleUtility.LogComplete();
            }
            catch (Exception ex)
            {
                ConsoleUtility.LogError(ex);
            }

            ConsoleUtility.LogExampleFinished(typeof(SetUserAsyncExample).Name);
        }
Exemplo n.º 9
0
        private void EnableOnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (Enable)
            {
                OnActivate();
                Render.Draw    += OnDraw;
                Game.OnWndProc += OnWndProc;

                if (OnInGameUpdateEventEnable)
                {
                    Game.OnIngameUpdate += OnInGameUpdate;
                }

                ConsoleUtility.InfoWriteLine($"[{MenuTitle}] activated.");
            }
            else
            {
                OnDeActivate();
                Render.Draw    -= OnDraw;
                Game.OnWndProc -= OnWndProc;

                if (OnInGameUpdateEventEnable)
                {
                    Game.OnIngameUpdate -= OnInGameUpdate;
                }

                ConsoleUtility.InfoWriteLine($"[{MenuTitle}] deactivated.");
            }
        }
Exemplo n.º 10
0
        private static async ValueTask <IReadOnlyList <Ability> > CreateAbilities(GameServiceClient client, IReadOnlyList <GamePackage> packages)
        {
            ConsoleUtility.WriteLine("Creating abilities");

            var existingAbilities = await AbilityUtility.GetAbilitiesAsync(client, null);

            if (existingAbilities.Any())
            {
                return(existingAbilities);
            }

            var doc = XDocument.Load(@"C:\Users\Ryan\SkyDrive\code\LegendaryGameStarter\LegendaryGameModel2\Abilities\Abilities.xml");

            var request = new CreateAbilitiesRequest();

            request.Abilities.AddRange(doc.Root.Elements("Ability").Select(ability =>
            {
                var gamePackage = packages.First(x => x.Name.Equals(ability.Element("Source").Value, StringComparison.OrdinalIgnoreCase));
                return(new Ability {
                    Name = ability.Element("Name").Value, Description = ability.Element("Description").Value, GamePackage = gamePackage
                });
            }));

            var result = await client.CreateAbilitiesAsync(request);

            ConsoleUtility.WriteLine($"Status: {result.Status.Code}: {result.Status.Message}");

            return(result.Abilities);
        }
Exemplo n.º 11
0
        private void ParseChildItems(XmlNode _node)
        {
            foreach (XmlNode node in _node.SelectNodes("sectiondef/memberdef"))
            {
                string id = node.Attributes["id"].Value;
                if (CompoundManager.Instance.IsIgnoredCompound(id))
                {
                    continue;
                }

                string kind = node.Attributes["kind"].Value;
                if (CompoundManager.Instance.IsIgnoredType(kind))
                {
                    continue;
                }

                Compound compound = CompoundManager.Instance.GetCompound(id);
                if (compound == null)
                {
                    ConsoleUtility.WriteErrorLine("Item {0} not found (for this {1})", id, RefID);
                }
                else
                {
                    if (compound.Parent != this)
                    {
                        ConsoleUtility.WriteErrorLine("Item {0} not added for {1}", compound.RefID, RefID);
                    }
                    else
                    {
                        compound.Parse(node);
                    }
                }
            }
        }
Exemplo n.º 12
0
 void Mixer_ErrorOccurred(object sender, ErrorEventArgs e)
 {
     using (ConsoleUtility.EnterColorScope(ConsoleColor.Red, null))
     {
         Console.WriteLine(e.Exception.ToString());
     }
 }
Exemplo n.º 13
0
 private void Mixer_ValidationErrorOccurred(object sender, ValidationErrorEventArgs e)
 {
     using (ConsoleUtility.EnterColorScope(ConsoleColor.Red, null))
     {
         Console.WriteLine(e.ValidationException.Message);
     }
 }
Exemplo n.º 14
0
        // --- internals
        internal ConsoleBackend(bool handleLogs, ConsoleGui.Options options)
        {
            // run this only once...
            if (m_textInput != null)
            {
                return;
            }
#if UNITY_EDITOR
            // Application.logMessageReceived += LogHandler;
#endif

            commandPrefix = ConsoleUtility.ToHex(options.colors.command) + "[CMD]: ";
            errorPrefix   = ConsoleUtility.ToHex(options.colors.error) + "[ERR]: ";
            warningPrefix = ConsoleUtility.ToHex(options.colors.warning) + "[WNG]: ";
            logPrefix     = ConsoleUtility.ToHex(options.colors.log) + "[LOG]: ";
            greyColor     = ConsoleUtility.ToHex(options.colors.suggestionGreyed);

            RegisterCommand("echo", "writes <string> to the console log (alias for echo)", this, Echo);
            RegisterCommand("list", "lists all currently registered console variables", this, ListCvars);
            RegisterCommand("print", "writes <string> to the console log", this, Echo);
            RegisterCommand("quit", "quit the game (not sure this works with iOS/Android)", this, Quit);

            // RegisterCommand("help", "displays help information for console command where available", this, Help);
            // RegisterCommand("callstack.warning", "display the call stack for the last warning message", LastWarningCallStack);
            // RegisterCommand("callstack.error", "display the call stack for the last error message", LastErrorCallStack);
            // RegisterCommand("callstack.exception", "display the call stack for the last exception message", LastExceptionCallStack);
            CollectAllData();

            if (handleLogs)
            {
                Application.logMessageReceived += LogHandler;
            }
        }
Exemplo n.º 15
0
        public void Run()
        {
            int  n   = 5;
            long fac = factorial(n);

            ConsoleUtility.WriteLine($"Data to display {fac}");
        }
Exemplo n.º 16
0
        private static void Initialize()
        {
            // Encodings

            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            // Logger

            Log.Logger = new LoggerConfiguration()
                         .WriteTo.Console(
                theme: AnsiConsoleTheme.Code,
                outputTemplate: "[MiniMe {Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
                         .CreateLogger();

            // SwitchBoard

            var config = new ConfigurationBuilder()
                         .SetBasePath(Directory.GetCurrentDirectory())
                         .AddJsonFile("appsettings.json", false)
                         .Build();

            MiniMeService.Add <ISwitchBoardService>(
                new SwitchBoard(
                    config.GetValue <string>("Host"),
                    config.GetOptions <MiniMePorts>("Port")));

            // Hook console terminate request for windows
            ConsoleUtility.HookExit(Terminate);
        }
Exemplo n.º 17
0
        public static async Task <string> Run(GeotabDataOnlyPlanAPI api, string deviceId, string userId)
        {
            ConsoleUtility.LogExampleStarted(typeof(AddDriverChangeAsyncExample).Name);

            string addedDriverChangeId = "";

            try
            {
                // Set parameter values to apply when adding driver change.
                DateTime      dateTime    = DateTime.Now;
                List <Device> deviceCache = await ExampleUtility.GetAllDevicesAsync(api);

                List <User> userCache = await ExampleUtility.GetAllUsersAsync(api);

                Device device = deviceCache.Where(targetDevice => targetDevice.Id.ToString() == deviceId).First();
                Driver driver = userCache.Where(targetUser => targetUser.Id.ToString() == userId).First() as Driver;

                DriverChangeType driverChangeType = DriverChangeType.Driver;

                ConsoleUtility.LogInfoStart($"Adding driverChange of type '{driverChangeType.ToString()}' for driver '{driver.Id.ToString()}' and device '{device.Id.ToString()}' to database '{api.Credentials.Database}'...");

                addedDriverChangeId = await api.AddDriverChangeAsync(dateTime, device, driver, driverChangeType);

                ConsoleUtility.LogComplete();
                ConsoleUtility.LogInfo($"Added driverChange Id: {addedDriverChangeId}");
            }
            catch (Exception ex)
            {
                ConsoleUtility.LogError(ex);
            }

            ConsoleUtility.LogExampleFinished(typeof(AddDriverChangeAsyncExample).Name);
            return(addedDriverChangeId);
        }
Exemplo n.º 18
0
        public static async Task Run(GeotabDataOnlyPlanAPI api)
        {
            ConsoleUtility.LogExampleStarted(typeof(GetControllersAsyncExample).Name);

            IList <Controller> controllers;
            Controller         controller;

            try
            {
                // Example: Get all controllers:
                controllers = await api.GetControllersAsync();

                // Example: Search for a controller based on id:
                string controllerId = KnownId.ControllerObdPowertrainId.ToString();
                controllers = await api.GetControllersAsync(controllerId);

                controller = controllers.FirstOrDefault();

                // Example: Search for controllers based on name:
                string controllerName = "Body (B)";
                controllers = await api.GetControllersAsync("", controllerName);

                // Example: Search for controllers based on sourceId:
                string controllerSourceId = KnownId.SourceObdId.ToString();
                controllers = await api.GetControllersAsync("", "", controllerSourceId);
            }
            catch (Exception ex)
            {
                ConsoleUtility.LogError(ex);
            }

            ConsoleUtility.LogExampleFinished(typeof(GetControllersAsyncExample).Name);
        }
        public static async Task Run(GeotabDataOnlyPlanAPI api)
        {
            ConsoleUtility.LogExampleStarted(typeof(GetBinaryDataAsyncExample).Name);

            IList <BinaryData> binaryData;

            try
            {
                // Get a random device Id for use in the following examples.
                List <Device> deviceCache = await ExampleUtility.GetAllDevicesAsync(api);

                string deviceId = ExampleUtility.GetRandomDeviceId(deviceCache);
                Device deviceForTextMessages = deviceCache.Where(targetDevice => targetDevice.Id.ToString() == deviceId).First();

                // Example: Get all binary data:
                binaryData = await api.GetBinaryDataAsync();

                // Example: Get all CalibrationId binary data for a single device:
                binaryData = await api.GetBinaryDataAsync("CalibrationId", null, null, "", deviceId);

                // Example: Get all CalibrationId binary data for a single device for the past week:
                DateTime fromDate = DateTime.Now - TimeSpan.FromDays(7);
                binaryData = await api.GetBinaryDataAsync("CalibrationId", fromDate, null, "", deviceId);
            }
            catch (Exception ex)
            {
                ConsoleUtility.LogError(ex);
            }

            ConsoleUtility.LogExampleFinished(typeof(GetBinaryDataAsyncExample).Name);
        }
Exemplo n.º 20
0
 public void Execute(string[] args)
 {
     if (args.Length == 1)
     {
         string manual = CommandRegistry.GetManual(args[0]);
         if (manual != null)
         {
             ConsoleUtility.WriteLine(manual, Program.TextColor);
         }
         else
         {
             ConsoleUtility.WriteLine("Manual for this command was not found.", Program.ErrorColor);
         }
     }
     else if (args.Length == 2)
     {
         string manual = CommandRegistry.GetManual(args[1]);
         if (manual != null)
         {
             ConsoleUtility.WriteLine(manual, Program.TextColor);
         }
         else
         {
             ConsoleUtility.WriteLine("Manual for this command was not found.", Program.ErrorColor);
         }
     }
     else
     {
         ConsoleUtility.WriteLine("Invalid number of arguments passed.", Program.ErrorColor);
     }
 }
        /// <summary>
        /// Processes the feed results.  First, <see cref="LogRecord"/>s are added to <see cref="TrackedGpsData"/> of <see cref="TrackedVehicle"/>s and <see cref="StatusData"/>/<see cref="FaultData"/> records are added to <see cref="TrackedDiagnostic"/>s of <see cref="TrackedVehicle"/>s.  Then, the newly-received data for the affected <see cref="TrackedVehicle"/>s is written to file(s) (and summary info is written to the console window).
        /// </summary>
        /// <param name="results">The <see cref="FeedResultData"/> containing new data received from the data feeds.</param>
        /// <returns></returns>
        async Task ProcessFeedResultsAsync(FeedResultData results)
        {
            try
            {
                // For each received LogRecord, if the LogRecord is for a vehicle that is being tracked, add the LogRecord to the TrackedVehicle's TrackedGpsData.
                foreach (LogRecord logRecord in results.GpsRecords)
                {
                    TrackedVehicle trackedVehicleToUpdate = GetTrackedVehicle(logRecord.Device);
                    if (trackedVehicleToUpdate != null)
                    {
                        TrackedGpsData trackedGpsData = trackedVehicleToUpdate.TrackedGpsData;
                        trackedGpsData.AddData(logRecord);
                    }
                }

                if (useStatusDataFeed == true)
                {
                    // For each received StatusData, if the StatusData represents a Diagnostic that is being tracked and the StatusData is for a vehicle that is being tracked, add the StatusData to the TrackedVehicle's TrackedDiagnostics.
                    foreach (StatusData statusData in results.StatusData)
                    {
                        if (!DiagnosticsToTrack.Where(diagnostic => diagnostic.Id == statusData.Diagnostic.Id).Any())
                        {
                            continue;
                        }
                        TrackedVehicle trackedVehicleToUpdate = GetTrackedVehicle(statusData.Device);
                        if (trackedVehicleToUpdate != null)
                        {
                            TrackedDiagnostic trackedDiagnosticToUpdate = trackedVehicleToUpdate.TrackedDiagnostics.Where(trackedDiagnostic => trackedDiagnostic.DiagnosticId == statusData.Diagnostic.Id).First();
                            trackedDiagnosticToUpdate.AddData(statusData);
                        }
                    }
                }
                if (useFaultDataFeed == true)
                {
                    // For each received FaultData, if the FaultData represents a Diagnostic that is being tracked and the FaultData is for a vehicle that is being tracked, add the FaultData to the TrackedVehicle's TrackedDiagnostics.
                    foreach (FaultData faultData in results.FaultData)
                    {
                        if (!DiagnosticsToTrack.Where(diagnostic => diagnostic.Id == faultData.Diagnostic.Id).Any())
                        {
                            continue;
                        }
                        TrackedVehicle trackedVehicleToUpdate = GetTrackedVehicle(faultData.Device);
                        if (trackedVehicleToUpdate != null)
                        {
                            TrackedDiagnostic trackedDiagnosticToUpdate = trackedVehicleToUpdate.TrackedDiagnostics.Where(trackedDiagnostic => trackedDiagnostic.DiagnosticId == faultData.Diagnostic.Id).First();
                            trackedDiagnosticToUpdate.AddData(faultData);
                        }
                    }
                }
                WriteFeedResultStatsToConsole();
                foreach (TrackedVehicle trackedVehicle in TrackedVehicles)
                {
                    await trackedVehicle.WriteDataToFileAsync();
                }
            }
            catch (Exception ex)
            {
                ConsoleUtility.LogError(ex);
            }
        }
Exemplo n.º 22
0
        public static async Task Run(GeotabDataOnlyPlanAPI api)
        {
            ConsoleUtility.LogExampleStarted(typeof(GetFailureModesAsyncExample).Name);

            IList <FailureMode> failureModes;
            FailureMode         failureMode;

            try
            {
                // Example: Get all failureModes:
                failureModes = await api.GetFailureModesAsync();

                // Example: Search for a failureMode based on id:
                if (failureModes.Any())
                {
                    string failureModeId = failureModes.FirstOrDefault().Id.ToString();
                    failureModes = await api.GetFailureModesAsync(failureModeId);

                    failureMode = failureModes.FirstOrDefault();
                }
            }
            catch (Exception ex)
            {
                ConsoleUtility.LogError(ex);
            }

            ConsoleUtility.LogExampleFinished(typeof(GetFailureModesAsyncExample).Name);
        }
        /// <summary>
        /// Executes a "feed iteration" whereby data is retrieved via feed(s), feed result tokens are stored and persisted to file, feed results are processed (including writing data to output files and displaying summary data in the console window), and a delay of the configured duration is applied.  This method is called iteratively via the inherited <see cref="Worker.DoWorkAsync(bool)"/> method of the base <see cref="Worker"/> class.
        /// </summary>
        /// <returns></returns>
        public async override Task WorkActionAsync()
        {
            iterationNumber += 1;
            ConsoleUtility.LogSeparator2();
            ConsoleUtility.LogInfoMultiPart("Iteration:", iterationNumber.ToString(), Common.ConsoleColorForUnchangedData);

            // Execute the feed calls and get the results for processing.
            FeedResultData feedResultData = await feedProcessor.GetFeedDataAsync(feedParameters);

            // Write the feed result token (toVersion) values to file.
            using (StreamWriter faultDataTokenFileWriter = new(faultDataTokenFilePath))
            {
                faultDataTokenFileWriter.Write(feedParameters.LastFaultDataToken);
            }
            using (StreamWriter gpsTokenFileWriter = new(gpsTokenFilePath))
            {
                gpsTokenFileWriter.Write(feedParameters.LastGpsDataToken);
            }
            using (StreamWriter statusDataTokenFileWriter = new(statusDataTokenFilePath))
            {
                statusDataTokenFileWriter.Write(feedParameters.LastStatusDataToken);
            }

            // Process the feed results.
            await ProcessFeedResultsAsync(feedResultData);

            // Wait for the configured duration before executing the process again.
            ConsoleUtility.LogListItem($"Waiting for {FeedIntervalSeconds} second(s) before starting next iteration...");
            await Task.Delay(TimeSpan.FromSeconds(FeedIntervalSeconds));
        }
Exemplo n.º 24
0
 public virtual int RunApplication(TApplicationSettings settings)
 {
     try
     {
         var application = CreateApplication();
         application.Run(settings, _errorWriter, _logWriter);
     }
     catch (Exception e)
     {
         //_result = 1;
         using (ConsoleUtility.EnterColorScope(ConsoleColor.White, ConsoleColor.DarkRed))
         {
             _errorWriter.WriteLine("Execution aborted. Exception stack:");
             for (; e != null; e = e.InnerException)
             {
                 _errorWriter.Write(e.GetType().FullName);
                 _errorWriter.Write(": ");
                 _errorWriter.WriteLine(e.Message);
                 _errorWriter.WriteLine(e.StackTrace);
                 _errorWriter.WriteLine();
             }
         }
         return(1);
     }
     return(0);
 }
Exemplo n.º 25
0
 public void Execute(string[] args)
 {
     if (args.Length == 2)
     {
         if (double.TryParse(args[1], out double requiredVersion))
         {
             if (VersionHandler.IsThereVersion(requiredVersion))
             {
                 UpdateDatabase(requiredVersion);
             }
             else
             {
                 ConsoleUtility.WriteLine($"Version {requiredVersion} is not found.", Program.ErrorColor);
             }
         }
         else
         {
             ConsoleUtility.WriteLine("Invalid database version.", Program.ErrorColor);
         }
     }
     else
     {
         ConsoleUtility.WriteLine("Invalid number of arguments passed for updating database.", Program.ErrorColor);
     }
 }
Exemplo n.º 26
0
 private void ExecCommand(string command)
 {
     if (command.StartsWith("?"))
     {
         string        substring   = command.Substring(1);
         List <string> suggestions = new List <string>();
         CConfigManager.Instance.GetConsoleSuggestionsContainingString(substring, ref suggestions);
         if (suggestions.Count > 0)
         {
             foreach (string suggestion in suggestions)
             {
                 LogUtility.Log(suggestion);
             }
         }
         else
         {
             LogUtility.Log("No commands found");
         }
     }
     else
     {
         ConsoleUtility.ProcessConsoleString(command);
         LogUtility.Log("Executing: " + command);
     }
     AddToHistory(command);
 }
Exemplo n.º 27
0
        public User GetUser(MySqlConnection conn, string username, string password)
        {
            MySqlDataReader reader = null;

            try
            {
                MySqlCommand cmd = new MySqlCommand(GetUserCommand, conn);
                cmd.Parameters.AddWithValue(UsernameParam, username);
                cmd.Parameters.AddWithValue(PasswordParam, password);
                reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    int  id   = reader.GetInt32(IdParam);
                    User user = new User(id, username, password);
                    return(user);
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception e)
            {
                ConsoleUtility.WriteLine(e, ConsoleColor.Red);
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
            return(null);
        }
Exemplo n.º 28
0
        private void OnConsoleCommandEntered(object textObject)
        {
            string text = textObject as string;

            if (SelectedConsoleSuggestion != -1)
            {
                ConsoleInputText          = m_rawConsoleSuggestions[SelectedConsoleSuggestion];
                SelectedConsoleSuggestion = -1;
                ConsoleView.SelectEndOfConsoleInput();
                OnUpdateSuggestions(ConsoleInputText);
            }
            else if (text.StartsWith("?"))
            {
                string argument = ConsoleUtility.GetConsoleStringArgument(text.Substring(1), 0);
                if (argument != null)
                {
                    LogUtility.Log("----------------------------------");
                    LogUtility.Log("Suggestions for search term '{0}':", argument);
                    List <string> suggestions = new List <string>();
                    CConfigManager.Instance.GetConsoleSuggestionsContainingString(argument, ref suggestions);

                    foreach (string suggestion in suggestions)
                    {
                        LogUtility.Log(suggestion);
                    }
                    ConsoleInputText = "";
                }
            }
            else
            {
                ConsoleUtility.ProcessConsoleString(text);
                ConsoleInputText = "";
                OnClearSuggestions(null);
            }
        }
        public void Run()
        {
            LinkedList <int> linkedList = new LinkedList <int>();

            linkedList.InsertFirst(5);
            linkedList.InsertFirst(4);
            linkedList.InsertFirst(3);
            linkedList.InsertFirst(2);
            linkedList.InsertFirst(1);
            linkedList.printAllNodes();
            linkedList.InsertTop(1);
            linkedList.InsertTop(2);
            linkedList.InsertTop(3);
            linkedList.InsertTop(4);
            linkedList.InsertTop(5);
            linkedList.printAllNodes();
            linkedList.ReverseLinkedList();
            linkedList.printAllNodes();
            ConsoleUtility.WriteLine($"Data {linkedList.ExistValue(4)}");
            linkedList.DeleteNodeByKey(4);
            ConsoleUtility.WriteLine($"Data {linkedList.ExistValue(4)}");
            linkedList.printAllNodes();
            linkedList.InsertTop(10);
            linkedList.printAllNodes();
            ConsoleUtility.WriteLine($"Total of elements of the linked list {linkedList.GetCount()}");
        }
Exemplo n.º 30
0
 public void Response(Client client, RequestCode requestCode, byte[] dataBytes)
 {
     if (notifiers.ContainsKey(requestCode))
     {
         foreach (var func in notifiers[requestCode])
         {
             Type[] types = func.GetType().GetGenericArguments();
             if (types[1] == typeof(byte[]) && types[2] == types[1])
             {
                 client.Publish(requestCode, (func as Func <Client, byte[], byte[]>)?.Invoke(client, dataBytes));
             }
             else if (types[1] == typeof(string) && types[2] == typeof(byte[]))
             {
                 client.Publish(requestCode, (func as Func <Client, string, byte[]>)?.Invoke(client, Encoding.UTF8.GetString(dataBytes)));
             }
             else if (types[1] == typeof(byte[]) && types[2] == typeof(string))
             {
                 client.Publish(requestCode, (func as Func <Client, byte[], string>)?.Invoke(client, dataBytes));
             }
             else if (types[1] == typeof(string) && types[2] == types[1])
             {
                 client.Publish(requestCode, (func as Func <Client, string, string>)?.Invoke(client, Encoding.UTF8.GetString(dataBytes)));
             }
         }
     }
     else
     {
         ConsoleUtility.WriteLine("The notifier corresponding to " + requestCode + " could not be found.");
     }
 }
Exemplo n.º 31
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ExecutionContext"/> class.
 /// </summary>
 /// <param name="io">The io.</param>
 /// <param name="command">The command.</param>
 /// <param name="runner">The runner.</param>
 /// <param name="arguments">The arguments.</param>
 public ExecutionContext(ConsoleUtility io, CommandResult command, CommandRunner runner, List<string> arguments)
 {
     IO = io;
     Command = command;
     Runner = runner;
     Arguments = arguments;
 }