Пример #1
1
        public ParsedArguments(string[] args) {
            var p = new OptionSet {
                {"sum", "If set Sum will be calculated", _ => _SumValues = true},
                {"max", "If set show Max value", _ => _MaxValue = true},
                {"min", "If set show Min value", _ => _MinValue = true},
                {"dir=", "Output directory", dir => _OutputDirectory = GetValidPath(dir)}, {
                    "count=", "Count of items to be generated. This value is mandatory.", count => {
                        if (!_CountIsSet && int.TryParse(count, out _Count) && _Count > 0) {
                            _CountIsSet = true;
                        }
                    }
                }
            };

            p.Parse(args);

            if (!ArgsAreValid) {
                Trace.WriteLine("Parameter args does not contain valid value for count.");

                using (var stringWriter = new StringWriter()) {
                    p.WriteOptionDescriptions(stringWriter);
                    _ErrorMessage = stringWriter.ToString();
                }
            }
        }
Пример #2
0
        private void CheckForAndShowHelp(OptionSet optionSet)
        {
            if (!Params.ShowHelp) return;

            _helpWriter.PrintHelp(optionSet);
            Environment.Exit(0);
        }
Пример #3
0
 public static void show_help(string message, OptionSet option_set)
 {
     //Console.Error.WriteLine(message);
     the_logger.Info(message);
     option_set.WriteOptionDescriptions(Console.Error);
     Environment.Exit(-1);
 }
Пример #4
0
		public override void Run (IEnumerable<string> args)
		{
			string rootPath = null;

			var options = new OptionSet () {
				{ "r=|root=", "Specify which documentation root to use. Default is $libdir/monodoc", v => rootPath = v },
			};

			var extra = Parse (options, args, "index", 
			                   "[OPTIONS]+ ACTION",
			                   "Create Monodoc indexes depending on ACTION. Possible values are \"tree\" or \"search\" for, respectively, mdoc tree and lucene search");
			if (extra == null)
				return;

			var root = string.IsNullOrEmpty (rootPath) ? RootTree.LoadTree () : RootTree.LoadTree (rootPath);

			foreach (var action in extra) {
				switch (action) {
				case "tree":
					RootTree.MakeIndex (root);
					break;
				case "search":
					RootTree.MakeSearchIndex (root);
					break;
				}
			}
		}
Пример #5
0
        public InstanceConfiguration Parse(IList<string> args)
        {
            var cfg = new InstanceConfiguration
                {
                    AppName = string.Empty,
                    Help = false,
                    Verbose = false,
                    ExtraParams = new List<string>()
                };

            var p = new OptionSet
                {
                    {"app=", v => cfg.AppName = v},
                    {"i|install", v => cfg.Install = v != null},
                    {"v|verbose", v => cfg.Verbose = v != null},
                    {"h|?|help", v => cfg.Help = v != null},
                };
            cfg.OptionSet = p;

            if (args == null || !args.Any())
            {
                cfg.Help = true;
                return cfg;
            }

            cfg.ExtraParams = p.Parse(args);
            cfg.AppName = cfg.AppName.Trim('"', '\'');
            return cfg;
        }
Пример #6
0
        static void Main(string[] args)
        {
            Thread.CurrentThread.CurrentUICulture = new CultureInfo("en");
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en");

            var threads = 1;
            var pipelining = 1;
            var duration = 10;
            int? count = null;

            var p = new OptionSet()
            {
                {"t|threads=", (int v) => threads = v},
                {"p|pipelining=", (int v) => pipelining = v},
                {"d|duration=", (int v) => duration = v},
                {"c|count=", (int? v) => count = v},
            };

            var extraArgs = p.Parse(args);
            var threadAffinity = extraArgs.Contains("-a");
            var url = extraArgs.FirstOrDefault(e => e.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || e.StartsWith("https://", StringComparison.OrdinalIgnoreCase));
            Uri uri = null;

            if (url != null && !Uri.TryCreate(url, UriKind.Absolute, out uri))
                Console.WriteLine("Failed to parse URL");
            else if (url != null && count.HasValue)
                RunWithCount(uri, count.Value).Wait();
            else if (url != null)
                RunWithDuration(uri, threads, threadAffinity, pipelining, TimeSpan.FromSeconds(duration)).Wait();
            else
                ShowHelp();
        }
        public override void Run(ApplicationContext appContext, IEnumerable<string> args)
        {
            string release = null;
            string env = null;
            var dryRun = false;
            var resume = false;
            var noCache = appContext.UserConfig.Cache.Disabled;
            var noBeeps = false;

            var p = new OptionSet
            {
                { "r=|release=", "Select which release to use, instead of the default.", v => release = v },
                { "e=|env=|environment=", "Select which environment to use, instead of the default.", v => env = v },
                { "n|dry-run", "Don't actually run actions, just print what would be done and exit.", v => dryRun = v != null },
                { "s|resume", "Resume a failed deploy, if possible.", v => resume = v != null },
                { "C|no-cache", "Disable cache.", v => noCache = v != null },
                { "B|no-beeps", "Disable buzzer.", v => noBeeps = v != null }
            };

            var extra = Parse(p, args,
                CommandConstants.Deploy,
                "[OPTIONS]+");
            if (extra == null)
                return;

            var runContext = RunContext.Create(appContext, CommandConstants.Deploy, release, env, dryRun);
            RunCore(DeployContext.Create(runContext, resume, noCache, noBeeps));
        }
Пример #8
0
 public void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration)
 {
     optionSet
         .Add("a|auto|automaticpackage",
              "AutomaticPackage - Generate automatic package instead of normal. Defaults to false",
              option => configuration.NewCommand.AutomaticPackage = option != null)  
         .Add("t=|template=|template-name=",
              "TemplateName - Use a named template in {0}\\templates\\templatename instead of built-in template.".format_with(ApplicationParameters.InstallLocation),
              option => configuration.NewCommand.TemplateName = option)
         .Add("name=",
              "Name [Required]- the name of the package. Can be passed as first parameter without \"--name=\".",
              option =>
                  {
                      configuration.NewCommand.Name = option.remove_surrounding_quotes();
                      configuration.NewCommand.TemplateProperties.Add(TemplateValues.NamePropertyName, option.remove_surrounding_quotes());
                  })
         .Add("version=",
              "Version - the version of the package. Can also be passed as the property PackageVersion=somevalue",
              option => configuration.NewCommand.TemplateProperties.Add(TemplateValues.VersionPropertyName, option.remove_surrounding_quotes()))
         .Add("maintainer=",
              "Maintainer - the name of the maintainer. Can also be passed as the property MaintainerName=somevalue",
              option => configuration.NewCommand.TemplateProperties.Add(TemplateValues.MaintainerPropertyName, option.remove_surrounding_quotes()))
         ;
     //todo: more built-in templates
 }
Пример #9
0
        public Options(params string[] args)
        {
            Port = DefaultPort;
            AssemblyPaths = new Collection<string>();

            options = new OptionSet
                          {
                              {
                                  "p|port=",
                                  "the {PORT} the server should listen on (default=" + DefaultPort + ").",
                                  (int v) => Port = v
                                  },
                              {
                                  "a|assembly=",
                                  "an assembly to search for step definition methods.",
                                  v => AssemblyPaths.Add(v)
                                  },
                              {
                                  "h|?|help",
                                  "show this message and exit.",
                                  v => ShowHelp = v != null
                                  }
                          };
            options.Parse(args);
        }
Пример #10
0
        public override void WriteHelp(OptionSet optionSet)
        {
            PrintCopyrightMessage();

            var help = @"
            Interact with a ConDep Server

            Usage: ConDep Server <command>

            where available commands are:

              Upload            Upload environment configurations (*.env.json),
                    deployment artifacts (*.dll) or deployment pipelines (*.pipe.json)

              Execute           Execute a deployment artifact or deployment pipeline

              List              List content from ConDep Server. Available content are configurations,
                    pipelines, deployment artifacts and logs.

              Show              Show content from ConDep Server. Available content are configurations,
                    pipelines, and logs.

              Help <command>    Show help about any of the above commands

              For more information on the individual commands, type ConDep Server Help <command>
            ";
            _writer.Write(help);
        }
Пример #11
0
    public static int Main(string[] args)
    {
        TextWriter writer = Console.Out;
        string method_name = null;
        string formatter = null;
        bool show_help = false;

        var os = new OptionSet () {
            { "formatter=", "Source code formatter. Valid values are: 'csharp-coregraphics'", v => formatter = v },
            { "out=", "Source code output", v => writer = new StreamWriter (v) },
            { "h|?|help", "Displays the help", v => show_help = true },
        };

        var svg = os.Parse (args);
        string path = (svg.Count > 1) ? String.Concat (svg) : svg [0];

        if (show_help)
            Usage (os, null);

        var parser = new SvgPathParser ();

        switch (formatter) {
        case "csharp-coregraphics":
        case "cs-cg":
            parser.Formatter = new CSharpCoreGraphicsFormatter (writer);
            break;
        default:
            Usage (os, "error: unkown {0} code formatter", formatter);
            break;
        }

        parser.Parse (path, method_name);
        return 0;
    }
Пример #12
0
        public static void Main(string[] args)
        {
            var sgopts = new StubGenOptions ();
            var opts = new OptionSet () {
                { "o=|output-dir=", "Directory to generate classes in. Defaults to current directory", v => sgopts.OutputDir = v },
                { "no-header", "Do not put header with license in generated files", v => sgopts.NoHeader = true },
                { "l|license=", "Name of the license or path to a text file with license text (defaults to MIT/X11)", v => sgopts.LicenseName = v },
                { "a|author=", "Author name", v => sgopts.AuthorName = v },
                { "e|email=", "Author email", v => sgopts.AuthorEmail = v },
                { "c|copyright=", "Copyright holder", v => sgopts.CopyrightHolder = v },
                { "f|force|overwrite-all", "Overwrite all files without prompting.", v => sgopts.OverwriteAll = true },
                { "d|debug", "Show more information on errors.", v => sgopts.Debug = true },
                { "p|private|non-public", "Include private/internal members in the outline.", v => sgopts.IncludeNonPublic = true },
                { "h|help|?", "Show this help screen", v => sgopts.ShowHelp = true }
            };

            if (sgopts.ShowHelp)
                ShowHelp (opts);

            List <string> assemblies = opts.Parse (args);
            if (assemblies == null || assemblies.Count == 0)
                ShowHelp (opts);

            foreach (string ap in assemblies)
                ProcessAssembly (ap, sgopts);
        }
 internal override bool IsInsertionTrigger(SourceText text, int characterPosition, OptionSet options)
 {
     var ch = text[characterPosition];
     return ch == ' ' ||
         (CompletionUtilities.IsStartingNewWord(text, characterPosition) &&
         options.GetOption(CompletionOptions.TriggerOnTypingLetters, LanguageNames.CSharp));
 }
Пример #14
0
 static void ShowHelp(OptionSet p)
 {
     Console.WriteLine("Usage: omnisharp -s /path/to/sln [-p PortNumber]");
     Console.WriteLine();
     Console.WriteLine("Options:");
     p.WriteOptionDescriptions(Console.Out);
 }
Пример #15
0
		public override void Run (IEnumerable<string> args)
		{
			string current_library = "";

			var options = new OptionSet () {
				{ "o|out=", 
					"{FILE} to generate/update documentation within.\n" + 
					"If not specified, will process " + file + ".\n" +
					"Set to '-' to skip updates and write to standard output.",
					v => file = v },
				{ "library=",
					"The {LIBRARY} that the following --type=TYPE types should be a part of.",
					v => current_library = v },
				{ "type=",
					"The full {TYPE} name of a type to copy into the output file.",
					v => AddTypeToLibrary (current_library, v) },
			};
			directories = Parse (options, args, "export-ecma-xml", 
					"[OPTIONS]+ DIRECTORIES",
					"Export mdoc documentation within DIRECTORIES into ECMA-format XML.\n\n" +
					"DIRECTORIES are mdoc(5) directories as produced by 'mdoc update'.");
			if (directories == null || directories.Count == 0)
				return;

			Update ();
		}
Пример #16
0
 static void ShowHelp(OptionSet p)
 {
     Console.WriteLine("Usage: SpeechBox [OPTIONS]+ message");
       Console.WriteLine();
       Console.WriteLine("Options:");
       p.WriteOptionDescriptions(Console.Out);
 }
Пример #17
0
 public void BindCommadLineParameters(OptionSet optionSet)
 {
     optionSet
         .Add("i|include=", "Include files to the package", _includes.Add)
         .Add("o|output=", "Name of the output file", x => _outputFileName = x)
         .Add("cn=", "CN of the certificate", x => _cn = x);
 }
 static void ShowHelp(OptionSet p)
 {
     Console.WriteLine("Usage: CheckFileAccess [options] path1 [path2..pathN]");
     Console.WriteLine();
     Console.WriteLine("Options:");
     p.WriteOptionDescriptions(Console.Out);
 }
 static void ShowHelp(OptionSet p)
 {
     Console.WriteLine("Usage: CommonObjects [options] pid0 pid1 [pid2..pidN]");
     Console.WriteLine();
     Console.WriteLine("Options:");
     p.WriteOptionDescriptions(Console.Out);
 }
		public static bool Run(IList<string> args) {
			var detail = false;
			// parse options
			var p = new OptionSet {
				{ "d|detail", v => detail = v != null },
			};
			try {
				args = p.Parse(args);
			} catch {
				return Program.Print(Usage);
			}

			if (args.Count < 1) {
				return Program.Print(Usage);
			}

			var iArgs = 0;
			var rootDir = new DirectoryInfo(args[iArgs++]);
			if (!rootDir.Exists) {
				return Program.Print(
						"Root directory doesn't exist.\nroot:" + rootDir.FullName);
			}

			var covDataFile = args.Count >= iArgs + 1
					? new FileInfo(args[iArgs++]) : null;
			covDataFile = FileUtil.GetCoverageRecord(covDataFile, rootDir);
			if (!covDataFile.SafeExists()) {
				return
						Program.Print(
								"Coverage data file doesn't exist.\ncoverage:" + covDataFile.FullName);
			}

			return Analyze(rootDir, covDataFile, detail);
		}
Пример #21
0
        static bool ParseCommandLineOptions(String[] args, Options options)
        {
            var set = new OptionSet()
                {
                    { "o|outdir=", v => options.OutputDir = v },
                    // Misc. options
                    { "v|verbose",  v => { options.Verbose = true; } },
                    { "h|?|help",   v => options.ShowHelpText = v != null },
                };

            if (args.Length == 0 || options.ShowHelpText)
            {
                ShowHelp(set);
                return false;
            }

            try
            {
                options.PackageName = set.Parse(args)[0].Replace("\"", "");
                options.PackageDir = set.Parse(args)[1].Replace("\"", "");
            }
            catch (OptionException)
            {
                Console.WriteLine("Error parsing the command line.");
                ShowHelp(set);
                return false;
            }

            return true;
        }
Пример #22
0
        public static void Main(string[] args)
        {
            var showHelp = false;

            var options = new OptionSet()
            {
                {
                    "h|help",
                    "show this message and exit",
                    v => showHelp = v != null
                    },
            };

            List<string> extras;

            try
            {
                extras = options.Parse(args);
            }
            catch (OptionException e)
            {
                Console.Write("{0}: ", GetExecutableName());
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `{0} --help' for more information.", GetExecutableName());
                return;
            }

            if (extras.Count < 1 || extras.Count > 2 ||
                showHelp == true)
            {
                Console.WriteLine("Usage: {0} [OPTIONS]+ input_cnd [output_file]", GetExecutableName());
                Console.WriteLine();
                Console.WriteLine("Options:");
                options.WriteOptionDescriptions(Console.Out);
                return;
            }

            var inputPath = extras[0];
            var outputPath = extras.Count > 1 ? extras[1] : null;

            var cnd = new ConditionalsFile();
            using (var input = File.OpenRead(inputPath))
            {
                cnd.Deserialize(input);
            }

            if (outputPath == null)
            {
                DumpConditionals(Console.Out, cnd);
            }
            else
            {
                using (var output = File.Create(outputPath))
                {
                    var writer = new StreamWriter(output);
                    DumpConditionals(writer, cnd);
                    writer.Flush();
                }
            }
        }
Пример #23
0
        public static void Main(string [] args)
        {
            // Parse the command line options
            bool show_help       = false;
            OptionSet option_set = new OptionSet () {
                { "v|version", _("Print version information"), v => { PrintVersion (); } },
                { "h|help", _("Show this help text"), v => show_help = v != null }
            };

            try {
                option_set.Parse (args);

            } catch (OptionException e) {
                Console.Write ("SparkleShare: ");
                Console.WriteLine (e.Message);
                Console.WriteLine ("Try `sparkleshare --help' for more information.");
            }

            if (show_help)
                ShowHelp (option_set);

            // Initialize the controller this way so that
            // there aren't any exceptions in the OS specific UI's
            Controller = new SparkleController ();
            Controller.Initialize ();

            if (Controller != null) {
                UI = new SparkleUI ();
                UI.Run ();
            }
        }
Пример #24
0
        /// <summary>
        /// Method performing the check command
        /// </summary>
        /// <param name="argsList">
        /// Command line like style
        /// </param>
        public static void Check(IEnumerable<string> argsList)
        {
            string outname = null;
            bool help = false;
            var op = new OptionSet() {
                {"check", "Command name, consumes token", v => int.Parse("0")},
                {"save|outname=", "Output of the tabulation filename", v => outname = v},
                {"help|h", "Shows this help message", v => help = true}
            };

            List<string> checkList = op.Parse(argsList);
            if (1 > checkList.Count || help) {
                Console.WriteLine ("Usage --check [--options] res-basis res-list...");
                op.WriteOptionDescriptions(Console.Out);
                return;
            }
            var list = new List<ResultSummary> ();
            var B = JsonConvert.DeserializeObject<ResultSummary> (File.ReadAllText (checkList [0]));
            foreach(string arg in checkList) {
                var R = JsonConvert.DeserializeObject<ResultSummary> (File.ReadAllText (arg));
                R.Parametrize (B);
                R.ResultName = arg;
                R.QueryList = null;
                list.Add (R);
                // Console.WriteLine (JsonConvert.SerializeObject(R, Formatting.Indented));
            }

            var s = JsonConvert.SerializeObject (list, Formatting.Indented);
            Console.WriteLine (s);
            if (outname != null) {
                File.WriteAllText(outname, s);
            }
        }
Пример #25
0
    /// <summary>Parameters: num_files weight_1 .. weight_n file_1 .. file_n output_file</summary>
    /// <param name="args">the command-line arguments</param>
    public static void Main(string[] args)
    {
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(Handlers.UnhandledExceptionHandler);

        // parse command-line parameters

        string prediction_file = null;
        //string score_file      = null;
           	var p = new OptionSet() {
           			{ "data-dir=",              v => data_dir = v         },
            { "prediction-file=",       v => prediction_file = v  },
            { "sigmoid",                v => sigmoid = v != null  },
            { "pairwise-probability",   v => pairwise_prob = v != null   },
            { "pairwise-wins",          v => pairwise_wins = v != null   },
            { "rated-probability",      v => rated_prob = v != null      },
            { "constant-rating",        v => constant_rating = v != null },
            //{ "score-file=",            v => score_file = v },
           	  	};
           		IList<string> extra_args = p.Parse(args);

        string rated_file = extra_args[0];

        // combine files
        IList<double> test_scores;
        IList<double> validation_scores;

        if (constant_rating)
        {
            test_scores = ReadFile(rated_file);
            validation_scores = ReadFile(ValidationFilename(rated_file));
        }
        else
        {
            string rating_file = extra_args[1];
            test_scores = CombineFiles(rated_file, rating_file);
            validation_scores = CombineFiles(ValidationFilename(rated_file), ValidationFilename(rating_file));
        }

        // compute error on validation set
        string validation_candidates_file = Path.Combine(data_dir, "mml-track2/validationCandidatesIdx2.txt");
        string validation_hits_file       = Path.Combine(data_dir, "mml-track2/validationHitsIdx2.txt");
        var candidates = Track2Items.Read(validation_candidates_file);
        var hits       = Track2Items.Read(validation_hits_file);
        double error = KDDCup.EvaluateTrack2(Decide(validation_scores), candidates, hits);
        Console.WriteLine("ERR {0:F7}", error);

        if (prediction_file != null)
        {
            WritePredictions(Decide(test_scores), prediction_file);
            WritePredictions(Decide(validation_scores), ValidationFilename(prediction_file));
        }

        /*
        if (score_file != null)
        {
            WriteScores(test_scores, score_file);
            WriteScores(test_scores, ValidationFilename(score_file));
        }
        */
    }
 /// <summary>
 /// Display the help text for this command line program.
 /// </summary>
 /// <param name="os"></param>
 private void Help(OptionSet os)
 {
     Console.WriteLine("Usage: " + System.AppDomain.CurrentDomain.FriendlyName + " [-?|--help] [-iINPUT|--input=INPUT] [-oOUTPUT|--output=OUTPUT] [-sSTICKY|--sticky=STICKY] [-aSORTATTRIBUTES|--attributes=SORTATTRIBUTES]");
     Console.WriteLine();
     Console.WriteLine("Option:");
     os.WriteOptionDescriptions(Console.Out);
 }
Пример #27
0
		static void Main(string[] args) {
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);

			try {
				// use command-line parameters if provided (used by auto-update functionality)
				bool showHelp = false;
				bool skipUpdateCheck = false;

				_options = new OptionSet {
			        {"h|help", "Show this short help text", v => showHelp = true},
			        {"k|killpid=", "Kill calling (old) process (to be used by updater)", KillDanglingProcess },
			        {"c|cleanupdate=", "Delete (old) executable (to be used by updater)", RemoveOldExecutable },
					{"s|skip-update-check", "Skip update check)", v => skipUpdateCheck = true },
			    };
				_options.Parse(args);
				if (showHelp) {
					ShowHelp();
					return;
				}

				Application.Run(new MainForm(skipUpdateCheck));
			}

			catch (Exception exc) {
				MessageBox.Show("An error ocurred: " + exc.Message + "\r\n\r\nCallstack: " + exc.StackTrace);
			}
		}
        public override void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node, OptionSet optionSet, NextAction<IndentBlockOperation> nextOperation)
        {
            nextOperation.Invoke(list);

            var queryExpression = node as QueryExpressionSyntax;
            if (queryExpression != null)
            {
                var firstToken = queryExpression.FromClause.Expression.GetFirstToken(includeZeroWidth: true);
                var lastToken = queryExpression.FromClause.Expression.GetLastToken(includeZeroWidth: true);
                AddIndentBlockOperation(list, queryExpression.FromClause.FromKeyword, firstToken, lastToken);

                for (int i = 0; i < queryExpression.Body.Clauses.Count; i++)
                {
                    // if it is nested query expression
                    var fromClause = queryExpression.Body.Clauses[i] as FromClauseSyntax;
                    if (fromClause != null)
                    {
                        firstToken = fromClause.Expression.GetFirstToken(includeZeroWidth: true);
                        lastToken = fromClause.Expression.GetLastToken(includeZeroWidth: true);
                        AddIndentBlockOperation(list, fromClause.FromKeyword, firstToken, lastToken);
                    }
                }

                // set alignment line for query expression
                var baseToken = queryExpression.GetFirstToken(includeZeroWidth: true);
                var endToken = queryExpression.GetLastToken(includeZeroWidth: true);
                if (!baseToken.IsMissing && !baseToken.Equals(endToken))
                {
                    var startToken = baseToken.GetNextToken(includeZeroWidth: true);
                    SetAlignmentBlockOperation(list, baseToken, startToken, endToken);
                }
            }
        }
		internal static CacheIndentEngine CreateEngine(string text, out SourceText sourceText, OptionSet options = null)
		{
			if (options == null) {
				options = FormattingOptionsFactory.CreateMono ();
				//	options.AlignToFirstIndexerArgument = formatOptions.AlignToFirstMethodCallArgument = true;
			}

			var sb = new StringBuilder ();
			int offset = 0;
			for (int i = 0; i < text.Length; i++) {
				var ch = text [i];
				if (ch == '$') {
					offset = i;
					continue;
				}
				sb.Append (ch);
			}


			sourceText = SourceText.From (sb.ToString ());

			var result = new CacheIndentEngine (new CSharpIndentEngine (options));
			result.Update (sourceText, offset);
			return result;
		}
Пример #30
0
        private static void Main(string[] args)
        {
            IStatCalculator stats = null;
            bool showErrors = true;
            bool showHelp = false;

            var p = new OptionSet
            {
                { "b|burndown", "Get burndown chart data", v => {
                    stats = new BurndownStats();
                }},
                { "c|cfd", "Get cumulative flow chart data", v => { stats = new CumulativeFlowStats(); }},
                { "t|table", "Summarize issues in sprint", v => { stats = new ContentTableStats(); }},
                { "e|errors", "Turn on or off list of issues with state errors (defaults to on)",
                    v => { showErrors = v != null; } },
                { "h|?|help", "Display this help message", v => showHelp = v != null }
            };
            List<String> extras = p.Parse(args);

            if (showHelp)
            {
                ShowHelp(p);
                return;
            }

            IList<Tuple<string, string>> repos = GetRepoNames(extras);

            if (stats == null)
            {
                stats = new BurndownStats();
            }

            var program = new Program(stats, repos, showErrors);
            program.Go();
        }
Пример #31
0
 /// <summary>
 /// 当执行命令时调用此方法。
 /// </summary>
 /// <param name="options">命令参数集合</param>
 /// <returns>是否执行成功</returns>
 protected virtual bool OnExecute(OptionSet options)
 {
     return(true);
 }
Пример #32
0
        public override AdjustNewLinesOperation GetAdjustNewLinesOperation(SyntaxToken previousToken, SyntaxToken currentToken, OptionSet optionSet, NextOperation <AdjustNewLinesOperation> nextOperation)
        {
            ////////////////////////////////////////////////////
            // brace related operations
            // * { or * }
            switch (currentToken.CSharpKind())
            {
            case SyntaxKind.OpenBraceToken:
                if (!previousToken.IsParenInParenthesizedExpression())
                {
                    return(CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines));
                }

                break;

            case SyntaxKind.CloseBraceToken:
                return(CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines));
            }

            // do { } while case
            if (previousToken.CSharpKind() == SyntaxKind.CloseBraceToken && currentToken.CSharpKind() == SyntaxKind.WhileKeyword)
            {
                return(CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines));
            }

            // { * or } *
            switch (previousToken.CSharpKind())
            {
            case SyntaxKind.CloseBraceToken:
                if (!previousToken.IsCloseBraceOfExpression())
                {
                    if (currentToken.CSharpKind() != SyntaxKind.SemicolonToken &&
                        !currentToken.IsParenInParenthesizedExpression() &&
                        !currentToken.IsCommaInInitializerExpression() &&
                        !currentToken.IsCommaInAnyArgumentsList() &&
                        !currentToken.IsParenInArgumentList() &&
                        !currentToken.IsDotInMemberAccess() &&
                        !currentToken.IsCloseParenInStatement())
                    {
                        return(CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines));
                    }
                }

                break;

            case SyntaxKind.OpenBraceToken:
                return(CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines));
            }

            ///////////////////////////////////////////////////
            // statement related operations
            // object and anonymous initializer "," case
            if (previousToken.IsCommaInInitializerExpression())
            {
                return(CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines));
            }

            // else * except else if case
            if (previousToken.CSharpKind() == SyntaxKind.ElseKeyword && currentToken.CSharpKind() != SyntaxKind.IfKeyword)
            {
                return(CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines));
            }

            // , * in enum declarations
            if (previousToken.IsCommaInEnumDeclaration())
            {
                return(CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines));
            }

            // : cases
            if (previousToken.IsColonInSwitchLabel() ||
                previousToken.IsColonInLabeledStatement())
            {
                return(CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines));
            }

            // embedded statement
            if (previousToken.CSharpKind() == SyntaxKind.CloseParenToken && previousToken.Parent.IsEmbeddedStatementOwnerWithCloseParen())
            {
                return(CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines));
            }

            if (previousToken.CSharpKind() == SyntaxKind.DoKeyword && previousToken.Parent.CSharpKind() == SyntaxKind.DoStatement)
            {
                return(CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines));
            }

            // for (int i = 10; i < 10; i++) case
            if (previousToken.IsSemicolonInForStatement())
            {
                return(nextOperation.Invoke());
            }

            // ; case in the switch case statement and else condition
            if (previousToken.CSharpKind() == SyntaxKind.SemicolonToken &&
                (currentToken.CSharpKind() == SyntaxKind.CaseKeyword || currentToken.CSharpKind() == SyntaxKind.DefaultKeyword || currentToken.CSharpKind() == SyntaxKind.ElseKeyword))
            {
                return(CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines));
            }

            // ; * or ; * for using directive
            if (previousToken.CSharpKind() == SyntaxKind.SemicolonToken)
            {
                var line = (previousToken.Parent is UsingDirectiveSyntax) ? 1 : 0;
                return(CreateAdjustNewLinesOperation(line, AdjustNewLinesOption.PreserveLines));
            }

            // attribute case ] *
            // force to next line for top level attributes
            if (previousToken.CSharpKind() == SyntaxKind.CloseBracketToken && previousToken.Parent is AttributeListSyntax)
            {
                var attributeOwner = (previousToken.Parent != null) ? previousToken.Parent.Parent : null;

                if (attributeOwner is CompilationUnitSyntax ||
                    attributeOwner is MemberDeclarationSyntax ||
                    attributeOwner is AccessorDeclarationSyntax)
                {
                    return(CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines));
                }

                return(CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines));
            }

            return(nextOperation.Invoke());
        }
Пример #33
0
        public override AdjustSpacesOperation GetAdjustSpacesOperation(SyntaxToken previousToken, SyntaxToken currentToken, OptionSet optionSet, NextOperation <AdjustSpacesOperation> nextOperation)
        {
            //////////////////////////////////////////////////////
            // ";" related operations
            if (currentToken.CSharpKind() == SyntaxKind.SemicolonToken)
            {
                // ; ;
                if (previousToken.CSharpKind() == SyntaxKind.SemicolonToken)
                {
                    return(CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
                }

                // ) ; with embedded statement case
                if (previousToken.CSharpKind() == SyntaxKind.CloseParenToken && previousToken.Parent.IsEmbeddedStatementOwnerWithCloseParen())
                {
                    return(CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
                }

                // * ;
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
            }

            // omitted tokens case
            if (previousToken.CSharpKind() == SyntaxKind.OmittedArraySizeExpressionToken ||
                previousToken.CSharpKind() == SyntaxKind.OmittedTypeArgumentToken ||
                currentToken.CSharpKind() == SyntaxKind.OmittedArraySizeExpressionToken ||
                currentToken.CSharpKind() == SyntaxKind.OmittedTypeArgumentToken)
            {
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
            }

            // some * "(" cases
            if (currentToken.CSharpKind() == SyntaxKind.OpenParenToken)
            {
                if (previousToken.CSharpKind() == SyntaxKind.IdentifierToken ||
                    previousToken.CSharpKind() == SyntaxKind.DefaultKeyword ||
                    previousToken.CSharpKind() == SyntaxKind.BaseKeyword ||
                    previousToken.CSharpKind() == SyntaxKind.ThisKeyword ||
                    previousToken.CSharpKind() == SyntaxKind.NewKeyword ||
                    previousToken.Parent.CSharpKind() == SyntaxKind.OperatorDeclaration ||
                    previousToken.IsGenericGreaterThanToken() ||
                    currentToken.IsParenInArgumentList())
                {
                    return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
                }
            }

            // empty () or []
            if (previousToken.ParenOrBracketContainsNothing(currentToken))
            {
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
            }

            // attribute case
            // , [
            if (previousToken.CSharpKind() == SyntaxKind.CommaToken && currentToken.CSharpKind() == SyntaxKind.OpenBracketToken && currentToken.Parent is AttributeListSyntax)
            {
                return(CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
            }

            // ] *
            if (previousToken.CSharpKind() == SyntaxKind.CloseBracketToken && previousToken.Parent is AttributeListSyntax)
            {
                // preserving dev10 behavior, in dev10 we didn't touch space after attribute
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.PreserveSpaces));
            }

            // * )
            // * [
            // * ]
            // * ,
            // * .
            // * ->
            switch (currentToken.CSharpKind())
            {
            case SyntaxKind.CloseParenToken:
            case SyntaxKind.OpenBracketToken:
            case SyntaxKind.CloseBracketToken:
            case SyntaxKind.CommaToken:
            case SyntaxKind.DotToken:
            case SyntaxKind.MinusGreaterThanToken:
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
            }

            // case * :
            // default:
            // <label> :
            switch (currentToken.CSharpKind())
            {
            case SyntaxKind.ColonToken:
                if (currentToken.IsParentKind(SyntaxKind.CaseSwitchLabel) ||
                    currentToken.IsParentKind(SyntaxKind.DefaultSwitchLabel) ||
                    currentToken.IsParentKind(SyntaxKind.LabeledStatement) ||
                    currentToken.IsParentKind(SyntaxKind.AttributeTargetSpecifier) ||
                    currentToken.IsParentKind(SyntaxKind.NameColon))
                {
                    return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
                }

                break;
            }

            // [cast expression] * case
            if (previousToken.Parent is CastExpressionSyntax &&
                previousToken.CSharpKind() == SyntaxKind.CloseParenToken)
            {
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
            }

            // generic name
            if (previousToken.Parent.CSharpKind() == SyntaxKind.TypeArgumentList || previousToken.Parent.CSharpKind() == SyntaxKind.TypeParameterList)
            {
                // generic name < *
                if (previousToken.CSharpKind() == SyntaxKind.LessThanToken)
                {
                    return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
                }

                // generic name > *
                if (previousToken.CSharpKind() == SyntaxKind.GreaterThanToken && currentToken.CSharpKind() == SyntaxKind.GreaterThanToken)
                {
                    return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
                }
            }

            // generic name * < or * >
            if ((currentToken.CSharpKind() == SyntaxKind.LessThanToken || currentToken.CSharpKind() == SyntaxKind.GreaterThanToken) &&
                (currentToken.Parent.CSharpKind() == SyntaxKind.TypeArgumentList || currentToken.Parent.CSharpKind() == SyntaxKind.TypeParameterList))
            {
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
            }

            // ++ * or -- *
            if ((previousToken.CSharpKind() == SyntaxKind.PlusPlusToken || previousToken.CSharpKind() == SyntaxKind.MinusMinusToken) &&
                previousToken.Parent is PrefixUnaryExpressionSyntax)
            {
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
            }

            // * ++ or * --
            if ((currentToken.CSharpKind() == SyntaxKind.PlusPlusToken || currentToken.CSharpKind() == SyntaxKind.MinusMinusToken) &&
                currentToken.Parent is PostfixUnaryExpressionSyntax)
            {
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
            }

            // ( * or ) * or [ * or ] * or . * or -> *
            switch (previousToken.CSharpKind())
            {
            case SyntaxKind.OpenParenToken:
            case SyntaxKind.OpenBracketToken:
            case SyntaxKind.DotToken:
            case SyntaxKind.MinusGreaterThanToken:
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));

            case SyntaxKind.CloseParenToken:
            case SyntaxKind.CloseBracketToken:
                int space = (previousToken.CSharpKind() == currentToken.CSharpKind()) ? 0 : 1;
                return(CreateAdjustSpacesOperation(space, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
            }

            // +1 or -1
            if (previousToken.IsPlusOrMinusExpression() && !currentToken.IsPlusOrMinusExpression())
            {
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
            }

            // +- or -+
            if (previousToken.IsPlusOrMinusExpression() && currentToken.IsPlusOrMinusExpression() &&
                previousToken.CSharpKind() != currentToken.CSharpKind())
            {
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
            }

            // ! *
            if (previousToken.CSharpKind() == SyntaxKind.ExclamationToken)
            {
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
            }

            // nullable
            if (currentToken.CSharpKind() == SyntaxKind.QuestionToken &&
                currentToken.Parent.CSharpKind() == SyntaxKind.NullableType)
            {
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
            }

            // pointer case
            if ((currentToken.CSharpKind() == SyntaxKind.AsteriskToken && currentToken.Parent is PointerTypeSyntax) ||
                (previousToken.CSharpKind() == SyntaxKind.AsteriskToken && previousToken.Parent is PrefixUnaryExpressionSyntax))
            {
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
            }

            // ~ * case
            if (previousToken.CSharpKind() == SyntaxKind.TildeToken && (previousToken.Parent is PrefixUnaryExpressionSyntax || previousToken.Parent is DestructorDeclarationSyntax))
            {
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
            }

            // & * case
            if (previousToken.CSharpKind() == SyntaxKind.AmpersandToken &&
                previousToken.Parent is PrefixUnaryExpressionSyntax)
            {
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
            }

            // * :: or :: * case
            if (previousToken.CSharpKind() == SyntaxKind.ColonColonToken || currentToken.CSharpKind() == SyntaxKind.ColonColonToken)
            {
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
            }

            if (previousToken.CSharpKind() == SyntaxKind.IdentifierToken && currentToken.CSharpKind() == SyntaxKind.QuestionToken && currentToken.Parent.IsKind(SyntaxKind.ConditionalAccessExpression))
            {
                return(CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine));
            }

            return(nextOperation.Invoke());
        }
Пример #34
0
 public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options)
 {
     return(false);
 }
Пример #35
0
 public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options)
 {
     return(false);
 }
Пример #36
0
 public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options)
 {
     return(false);
 }
Пример #37
0
 public WrappingViewModel(OptionSet options, IServiceProvider serviceProvider) : base(options, serviceProvider, LanguageNames.CSharp)
 {
     Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.WrappingPreserveSingleLine, CSharpVSResources.Leave_block_on_single_line, s_blockPreview, this, options));
     Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, CSharpVSResources.Leave_statements_and_member_declarations_on_the_same_line, s_declarationPreview, this, options));
 }
Пример #38
0
        public static int Main(string[] args)
        {
            var exeName  = Path.GetFileName(Assembly.GetExecutingAssembly().Location);
            var showHelp = false;

            string hostPipe           = null;
            bool   waitDebuggerAttach = false;

            var p = new OptionSet
            {
                "Copyright (C) 2015 Silicon Studio Corporation. All Rights Reserved",
                "Xenko Debugger Host tool - Version: "
                +
                String.Format(
                    "{0}.{1}.{2}",
                    typeof(Program).Assembly.GetName().Version.Major,
                    typeof(Program).Assembly.GetName().Version.Minor,
                    typeof(Program).Assembly.GetName().Version.Build) + string.Empty,
                string.Format("Usage: {0} --host=[hostpipe]", exeName),
                string.Empty,
                "=== Options ===",
                string.Empty,
                { "h|help", "Show this message and exit", v => showHelp = v != null },
                { "host=", "Host pipe", v => hostPipe = v },
                { "wait-debugger-attach", "Process will wait for a debuggger to attach, for 5 seconds", v => waitDebuggerAttach = true },
            };

            try
            {
                var unexpectedArgs = p.Parse(args);
                if (unexpectedArgs.Any())
                {
                    throw new OptionException("Unexpected arguments [{0}]".ToFormat(string.Join(", ", unexpectedArgs)), "args");
                }

                if (waitDebuggerAttach)
                {
                    // Wait for 2 second max
                    for (int i = 0; i < 500; ++i)
                    {
                        if (System.Diagnostics.Debugger.IsAttached)
                        {
                            break;
                        }

                        Thread.Sleep(10);
                    }
                }

                if (hostPipe == null)
                {
                    throw new OptionException("Host pipe not specified", "host");
                }

                // Open WCF channel with master builder
                var namedPipeBinding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None)
                {
                    SendTimeout = TimeSpan.FromSeconds(300.0), MaxReceivedMessageSize = int.MaxValue
                };
                try
                {
                    var gameDebuggerTarget = new GameDebuggerTarget();
                    var gameDebuggerHost   = DuplexChannelFactory <IGameDebuggerHost> .CreateChannel(new InstanceContext(gameDebuggerTarget), namedPipeBinding, new EndpointAddress(hostPipe));

                    gameDebuggerTarget.MainLoop(gameDebuggerHost);
                }
                catch (Exception)
                {
                    throw;
                }
            }
            catch (OptionException e)
            {
                Console.WriteLine("Command option '{0}': {1}", e.OptionName, e.Message);
                return(-1);
            }
            catch (Exception e)
            {
                Console.WriteLine("Unhandled exception: {0}", e);
                return(-1);
            }

            return(0);
        }
Пример #39
0
        static void Main(string[] args)
        {
            Log.Output   = Log.Mode.Quiet;
            LogPath      = Path.Combine(Settings.Location, "SmartInstaller.log");
            Log.FilePath = LogPath;

            var    upgrade          = false;
            var    uninstall        = false;
            var    tray             = false;
            var    start            = false;
            var    rootLog          = false;
            var    https            = false;
            string server           = null;
            string webRoot          = null;
            bool   relaunchRequired = false;
            var    logFile          = "";

            var help = false;

            var p = new OptionSet()
            {
                { "server=|SERVER=", $"the FOG server address, defaults to {DEFAULT_SERVER}",
                  v => server = v },
                { "webroot=|WEBROOT=", $"the FOG server webroot, defaults to {DEFAULT_WEBROOT}",
                  v => webRoot = v },
                { "h|https|HTTPS", "use HTTPS for communication",
                  v => https = v != null },
                { "r|rootlog|ROOTLOG", "store fog.log in the root of the filesystem",
                  v => rootLog = v != null },
                { "s|start", "start the service when complete",
                  v => start = v != null },
                { "t|tray|TRAY", "enable the FOG Tray and notifications",
                  v => tray = v != null },
                { "u|uninstall", "uninstall an existing installation",
                  v => uninstall = v != null },
                { "upgrade", "upgrade an existing installation",
                  v => upgrade = v != null },
                { "l=|log=", "the log file to use",
                  v => logFile = v },
                { "?|help", "show this message and exit",
                  v => help = v != null },
            };

            p.Parse(args);

            if (help)
            {
                ShowHelp(p);
                return;
            }

            // Defaults
            if (server == null && !upgrade)
            {
                server = DEFAULT_SERVER;
            }
            if (webRoot == null && !upgrade)
            {
                webRoot = DEFAULT_WEBROOT;
            }

            // If no server was set, show help
            if (string.IsNullOrWhiteSpace(server) && !upgrade)
            {
                ShowHelp(p);
                return;
            }
            // A blank webroot is equal to /
            if (string.IsNullOrWhiteSpace(webRoot) && !upgrade)
            {
                webRoot = DEFAULT_WEBROOT;
            }

            if (!string.IsNullOrWhiteSpace(logFile))
            {
                LogPath      = logFile;
                Log.FilePath = LogPath;
                Log.Output   = Log.Mode.File;
            }

            if (args.Length == 1)
            {
                if (args[0].Equals("upgrade"))
                {
                    upgrade = true;
                }
                else if (args[0].Equals("uninstall"))
                {
                    uninstall = true;
                }
            }

            //Preliminary environment checks
            if (Settings.OS == Settings.OSType.Mac)
            {
                relaunchRequired = (Environment.UserName != "root" || Environment.GetEnvironmentVariable("HOME") != "/var/root");
            }


            if (relaunchRequired)
            {
                RelaunchAsRoot(args);
            }
            else if (uninstall)
            {
                PerformCLIUninstall();
            }
            else if (upgrade)
            {
                PerformUpgrade(https ? "1" : "", tray ? "1" : "", server, webRoot, rootLog ? "1" : "");
            }
            else if (args.Length == 0)
            {
                InteractiveMode();
            }
            else
            {
                PrintBanner();
                PrintLicense();
                PrintInfo();
                Install(https ? "1" : "0", tray ? "1" : "0", server, webRoot, "FOG", rootLog ? "1" : "0");
            }
        }
Пример #40
0
 /// <summary>
 /// 执行命令。
 /// </summary>
 /// <param name="options">命令参数集合</param>
 public void Execute(OptionSet options)
 {
     OnExecute(options);
 }
Пример #41
0
 static void helpscr(OptionSet options)
 {
     Console.WriteLine("Toolson CODE1 SIGNAL MANAGER SHELL\n\nUsage :");
     options.WriteOptionDescriptions(Console.Out);
 }
        internal virtual Diagnostic AnalyzeSyntax(OptionSet optionSet, TDeclaration declaration)
        {
            // Note: we will always offer to convert a block to an expression-body (and vice versa)
            // if possible.  All the user preference does is determine if we show them anything in
            // the UI (i.e. suggestion dots, or a squiggle) to let them know that they can make the
            // change.  
            //
            // This way, users can turn off the option so they don't get notified, but they can still
            // make the transformation on a case by case basis.
            //
            // Note: if we decide to hide any adornments, then we also broaden the location where the
            // fix is available.  That way the user can go to any place in the member and choose to
            // convert it.  Otherwise, they'd have no idea what the 'right' location was to invoke
            // the conversion.
            //
            // Also, if the diagnostic is hidden, we'll lower the priority of the code action.  We
            // always want it to be available.  But we don't want it to override issues that are
            // actually being reported in the UI.

            var preferExpressionBodiedOption = optionSet.GetOption(_option);

            var expressionBody = GetExpressionBody(declaration);

            if (expressionBody == null)
            {
                // They don't have an expression body.  See if we can convert into one.
                // If so, offer the conversion (with the proper severity depending on their options).
                if (!GetBody(declaration).TryConvertToExpressionBody(declaration.SyntaxTree.Options,
                        out expressionBody, out var semicolonToken))
                {
                    // Not a block that can be converted to an expression.
                    return null;
                }

                var severity = preferExpressionBodiedOption.Value
                    ? preferExpressionBodiedOption.Notification.Value
                    : DiagnosticSeverity.Hidden;

                var location = severity == DiagnosticSeverity.Hidden
                    ? declaration.GetLocation()
                    : GetBody(declaration).Statements[0].GetLocation();

                var additionalLocations = ImmutableArray.Create(declaration.GetLocation());
                return Diagnostic.Create(
                    CreateDescriptorWithTitle(_expressionBodyTitle, severity, GetCustomTags(severity)),
                    location, additionalLocations: additionalLocations);
            }
            else
            {
                // They have an expression body.  These can always be converted into blocks.
                // Offer to convert this to a block, with the appropriate severity based
                // on their options.
                var severity = preferExpressionBodiedOption.Value
                    ? DiagnosticSeverity.Hidden
                    : preferExpressionBodiedOption.Notification.Value;

                var location = severity == DiagnosticSeverity.Hidden
                    ? declaration.GetLocation()
                    : expressionBody.GetLocation();

                var additionalLocations = ImmutableArray.Create(declaration.GetLocation());
                return Diagnostic.Create(
                    CreateDescriptorWithTitle(_blockBodyTitle, severity, GetCustomTags(severity)),
                    location, additionalLocations: additionalLocations);
            }
        }
Пример #43
0
        protected override Task <ImmutableArray <ISymbol> > GetSymbolsAsync(SyntaxContext context, int position, OptionSet options, CancellationToken cancellationToken)
        {
            var recommender = context.GetLanguageService <IRecommendationService>();

            return(recommender.GetRecommendedSymbolsAtPositionAsync(context.Workspace, context.SemanticModel, position, options, cancellationToken));
        }
 public override bool IsTriggerCharacter(SourceText text, int characterPosition, OptionSet options)
 {
     return(CompletionUtilities.IsTriggerAfterSpaceOrStartOfWordCharacter(text, characterPosition, options));
 }
Пример #45
0
 /// <summary>
 /// constructor
 /// </summary>
 private UpdateMiniCacheFilesMain(string programDescription, OptionSet ops, string commandLineExample, string programAuthors)
     : base(programDescription, ops, commandLineExample, programAuthors)
 {
 }
Пример #46
0
        protected override async Task <ImmutableArray <ISymbol> > GetPreselectedSymbolsAsync(SyntaxContext context, int position, OptionSet options, CancellationToken cancellationToken)
        {
            var recommender = context.GetLanguageService <IRecommendationService>();

            var inferredTypes = context.InferredTypes.Where(t => t.SpecialType != SpecialType.System_Void).ToSet();

            if (inferredTypes.Count == 0)
            {
                return(ImmutableArray <ISymbol> .Empty);
            }

            var symbols = await recommender.GetRecommendedSymbolsAtPositionAsync(
                context.Workspace,
                context.SemanticModel,
                context.Position,
                options,
                cancellationToken).ConfigureAwait(false);

            // Don't preselect intrinsic type symbols so we can preselect their keywords instead. We will also ignore nullability for purposes of preselection
            // -- if a method is returning a string? but we've inferred we're assigning to a string or vice versa we'll still count those as the same.
            return(symbols.WhereAsArray(s => inferredTypes.Contains(GetSymbolType(s), SymbolEqualityComparer.Default) && !IsInstrinsic(s)));
        }
Пример #47
0
        static int Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            bool          help    = false;
            bool          nogui   = false;
            string        logfile = null;
            List <string> extra   = new List <string>();
            var           format  = "t";

            OptionSet opts = new OptionSet();

            opts.Add("h|?|help", "display this help screen", delegate(string v) { help = v != null; })
            .Add("l|logfile=", "the log file to use", delegate(string v) { logfile = v; })
            .Add("f|format=", "the format to use for logging (t[ext], x[ml])", delegate(string v) { format = v.Substring(0, 1); })
            .Add("n|nogui", "do not open a graphical user interface", delegate(string v) { nogui = v != null; });

            try
            {
                extra = opts.Parse(args);
            }
            catch (OptionException e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                return(1);
            }

            if (help)
            {
                DisplayHelp(opts);
                return(0);
            }

            using (var main = new MainForm())
            {
                var isValid = true;
                if (!string.IsNullOrEmpty(logfile))
                {
                    main.LogFile = logfile;
                    switch (format.ToLowerInvariant())
                    {
                    case "x":
                        main.LogFileFormat = LogFileFormat.Xml;
                        break;

                    default:
                        main.LogFileFormat = LogFileFormat.Text;
                        break;
                    }

                    var dir = Path.GetDirectoryName(logfile);
                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }
                }

                if (extra.Count == 1)
                {
                    isValid = main.ValidateConfig(extra[0]);
                }
                if (!nogui)
                {
                    Application.Run(main);
                }
                else
                {
                    main.CleanUpLog();
                }

                return(isValid ? 0 : 1);
            }
        }
 public virtual void configure_argument_parser(OptionSet optionSet, ChocolateyConfiguration configuration)
 {
     optionSet
     .Add("s=|source=",
          "Source - The source to find the package(s) to install. Special sources include: ruby, webpi, cygwin, windowsfeatures, and python. Defaults to default feeds.",
          option => configuration.Sources = option)
     .Add("version=",
          "Version - A specific version to uninstall. Defaults to unspecified.",
          option => configuration.Version = option.remove_surrounding_quotes())
     .Add("a|allversions|all-versions",
          "AllVersions - Uninstall all versions? Defaults to false.",
          option => configuration.AllVersions = option != null)
     .Add("ua=|uninstallargs=|uninstallarguments=|uninstall-arguments=",
          "UninstallArguments - Uninstall Arguments to pass to the native installer in the package. Defaults to unspecified.",
          option => configuration.InstallArguments = option.remove_surrounding_quotes())
     .Add("o|override|overrideargs|overridearguments|override-arguments",
          "OverrideArguments - Should uninstall arguments be used exclusively without appending to current package passed arguments? Defaults to false.",
          option => configuration.OverrideArguments = option != null)
     .Add("notsilent|not-silent",
          "NotSilent - Do not uninstall this silently. Defaults to false.",
          option => configuration.NotSilent = option != null)
     .Add("params=|parameters=|pkgparameters=|packageparameters=|package-parameters=",
          "PackageParameters - Parameters to pass to the package. Defaults to unspecified.",
          option => configuration.PackageParameters = option.remove_surrounding_quotes())
     .Add("x|forcedependencies|force-dependencies|removedependencies|remove-dependencies",
          "RemoveDependencies - Uninstall dependencies when uninstalling package(s). Defaults to false.",
          option => configuration.ForceDependencies = option != null)
     .Add("n|skippowershell|skip-powershell|skipscripts|skip-scripts|skip-automation-scripts",
          "Skip Powershell - Do not run chocolateyUninstall.ps1. Defaults to false.",
          option => configuration.SkipPackageInstallProvider = option != null)
     .Add("ignorepackagecodes|ignorepackageexitcodes|ignore-package-codes|ignore-package-exit-codes",
          "IgnorePackageExitCodes - Exit with a 0 for success and 1 for non-success, no matter what package scripts provide for exit codes. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.UsePackageExitCodes, configuration.Features.UsePackageExitCodes.to_string()),
          option =>
     {
         if (option != null)
         {
             configuration.Features.UsePackageExitCodes = false;
         }
     })
     .Add("usepackagecodes|usepackageexitcodes|use-package-codes|use-package-exit-codes",
          "UsePackageExitCodes - Package scripts can provide exit codes. Use those for choco's exit code when non-zero (this value can come from a dependency package). Chocolatey defines valid exit codes as 0, 1605, 1614, 1641, 3010. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.UsePackageExitCodes, configuration.Features.UsePackageExitCodes.to_string()),
          option => configuration.Features.UsePackageExitCodes = option != null
          )
     .Add("autouninstaller|use-autouninstaller",
          "UseAutoUninstaller - Use auto uninstaller service when uninstalling. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.AutoUninstaller, configuration.Features.AutoUninstaller.to_string()),
          option => configuration.Features.AutoUninstaller = option != null
          )
     .Add("skipautouninstaller|skip-autouninstaller",
          "SkipAutoUninstaller - Skip auto uninstaller service when uninstalling. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.AutoUninstaller, configuration.Features.AutoUninstaller.to_string()),
          option =>
     {
         if (option != null)
         {
             configuration.Features.AutoUninstaller = false;
         }
     })
     .Add("failonautouninstaller|fail-on-autouninstaller",
          "FailOnAutoUninstaller - Fail the package uninstall if the auto uninstaller reports and error. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.FailOnAutoUninstaller, configuration.Features.FailOnAutoUninstaller.to_string()),
          option => configuration.Features.FailOnAutoUninstaller = option != null
          )
     .Add("ignoreautouninstallerfailure|ignore-autouninstaller-failure",
          "Ignore Auto Uninstaller Failure - Do not fail the package if auto uninstaller reports an error. Overrides the default feature '{0}' set to '{1}'. Available in 0.9.10+.".format_with(ApplicationParameters.Features.FailOnAutoUninstaller, configuration.Features.FailOnAutoUninstaller.to_string()),
          option =>
     {
         if (option != null)
         {
             configuration.Features.FailOnAutoUninstaller = false;
         }
     })
     ;
 }
Пример #49
0
        static void Main(string[] args)
        {
            string configFileName = null;
            string loggingDir     = null;

            Configuration.Configuration config = null;

            var p = new OptionSet()
            {
                {
                    "c=|config=|configuration=", "Path to the configuration file",
                    v => configFileName = v ?? "configuration.xml"
                },
                {
                    "l=|log=|logdir=",
                    "Path to the logging dir",
                    v => loggingDir = v ?? @".\Log"
                },
                {
                    "?|help",
                    "Help",
                    v =>
                    {
                        Console.WriteLine($"Usage: ContentTypesSyncSPToDB.exe -config=CONFIGFILENAME [-logdir=LOGDIR]");
                        return;
                    }
                }
            };

            try
            {
                var messages = p.Parse(args);
                Console.WriteLine(string.Join("\n", messages));
            }
            catch (OptionException e)
            {
                Console.WriteLine();
            }

            if (configFileName == null)
            {
                throw new InvalidOperationException("Missing required option -config=CONFIGFILENAME");
            }
            if (!File.Exists(configFileName))
            {
                throw new InvalidOperationException($"File {configFileName} does not exist");
            }
            try
            {
                config = (Configuration.Configuration) new XmlSerializer(typeof(Configuration.Configuration))
                         .Deserialize(
                    new XmlTextReader(
                        configFileName));
            }
            catch (Exception)
            {
                throw new InvalidOperationException($"File {configFileName} is not a valid config file");
            }

            Logging.LogDir = loggingDir;

            Logging.Logger.Information("Start Sync");

            var dbWriter = new DBWriter();

            Logging.Logger.Debug("Start reading SharePoint");
            var data = SharePointReader.Read(config);

            Logging.Logger.Debug("Stop  reading SharePoint");

            var script = new List <string>();

            script.AddRange(dbWriter.GenerateDropTableScript(data));
            script.AddRange(dbWriter.GenerateTableCreationScript(data));
            script.AddRange(dbWriter.GenerateInsertScript(data));

            Logging.Logger.Debug("Start writing to database");
            dbWriter.ExecuteScript(script, config.DBConnectionString);
            Logging.Logger.Debug("Stop  writing to database");

            Logging.Logger.Information("Stop Sync");
        }
Пример #50
0
        static void Main(string[] args)
        {
            bool help         = false;
            int  port         = 2222;
            int  messagesRate = 1000000;
            int  messageSize  = 32;

            var options = new OptionSet()
            {
                { "h|?|help", v => help = v != null },
                { "p|port=", v => port = int.Parse(v) },
                { "m|messages=", v => messagesRate = int.Parse(v) },
                { "s|size=", v => messageSize = int.Parse(v) }
            };

            try
            {
                options.Parse(args);
            }
            catch (OptionException e)
            {
                Console.Write("Command line error: ");
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `--help' to get usage information.");
                return;
            }

            if (help)
            {
                Console.WriteLine("Usage:");
                options.WriteOptionDescriptions(Console.Out);
                return;
            }

            Console.WriteLine($"Server port: {port}");
            Console.WriteLine($"Messages rate: {messagesRate}");
            Console.WriteLine($"Message size: {messageSize}");

            Console.WriteLine();

            // Create and prepare a new SSL server context
            var context = new SslContext(SslProtocols.Tls12, new X509Certificate2("server.pfx", "qwerty"));

            // Create a new echo server
            var server = new MulticastServer(context, IPAddress.Any, port);

            // server.OptionNoDelay = true;
            server.OptionReuseAddress = true;
            server.OptionReusePort    = true;

            // Start the server
            Console.Write("Server starting...");
            server.Start();
            Console.WriteLine("Done!");

            // Start the multicasting thread
            bool multicasting = true;
            var  multicaster  = Task.Factory.StartNew(() =>
            {
                // Prepare message to multicast
                byte[] message = new byte[messageSize];

                // Multicasting loop
                while (multicasting)
                {
                    var start = DateTime.UtcNow;
                    for (int i = 0; i < messagesRate; ++i)
                    {
                        server.Multicast(message);
                    }
                    var end = DateTime.UtcNow;

                    // Sleep for remaining time or yield
                    var milliseconds = (int)(end - start).TotalMilliseconds;
                    if (milliseconds < 1000)
                    {
                        Thread.Sleep(milliseconds);
                    }
                    else
                    {
                        Thread.Yield();
                    }
                }
            });

            Console.WriteLine("Press Enter to stop the server or '!' to restart the server...");

            // Perform text input
            for (;;)
            {
                string line = Console.ReadLine();
                if (line == string.Empty)
                {
                    break;
                }

                // Restart the server
                if (line == "!")
                {
                    Console.Write("Server restarting...");
                    server.Restart();
                    Console.WriteLine("Done!");
                }
            }

            // Stop the multicasting thread
            multicasting = false;
            multicaster.Wait();

            // Stop the server
            Console.Write("Server stopping...");
            server.Stop();
            Console.WriteLine("Done!");
        }
Пример #51
0
        public static void Main(string[] args)
        {
            bool verbose  = false;
            bool showHelp = false;

            OptionSet options = new OptionSet()
            {
                {
                    "h|help",
                    "show this message and exit",
                    v => showHelp = v != null
                },
            };

            List <string> extras;

            try
            {
                extras = options.Parse(args);
            }
            catch (OptionException e)
            {
                Console.Write("{0}: ", GetExecutableName());
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `{0} --help' for more information.", GetExecutableName());
                return;
            }

            if (extras.Count < 1 || extras.Count > 2 || showHelp == true)
            {
                Console.WriteLine("Usage: {0} [OPTIONS]+ input_archive [output_directory]", GetExecutableName());
                Console.WriteLine("Unpack specified archive.");
                Console.WriteLine();
                Console.WriteLine("Options:");
                options.WriteOptionDescriptions(Console.Out);
                return;
            }

            string inputPath  = extras[0];
            string outputPath = extras.Count > 1 ? extras[1] : Path.ChangeExtension(inputPath, null);

            using (var input = File.Open(
                       inputPath,
                       FileMode.Open,
                       FileAccess.Read,
                       FileShare.ReadWrite))
            {
                var archive = new ArchiveFile();
                archive.Deserialize(input);

                Directory.CreateDirectory(outputPath);

                byte[] buffer = new byte[0x4000];

                long counter = 0;
                foreach (var entry in archive.Entries)
                {
                    string entryPath = Path.Combine(outputPath, entry.Path);
                    Directory.CreateDirectory(Path.GetDirectoryName(entryPath));

                    using (Stream output = File.Open(entryPath, FileMode.Create, FileAccess.Write, FileShare.Read))
                    {
                        input.Seek(entry.Offset, SeekOrigin.Begin);
                        output.WriteFromStream(input, entry.Size);
                    }

                    counter++;
                }
            }
        }
Пример #52
0
 public bool TryNavigateToSymbol(ISymbol symbol, Project project, OptionSet options = null, CancellationToken cancellationToken = default(CancellationToken))
 => false;
Пример #53
0
 public static void ShowHelp(OptionSet p)
 {
     Console.WriteLine("Usage:");
     p.WriteOptionDescriptions(Console.Out);
 }
Пример #54
0
 public static void ShowUsage(String toolName, OptionSet p)
 {
     Log.Info("Usage: " + toolName + " [OPTIONS]");
     Log.Info("Options:");
     p.WriteOptionDescriptions(Console.Out);
 }
Пример #55
0
 public static bool IsOpenFileOnly(this DiagnosticAnalyzer analyzer, OptionSet options)
 => analyzer is IBuiltInAnalyzer builtInAnalyzer && builtInAnalyzer.OpenFileOnly(options);
Пример #56
0
        private static void Main(string[] args)
        {
            var help   = false;
            var target = string.Empty;
            var binary = string.Empty;
            var arg    = string.Empty;
            var method = string.Empty;
            var registryManipulation = false;

            var options = new OptionSet
            {
                { "t|target=", "Target Machine", o => target = o },
                { "b|binary=", "Binary: powershell.exe", o => binary = o },
                { "a|args=", "Arguments: -enc <blah>", o => arg = o },
                { "m|method=", $"Methods: {string.Join(", ", Enum.GetNames(typeof(Method)))}", o => method = o },
                { "r|reg|registry", "Enable registry manipulation", o => registryManipulation = true },
                { "h|?|help", "Show Help", o => help = true }
            };

            try
            {
                options.Parse(args);

                if (help)
                {
                    ShowHelp(options);
                    return;
                }

                if (string.IsNullOrEmpty(target) || string.IsNullOrEmpty(binary) || string.IsNullOrEmpty(method))
                {
                    ShowHelp(options);
                    return;
                }

                if ((binary.Contains("powershell") || binary.Contains("cmd")) && string.IsNullOrEmpty(arg))
                {
                    Console.WriteLine($" [x] PowerShell and CMD need arguments! {Environment.NewLine}");
                    ShowHelp(options);
                    return;
                }

                if (!Enum.IsDefined(typeof(Method), method))
                {
                    ShowHelp(options);
                    return;
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message);
                ShowHelp(options);
                return;
            }

            if (registryManipulation)
            {
                DCOMcfg dcomCfg = new DCOMcfg(target);
                try
                {
                    dcomCfg.EnsureDCOMPermission();
                }
                catch (Exception e)
                {
                    Console.WriteLine($" [x] {e}");
                    Console.WriteLine($" [x] Could not edit DCOM configuration on {dcomCfg.getTarget()}");
                }
            }
            try
            {
                Console.WriteLine($"[+] Executing {method}");
                typeof(Program).GetMethod(method).Invoke(null, new object[] { target, binary, arg });
            }
            catch (Exception e)
            {
                Console.WriteLine($" [x] FAIL: Executing {method}");
                Console.WriteLine($" [x] Description: {e.Message}");
            }
        }
Пример #57
0
        public static void Main(string[] args)
        {
            bool convertTextures = false;
            bool noPatch         = false;
            bool noCatch         = false;
            int  logLevelOrdinal = 3;
            bool showHelp        = false;

            var options = new OptionSet()
            {
                { "t|convert-textures", "convert textures", v => convertTextures = v != null },
                { "no-patch", "don't use patch data", v => noPatch = v != null },
                { "no-catch", "don't catch exceptions when loading data", v => noCatch = v != null },
                { "v|verbose", "increase log level (-v/-vv/-vvv)", v => IncreaseLogLevel(v, ref logLevelOrdinal) },
                { "h|help", "show this message and exit", v => showHelp = v != null },
            };

            List <string> extras;

            try
            {
                extras = options.Parse(args);
            }
            catch (OptionException e)
            {
                Console.Write("{0}: ", GetExecutableName());
                Console.WriteLine(e.Message);
                Console.WriteLine("Try `{0} --help' for more information.", GetExecutableName());
                return;
            }

            if (extras.Count < 1 || extras.Count > 2 || showHelp == true)
            {
                Console.WriteLine("Usage: {0} [OPTIONS]+ input_[sb|toc] [output_dir]", GetExecutableName());
                Console.WriteLine();
                Console.WriteLine("Options:");
                options.WriteOptionDescriptions(Console.Out);
                return;
            }

            LogHelper.SetConfiguration(NLog.LogLevel.FromOrdinal(logLevelOrdinal));

            var inputPath      = extras[0];
            var outputBasePath = extras.Count > 1 ? extras[1] : Path.ChangeExtension(inputPath, null) + "_res_unpack";

            string superbundleName;
            var    dataBasePath = Discovery.FindBasePath(inputPath, out superbundleName);

            if (string.IsNullOrEmpty(dataBasePath) == true)
            {
                Logger.Error("Failed to discover base game path.");
                return;
            }

            var dataManager = DataManager.Initialize(dataBasePath, noPatch);

            if (dataManager == null)
            {
                Logger.Fatal("Could not initialize superbundle manager.");
                return;
            }

            var extensionsById = ResourceTypes.GetExtensions();

            var superbundle = dataManager.MountSuperbundle(superbundleName);

            foreach (var resourceInfo in superbundle.Bundles
                     .Where(bi => bi.Resources != null)
                     .SelectMany(bi => bi.Resources)
                     .OrderBy(bi => bi.Name))
            {
                using (var data = new MemoryStream())
                {
                    Logger.Info(resourceInfo.Name);

                    if (noCatch == true)
                    {
                        dataManager.LoadData(resourceInfo, data);
                        data.Position = 0;
                    }
                    else
                    {
                        try
                        {
                            dataManager.LoadData(resourceInfo, data);
                            data.Position = 0;
                        }
                        catch (ChunkCryptoKeyMissingException e)
                        {
                            Logger.Warn("Cannot decrypt '{0}' without crypto key '{1}'.",
                                        resourceInfo.Name,
                                        e.KeyId);
                            continue;
                        }
                        catch (Exception e)
                        {
                            Logger.Warn(e, "Exception while loading '{0}':", resourceInfo.Name);
                            continue;
                        }
                    }

                    var outputName       = Helpers.FilterPath(resourceInfo.Name);
                    var outputPath       = Path.Combine(outputBasePath, outputName + ".dummy");
                    var outputParentPath = Path.GetDirectoryName(outputPath);
                    if (string.IsNullOrEmpty(outputParentPath) == false)
                    {
                        Directory.CreateDirectory(outputParentPath);
                    }

                    bool wasConverted = false;
                    if (convertTextures == true && resourceInfo.ResourceType == ResourceTypes.Texture)
                    {
                        outputPath   = Path.Combine(outputBasePath, outputName + ".dds");
                        wasConverted = ConvertTexture(data, outputPath, dataManager);
                    }

                    if (wasConverted == false)
                    {
                        string extension;
                        if (extensionsById.TryGetValue(resourceInfo.ResourceType, out extension) == true)
                        {
                            extension = "." + extension;
                        }
                        else
                        {
                            extension = ".#" + resourceInfo.ResourceType.ToString("X8");
                        }

                        outputPath = Path.Combine(outputBasePath, outputName + extension);
                        using (var output = File.Create(outputPath))
                        {
                            data.Position = 0;
                            output.WriteFromStream(data, data.Length);
                        }
                    }
                }
            }

            dataManager.Dispose();
        }
 protected override CSharpSelectionValidator CreateSelectionValidator(SemanticDocument document, TextSpan textSpan, OptionSet options)
 => new CSharpSelectionValidator(document, textSpan, options);
Пример #59
0
        static int Main(string[] args)
        {
            var exeName  = Path.GetFileName(Assembly.GetExecutingAssembly().Location);
            var showHelp = false;
            int exitCode = 0;

            var p = new OptionSet
            {
                "Copyright (c) Stride contributors (https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) All Rights Reserved",
                "Stride Effect Compiler Server - Version: "
                +
                String.Format(
                    "{0}.{1}.{2}",
                    typeof(Program).Assembly.GetName().Version.Major,
                    typeof(Program).Assembly.GetName().Version.Minor,
                    typeof(Program).Assembly.GetName().Version.Build) + string.Empty,
                string.Format("Usage: {0}", exeName),
                string.Empty,
                "=== Options ===",
                string.Empty,
                { "h|help", "Show this message and exit", v => showHelp = v != null },
            };

            try
            {
                var commandArgs = p.Parse(args);
                if (showHelp)
                {
                    p.WriteOptionDescriptions(Console.Out);
                    return(0);
                }

                // Make sure path exists
                if (commandArgs.Count > 0)
                {
                    throw new OptionException("This command expect no additional arguments", "");
                }

                var effectCompilerServer = new EffectCompilerServer();
                effectCompilerServer.TryConnect("127.0.0.1", RouterClient.DefaultPort);

                AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) =>
                {
                    var e = eventArgs.ExceptionObject as Exception;
                    if (e == null)
                    {
                        return;
                    }

                    Console.WriteLine($"Unhandled Exception: {e.Message.ToString()}");
                };

                // Forbid process to terminate (unless ctrl+c)
                while (true)
                {
                    Console.Read();
                    Thread.Sleep(100);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("{0}: {1}", exeName, e);
                if (e is OptionException)
                {
                    p.WriteOptionDescriptions(Console.Out);
                }
                exitCode = 1;
            }

            return(exitCode);
        }
Пример #60
0
        public static void Main(string[] args)
        {
            string      community      = "public";
            bool        showHelp       = false;
            bool        showVersion    = false;
            VersionCode version        = VersionCode.V1;
            int         timeout        = 1000;
            int         retry          = 0;
            int         maxRepetitions = 10;
            Levels      level          = Levels.Reportable;
            string      user           = string.Empty;
            string      authentication = string.Empty;
            string      authPhrase     = string.Empty;
            string      privacy        = string.Empty;
            string      privPhrase     = string.Empty;
            WalkMode    mode           = WalkMode.WithinSubtree;
            bool        dump           = false;

            OptionSet p = new OptionSet()
                          .Add("c:", "Community name, (default is public)", delegate(string v) { if (v != null)
                                                                                                 {
                                                                                                     community = v;
                                                                                                 }
                               })
                          .Add("l:", "Security level, (default is noAuthNoPriv)", delegate(string v)
            {
                if (v.ToUpperInvariant() == "NOAUTHNOPRIV")
                {
                    level = Levels.Reportable;
                }
                else if (v.ToUpperInvariant() == "AUTHNOPRIV")
                {
                    level = Levels.Authentication | Levels.Reportable;
                }
                else if (v.ToUpperInvariant() == "AUTHPRIV")
                {
                    level = Levels.Authentication | Levels.Privacy | Levels.Reportable;
                }
                else
                {
                    throw new ArgumentException("no such security mode: " + v);
                }
            })
                          .Add("a:", "Authentication method (MD5 or SHA)", delegate(string v) { authentication = v; })
                          .Add("A:", "Authentication passphrase", delegate(string v) { authPhrase = v; })
                          .Add("x:", "Privacy method", delegate(string v) { privacy = v; })
                          .Add("X:", "Privacy passphrase", delegate(string v) { privPhrase = v; })
                          .Add("u:", "Security name", delegate(string v) { user = v; })
                          .Add("h|?|help", "Print this help information.", delegate(string v) { showHelp = v != null; })
                          .Add("V", "Display version number of this application.", delegate(string v) { showVersion = v != null; })
                          .Add("d", "Display message dump", delegate(string v) { dump = true; })
                          .Add("t:", "Timeout value (unit is second).", delegate(string v) { timeout = int.Parse(v) * 1000; })
                          .Add("r:", "Retry count (default is 0)", delegate(string v) { retry = int.Parse(v); })
                          .Add("v|version:", "SNMP version (1, 2, and 3 are currently supported)", delegate(string v)
            {
                switch (int.Parse(v))
                {
                case 1:
                    version = VersionCode.V1;
                    break;

                case 2:
                    version = VersionCode.V2;
                    break;

                case 3:
                    version = VersionCode.V3;
                    break;

                default:
                    throw new ArgumentException("no such version: " + v);
                }
            })
                          .Add("m|mode:", "WALK mode (subtree, all are supported)", delegate(string v)
            {
                if (v == "subtree")
                {
                    mode = WalkMode.WithinSubtree;
                }
                else if (v == "all")
                {
                    mode = WalkMode.Default;
                }
                else
                {
                    throw new ArgumentException("unknown argument: " + v);
                }
            })
                          .Add("Cr:", "Max-repetitions (default is 10)", delegate(string v) { maxRepetitions = int.Parse(v); });

            if (args.Length == 0)
            {
                ShowHelp(p);
                return;
            }

            List <string> extra;

            try
            {
                extra = p.Parse(args);
            }
            catch (OptionException ex)
            {
                Console.WriteLine(ex.Message);
                return;
            }

            if (showHelp)
            {
                ShowHelp(p);
                return;
            }

            if (extra.Count < 1 || extra.Count > 2)
            {
                Console.WriteLine("invalid variable number: " + extra.Count);
                return;
            }

            if (showVersion)
            {
                Console.WriteLine(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
                return;
            }

            IPAddress ip;
            bool      parsed = IPAddress.TryParse(extra[0], out ip);

            if (!parsed)
            {
                foreach (IPAddress address in
                         Dns.GetHostAddresses(extra[0]).Where(address => address.AddressFamily == AddressFamily.InterNetwork))
                {
                    ip = address;
                    break;
                }

                if (ip == null)
                {
                    Console.WriteLine("invalid host or wrong IP address found: " + extra[0]);
                    return;
                }
            }

            try
            {
                ObjectIdentifier test     = extra.Count == 1 ? new ObjectIdentifier("1.3.6.1.2.1") : new ObjectIdentifier(extra[1]);
                IList <Variable> result   = new List <Variable>();
                IPEndPoint       receiver = new IPEndPoint(ip, 161);
                if (version == VersionCode.V1)
                {
                    Messenger.Walk(version, receiver, new OctetString(community), test, result, timeout, mode);
                }
                else if (version == VersionCode.V2)
                {
                    Messenger.BulkWalk(version, receiver, new OctetString(community), test, result, timeout, maxRepetitions, mode, null, null);
                }
                else
                {
                    if (string.IsNullOrEmpty(user))
                    {
                        Console.WriteLine("User name need to be specified for v3.");
                        return;
                    }

                    IAuthenticationProvider auth = (level & Levels.Authentication) == Levels.Authentication
                        ? GetAuthenticationProviderByName(authentication, authPhrase)
                        : DefaultAuthenticationProvider.Instance;
                    IPrivacyProvider priv;
                    if ((level & Levels.Privacy) == Levels.Privacy)
                    {
                        priv = new DESPrivacyProvider(new OctetString(privPhrase), auth);
                    }
                    else
                    {
                        priv = new DefaultPrivacyProvider(auth);
                    }

                    Discovery     discovery = Messenger.GetNextDiscovery(SnmpType.GetBulkRequestPdu);
                    ReportMessage report    = discovery.GetResponse(timeout, receiver);
                    Messenger.BulkWalk(version, receiver, new OctetString(user), test, result, timeout, maxRepetitions, mode, priv, report);
                }

                foreach (Variable variable in result)
                {
                    Console.WriteLine(variable);
                }
            }
            catch (SnmpException ex)
            {
                Console.WriteLine(ex);
            }
            catch (SocketException ex)
            {
                Console.WriteLine(ex);
            }
        }