public FirewallConfiguration(FirewallName name, CLIOptions options, EAction defaultAction = EAction.Drop) { this.name = name; this.defaultAction = defaultAction; this.options = options; AddDefaultRules(); }
static async void Run(CLIOptions options) { IResxHandler resxHandler = new SimpleResxHandler(); ITranslator translator; if (options.APIKeyPath == null) { translator = new GoogleTranslation(); } else { translator = new GoogleTranslation(options.APIKeyPath); } var resources = resxHandler.Read(options.FilePath); var words = resources.Select(kv => kv.Value); foreach (var lge in options.TranslationLanguages) { var res = await translator.TranslateAsync(new List <string>(words), lge); var dic = new Dictionary <string, string>(); var outputFile = $"{Path.GetFileNameWithoutExtension(options.FilePath)}.{lge}{Path.GetExtension(options.FilePath)}"; for (int i = 0; i < res.Count(); i++) { dic.Add(resources.Keys.ElementAt(i), res.ElementAt(i)); } resxHandler.Create(dic, outputFile, options.OutPutPath); Console.WriteLine($"Translations finished and file created: ${outputFile}"); } }
public void Test1() { var cli = new CLIOptions() { Email = "*****@*****.**", Password = "******" }; Assert.NotNull(cli); }
/// <summary> /// The main entry point for the application. /// </summary> private static async Task Main(string[] args) { var options = new CLIOptions(); Parser.Default.ParseArguments <CLIOptions>(args) .WithParsed(r => options = r); if (options.RunBatchProcessing) { if (string.IsNullOrEmpty(options.TargetDirectory) || options.ManifestType == EManifestType.Unknown) { Log.Error("Target directory not set, or manifest type not set."); return; } // At this point, the options should be valid. Run batch processing. if (Directory.Exists(options.TargetDirectory)) { Log.Info("Generating manifest..."); var manifestGenerationHandler = new ManifestGenerationHandler(); var progressReporter = new Progress <ManifestGenerationProgressChangedEventArgs> ( e => Log.Info($"Processed file {e.Filepath} : {e.Hash} : {e.Filesize}") ); await manifestGenerationHandler.GenerateManifestAsync ( options.TargetDirectory, options.ManifestType, progressReporter, CancellationToken.None ); Log.Info("Generation finished."); } else { Log.Error("The selected directory did not exist."); } } else if (string.IsNullOrEmpty(options.TargetDirectory) && options.ManifestType == EManifestType.Unknown) { // Run a GTK UI instead of batch processing Application.Init(); SynchronizationContext.SetSynchronizationContext(new GLibSynchronizationContext()); var win = MainWindow.Create(); win.Show(); Application.Run(); } }
static void Main(string[] args) { options = new CLIOptions(); if (args != null) { if (!Parser.Default.ParseArguments(args, options)) { throw new ArgumentException($@"Cannot parse the arguments. Possible usages: {options.GetUsage()}"); } } (new MainFloydWarshallParcs()).RunModule(options); }
void run(CLIOptions opts) { ILog log = null; INATS nats = null; try { log = new dotnet_nats.log.Logger(opts.loglevel); IFactory f = new Factory(log); nats = new NATS(f, opts, log); var t = nats.Connect(); t.Wait(); if (t.Result) { if (opts.mode.Equals("pub", StringComparison.InvariantCultureIgnoreCase)) { publish(nats, opts.subject, opts.data, opts.count, log); } else if (opts.mode.Equals("sub", StringComparison.InvariantCultureIgnoreCase)) { subscribe(nats, opts.subject, opts.count, log); } else { log.Fatal("Unknown mode supplied: {0}", opts.mode); } } else { throw new Exception("Failed to connect to server"); } } catch (Exception ex) { if (log != null) { log.Error("Error processing", ex); } //throw; } finally { if (nats != null) { nats.Close(); } nats = null; } }
public static async Task <int> RunOptionsAndReturnExitCode(CLIOptions opts) { var licenseActivator = new LicenseActivator(); var debugFilePasswordPath = @"C:\XGitPrivate\pw.txt"; if (string.IsNullOrWhiteSpace(opts.Password) && File.Exists(debugFilePasswordPath)) { opts.Password = File.ReadAllText(debugFilePasswordPath).Trim(); } var exitCode = await licenseActivator.Run(opts); return(exitCode); }
private static void Main(string[] args) { CLIOptions options = new CLIOptions(); if (CommandLine.Parser.Default.ParseArguments(args, options)) { if (options.RunBatchProcessing) { if (string.IsNullOrEmpty(options.TargetDirectory) || options.ManifestType == EManifestType.Unknown) { Console.Write(options.GetUsage()); } // At this point, the options should be valid. Run batch processing. if (Directory.Exists(options.TargetDirectory)) { Log.Info("Generating manifest..."); ManifestGenerationHandler manifestGenerationHandler = new ManifestGenerationHandler(); manifestGenerationHandler.ManifestGenerationProgressChanged += OnProgressChanged; manifestGenerationHandler.ManifestGenerationFinished += OnGenerationFinished; manifestGenerationHandler.GenerateManifest(options.TargetDirectory, options.ManifestType); } else { Log.Error("The selected directory did not exist."); } } else if (string.IsNullOrEmpty(options.TargetDirectory) && options.ManifestType == EManifestType.Unknown) { // Run a GTK UI instead of batch processing Application.Init(); MainWindow win = new MainWindow(); win.Show(); Application.Run(); } else { Console.Write(options.GetUsage()); } } }
/// <summary> /// Parses command line argument options for the CLI/Docker program. /// </summary> /// <param name="options">Parsed options.</param> /// <returns>Model Analyzer configuration with parsed options.</returns> private ModelAnalyzerConfig ParseCLI(CLIOptions options) { var analyzerConfig = ParseBaseOptions(options); if (ModelAnalyzer.IsServerRunning()) { throw new ArgumentException("Inference server is already running on the default port"); } if (!Directory.Exists(options.ModelFolder)) { throw new ArgumentException("Model folder does not exist"); } analyzerConfig.ModelFolder = options.ModelFolder; return(analyzerConfig); }
internal ExpectedRejections(CLIOptions options) { // Read and process the expected rejections file, if one is present this.Options = options; this.UsingRegex = options.UseRegex; if (this.UsingRegex) { this.Expressions = new HashSet <Regex>(); } else { this.Parts = new HashSet <string>(); } if (options.ExpectedRejectionsFile != null && options.ExpectedRejectionsFile.Length > 0) { string currentFolder = Directory.GetCurrentDirectory(); this.ReadExpectedRejectionsFile(currentFolder, options.ExpectedRejectionsFile); } }
private static int DoDecompile(CLIOptions options) { OSIFile osi = null; string osiFilename = options.Inputs.ElementAt(0); string outputDirectory = options.Output == "" ? System.IO.Path.ChangeExtension(osiFilename, "") : options.Output; using (System.IO.FileStream stream = new System.IO.FileStream(osiFilename, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) using (System.IO.BinaryReader reader = new System.IO.BinaryReader(stream)) { osi = new OSIFile(reader); } if (!System.IO.Directory.Exists(outputDirectory)) { System.IO.Directory.CreateDirectory(outputDirectory); } Decompiler.DecompileOSIProject(osi, outputDirectory); return(EXIT_SUCCESS); }
public VyosConfiguration(ZoneConfig zoneConfig, CLIOptions options) { foreach (ZoneName zName in zoneConfig.Zones) { ZoneConfiguration.Add(zName, new ZoneConfiguration(zName, zoneConfig.ZoneDefinitions.GetValueOrDefault(zName, Zone.DefaultZone))); FirewallConfiguration.Add(zName, new Dictionary <ZoneName, FirewallConfiguration>()); foreach (ZoneName other in zoneConfig.Zones.Where(z => z != zName)) { var dict = FirewallConfiguration[zName]; dict.Add(other, new FirewallConfiguration($"{zName}-{other}", options)); } } foreach (var(zName, definition) in zoneConfig.ZoneDefinitions) { var pingableZones = definition.AllowPingTo == TargetDefinition.All ? TargetDefinition.GetTargetDefinition(FirewallConfiguration[zName].Keys.ToList()) : definition.AllowPingTo; foreach (var pingableZone in pingableZones) { FirewallConfiguration[zName][pingableZone.Name].AllowPing(); } var whitelistedZones = definition.AllowTrafficTo == TargetDefinition.All ? TargetDefinition.GetTargetDefinition(FirewallConfiguration[zName].Keys.ToList()) : definition.AllowTrafficTo; foreach (var whitelistedZone in whitelistedZones) { if (whitelistedZone.Name == TargetDefinition.WILDCARD) { foreach (var other in TargetDefinition.GetTargetDefinition(FirewallConfiguration[zName].Keys.ToList())) { FirewallConfiguration[zName][other.Name].AllowTraffic(whitelistedZone.AllowedPorts, whitelistedZone.AllowedAddresses); } } else { FirewallConfiguration[zName][whitelistedZone.Name].AllowTraffic(whitelistedZone.AllowedPorts, whitelistedZone.AllowedAddresses); } } } }
static async void StartEmulating(CLIOptions options) { Keyboard keyboard = new Keyboard(options.KeyboardDelay); Screen screen = new Screen(options.Scale); RAM ram = new RAM(); ram.LoadROM(options.RomPath); CPU cpu = new CPU(screen, ram, keyboard); timer = new Timer(60); timer.OnTick += () => cpu.TimerTick(); screen.OnResumed += () => timer.Restart(); UpdateTimerAsync(); while (screen.Window.IsOpen) { cpu.Tick(); screen.Render(); } }
/// <summary> /// The main entry point for the application. /// </summary> private static async Task Main(string[] args) { // Set correct working directory for compatibility with double-clicking Directory.SetCurrentDirectory(DirectoryHelpers.GetLocalDir()); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Environment.SetEnvironmentVariable("GSETTINGS_SCHEMA_DIR", "share\\glib-2.0\\schemas\\"); } var options = new CLIOptions(); Parser.Default.ParseArguments <CLIOptions>(args) .WithParsed(r => options = r) .WithNotParsed(r => options = null); if (options is null) { // Parsing probably failed, bail out return; } if (options.RunBatchProcessing) { if (string.IsNullOrEmpty(options.TargetDirectory) || options.ManifestType == EManifestType.Unknown) { Log.Error("Target directory not set, or manifest type not set."); return; } // At this point, the options should be valid. Run batch processing. if (Directory.Exists(options.TargetDirectory)) { Log.Info("Generating manifest..."); var manifestGenerationHandler = new ManifestGenerationHandler(); var progressReporter = new Progress <ManifestGenerationProgressChangedEventArgs> ( e => Log.Info($"Processed file {e.Filepath} : {e.Hash} : {e.Filesize}") ); await manifestGenerationHandler.GenerateManifestAsync ( options.TargetDirectory, options.ManifestType, progressReporter, CancellationToken.None ); Log.Info("Generation finished."); } else { Log.Error("The selected directory did not exist."); } } else if (string.IsNullOrEmpty(options.TargetDirectory) && options.ManifestType == EManifestType.Unknown) { // Run a GTK UI instead of batch processing Application.Init(); SynchronizationContext.SetSynchronizationContext(new GLibSynchronizationContext()); var win = MainWindow.Create(); win.Show(); Application.Run(); } }
void run(CLIOptions opts) { ILog log = null; INATS nats = null; try { log = new dotnet_nats.log.Logger(opts.loglevel); IFactory f = new Factory(log); nats = new NATS(f, opts, log); var t = nats.Connect(); t.Wait(); if (t.Result) { if (opts.mode.Equals("pub", StringComparison.InvariantCultureIgnoreCase)) { publish(nats, opts.subject, opts.data, opts.count, log); } else if (opts.mode.Equals("sub", StringComparison.InvariantCultureIgnoreCase)) { subscribe(nats, opts.subject, opts.count, log); } else { log.Fatal("Unknown mode supplied: {0}", opts.mode); } } else { throw new Exception("Failed to connect to server"); } } catch (Exception ex) { if (log != null) log.Error("Error processing", ex); //throw; } finally { if (nats != null) nats.Close(); nats = null; } }
/// <summary> /// Initializes a new instance of the <see cref="RejectionTracer"/> class. /// </summary> /// <param name="derivedInfo">The catalog and config associated with the input files.</param> /// <param name="arguments">The arguments specified by the user.</param> internal RejectionTracer(ConfigCreator derivedInfo, CLIOptions arguments) : base(derivedInfo, arguments) { this.GenerateNodeGraph(); }
public async Task <int> Run(CLIOptions cliOptions) { if (!File.Exists(cliOptions.LicenseFile)) { Console.WriteLine($"Error: File not found: ${cliOptions.LicenseFile}"); if (cliOptions.LicenseFile.StartsWith("'")) { Console.WriteLine("' is not supported for the LicenseFile path. Please use \""); } throw new FileNotFoundException(cliOptions.LicenseFile); } var slowerTypeOptions = new TypeOptions() { Delay = 5 }; Console.WriteLine("Downloading browser"); var refInfo = await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision); Console.WriteLine($"Obtained Chrome: {refInfo.Revision}"); string[] args = Array.Empty <string>(); if (Environment.OSVersion.Platform == PlatformID.Unix) { Console.WriteLine($"Disabling Chrome Sandbox because we're running in a Docker container..."); args = new string[] { "--no-sandbox", "--disable-setuid-sandbox" }; } using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = !cliOptions.ShowWindow, Args = args, })) { Console.WriteLine("Opening page..."); using (var page = await browser.NewPageAsync()) { await page.SetViewportAsync(new ViewPortOptions() { Width = 1280, Height = 1024 }); await page.GoToAsync(Constants.UnityLicenseUrl); try { //Login await page.WaitForSelectorAsync("#conversations_create_session_form_email"); await page.WaitForSelectorAsync("#conversations_create_session_form_password"); Console.WriteLine("Logging in..."); await Task.Delay(500); //await page.TypeAsync("#conversations_create_session_form_email", cliOptions.Email, slowerTypeOptions); //await page.TypeAsync("#conversations_create_session_form_password", cliOptions.Password, slowerTypeOptions); await page.EvaluateExpressionAsync($"document.querySelector('#conversations_create_session_form_email').value = \"{cliOptions.Email}\""); await page.EvaluateExpressionAsync($"document.querySelector('#conversations_create_session_form_password').value = \"{cliOptions.Password}\""); await page.ClickAsync("#new_conversations_create_session_form input[value='Sign in']"); await page.WaitForExpressionAsync("document.querySelectorAll('#conversations_tfa_required_form_verify_code, #licenseFile').length > 0 || document.querySelectorAll(\"button[name='conversations_accept_updated_tos_form[accept]'\").length > 0"); //await page.WaitForAnySelectors(null, "#conversations_accept_updated_tos_form[accept]", "document.querySelectorAll('#conversations_tfa_required_form_verify_code, #licenseFile').length"); await AcceptTosIfRequired(page); var twoFactorBox = await page.QuerySelectorAsync("#conversations_tfa_required_form_verify_code"); if (twoFactorBox != null) { //2fa Console.WriteLine("Logging in using 2fa..."); var code = VipAccess.CreateCurrentTotpKey(cliOptions.Secret2fa); Console.WriteLine($"Using code: {code}"); //await twoFactorBox.TypeAsync(code, slowerTypeOptions); await page.EvaluateExpressionAsync($"document.querySelector('#conversations_tfa_required_form_verify_code').value = \"{code}\""); await page.ClickAsync("input[value='Verify']"); } await page.WaitForExpressionAsync("document.querySelectorAll('#licenseFile').length > 0 || document.querySelectorAll(\"button[name='conversations_accept_updated_tos_form[accept]'\").length > 0"); await AcceptTosIfRequired(page); //Upload file await page.WaitForSelectorAsync("#licenseFile"); Console.WriteLine("Uploading file..."); var fileChooserTask = page.WaitForFileChooserAsync(); await page.ClickAsync("#licenseFile"); var fileChooser = await fileChooserTask; await fileChooser.AcceptAsync(cliOptions.LicenseFile); await page.ClickAsync("input[value='Next']"); //Activate your license var unityPersonalEditionButton = await page.WaitForSelectorAsync("label[for='type_personal']"); Console.WriteLine("Selecting edition..."); await unityPersonalEditionButton.ClickAsync(); var notUseUnityInProfessionalCapacity = await page.WaitForSelectorAsync("label[for='option3']"); await notUseUnityInProfessionalCapacity.ClickAsync(); var nextButton = await page.WaitForSelectorAsync(".selected input[value='Next']"); await nextButton.ClickAsync(); //Download license file await page.WaitForSelectorAsync("input[value='Download license file']"); Console.WriteLine("Downloading license file..."); var downloadManager = new DownloadManager(Directory.GetCurrentDirectory()); await downloadManager.SetupPageAsync(page); await page.ClickAsync("input[value='Download license file']"); var response = await page.WaitForResponseAsync(r => r.Url.Equals($"https://license.unity3d.com/genesis/activation/download-license", StringComparison.OrdinalIgnoreCase)); var data = await response.JsonAsync(); var xmlData = data["xml"].ToString(); var fileName = data["name"].ToString(); File.WriteAllText("Unity_lic.ulf", xmlData); Console.WriteLine($"File 'Unity_lic.ulf' created. Size: {new FileInfo("Unity_lic.ulf").Length}"); return(0); } catch (Exception ex) { Console.WriteLine($"Error: {ex}"); var ssstream = await page.ScreenshotStreamAsync(); var curDir = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); var outputFile = Path.Combine(curDir, "error.png"); Console.WriteLine($"Writing error screenshot to: {outputFile}"); using (var fileStream = File.Create(outputFile)) { ssstream.Seek(0, SeekOrigin.Begin); ssstream.CopyTo(fileStream); } Console.WriteLine($"Done writing error screenshot to: {outputFile}"); return(1); } } } }
static void Run(CLIOptions opts) { if ((string.IsNullOrEmpty(opts.SprayPassword)) && (opts.Action == LDAPAction.SPRAY_USERS)) { Console.WriteLine("Please supply a password to spray: "); var response = Console.ReadLine(); if (!string.IsNullOrEmpty(response)) { opts.SprayPassword = response; } else { Console.WriteLine($"Missing --spraypassword argument."); Environment.Exit(0); } } if ((string.IsNullOrEmpty(opts.PolicyName)) && (opts.Action == LDAPAction.GET_POLICY_USERS)) { Console.WriteLine("Please supply a policy name: "); var response = Console.ReadLine(); if (!string.IsNullOrEmpty(response)) { opts.PolicyName = response; } else { Console.WriteLine($"Missing --policy argument."); Environment.Exit(0); } } if ((string.IsNullOrEmpty(opts.OutputPath)) && (opts.Quiet)) { Console.WriteLine("Missing --output argument while supplying --quiet, please supply an output directory: "); var response = Console.ReadLine(); if (!string.IsNullOrEmpty(response)) { opts.OutputPath = response; } else { Console.WriteLine($"Missing --output argument while using --quiet."); Environment.Exit(0); } } var config = new LDAPConfig() { DomainName = opts.DomainName, DomainController = opts.DomainController, DomainUsername = opts.DomainUsername, DomainPassword = opts.DomainPassword, SprayPassword = opts.SprayPassword, Auto = opts.Auto, OutputPath = opts.OutputPath, ExcludeFilePath = opts.ExcludeFilePath, SaveOutput = !string.IsNullOrEmpty(opts.OutputPath), ExcludeUsers = !string.IsNullOrEmpty(opts.ExcludeFilePath), Logger = new ConsoleLogger(opts.Quiet) }; switch (opts.Nozzle) { case NozzleType.LDAP: var ldapNozzle = new LDAPNozzle(config); switch (opts.Action) { case LDAPAction.GET_POLICIES: ldapNozzle.DisplayPolicies(); break; case LDAPAction.GET_POLICY_USERS: ldapNozzle.DisplayPolicyUsers(opts.PolicyName, false); break; case LDAPAction.GET_ENABLED_USERS: ldapNozzle.DisplayEnabledUsers(); break; case LDAPAction.SPRAY_USERS: ldapNozzle.Start(); break; } break; } }
/// <summary> /// Initializes a new instance of the <see cref="Command"/> class. /// </summary> /// <param name="derivedInfo">The ConfigCreator for the input files.</param> /// <param name="arguments">The command line arguments from the user.</param> internal Command(ConfigCreator derivedInfo, CLIOptions arguments) { this.Creator = derivedInfo; this.Options = arguments; }
/// <summary> /// Initializes a new instance of the <see cref="MatchChecker"/> class. /// </summary> /// <param name="derivedInfo">ConfigCreator for the specified input parts.</param> /// <param name="arguments">Input arguments specified by the user.</param> internal MatchChecker(ConfigCreator derivedInfo, CLIOptions arguments) : base(derivedInfo, arguments) { }
/// <summary> /// Initializes a new instance of the <see cref="PartInfo"/> class. /// </summary> /// <param name="derivedInfo">ConfigCreator for input parts.</param> /// <param name="arguments">Input arguments specified by the user.</param> internal PartInfo(ConfigCreator derivedInfo, CLIOptions arguments) : base(derivedInfo, arguments) { }
private static int DoCompile(CLIOptions options) { List <CompileMessage> messages = new List <CompileMessage>(); // Translate CLIOptions into compiler options Compiler.Settings settings = new Compiler.Settings(); settings.EmitLineNumbers = options.EmitLineNumbers; string[] versionNumberParts = options.OSIVersion.Split('.'); if (versionNumberParts.Length == 2) { settings.VersionMajor = Int32.Parse(versionNumberParts[0]); settings.VersionMinor = Int32.Parse(versionNumberParts[1]); } else { messages.Add(new CompileMessage("Invalid OSI version. Version number should be specified like '4.1'.", "LSSC001", CompileMessage.MessageSeverity.Warning, new SourceSpan("", 0, null, 0))); } // Check options.Inputs for directory names, and replace them with the files they contain, considering the option to be recursive List <string> inputs = new List <string>(); foreach (string input in options.Inputs) { if (System.IO.Directory.Exists(input)) { EnumerateDirectory(input, inputs, options.RecurseDirectories); } else if (System.IO.File.Exists(input)) { inputs.Add(input); } } Compiler.Result result = Compiler.CompileFiles(inputs); messages.AddRange(result.Messages); int errorCount = 0; foreach (CompileMessage message in messages) { Console.WriteLine(message.ToString()); if (message.Severity >= CompileMessage.MessageSeverity.Error) { errorCount++; } } if (errorCount > 0) { Console.WriteLine("Finished with " + errorCount + " errors."); return(EXIT_SYNTAX_ERROR); } else { string outputFilename = System.IO.Path.GetFullPath(options.Output == "" ? "./base.osi" : options.Output); if (System.IO.File.Exists(outputFilename) && !options.AllowOverwrite) { Console.WriteLine("Aborted - file '" + outputFilename + "' already exists. (Specify -y to overwrite.)"); return(EXIT_OUTPUT_EXISTS); } else { try { using (System.IO.FileStream stream = new System.IO.FileStream(outputFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Read)) using (System.IO.BinaryWriter writer = new System.IO.BinaryWriter(stream)) { result.OSI.Write(writer); } Console.WriteLine("Compiled into '" + outputFilename + "'."); return(EXIT_SUCCESS); } catch (System.IO.IOException exception) { Console.WriteLine("Failed to write result to '" + outputFilename + "': " + exception.ToString()); return(EXIT_IO_ERROR); } } } }