public static ConsoleScreenBufferInfoEx GetCurrent()
        {
            var ret = GetNew();

            ExtendedConsole.GetConsoleInfo(ref ret);
            return(ret);
        }
Exemplo n.º 2
0
        private static void AddNoteIntoNotebook()
        {
            var existingNotebooks = DataAccessor.GetNotebooks(_sourceType);

            PrintNotebooks(existingNotebooks);

            if (ExtendedConsole.TryReadInt32WithMessage("Enter the index of the notebook you are interested in", out int index))
            {
                try
                {
                    var notebook = existingNotebooks[index];
                    var note     = ExtendedConsole.ReadNote();

                    notebook.Notes.Add(note);

                    DataAccessor.UpdateNotebook(notebook, _sourceType);
                    Console.WriteLine("Note has been successfully added to notebook");
                }
                catch (IndexOutOfRangeException)
                {
                    Console.WriteLine("The index you specified is out of bounds for existing notebooks, please try again");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
        }
        public override async Task OnExceptionAsync(ExceptionContext context)
        {
            ExtendedConsole.Log(context.Exception);
            await Logger.LogExceptionAsync(context.Exception, false);

            await base.OnExceptionAsync(context);
        }
Exemplo n.º 4
0
        private static void ExtendedConsoleDemo()
        {
            Console.CursorVisible = false;
            short w = (short)Console.BufferWidth;
            short h = (short)Console.BufferHeight;

            var buf = new ExtendedConsole.CharInfo[w * h];

            var rect = new ExtendedConsole.SmallRect {
                Left = 0, Top = 0, Right = w, Bottom = h
            };

            var p     = ExtendedConsole.Coord.Zero;
            var s     = new ExtendedConsole.Coord(w, h);
            var chars = Encoding.GetEncoding(437).GetChars(Enumerable.Range(0, byte.MaxValue).Select(i => (byte)i).Except(new byte[] { 8, 9, 10, 7 }).ToArray());

            for (int x = 0; x < 10000; x++)
            {
                for (int i = 0; i < buf.Length; ++i)
                {
                    buf[i].Attributes     = (short)((x + i) % 0x80);
                    buf[i].Char.AsciiChar = (byte)chars[(x + i) % chars.Length];
                }

                ExtendedConsole.UpdateRegion(buf, p, s, ref rect);
            }
        }
Exemplo n.º 5
0
            public static void Line(Resource.Position p1, Resource.Position p2)
            {
                if (p1.X == p2.X)
                {
                    return;
                }
                double k = (p2.Y - p1.Y) / (p2.X - p1.X);

                int y(int x) => (int)(k * (x - p1.X) + p1.Y);

                if (p1.X < p2.X)
                {
                    for (int x = p1.X; x < p2.X; x++)
                    {
                        ExtendedConsole.SetChar(x, y(x), '#');
                    }
                }
                else
                {
                    for (int x = p2.X; x < p1.X; x++)
                    {
                        ExtendedConsole.SetChar(x, y(x), '#');
                    }
                }
            }
Exemplo n.º 6
0
        public static void ApplyMigrations(ServiceProvider serviceProvider)
        {
            var connectionStrings = serviceProvider.GetServices <SqlConnectionStringWrapper>();

            foreach (var connectionString in connectionStrings)
            {
                ExtendedConsole.Log($"Applying migrations for {connectionString.ContextType.Name}");
                using (var context = (DbContext)serviceProvider.GetRequiredService(connectionString.ContextType))
                {
                    var migrations = context.Database.GetPendingMigrations();
                    if (migrations.Any())
                    {
                        ExtendedConsole.Log($"Applying the following {migrations.Count()} migrations for {connectionString.ContextType.Name}:");
                        foreach (var migration in migrations)
                        {
                            ExtendedConsole.Log(migration);
                        }
                        context.Database.Migrate();
                        ExtendedConsole.Log($"Finished applying migrations for {connectionString.ContextType.Name}");
                    }
                    else
                    {
                        ExtendedConsole.Log($"No migrations found to apply for {connectionString.ContextType.Name}");
                    }
                }
            }
        }
Exemplo n.º 7
0
        public WindowsCore()
        {
            Console = new ExtendedConsole(new MaxLib.Console.ExtendedConsole.ExtendedConsoleOptions()
            {
                BoxHeight            = 15,
                BoxWidth             = 10,
                ShowMouse            = true,
                RunFormInExtraThread = false,
            });
            Console.Load += () =>
            {
                Console.Options.SetFontSize(11);
                MainPart.Width  = Console.Matrix.Width;
                MainPart.Height = Console.Matrix.Height - 2;
            };

            var back = new ImageViewer();

            back.AlternativeColor = ConsoleColor.Green;
            Console.MainContainer.Add(MainPart = new MainTargetWindow(back)
            {
                X = 0,
                Y = 0
            });
            Console.MainContainer.Add(TaskBar = new TaskBar());
            InitialStartMenu();
        }
Exemplo n.º 8
0
        private static void DeleteNotebook()
        {
            var existingNotebooks = DataAccessor.GetNotebooks(_sourceType);

            PrintNotebooks(existingNotebooks);

            if (ExtendedConsole.TryReadInt32WithMessage("Enter the index of the notebook you are delete", out int index))
            {
                try
                {
                    var notebook = existingNotebooks[index];

                    DataAccessor.RemoveNotebook(notebook, _sourceType);
                    Console.WriteLine("Notebook successfully deleted");
                }
                catch (IndexOutOfRangeException)
                {
                    Console.WriteLine("The index you specified is out of bounds for existing notebooks, please try again");
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
        }
Exemplo n.º 9
0
 public MainMenu(ExtendedConsole Console, string Text, string Key)
 {
     Submenu      = new List <MainMenu>();
     this.Console = Console;
     this.Text    = Text;
     this.Key     = Key;
 }
Exemplo n.º 10
0
        public static ServiceProvider Run(Assembly assembly, string busConnectionString, Func <IServiceCollection, IServiceCollection> addAdditionalServices = null, params Action <ServiceProvider>[] additionalActions)
        {
            var installerStopwatch = new Stopwatch();

            installerStopwatch.Start();

            addAdditionalServices = addAdditionalServices ?? (s => s);

            var bus = RabbitHutch.CreateBus(busConnectionString).WaitForConnection();

            ExtendedConsole.Log($"ServiceInstaller: Bus connected: {bus.IsConnected}.");

            var serviceProvider = addAdditionalServices(new ServiceCollection())
                                  .AddEventHandlers(assembly)
                                  .AddRequestHandlers(assembly)
                                  .AddPingRequestHandlers(assembly)
                                  .AddSingleton(bus)
                                  .BuildServiceProvider(true);

            ExtendedConsole.Log("ServiceInstaller: Services are registered.");

            Logger.SetServiceProvider(serviceProvider);
            ExtendedConsole.Log("ServiceInstaller: Logger initialized");

            var responder = new AutoResponder(bus, new AutoResponderRequestDispatcher(serviceProvider));

            responder.RespondAsync(assembly);
            ExtendedConsole.Log("ServiceInstaller: AutoResponders initialized.");

            var pingResponder = new PingResponder(bus, new AutoResponderRequestDispatcher(serviceProvider));

            pingResponder.RespondAsync(assembly);
            ExtendedConsole.Log("ServiceInstaller: PingResponder initialized.");

            var subscriber = new CustomAutoSubscriber(bus, new CustomAutoSubscriberMessageDispatcher(serviceProvider), assembly.FullName);

            subscriber.SubscribeAsync(assembly);
            ExtendedConsole.Log("ServiceInstaller: AutoSubscribers initialized.");

            if (additionalActions != null)
            {
                foreach (var additionalAction in additionalActions)
                {
                    var additionalActionStopwatch = new Stopwatch();
                    additionalActionStopwatch.Start();

                    ExtendedConsole.Log($"ServiceInstaller: Running {additionalAction.Method.Name}");
                    additionalAction(serviceProvider);
                    additionalActionStopwatch.Stop();

                    ExtendedConsole.Log($"ServiceInstaller: {additionalAction.Method.Name} finished running in {additionalActionStopwatch.ElapsedMilliseconds}ms.");
                }
            }

            installerStopwatch.Stop();
            ExtendedConsole.Log($"ServiceInstaller: Finished running in {installerStopwatch.ElapsedMilliseconds}ms.");

            return(serviceProvider);
        }
Exemplo n.º 11
0
 public ClipWriterAsync(ExtendedConsole Owner, int x, int y, int width, int height)
 {
     this.Owner = Owner;
     X          = x;
     Y          = y;
     Width      = width;
     Height     = height;
 }
        public static IServiceCollection AddRabbitBus(this IServiceCollection serviceCollection, string connectionString)
        {
            var bus = RabbitHutch.CreateBus(connectionString).WaitForConnection();

            ExtendedConsole.Log($"Bus connected: {bus.IsConnected}.");

            return(serviceCollection.AddSingleton(bus));
        }
Exemplo n.º 13
0
        private static void PrintAvailableCommands()
        {
            var commandInfos = ExtendedConsole.GetAvailableCommands();

            for (int i = 0; i < commandInfos.Length; i++)
            {
                Console.WriteLine(commandInfos[i]);
            }
        }
Exemplo n.º 14
0
 public MainMenu(ExtendedConsole Console, string Text, Action click)
 {
     Submenu      = new List <MainMenu>();
     this.Console = Console;
     this.Text    = Text;
     if (click != null)
     {
         Click += click;
     }
 }
Exemplo n.º 15
0
        private string Tabcallback(string s)
        {
            var x = Console.CursorLeft;
            var y = Console.CursorTop;

            ExtendedConsole.ClearConsoleLine(48);
            Console.SetCursorPosition(0, 48);
            var ret = PrintLevel(s);

            Console.SetCursorPosition(x, y);
            return(ret);
        }
Exemplo n.º 16
0
 public void Run()
 {
     IsDone = false;
     OnInit();
     while (!IsDone)
     {
         var title = ExtendedConsole.GetHeader(Title, qHeaderChars: 10);
         ExtendedConsole.WriteLineColorized(title, ConsoleColor.Green);
         OnShowLegend();
         OnPerform();
     }
     OnExit();
 }
Exemplo n.º 17
0
        private static void Main()
        {
            Console.Title = "The Closet";

            Console.SetWindowSize(200, 50);
            Console.SetBufferSize(Console.WindowWidth, Console.WindowHeight);

            ExtendedConsole.FixConsoleSize();

            //ExtendedConsoleMouseDemo();
            //ExtendedConsoleDemo();
            //ScrollingPaneDemo();
            new Game().Run();
            Console.ReadLine();
        }
Exemplo n.º 18
0
        public Task <bool> TrySaveChangesAsync()
        {
            try
            {
                SaveChangesAsync();
            }
            catch (DbUpdateException ex)
            {
                ExtendedConsole.Log(ex);
                Logger.LogExceptionAsync(ex, true);
                return(Task.FromResult(false));
            }

            return(Task.FromResult(true));
        }
Exemplo n.º 19
0
        private async Task CheckInterval(TimeInterval interval, DateTime now, Func <DateTime, Task> publishAction)
        {
            if (IntervalHasPassed(_lastCheck[interval], now))
            {
                ExtendedConsole.Log($"{interval.ToString()} has passed!");
                _lastCheck[interval].Last = now;
                _context.TimeEvents.Add(new TimeEvent
                {
                    Type    = interval,
                    Created = now
                });

                await _context.SaveChangesAsync();
                await publishAction(now);
            }
        }
Exemplo n.º 20
0
        private static void Main(string[] args)
        {
            DataAccessor.SetDefaultConfiguration();
            ExtendedConsole.Initialize();

            PrintAvailableCommands();

            while (!_exited)
            {
                if (ExtendedConsole.TryReadCommand(out ConsoleCommand command))
                {
                    ExtendedConsole.ExecuteCommand(command);
                }
            }

            Console.WriteLine("The program has successfully completed its work");
        }
        public async Task DispatchAsync <TMessage, TConsumer>(TMessage message)
            where TMessage : class
            where TConsumer : class, IConsumeAsync <TMessage>
        {
            ExtendedConsole.Log($"{message.GetType().Name} received");
            var consumer = _serviceProvider.GetRequiredService <TConsumer>();

            try
            {
                await consumer.ConsumeAsync(message);
            }
            catch (Exception ex)
            {
                ExtendedConsole.Log(ex);
                Logger.LogExceptionAsync(ex, false, consumer.GetType().Name);
            }
        }
Exemplo n.º 22
0
        public async Task Run(string[] args)
        {
            _logger.Log("Starting Application");
            ExtendedConsole.PrintHelpText();

            while (!_cts.IsCancellationRequested)
            {
                var key = Console.ReadKey();
                ExtendedConsole.BlankLine();
                switch (key.Key)
                {
                case ConsoleKey.W:
                    //This could be for example on an event or message received from RabbitMQ, etc...
                    await _finiteStateMachine.TriggerAction(TransportActions.WakeUp);

                    break;

                case ConsoleKey.T:
                    await _finiteStateMachine.TriggerAction(TransportActions.TakeTrain);

                    break;

                case ConsoleKey.S:
                    await _finiteStateMachine.TriggerAction(TransportActions.FallAsleep);

                    break;

                case ConsoleKey.L:
                    _logger.Log(_finiteStateMachine.GetCurrentState());
                    break;

                case ConsoleKey.Escape:
                case ConsoleKey.E:
                    _cts.Cancel();
                    break;

                default:
                    Console.WriteLine($"You Pressed {key.Key}");
                    ExtendedConsole.PrintHelpText();
                    ExtendedConsole.BlankLine();
                    break;
                }
            }

            _logger.Log($"Closing Application");
        }
Exemplo n.º 23
0
        /// <summary>
        /// Export all records from <paramref name="tableName"/> in database <paramref name="databaseName"/> to external table
        /// <paramref name="externalTableName"/>. Split by intervals of <paramref name="step"/> (of ingestion time)
        /// </summary>
        private static void ExportTableToExternalTable(string databaseName, string tableName, string externalTableName, TimeSpan step)
        {
            // This authenticates based on user credentials. Can replace with AAD app if needed (see KustoConnectionStringBuilder API)
            var connection          = new KustoConnectionStringBuilder($"{KustoClusterUri};Fed=true");
            var queryClient         = KustoClientFactory.CreateCslQueryProvider(connection);
            var adminClient         = KustoClientFactory.CreateCslAdminProvider(connection);
            var minMaxIngestionTime = queryClient.ExecuteQuery <MinMaxDateTime>(databaseName, $"{tableName} | summarize min(ingestion_time()), max(ingestion_time())").Single();

            var start = minMaxIngestionTime.Min;
            var end   = minMaxIngestionTime.Max;

            while (start < end)
            {
                DateTime curEnd        = start + step;
                var      exportCommand = CslCommandGenerator.GenerateExportToExternalTableCommand(externalTableName,
                                                                                                  query: $"{tableName} | where ingestion_time() >= {CslDateTimeLiteral.AsCslString(start)} and ingestion_time() < {CslDateTimeLiteral.AsCslString(curEnd)}",
                                                                                                  sizeLimitInBytes: MemoryConstants._1GB,
                                                                                                  persistDetails: true,
                                                                                                  isAsync: true);

                var crp = new ClientRequestProperties();
                crp.ClientRequestId = $"ExportApp;{Guid.NewGuid().ToString()}";
                ExtendedConsole.WriteLine(ConsoleColor.Cyan, $"Executing export command from {start.FastToString()} to {curEnd.FastToString()} with request id {crp.ClientRequestId}");

                var operationDetails = adminClient.ExecuteAsyncControlCommand(databaseName, exportCommand, TimeSpan.FromMinutes(60), TimeSpan.FromSeconds(1), crp);
                var state            = operationDetails.State;
                if (state == "Completed")
                {
                    // check num records exported
                    var  command         = $"{CslCommandGenerator.GenerateOperationDetailsShowCommand(operationDetails.OperationId)} | summarize sum(NumRecords)";
                    long exportedRecords = adminClient.ExecuteControlCommand <long>(command).Single();

                    ExtendedConsole.WriteLine(ConsoleColor.Green, $"Operation {operationDetails.OperationId} completed with state {operationDetails.State} and exported {exportedRecords} records");
                }
                else
                {
                    // TODO: retry same scope again (or abort and check root cause for failure). Operation may still be running on server side, so retrying
                    // without checking status can lead to duplicates
                    ExtendedConsole.WriteLine(ConsoleColor.Red, $"Operation {operationDetails.OperationId} completed with state {operationDetails.State}. Status: {operationDetails.Status}");
                }

                start = curEnd;
            }
        }
Exemplo n.º 24
0
        public void Run()
        {
            Player.ChangeLocation(new Locations.OfficeBuilding.TheCloset.DarkPlace());
            PrintHeader();
            Console.ForegroundColor = ConsoleColor.DarkGray;
            do
            {
                DrawInventory();

                OutputPane.Draw();

                ExtendedConsole.ClearConsoleLine(49);
                Console.SetCursorPosition(0, 49);
                var str = ReadMyLine(PrintStr, Tabcallback).Trim();

                var match = Player.Verbs.FirstOrDefault(
                    o => o.FirstPart.Permute().Any(x => x.ToString().Equals(str, StringComparison.InvariantCultureIgnoreCase)));

                if (match?.Action != null)
                {
                    if (!CommandHistory.LastOrDefault()?.Equals(str, StringComparison.InvariantCultureIgnoreCase) ?? true)
                    {
                        CommandHistory.Add(str);
                    }

                    if (OutputPane.Entries.Last().Length != 0)
                    {
                        OutputPane.WriteLine();
                    }
                    //OutputPane.Write($"{str}> ".DarkGray());
                    match.Action(str);
                }
                else
                {
                    ExtendedConsole.ClearConsoleLine(48);
                    Console.SetCursorPosition(0, 48);
                    "\rCould not find that command...".Red(true).Write();
                }
                CommandHistoryIndex = 0;
            } while (Player.Verbs.Any());
        }
Exemplo n.º 25
0
        public static void ValidateMongoConnections(ServiceProvider serviceProvider)
        {
            var mongoConnectionStrings = serviceProvider.GetServices <MongoConnectionStringWrapper>();

            foreach (var connectionStringWrapper in mongoConnectionStrings)
            {
                while (true)
                {
                    var client = new MongoClient(connectionStringWrapper.ConnectionString);
                    if (client.Cluster.Description.State == ClusterState.Connected)
                    {
                        break;
                    }

                    Thread.Sleep(2500);
                    ExtendedConsole.Log($"Waiting for mongoserver for database {connectionStringWrapper.DatabaseName} to come online..");
                }

                ExtendedConsole.Log($"Mongoserver for database {connectionStringWrapper.DatabaseName} is online.");
            }
        }
Exemplo n.º 26
0
 private void DrawInventory()
 {
     ExtendedConsole.ClearConsoleArea((short)(Console.BufferWidth - (INV_WIDTH - 1)), 1, INV_WIDTH - 1,
                                      (short)(Console.BufferHeight - (1 + 3)));
     Console.SetCursorPosition(Console.BufferWidth - (INV_WIDTH - 2), 1);
     foreach (var item in Player.Items)
     {
         if (item is LiquidContainerItem)
         {
             ("» " + item.Name).Write();
             Console.ForegroundColor = ConsoleColor.DarkGray;
             var li = item as LiquidContainerItem;
             var ml = li.LiquidTypes.Max(o => o.Length);
             var mt = li.LiquidUnits.Values.Max(o => o.Length);
             var am = li.LiquidStorage.Values.Max(o => $"{o:0.##}".Length);
             var mm = li.LiquidMax.Values.Max(o => $"{o:0.##}".Length);
             foreach (var l in li.LiquidTypes.Where(o => li.LiquidStorage[o] > 0))
             {
                 var a    = li.LiquidStorage[l];
                 var m    = li.LiquidMax[l];
                 var astr = $"{a:0.##}";
                 var mstr = $"{m:0.##}";
                 var amnt = $"{new string(' ', am - astr.Length)}{astr}/{mstr}{li.LiquidUnits[l]}{new string(' ', mt - li.LiquidUnits[l].Length)}{new string(' ', mm - mstr.Length)}";
                 var w    = (INV_WIDTH - 7) - (ml + amnt.Length);
                 var p    = (int)(w * (a / m));
                 Console.SetCursorPosition(Console.BufferWidth - (INV_WIDTH - 2), Console.CursorTop + 1);
                 var n = $"{l}{new string(' ', ml - l.Length)}";
                 Console.Write($"∙ {n} {amnt} {new string('█', p)}");
                 Console.Write(new string('░', w - p));
             }
         }
         else
         {
             ("» " + item.Name).Write();
         }
         Console.SetCursorPosition(Console.BufferWidth - (INV_WIDTH - 2), Console.CursorTop + 1);
     }
 }
Exemplo n.º 27
0
        public override void OnPerform()
        {
            var key = Console.ReadKey(true).Key;

            Console.WriteLine();
            switch (key)
            {
            case ConsoleKey.D1:
            case ConsoleKey.NumPad1:
                _productDepartmentMenu.Run();
                break;

            case ConsoleKey.Escape:
                IsDone = true;
                break;

            default:
                ExtendedConsole.WriteLineColorized("Wrong key!", ConsoleColor.Red);
                Thread.Sleep(1000);
                break;
            }
            Console.Clear();
        }
Exemplo n.º 28
0
        static void Main(string[] args)
        {
            ExtendedConsole.Log("LoggingService started..");

            SetupConfiguration();

            var serviceProvider = ServiceInstaller.Run(
                Assembly.GetExecutingAssembly(),
                _rabbitMqConnectionString,
                services => services
                .AddAutoMapper(Assembly.GetExecutingAssembly())
                .AddMongoDatabase(_mongoConnectionString, _mongoDatabase)
                .AddTransient <MessageHandler>()
                .AddTransient <ExceptionMessageHandler>()
                .AddTransient <WebRequestMessageHandler>(),
                DatabaseHelper.ValidateMongoConnections);

            var bus    = serviceProvider.GetRequiredService <IBus>();
            var logger = new MessageLogger(bus, serviceProvider, "MessageLoggerSubscription");

            logger.Start();

            bus.Receive <ExceptionMessage>(ServiceInstaller.ExceptionQueue, async message =>
            {
                var handler = serviceProvider.GetRequiredService <ExceptionMessageHandler>();
                await handler.HandleAsync(message);
            });

            bus.Receive <WebRequest>(ServiceInstaller.WebRequestsQueue, async message =>
            {
                var handler = serviceProvider.GetRequiredService <WebRequestMessageHandler>();
                await handler.HandleAsync(message);
            });

            Thread.Sleep(Timeout.Infinite);
        }