/// <summary> /// Process the command line arguments. /// </summary> /// <param name="args">commandline arguments.</param> /// <returns>Command line options.</returns> private static CommandLineOptions ProcessCommandLine(string[] args) { CommandLineOptions filterReadsParams = new CommandLineOptions(); CommandLineArguments parser = new CommandLineArguments(); // Add parameters parser.Parameter(ArgumentType.DefaultArgument, "Filename", ArgumentValueType.String, "", "Input fasta file to filter reads."); parser.Parameter(ArgumentType.Optional, "AmbiguousOutputFile", ArgumentValueType.String, "a", "Filtered ambiguous reads output file"); parser.Parameter(ArgumentType.Optional, "OutputFile", ArgumentValueType.String, "o", "Output file"); parser.Parameter(ArgumentType.Optional, "FilterAmbiguousReads", ArgumentValueType.Bool, "fa", "Filter ambiguous reads"); parser.Parameter(ArgumentType.Optional, "Verbose", ArgumentValueType.Bool, "v", "Display Verbose logging"); parser.Parameter(ArgumentType.Optional, "Help", ArgumentValueType.Bool, "h", "Show the help information with program options and a description of program operation."); try { parser.Parse(args, filterReadsParams); } catch (Exception e) { Console.Error.WriteLine("\nException while processing Command Line arguments [{0}]", e.Message); Console.Error.WriteLine(Properties.Resource.FilterReadsUtilHelp); Environment.Exit(-1); } if (filterReadsParams.OutputFile != null) { // redirect stdout FileStream fsConsoleOut = new FileStream(filterReadsParams.OutputFile, FileMode.Create); StreamWriter swConsoleOut = new StreamWriter(fsConsoleOut); Console.SetOut(swConsoleOut); swConsoleOut.AutoFlush = true; } return (filterReadsParams); }
private static void ProcessAssembly( CommandLineOptions options ) { AssemblyDefinition assembly = ReadAssembly( options.AssemblyPath ); string attributeToStrip = "System.Runtime.CompilerServices.ExtensionAttribute"; var query = assembly.MainModule.Types.Where( x => x.FullName == attributeToStrip ); if (!query.Any()) { Console.WriteLine( "Nothing to do, no definition of {0} found.", attributeToStrip ); Console.WriteLine( "Just round-tripping the assembly." ); } else { AttributeStripper stripper = new AttributeStripper( query.Single() ); stripper.Process( assembly ); } PrepareOutputDirectory( options.OutputDirectory ); string targetPath = Path.Combine( options.OutputDirectory, Path.GetFileName( options.AssemblyPath ) ); StrongNameKeyPair snk = options.SigningKeyPairFile != null ? new StrongNameKeyPair( File.ReadAllBytes( options.SigningKeyPairFile ) ) : null; WriteAssembly( assembly, targetPath, snk ); }
public static CommandLineOptions ParseArgs(string[] args) { var options = new CommandLineOptions(); var parser = new CommandLineParser(); parser.AddOption("--debug"); parser.AddOption("--release"); parser.Parse(args); var s = parser.GetArgument(0); if (s != null) { options.ScriptName = s; options.Debug = false; options.UserArguments = Runtime.AsList(parser.GetArgumentArray(1)); } if (parser.GetOption("release") != null) { options.Debug = false; } if (parser.GetOption("debug") != null) { options.Debug = true; } return options; }
public void WhenTimeoutIsSpecified_RunSettingsIncludeIt() { var options = new CommandLineOptions("test.dll", "--timeout=50"); var settings = TextUI.MakeRunSettings(options); Assert.That(settings.ContainsKey("DefaultTimeout")); Assert.AreEqual(50, settings["DefaultTimeout"]); }
public void WhenWorkDirectoryIsSpecified_RunSettingsIncludeIt() { var options = new CommandLineOptions("test.dll", "--work=results"); var settings = TextUI.MakeRunSettings(options); Assert.That(settings.ContainsKey("WorkDirectory")); Assert.AreEqual(Path.GetFullPath("results"), settings["WorkDirectory"]); }
public void WhenSeedIsSpecified_RunSettingsIncludeIt() { var options = new CommandLineOptions("test.dll", "--seed=1234"); var settings = TextUI.MakeRunSettings(options); Assert.That(settings.ContainsKey("RandomSeed")); Assert.AreEqual(1234, settings["RandomSeed"]); }
public GitHubWorker(CommandLineOptions options) { _options = options; var credentials = new Credentials(_options.GitHubAccessToken); var connection = new Connection(new ProductHeaderValue("CodeplexIssueMigrator")) { Credentials = credentials }; _gitHubClient = new GitHubClient(connection); }
/// <summary> /// Set the options to be used to coonfigure the current template /// </summary> /// <param name="options">The options to be used to configure the current template.</param> /// <returns> /// Gets a reference to the parent ITemplateConfigurator object /// </returns> public ITemplateConfigurator Options(CommandLineOptions options) { Condition.Requires(options, "options").IsNotNull(); options.ProcessOptions(); this.CurrentOptions = options; return this.templateConfigurator; }
/// <summary> /// /// </summary> public frmMain(CommandLineOptions cmdLineOpt) { //btGRMain.frmLogin f = new btGRMain.frmLogin(); //f.ShowDialog(); InitializeComponent(); this.Text = strings.AppText; this._cmdLineOpt = cmdLineOpt; this.mnu2Data.Visible = Config.Default.Show2DataGather; }
public void when_not_specifying_the_solution_path_the_parser_should_return_true_because_it_is_optional() { var options = new CommandLineOptions(); string[] args = new[] { "-p", "product", "-o de" }; ICommandLineParser parser = new CommandLineParser(); bool res = parser.ParseArguments(args, options); res.Should().BeTrue(); }
public void when_specifying_an_invalid_argument_the_parser_should_return_false() { var options = new CommandLineOptions(); string[] args = new[] { "-de", "-o de" }; ICommandLineParser parser = new CommandLineParser(); bool parserResults = parser.ParseArguments(args, options); parserResults.Should().BeFalse(); }
public void when_specifying_the_ProductName_argument_with_a_value_the_parser_method_should_return_true() { var options = new CommandLineOptions(); string[] args = new[] { "-p hhh", "-o de" }; ICommandLineParser parser = new CommandLineParser(); bool parserResults = parser.ParseArguments(args, options); parserResults.Should().BeTrue(); }
public void when_specifying_the_solution_path_with_a_valid_value_the_parser_should_return_true() { var options = new CommandLineOptions(); string[] args = new[] { "-s", "solpath", "-p", "product", "-o de" }; ICommandLineParser parser = new CommandLineParser(); bool res = parser.ParseArguments(args, options); res.Should().BeTrue(); }
public void when_specifying_the_solution_path_with_incomplete_arguments_the_parser_should_return_false() { var options = new CommandLineOptions(); string[] args = new[] { "-s", "-p", "product", "-o de" }; ICommandLineParser parser = new CommandLineParser(); bool res = parser.ParseArguments(args, options); res.Should().BeFalse(); }
/// <summary> /// Entry point /// </summary> public static int Main(string[] args) { #if DEBUG for (var i = 0; i < args.Length; i++) { Console.WriteLine("args[{0}]={1}", i, args[i]); } #endif try { #if DEBUG if (args.Length == 0) { var folder = Path.GetDirectoryName(typeof(Program).Assembly.Location); var rootFolder = Path.GetFullPath(Path.Combine(folder, @"..\..\..\..")); folder = Path.Combine(rootFolder, @"RegressionTests\Simple"); args = new[] { ToolOptions.InputManifest.CreateArg(Path.Combine(folder, @"Out\AndroidManifest.xml")), ToolOptions.InputCodeFile.CreateArg(Path.Combine(folder, @"Out\Code\classes.dex")), ToolOptions.OutputPackage.CreateArg(Path.Combine(folder, @"Out\Simple.apk")), ToolOptions.CertificateThumbprint.CreateArg("EF53D093F360F8941566B7924BFD11027C88FABB") }; } #endif // Parse command line options var options = new CommandLineOptions(args); if (options.ShowHelp) { options.Usage(); return 2; } // Compile now var builder = new ApkBuilder(options.ApkFile); builder.ManifestPath = options.ManifestFile; builder.DexFiles.AddRange(options.DexFiles); builder.ResourcesFolder = options.ResourcesFolder; builder.PfxFile = options.PfxFile; builder.PfxPassword = options.PfxPassword; builder.CertificateThumbprint = options.CertificateThumbprint; builder.Build(); return 0; } catch (Exception ex) { Console.WriteLine("Error: {0}", ex.Message); #if DEBUG Console.WriteLine(ex.StackTrace); #endif return 1; } }
public void ProcessArgs_InvalidOptionsSpace_ExceptionThrown() { // arrange CommandLineOptions expected = new CommandLineOptions(); string[] args = { }; clp.Options = "azAz09: "; // act actual = clp.ProcessArgs(args); // assert -- should not get here }
private static void Main(string[] args) { var options = new CommandLineOptions(); Parser.Default.ParseArguments(args, options); if (string.IsNullOrWhiteSpace(options.DataDirectory)) { Console.WriteLine("Parameter directory not specified."); return; } if (string.IsNullOrWhiteSpace(options.Host)) { Console.WriteLine("Parameter host not specified."); return; } var nodesXmlParser = new NodesXmlParser(); var nodesLoader = new NodesLoader(nodesXmlParser); var httpClient = new BasicHttpClient(); var uploader = new NodeUploader(httpClient, options.Host); Console.WriteLine("Loading files from {0}", options.DataDirectory); NodeContainer nodes; try { nodes = nodesLoader.ParseFiles(options.DataDirectory).Result; } catch (Exception e) { Console.WriteLine("Error: {0}", e.Message); return; } try { Console.WriteLine(uploader.Delete().Result); Console.WriteLine(uploader.Upload(nodes).Result); } catch (Exception e) { if (e.InnerException != null) { Console.WriteLine("Error: {0}", e.InnerException.Message); } else { Console.WriteLine("Error: {0}", e.InnerException); } return; } Console.WriteLine("Successfully uploaded."); }
public void ProcessArgs_NoneSupplied_NoneReturned() { // arrange CommandLineOptions expected = new CommandLineOptions(); string[] args = { }; // act actual = clp.ProcessArgs(args); // assert Assert.AreEqual(expected.GetNonOptions().Count, actual.GetNonOptions().Count); Assert.AreEqual(expected.GetOptionCount(), actual.GetOptionCount()); }
public static int Main( string[] args ) { Console.WriteLine(); CommandLineOptions options = new CommandLineOptions(); ICommandLineParser parser = new CommandLineParser( new CommandLineParserSettings( Console.Out ) ); if (!parser.ParseArguments( args, options )) return 1; ProcessAssembly( options ); return 0; }
/// <summary> /// Parses commandline arguments into a generic CommandLineOptions object. /// /// Supported Format /// /// [parameter1 parameter2 parameter3] /flag /flagWithValue value /// [parameter1 parameter2 parameter3] -flag -flagWithValue value /// [parameter1 parameter2 parameter3] --flag --flagWithValue value /// /// /// Specifing a flag without a value is equally as setting it to true /// Example /// '-quiet' has the same effect '-quiet true' /// /// </summary> /// <param name="args"></param> /// <returns></returns> public static CommandLineOptions ParseCommandLineArgs(string[] args) { var commandLineOptions = new CommandLineOptions(); var flagParser = new Regex("^[/|-](.*)$"); string currentFlag = null; for (int i = 0; i != args.Length; ++i) { string current = args[i]; if (flagParser.IsMatch(current)) { if (currentFlag != null) { commandLineOptions.SetParameterEnabled(currentFlag); } currentFlag = flagParser.Match(current).Groups[1].Value; } else { // Simple Argument without any flag/id if (currentFlag == null) { commandLineOptions.AddArgument(current); } else { commandLineOptions.SetParameterValue(currentFlag, current); currentFlag = null; } } } // If last param is flag without param if (currentFlag != null) { commandLineOptions.SetParameterEnabled(currentFlag); } return commandLineOptions; }
private static void Main(string[] args) { _imuTrigger.motion = new GestureDescription(); _imuTrigger.motion.name = "IMU_WAVE"; _stopTask = false; Node info = null; var options = new CommandLineOptions(); try { if (args.Length > 0) { Parser.Default.ParseArguments(args, options); info = MessageUtil.RequestProtoMessage<Node>(options.ParameterServer, options.Name); if (info != null) { } } } catch (Exception ex) { Console.WriteLine("Retrieving the parameter from server failed : {0}", ex.StackTrace); } try { if (info != null) { SendMotionRecognitionModuleInfo(info, options.ParameterServer); var tasks = new List<Task>(); tasks.Add(Task.Run(() => CollectData(info))); tasks.Add(Task.Run(() => PublishData(info))); Task.WaitAll(tasks.ToArray()); } } catch (Exception ex) { Console.WriteLine("Exception : {0}", ex.StackTrace); } Console.WriteLine("About to exit. Press enter to close the console window."); Console.Read(); }
static void Main(string[] args) { // Setup _defaultLogger = LogManager.GetLogger("Default"); EnsureWorkingAreaExists(); // Parse command line options CommandLineOptions options = new CommandLineOptions(); Parser.Default.ParseArguments(args, options); Job currentJob = JobHelper.GetJob(options.JobId, _defaultLogger); if (currentJob == null) ExitProgramWithError("Job not found"); // Intialise deployment context. DeploymentContext deploymentContext = DeploymentContextFactory.CreateContextForJob(currentJob); _statusUpdater = new DeploymentStatusUpdater(deploymentContext); // Checkout code from source control _statusUpdater.UpdateStatus(DeploymentStatuses.VscCheckout); GitProvider gitProvider = new GitProvider(deploymentContext); bool checkoutSuccess = gitProvider.Checkout(); if (!checkoutSuccess) ExitProgramWithError("Git checkout was unsuccessful.", currentJob); // Load deployment conifguration bool configLoadSuccess = ConfigLoader.LoadConfigurationIntoContext(deploymentContext); if (!configLoadSuccess) ExitProgramWithError("Could not load configuration", currentJob); // Run Tasks bool taskRunResult = DeploymentTaskRunner.RunTasks(deploymentContext, _statusUpdater); if (taskRunResult) { _statusUpdater.Dispose(); JobHelper.MarkJobAsComplete(currentJob); } else { ExitProgramWithError("Task did not complete.", currentJob); } }
public void WhenInvalidFlagSpecified_ThenParseRaisesInvalidCommandLineException() { Assert.Throws <InvalidCommandLineException>( () => CommandLineOptions.Parse( new[] { "/" })); }
/// <summary> /// Sets Options instance to be used by other membres. /// </summary> /// <param name="options"></param> public FileHelper(CommandLineOptions options) { CommandLineOptions = options; }
public void Init() { clo = new CommandLineOptions(); }
static void Main(string[] args) { // Usage: // SampleCode.exe -u "Your Account Username" -k "Your Account Key" --url "http://site.com/your-webpage" // OR // SampleCode.exe -u "Your Account Username" -k "Your Account Key" --local-document "C:\your-directory\document.doc" CommandLineOptions options = new CommandLineOptions(); if (!CommandLine.Parser.Default.ParseArguments(args, options)) Environment.Exit(1); else if ((options.URL == null && options.LocalFile == null) || (options.URL != null && options.LocalFile != null)) { Console.WriteLine("Error: You can speicfy either a URL or a local document to scan. For more information please enter '--help'."); Environment.Exit(1); } // For more information, visit Copyleaks "How-To page": https://api.copyleaks.com/Guides/HowToUse // Creating Copyleaks account: https://copyleaks.com/Account/Signup // Use your Copyleaks account information. // Generate your Account API Key: https://copyleaks.com/Account/Manage Scanner scanner = new Scanner(options.Username, options.ApiKey); uint creditsBalance = scanner.Credits; if (creditsBalance == 0) { Console.WriteLine("ERROR: You do not have enough credits to complete this scan. Your current credits balance = {0}).", creditsBalance); Environment.Exit(2); } Uri httpCallback = null; if (options.HttpCallback != null) { // Http callback example value: // https://your-website.com/copyleaks-gateway?id={PID} // Copyleaks server will replace the "{PID}" token with the actual process id. if (!Uri.TryCreate(options.HttpCallback, UriKind.Absolute, out httpCallback)) { Console.WriteLine("ERROR: Bad Http-Callback."); Environment.Exit(3); } } try { ResultRecord[] results; if (options.URL != null) { Uri uri; if (!Uri.TryCreate(options.URL, UriKind.Absolute, out uri)) { Console.WriteLine("ERROR: The URL ('{0}') is invalid.", options.URL); // Bad URL format. Environment.Exit(1); } results = scanner.ScanUrl(uri, httpCallback); } else { if (!File.Exists(options.LocalFile)) { Console.WriteLine("ERROR: The file '{0}' does not exist.", options.LocalFile); // Bad URL format. Environment.Exit(1); } results = scanner.ScanLocalTextualFile(new FileInfo(options.LocalFile), httpCallback); } if (results.Length == 0) { Console.WriteLine("\tNo results."); } else { for (int i = 0; i < results.Length; ++i) { Console.WriteLine(); Console.WriteLine("Result {0}:", i + 1); Console.WriteLine("Url: {0}", results[i].URL); Console.WriteLine("Precents: {0}", results[i].Precents); Console.WriteLine("CopiedWords: {0}", results[i].NumberOfCopiedWords); } } } catch (UnauthorizedAccessException e) { Console.WriteLine("\tFailed!"); Console.WriteLine("+Error Description:"); Console.WriteLine("{0}", e.Message); } catch (CommandFailedException theError) { Console.WriteLine("\tFailed!"); Console.WriteLine("+Error Description:"); Console.WriteLine("{0}", theError.Message); } catch (Exception ex) { Console.WriteLine("\tFailed!"); Console.WriteLine("Unhandled Exception"); Console.WriteLine(ex); } Environment.Exit(0); }
public DirectoryInfo GetOutputDirectory(CommandLineOptions options) { return new DirectoryInfo(options.GetOutput()); }
internal CLIRunSettingsArgumentExecutor(IRunSettingsProvider runSettingsManager, CommandLineOptions commandLineOptions) { this.runSettingsManager = runSettingsManager; this.commandLineOptions = commandLineOptions; }
/// <summary> /// Get a build asset registry only remote for a specific repo. /// </summary> /// <param name="options">Command line options</param> /// <param name="logger">Logger</param> /// <returns>New remote</returns> public static IRemote GetBarOnlyRemote(CommandLineOptions options, ILogger logger) { return(GetRemote(options, null, logger)); }
public DirectoryInfo GetOutputDirectory(CommandLineOptions options) { return(new DirectoryInfo(options.GetInput())); }
private static void ProcessDiagrams(CommandLineOptions options) { // Read and verify passed command-line options: string outputFolder = Directory.GetCurrentDirectory(); if (!string.IsNullOrWhiteSpace(options.OutputFolder) && options.OutputFolder != CommandLineOptions.CurrentDirectoryMark) { outputFolder = Directory.CreateDirectory(options.OutputFolder).FullName; } var diagramFiles = PathTools.GatherFiles(options.VisioFiles).ToArray(); string format = options.Format.TrimStart('.'); if (!SupportedFormats.Contains(format)) { string expected = string.Join(", ", SupportedFormats.ToArray()); throw new ArgumentException($"Passed unknown format '{format}', expected one of {{ {expected} }}."); } // We have options in check, so start actual export now: foreach (var diagramFile in diagramFiles) { Console.WriteLine($"Exporting '{diagramFile.FullName}':"); ExportPages(diagramFile.FullName, outputFolder, format); Console.WriteLine($"Finished '{diagramFile}'."); Console.WriteLine(); } }
static CommandLineOptions ProcessCommandLine(string[] args) { CommandLineOptions myArgs = new CommandLineOptions(); CommandLineArguments parser = new CommandLineArguments(); AddParameters(parser); try { parser.Parse(args, myArgs); } catch (Exception e) { Console.Error.WriteLine("\nException while processing Command Line arguments [{0}]", e.Message); Environment.Exit(-1); } if (myArgs.help) { Console.WriteLine(Resources.MumUtilHelp); Environment.Exit(-1); } /* * Process all the arguments for 'semantic' correctness */ if ((myArgs.maxmatch && myArgs.mum) || (myArgs.maxmatch && myArgs.mumreference) || (myArgs.mum && myArgs.mumreference) ) { Console.Error.WriteLine("\nError: only one of -maxmatch, -mum, -mumreference options can be specified."); Environment.Exit(-1); } if (!myArgs.mumreference && !myArgs.mum && !myArgs.maxmatch) { myArgs.mumreference = true; } if ((myArgs.fileList == null) || (myArgs.fileList.Length < 2)) { Console.Error.WriteLine("\nError: A reference file and at least 1 query file are required."); Environment.Exit(-1); } if ((myArgs.length <= 0) || (myArgs.length >= (8 * 1024))) // TODO: What are real reasonable mum length limits? { Console.Error.WriteLine("\nError: mum length must be between 1 and 1024."); Environment.Exit(-1); } if (myArgs.both && myArgs.reverseOnly) { Console.Error.WriteLine("\nError: only one of -both or -reverseOnly options can be specified."); Environment.Exit(-1); } if (myArgs.c && (!myArgs.both && !myArgs.reverseOnly)) { Console.Error.WriteLine("\nError: c requires one of either /b or /r options."); Environment.Exit(-1); } if (myArgs.outputFile != null) { // redirect stdout fsConsoleOut = new FileStream(myArgs.outputFile, FileMode.Create); swConsoleOut = new StreamWriter(fsConsoleOut); Console.SetOut(swConsoleOut); swConsoleOut.AutoFlush = true; } return(myArgs); }
public static void setupCmdLineParser() { // THIS IS A HACK. Boogie's methods // depend on its command line parser being set! CommandLineOptions.Install(new Microsoft.Boogie.CommandLineOptions()); }
public void WhenUrlIsInvalid_ThenParseRaisesInvalidCommandLineException() { Assert.Throws <InvalidCommandLineException>( () => CommandLineOptions.Parse( new[] { "/url", "notaurl" })); }
public FileInfo[] GetInputFiles(CommandLineOptions options) { return(GetInputFilesInDirectory(options.GetInput())); }
public void WhenUrlMissesArgument_ThenParseRaisesInvalidCommandLineException() { Assert.Throws <InvalidCommandLineException>( () => CommandLineOptions.Parse( new[] { "/url" })); }
public bool AreCompatibile(CommandLineOptions options) { return(options.GetOutput() == null && Directory.Exists(options.GetInput())); }
public void CreateOptions() { options = new CommandLineOptions("-"); }
public TicExtraction(CommandLineOptions options) : base(options) { }
/// <summary> /// Initializes a new instance of the <see cref="ApplicationController"/> class. /// </summary> /// <param name="arguments">The arguments.</param> public ApplicationController(string[] arguments) { this.arguments = arguments; this.options = new CommandLineOptions(); }
/// <inheritdoc /> protected override async Task <CacheExecutorResults> InternalExecuteAsync(CommandLineOptions options) { var v1App = PreRegisteredApps.CommonCacheTestV1; string resource = PreRegisteredApps.MsGraph; string[] scopes = new[] { resource + "/user.read" }; Logger.LogCallback = (LogLevel level, string message, bool containsPii) => { Console.WriteLine("{0}: {1}", level, message); }; CommonCacheTestUtils.EnsureCacheFileDirectoryExists(); var tokenCache = new TokenCache(); FileBasedTokenCacheHelper.ConfigureUserCache( options.CacheStorageType, tokenCache, CommonCacheTestUtils.AdalV3CacheFilePath, CommonCacheTestUtils.MsalV2CacheFilePath); var app = new PublicClientApplication(v1App.ClientId, v1App.Authority, tokenCache) { ValidateAuthority = true }; IEnumerable <IAccount> accounts = await app.GetAccountsAsync().ConfigureAwait(false); try { var result = await app.AcquireTokenSilentAsync(scopes, accounts.FirstOrDefault(), app.Authority, false).ConfigureAwait(false); Console.WriteLine($"got token for '{result.Account.Username}' from the cache"); return(new CacheExecutorResults(result.Account.Username, true)); } catch (MsalUiRequiredException) { var result = await app.AcquireTokenByUsernamePasswordAsync(scopes, options.Username, options.UserPassword.ToSecureString()).ConfigureAwait(false); Console.WriteLine($"got token for '{result.Account.Username}' without the cache"); return(new CacheExecutorResults(result.Account.Username, false)); } }
static void Main(string[] args) { TinyIoCContainer.Current.Register(ConfigManager.GetConfigurationFromDisk()); TinyIoCContainer.Current.Register(typeof(ConsoleManager)).AsSingleton(); TinyIoCContainer.Current.Register<Deployer>().AsSingleton(); AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException; var config = TinyIoCContainer.Current.Resolve<ServantAgentConfiguration>(); #if !DEBUG if (Environment.UserInteractive) { var options = new CommandLineOptions(); if (CommandLine.Parser.Default.ParseArguments(args, options)) { if (options.Install) { ServiceHelper.Install(); } else if (options.Uninstall) { ServiceHelper.Uninstall(); } if (options.Key != null) { config.ServantIoKey = options.Key; ConfigManager.UpdateConfiguration(config); } } return; } #endif #if DEBUG if (string.IsNullOrWhiteSpace(config.ServantIoKey)) { Console.WriteLine("There's no Servant.io key defined. Please enter one here:"); Console.Write(">"); var key = Console.ReadLine(); if (string.IsNullOrWhiteSpace(key)) { return; } config.ServantIoKey = key; ConfigManager.UpdateConfiguration(config); } Servant.Start(); Console.ReadLine(); #else var servicesToRun = new ServiceBase[] { new ServantAgentService() }; ServiceBase.Run(servicesToRun); #endif }
private static void WriteMums(IEnumerable <Match> mums, Sequence refSequence, Sequence querySequence, CommandLineOptions myArgs) { // write the QuerySequenceId string DisplayID = querySequence.ID; Console.Write("> {0}", DisplayID); if (myArgs.displayQueryLength) { Console.Write(" " + querySequence.Count); } Console.WriteLine(); // DISCUSSION: // If a ReverseComplement sequence, MUMmer has the option to print the index start point relative // to the original sequence we tagged the reversed DisplayID with " Reverse" so _if_ we find a // " Reverse" on the end of the ID, assume it is a ReverseComplement and reverse the index bool isReverseComplement = myArgs.c && querySequence.IsMarkedAsReverseComplement(); // Start is 1 based in literature but in programming (e.g. MaxUniqueMatch) they are 0 based. // Add 1 Stopwatch swInterval = new Stopwatch(); swInterval.Start(); foreach (Match match in mums) { swInterval.Stop(); // Add time taken by GetMatches(). mummerTime = mummerTime.Add(swInterval.Elapsed); swInterval.Restart(); Console.WriteLine("{0,8} {1,8} {2,8}", match.ReferenceSequenceOffset + 1, !isReverseComplement ? match.QuerySequenceOffset + 1 : querySequence.Count - match.QuerySequenceOffset, match.Length); if (myArgs.showMatchingString) { StringBuilder sb = new StringBuilder((int)match.Length); for (int i = 0; i < match.Length; ++i) { sb.Append((char)querySequence[match.QuerySequenceOffset + i]); } Console.WriteLine(sb.ToString()); } swInterval.Stop(); writetime = writetime.Add(swInterval.Elapsed); swInterval.Restart(); } }
public void Dispose() { clo = null; }
static void Main(string[] args) { try { // DateTime dStart = DateTime.Now; Stopwatch swMumUtil = Stopwatch.StartNew(); Stopwatch swInterval = new Stopwatch(); Console.Error.WriteLine(SplashString()); if (args.Length > 0) { CommandLineOptions myArgs = ProcessCommandLine(args); if (myArgs.help) { Console.WriteLine(Resources.MumUtilHelp); } else { FileInfo refFileinfo = new FileInfo(myArgs.fileList[0]); long refFileLength = refFileinfo.Length; refFileinfo = null; swInterval.Restart(); IEnumerable <ISequence> referenceSequences = ParseFastA(myArgs.fileList[0]); Sequence referenceSequence = referenceSequences.First() as Sequence; swInterval.Stop(); if (myArgs.verbose) { Console.Error.WriteLine(); Console.Error.WriteLine(" Processed Reference FastA file: {0}", Path.GetFullPath(myArgs.fileList[0])); Console.Error.WriteLine(" Length of first Sequence: {0:#,000}", referenceSequence.Count); Console.Error.WriteLine(" Read/Processing time: {0}", swInterval.Elapsed); Console.Error.WriteLine(" File size : {0:#,000} bytes", refFileLength); } FileInfo queryFileinfo = new FileInfo(myArgs.fileList[1]); long queryFileLength = queryFileinfo.Length; refFileinfo = null; IEnumerable <ISequence> parsedQuerySequences = ParseFastA(myArgs.fileList[1]); IEnumerable <ISequence> querySequences = parsedQuerySequences; if (myArgs.reverseOnly) { // convert to reverse complement sequences querySequences = ReverseComplementSequenceList(parsedQuerySequences); } else if (myArgs.both) { // add the reverse complement sequences along with query sequences. querySequences = AddReverseComplementsToSequenceList(parsedQuerySequences); } // DISCUSSION: // Three possible outputs desired. Globally unique 'mum' (v1), unique in reference sequence (v2), // or get the maximum matches of length or greater. // mummerTime = new TimeSpan(); writetime = new TimeSpan(); IEnumerable <Match> mums; long memoryAtStart = 0; long memoryAtEnd = 0; if (myArgs.verbose) { swMumUtil.Stop(); memoryAtStart = GC.GetTotalMemory(true); swMumUtil.Start(); } swInterval.Restart(); MultiWaySuffixTree suffixTreee = new MultiWaySuffixTree(referenceSequence); swInterval.Stop(); if (myArgs.verbose) { swMumUtil.Stop(); memoryAtEnd = GC.GetTotalMemory(true); swMumUtil.Start(); } MUMmer mummer = new MUMmer(suffixTreee); if (myArgs.verbose) { Console.Error.WriteLine(); Console.Error.WriteLine("Suffix tree construction time : {0}", swInterval.Elapsed); Console.Error.WriteLine("Memory consumed by Suffix tree : {0:#,000}", memoryAtEnd - memoryAtStart); Console.Error.WriteLine("Total edges created : {0:#,000}", suffixTreee.EdgesCount); Console.Error.WriteLine("Memory per edge : {0:#,000.00} bytes", (((double)(memoryAtEnd - memoryAtStart)) / suffixTreee.EdgesCount)); Console.Error.WriteLine(); Console.Error.WriteLine(" Processed Query FastA file: {0}", Path.GetFullPath(myArgs.fileList[1])); Console.Error.WriteLine(" File Size : {0:#,000} bytes", queryFileLength); } mummer.LengthOfMUM = myArgs.length; mummer.NoAmbiguity = myArgs.noAmbiguity; long querySeqCount = 0; double sumofSeqLength = 0; TimeSpan totalTimetakenToProcessQuerySequences = new TimeSpan(); string outputOption = string.Empty; if (myArgs.maxmatch) { outputOption = "GetMumsMaxMatch()"; swInterval.Restart(); foreach (Sequence qSeq in querySequences) { // Stop the wath after each query sequence parsed. swInterval.Stop(); // Add total time to process query sequence. // if reverse complement option is set, includes reverse complement time also. totalTimetakenToProcessQuerySequences = totalTimetakenToProcessQuerySequences.Add(swInterval.Elapsed); mums = mummer.GetMatches(qSeq); WriteMums(mums, referenceSequence, qSeq, myArgs); querySeqCount++; sumofSeqLength += qSeq.Count; // Start the watch for next query sequence parse. swInterval.Restart(); } swInterval.Stop(); } else if (myArgs.mum) { // mums = mum3.GetMumsMum( referenceSequences[0], querySequences); outputOption = "GetMumsMum()"; swInterval.Restart(); foreach (Sequence qSeq in querySequences) { // Stop the wath after each query sequence parsed. swInterval.Stop(); // Add total time to process query sequence. // if reverse complement option is set, includes reverse complement time also. totalTimetakenToProcessQuerySequences = totalTimetakenToProcessQuerySequences.Add(swInterval.Elapsed); swInterval.Restart(); // TODO: After implementing GetMatchesUniqueInBothReferenceAndQuery() in MUMmer //// GetMatchesUniqueInReference() with GetMatchesUniqueInBothReferenceAndQuery() in the line below. mums = mummer.GetMatchesUniqueInReference(qSeq); swInterval.Stop(); // Add time taken by GetMatchesUniqueInBothReferenceAndQuery(). mummerTime = mummerTime.Add(swInterval.Elapsed); swInterval.Restart(); WriteMums(mums, referenceSequence, qSeq, myArgs); swInterval.Stop(); // Add time taken by write matches. writetime = writetime.Add(swInterval.Elapsed); querySeqCount++; sumofSeqLength += qSeq.Count; // Start the watch for next query sequence parse. swInterval.Restart(); } swInterval.Stop(); } else if (myArgs.mumreference) { // NOTE: // mum3.GetMUMs() this really implements the GetMumReference() functionality // mums = mum3.GetMumsReference( referenceSequences[0], querySequences); // should be //swInterval.Restart(); outputOption = "GetMumsReference()"; swInterval.Restart(); foreach (Sequence qSeq in querySequences) { // Stop the watch after each query sequence parsed. swInterval.Stop(); // Add total time to process query sequence. // if reverse complement option is set, includes reverse complement time also. totalTimetakenToProcessQuerySequences = totalTimetakenToProcessQuerySequences.Add(swInterval.Elapsed); swInterval.Restart(); mums = mummer.GetMatchesUniqueInReference(qSeq); swInterval.Stop(); // Add time taken by GetMatchesUniqueInReference(). mummerTime = mummerTime.Add(swInterval.Elapsed); swInterval.Restart(); WriteMums(mums, referenceSequence, qSeq, myArgs); swInterval.Stop(); // Add time taken by write matches. writetime = writetime.Add(swInterval.Elapsed); querySeqCount++; sumofSeqLength += qSeq.Count; // Start the watch for next query sequence parse. swInterval.Restart(); } swInterval.Stop(); } else { // cannot happen as argument processing already asserted one of the three options must be specified Console.Error.WriteLine("\nError: one of /maxmatch, /mum, /mumreference options must be specified."); Environment.Exit(-1); // kill the error about unitialized use of 'mums' in the next block...the compiler does not recognize // Environment.Exit() as a no-return function throw new Exception("Never hit this"); } if (myArgs.verbose) { if (myArgs.reverseOnly || myArgs.both) { Console.Error.WriteLine(" Read/Processing time : {0}", timeTakenToParseQuerySequences); Console.Error.WriteLine(" Reverse Complement time : {0}", timeTakenToGetReverseComplement); Console.Error.WriteLine(" Total time taken to Process reads: {0}", totalTimetakenToProcessQuerySequences); } else { Console.Error.WriteLine(" Read/Processing time : {0}", totalTimetakenToProcessQuerySequences); } Console.Error.WriteLine(); Console.Error.WriteLine(" Number of query Sequences : {0:#,000}", querySeqCount); Console.Error.WriteLine(" Average length of query Sequences: {0:#,000}", sumofSeqLength / querySeqCount); Console.Error.WriteLine(); Console.Error.WriteLine("Compute {0,20} time : {1}", outputOption, mummerTime); Console.Error.WriteLine(" WriteMums() time : {0}", writetime); } swMumUtil.Stop(); if (myArgs.verbose) { Console.Error.WriteLine(" Total MumUtil Runtime : {0}", swMumUtil.Elapsed); } } } else { Console.WriteLine(Resources.MumUtilHelp); } } catch (Exception ex) { DisplayException(ex); } }
public VerifyCommand(CommandLineOptions options) { this.options = options; }
public TicketConsoleExport(CommandLineOptions commandLineOptions) { this.isDetailledMode = commandLineOptions.Detailled; }
public void WhenUrlAndInvalidFlagSpecified_ThenParseRaisesInvalidCommandLineException() { Assert.Throws <InvalidCommandLineException>( () => CommandLineOptions.Parse( new[] { "/url", "iap-rdp:///project-1/us-central1-a/vm-1", "/ debug" })); }
public DeleteCommand(CommandLineOptions options, ICollection <int?> claimIds, bool all) { this.options = options; this.claimIds = claimIds; this.all = all; }
static void Main(string[] args) { bool debug = Debugger.IsAttached; if (!debug) { AppDomain.CurrentDomain.UnhandledException += OnUnhandledException; } var options = new CommandLineOptions(); if (Parser.Default.ParseArgumentsStrict(args, options)) { ProcessDiagrams(options); if (debug) { Console.ReadKey(); } } }
public RemoteFactory(CommandLineOptions options) { _options = options; }