Example #1
0
            private static bool MainMenu()
            {
                Console.Clear();
                Console.WriteLine("Choose an option:");
                Console.WriteLine("1) Print Numberz Game");
                Console.WriteLine("2) Guessing Game");
                Console.WriteLine("3) Exit");

                string result = Console.ReadLine();

                if (result == "1")
                {
                    PrintNumbers();
                    return(true);
                }
                if (result == "2")
                {
                    GuessingGame();
                    return(true);
                }
                if (result == "3")
                {
                    return(false);
                }
                return(true);
            }
Example #2
0
        /// <summary>
        /// Main entry point for this application.
        /// </summary>
        /// <param name="args">The arguments.</param>
        static void Main(String[] args)
        {
            Kernel = new StandardKernel();
            Dependencies.Register(Kernel);
            Initialize();
            Console.SetWindowSize(Console.LargestWindowWidth, Console.LargestWindowHeight);

start:
            Console.Clear();

            var banner1 = new ConsoleBanner("HYPERSPIN VALIDATOR", "Arial", 8, FontStyle.Bold, 150, 14)
            {
                ForeColor = ConsoleColor.Blue, Pallet = new Char[] { '#', '%', 'M', 'V', 'l', ',', '.', ' ' }
            };

            banner1.Execute();


            var menu = new ConsoleMenuList {
                GridWidth = 4, ItemWidth = 40, BorderStyle = ConsoleBorderStyle.SingleDouble
            };

            foreach (var console in HyperSpin.Consoles)
            {
                menu.Items.Add(new ConsoleListItem(console.Name, console));
            }

            menu.Execute();
            CurrentConsole = menu.SelectedValue as HyperValidator.Models.Console;
            TestConsoleRepository(menu.SelectedItem.Text);
            goto start;
        }
Example #3
0
        public void Render(object target)
        {
            var result = target as ConceptDefs;

            if (result == null)
            {
                throw new ArgumentException($"The specified item is not of type {nameof(ConceptDefs)}", nameof(target));
            }

            CONS.Clear();
            CONS.WriteLine(nameof(ConceptDefs));

            if (result.Items != null)
            {
                foreach (var item in result.Items)
                {
                    WriteItemToConsole(item);
                }
            }

            if (result.Instructions != null)
            {
                foreach (var instr in result.Instructions)
                {
                    WriteInstructionToConsole(instr);
                }
            }
        }
Example #4
0
        public static void PigActions()
        {
            Console.WriteLine("Pig 1, Pig 2, or Pig 3, Return 4");
            var var2 = Console.ReadLine();

            if (var2 == "1")
            {
                Console.WriteLine("The first pig says \"Oink\"");
                ReturntoPigs();
            }
            else if (var2 == "2")
            {
                Console.WriteLine("The second pig rolls in the mud");
                ReturntoPigs();
            }
            else if (var2 == "3")
            {
                Console.WriteLine("Napoleon the pig says \"All animals are equal, " +
                                  "but some animals are more equal than others\"...Oink");
                ReturntoPigs();
            }
            else if (var2 == "4")
            {
                Console.Clear();
                Menu.AnimalMenu();
            }
            //else if (var2 == "5")
            //{
            //    Menu.AnimalMenu();
            //}
        }
Example #5
0
        static void Main(string[] args)
        {
            ConsoleOutput console = new ConsoleOutput(OriginalConsole.BufferWidth, 29);
            IConsoleInput input   = new ConsoleInput();
            int           i       = 0;
            Random        random;

            while (true)
            {
                random = new Random(DateTime.Now.Millisecond + i);

                OriginalConsole.Clear();
                for (var y = 0; y < 29; y++)
                {
                    for (var x = 0; x < console.BufferWidth; x++)
                    {
                        console.Fore = (ConsoleColor)random.Next(16);
                        console.Back = (ConsoleColor)random.Next(16);
                        console.Print('#');
                    }
                }
                console.Reset();
                console.CursorY = 10;
                console.CursorX = 5;
                console.Fore    = ConsoleColor.White;
                console.Back    = ConsoleColor.Black;
                console.Print("Burklax");

                console.Flush();
                input.Read();
            }
        }
Example #6
0
 private void CmdRefresh()
 {
     C.Clear();
     _maxRendered = 0;
     Render();
     ForceCursor(_cursor);
 }
Example #7
0
        private static void Main()
        {
            Task.Factory.StartNew(RefreshTitle);

            while (true)
            {
                Console.ForegroundColor = Settings.Default.MessageForeground;
                string oldTask = ReadLastTask();
                Console.WriteLine(Settings.Default.Label);
                Console.ForegroundColor = Settings.Default.TaskForegroundColor;
                Console.WriteLine(oldTask);
                Console.ForegroundColor = Settings.Default.MessageForeground;
                Console.WriteLine(Settings.Default.NewTaskMessage);
                Console.ForegroundColor = Settings.Default.TaskForegroundColor;
                string newTask = Console.ReadLine();
                if (string.IsNullOrEmpty(newTask))
                {
                    newTask = oldTask;
                }

                SaveTask(newTask);
                Console.Clear();
                Console.ForegroundColor = Settings.Default.MessageForeground;
                Console.Write(Settings.Default.SavingMessage);
                for (int i = 0; i < 3; ++i)
                {
                    Thread.Sleep(Settings.Default.SaveDelay);
                    Console.Write('.');
                }
                Console.WriteLine();
                Console.WriteLine(Settings.Default.SaveMessage);
                Thread.Sleep(Settings.Default.PostSaveDelay);
                Console.Clear();
            }
        }
Example #8
0
        static void Main(string[] args)
        {
            // Получить с консоли значение трех целых чисел
            // Выбрать наибоьшее из трех чисел
            // Вывести на консоль
            // Сравнить число на четность с помощью свич
            // Проверить на размер < 100 с помощью быстрой проверки

            int a, b, c = 0;

            Console.WriteLine("Вам нужно ввести три разных числа:");

            Console.Write("Введите первое число: ");
            a = EvenNumber(Convert.ToInt32(Console.ReadLine()));


            Console.Write("Введите второе число: ");
            b = EvenNumber(Convert.ToInt32(Console.ReadLine()));

            Console.Write("Введите третие число: ");
            c = EvenNumber(Convert.ToInt32(Console.ReadLine()));



            Console.Clear();
            Console.WriteLine($"Вы ввели: {a}, {b}, {c}");

            NumberCheck(a, b, c);

            Console.ReadLine();
        }
Example #9
0
        /// <summary>
        /// Tests the console repository.
        /// </summary>
        /// <param name="consoleName">Name of the console.</param>
        static void TestConsoleRepository(String consoleName)
        {
            try
            {
                Console.Clear();
                new ConsoleBanner(consoleName, "Arial", 8, FontStyle.Bold, 150, 14)
                {
                    ForeColor = ConsoleColor.Cyan, Pallet = new [] { '#', '%', 'M', 'V', 'l', ',', '.', ' ' }
                }.Execute();
                Console.WriteLine("Validating Console Data");


                var console = ConsoleRepository.Get(consoleName);
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("[ERROR] An error occurred while getting validating this console.");
                Console.WriteLine(ex.Message);
                Console.ForegroundColor = ConsoleColor.White;

                var menu = new ConsoleMenuList {
                    GridWidth = 2, ItemWidth = 14, BorderStyle = ConsoleBorderStyle.SingleDouble
                };
                menu.Items.Add(new ConsoleListItem("Refresh", "Refresh"));
                menu.Items.Add(new ConsoleListItem("Main Menu", "Main Menu"));
                menu.Execute();
                if (menu.SelectedItem.Text == "Refresh")
                {
                    TestConsoleRepository(CurrentConsole.Name);
                }
            }
        }
Example #10
0
            private static void GuessingGame()
            {
                Console.Clear();
                Console.WriteLine("Guessing Game!");

                Random myRandom     = new Random();
                int    randomNumber = myRandom.Next(1, 11);

                int  guesses   = 0;
                bool incorrect = true;

                do
                {
                    Console.WriteLine("Guess a number between 1 and 10: ");
                    string result = Console.ReadLine();
                    guesses++;
                    if (result == randomNumber.ToString())
                    {
                        incorrect = false;
                    }
                    else
                    {
                        Console.WriteLine("Wrong!");
                    }
                } while (incorrect);

                Console.WriteLine("Correct! It took you {0} guesses.", guesses);
                Console.ReadLine();
            }
Example #11
0
        protected override unsafe void Run()
        {
            Console.BackgroundColor = ConsoleColor.DarkBlue;
            Console.Clear();
            Thread.Sleep(1000);
            while (true)
            {
                Beep();
            }
            return;

            for (int i = 0; i != 10; i++)
            {
                Console.WriteLine("test!");
            }
            Thread.Sleep(5000);
            Cosmos.HAL.Global.TextScreen.Background = ConsoleColor.DarkRed;
            Cosmos.HAL.Global.TextScreen.Foreground = ConsoleColor.Black;
            Cosmos.HAL.Global.TextScreen.SetColors(ConsoleColor.Black, ConsoleColor.DarkRed);
            Cosmos.HAL.Global.TextScreen.Clear();
            while (true)
            {
                Console.WriteLine("test!");
                Thread.Sleep(1000);
            }
        }
        public void T()
        {
            int HE = 100, M = 100, F = 10, HU = 0, S = 0, P = 0;

            Action w = () => {
                X.Clear(); X.WriteLine(string.Format("Health: {0}\r\nMoney: {1}\r\nFood: {2}\r\nHunger: {3}\r\nSleep: {4}\r\nPotions: {5}\r\n",
                                                     HE, M, F, HU, S, P));
            };

            while (HE > 0)
            {
                if (X.KeyAvailable)
                {
                    var i = X.ReadKey();

                    if (i.Key == Y.F)
                    {
                        F  -= F > 0 ? 1 : 0;
                        HU -= HU > 8 && F > 0 ? 9 : 0;
                        w();
                    }
                    if (i.Key == Y.S)
                    {
                        S = 0;
                        w();
                    }
                    if (i.Key == Y.P)
                    {
                        HE += P > 0 ? 9 : 0;
                        P  -= P > 0 ? 1 : 0;
                        w();
                    }
                    if (i.Key == Y.B)
                    {
                        P += M > 9 ? 1 : 0;
                        M -= M > 8 ? 9 : 0;
                        w();
                    }
                    if (i.Key == Y.T)
                    {
                        F += M > 8 ? 1 : 0;
                        M -= M > 8 ? 9 : 0;
                        w();
                    }
                }


                HU++;
                S++;
                HE -= HU >= 80 ? 1 : 0;
                HU += S >= 80 ? 9 : 0;
                S   = S >= 80 ? 0 : S;
                M  += HE >= 80 ? 1 : 0;

                System.Threading.Thread.Sleep(500);
                w();
            }
        }
Example #13
0
 private static void Overthrow()
 {
     Console.WriteLine("The animals have risen against you, nowhere is safe. It’s time to leave " +
                       "\n     you run down the street as you hear the animals chanting " +
                       "\n   \"four legs good, two legs bad\" over and over……there is no returning, everything is lost.");
     Console.ReadKey();
     Console.Clear();
     MainMenu();
 }
Example #14
0
 private static void FeedChickens()
 {
     Console.WriteLine("The chickens have been fed and return to their Coops. " +
                       "\n   They silently judge your life decisions and talk about you when you're gone " +
                       "\n   They know your weaknesses and fears, they are the enemy of the proud and the " +
                       "\n   harbingers of judgment....do not underestimate them");
     Console.ReadKey();
     Console.Clear();
     MainMenu();
 }
Example #15
0
        public static string ReadLine(string text, ConsoleColor color = ConsoleColor.White, bool clear = true)
        {
            if (clear)
            {
                C.Clear();
            }
            C.ForegroundColor = color;
            C.Write(text);
            var result = C.ReadLine();

            return(result);
        }
Example #16
0
        /// <summary>
        /// Start of the Assignment class.
        /// </summary>
        public void Main()
        {
            while (true)
            {
                Show();
                var input = Console.ReadLine();
                Console.Clear();
                switch (input)
                {
                case "1":
                    Rename();
                    break;

                case "2":
                    Calculate();
                    break;

                case "3":
                    ShowName();
                    break;

                case "4":
                    Console.Clear();
                    // Splits an input string into an array of substrings.
                    string[] _string = Regex.Split("Are you ready captain?", string.Empty);
                    foreach (string s in _string)
                    {
                        Console.Write(s);
                        Thread.Sleep(100);
                    }
                    Console.Write("\n\n");
                    Thread.Sleep(500);
                    Console.Write("ATTACK!");
                    Thread.Sleep(500);
                    StartBunny();
                    break;

                case "5":
                    Environment.Exit(0);
                    break;

                default:
                    Console.WriteLine("This isn't a valid option");
                    Return();
                    Console.Write("You suck at destroying worlds!");
                    Thread.Sleep(200);
                    continue;
                }

                break;
            }
        }
Example #17
0
        public void BadActsMenu()
        {
            Console.Clear();
            const string menuitem  = "================Bad Acts================";
            const string menuitem1 = "Drinking";
            const string menuitem2 = "Drugs";

            Console.WriteLine("{0," + (Console.WindowWidth / 2 + menuitem.Length / 2) + "}", menuitem);
            Console.WriteLine("{0," + (Console.WindowWidth / 2 + menuitem1.Length / 2) + "}", menuitem1);
            Console.WriteLine("{0," + (Console.WindowWidth / 2 + menuitem2.Length / 2) + "}", menuitem2);
            Console.WriteLine("What are you going to do?");
            BadPick();
        }
Example #18
0
 /// <summary>
 /// Shows the menu screen.
 /// </summary>
 private void Show()
 {
     Console.Clear();
     Console.Write("Welcome captain! Pick an action:\n" +
                   "___________________________________________________________________________________________________________\n\n" +
                   "1. Name the captain\n" +
                   "2. Calculator\n" +
                   "3. Show captains name\n" +
                   "4. Attack worlds\n" +
                   "5. Close!\n" +
                   "___________________________________________________________________________________________________________\n\n" +
                   "");
 }
Example #19
0
        public void Render(object target)
        {
            var result = target as TraderKindDefs;
            if (result == null)
                throw new ArgumentException($"The specified item is not of type {nameof(TraderKindDefs)}", nameof(target));

            CONS.Clear();
            CONS.WriteLine(nameof(TraderKindDefs));

            foreach (var item in result.Items)
            {
                WriteItemToConsole(item);
            }
        }
Example #20
0
            private static void PrintNumbers()
            {
                Console.Clear();
                Console.WriteLine("Print Numberz Game!");
                Console.Write("Type a number: ");
                int result  = int.Parse(Console.ReadLine());
                int counter = 1;

                while (counter <= result)
                {
                    Console.Write(counter);
                    Console.Write("-");
                    counter++;
                }
                Console.ReadLine();
            }
Example #21
0
 static void Intro()
 {
     C.WriteLine("#################################");
     C.WriteLine("           Console2048           ");
     C.WriteLine("#################################");
     C.WriteLine();
     C.WriteLine("Use the arrow keys to move around");
     C.WriteLine("        Type 'H' for help        ");
     C.WriteLine();
     C.WriteLine(" Combine numbers to get to 2048! ");
     C.WriteLine();
     C.WriteLine("#################################");
     C.WriteLine();
     C.Write("Press any key to start...");
     C.ReadKey();
     C.Clear();
 }
Example #22
0
        public static void Run()
        {
            Running = true;

            SysCon.Clear();
            Console = NeonConsole.GetConsole("win", 121, 31);
            OpenScreen(new TitleScreen());

            while (Running)
            {
                Update();
                Draw();
                Console.Draw();

                //Thread.Sleep(1000 / 60);
            }
        }
Example #23
0
        static void Main(string[] args)
        {
            IEnumerable <IOperation> operationList = LoadOperations();

            try
            {
                do
                {
                    SConsole.Clear();
                    showCalcDescription(operationList);
                    showDialog(operationList);
                }while (SConsole.ReadKey().Key != ConsoleKey.Escape);
            }
            catch (Exception ex)
            {
                SConsole.WriteLine(ex.Message);
                SConsole.ReadKey();
            }
        }
Example #24
0
 private static void DisplayMenuOptions()
 {
     Console.Clear();
     Console.WriteLine(" ___________________________________________________________ ");
     Console.WriteLine("|                                                           |");
     Console.WriteLine("| 1. Add or remove user data                                |");
     Console.WriteLine("| 2. Add or remove  mobilephone inventory data              |");
     Console.WriteLine("| 3. Add or remove  computer inventory data                 |");
     Console.WriteLine("| 4. Add or remove vehicle inventory data                   |");
     Console.WriteLine("| 5. Print all users                                        |");
     Console.WriteLine("| 6. Run requests on mobile inventory data                  |");
     Console.WriteLine("| 7. Run requests computer inventory data                   |");
     Console.WriteLine("| 8. Run requests on vehicle inventory data                 |");
     Console.WriteLine("| 9. Count number of batteries in inventory                 |");
     Console.WriteLine("| 10. Press this to generate random data for every inventory|");
     Console.WriteLine("|                                                           |");
     Console.WriteLine("|      Any number choice not within the given number        |");
     Console.WriteLine("|                options stops execution                    |");
     Console.WriteLine("|___________________________________________________________|");
 }
Example #25
0
        static void Main(string[] args)
        {
            //Test resource
            var             culture         = CultureInfo.CreateSpecificCulture("ru-ru");
            ResourceManager resourceManager = new ResourceManager("Fitness.ConsoleUI.Languages.Messages", typeof(Program).Assembly);

            C.WriteLine(resourceManager.GetString("Hello", culture));
            C.ReadKey();

            var            name           = ConsoleHelper.ParseString("Please Enter name");
            UserController userController = new UserController(name);

            if (userController.IsNewUser)
            {
                EnterNewUser(userController);
            }

            C.Clear();
            C.WriteLine(userController.CurrentUser);


            C.WriteLine(userController.CurrentUser);
            C.ReadKey();
        }
Example #26
0
        public static void Main()
        {
            BasicConsole.Clear();
            Console.InitDefault();

            // Wait for other system startup to occur
            Processes.SystemCalls.SleepThread(1000);
            
            MainConsole = new Consoles.AdvancedConsole();
            MainConsole.ScreenHeight = 7;
            MainConsole.LineLength = 55;
            MainConsole.ScreenStartLineOffset = 0;
            MainConsole.UpdateScreenCursor = false;

            StatusConsole = new Consoles.AdvancedConsole();
            StatusConsole.ScreenHeight = 7;
            StatusConsole.LineLength = 24;
            StatusConsole.ScreenStartLineOffset = 56;
            StatusConsole.UpdateScreenCursor = false;

            MainConsole.Clear();
            StatusConsole.Clear();

            bool StatusLine1 = true;

            Hardware.DeviceManager.AddDeviceAddedListener(DeviceManager_DeviceAdded, null);

            Processes.SystemCalls.SleepThread(500);
            Console.Default.ScreenHeight = 25 - 8;
            Console.Default.ScreenStartLine = 8;

            while (!Terminating)
            {
                try
                {
                    ((Consoles.AdvancedConsole)StatusConsole).DrawBottomBorder();
                    ((Consoles.AdvancedConsole)StatusConsole).DrawLeftBorder();
                    ((Consoles.AdvancedConsole)MainConsole).DrawBottomBorder();
            
                    StatusConsole.Clear();
                    if (StatusLine1)
                    {
                        StatusConsole.WriteLine("State: 1");
                    }
                    else
                    {
                        StatusConsole.WriteLine("State: 2");
                    }
                    StatusLine1 = !StatusLine1;

                    StatusConsole.Write("Processes: ");
                    StatusConsole.WriteLine_AsDecimal(ProcessManager.Processes.Count);

                    int ThreadCount = 0;
                    int SleptThreads = 0;
                    int IndefiniteSleptThreads = 0;
                    for (int i = 0; i < ProcessManager.Processes.Count; i++)
                    {
                        List threads = ((Process)ProcessManager.Processes[i]).Threads;
                        ThreadCount += threads.Count;
                        for (int j = 0; j < threads.Count; j++)
                        {
                            Thread thread = (Thread)threads[j];
                            if (thread.TimeToSleep == Thread.IndefiniteSleep)
                            {
                                IndefiniteSleptThreads++;
                                SleptThreads++;
                            }
                            else if (thread.TimeToSleep > 0)
                            {
                                SleptThreads++;
                            }
                        }
                    }
                    StatusConsole.Write("Threads: ");
                    StatusConsole.Write_AsDecimal(ThreadCount);
                    StatusConsole.Write(" / ");
                    StatusConsole.Write_AsDecimal(SleptThreads);
                    StatusConsole.Write(" / ");
                    StatusConsole.WriteLine_AsDecimal(IndefiniteSleptThreads);

                    StatusConsole.Write("Devices: ");
                    StatusConsole.WriteLine_AsDecimal(Hardware.DeviceManager.Devices.Count);
                    StatusConsole.Write("File Sys:");
                    for(int i = 0; i < FileSystemManager.FileSystemMappings.Count; i++)
                    {
                        FileSystemMapping mapping = (FileSystemMapping)FileSystemManager.FileSystemMappings[i];
                        StatusConsole.Write(" ");
                        StatusConsole.Write(mapping.Prefix);
                    }
                    StatusConsole.WriteLine();
                    StatusConsole.Write("USB Devices: ");
                    StatusConsole.WriteLine_AsDecimal(Hardware.USB.USBManager.Devices.Count);

                    unsafe
                    {
                        StatusConsole.Write("Heap: ");
                        //StatusConsole.Write_AsDecimal(Heap.GetTotalUsedMem());
                        //StatusConsole.Write(" / ");
                        //StatusConsole.Write_AsDecimal(Heap.GetTotalMem());
                        uint totalMem = Heap.GetTotalMem();
                        StatusConsole.Write_AsDecimal(Heap.GetTotalUsedMem() / (totalMem / 100));
                        StatusConsole.Write("% / ");
                        StatusConsole.Write_AsDecimal(totalMem / 1024);
                        StatusConsole.Write(" KiB");
                    }
                }
                catch
                {
                    MainConsole.ErrorColour();
                    MainConsole.WriteLine("Error updating the status console:");
                    if (ExceptionMethods.CurrentException != null)
                    {
                        MainConsole.WriteLine(ExceptionMethods.CurrentException.Message);
                    }
                    MainConsole.DefaultColour();
                }

                MainConsole.Update();
                StatusConsole.Update();

                Processes.SystemCalls.SleepThread(500);
            }
        }
Example #27
0
        public static void Main(string[] args)
        {
            var userList      = new List <User>();
            var vehicleList   = new List <VehicleItem>();
            var mobileList    = new List <MobilephoneTechnologyItem>();
            var computerList  = new List <ComputerTechnologyItem>();
            var choiceForMenu = 0;

            do
            {
                DisplayMenuOptions();
                Console.WriteLine("Your choice if you choose to accept it:");
                var inputTesting = int.TryParse(Console.ReadLine(), out choiceForMenu);
                if (!inputTesting)
                {
                    Console.WriteLine("Input is not an number please try again.");
                    choiceForMenu = 0;
                }
                else
                {
                    var choiceForSubMenu = 0;
                    switch (choiceForMenu)
                    {
                    case 1:
                    {
                        do
                        {
                            Console.Clear();
                            Console.WriteLine(" _______________________________________________________________________ ");
                            Console.WriteLine("|                                                                       |");
                            Console.WriteLine("| 1. Add an user to the existing user database.                         |");
                            Console.WriteLine("| 2. Delete an user by entering his ID.                                 |");
                            Console.WriteLine("|        [Optionally enter any value to exit to main menu]              |");
                            Console.WriteLine("|_______________________________________________________________________|");
                            int.TryParse(Console.ReadLine(), out choiceForSubMenu);
                            switch (choiceForSubMenu)
                            {
                            case 1:
                            {
                                userList.Add(new User().AddUser());
                                break;
                            }

                            case 2:
                            {
                                Console.WriteLine("Enter value of ID of user you wish to delete.");
                                var idInputed = int.Parse(Console.ReadLine());
                                foreach (var user in userList)
                                {
                                    if (user.IdUser == idInputed)
                                    {
                                        Console.WriteLine("Are you sure you want to delete:");
                                        user.PrintUserInfo();
                                        Console.WriteLine("Delete: y[es]/n[o]");
                                        if (Console.ReadKey().Key == ConsoleKey.Y)
                                        {
                                            userList.Remove(user);
                                        }
                                        break;
                                    }
                                }
                                Console.WriteLine("User not found.");
                                break;
                            }

                            default:
                            {
                                choiceForSubMenu = 0;
                                Console.WriteLine("Exiting sub-menu.");
                                break;
                            }
                            }
                        }while (choiceForSubMenu == 0);
                        break;
                    }

                    case 2:
                    {
                        do
                        {
                            Console.Clear();
                            Console.WriteLine(
                                " _______________________________________________________________________ ");
                            Console.WriteLine(
                                "|                                                                       |");
                            Console.WriteLine(
                                "| 1. Add an mobilephone to the existing mobilephone database.           |");
                            Console.WriteLine(
                                "| 2. Delete an mobilephone by entering Guid.                            |");
                            Console.WriteLine(
                                "|        [Optionally enter any value to exit to main menu]              |");
                            Console.WriteLine(
                                "|_______________________________________________________________________|");
                            int.TryParse(Console.ReadLine(), out choiceForSubMenu);
                            switch (choiceForSubMenu)
                            {
                            case 1:
                            {
                                mobileList.Add(new MobilephoneTechnologyItem().AddPhone(userList));
                                break;
                            }

                            case 2:
                            {
                                Console.WriteLine("Enter value of Guid [or unique start of guid] of mobilephone you wish to delete.");
                                var idInputed = Console.ReadLine();
                                foreach (var phone in mobileList)
                                {
                                    if (phone.IsGuid(idInputed))
                                    {
                                        Console.WriteLine("Are you sure you want to delete:");
                                        phone.PrintMobilephoneInfo();
                                        Console.WriteLine("Delete: y[es]/n[o]");
                                        if (Console.ReadKey().Key == ConsoleKey.Y)
                                        {
                                            mobileList.Remove(phone);
                                        }
                                        break;
                                    }
                                }

                                Console.WriteLine("Phone not found.");
                                break;
                            }

                            default:
                            {
                                choiceForSubMenu = 0;
                                break;
                            }
                            }
                        } while (choiceForSubMenu == 0);
                        break;
                    }

                    case 3:
                    {
                        do
                        {
                            Console.Clear();
                            Console.WriteLine(" _______________________________________________________________________ ");
                            Console.WriteLine("|                                                                       |");
                            Console.WriteLine("| 1. Add an computer to the existing computer database.                 |");
                            Console.WriteLine("| 2. Delete an computer by entering Guid.                               |");
                            Console.WriteLine("|        [Optionally enter any value to exit to main menu]              |");
                            Console.WriteLine("|_______________________________________________________________________|");
                            int.TryParse(Console.ReadLine(), out choiceForSubMenu);
                            switch (choiceForSubMenu)
                            {
                            case 1:
                            {
                                computerList.Add(new ComputerTechnologyItem().AddComputer());
                                break;
                            }

                            case 2:
                            {
                                Console.WriteLine("Enter value of Guid [or unique start of guid] of computer you wish to delete.");
                                var idInputed = Console.ReadLine();
                                foreach (var computer in computerList)
                                {
                                    if (computer.IsGuid(idInputed))
                                    {
                                        Console.WriteLine("Are you sure you want to delete:");
                                        computer.PrintComputerInfo();
                                        Console.WriteLine("Delete: y[es]/n[o]");
                                        if (Console.ReadKey().Key == ConsoleKey.Y)
                                        {
                                            computerList.Remove(computer);
                                        }
                                        break;
                                    }
                                }

                                Console.WriteLine("Computer not found.");
                                break;
                            }

                            default:
                            {
                                choiceForSubMenu = 0;
                                break;
                            }
                            }
                        } while (choiceForSubMenu == 0);
                        break;
                    }

                    case 4:
                    {
                        do
                        {
                            Console.Clear();
                            Console.WriteLine(
                                " _______________________________________________________________________ ");
                            Console.WriteLine(
                                "|                                                                       |");
                            Console.WriteLine(
                                "| 1. Add an vehicle to the existing vehicle database.                   |");
                            Console.WriteLine(
                                "| 2. Delete an vehicle by entering Guid.                                |");
                            Console.WriteLine(
                                "|        [Optionally enter any value to exit to main menu]              |");
                            Console.WriteLine(
                                "|_______________________________________________________________________|");
                            int.TryParse(Console.ReadLine(), out choiceForSubMenu);
                            switch (choiceForSubMenu)
                            {
                            case 1:
                            {
                                vehicleList.Add(new VehicleItem().AddVehicle(userList));
                                break;
                            }

                            case 2:
                            {
                                Console.WriteLine("Enter value of Guid [or unique start of guid] of vehicle you wish to delete.");
                                var idInputed = Console.ReadLine();
                                foreach (var vehicle in vehicleList)
                                {
                                    if (vehicle.IsGuid(idInputed))
                                    {
                                        Console.WriteLine("Are you sure you want to delete:");
                                        vehicle.PrintVehicleInfo();
                                        Console.WriteLine("Delete: y[es]/n[o]");
                                        if (Console.ReadKey().Key == ConsoleKey.Y)
                                        {
                                            vehicleList.Remove(vehicle);
                                        }
                                        break;
                                    }
                                }
                                Console.WriteLine("Computer not found.");
                                break;
                            }

                            default:
                            {
                                choiceForSubMenu = 0;
                                break;
                            }
                            }
                        } while (choiceForSubMenu == 0);
                        break;
                    }

                    case 5:
                    {
                        PrintUserList(userList);
                        Console.WriteLine("Press any button to return to main menu.");
                        Console.ReadKey();
                        break;
                    }

                    case 6:
                    {
                        do
                        {
                            Console.Clear();
                            Console.WriteLine(" __________________________________________________________________ ");
                            Console.WriteLine("|                                                                  |");
                            Console.WriteLine("| 1.Print all mobile inventory                                     |");
                            Console.WriteLine("| 2.Print depending on serial entered                              |");
                            Console.WriteLine("| 3.Print all phones by entered manufacturer                       |");
                            Console.WriteLine("| 4.Print users who's phones warranty is expiring in year entered  |");
                            Console.WriteLine("| 5.Current estimated value of phone. [Enter serial]               |");
                            Console.WriteLine("|   [Optionally enter any value to return to main menu]            |");
                            Console.WriteLine("|__________________________________________________________________|");
                            int.TryParse(Console.ReadLine(), out choiceForSubMenu);
                            switch (choiceForSubMenu)
                            {
                            case 1:
                            {
                                Console.Clear();
                                PrintMobilephoneList(mobileList);
                                Console.WriteLine("Press any button to return to sub menu.");
                                Console.ReadKey();
                                break;
                            }

                            case 2:
                            {
                                var printedSomething = 0;
                                Console.WriteLine("Please enter part or whole guid:");
                                var enteredSerialNumber = Console.ReadLine();
                                Console.Clear();
                                foreach (var phone in mobileList)
                                {
                                    if (phone.IsGuid(enteredSerialNumber))
                                    {
                                        phone.PrintMobilephoneInfo();
                                        printedSomething++;
                                    }
                                }
                                if (printedSomething == 0)
                                {
                                    Console.Write("Phone not found. ");
                                }
                                Console.WriteLine("Press any button to return to sub menu.");
                                Console.ReadKey();
                                break;
                            }

                            case 3:
                            {
                                var printedSomething = 0;
                                Console.WriteLine("Please enter manufacturer:");
                                var manufacturerString = Console.ReadLine();
                                Console.Clear();
                                foreach (var phone in mobileList)
                                {
                                    if (phone.IsManufacturer(manufacturerString))
                                    {
                                        printedSomething++;
                                        phone.PrintMobilephoneInfo();
                                    }
                                }
                                if (printedSomething == 0)
                                {
                                    Console.Write("Phone not found. ");
                                }
                                Console.WriteLine("Press any button to return to sub menu.");
                                Console.ReadKey();
                                break;
                            }

                            case 4:
                            {
                                Console.WriteLine("Enter year you're interested in:");
                                var yearEntered = int.Parse(Console.ReadLine());
                                Console.Clear();
                                foreach (var phone in mobileList)
                                {
                                    if (phone.IsWarrantyEndYear(yearEntered))
                                    {
                                        phone.MobilephoneUser.PrintUserInfo();
                                        Console.WriteLine("~ Phone number of user:"******"Press any button to return to sub menu.");
                                Console.ReadKey();
                                break;
                            }

                            case 5:
                            {
                                var printedSomething = 0;
                                Console.WriteLine("Please enter part or whole guid:");
                                var enteredSerialNumber = Console.ReadLine();
                                Console.Clear();
                                foreach (var phone in mobileList)
                                {
                                    if (phone.IsGuid(enteredSerialNumber))
                                    {
                                        Console.WriteLine("Estimated value is: " + phone.GetRealValue());
                                        Console.WriteLine("Difference since new is: " + (phone.PriceOnPurchase - phone.GetRealValue()));
                                        phone.PrintMobilephoneInfo();
                                        printedSomething++;
                                    }
                                }
                                if (printedSomething == 0)
                                {
                                    Console.Write("Phone not found. ");
                                }
                                Console.WriteLine("Press any button to return to sub menu.");
                                Console.ReadKey();
                                break;
                            }

                            default:
                            {
                                choiceForSubMenu = 99;
                                break;
                            }
                            }
                        } while (choiceForSubMenu != 99);
                        break;
                    }

                    case 7:
                    {
                        do
                        {
                            Console.Clear();
                            Console.WriteLine(" __________________________________________________________________ ");
                            Console.WriteLine("|                                                                  |");
                            Console.WriteLine("| 1.Print all computer inventory                                   |");
                            Console.WriteLine("| 2.Print depending on serial entered                              |");
                            Console.WriteLine("| 3.Print all computers by entered operating system                |");
                            Console.WriteLine("| 4.Print all computers who's warranty is expiring in year entered |");
                            Console.WriteLine("| 5.Current estimated value of computer. [Enter serial]            |");
                            Console.WriteLine("|   [Optionally enter any value to return to main menu]            |");
                            Console.WriteLine("|__________________________________________________________________|");
                            int.TryParse(Console.ReadLine(), out choiceForSubMenu);
                            switch (choiceForSubMenu)
                            {
                            case 1:
                            {
                                Console.Clear();
                                PrintComputerList(computerList);
                                Console.WriteLine("Press any button to return to sub menu.");
                                Console.ReadKey();
                                break;
                            }

                            case 2:
                            {
                                var printedSomething = 0;
                                Console.WriteLine("Please enter part or whole guid:");
                                var enteredSerialNumber = Console.ReadLine();
                                Console.Clear();
                                foreach (var computer in computerList)
                                {
                                    if (computer.IsGuid(enteredSerialNumber))
                                    {
                                        computer.PrintComputerInfo();
                                        printedSomething++;
                                    }
                                }
                                if (printedSomething == 0)
                                {
                                    Console.Write("Computer not found. ");
                                }
                                Console.WriteLine("Press any button to return to sub menu.");
                                Console.ReadKey();
                                break;
                            }

                            case 3:
                            {
                                var printedSomething = 0;
                                Console.WriteLine("Please enter operating system:");
                                var operatingSystemEntered = Console.ReadLine();
                                Console.Clear();
                                foreach (var computer in computerList)
                                {
                                    if (computer.IsOperatingSystem(operatingSystemEntered))
                                    {
                                        printedSomething++;
                                        computer.PrintComputerInfo();
                                    }
                                }
                                if (printedSomething == 0)
                                {
                                    Console.Write("Computer not found. ");
                                }
                                Console.WriteLine("Press any button to return to sub menu.");
                                Console.ReadKey();
                                break;
                            }

                            case 4:
                            {
                                Console.WriteLine("Enter year you're interested in:");
                                var yearEntered = int.Parse(Console.ReadLine());
                                Console.Clear();
                                foreach (var computer in computerList)
                                {
                                    if (computer.IsWarrantyEndYear(yearEntered))
                                    {
                                        computer.PrintComputerInfo();
                                        Console.WriteLine();
                                    }
                                }
                                Console.WriteLine("Press any button to return to sub menu.");
                                Console.ReadKey();
                                break;
                            }

                            case 5:
                            {
                                var printedSomething = 0;
                                Console.WriteLine("Please enter part or whole guid:");
                                var enteredSerialNumber = Console.ReadLine();
                                Console.Clear();
                                foreach (var computer in computerList)
                                {
                                    if (computer.IsGuid(enteredSerialNumber))
                                    {
                                        Console.WriteLine("Estimated value is: " + computer.GetRealValue());
                                        Console.WriteLine("Difference since new is: " + (computer.PriceOnPurchase - computer.GetRealValue()));
                                        computer.PrintComputerInfo();
                                        printedSomething++;
                                    }
                                }
                                if (printedSomething == 0)
                                {
                                    Console.Write("Computer not found. ");
                                }
                                Console.WriteLine("Press any button to return to sub menu.");
                                Console.ReadKey();
                                break;
                            }

                            default:
                            {
                                choiceForSubMenu = 99;
                                break;
                            }
                            }
                        } while (choiceForSubMenu != 99);

                        break;
                    }

                    case 8:
                    {
                        do
                        {
                            Console.Clear();
                            Console.WriteLine(" __________________________________________________________________ ");
                            Console.WriteLine("|                                                                  |");
                            Console.WriteLine("| 1.Print all vehicle inventory                                    |");
                            Console.WriteLine("| 2.Print depending on serial entered                              |");
                            Console.WriteLine("| 3.Print all vehicles who's warranty is expiring next month       |");
                            Console.WriteLine("| 4.Current estimated value of vehicle. [Enter serial]             |");
                            Console.WriteLine("|   [Optionally enter any value to return to main menu]            |");
                            Console.WriteLine("|__________________________________________________________________|");
                            int.TryParse(Console.ReadLine(), out choiceForSubMenu);
                            switch (choiceForSubMenu)
                            {
                            case 1:
                            {
                                Console.Clear();
                                PrintVehicleList(vehicleList);
                                Console.WriteLine("Press any button to return to sub menu.");
                                Console.ReadKey();
                                break;
                            }

                            case 2:
                            {
                                var printedSomething = 0;
                                Console.WriteLine("Please enter part or whole guid:");
                                var enteredSerialNumber = Console.ReadLine();
                                Console.Clear();
                                foreach (var vehicle in vehicleList)
                                {
                                    if (vehicle.IsGuid(enteredSerialNumber))
                                    {
                                        vehicle.PrintVehicleInfo();
                                        printedSomething++;
                                    }
                                }
                                if (printedSomething == 0)
                                {
                                    Console.Write("Vehicle not found. ");
                                }
                                Console.WriteLine("Press any button to return to sub menu.");
                                Console.ReadKey();
                                break;
                            }

                            case 3:
                            {
                                var printedSomething = 0;
                                Console.Clear();
                                foreach (var vehicle in vehicleList)
                                {
                                    if (vehicle.IsRegistrationWithinMonth())
                                    {
                                        vehicle.PrintVehicleInfo();
                                        printedSomething++;
                                    }
                                }
                                if (printedSomething == 0)
                                {
                                    Console.Write("No vehicles registrations expire next month.");
                                }
                                Console.WriteLine("Press any button to return to sub menu");
                                Console.ReadKey();
                                break;
                            }

                            case 4:
                            {
                                var printedSomething = 0;
                                Console.WriteLine("Please enter part or whole guid:");
                                var enteredSerialNumber = Console.ReadLine();
                                Console.Clear();
                                foreach (var vehicle in vehicleList)
                                {
                                    if (vehicle.IsGuid(enteredSerialNumber))
                                    {
                                        Console.WriteLine("Estimated value is: " + vehicle.GetRealValue());
                                        Console.WriteLine("Difference since new is: " + (vehicle.PriceOnPurchase - vehicle.GetRealValue()));
                                        vehicle.PrintVehicleInfo();
                                        printedSomething++;
                                    }
                                }
                                if (printedSomething == 0)
                                {
                                    Console.Write("Vehicle not found. ");
                                }
                                Console.WriteLine("Press any button to return to sub menu.");
                                Console.ReadKey();
                                break;
                            }

                            default:
                            {
                                choiceForSubMenu = 99;
                                break;
                            }
                            }
                        } while (choiceForSubMenu != 99);

                        break;
                    }

                    case 9:
                    {
                        Console.Clear();
                        var numberOfBatteries = 0;
                        foreach (var computer in computerList)
                        {
                            if (computer.BatteryBoolean)
                            {
                                numberOfBatteries++;
                            }
                        }
                        foreach (var phone in mobileList)
                        {
                            if (phone.BatteryBoolean)
                            {
                                numberOfBatteries++;
                            }
                        }
                        Console.WriteLine("Number of batteries in the company is: " + numberOfBatteries);
                        Console.WriteLine("Press any button to return to main menu.");
                        Console.ReadKey();
                        break;
                    }

                    case 10:
                    {
                        userList     = new List <User>(new User().FillWithDummyUsers());
                        vehicleList  = new List <VehicleItem>(new VehicleItem().FillVehiclesWithDummyValues(userList));
                        mobileList   = new List <MobilephoneTechnologyItem>(new MobilephoneTechnologyItem().FillMobilesphonesWithDummyItems(userList));
                        computerList = new List <ComputerTechnologyItem>(new ComputerTechnologyItem().FillComputerTechnologyWithDummyItems());
                        PrintUserList(userList);
                        Console.WriteLine("Press any button to view vehicle list.");
                        Console.ReadKey();
                        Console.Clear();
                        PrintVehicleList(vehicleList);
                        Console.WriteLine("Press any button to view mobile list.");
                        Console.ReadKey();
                        Console.Clear();
                        PrintMobilephoneList(mobileList);
                        Console.WriteLine("Press any button to view computer list.");
                        Console.ReadKey();
                        Console.Clear();
                        PrintComputerList(computerList);
                        Console.WriteLine("Press any key to return to main menu");
                        Console.ReadKey();
                        break;
                    }

                    default:
                    {
                        Console.WriteLine("Execution stopping.");
                        choiceForMenu = 99;
                        break;
                    }
                    }
                }
            } while (choiceForMenu != 99);
        }
Example #28
0
        public void StandardIOComplies()
        {
            #region In, Out, Error
            // Assert.
            Assert.Same(Base.In, Facade.In);
            Assert.Same(Base.Out, Facade.Out);
            Assert.Same(Base.Error, Facade.Error);
            #endregion

            #region SetIn, SetOut, SetError
            // Base/Facade
            // Act.
            Base.SetIn(TestIn);
            Base.SetOut(TestOut);
            Base.SetError(TestError);

            // Assert.
            Assert.Same(Base.In, Facade.In);
            Assert.Same(Base.Out, Facade.Out);
            Assert.Same(Base.Error, Facade.Error);

            // Teardown.
            Base.SetIn(BaseIn);
            Base.SetOut(BaseOut);
            Base.SetError(BaseError);

            // Facade/Base
            // Act.
            Facade.SetIn(TestIn);
            Facade.SetOut(TestOut);
            Facade.SetError(TestError);

            // Assert.
            Assert.Same(Facade.In, Base.In);
            Assert.Same(Facade.Out, Base.Out);
            Assert.Same(Facade.Error, Base.Error);
            #endregion

            #region WriteLine, ReadLine, Clear
            // Base/Facade
            // Act.
            Base.WriteLine("Hello, world!");

            // Assert.
            TestStream.Position = 0;
            Assert.Equal("Hello, world!", Facade.ReadLine());

            // Act.
            Base.Clear();

            // Assert.
            Assert.Equal(string.Empty, Facade.ReadLine());

            // Facade/Base
            // Act.
            Facade.WriteLine("Hello, world!");

            // Assert.
            TestStream.Position = 0;
            Assert.Equal("Hello, world!", Base.ReadLine());

            // Act.
            Facade.Clear();

            // Assert.
            Assert.Equal(string.Empty, Base.ReadLine());
            #endregion

            #region Teardown
            // Act.
            Base.SetIn(BaseIn);
            Base.SetOut(BaseOut);
            Base.SetError(BaseError);

            // Assert.
            Assert.Same(BaseIn, Facade.In);
            Assert.Same(BaseOut, Facade.Out);
            Assert.Same(BaseError, Facade.Error);
            #endregion
        }
Example #29
0
        static void Main(string[] args)
        {
            var loader = new ProductLoader();

            try
            {
                Console.WindowWidth = 150;
                bool terminate = false;
                while (terminate == false)
                {
                    Console.Clear();
                    Console.WriteLine("Welcome to VirtusFit application.");
                    Console.WriteLine("----------------------------------");
                    Console.WriteLine("Available options:");
                    Console.WriteLine("1. Display full list of products.");
                    Console.WriteLine("2. Search for products.");
                    Console.WriteLine("3. Add new product.");
                    Console.WriteLine("4. Edit product.");
                    Console.WriteLine("5. Prepare diet plan.");
                    Console.WriteLine("6. Close application.");
                    Console.WriteLine("----------------------------------");
                    Console.WriteLine("Please choose your action:");
                    string userChoice = (Console.ReadLine());
                    if (userChoice != "1" && userChoice != "2" && userChoice != "3" && userChoice != "4" && userChoice != "5" && userChoice != "6")
                    {
                        Console.WriteLine("Incorrect input");
                        Console.WriteLine();
                        Console.WriteLine("Press any key to continue.");
                        Console.ReadKey();
                    }
                    else
                    {
                        int _userChoice = int.Parse(userChoice);
                        switch (_userChoice)
                        {
                        case 1:
                            DisplayProductList.DisplayList(ListOfProducts);
                            break;

                        case 2:
                            SearchProductConsoleInterface newSearch = new SearchProductConsoleInterface();
                            newSearch.SearchProductInterface(ListOfProducts);
                            break;

                        case 3:
                            AddProductFromConsole();
                            break;

                        case 4:
                            DisplayProductList.DisplayList(ListOfProducts);
                            EditDataFromConsoleInterface testInterface = new EditDataFromConsoleInterface();
                            testInterface.EditProductInterface();
                            break;

                        case 5:
                            Console.WriteLine("There will be a super cool diet planner");
                            Console.WriteLine();
                            Console.WriteLine("Press any key to continue.");
                            Console.ReadKey();
                            break;

                        case 6:
                            terminate = true;
                            break;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"An error occured: {e.Message} \nPress any key.");
                Console.ReadKey();
            }
        }
Example #30
0
        static public int RunBotSession(
            byte[] kalmitElmApp,
            Func <byte[], byte[]> getFileFromHashSHA256,
            string processStoreDirectory,
            Action <string> logEntry,
            Action <LogEntry.ProcessBotEventReport> logProcessBotEventReport,
            string botConfiguration)
        {
            var botId = Kalmit.CommonConversion.StringBase16FromByteArray(Kalmit.CommonConversion.HashSHA256(kalmitElmApp));

            var botSessionClock = System.Diagnostics.Stopwatch.StartNew();

            /*
             * Implementat store and process based on Kalmit Web Host
             * from https://github.com/Viir/Kalmit/blob/640078f59bea3fa2ba1af43372933cff304b8c94/implement/PersistentProcess/PersistentProcess.WebHost/Startup.cs
             * */

            var process = new Kalmit.PersistentProcess.PersistentProcessWithHistoryOnFileFromElm019Code(
                new EmptyProcessStore(), kalmitElmApp);

            var processStore = new ProcessStoreInFileDirectory(
                processStoreDirectory,
                () =>
            {
                var time          = DateTimeOffset.UtcNow;
                var directoryName = time.ToString("yyyy-MM-dd");
                return(System.IO.Path.Combine(directoryName, directoryName + "T" + time.ToString("HH") + ".composition.jsonl"));
            });

            (DateTimeOffset time, string statusMessage, ImmutableList <InterfaceToBot.BotRequest>)? lastBotStep = null;

            ImmutableList <InterfaceToBot.BotRequest> remainingBotRequests = null;

            bool pauseBot = false;

            (string text, DateTimeOffset time)lastConsoleUpdate = (null, DateTimeOffset.MinValue);

            void updatePauseContinue()
            {
                if (DotNetConsole.KeyAvailable)
                {
                    var inputKey = DotNetConsole.ReadKey();

                    if (inputKey.Key == ConsoleKey.Enter)
                    {
                        pauseBot = false;
                        displayStatusInConsole();
                    }
                }

                if (Windows.IsKeyDown(Windows.VK_CONTROL) && Windows.IsKeyDown(Windows.VK_MENU))
                {
                    pauseBot = true;
                    displayStatusInConsole();
                }
            }

            void displayStatusInConsole()
            {
                var textToDisplay = string.Join("\n", textLinesToDisplayInConsole());

                var time = DateTimeOffset.UtcNow;

                if (lastConsoleUpdate.text == textToDisplay && time < lastConsoleUpdate.time + TimeSpan.FromSeconds(1))
                {
                    return;
                }

                DotNetConsole.Clear();
                DotNetConsole.WriteLine(textToDisplay);

                lastConsoleUpdate = (textToDisplay, time);
            }

            IEnumerable <string> textLinesToDisplayInConsole()
            {
                //  TODO: Add display bot configuration.

                yield return
                    ("Bot " + UserInterface.BotIdDisplayText(botId) +
                     (pauseBot ?
                      " is paused. Press the enter key to continue." :
                      " is running. Press CTRL + ALT keys to pause the bot."));

                if (!lastBotStep.HasValue)
                {
                    yield break;
                }

                var lastBotStepAgeInSeconds = (int)((DateTimeOffset.UtcNow - lastBotStep.Value.time).TotalSeconds);

                yield return("Last bot event was " + lastBotStepAgeInSeconds + " seconds ago at " + lastBotStep.Value.time.ToString("HH-mm-ss.fff") + ".");

                yield return("Status message from bot:\n");

                yield return(lastBotStep.Value.statusMessage);

                yield return("");
            }

            var createVolatileHostAttempts = 0;

            var volatileHosts = new ConcurrentDictionary <string, Kalmit.CSharpScriptContext>();

            InterfaceToBot.Result <InterfaceToBot.TaskResult.RunInVolatileHostError, InterfaceToBot.TaskResult.RunInVolatileHostComplete> ExecuteRequestToRunInVolatileHost(
                InterfaceToBot.Task.RunInVolatileHost runInVolatileHost)
            {
                if (!volatileHosts.TryGetValue(runInVolatileHost.hostId, out var volatileHost))
                {
                    return(new InterfaceToBot.Result <InterfaceToBot.TaskResult.RunInVolatileHostError, InterfaceToBot.TaskResult.RunInVolatileHostComplete>
                    {
                        err = new InterfaceToBot.TaskResult.RunInVolatileHostError
                        {
                            hostNotFound = new object(),
                        }
                    });
                }

                var stopwatch = System.Diagnostics.Stopwatch.StartNew();

                var fromHostResult = volatileHost.RunScript(runInVolatileHost.script);

                stopwatch.Stop();

                return(new InterfaceToBot.Result <InterfaceToBot.TaskResult.RunInVolatileHostError, InterfaceToBot.TaskResult.RunInVolatileHostComplete>
                {
                    ok = new InterfaceToBot.TaskResult.RunInVolatileHostComplete
                    {
                        exceptionToString = fromHostResult.Exception?.ToString(),
                        returnValueToString = fromHostResult.ReturnValue?.ToString(),
                        durationInMilliseconds = stopwatch.ElapsedMilliseconds,
                    }
                });
            }

            void processBotEvent(InterfaceToBot.BotEvent botEvent)
            {
                var       eventTime             = DateTimeOffset.UtcNow;
                Exception processEventException = null;
                string    serializedEvent       = null;
                string    serializedResponse    = null;
                string    compositionRecordHash = null;

                try
                {
                    var botEventAtTime = new InterfaceToBot.BotEventAtTime
                    {
                        timeInMilliseconds = botSessionClock.ElapsedMilliseconds,
                        @event             = botEvent,
                    };

                    serializedEvent = SerializeToJsonForBot(botEventAtTime);

                    var processEventResult = process.ProcessEvents(
                        new[]
                    {
                        serializedEvent
                    });

                    compositionRecordHash = Kalmit.CommonConversion.StringBase16FromByteArray(processEventResult.Item2.serializedCompositionRecordHash);

                    processStore.AppendSerializedCompositionRecord(processEventResult.Item2.serializedCompositionRecord);

                    serializedResponse = processEventResult.responses.Single();

                    var botResponse = Newtonsoft.Json.JsonConvert.DeserializeObject <InterfaceToBot.BotResponse>(serializedResponse);

                    if (botResponse.decodeEventSuccess == null)
                    {
                        throw new Exception("Bot reported decode error: " + botResponse.decodeEventError);
                    }

                    var botRequests =
                        botResponse.decodeEventSuccess.botRequests.ToImmutableList();

                    var setStatusMessageRequests =
                        botRequests
                        .Where(request => request.setStatusMessage != null)
                        .ToImmutableList();

                    var statusMessage =
                        setStatusMessageRequests?.Select(request => request.setStatusMessage)?.LastOrDefault() ?? lastBotStep?.statusMessage;

                    lastBotStep = (eventTime, statusMessage, botRequests);

                    var stepRemainingRequests =
                        botRequests
                        .Except(setStatusMessageRequests);

                    remainingBotRequests =
                        (remainingBotRequests ?? ImmutableList <InterfaceToBot.BotRequest> .Empty)
                        .AddRange(stepRemainingRequests);
                }
                catch (Exception exception)
                {
                    processEventException = exception;
                }

                logProcessBotEventReport(new LogEntry.ProcessBotEventReport
                {
                    time                  = eventTime,
                    exception             = processEventException,
                    serializedResponse    = serializedResponse,
                    compositionRecordHash = compositionRecordHash,
                });

                if (processEventException != null)
                {
                    throw new Exception("Failed to process bot event.", processEventException);
                }

                displayStatusInConsole();
            }

            //  TODO: Get the bot requests from the `init` function.

            processBotEvent(new InterfaceToBot.BotEvent {
                setBotConfiguration = botConfiguration ?? ""
            });

            while (true)
            {
                displayStatusInConsole();

                updatePauseContinue();

                System.Threading.Thread.Sleep(111);

                if (pauseBot)
                {
                    continue;
                }

                var botStepTime = DateTimeOffset.UtcNow;

                var lastBotStepAgeMilli =
                    botStepTime.ToUnixTimeMilliseconds() - lastBotStep?.time.ToUnixTimeMilliseconds();

                var finishSessionRequest =
                    remainingBotRequests
                    ?.FirstOrDefault(request => request.finishSession != null);

                if (finishSessionRequest != null)
                {
                    logEntry("Bot has finished.");
                    return(0);
                }

                var botRequestToExecute =
                    remainingBotRequests
                    ?.FirstOrDefault();

                if (botRequestToExecute == null)
                {
                    if (!(lastBotStepAgeMilli < 10_000))
                    {
                        processBotEvent(new InterfaceToBot.BotEvent
                        {
                            setSessionTimeLimitInMilliseconds = 0,
                        });
                    }

                    continue;
                }

                var requestTask = botRequestToExecute.startTask;

                if (requestTask?.task?.createVolatileHost != null)
                {
                    var volatileHostId = System.Threading.Interlocked.Increment(ref createVolatileHostAttempts).ToString();

                    volatileHosts[volatileHostId] = new Kalmit.CSharpScriptContext(getFileFromHashSHA256);

                    processBotEvent(new InterfaceToBot.BotEvent
                    {
                        taskComplete = new InterfaceToBot.ResultFromTaskWithId
                        {
                            taskId     = requestTask?.taskId,
                            taskResult = new InterfaceToBot.TaskResult
                            {
                                createVolatileHostResponse = new InterfaceToBot.Result <object, InterfaceToBot.TaskResult.CreateVolatileHostComplete>
                                {
                                    ok = new InterfaceToBot.TaskResult.CreateVolatileHostComplete
                                    {
                                        hostId = volatileHostId,
                                    },
                                },
                            },
                        },
                    });
                }

                if (requestTask?.task?.releaseVolatileHost != null)
                {
                    volatileHosts.TryRemove(requestTask?.task?.releaseVolatileHost.hostId, out var volatileHost);
                }

                if (requestTask?.task?.runInVolatileHost != null)
                {
                    var result = ExecuteRequestToRunInVolatileHost(requestTask?.task?.runInVolatileHost);

                    processBotEvent(new InterfaceToBot.BotEvent
                    {
                        taskComplete = new InterfaceToBot.ResultFromTaskWithId
                        {
                            taskId     = requestTask?.taskId,
                            taskResult = new InterfaceToBot.TaskResult
                            {
                                runInVolatileHostResponse = result,
                            },
                        }
                    });
                }

                if (requestTask?.task?.delay != null)
                {
                    var delayStopwatch = System.Diagnostics.Stopwatch.StartNew();

                    while (true)
                    {
                        var remainingWaitTime = requestTask.task.delay.milliseconds - delayStopwatch.ElapsedMilliseconds;

                        if (remainingWaitTime <= 0)
                        {
                            break;
                        }

                        System.Threading.Thread.Sleep((int)Math.Min(100, remainingWaitTime));

                        updatePauseContinue();
                        displayStatusInConsole();
                    }

                    processBotEvent(new InterfaceToBot.BotEvent
                    {
                        taskComplete = new InterfaceToBot.ResultFromTaskWithId
                        {
                            taskId     = requestTask?.taskId,
                            taskResult = new InterfaceToBot.TaskResult
                            {
                                completeWithoutResult = new object(),
                            },
                        }
                    });
                }

                remainingBotRequests = remainingBotRequests.Remove(botRequestToExecute);
            }
        }
Example #31
0
        static public int RunBotSession(
            byte[] kalmitElmApp,
            Func <byte[], byte[]> getFileFromHashSHA256,
            string processStoreDirectory,
            Action <string> logEntry,
            Action <LogEntry.ProcessBotEventReport> logProcessBotEventReport,
            string botConfiguration,
            string sessionId,
            string botSource)
        {
            var botId = Kalmit.CommonConversion.StringBase16FromByteArray(Kalmit.CommonConversion.HashSHA256(kalmitElmApp));

            var botSessionClock = System.Diagnostics.Stopwatch.StartNew();

            /*
             * Implementat store and process based on Kalmit Web Host
             * from https://github.com/Viir/Kalmit/blob/640078f59bea3fa2ba1af43372933cff304b8c94/implement/PersistentProcess/PersistentProcess.WebHost/Startup.cs
             * */

            var process = new Kalmit.PersistentProcess.PersistentProcessWithHistoryOnFileFromElm019Code(
                new EmptyProcessStore(), kalmitElmApp);

            var processStore = new ProcessStoreInFileDirectory(
                processStoreDirectory,
                () =>
            {
                var time          = DateTimeOffset.UtcNow;
                var directoryName = time.ToString("yyyy-MM-dd");
                return(System.IO.Path.Combine(directoryName, directoryName + "T" + time.ToString("HH") + ".composition.jsonl"));
            });

            (DateTimeOffset time, string statusDescriptionForOperator, InterfaceToBot.BotResponse.DecodeEventSuccessStructure response)? lastBotStep = null;

            var botSessionTaskCancellationToken = new System.Threading.CancellationTokenSource();
            var activeBotTasks = new ConcurrentDictionary <InterfaceToBot.StartTask, System.Threading.Tasks.Task>();

            bool pauseBot = false;

            (string text, DateTimeOffset time)lastConsoleUpdate = (null, DateTimeOffset.MinValue);

            void updatePauseContinue()
            {
                if (DotNetConsole.KeyAvailable)
                {
                    var inputKey = DotNetConsole.ReadKey();

                    if (inputKey.Key == ConsoleKey.Enter)
                    {
                        pauseBot = false;
                        displayStatusInConsole();
                    }
                }

                if (Windows.IsKeyDown(Windows.VK_CONTROL) && Windows.IsKeyDown(Windows.VK_MENU))
                {
                    pauseBot = true;
                    displayStatusInConsole();
                }
            }

            void cleanUpBotTasksAndPropagateExceptions()
            {
                foreach (var(request, engineTask) in activeBotTasks.ToList())
                {
                    if (engineTask.Exception != null)
                    {
                        throw new Exception("Bot task '" + request.taskId + "' has failed with exception", engineTask.Exception);
                    }

                    if (engineTask.IsCompleted)
                    {
                        activeBotTasks.TryRemove(request, out var _);
                    }
                }
            }

            var displayLock = new object();

            void displayStatusInConsole()
            {
                lock (displayLock)
                {
                    cleanUpBotTasksAndPropagateExceptions();

                    var textToDisplay = string.Join("\n", textLinesToDisplayInConsole());

                    var time = DateTimeOffset.UtcNow;

                    if (lastConsoleUpdate.text == textToDisplay && time < lastConsoleUpdate.time + TimeSpan.FromSeconds(1))
                    {
                        return;
                    }

                    DotNetConsole.Clear();
                    DotNetConsole.WriteLine(textToDisplay);

                    lastConsoleUpdate = (textToDisplay, time);
                }
            }

            IEnumerable <string> textLinesToDisplayInConsole()
            {
                //  TODO: Add display bot configuration.

                yield return
                    ("Bot " + UserInterface.BotIdDisplayText(botId) +
                     " in session '" + sessionId + "'" +
                     (pauseBot ?
                      " is paused. Press the enter key to continue." :
                      " is running. Press CTRL + ALT keys to pause the bot."));

                if (!lastBotStep.HasValue)
                {
                    yield break;
                }

                var lastBotStepAgeInSeconds = (int)((DateTimeOffset.UtcNow - lastBotStep.Value.time).TotalSeconds);

                yield return
                    ("Last bot event was " + lastBotStepAgeInSeconds + " seconds ago at " + lastBotStep.Value.time.ToString("HH-mm-ss.fff") + ". " +
                     "There are " + activeBotTasks.Count + " tasks in progress.");

                yield return("Status message from bot:\n");

                yield return(lastBotStep.Value.statusDescriptionForOperator);

                yield return("");
            }

            long lastRequestToReactorTimeInSeconds = 0;

            async System.Threading.Tasks.Task requestToReactor(RequestToReactorUseBotStruct useBot)
            {
                lastRequestToReactorTimeInSeconds = (long)botSessionClock.Elapsed.TotalSeconds;

                var toReactorStruct = new RequestToReactorStruct {
                    UseBot = useBot
                };

                var serializedToReactorStruct = Newtonsoft.Json.JsonConvert.SerializeObject(toReactorStruct);

                var reactorClient = new System.Net.Http.HttpClient();

                reactorClient.DefaultRequestHeaders.UserAgent.Add(
                    new System.Net.Http.Headers.ProductInfoHeaderValue(new System.Net.Http.Headers.ProductHeaderValue("windows-console", BotEngine.AppVersionId)));

                var content = new System.Net.Http.ByteArrayContent(System.Text.Encoding.UTF8.GetBytes(serializedToReactorStruct));

                var response = await reactorClient.PostAsync("https://reactor.botengine.org/api/", content);

                var responseString = await response.Content.ReadAsStringAsync();
            }

            void fireAndForgetReportToReactor(RequestToReactorUseBotStruct report)
            {
                lastRequestToReactorTimeInSeconds = (long)botSessionClock.Elapsed.TotalSeconds;

                System.Threading.Tasks.Task.Run(() =>
                {
                    try
                    {
                        requestToReactor(report).Wait();
                    }
                    catch { }
                });
            }

            fireAndForgetReportToReactor(new RequestToReactorUseBotStruct
            {
                StartSession = new RequestToReactorUseBotStruct.StartSessionStruct
                {
                    botId = botId, sessionId = sessionId, botSource = BotSourceIsPublic(botSource) ? botSource : null
                }
            });

            var createVolatileHostAttempts = 0;

            var volatileHosts = new ConcurrentDictionary <string, Kalmit.CSharpScriptContext>();

            InterfaceToBot.Result <InterfaceToBot.TaskResult.RunInVolatileHostError, InterfaceToBot.TaskResult.RunInVolatileHostComplete> ExecuteRequestToRunInVolatileHost(
                InterfaceToBot.Task.RunInVolatileHostStructure runInVolatileHost)
            {
                if (!volatileHosts.TryGetValue(runInVolatileHost.hostId, out var volatileHost))
                {
                    return(new InterfaceToBot.Result <InterfaceToBot.TaskResult.RunInVolatileHostError, InterfaceToBot.TaskResult.RunInVolatileHostComplete>
                    {
                        Err = new InterfaceToBot.TaskResult.RunInVolatileHostError
                        {
                            hostNotFound = new object(),
                        }
                    });
                }

                var stopwatch = System.Diagnostics.Stopwatch.StartNew();

                var fromHostResult = volatileHost.RunScript(runInVolatileHost.script);

                stopwatch.Stop();

                return(new InterfaceToBot.Result <InterfaceToBot.TaskResult.RunInVolatileHostError, InterfaceToBot.TaskResult.RunInVolatileHostComplete>
                {
                    Ok = new InterfaceToBot.TaskResult.RunInVolatileHostComplete
                    {
                        exceptionToString = fromHostResult.Exception?.ToString(),
                        returnValueToString = fromHostResult.ReturnValue?.ToString(),
                        durationInMilliseconds = stopwatch.ElapsedMilliseconds,
                    }
                });
            }

            void processBotEvent(InterfaceToBot.BotEvent botEvent)
            {
                var       eventTime             = DateTimeOffset.UtcNow;
                Exception processEventException = null;
                string    serializedEvent       = null;
                string    serializedResponse    = null;
                string    compositionRecordHash = null;

                try
                {
                    serializedEvent = SerializeToJsonForBot(botEvent);

                    var processEventResult = process.ProcessEvents(
                        new[]
                    {
                        serializedEvent
                    });

                    compositionRecordHash = Kalmit.CommonConversion.StringBase16FromByteArray(processEventResult.Item2.serializedCompositionRecordHash);

                    processStore.AppendSerializedCompositionRecord(processEventResult.Item2.serializedCompositionRecord);

                    serializedResponse = processEventResult.responses.Single();

                    var botResponse = Newtonsoft.Json.JsonConvert.DeserializeObject <InterfaceToBot.BotResponse>(serializedResponse);

                    if (botResponse.DecodeEventSuccess == null)
                    {
                        throw new Exception("Bot reported decode error: " + botResponse.DecodeEventError);
                    }

                    var statusDescriptionForOperator =
                        botResponse.DecodeEventSuccess?.ContinueSession?.statusDescriptionForOperator ??
                        botResponse.DecodeEventSuccess?.FinishSession?.statusDescriptionForOperator;

                    lastBotStep = (eventTime, statusDescriptionForOperator, botResponse.DecodeEventSuccess);

                    foreach (var startTask in botResponse.DecodeEventSuccess?.ContinueSession?.startTasks ?? Array.Empty <InterfaceToBot.StartTask>())
                    {
                        var engineTask = System.Threading.Tasks.Task.Run(() => startTaskAndProcessEvent(startTask), botSessionTaskCancellationToken.Token);

                        activeBotTasks[startTask] = engineTask;
                    }
                }
                catch (Exception exception)
                {
                    processEventException = exception;
                }

                logProcessBotEventReport(new LogEntry.ProcessBotEventReport
                {
                    time                  = eventTime,
                    exception             = processEventException,
                    serializedResponse    = serializedResponse,
                    compositionRecordHash = compositionRecordHash,
                });

                if (processEventException != null)
                {
                    throw new Exception("Failed to process bot event.", processEventException);
                }

                displayStatusInConsole();
            }

            //  TODO: Get the bot requests from the `init` function.

            processBotEvent(new InterfaceToBot.BotEvent {
                SetBotConfiguration = botConfiguration ?? ""
            });

            while (true)
            {
                displayStatusInConsole();

                updatePauseContinue();

                var millisecondsToNextNotification =
                    (lastBotStep?.response?.ContinueSession?.notifyWhenArrivedAtTime?.timeInMilliseconds - botSessionClock.ElapsedMilliseconds) ?? 1000;

                System.Threading.Thread.Sleep((int)Math.Min(1000, Math.Max(10, millisecondsToNextNotification)));

                var lastRequestToReactorAgeInSeconds = (long)botSessionClock.Elapsed.TotalSeconds - lastRequestToReactorTimeInSeconds;

                if (30 <= lastRequestToReactorAgeInSeconds)
                {
                    fireAndForgetReportToReactor(new RequestToReactorUseBotStruct
                    {
                        ContinueSession = new RequestToReactorUseBotStruct.ContinueSessionStruct
                        {
                            sessionId = sessionId, statusDescriptionForOperator = lastBotStep?.statusDescriptionForOperator
                        }
                    });
                }

                if (pauseBot)
                {
                    continue;
                }

                var botStepTime = DateTimeOffset.UtcNow;

                var lastBotStepAgeMilli =
                    botStepTime.ToUnixTimeMilliseconds() - lastBotStep?.time.ToUnixTimeMilliseconds();

                if (lastBotStep?.response?.FinishSession != null)
                {
                    logEntry("Bot has finished.");
                    botSessionTaskCancellationToken.Cancel();
                    return(0);
                }

                if (lastBotStep?.response?.ContinueSession?.notifyWhenArrivedAtTime?.timeInMilliseconds <= botSessionClock.ElapsedMilliseconds ||
                    !(lastBotStepAgeMilli < 10_000))
                {
                    processBotEvent(new InterfaceToBot.BotEvent
                    {
                        ArrivedAtTime = new InterfaceToBot.TimeStructure {
                            timeInMilliseconds = botSessionClock.ElapsedMilliseconds
                        },
                    });
                }
            }

            void startTaskAndProcessEvent(InterfaceToBot.StartTask startTask)
            {
                var taskResult = performTask(startTask.task);

                processBotEvent(new InterfaceToBot.BotEvent
                {
                    TaskComplete = new InterfaceToBot.ResultFromTaskWithId
                    {
                        taskId     = startTask.taskId,
                        taskResult = taskResult,
                    },
                });
            }

            InterfaceToBot.TaskResult performTask(InterfaceToBot.Task task)
            {
                if (task?.CreateVolatileHost != null)
                {
                    var volatileHostId = System.Threading.Interlocked.Increment(ref createVolatileHostAttempts).ToString();

                    volatileHosts[volatileHostId] = new Kalmit.CSharpScriptContext(getFileFromHashSHA256);

                    return(new InterfaceToBot.TaskResult
                    {
                        CreateVolatileHostResponse = new InterfaceToBot.Result <object, InterfaceToBot.TaskResult.CreateVolatileHostComplete>
                        {
                            Ok = new InterfaceToBot.TaskResult.CreateVolatileHostComplete
                            {
                                hostId = volatileHostId,
                            },
                        },
                    });
                }

                if (task?.ReleaseVolatileHost != null)
                {
                    volatileHosts.TryRemove(task?.ReleaseVolatileHost.hostId, out var volatileHost);

                    return(new InterfaceToBot.TaskResult {
                        CompleteWithoutResult = new object()
                    });
                }

                if (task?.RunInVolatileHost != null)
                {
                    var result = ExecuteRequestToRunInVolatileHost(task?.RunInVolatileHost);

                    return(new InterfaceToBot.TaskResult
                    {
                        RunInVolatileHostResponse = result,
                    });
                }

                return(null);
            }
        }