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 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; }
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); }
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, 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 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()); }
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; }
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(); }
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) { 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 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 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()); }
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(); }
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 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 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 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); } } }
public void Handle(IConsoleAdapter console) { console.WrapLine(GetType().Name); }
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 void Handle(IConsoleAdapter console) { console.WrapLine("You said: {0}", Pos1); }
public void Handle(IConsoleAdapter adapter) { var item = adapter.ReadInput(new {String = string.Empty, Int = 0}); adapter.WriteLine(); if (item == null) { adapter.WrapLine("Invalid input. No item received."); } else { adapter.WrapLine("Input received."); adapter.WrapLine("String was \"{0}\", integer was {1}", item.String, item.Int); } }
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 void Handle(IConsoleAdapter console) { console.WrapLine("Self handled command."); console.WrapLine("Positional parameter: {0}", Pos); console.WrapLine("Option TestOpt : {0}", TestOpt); }
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 Handle(IInteractiveSessionService service, IConsoleAdapter console) { console.WrapLine(GetType().Name); service.EndSession(); }
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(IInteractiveSessionService service, IConsoleAdapter console) { console.WrapLine(GetType().Name); if (Prompt != null) service.SetPrompt(Prompt); service.BeginSession(); }