/// <summary> /// Destroys an existing Vultr script. /// </summary> /// <param name="script">The configuration to reference to destroy the /// script.</param> /// <param name="dryrun">Whether or not this is a dryrun. If set to true then /// provision commands will not be sent to the platform and instead messaging /// will be outputted describing what would be done.</param> public override void Destroy(Script script, bool dryrun = false) { Console.WriteLine("Destroying script"); ConsoleX.WriteLine("name", script.Name); var existingScripts = Client.StartupScript.GetStartupScripts(); bool Predicate(KeyValuePair <string, StartupScript> existingScript) => existingScript.Value.name == script.Name && existingScript.Value.type == script.Type.ToString().ToLower(); if (existingScripts.StartupScripts != null && existingScripts.StartupScripts.Exists(Predicate)) { var(id, _) = existingScripts.StartupScripts.Single(Predicate); Console.WriteLine("Script {0} with ID {1} exists", script.Name, id); if (!dryrun) { Client.StartupScript.DeleteStartupScript(id); Console.WriteLine("Deleted script {0}", script.Name); } } else { Console.WriteLine("Script {0} does not exist", script.Name); } Console.WriteLine("---"); }
private void CreateRule( string firewallName, string firewallGroupId, Configuration.FirewallRule rule, bool dryrun) { var ipType = rule.IpType.ToString().ToLower(); var protocol = rule.Protocol.ToString().ToLower(); Console.WriteLine("Creating firewall rule for {0}", firewallName); ConsoleX.WriteLine("ip_type", ipType); ConsoleX.WriteLine("port", rule.Ports); ConsoleX.WriteLine("protocol", protocol); ConsoleX.WriteLine("source", rule.Source); ConsoleX.WriteLine("subnet", rule.Subnet); ConsoleX.WriteLine("subnet_size", rule.SubnetSize); if (!dryrun) { Client.Firewall.CreateFirewallRule( firewallGroupId, ip_type: ipType, protocol: protocol, subnet: rule.Subnet, subnet_size: rule.SubnetSize, port: rule.Ports, source: rule.Source); } Console.WriteLine("--"); }
/// <summary> /// Destroys an existing Vultr firewall. /// </summary> /// <param name="firewall">The configuration to reference to destroy the /// firewall.</param> /// <param name="dryrun">Whether or not this is a dryrun. If set to true then /// provision commands will not be sent to the platform and instead messaging /// will be outputted describing what would be done.</param> public override void Destroy(Firewall firewall, bool dryrun = false) { Console.WriteLine("Destroying firewall"); ConsoleX.WriteLine("name", firewall.Name); var firewallGroupId = Client.Firewall.GetExistingFirewall(firewall.Name); if (!string.IsNullOrEmpty(firewallGroupId)) { Console.WriteLine("Firewall {0} with ID {1} exists", firewall.Name, firewallGroupId); var existingRules = Client.Firewall.GetExistingRules(firewallGroupId); foreach (var firewallRule in existingRules) { Client.Firewall.DeleteRule( firewall.Name, firewallGroupId, firewallRule.Value, dryrun); } if (!dryrun) { Client.Firewall.DeleteFirewallGroup(firewallGroupId); Console.WriteLine("Deleted firewall {0}", firewall.Name); } } else { Console.WriteLine("Firewall {0} doesn't exist", firewall.Name); } Console.WriteLine("---"); }
public static bool DownloadAccessFile(ConsoleX consoleX) { bool fileDownloaded = false; do { var url = consoleX.WriteClipboardQuery("CORRECT URL"); url = url.Trim(); // Remove any whitespace that may have been copied by mistake. if(!AccessFileDownloader.IsUrlCorrect(url)) { consoleX.WriteLine("Sorry, incorrect URL. Please try again."); } else { try { consoleX.WriteLine("Thanks! Downloading file now. Please wait..."); AccessFileDownloader.DownloadFile(url); consoleX.WriteLine("OK, Done."); fileDownloaded = true; } catch(Exception ex) { ExceptionHelper.HandleException(ex, consoleX); } } } while(!fileDownloaded); return fileDownloaded; }
public static void Process(string[] args) { string dir; if (args.Length > 1) { dir = args[1]; // addtopath xxx if (!Path.IsPathRooted(dir)) { //相对路径 dir = Path.Combine(System.Environment.CurrentDirectory, dir); } } else { dir = System.Environment.CurrentDirectory; } var path = System.Environment.GetEnvironmentVariable("path", EnvironmentVariableTarget.Machine); if (path.Contains(dir)) { path = path.Replace(dir, "").Replace(";;", ";").TrimEnd(';'); System.Environment.SetEnvironmentVariable("path", path, EnvironmentVariableTarget.Machine); ConsoleX.Success("已成功将 {0} 从path环境变量去除", System.Environment.CurrentDirectory); } else { ConsoleX.Warn("当前目录不在path环境变量中..."); } }
public static void TestDatabaseState(ConsoleX consoleX, bool showTestFeedback = false) { if(showTestFeedback) consoleX.WriteLine("Ok, let's check the database for synchronisation issues..."); if(!DatabaseState.IsDataSynchronised()) { consoleX.WriteWarning("Warning: Database records have not been synchronised!", false); consoleX.WriteWarning("Attempting to synchronise now..."); if(DatabaseState.TrySync()) { consoleX.WriteWarning("Success!", true); } else { consoleX.WriteWarning("Failure! Could not synchronise at this time.", false); } consoleX.WriteWarning("If this message persists, please contact IT Support."); } else if(showTestFeedback) { consoleX.WriteLine("Great, no synchronisation issues found!"); } }
/// <summary> /// executes the close of the current command handler <see cref="CommandHandler"/> /// </summary> public static void ExecuteClose() { var response = ConsoleX.WriteCheck($"Are you sure you want to close the { Handler.CurrentCommandBranchName } command handler?"); if (response) { Handler.CloseCurrentListener = true; } }
static void Main() { ConsoleX.WriteTitle("MS SQL CLR Assembly Extractor"); Handler.AddCommands(new ICommandContainer[] { new ProgramCommands() }); ConsoleX.WriteLine("Use the commands to build a connection string", ConsoleX.MessageStatus.Info); ConsoleX.WriteLine("Once complete use -c to return to the exporter.", ConsoleX.MessageStatus.Info); Handler.Execute("-bc"); Handler.Listen(); }
private static void Encase(bool isHeader, string splitter, int maxLength) { var loop = 1; while (loop <= 3) { if (isHeader && loop == 3 || !isHeader && loop == 1) { Console.WriteLine("{0,2} {1,0} {2, " + (maxLength - 2) + "}", splitter.Repeat(2), "", splitter.Repeat(2)); } else { ConsoleX.WriteSplitter(splitter, maxLength + 2); } loop++; } }
public static void HandleException(Exception ex, ConsoleX consoleX) { consoleX.WriteException(ex); if(consoleX.WriteBooleanQuery("Would you like to report this error?")) { consoleX.WriteLine("Ok. I'll compose an email for you."); consoleX.WriteLine("This should open in your default email client. Please send the email."); string mailto = "mailto:[email protected]?subject=Error report: {0}&body={1}"; string body = "Error: " + ex.Message + Environment.NewLine; body += "Type: " + ex.GetType().ToString() + Environment.NewLine; body += "Stack Trace: " + Environment.NewLine + ex.StackTrace; mailto = string.Format(mailto, ex.Message, body); mailto = Uri.EscapeUriString(mailto); Process.Start(mailto); } consoleX.WriteHorizontalRule(); }
public static void CheckForAccessFile(ConsoleX consoleX) { if(!AccessFileDownloader.AccessFileExists) { consoleX.WriteIntro("Database requirements"); consoleX.WriteWarning("It looks like you don't have the Access database file yet."); consoleX.WriteLine("Don't worry, I can download it for you and save it to the correct place."); var fileDownloaded = AccessFileHelper.DownloadAccessFile(consoleX); if(fileDownloaded) consoleX.WriteLine("You can now continue with your previous task."); consoleX.WriteHorizontalRule(); } }
public static void Process(string[] args) { string exe = ""; if (args.Length > 1) //pm [bat a.exe] { exe = args[1]; } else { var exes = System.IO.Directory.GetFiles(System.Environment.CurrentDirectory, "*.exe"); if (exes.Length < 1) { ConsoleX.Error("没有exe文件..."); return; } else if (exes.Length > 1) { ConsoleX.Warn("exe文件超过两个,取第一个..."); } if (!string.IsNullOrWhiteSpace(exes[0])) { exe = exes[0]; } } exe = Path.Combine(System.Environment.CurrentDirectory, exe); var name = System.IO.Path.GetFileNameWithoutExtension(exe); var content = String.Format("@\"{0}\" %*", exe); var ext = ".cmd"; if (args[0] == "bat") { ext = ".bat"; } var dest = AppDomain.CurrentDomain.BaseDirectory + name + ext; System.IO.File.WriteAllText(dest, content); Console.WriteLine("已为{0}.exe创建.cmd文件:{1}", name, dest); }
public static void Listen() { var tree = GetTree(); ConsoleX.WriteInfoLine($"listening for calls in the command named branch ({ CurrentCommandBranchName }) (use -h or -help for a list of commands)", ConsoleX.LogLevel.basic); do { if (CloseCurrentListener) { break; } var commands = ConsoleX.ReadCommands().ToArray(); ExecuteAll(commands); continue; } while (true); CloseCurrentListener = false; Handler.BranchNavigation.StepUp(tree); }
public static bool WriteCheck(string Question) { ConsoleKey response; do { ConsoleX.Write($"{ Question } [y/n]", MessageStatus.Question); response = Console.ReadKey(false).Key; if (response != ConsoleKey.Enter) { Console.WriteLine(); } } while (response != ConsoleKey.Y && response != ConsoleKey.N); Console.ForegroundColor = defaultStatusColor; return(response == ConsoleKey.Y); }
public static void ExecuteAll(IEnumerable <IExecutableCommand> exeCommands) { foreach (var exeCommand in exeCommands) { var matchedCommands = GetAllCommandsProperties().Where(c => c.IsCommand(exeCommand.Command)); if (!matchedCommands.Any()) { ConsoleX.WriteWarningLine($"The command { exeCommand.Command.ShortName ?? exeCommand.Command.LongName } cannot be found", ConsoleX.LogLevel.basic); continue; } foreach (var cmd in matchedCommands) { var result = cmd.Invoke(exeCommand.Arguments?.ToArray()); switch (result) { case null: continue; case string str: { ConsoleX.WriteLine(str); break; } case IEnumerable enumerable: { foreach (var s in enumerable.Cast <object>().Select(i => i.ToString())) { ConsoleX.WriteLine(s); } break; } default: ConsoleX.WriteLine(result.ToString()); break; } } } }
internal static IEnumerable <string> GetArgDescriptions(this CommandProperty cmdProperty) { string[] desc = null; try { desc = JsonConvert.DeserializeObject <string[]>(cmdProperty.ArgDescriptionArray); } catch (Exception) { ConsoleX.WriteError(new ArgumentException($"The commands Argument Description of \"{ cmdProperty.ArgDescriptionArray }\" is not of string format containing an array or strings")); } for (var i = 0; i < cmdProperty._propertyInfo.PropertyType.GetGenericArguments().Length; i++) { var argument = cmdProperty._propertyInfo.PropertyType.GetGenericArguments()[i]; yield return(cmdProperty._propertyInfo.PropertyType.Name.Contains("Func") && i != 0 ? $"return[{i}]({argument.Name}): { desc?.ElementAtOrDefault(i) ?? "No return description" }" : $"argument[{i}]({argument.Name}): { desc?.ElementAtOrDefault(i) ?? "No argument description" }"); } }
/// <summary> /// executes the help command for the current command handler <see cref="CommandHandler"/> /// </summary> public static void WriteHelp(string arg) { if (arg == string.Empty) { System.Console.WriteLine("{0,-20} {1,-20} {2,10}", "Short Name", "Long Name", "Description"); ConsoleX.WriteSplitter("-", 100); foreach (var commandProp in Handler.GetAllCommandsProperties()) { System.Console.WriteLine("-{0,-20} -{1,-20} {2,10}", commandProp.Command.ShortName, commandProp.Command.LongName, commandProp.Command.Description); } ConsoleX.WriteSplitter("-", 100); } else { WriteCommandHelp(arg); } }
static void Main(string[] args) { var solution = new Solution(); while (true) { //int input = int.Parse(Console.ReadLine()); //int input2 = int.Parse(Console.ReadLine()); //int input3 = int.Parse(Console.ReadLine()); //string input = Console.ReadLine(); //string input2 = Console.ReadLine(); //int[] intArr = input.Split(',').Select(s => int.Parse(s)).ToArray(); //int input2 = int.Parse(Console.ReadLine()); //var builder = new DataStructureBuilder(); //int?[] data = new int?[] { 1, 2, 3, 4, 5, null, 6, null, null, 7, 8 }; //var tree = builder.BuildTree(data); //var listNode = builder.BuildListNode(new int[] { 1, 4, 5 }); //int[][] arr = new int[3][] { new int[] { 1, 3, 1 }, new int[] { 1, 5, 1 }, new int[] { 4, 2, 1 } }; //string input = "abcbefga"; //string input2 = "dbefga"; //int[] nums1 = new int[] { 1, 2, 3 }; //int[] nums2 = new int[] { 1, 1 }; //IList<IList<int>> data = new List<IList<int>>() //{ // new List<int>() { 1, 3 }, // new List<int>() { 3, 0, 1 }, // new List<int>() { 2 }, // new List<int>() { 0 } // //new List<int>() { 1 }, // //new List<int>() { 2 }, // //new List<int>() { 3 }, // //new List<int>() { } //}; string str = "ABAB"; var res = solution.CharacterReplacement(str, 2); ConsoleX.WriteLine(res); } }
protected override void RowGUI(RowGUIArgs args) { int row = args.row; object[] arg = new object[4] { row, 2, 0, "" }; ConsoleX.getLinesAndModeFromEntryInternalMethod.Invoke(null, arg); int mode = (int)arg[2]; string text = arg[3].ToString(); if (reg != null) { if (reg.IsMatch(text)) { GUI.contentColor = Color.cyan; } else { GUI.contentColor = Color.gray; } } else { GUI.contentColor = Color.white; } EditorGUI.DrawRect(new Rect(args.rowRect.x + 4, args.rowRect.y + 12, 8, 8), ConsoleX.GetColorByMode(mode)); EditorGUI.LabelField(new Rect(args.rowRect.x + 16, args.rowRect.y, args.rowRect.width - 16, args.rowRect.height), text); if (collapse) { int count = (int)ConsoleX.getEntryCountMethod.Invoke(null, new object[1] { row }); EditorGUI.LabelField(new Rect(args.rowRect.width - 48, args.rowRect.y + 8, 40, 16), count > 999 ? "999+" : count.ToString(), EditorStyles.miniButton); } GUI.contentColor = Color.white; }
/// <summary> /// Deletes an existing firewall rule. /// </summary> /// <param name="client">The FirewallClient to use to delete the firewall /// rule.</param> /// <param name="firewallName">The name of the firewall the rule belongs /// to.</param> /// <param name="firewallGroupId">The ID of the firewall the rule belongs /// to.</param> /// <param name="rule">The rule to delete.</param> /// <param name="dryrun">Whether or not this is a dryrun. If set to true then /// provision commands will not be sent to the platform and instead messaging /// will be outputted describing what would be done.</param> public static void DeleteRule( this FirewallClient client, string firewallName, string firewallGroupId, FirewallRule rule, bool dryrun) { Console.WriteLine("Deleting existing firewall rule for {0}", firewallName); ConsoleX.WriteLine("port", rule.port); ConsoleX.WriteLine("port", rule.rulenumber); ConsoleX.WriteLine("port", rule.subnet); ConsoleX.WriteLine("port", rule.subnet_size); ConsoleX.WriteLine("protocol", rule.protocol); ConsoleX.WriteLine("source", rule.source); if (!dryrun) { client.DeleteFirewallRule(firewallGroupId, rule.rulenumber); } Console.WriteLine("--"); }
public static void WriteCommandHelp(string arg) { var commandProps = Handler.GetAllCommandsProperties().Where(c => c.IsCommand(arg)); if (!commandProps.Any()) { ConsoleX.WriteError(new Exception($"command does not exist"), ConsoleX.LogLevel.basic); return; } foreach (var commandProp in commandProps) { ConsoleX.WriteLine($"short name : { commandProp.Command.ShortName }"); ConsoleX.WriteLine($"long name : { commandProp.Command.LongName }"); ConsoleX.WriteLine($"description : { commandProp.Command.Description } "); if (!commandProp.HasArguments()) { ConsoleX.WriteLine($"no arguments"); continue; } ConsoleX.WriteLines(commandProp.GetArgDescriptions()); } }
/// <summary> /// Destroys an existing Vultr server. /// </summary> /// <param name="server">The configuration to reference to destroy the /// server.</param> /// <param name="dryrun">Whether or not this is a dryrun. If set to true then /// provision commands will not be sent to the platform and instead messaging /// will be outputted describing what would be done.</param> public override void Destroy(Server server, bool dryrun = false) { var dcId = Client.Region.GetRegionId(server.Region); var label = server.Label; Console.WriteLine("Destroying server"); ConsoleX.WriteLine("DCID", dcId); ConsoleX.WriteLine("label", label); var existingServers = Client.Server.GetServers(); bool Predicate(KeyValuePair < string, global::Vultr.API.Models.Server> existingServer) => existingServer.Value.DCID == dcId.ToString() && existingServer.Value.label == label; if (existingServers.Servers != null && existingServers.Servers.Exists(Predicate)) { var(id, _) = existingServers.Servers.Single(Predicate); Console.WriteLine("Server with label {0} in DCID {1} exists", label, dcId); var subId = int.Parse(id); if (!dryrun) { Client.Server.DestroyServer(subId); Console.WriteLine("Deleted server {0}", subId); } } else { Console.WriteLine("Server with label {0} in DCID {1} does not exist", label, dcId); } Console.WriteLine("---"); }
public static object Invoke(this CommandProperty cmdProperty, IEnumerable <object> arguments) { try { var cmdMethod = cmdProperty._propertyInfo.PropertyType.GetMethod("Invoke"); var cmdObj = cmdProperty._propertyInfo.GetValue(cmdProperty._commandContainer); return(cmdMethod.Invoke(cmdObj, cmdProperty.CheckArguments(cmdMethod, arguments ?? new object[] { }).ToArray())); } catch (TargetParameterCountException) { ConsoleX.WriteError(new TargetParameterCountException($"The argument count for the command '{ cmdProperty.LongName ?? cmdProperty.ShortName }' does not match. " + $"Single arguments should be passed in as a single string and multiple should be passed in as an array. " + $"eg [ arg1, arg2 , arg3 ]"), ConsoleX.LogLevel.basic); return(null); } catch (Exception e) { ConsoleX.WriteError(new MethodAccessException($"There has been an unexpected error with the command '{ cmdProperty.LongName ?? cmdProperty.ShortName }'", e), ConsoleX.LogLevel.basic); return(null); } }
/// <summary> /// Provisions a new Vultr firewall. /// </summary> /// <param name="firewall">The configuration to reference to provision the /// firewall.</param> /// <param name="dryrun">Whether or not this is a dryrun. If set to true then /// provision commands will not be sent to the platform and instead messaging /// will be outputted describing what would be done.</param> public override void Provision(Firewall firewall, bool dryrun = false) { Console.WriteLine("Creating firewall"); ConsoleX.WriteLine("name", firewall.Name); var firewallGroupId = Client.Firewall.GetExistingFirewall(firewall.Name); if (!string.IsNullOrEmpty(firewallGroupId)) { Console.WriteLine("Firewall {0} with ID {1} already exists", firewall.Name, firewallGroupId); var existingRules = Client.Firewall.GetExistingRules(firewallGroupId); CreateRules(firewall, firewallGroupId, dryrun, existingRules); DeleteOldRules(firewall, firewallGroupId, existingRules, dryrun); } else { CreateRules(firewall, CreateNewFirewallGroup(firewall, dryrun), dryrun); } Console.WriteLine("---"); }
public static bool TrySearchForNames(Volunteer volunteer, ConsoleX consoleX) { // TODO Use Gender also to help with match. bool matchesFound = true; consoleX.WriteLine("Searching for matches on both First and Last name..."); var table = Volunteers.GetByBothNames(volunteer.FirstName, volunteer.LastName, volunteer.Gender); if(table.Rows.Count == 0) { consoleX.WriteLine("No matched found on both First and Last name! Trying a wider search:"); if(volunteer.Gender == GenderKind.Male) { consoleX.WriteLine("Searching for other brothers with same Last name..."); table = Volunteers.GetByLastName(volunteer.LastName, volunteer.Gender); } else { consoleX.WriteLine("Searching for other sisters with same First OR Last name..."); table = Volunteers.GetByEitherName(volunteer.FirstName, volunteer.LastName, volunteer.Gender); } } if(table.Rows.Count > 0) { consoleX.WriteLine(table.Rows.Count > 1 ? "The following matches where found:" : "The following match was found"); consoleX.WriteDataTable(table, 15); } else { matchesFound = false; consoleX.WriteLine("No matches found!"); } return matchesFound; }
public static void ShowStartUpMessage(ConsoleX consoleX) { // Display application title consoleX.WriteTitle("RBC Console, application for interfacing with RBC South Wales and Gloucestershire database"); consoleX.WriteLine("Enter a command to start (e.g. 'help')"); }
public static string WriteQuestion(string Question, MessageStatus messageStatus = MessageStatus.Question) { ConsoleX.Write($"{ Question }", messageStatus); return(Console.ReadLine()); }
/// <summary> /// Provisions a new Vultr startup script. /// </summary> /// <param name="script">The configuration to reference to provision the /// script.</param> /// <param name="dryrun">Whether or not this is a dryrun. If set to true then /// provision commands will not be sent to the platform and instead messaging /// will be outputted describing what would be done.</param> public override void Provision(Script script, bool dryrun = false) { var type = script.Type switch { ScriptType.Boot => global::Vultr.API.Models.ScriptType.boot, ScriptType.PXE => global::Vultr.API.Models.ScriptType.pxe, _ => throw new ArgumentException( $"Unknown script type {script.Type}", nameof(script)), }; Console.WriteLine("Creating script"); ConsoleX.WriteLine("name", script.Name); ConsoleX.WriteLine("type", type); ConsoleX.WriteLine("script", script.Content); var existingScripts = Client.StartupScript.GetStartupScripts(); bool Predicate(KeyValuePair <string, StartupScript> existingScript) => existingScript.Value.name == script.Name; if (existingScripts.StartupScripts != null && existingScripts.StartupScripts.Exists(Predicate)) { var(id, existingScript) = existingScripts.StartupScripts.Single(Predicate); Console.WriteLine("Script {0} with ID {1} already exists", script.Name, id); if (existingScript.type != script.Type.ToString().ToLower()) { Console.WriteLine("Script {0} type is different", script.Name); Console.WriteLine("Deleting script {0}", script.Name); if (!dryrun) { Client.StartupScript.DeleteStartupScript(id); Console.WriteLine("Deleted script {0}", script.Name); } Console.WriteLine("Creating new script called {0}", script.Name); if (!dryrun) { var result = Client.StartupScript.CreateStartupScript( script.Name, script.Content, type); Console.WriteLine("Created script with ID {0}", result.StartupScript.SCRIPTID); } } else if (existingScript.script != script.Content) { Console.WriteLine("Script {0} content is different", script.Name); Console.WriteLine("Updating script {0} content", script.Name); if (!dryrun) { Client.StartupScript.UpdateStartupScript( id, script: script.Content); Console.WriteLine("Updated script {0} content", script.Name); } } else { Console.WriteLine("Script {0} is the same. Moving on.", script.Name); } } else { if (!dryrun) { var result = Client.StartupScript.CreateStartupScript( script.Name, script.Content, type); Console.WriteLine( "Created script with ID {0}", result.StartupScript.SCRIPTID); } } Console.WriteLine("---"); }
static void Main(string[] args) { string ruleId = string.Empty, containerId = string.Empty, environmentId = string.Empty, environmentName = string.Empty; if (args == null) { Console.WriteLine("Parameters are needed"); return; } if (args.Length != 8) { Console.WriteLine("All parameters need to be provided"); return; } for (int i = 0; i < args.Length; i++) { string arg = args[i].ToLower(); switch (arg) { case "--ruleid": ruleId = args[i + 1]; break; case "--containerid": containerId = args[i + 1]; break; case "--environmentid": environmentId = args[i + 1]; break; case "--environmentname": environmentName = args[i + 1]; break; } } Guid environmentGUID; if (!Guid.TryParse(environmentId, out environmentGUID)) { Console.WriteLine("Please provide a valid environmentId"); return; } // IoC var serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection); var serviceProvider = serviceCollection.BuildServiceProvider(); var environmentService = serviceProvider.GetService <IDatabaseEnvironmentService>(); var ruleService = serviceProvider.GetService <IRuleService>(); var dataChecker = serviceProvider.GetService <IRuleExecutionService>(); var getEnvironment = environmentService.GetAsync(environmentGUID).GetAwaiter().GetResult(); if (getEnvironment == null || string.IsNullOrEmpty(getEnvironment.GetConnectionString())) { Console.WriteLine("Please provide a valid environmentId"); return; } if (getEnvironment.Name.ToLower() != environmentName) { Console.WriteLine("environmentName does not match, review it"); return; } Console.WriteLine($"Running Data Checker V{getEnvironment.Version} Session ({Guid.NewGuid()})"); Console.WriteLine(""); List <RuleBO> rules = new List <RuleBO>(); // Get all rules to execute Console.Write("Loading rules ..."); var sw = System.Diagnostics.Stopwatch.StartNew(); if (!string.IsNullOrEmpty(containerId)) { string[] listContainers = containerId.Split(","); foreach (string currentContainer in listContainers) { Guid containerGUID; if (!Guid.TryParse(currentContainer, out containerGUID)) { Console.WriteLine("Please provide a valid containerId"); return; } Console.WriteLine($"Getting rules from containerId:{currentContainer}"); rules.AddRange(ruleService.GetWithLogsByContainerIdAsync(containerGUID).GetAwaiter().GetResult()); } rules = rules.Distinct().ToList(); } if (!string.IsNullOrEmpty(ruleId)) { if (rules.Count == 0) { rules = ruleService.GetAsync().GetAwaiter().GetResult(); } Guid ruleGUID; if (!Guid.TryParse(ruleId, out ruleGUID)) { Console.WriteLine("Please provide a valid ruleId"); return; } rules = rules.Where(p => p.Id == ruleGUID).ToList(); if (rules.Count == 0) { Console.WriteLine($"Rule with Id {ruleId} not found"); return; } } sw.Stop(); Console.WriteLine($" Loaded {rules.Count()} in {sw.ElapsedMilliseconds}ms"); Console.WriteLine(""); // Execute the rules var testReuslts = dataChecker.ExecuteRulesByEnvironmentIdAsync(rules, getEnvironment).GetAwaiter().GetResult(); foreach (var result in testReuslts) { if (result.Evaluation) { ConsoleX.WriteLineSuccess($"Test {result.Rule.Id} \"{result.Rule.Name}\" executed SUCCESSFULLY! Found {result.Result} records in {result.ExecutionTimeMs} ms."); } else { ConsoleX.WriteLineError($"Test {result.Rule.Id} \"{result.Rule.Name}\" FAILED! {result.Rule.ErrorMessage.Replace("{TestResult.Result}", result.Result.ToString())}"); if (!string.IsNullOrEmpty(result.Rule.DiagnosticSql)) { ConsoleX.WriteLineInfo($"For diagnostics data run: {result.Rule.DiagnosticSql}"); } } } // TODO: Use a logging framework like the one in .net core or Log4net WriteErrorsToFile(testReuslts); Console.WriteLine("Press any key to exit."); Console.ReadKey(); Console.SetOut(Console.Out); }
/// <summary> /// Provisions a new Vultr server. /// </summary> /// <param name="server">The configuration to reference to provision the /// server.</param> /// <param name="dryrun">Whether or not this is a dryrun. If set to true then /// provision commands will not be sent to the platform and instead messaging /// will be outputted describing what would be done.</param> public override void Provision(Server server, bool dryrun = false) { var os = GetOs(server); const bool notifyActivate = false; var appId = os.Appid; var dcId = Client.Region.GetRegionId(server.Region); var enablePrivateNetwork = server.PrivateNetworking; var firewallId = GetFirewallId(server.Firewall); var isoId = os.IsoId?.ToString(); var label = server.Label; var osId = os.OsId; var scriptId = os.ScriptId; var snapshotId = os.SnapshotId; var sshKeys = GetSshKeys(server.SshKeys); var tag = server.Tag; var userdata = server.UserData.Base64Encode(); var vpsPlanId = GetPlanId(server.Plan); Console.WriteLine("Provisioning server"); ConsoleX.WriteLine("APPID", appId); ConsoleX.WriteLine("DCID", dcId); ConsoleX.WriteLine("enable_private_network", enablePrivateNetwork); ConsoleX.WriteLine("FIREWALLGROUPID", firewallId); ConsoleX.WriteLine("ISOID", isoId); ConsoleX.WriteLine("label", label); ConsoleX.WriteLine("notify_activate", notifyActivate); ConsoleX.WriteLine("OSID", osId); ConsoleX.WriteLine("SCRIPTID", scriptId); ConsoleX.WriteLine("SNAPSHOTID", snapshotId); ConsoleX.WriteLine("SSHKEYID", sshKeys); ConsoleX.WriteLine("tag", tag); ConsoleX.WriteLine("userdata", server.UserData); ConsoleX.WriteLine("VPSPLANID", vpsPlanId); var existingServers = Client.Server.GetServers(); bool Predicate(KeyValuePair < string, global::Vultr.API.Models.Server> existingServer) => existingServer.Value.DCID == dcId.ToString() && existingServer.Value.label == label; if (existingServers.Servers != null && existingServers.Servers.Exists(Predicate)) { var(id, existingServer) = existingServers.Servers.Single(Predicate); Console.WriteLine("Server with label {0} in DCID {1} already exists", label, dcId); var vultrServer = new global::Vultr.API.Models.Server { OSID = osId.ToString(), tag = tag, label = label, APPID = appId?.ToString(), DCID = dcId.ToString(), FIREWALLGROUPID = firewallId, VPSPLANID = vpsPlanId.ToString() }; // TODO: Check if userdata has changed var subId = int.Parse(id); if (!vultrServer.IsEquivalent(existingServer)) { Console.WriteLine("Server is different. Deleting server {0}", subId); if (!dryrun) { Client.Server.DestroyServer(subId); Console.WriteLine("Deleted server {0}", subId); } } else { Console.WriteLine("Server {0} is the same. Moving on.", subId); return; } } if (!dryrun) { var result = Client.Server.CreateServer( dcId, vpsPlanId, osId, APPID: appId, enable_private_network: enablePrivateNetwork, FIREWALLGROUPID: firewallId, ISOID: isoId, label: label, notify_activate: notifyActivate, SCRIPTID: scriptId, SNAPSHOTID: snapshotId, SSHKEYID: sshKeys, tag: tag, userdata: userdata ); Console.WriteLine("Provisioned server with ID {0}", result.Server.SUBID); } Console.WriteLine("---"); }
public static string[] GetFiles(ConsoleX consoleX) { consoleX.WriteLine("Press any key to select the S82 PDF files..."); Console.ReadKey(); string[] files = null; OpenFileDialog dlg = new OpenFileDialog(); dlg.Multiselect = true; dlg.Title = "Choose S82 PDF files"; dlg.Filter = "PDF Files|*.pdf"; if (dlg.ShowDialog() == DialogResult.OK) { files = dlg.FileNames; } return files; }