public PackageProcessor(IActionExecutor actionExecutor, IConsoleWriter writer, INuGetProcess nugetProcess, RunContext runContext)
 {
     _actionExecutor = actionExecutor;
     _writer = writer;
     _nugetProcess = nugetProcess;
     _runContext = runContext;
 }
 public CommandLineRunner(IConsoleWriter writer, IPackageProcessor packageProcessor, IActionExecutor actionExecutor, RunContext runContext)
 {
     _writer = writer;
     _packageProcessor = packageProcessor;
     _actionExecutor = actionExecutor;
     _runContext = runContext;
 }
 public ConsoleJSLintProvider(Func<IJSLintContext> jsLintFactory, IFileSystemWrapper fileSystemWrapper, ISettingsRepository settingRepository, IConsoleWriter consoleWriter, IViewFactory viewFactory)
 {
     this.jsLintFactory = jsLintFactory;
     this.fileSystemWrapper = fileSystemWrapper;
     this.settingRepository = settingRepository;
     this.consoleWriter = consoleWriter;
     this.viewFactory = viewFactory;
 }
 /// <summary>
 /// A method which knows how exactly to render error messages.
 /// </summary>
 /// <param name="message">Message that needs to be printed.</param>
 /// <param name="consoleWriter">Console context for rendering the message.</param>
 public static void DisplayInputErrorMessage(string message, IConsoleWriter consoleWriter)
 {
     ClearConsoleLine(consoleWriter);
     Console.ForegroundColor = ConsoleColor.Red;
     consoleWriter.WriteLine(message);
     Console.ForegroundColor = ConsoleColor.Gray;
     Thread.Sleep(500);
     ClearConsoleLine(consoleWriter);
 }
Beispiel #5
0
        public TestService()
        {
            CommandLogWriter = new BasicConsoleWriter("command-log");
            RegisterConsoleWriter(CommandLogWriter);

            RegisterCommand(new EchoCommand());

            RegisterCommand(new LoggingCommand("ambig-foo"));
            RegisterCommand(new LoggingCommand("ambig-foobar"));
            RegisterCommand(new LoggingCommand("ambig-bar"));
        }
        static void Main(string[] args)
        {
            if (Array.Exists(args, s => s == "/debug") && Environment.UserInteractive)
            {
                Debugger.Break();
            }

            AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;

            LogManager.Adapter = Log4NetFactoryAdapter.Load();
            _logger = LogManager.GetLogger(typeof (Program));
            _logger.InfoFormat("Logging configured");

            Services.Config.EnableServiceMode();
            _writer = ConsoleWriter.Get<Program>();

            Config.ConsoleMode.Enabled = true;
            Config.ConsoleMode.CommandPromptText = "console";
            Config.ConsoleMode.HistorySize = 5;
            Config.ConsoleMode.AppName = "example_console";
            Config.ConsoleMode.OnBeginRunCommand += cmd => _writer.WriteLine(cmd.Dump());

            Config.ShowViewArgsCommand = true;
            Config.WriteRunTimeToConsole = true;
            //Config.DefaultCommand = typeof (RepeatConsoleCommand);
            Config.Help.GetCategoryDelegate = (name, type) =>
                {
                    if (name.EndsWith("-service"))
                    {
                        return " - service -";
                    }
                    if (type.Assembly == typeof (Program).Assembly)
                    {
                        return " - example -";
                    }
                    return "";
                };
            Config.Help.GetAddlHelpDelegate = (s, type) => new[] { type.FullName };

            Services.Config.Defaults.CommandLine = "ping /s=google.com /i=10";

            try
            {
                new Engine(new[]
                    {
                        typeof(Program).Assembly,
                        typeof(InstallServiceCommand).Assembly
                    }).Run(args);
            }
            catch (Exception e)
            {
                _writer.WriteLine(e.Dump());
            }
        }
Beispiel #7
0
        public static void Main(string[] args)
        {
            string message = "Hello World";

            try
            {
                var whereToWriteMessage = ConfigurationManager.AppSettings["WriteMessageTo"];
                Enum.TryParse <WhereToWrite>(whereToWriteMessage, out var parsedValue);

                IConsoleWriter _consoleWriter = Factory.Create <ConsoleWriter>();
                WriteMessage(_consoleWriter, message);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error Occurred while Writing Message: {ex.Message}");
            }
        }
Beispiel #8
0
        public KeyHandler(IConsole console,
                          IConsoleWriter writer,
                          IPromptProvider promptProvider,
                          IHistoryNavigator historyNavigator,
                          ICompletionNavigator completionNavigator,
                          ICompletionWriter completionWriter)
        {
            _console             = console;
            _writer              = writer;
            _promptProvider      = promptProvider;
            _historyNavigator    = historyNavigator;
            _completionNavigator = completionNavigator;
            _completionWriter    = completionWriter;
            AddHandler(_writer.MoveCursorLeft, Seqs.ControlB, Seqs.LeftArrow);
            AddHandler(_writer.MoveCursorRight, Seqs.ControlF, Seqs.RightArrow);

            AddHandler(_writer.MoveCursorHome, Seqs.ControlA, Seqs.Home);

            AddHandler(_writer.MoveCursorEnd, Seqs.ControlE, Seqs.End);

            AddHandler(Backspace, Seqs.ControlH, Seqs.Backspace);

            AddHandler(ClearScreen, Seqs.ControlL);

            AddHandler(PreviousHistory, Seqs.ControlP, Seqs.UpArrow);
            AddHandler(NextHistory, Seqs.ControlN, Seqs.DownArrow);

            AddHandler(BreakProcess, Seqs.ControlC);

            AddHandler(NextAutoComplete, Seqs.Tab);
            AddHandler(PrevAutoComplete, Seqs.ShiftTab);

            // Cmder specific features
            //AddHandler(TraverseUpDirectory, Seqs.ControlAltU);

            // Gnu Readline https://en.wikipedia.org/wiki/GNU_Readline
            //AddHandler(DeleteNextChar, Seqs.ControlD);

            //AddHandler(SearchHistoryUp, Seqs.ControlR);
            //AddHandler(SearchHistoryDown, Seqs.ControlS);

            // Undo
            //AddHandler(Undo, Seqs.ControlUnderscore, Seqs.ControlXControlU);
            //_handlers.Add(BuildKey(ConsoleKey.Underscore, Console.Control), Undo);
        }
        public GameContext(IPlayer player,
                           IConsoleWriter consoleWriter,
                           IConsoleReader consoleReader,
                           IDirective[] directives,
                           IRoom[] rooms,
                           ISpecialEventManager specialEventManager,
                           IRoomStateManager roomStateManager)
        {
            _player              = player;
            _consoleWriter       = consoleWriter;
            _consoleReader       = consoleReader;
            _directives          = directives;
            _rooms               = rooms;
            _specialEventManager = specialEventManager;
            _roomStateManager    = roomStateManager;

            _isGameOver = false;
        }
Beispiel #10
0
 public ColorConsoleWriter(IConsoleWriter writer, ConsoleColor backgroundColor, ConsoleColor foregroundColor)
 {
     if (writer == null)
     {
         throw new ArgumentNullException(nameof(writer));
     }
     if (!Enum.IsDefined(typeof(ConsoleColor), backgroundColor))
     {
         throw new ArgumentOutOfRangeException(nameof(backgroundColor));
     }
     if (!Enum.IsDefined(typeof(ConsoleColor), foregroundColor))
     {
         throw new ArgumentOutOfRangeException(nameof(foregroundColor));
     }
     _writer          = writer;
     _backgroundColor = backgroundColor;
     _foregroundColor = foregroundColor;
 }
Beispiel #11
0
        public TextSummaryOutputWriter(
            IConsoleWriter consoleWriter,
            IList <IValidationDescription> validationDescriptions)
        {
            this._consoleWriter             = consoleWriter;
            this._validationErrorsHistogram = new Dictionary <ValidationType, long>();
            this._systemValidationResults   = new List <IValidationResult>();

            this._systemValidationTypes = new HashSet <ValidationType>(validationDescriptions
                                                                       .Where(o => o.ValidationKind == ValidationKind.SystemValidation)
                                                                       .Select(o => o.ValidationType));

            this._validationTypeDescriptions = new Dictionary <ValidationType, string>();
            foreach (IValidationDescription validationDescription in validationDescriptions)
            {
                this._validationTypeDescriptions[validationDescription.ValidationType] = validationDescription.DisplayName;
            }
        }
        static void Main(string[] args)
        {
            ApplicationEnvironment env = PlatformServices.Default.Application;

            CommandLineApplication app = new CommandLineApplication()
            {
                Name     = "AttachDebuggerByPort",
                FullName = "Attach Debugger By Port"
            };

            app.ShowHelp();

            ServiceProvider serviceProvider = new ServiceCollection()
                                              .AddSingleton <IConsoleWriter, ConsoleWriter>()
                                              .AddSingleton <ILowerLevelOpertationsService, LowerLevelOpertationsService>()
                                              .AddSingleton <IApplicationManager, ApplicationManager>()
                                              .BuildServiceProvider();

            CommandOption helpOption = app.HelpOption("-?|-h|--help");

            app.VersionOption("--version", () => env.ApplicationVersion);

            CommandOption portOption   = app.Option("-p|--port", "Port", CommandOptionType.SingleValue);
            CommandOption filterOption = app.Option("-f|--filter", "VS instance filter", CommandOptionType.SingleValue);

            app.OnExecute(() =>
            {
                IConsoleWriter consoleWriter = serviceProvider.GetService <IConsoleWriter>();

                IApplicationManager applicationManager = serviceProvider.GetService <IApplicationManager>();

                if (!portOption.HasValue())
                {
                    consoleWriter.PrintPortNumberNotAcceptableError();
                    return(-1);
                }

                return(applicationManager.AttachDebugger(
                           portOption.Value().Split(",").ToList(),
                           filterOption.Value() ?? string.Empty));
            });

            int exitCode = app.Execute(args);
        }
Beispiel #13
0
        public LiteServerImpl(IKernel kernel, InternalConfiguration configuration)
        {
            if (kernel == null)
            {
                throw new ArgumentNullException(nameof(kernel));
            }

            _kernel        = kernel;
            _console       = kernel.Resolve <IConsoleWriter>();
            _configuration = configuration;

            Output("Starting");

            Execute(_configuration.OnStartup);

            _houseKeeping = new HouseKeeping(kernel, configuration, Output);

            Output("Started");
        }
Beispiel #14
0
        static void Main(string[] args)
        {
            data = new Dictionary <string, string>();

            InvocationHandlerManager invocationManager = new InvocationHandlerManager();

            invocationManager.OnMethodInvoked   += new MethodInvocationHandler(MethodCalled);
            invocationManager.OnPropertyInvoked += InvocationManager_OnPropertyInvoked;

            IConsoleWriter writer = Proxy.Get <IConsoleWriter>(invocationManager, typeof(IConsoleWriter));

            Proxy.SaveGeneratedProxies("SharpProxyContainer.dll");

            writer.Value = "Michael";

            writer.Write("Hello, {0}!");

            writer.Write("Hello, {0}!");
        }
Beispiel #15
0
 public NativeProjectsPluginGenerator(
     IConsoleWriter consoleWriter,
     IFileGenerator fileGenerator,
     IFileManipulator fileManipulator,
     IUserInputProvider userInputProvider,
     IVariableProvider variableProvider,
     IProjectInformation projectInformation,
     ITfsPaths tfsPaths,
     ITools tools)
 {
     _consoleWriter      = consoleWriter;
     _fileGenerator      = fileGenerator;
     _fileManipulator    = fileManipulator;
     _userInputProvider  = userInputProvider;
     _variableProvider   = variableProvider;
     _projectInformation = projectInformation;
     _tfsPaths           = tfsPaths;
     _tools = tools;
 }
Beispiel #16
0
        static void Main(string[] args)
        {
            // Задаем количество строк, которые будут выведены на экран.
            var count = 25;

            // Задаем задержку между выводом сообщений на консоль.
            var delay = TimeSpan.FromSeconds(1);

            // Создаем коллекцию из конкретных реализаций стратегии.
            // Обратите внимание, что мы используем тип IConsoleWriter,
            // что позволяет разместить в эту коллекцию любой класс,
            // который реализует данный интерфейс стратегии.
            var writers = new IConsoleWriter[]
            {
                new RedConsoleWriter(),
                new BlueConsoleWriter(),
                new GreenConsoleWriter()
            };

            // Простой цикл, чтобы вывести на консоль текст заданное количество раз.
            for (var i = 0; i < count; i++)
            {
                // Получаем индекс элемента из коллекции остатком от деления
                // текущего номера итерации на общее количество элементов в коллекции.
                var index = i % writers.Length;

                // Получаем конкретную реализацию стратегии.
                var writer = writers[index];

                // Подготавливаем случайный текст, который будет выведен на экран.
                var text = Guid.NewGuid().ToString();

                // Выводим текст конкретной реализацией стратегии.
                writer.WriteText(text);

                // Ждем заданный промежуток времени, чтобы выполнялось не слишком быстро.
                Thread.Sleep(delay);
            }

            // Ждем завершения.
            Console.ReadLine();
        }
        private static void Main(string[] args)
        {
            WindsorContainerWrapper containerWrapper = new WindsorContainerWrapper(new WindsorContainer(),
                                                                                   new MainAssemblyProvider(), new PluginRegistration());

            containerWrapper.RegistrationLogger = new ConsoleLogger();
            containerWrapper.Install();
            IWindsorContainer container = containerWrapper.WindsorContainer;

            do
            {
                Console.Write("Customer Key: ");
                Console.ReadLine();
                //ContextUtilities.ContextValidationString = Console.ReadLine();
                ICustomerInformation customerInformation = container.Resolve <ICustomerInformation>();
                IConsoleWriter       consoleWriter       = container.Resolve <IConsoleWriter>();

                consoleWriter.WriteCustomerInformation(customerInformation);
            } while (Console.ReadLine() != "exit".ToLower());
        }
Beispiel #18
0
        // OnExecute will be called every interval specified in IntervalBetweenExecution property
        public override void OnExecute(IConsoleWriter writer, TimeSpan elapsed)
        {
            // Generate random value
            double value = rnd.NextDouble();

            // Check value to succes margin
            if (value > successMargin)
            {
                // If error write a message and increment fail count
                writer.Error("Error from: {0} with value {1}", Name, value);
                Failures++;
            }
            else
            {
                // If success write a message and increment success count
                writer.Success("Success from: {0} with value {1}", Name, value);
                Successes++;
            }
            writer.NewLine();
        }
Beispiel #19
0
        private void WriteBatch(IList <LogEventInfo> batch, IConsoleWriter writer)
        {
            var settings = batch[0].Settings;

            if (settings.ColorsEnabled && consoleFeaturesDetector.AreColorsSupported)
            {
                if (!settings.ColorMapping.TryGetValue(batch[0].Event.Level, out var color))
                {
                    color = ConsoleColor.Gray;
                }

                using (writer.ChangeColor(color))
                {
                    WriteBatchInternal(batch, writer);
                }
            }
            else
            {
                WriteBatchInternal(batch, writer);
            }
        }
Beispiel #20
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ConsoleMio"/> class.
        /// Creates a new ConsoleMio helper using the provided writer and reader
        /// and invokes the <see cref="Setup"/> method
        /// </summary>
        /// <param name="writer">An <see cref="IConsoleWriter"/> implementation</param>
        /// <param name="reader">An <see cref="IConsoleReader"/> implementation</param>
        /// <param name="hombre">An <see cref="IConsoleHombre"/> implementation</param>
        /// <exception cref="ArgumentNullException">
        /// Throws an exception if some of the provided parameters is null
        /// </exception>
        public ConsoleMio(IConsoleWriter writer, IConsoleReader reader, IConsoleHombre hombre)
        {
            if (writer == null)
            {
                throw new ArgumentNullException(nameof(writer));
            }

            if (reader == null)
            {
                throw new ArgumentNullException(nameof(reader));
            }

            if (hombre == null)
            {
                throw new ArgumentNullException(nameof(hombre));
            }

            this.reader = reader;
            this.writer = writer;
            this.hombre = hombre;
        }
Beispiel #21
0
        static void WriteFolder(IConsoleWriter writer)
        {
            // Create support collection
            List <FileInfo> infos = new List <FileInfo>();

            // Read files and directories
            string[] files = Directory.GetFiles(actualFolder);
            string[] dirs  = Directory.GetDirectories(actualFolder);

            // Write each dir in collection
            infos.AddRange(dirs.Select(dir => new FileInfo(dir)));

            // Write each file in collection
            infos.AddRange(files.Select(file => new FileInfo(file)));

            // Sort collection
            infos.Sort(new FileInfoComparer());

            // Cicle every item
            foreach (FileInfo info in infos)
            {
                // Check if item is a directory
                bool isDirectory = info.Attributes.HasFlag(FileAttributes.Directory);

                // Write item in correct format
                if (isDirectory)
                {
                    writer.Warning(LineRenderer(info));
                }
                else
                {
                    writer.Text(LineRenderer(info));
                }

                // New line
                writer.NewLine();
            }
            // New line for separation
            writer.NewLine();
        }
Beispiel #22
0
        public static void Generate(
            CliDefinitionList cliDefinition,
            string outputPath,
            bool overwriteFiles,
            bool verbose,
            IConsoleWriter console)
        {
            ParsedDefinitionList parsedDefinitionSet;

            try
            {
                parsedDefinitionSet = ParsedDefinitionList.Parse(cliDefinition, console);
            }
            catch (Exception exc)
            {
                console.WriteError($"ERROR: Could not parse the definition.");
                console.WriteError(exc.Message);
                return;
            }

            try
            {
                var generator = new CliGenerator();
                generator.Generate(parsedDefinitionSet,
                                   new GeneratorSettings()
                {
                    OverwriteFiles = overwriteFiles,
                    Verbose        = verbose,
                    OutputPath     = outputPath
                },
                                   console);
            }
            catch (Exception exc)
            {
                console.WriteError($"ERROR: Could not generate command line classes.");
                console.WriteError(exc.Message);
                return;
            }
        }
Beispiel #23
0
        private static IGameWorld CreateWorld(IConsoleWriter consoleWriter)
        {
            var gameObjectLocator = new GameObjectLocator();

            var lineIntersectionResolver = new LianBarskyIntersectionResolver();
            var geometryMathService      = new GeometryMathService(lineIntersectionResolver);

            var serializedGameObjectDataProvider = new SerializedGameObjectDataProvider();
            var enemyData  = serializedGameObjectDataProvider.GetEnemyData();
            var playerData = serializedGameObjectDataProvider.GetPlayerData();
            var stoneData  = serializedGameObjectDataProvider.GetStoneData();
            var shellData  = serializedGameObjectDataProvider.GetShellData();

            var shellInputComponent   = new ShellInputComponent();
            var shellPhysicComponent  = new PhysicComponent(shellData.Speed);
            var shellLogicComponent   = new ShellLogicComponent();
            var shellGraphicComponent = new CharGraphicComponent(shellData.DisplayChar, consoleWriter);
            var shell = new GameObject(shellInputComponent, shellPhysicComponent,
                                       shellLogicComponent, shellGraphicComponent);

            shell.Width  = shellData.Width;
            shell.Height = shellData.Height;
            var fireCommand = new FireCommand(shell);

            var serializedGameObjectBuilders = new List <ISerializedGameObjectBuilder>()
            {
                new StoneBuilder(consoleWriter, stoneData),
                new PlayerBuilder(consoleWriter, geometryMathService, fireCommand, playerData),
                new EnemyBuilder(consoleWriter, gameObjectLocator, geometryMathService, fireCommand, enemyData),
                new WinPlatformBuilder(consoleWriter, gameObjectLocator, geometryMathService)
            };

            var gameObjectBuilder = new GameObjectBuilder(serializedGameObjectBuilders, gameObjectLocator);

            var worldProvider = new WorldProvider(gameObjectBuilder, geometryMathService, consoleWriter);
            var world         = worldProvider.GetWorld(1);

            return(world);
        }
Beispiel #24
0
        private static void Run(IDedoxConfig config)
        {
            IConsoleWriter writer = GetConsoleWriter(config);

            config.Writer = writer;

            writer.Debug("Verbose? " + config.Verbose);
            writer.Debug("Output dir? " + config.OutputDirectory);
            writer.Debug("Levenshtein? " + config.LevenshteinLimit);
            writer.Debug("Metrics? " + config.Metrics);
            writer.Debug();

            var metrics = new DedoxMetrics();

            var inputFiles = config.GetInputFiles();

            if (inputFiles.Any())
            {
                foreach (var inputFile in config.GetInputFiles())
                {
                    ProcessInputFile(inputFile, config, metrics);
                }
            }
            else
            {
                var sampleOutput = new Dedoxifier(config, metrics).Run(GetSampleProgram());
                Console.WriteLine(sampleOutput);
            }

            if (config.Metrics)
            {
                // Always write to console, even in non-verbose mode.
                Console.WriteLine("Code elements (all): " + metrics.AllCodeElements);
                Console.WriteLine("Code elements (included): " + metrics.CodeElements);
                Console.WriteLine("Code elements (documented): " + metrics.CodeElementsWithDocumentation);
                Console.WriteLine("Code elements (generated): " + metrics.CodeElementsWithGeneratedDocumentation);
            }
        }
        public static void RunTaskWithSpinner(IConsoleWriter writer, string message, Action action)
        {
            _c = '/';
            var bgw = new BackgroundWorker();

            bgw.RunWorkerCompleted += Bgw_RunWorkerCompleted;
            bgw.DoWork             += delegate
            {
                action?.Invoke();
            };
            IsRunning = true;

            bgw.RunWorkerAsync();

            while (IsRunning)
            {
                switch (_c)
                {
                case '/':
                    _c = '-';
                    break;

                case '-':
                    _c = '\\';
                    break;

                case '\\':
                    _c = '|';
                    break;

                case '|':
                    _c = '/';
                    break;
                }
                writer.Write($"\r{message}{_c}");
                System.Threading.Thread.Sleep(100);
            }
        }
Beispiel #26
0
        static void WriteMenu(IConsoleWriter writer)
        {
            // Clear console and write the static part of menu
            writer.Clear();
            writer.Info("Use number to select an option").NewLine().NewLine();
            writer.Text("01 - Create Console").NewLine();
            writer.Text("02 - Reset").NewLine();
            writer.Text("03 - Quit").NewLine();
            writer.NewLine();

            // Cicle through console and write a menu item for each
            int index = 4;

            foreach (IConsole console in ConsoleAsync.EnumerateConsoles())
            {
                if (console.Name != systemConsoleName)
                {
                    writer.Text("{0:00} - Delete console '{1}'", index++, console.Name).NewLine();
                }
            }

            writer.NewLine().NewLine();
        }
        public GiveMeDirective(IConsoleWriter consoleWriter,
                               IEnumerable <IBarItem> barItems,
                               IEnumerable <IBasementItem> basementItems,
                               IEnumerable <ICellItem> cellItems,
                               IEnumerable <ICorridorItem> corridorItems,
                               IEnumerable <IGardenItem> gardenItems,
                               IEnumerable <IGardenShedItem> gardenShedItems,
                               IEnumerable <ILoungeItem> loungeItems,
                               IEnumerable <IStairsItem> stairsItems,
                               IEnumerable <IItem> otherItems)
        {
            _consoleWriter = consoleWriter;
            _allItems      = new List <IItem>();

            _allItems.AddRange(barItems);
            _allItems.AddRange(basementItems);
            _allItems.AddRange(cellItems);
            _allItems.AddRange(corridorItems);
            _allItems.AddRange(gardenItems);
            _allItems.AddRange(gardenShedItems);
            _allItems.AddRange(loungeItems);
            _allItems.AddRange(stairsItems);
            _allItems.AddRange(otherItems);
        }
Beispiel #28
0
        public static bool FireWeapon(this Player thisPlayer, Player otherPlayer, IConsoleWriter consoleWriter)
        {
            if (!thisPlayer.IsVictor)
            {
                consoleWriter.ClearScreen();

                PrintEnemyBattlefield(otherPlayer, consoleWriter);
                var coordinates = consoleWriter.ReadCoordinates();

                var avatar = otherPlayer.Battlefield[coordinates.PosX, coordinates.PosY];
                if (string.Equals(avatar, Constants.OCEAN_AVATAR) ||
                    string.Equals(avatar, Constants.DEBRIS) ||
                    string.Equals(avatar, Constants.HIT_ALREADY))
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"{thisPlayer.Name} : It's a Miss.");
                    Console.ResetColor();
                    otherPlayer.MaskedBattlefield[coordinates.PosX, coordinates.PosY] = Constants.HIT_ALREADY;
                }
                else
                {
                    otherPlayer.Battlefield[coordinates.PosX, coordinates.PosY]       = Constants.DEBRIS;
                    otherPlayer.MaskedBattlefield[coordinates.PosX, coordinates.PosY] = Constants.DEBRIS;
                    otherPlayer.BattlefieldAnalyzer[avatar] -= 1;
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine($"{thisPlayer.Name} : It's a Hit!");
                    Console.ResetColor();
                }
                var gameOn = AnalyzeBattlefield(otherPlayer);

                thisPlayer.IsVictor = gameOn ? false : true;
                Thread.Sleep(1000);
                return(gameOn);
            }
            return(false);
        }
Beispiel #29
0
        public HelpWriter([NotNull] IConsoleWriter consoleWriter)
        {
            if (consoleWriter == null)
            {
                throw new ArgumentNullException(nameof(consoleWriter));
            }
            _consoleWriter = consoleWriter;
            _consoleInputToPreferenceConverter = new ConsoleInputToPreferenceConverter();

            try
            {
                int width = Console.WindowWidth;
                _width = width - 20;
                if (_width < 20)
                {
                    _width = 20;
                }
            }
            catch (Exception)
            {
                // probably not actually running in a console window
                _width = 50;
            }
        }
 public NuGetProcess(IConsoleWriter writer)
 {
     _writer = writer;
 }
Beispiel #31
0
 public void WriteToConsole(IConsoleWriter writer)
 {
     writer.WriteString(this);
 }
 public ConsoleFormatter(IConsoleWriter consoleWriter)
 {
     _consoleWriter = consoleWriter;
 }
Beispiel #33
0
 public UserStatus(IConsoleWriter writer)
 {
     this.writer = writer;
 }
Beispiel #34
0
 public TimeKeeper(IConsoleWriter consoleWriter)
 {
     _consoleWriter = consoleWriter;
     _measurements  = new List <TimeMeasurements>();
 }
Beispiel #35
0
 public LookDirective(IConsoleWriter consoleWriter)
 {
     _consoleWriter = consoleWriter;
 }
        public ConsoleWriterActor()
        {
            _writer = new ConsoleWriter();

            this.Initialize();
        }
 public Scope(IConsoleWriter consoleWriter)
 {
     _consoleWriter = consoleWriter;
     _consoleWriter.Indent(1);
 }
Beispiel #38
0
        protected void RegisterConsoleWriter(IConsoleWriter writer)
        {
            if (writer == null)
                throw new ArgumentNullException("writer");

            writer.LineWritten += ProxyLineWritten;

            IConsoleWriter oldWriter;

            using (ConsoleWriterMapLock.UpgradeableRead())
            {
                if (ConsoleWriterMap.ContainsKey(writer.Name) && (writer.Name == "normal" || writer.Name == "error"))
                    throw new ArgumentException("Cannot replace the normal or error console writers.", "writer");

                using (ConsoleWriterMapLock.Write())
                {
                    oldWriter = ConsoleWriterMap.GetOrDefault(writer.Name);
                    ConsoleWriterMap[writer.Name] = writer;
                }
            }

            if (oldWriter != null)
                oldWriter.LineWritten -= ProxyLineWritten;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ConsoleRenderer"/> class.
 /// </summary>
 /// <param name="consoleWriter">Concrete console context.</param>
 public ConsoleRenderer(IConsoleWriter consoleWriter)
 {
     this.consoleWriter = consoleWriter;
 }
Beispiel #40
0
 public AttributeWriter(IConsoleWriter _console)
 {
     console = _console;
 }
 public ActionExecutor(IConsoleWriter writer, RunContext runContext)
 {
     _writer = writer;
     _runContext = runContext;
 }
Beispiel #42
0
 public void BeginExecutePipeline()
 {
     _writer = _writerProvider.ConsoleWriter;
     sb = new StringBuilder();
 }
 public void InitConsole(IConsoleWriter writer)
 {
     mConsoleWriter = writer;
 }
        /// <summary>
        /// Clears the exact line the cursor is.
        /// </summary>
        /// <param name="consoleWriter">Console context.</param>
        private static void ClearConsoleLine(IConsoleWriter consoleWriter)
        {
            var currentLine = 1;
            if (Console.CursorTop < 2)
            {
                currentLine = Console.CursorTop;
            }
            else
            {
                currentLine = Console.CursorTop - 1;
            }

            Console.SetCursorPosition(0, currentLine);
            consoleWriter.Write(new string(' ', Console.WindowWidth));
            Console.SetCursorPosition(0, currentLine);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ConsoleInputHandler"/> class.
 /// </summary>
 /// <param name="consoleWriter">Console context for writing.</param>
 /// <param name="consoleReader">Console context for reading.</param>
 public ConsoleInputHandler(IConsoleWriter consoleWriter, IConsoleReader consoleReader)
 {
     this.consoleWriter = consoleWriter;
     this.consoleReader = consoleReader;
 }
 public TextWriter(IConsoleWriter consoleWriter)
 {
     _consoleWriter = consoleWriter;
 }
 public ConsoleProxy()
 {
     this.writer = new ConsoleWriter();
 }
Beispiel #48
0
 public CompletionWriter(IConsoleWriter consoleWriter)
 {
     _consoleWriter = consoleWriter;
 }
 public CheckoutBootStrap(IEnumerable<string> cartData, IEnumerable<string> productCatalogData, IConsoleWriter consoleWriter)
 {
     _cartData = cartData;
     _productCatalogData = productCatalogData;
     _consoleWriter = consoleWriter;
 }
Beispiel #50
0
 public PluginsCommand(IConsoleWriter consoleWriter, IPluginLoader pluginLoader)
 {
     _consoleWriter = consoleWriter;
     _pluginLoader  = pluginLoader;
 }
 public PricingConsole(IBasketBuilder basketBuilder, IConsoleWriter consoleWriter)
 {
     _basketBuilder = basketBuilder;
     _consoleWriter = consoleWriter;
 }
 public ProgramLoop(IMenu mainMenu, IConsoleWriter consoleWriter)
 {
     _menu          = mainMenu;
     _consoleWriter = consoleWriter;
 }
 public static void InitConsole(IConsoleWriter writer)
 {
     runner.InitConsole(writer);
 }
 public IdentifyCommand(IConsoleWriter consoleWriter, IFileTypeFinder fileTypeFinder, IFilePathExtractor filePathExtractor)
 {
     _consoleWriter     = consoleWriter;
     _fileTypeFinder    = fileTypeFinder;
     _filePathExtractor = filePathExtractor;
 }
 public LineWrittenEventArgs(string line, IConsoleWriter writer)
 {
     Line = line;
     ConsoleWriter = writer;
 }