public void Handle(IConsoleAdapter console, IErrorAdapter error)
        {
            console.WrapLine("Default table format");
            console.WriteLine();
            var data1 = Enumerable.Range(0, 5)
                                  .Select(i => new {Text = string.Format("item {0}", i), Index = i});
            console.FormatTable(data1);
            console.WriteLine();

            var report = Enumerable.Range(0, 5)
                                 .Select(i => new {Text = string.Format("item {0}", i), Index = i})
                                 .AsReport(x => x.AddColumn(c => c.Index, d => d.Heading("Just The Index"))
                                                 .AddColumn(c => string.Format("{0} miles", c.Index*2),
                                                            d => d.Heading("Index in miles")));
            console.WriteLine();
            console.WrapLine("Report with custom headings");
            console.WriteLine();
            console.FormatTable(report);
            console.WriteLine();

            var report2 = Enumerable.Range(0, 5)
                                 .Select(i => new {Text = string.Format("item {0}", i), Index = i})
                                 .AsReport(x => x.AddColumn(c => c.Index, d => d.Heading("Fixed Width Index (12 wide)")
                                                                                .Width(12))
                                                 .AddColumn(c => string.Format("{0} miles", c.Index*2),
                                                            d => d.Heading("Index in miles")));
            console.WriteLine();
            console.WrapLine("Report with fixed width column");
            console.WriteLine();
            console.FormatTable(report2);
        }
        public bool ValidateDatabaseParameters(IConsoleAdapter adapter)
        {
            var serverSpecified = Server != null;
            var databaseSpecified = Database != null;
            var userSpecified = User != null;
            var passwordSpecified = Password != null;

            if ((serverSpecified && !databaseSpecified)
                || (!serverSpecified && databaseSpecified))
            {
                adapter.WrapLine("Server name and database name must be specified together.");
                return false;
            }

            if ((userSpecified && !passwordSpecified)
                || (!userSpecified && passwordSpecified))
            {
                adapter.WrapLine("User name and password must be specified together.");
                return false;
            }

            if (userSpecified && !serverSpecified)
            {
                adapter.WrapLine("User name and password cannot be specified unless a database is specified.");
                return false;
            }
            return true;
        }
        private static bool ConvertInput(InputItem item, IConsoleAdapter consoleOut, out object value, string input)
        {
            if (item.ReadInfo != null && item.ReadInfo.Options.Any())
                return SelectOption(input, item.ReadInfo.Options, consoleOut, out value);

            return ConvertString(input, item.Type, consoleOut, out value);
        }
        private static bool ConvertString(string input, Type type, IConsoleAdapter consoleOut, out object result)
        {
            try
            {
                if (input != null && type == input.GetType())
                {
                    result = input;
                    return true;
                }

                var conversion = typeof(Convert).GetMethods()
                    .FirstOrDefault(m => m.ReturnType == type
                                         && m.GetParameters().Length == 1
                                         && m.GetParameters()[0].ParameterType == typeof(string));
                if (conversion != null)
                {
                    result = MethodInvoker.Invoke(conversion, null, new object[] { input });
                    return true;
                }

                result = null;
            }
            catch (Exception e)
            {
                result = null;
                consoleOut.WrapLine(e.Message);
            }
            return false;
        }
Exemple #5
0
 public RunSampleArgs(LanguageData language, string sample, ParseTree parsedSample, IConsoleAdapter console = null)
 {
     Language     = language;
     Sample       = sample;
     ParsedSample = parsedSample;
     Console      = console;
 }
 public static void Describe(CommandLineInterpreterConfiguration config, IConsoleAdapter console, string applicationName, CommandExecutionMode executionMode, IOptionNameHelpAdorner adorner = null)
 {
     if (config.DefaultCommand != null && executionMode == CommandExecutionMode.CommandLine)
         AddDefaultCommandText(console, config.DefaultCommand, applicationName, adorner);
     else
         AddCommandListText(console, config, adorner, executionMode);
 }
Exemple #7
0
        public void Handle(IConsoleAdapter console, IErrorAdapter error, IMapper mapper)
        {
            try
            {
                var ops  = new UserOperations("https://senlabltd.eu.auth0.com/api/v2/", ClientId, Secret, mapper);
                var user = ops.AddUser(Email, Password);
                console.WrapLine($"{user.UserId} created.".Cyan());
            }
            catch (AggregateException e)
            {
                error.WrapLine($"Unable to create user {Email} due to error:".Yellow());

                error.WrapLine(e.Message.Red());

                foreach (var exception in e.InnerExceptions)
                {
                    error.WrapLine(exception.Message.Red());
                }

                Environment.ExitCode = -100;
            }
            catch (Exception e)
            {
                error.WrapLine($"Unable to create user {Email} due to error:".Yellow());

                error.WrapLine(e.Message.Red());
                if (e.InnerException != null)
                {
                    error.WrapLine(e.InnerException.Message.Red());
                }

                Environment.ExitCode = -100;
            }
        }
        public void Handle(IConsoleAdapter console, IErrorAdapter error, Settings settings)
        {
            console.WrapLine("Exporting public key file".Green());
            console.WrapLine("The file will be in XML format".Green());

            string location = null;

            //user is prompted to specify a location until select a valid one - either option one or option two
            while (location == null)
            {
                console.WrapLine("Please Select a valid location to export the file to:".Yellow());
                console.WrapLine("      (1) Desktop".White());
                console.WrapLine("      (2) Documents".White());
                console.WrapLine("Enter number:".Yellow());
                var option = Console.ReadLine();

                location = GetLocation(option);

                if (location == null)
                {
                    console.WrapLine("Invalid Location, Please choose again".Red());
                }
            }

            XmlHandler.CreateFile(settings, location);
        }
        protected static void Run(FakeApplicationBase app, string[] args, IConsoleAdapter console,
            IErrorAdapter errorAdapter)
        {
            app.Console = console;
            app.Error = errorAdapter;
            app.Initialise();
            app.PostInitialise();

            var commandLineInterpreter = new CommandLineInterpreter(app.Config);

            ConfigureHelpHandler(app, commandLineInterpreter);

            string[] errors;
            var command = commandLineInterpreter.Interpret(args, out errors, false);
            if (command == null)
            {
                if (errors != null)
                {
                    foreach (var error in errors)
                    {
                        app.Error.WrapLine(error);
                    }
                    Environment.ExitCode = app.CommandLineErrorExitCode;
                    return;
                }

                app._helpHandler.Execute(app, null, app.Console, app.Injector.Value, CommandExecutionMode.CommandLine);
                return;
            }

            ExecuteCommand(app, command, CommandExecutionMode.CommandLine);
        }
Exemple #10
0
        public void Handle(IConsoleAdapter console, IErrorAdapter error)
        {
            if (string.IsNullOrEmpty(OutputPath))
            {
                error.WrapLine("Please specify an output path.".Red());
                Environment.ExitCode = 100;
                return;
            }

            _console = console;
            _error   = error;

            try
            {
                var doc = XDocument.Load(XmlFile);

                foreach (var element in doc.Root.Elements())
                {
                    Extract(element);
                }
            }
            catch (Exception e)
            {
                _error.WrapLine("Unable to process file due to error:".Red());
                _error.WrapLine(e.ToString().Red());
            }
        }
Exemple #11
0
        public void Handle(IConsoleAdapter console, IErrorAdapter error)
        {
            //Connect to the local, default instance of SQL Server.
            var srv = new Server(Server);

            ReportDatabases(console, srv);

            var db = srv.Databases.Enumerate().SingleOrDefault(d => d.Name == Database);

            if (db != null)
            {
                if (!Replace && !console.Confirm($"Drop {Database.Yellow()}?".Cyan()))
                {
                    error.WrapLine($"Database {Database.Yellow()} already exists. Specify -r to replace it.".Red());
                    Environment.ExitCode = -100;
                    return;
                }

                console.WrapLine($"Dropping {Database.Yellow()}".Cyan());
                db.Drop();
            }

            console.WrapLine($"Creating {Database.Yellow()}".Cyan());
            var database = new Database(srv, Database);

            database.Create();

            var connectionString = $"Server={Server};Database={Database};Trusted_Connection=True;";
            var upgradeCommand   = UpgradeDb(console, error, connectionString);

            if (!NoConfig)
            {
                GenerateTestingConfig(console, error, connectionString);
            }
        }
        public void Handle(IConsoleAdapter console, IErrorAdapter error, Settings keyPair)
        {
            var data = BufferUtils.GetFileContents(EncryptedFile);

            string key;

            if (!SkipPassword)
            {
                var pword = SetupSystem.RequestPassword();
                //the key is decrypted with CipherTools decryption, using the AES algorithm
                key = CipherTools.Decrypt<AesManaged>(keyPair.PrivateKey, pword, "salty");
            }
            else
            {
                key = keyPair.PrivateKey;
            }

            byte[] dataOut;
            if (NoDecompression)
                //data is decrypted with the private key
                dataOut = PrivateKeyDecryption.Decrypt(key, data);
            else
            {
                //data is decrypted with the private key
                data =  PrivateKeyDecryption.Decrypt(key, data);
                //data is decompressed
                dataOut = Compression.Decompress(data);
            }

            //data is written to file
            BufferUtils.WriteToFile(DecryptedFile, dataOut);

            console.WrapLine("EncryptedFile = {0}".Yellow(), EncryptedFile.Cyan());
            console.WrapLine("DecryptedFile = {0}".Yellow(), DecryptedFile.Cyan());
        }
Exemple #13
0
        private static void ConfigureProgram()
        {
            var fileAdapter         = new FileAdapter("./input");
            var inputFileRepository = new InputFileRepository(fileAdapter);

            _solutionManager = new SolutionManager(inputFileRepository);
            _consoleAdapter  = new ConsoleAdapter();
        }
 public InteractiveSession(ConsoleApplicationBase app, MethodParameterInjector injector, Dictionary<Type, ICommandHandler> handlers, IConsoleAdapter console, IErrorAdapter error, CommandLineInterpreterConfiguration config)
 {
     _app = app;
     _injector = injector;
     _handlers = handlers;
     _console = console;
     _error = error;
     _config = config;
     _interpreter = new CommandLineInterpreter(_config);
 }
Exemple #15
0
        private static UpgradeCommand UpgradeDb(IConsoleAdapter console, IErrorAdapter error, string connectionString)
        {
            var upgradeCommand = new UpgradeCommand()
            {
                ConnectionString = connectionString
            };

            upgradeCommand.Handle(console, error);
            return(upgradeCommand);
        }
        public void Handle(IConsoleAdapter console, IErrorAdapter error)
        {
            var upgrader = DeployChanges.To
                           .SqlDatabase(ConnectionString)
                           .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly())
                           .LogToConsole()
                           .Build();

            var result = upgrader.PerformUpgrade();
        }
Exemple #17
0
        internal async Task ReceiveMessageAsync(IConsoleAdapter consoleAdapter,
                                                CancellationToken cts)
        {
            var tasks = new List <Task>();

            foreach (string partition in _partitionIds)
            {
                tasks.Add(ReceiveMessagesFromDeviceAsync(partition, consoleAdapter, cts));
            }
            await Task.WhenAll(tasks.ToArray());
        }
        public FileScanner(IEnumerable <string> directories, IConsoleAdapter console, string defaultDirectory, IEnumerable <Rule> rules)
        {
            _console          = console;
            _defaultDirectory = defaultDirectory;
            _helper           = new FileScannerHelper(rules, defaultDirectory, console);

            foreach (var directory in directories)
            {
                AddDirectoryToScan(directory);
            }
        }
 private static void AddCommandListText(IConsoleAdapter console, CommandLineInterpreterConfiguration config, IOptionNameHelpAdorner adorner, CommandExecutionMode executionMode)
 {
     var commands = config.Commands.Where(c => c.Name != null && CommandModeFilter(executionMode, c)).OrderBy(c => c.Name).ToList();
     if (commands.Any())
     {
         console.WriteLine("Available commands");
         console.WriteLine();
         var commandItems = commands.Select(c => new { Command = c.Name, Text = FormatShortCommandDescription(c) });
         console.FormatTable(commandItems, FormattingOptions, ColumnSeperator);
     }
 }
        public void Handle(IConsoleAdapter adapter)
        {
            if (!DbOptions.ValidateDatabaseParameters(adapter))
                return;

            if (To == default(DateTime))
                To = DateTime.MaxValue;

            adapter.WrapLine("Import data from {0} to {1} from file \"{2}\".",
                             From.ToString().White(),
                             To.ToString().White(),
                             File.White());
        }
        public void Handle(IConsoleAdapter console, IErrorAdapter error)
        {
            var activity = new Dinner
            {
                Where          = Where,
                WhenDidItStart = When,
                Key            = Guid.NewGuid()
            };

            var context = TableContextFactory.Get(this, Constants.DinnerTable, CreateTable);

            context.AddAsync(activity).Wait();
        }
Exemple #22
0
 private void GenerateTestingConfig(IConsoleAdapter console, IErrorAdapter error, string connectionString)
 {
     console.WrapLine($"Creating testing configuration file".Cyan());
     var(configFile, configError) = TestConfigWriter.Write(connectionString, Server, Database);
     if (configError == null)
     {
         console.WrapLine($"{configFile.Yellow()} created.".Cyan());
     }
     else
     {
         error.WrapLine(configError.Red());
         return;
     }
 }
Exemple #23
0
        private void ReportDatabases(IConsoleAdapter console, Server srv)
        {
            console.FormatTable(new[] { new { Server = Server, Version = srv.Information.Version } });
            console.WriteLine();
            console.WrapLine("Databases");
            console.WriteLine();
            var databases = srv.Databases.Enumerate()
                            .Where(d => !d.IsSystemObject)
                            .Select(d => new { d.Name, d.CreateDate, Size = $"{d.Size} MB" })
                            .OrderBy(d => d.CreateDate);

            console.FormatTable(databases);
            console.WriteLine();
        }
Exemple #24
0
        private static bool ApplyValidations(InputItem item, object value, IConsoleAdapter consoleOut)
        {
            if (item.ReadInfo != null)
            {
                var error = item.ReadInfo.GetValidationError(value);
                if (error != null)
                {
                    consoleOut.WrapLine(error);
                    return false;
                }
            }

            return true;
        }
        public CommandLine(LanguageRuntime runtime, IConsoleAdapter console = null)
        {
            Runtime  = runtime;
            _console = console ?? new SystemConsoleAdapter();
            var grammar = runtime.Language.Grammar;

            Title           = grammar.ConsoleTitle;
            Greeting        = grammar.ConsoleGreeting;
            Prompt          = grammar.ConsolePrompt;
            PromptMoreInput = grammar.ConsolePromptMoreInput;
            App             = new ScriptApp(Runtime);
            App.ParserMode  = ParseMode.CommandLine;
            // App.PrintParseErrors = false;
            App.RethrowExceptions = false;
        }
Exemple #26
0
        private static bool SelectOption(string input, IEnumerable<OptionDefinition> optionDefinitions, IConsoleAdapter consoleOut, out object result)
        {
            var options = optionDefinitions.ToList();
            var hit = options.FirstOrDefault(o => o.RequiredValue == input)
                ?? options.FirstOrDefault(o => string.Compare(o.RequiredValue, input, StringComparison.OrdinalIgnoreCase) == 0);
            if (hit == null)
            {
                consoleOut.WrapLine(@"""{0}"" is not a valid selection.", input);
                result = null;
                return false;
            }

            result = hit.SelectedValue;
            return true;
        }
        public void Handle(IConsoleAdapter console, IErrorAdapter error)
        {
            var context = BlobContextFactory.Get(this, true);

            var container = context.GetContainer("test");

            console.WrapLine("Getting a shared access signature:");
            console.WrapLine(container.GetSharedAccessSignature(30).Cyan());

            console.WrapLine("Uploading to test.txt");

            container.UploadText("test.txt", "my test text");

            console.WriteLine();
            console.WrapLine("Listing blobs");

            console.FormatTable(container.ListBlobs("").Select(s => new { BlobName = s }));

            console.WrapLine("Deleting blob");
            container.DeleteBlob("test.txt");
            console.WriteLine();
            console.WrapLine("Listing blobs again");
            console.FormatTable(container.ListBlobs("").Select(s => new { BlobName = s }));

            console.WriteLine();
            console.WrapLine("Uploading stream data");

            using (var data = File.OpenRead(Assembly.GetExecutingAssembly().Location))
            {
                container.Upload("exedata", data);
            }

            console.WriteLine();
            console.WrapLine("Downloading stream data");

            using (var stream = container.OpenStream("exedata"))
            {
                var bytesRead      = 0;
                var totalBytesRead = 0;
                var buffer         = new Byte[100];
                while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    totalBytesRead += bytesRead;
                }

                console.WrapLine($"{totalBytesRead} read.");
            }
        }
        public void Handle(IConsoleAdapter console, IErrorAdapter error, IMapper mapper)
        {
            var ops = new UserOperations("https://senlabltd.eu.auth0.com/api/v2/", ClientId, Secret, mapper);

            try
            {
                console.FormatTable(ops.GetAllUsers().Select(c => new { c.Email, c.UserId }));
            }
            catch (AggregateException e)
            {
                error.WrapLine($"{e.InnerException.Message.Red()} (Aggregate)");
            }
            catch (Exception e)
            {
                error.WrapLine(e.Message.Red());
            }
        }
Exemple #29
0
        public ConsoleBirthdayManager(TextWriter consoleTextWriter, TextReader consoleTextReader,
                                      TextWriter errorWriter = null)
        {
            this.TextWriter  = consoleTextWriter;
            this.TextReader  = consoleTextReader;
            this.ErrorWriter = errorWriter ?? TextWriter;

            Commands           = new CommandList();
            CommandListAdapter = new CommandListAdapter(TextWriter);
            CommandParser      = new CommandParserService(Commands);
            CommandReader      = new CommandReaderService(TextReader, CommandParser);

            var personValidator = new ValidatorFactory().NewValidator <Person>();

            PersonRepository  = new RepositoryFactory().NewRepository(StorageOption.Filesystem, personValidator);
            PersonListAdapter = new PersonListAdapter(TextWriter, ErrorWriter);
        }
        public void Handle(IConsoleAdapter adapter)
        {
            if (!DbOptions.ValidateDatabaseParameters(adapter))
            {
                return;
            }

            adapter.WrapLine("Server: {0}  Database: {1}", DbOptions.Server ?? "(config)", DbOptions.Database ?? "(config)");
            adapter.WriteLine();

            adapter.WrapLine("Export data from {0} to {1} to file \"{2}\".",
                             From.ToString().White(),
                             To.ToString().White(),
                             File.White());

            adapter.WriteLine();
        }
Exemple #31
0
        public CommandLine(LanguageRuntime runtime, IConsoleAdapter adapter)
        {
            Runtime = runtime;
            Adapter = adapter ?? new ConsoleAdapter();
            var grammar = runtime.Language.Grammar;

            Title           = grammar.ConsoleTitle;
            Greeting        = grammar.ConsoleGreeting;
            Prompt          = grammar.ConsolePrompt;
            PromptMoreInput = grammar.ConsolePromptMoreInput;
            App             = new ScriptApp(Runtime)
            {
                ParserMode        = ParseMode.CommandLine,
                RethrowExceptions = false
            };
            // App.PrintParseErrors = false;
        }
        public void Handle(IConsoleAdapter console, IErrorAdapter error)
        {
            var context = TableContextFactory.Get(this, Constants.ActivityTable, true);
            var query   = new TableQuery <DynamicTableEntity>();
            var items   = context.CreateDynamicQuery(query,
                                                     e => error.WrapLine($"Unable to complete query due to exception:\r\n{e.Message}"))
                          .Select(a =>
                                  new
            {
                Who            = PropertyOrEmptyString(a, "Who"),
                What           = PropertyOrEmptyString(a, "What"),
                WhenDidItStart = PropertyOrEmptyString(a, "WhenDidItStart"),
                HowLong        = PropertyOrEmptyString(a, "HowLong")
            })
                          .ToList();

            console.FormatTable(items);
        }
        public void Handle(IConsoleAdapter console)
        {
            console.WrapLine("Get user input".BGWhite().Black());
            console.WriteLine();

            var item = console.ReadInput(new {String = Read.String().Prompt("Enter some text".Yellow())});

            var characters = item.String.Value
                .Select(c => string.Format(@"""{0}"" = {1}".Red(),
                    ConsoleIOExtensions.Yellow(c.ToString()),
                    string.Format("{0:X}", (byte) c).PadLeft(2, '0').Green()));

            console.WriteLine();
            console.WrapLine(string.Join("  ", characters));
            console.WriteLine();

            console.ReadLine();
        }
        public static bool GetValue(InputItem item, IConsoleInInterface consoleIn, IConsoleAdapter consoleOut)
        {
            var redirected = consoleIn.InputIsRedirected;

            var displayPrompt = ConstructPromptText.FromItem(item);

            do
            {
                consoleOut.Wrap(displayPrompt);
                object value;
                if (ReadValue.UsingReadLine(item, consoleIn, consoleOut, out value))
                {
                    item.Value = value;
                    return true;
                }
            } while (!redirected);

            return false;
        }
 public void Execute(ConsoleApplicationBase app, object command, IConsoleAdapter console, MethodParameterInjector injector, CommandExecutionMode executionMode)
 {
     var parameter = _parameterGetter == null || command == null ? String.Empty : _parameterGetter(command);
     if (String.IsNullOrWhiteSpace(parameter))
     {
         CommandDescriber.Describe(_config, console, DefaultApplicationNameExtractor.Extract(app.GetType()), executionMode, Adorner);
     }
     else
     {
         var chosenCommand = _config.Commands.FirstOrDefault(c => String.CompareOrdinal(c.Name, parameter) == 0);
         if (chosenCommand == null)
         {
             console.WrapLine(@"The command ""{0}"" is not supported.");
         }
         else
         {
             CommandDescriber.Describe(chosenCommand, console, executionMode, Adorner);
         }
     }
 }
Exemple #36
0
        private async Task ReceiveMessagesFromDeviceAsync(string partition, IConsoleAdapter adapter,
                                                          CancellationToken ct)
        {
            var eventHubReceiver = _eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow);

            while (true)
            {
                if (ct.IsCancellationRequested)
                {
                    break;
                }
                EventData eventData = await eventHubReceiver.ReceiveAsync();

                if (eventData == null)
                {
                    continue;
                }

                string data = Encoding.UTF8.GetString(eventData.GetBytes());
                adapter.WriteLine(string.Format("Partition:{0}  Message: \"{1}\"", partition, data));
            }
        }
        public void Handle(IConsoleAdapter console, IErrorAdapter error)
        {
            TimeSpan howLong;

            if (!TimeSpan.TryParse(HowLong, out howLong))
            {
                error.WrapLine("Invalid timespan format.");
                Environment.ExitCode = -100;
                return;
            }

            var activity = new Activity()
            {
                Who            = Who,
                What           = What,
                WhenDidItStart = When,
                HowLong        = howLong,
                Key            = Guid.NewGuid()
            };

            var context = TableContextFactory.Get(this, Constants.ActivityTable, CreateTable);

            context.UpdateAsync(activity).Wait();
        }
        public void Handle(IConsoleAdapter console, IErrorAdapter error, Settings settings)
        {
            console.WriteLine("On average, encryption with compression is taking {0} to complete, press enter to continue..", ProcessingTime.GetAverageTime());
            console.ReadLine();
            ProcessingTime.StartTimer();

            //the file is stored in a byte array called data
            var data = BufferUtils.GetFileContents(OriginalFile);

            //if they have selected the option of external key then the variable key will contain the
            //external key, otherwise the public key is taken from the settings object
            var key = OtherKey ? GetExternalKey() : settings.PublicKey;

            if (NoCompression)
            {
                //if the user selected the option no compression then the file is encrypted without compressing first

                data = PublicKeyEncryption.Encrypt(key, data);
                console.WrapLine("Encryption complete".Blue());
            }
            else
            {
                //if the user didn't specify the option no compression then the file is compressed and then encrypted
                data = Compression.Compress(data);
                console.WrapLine("Compression complete".Green());
                data = PublicKeyEncryption.Encrypt(key, data);
                console.WrapLine("Encryption complete".Blue());
            }

            //the byte array is then written to the encrypted file location
            BufferUtils.WriteToFile(EncryptedFile, data);

            console.WrapLine("OriginalFile = {0}".Yellow(), OriginalFile.Cyan());
            console.WrapLine("EncryptedFile = {0}".Yellow(), EncryptedFile.Cyan());
            ProcessingTime.StopTimer();
        }
 private void ExceptionHandler(IConsoleAdapter console, IErrorAdapter error, Exception exception, object options)
 {
     LastException = exception;
 }
 private static void AddDefaultCommandText(IConsoleAdapter console, BaseCommandConfig defaultCommand, string applicationName, IOptionNameHelpAdorner adorner)
 {
     console.Write(FormatFullCommandDescription(defaultCommand, string.Format("Usage: {0}", applicationName), adorner, false));
 }
        public async void Handle(IConsoleAdapter console, IErrorAdapter error)
        {
            try
            {
                var table     = TableContextFactory.Get(this, Constants.TestTable, true);
                var variables = new[]
                {
                    "Alpha", "Beta", "Charlie", "Delta", "Echo"
                }.ToList();

                var partition = DateTime.Now.ToString("s");
                console.WrapLine($"Partition key = {partition}");

                var entities = Enumerable.Range(0, 20)
                               .Select(e =>
                {
                    var item = new TestEntity
                    {
                        Alpha        = variables[0],
                        Beta         = variables[1],
                        Charlie      = variables[2],
                        Delta        = variables[3],
                        Echo         = variables[4],
                        PartitionKey = partition,
                        RowKey       = variables[1] + " " + Guid.NewGuid().ToString()
                    };
                    var top = variables[0];
                    variables.RemoveAt(0);
                    variables.Add(top);
                    return(item);
                }).ToList();

                console.WrapLine("Generating entities using batch add...");
                foreach (var entity in entities)
                {
                    table.BatchAdd(entity);
                }

                table.BatchExecuteAsync().Wait();

                console.WrapLine("Performing batch updates");

                table.BatchDelete(entities[5]);
                entities[7].Alpha = "Updated (Batch)";
                table.BatchUpdate(entities[7]);
                entities[8].Beta = "Updated (Batch)";
                table.BatchUpdate(entities[8]);

                table.BatchExecuteAsync().Wait();

                console.WrapLine("Performing individual delete");

                table.DeleteAsync(entities[9]).Wait();

                console.WrapLine("Retrieving deleted item");

                var deletedItem = table.GetAsync <TestEntity>(entities[9].PartitionKey, entities[9].RowKey).Result;
                if (deletedItem == null)
                {
                    console.WrapLine("Deleted item not found");
                }
                else
                {
                    console.WrapLine("Deleted item found".Red());
                }

                console.WrapLine("Performing delete again");
                try
                {
                    table.DeleteAsync(entities[9]).Wait();
                }
                catch
                {
                    console.WrapLine("Caught exception");
                }

                console.WrapLine("Performing individual update");
                entities[10].Beta = "Updated (Individual)";
                table.UpdateAsync(entities[10]).Wait();

                console.WrapLine("Retrieving test partition:");

                var query = new TableQuery <TestEntity>();
                query.FilterString = TableQuery.GenerateFilterCondition("PartitionKey", "eq", partition);
                var items = table.Query(query,
                                        e => error.WrapLine($"Unable to complete query due to exception:\r\n{e.Message}"))
                            .Select(i => new { i.Alpha, i.Beta, i.Charlie, i.Delta, i.Echo })
                            .OrderBy(i => i.Alpha)
                            .ThenBy(i => i.Beta)
                            .ThenBy(i => i.Charlie)
                            .ThenBy(i => i.Delta)
                            .ThenBy(i => i.Echo);
                console.FormatTable(items);
                console.WriteLine();
                console.WrapLine("Running test query:");

                var whereForQuery = $"PartitionKey eq '{partition}' and (Alpha eq 'Delta' or Alpha eq 'Alpha' and Delta eq 'Beta')";

                var queryWithWhere = new TableQuery <TestEntity>().Where(whereForQuery);

                var resultWithWhere = table.Query(queryWithWhere,
                                                  e => error.WrapLine($"Unable to complete query due to exception:\r\n{e.Message}"))
                                      .Select(i => new { i.Alpha, i.Beta, i.Charlie, i.Delta, i.Echo })
                                      .OrderBy(i => i.Alpha)
                                      .ThenBy(i => i.Beta)
                                      .ThenBy(i => i.Charlie)
                                      .ThenBy(i => i.Delta)
                                      .ThenBy(i => i.Echo);

                console.WrapLine(whereForQuery);
                console.FormatTable(resultWithWhere);

                console.WriteLine();
                console.WrapLine("Dynamic query (same where)");

                var dynamicQ = new TableQuery <DynamicTableEntity> {
                    SelectColumns = new List <string> {
                        "Alpha", "Charlie"
                    }
                };
                var dynamicItems = table.CreateDynamicQuery(dynamicQ.Where(whereForQuery),
                                                            e => error.WrapLine($"Unable to complete query due to exception:\r\n{e.Message}"))
                                   .Select(a =>
                                           new
                {
                    Alpha   = a.Properties["Alpha"].StringValue,
                    Charlie = a.Properties["Charlie"].StringValue,
                })
                                   .OrderBy(i => i.Alpha)
                                   .ThenBy(i => i.Charlie)
                                   .ToList();
                console.FormatTable(dynamicItems);

                console.WrapLine("Done");
            }
            catch (Exception e)
            {
                error.WrapLine(e.ToString().Red());
                throw;
            }
        }
 protected FakeApplicationBase(IConsoleAdapter console, IErrorAdapter error)
 {
     Console = console;
     Error = error;
 }
        public void Handler(IConsoleAdapter console, IErrorAdapter error)
        {
            if (!Silent)
            {
                if (!File.Exists(InputFile))
                {
                    console.WrapLine("Input map file does not exist...".Red());
                    return;
                }

                if (File.Exists($"{OutputFile}.N2SMAP"))
                {
                    if (!console.Confirm("Output file exists... Would you like to overwrite it?".Red()))
                    {
                        return;
                    }
                }
            }

            string jsonText;

            if (Xml)
            {
                console.WrapLine("Loading map from XML...");
                var doc = new XmlDocument();
                doc.LoadXml(File.ReadAllText(InputFile));
                jsonText = JsonConvert.SerializeXmlNode(doc.FirstChild);
            }
            else
            {
                console.WrapLine("Loading map from JSON...");
                jsonText = File.ReadAllText(InputFile);
            }


            var deserialized = JsonConvert.DeserializeObject <MapT>(jsonText);

            deserialized.GameVersion += ":N2SMap_Viewer";

            var fb = new FlatBufferBuilder(1);

            console.WrapLine("Packing map...");
            fb.Finish(N2S.FileFormat.Map.Pack(fb, deserialized).Value);


            var buf = fb.SizedByteArray();

            using (var outputStream = new MemoryStream())
            {
                //Here we're compressing the data to make it smaller
                console.WrapLine("Compressing map...");
                using (var gZipStream = new GZipStream(outputStream, CompressionMode.Compress))
                    gZipStream.Write(buf, 0, buf.Length);

                //Writing compressed data to a file
                console.WrapLine("Writing map to file...");
                File.WriteAllBytes(OutputFile + ".N2SMAP", outputStream.ToArray());
            }

            console.WrapLine($"Complete! File written to {OutputFile}.N2SMAP");
        }
 private void FixedColumnsThatRequiredSixtyChars(IConsoleAdapter adapter)
 {
     var report = _data.AsReport(p => p.AddColumn(a => a,
                                           col => col.Heading("Character").Width(10))
                                       .AddColumn(a => a.Length,
                                           col => col.Heading("Name Length").Width(10))
                                       .AddColumn(a => new string(a.Reverse().ToArray()),
                                           col => col.Heading("Backwards").Width(10))
                                       .AddColumn(a => string.Join(" ", Enumerable.Repeat(a, a.Length)),
                                           col => col.Heading("Repeated").Width(27)));
     adapter.FormatTable(report);
 }
Exemple #45
0
 public void Handle(IConsoleAdapter console)
 {
     console.WrapLine("You said: {0}", Pos1);
 }
 public RobotController(IConsoleAdapter console)
 {
     _console   = console;
     Commands   = new Queue <IRobotCommand>();
     _undoStack = new Stack <IRobotCommand>();
 }
 public static void Describe(BaseCommandConfig command, IConsoleAdapter console, CommandExecutionMode executionMode, IOptionNameHelpAdorner adorner)
 {
     console.Write(FormatFullCommandDescription(command, adorner: adorner));
 }
Exemple #48
0
 public DoItAll(IConsoleAdapter consoleAdapter, ILogger logger)
 {
     _logger         = logger;
     _consoleAdapter = consoleAdapter;
 }
                public void Handle(IConsoleAdapter adapter)
                {
                    switch (Test)
                    {
                        case 60:
                            FixedColumnsThatRequiredSixtyChars(adapter);
                            break;

                        case 61:
                            ColumnsHaveMinWidthToFillSixtyChars(adapter);
                            break;
                    }
                }
Exemple #50
0
 public void Handle(IConsoleAdapter console, IErrorAdapter error)
 {
     var context = TableContextFactory.Get(this, Table);
     //table.UpdateAsync()
 }
Exemple #51
0
 public SurveyController(IConsoleAdapter consoleAdapter)
 {
     _consoleAdapter = consoleAdapter;
 }
 public void Handle(IConsoleAdapter console, IErrorAdapter error, Options command)
 {
     console.WriteLine("Parameter is \"{0}\"", command.Pos);
 }
 public FileScannerHelper(IEnumerable <Rule> rules, string defaultDirectory, IConsoleAdapter logger)
 {
     _logger           = logger;
     _rules            = rules;
     _defaultDirectory = defaultDirectory;
 }
 public void Handle(IConsoleAdapter console, IErrorAdapter error, Options command, CustomObject custom)
 {
     console.WriteLine("Custom string is \"{0}\"", custom.Message);
 }
 public void Handle(IConsoleAdapter console, Options command, IErrorAdapter error)
 {
     console.WriteLine("Text from handler class.");
     error.WriteLine("Error text");
 }
 public void Handle(IConsoleAdapter console)
 {
     console.Write("output");
 }
 public void Handle(IConsoleAdapter console, IErrorAdapter error)
 {
     console.FormatTable(Directory.EnumerateDirectories(Path).Select(d => new { Directory = d }));
 }
 /// <summary>
 /// Main constructor injecting instance dependancies
 /// </summary>
 /// <param name="consoleAdapter"></param>
 public ConsoleInteractionController(IConsoleAdapter consoleAdapter)
 {
     ConsoleAdapter = consoleAdapter;
 }
Exemple #59
0
        public void Handler(IConsoleAdapter console, IErrorAdapter error)
        {
            if (!Silent)
            {
                if (!File.Exists(InputFile))
                {
                    console.WrapLine("Input map file does not exist...".Red());
                    return;
                }


                if (File.Exists($"{OutputFile}.xml") && Xml)
                {
                    if (!console.Confirm("Output file exists... Would you like to overwrite it?".Red()))
                    {
                        return;
                    }
                }
                else if (File.Exists($"{OutputFile}.json") && !Xml)
                {
                    if (!console.Confirm("Output file exists... Would you like to overwrite it?".Red()))
                    {
                        return;
                    }
                }
            }


            console.WrapLine("Reading map file...");
            var bytes = File.ReadAllBytes(InputFile);

            console.WrapLine("Decompressing map...");
            byte[] lengthBuffer = new byte[4];
            Array.Copy(bytes, bytes.Length - 4, lengthBuffer, 0, 4);
            int uncompressedSize = BitConverter.ToInt32(lengthBuffer, 0);

            var buffer = new byte[uncompressedSize];

            using (var ms = new MemoryStream(bytes))
            {
                using (var gzip = new GZipStream(ms, CompressionMode.Decompress))
                {
                    gzip.Read(buffer, 0, uncompressedSize);
                }
            }

            ByteBuffer bb = new ByteBuffer(buffer);


            if (!N2S.FileFormat.Map.MapBufferHasIdentifier(bb))
            {
                if (!console.Confirm(
                        "The input map might be corrupted or not be in the correct format, would you like to continue?"
                        .Red()))
                {
                    return;
                }
            }

            console.WrapLine("Unpacking map...");
            var data = N2S.FileFormat.Map.GetRootAsMap(bb).UnPack();


            console.WrapLine("Serialized into JSON...");
            string output = JsonConvert.SerializeObject(data, Formatting.Indented);


            if (Xml)
            {
                console.WrapLine("Converting into XML");
                XmlDocument xmlDocument = (XmlDocument)JsonConvert.DeserializeXmlNode(output, "Map");

                xmlDocument.Save($"{OutputFile}.xml");

                console.WrapLine($"Complete! File written to {OutputFile}.xml");
            }
            else
            {
                File.WriteAllText($"{OutputFile}.json", output);
                console.WrapLine($"Complete! File written to {OutputFile}.json");
            }
        }
Exemple #60
0
 private void InitializeAdapter()
 {
     ResultsAdapter = new PersonListAdapter(Writer, ErrorWriter);
 }