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()); }
public void Handle(IConsoleOperations console, IErrorAdapter error) { console.WriteLine("Coloured".Red() + " text is " + "easy".Yellow() + " to configure."); console.WriteLine(); console.WriteLine("For example:"); console.WriteLine(); console.WriteLine(@" ""red on green"".Red().BGDarkGreen()"); console.WriteLine(); console.WriteLine("Displays like this:"); console.WriteLine(); console.WriteLine("red on green".Red().BGGreen()); console.WriteLine(); console.WriteLine("It's".Cyan() + "easy".BGYellow().Black() + "to".BGDarkCyan().Cyan() + "overuse".BGDarkBlue().White() + "it!".Magenta().BGGray()); console.WriteLine(); console.WriteLine(); var data = Enumerable.Range(1, 10) .Select(i => new { Number = i, String = string.Join(" ", Enumerable.Repeat("blah", i)).Cyan(), Red = (("Red" + Environment.NewLine + "Lines").Cyan() + Environment.NewLine + "lines").BGDarkRed() + "Clear", Wrapped = @"Complex data string. Includes a hard newline.".Yellow() }); console.FormatTable(data); error.WriteLine("This is " + "error".Red() + " text"); }
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) { 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()); } }
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); }
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); }
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) { 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 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); }
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(); }
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(); }
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; } }
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()); } }
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, 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(); }
public void Handle(IConsoleAdapter console, IErrorAdapter error, ClassHandledThrowingCommand cmd) { throw new Exception("Exception from throwing class handled command."); }
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"); }
public void SetUp() { _testConsole = new ConsoleInterfaceForTesting(); _console = new ConsoleAdapter(_testConsole); _error = new ErrorAdapter(_testConsole, "ERROR: "); _app = FakeApplication.MakeFakeApplication(_console, _error, typeof(StartCommand), typeof(Command1), typeof(Command2), typeof(Command3), typeof(ExitCommand), typeof(SetPromptCommand)); }
private FakeApplication(IConsoleAdapter console, IErrorAdapter error, Type[] commands) : base(console, error) { _commands = commands; }
public void Handle(IConsoleAdapter console, IErrorAdapter error, ClassHandledCommand cmd) { console.WrapLine("Class handled command."); console.WrapLine("Positional parameter: {0}", cmd.Pos); console.WrapLine("Option TestOpt : {0}", cmd.TestOpt); }
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; } }
public void Handle(IConsoleAdapter console, IErrorAdapter error, Options command) { console.WriteLine("Parameter is \"{0}\"", command.Pos); }
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"); } }
public static FakeApplication MakeFakeApplication(IConsoleAdapter console, IErrorAdapter error, params Type[] commands) { var fake = new FakeApplication(console, error, commands); return fake; }
public void Handle(IConsoleAdapter console, IErrorAdapter error) { var context = TableContextFactory.Get(this, Table); //table.UpdateAsync() }
protected FakeApplicationBase(IConsoleAdapter console, IErrorAdapter error) { Console = console; Error = error; }
public void Handle(IConsoleAdapter console, IErrorAdapter error, Options command, CustomObject custom) { console.WriteLine("Custom string is \"{0}\"", custom.Message); }
private void ExceptionHandler(IConsoleAdapter console, IErrorAdapter error, Exception exception, object command) { Exception = exception; }
public void Handle(IConsoleAdapter console, Options command, IErrorAdapter error) { console.WriteLine("Text from handler class."); error.WriteLine("Error text"); }
public void Handle(IConsoleAdapter console, IErrorAdapter error) { console.FormatTable(Directory.EnumerateDirectories(Path).Select(d => new { Directory = d })); }
private void ExceptionHandler(IConsoleAdapter console, IErrorAdapter error, Exception exception, object options) { LastException = exception; }
public InteractiveSessionService(IConsoleAdapter console, IErrorAdapter error) { _console = console; _error = error; }
public static void Handler(IConsoleAdapter console, IErrorAdapter error, Exception exception, object command) { error.WrapLine("Processing halted due to exception:"); error.WrapLine(exception.Message); }