Inheritance: MonoBehaviour
        public static string RenderFormGroupRadioButton(HtmlHelper html, RadioButtonModel inputModel, LabelModel labelModel)
        {
            var validationMessage = "";
            var radioType = "form-icon";

            if (inputModel.displayValidationMessage)
            {
                var validation = html.ValidationMessage(inputModel.htmlFieldName).ToHtmlString();
                validationMessage = new HelpText(validation, inputModel.validationMessageStyle).ToHtmlString();
            }

            if (labelModel == null && inputModel.RadioType != InputRadioCheckBoxType._NotSet)
                radioType = inputModel.RadioType.ToName();

            var label = RenderLabel(html, labelModel ?? new LabelModel
            {
                htmlFieldName = inputModel.htmlFieldName,
                metadata = inputModel.metadata,
                innerInputType = InputType.Radio,
                innerInputModel = inputModel,
                innerValidationMessage = validationMessage,
                htmlAttributes = new {@class = $"form-radio {radioType} form-text"}.ToDictionary()
            });

            var fieldIsValid = true;

            if (inputModel != null)
                fieldIsValid = html.ViewData.ModelState.IsValidField(inputModel.htmlFieldName);

            return new FormGroup(null, label, FormGroupType.CheckBoxLike, fieldIsValid).ToHtmlString();
        }
Exemplo n.º 2
0
    void HandleParsingErrorsInHelp(HelpText help)
    {
        if (this.LastPostParsingState.Errors.Count > 0)
        {
            var errors = help.RenderParsingErrorsText(this, 2); // indent with two spaces
            if (!string.IsNullOrEmpty(errors))
            {

                help.AddPreOptionsLine(string.Concat(Environment.NewLine, "ERROR(S):"));
                help.AddPreOptionsLine(errors);
            }
        }
    }
Exemplo n.º 3
0
        public void AddOptionsWithDashes()
        {
            var local = new HelpText {
                AddDashesToOption = true,
                Heading = new HeadingInfo("AddOptionsWithDashes"),
                Copyright = new CopyrightInfo("Author", DateTime.Now.Year)
            };
            local.AddOptions(new MockOptionsSimple());

            string help = local.ToString();

            Console.WriteLine(help);

            string[] lines = help.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            lines[3].Should().Equal("  -s, --something    Input something here.");
        }
Exemplo n.º 4
0
        public void CustomizeOptionsFormat()
        {
            var local = new HelpText("Customizing Test.");
            local.FormatOptionHelpText += new EventHandler<FormatOptionHelpTextEventArgs>(CustomizeOptionsFormat_FormatOptionHelpText);
            local.AddPreOptionsLine("Pre-Options.");
            local.AddOptions(new MockOptionsWithDescription());
            local.AddPostOptionsLine("Post-Options.");

            string help = local.ToString();

            Console.WriteLine(help);

            string[] lines = help.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            Assert.AreEqual("Customizing Test.", lines[0]);
            Assert.AreEqual("Pre-Options.", lines[1]);
            Assert.AreEqual("  v, verbose       Kommentar umfassend Operationen.", lines[3]);
            Assert.AreEqual("  i, input-file    Erforderlich. Gibt den Eingang an zu bearbeitenden Datei.", lines[4]);
            Assert.AreEqual("Post-Options.", lines[6]);
        }
Exemplo n.º 5
0
        public static HtmlString RenderTextArea(HtmlHelper html, TextAreaModel model)
        {
            var validationMessage = "";

            if (model.displayValidationMessage)
            {
                var validation = html.ValidationMessage(model.htmlFieldName).ToHtmlString();
                validationMessage = new HelpText(validation, model.validationMessageStyle).ToHtmlString();
            }

            model.htmlAttributes.MergeHtmlAttributes(html.GetUnobtrusiveValidationAttributes(model.htmlFieldName, model.metadata));

            if (!string.IsNullOrEmpty(model.id))
                model.htmlAttributes.AddOrReplace("id", model.id);

            if (!string.IsNullOrEmpty(model.placeholder))
                model.htmlAttributes.Add("placeholder", model.placeholder);

            model.htmlAttributes.AddOrMergeCssClass("class", "form-control");

            var htmlTextArea =
                html.TextArea(model.htmlFieldName, model.value, model.rows, model.columns,
                    model.htmlAttributes.FormatHtmlAttributes()).ToHtmlString() + validationMessage;

            TagBuilder inputWrapper = null;

            if (!string.IsNullOrEmpty(model.inputElementWrapper))
            {
                inputWrapper = new TagBuilder(model.inputElementWrapper);

                if (model.inputElementWrapperAttributes != null)
                    inputWrapper.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(model.inputElementWrapperAttributes));

                inputWrapper.InnerHtml = htmlTextArea;
            }

            var htmlString = inputWrapper != null
                ? inputWrapper.ToString(TagRenderMode.Normal)
                : htmlTextArea;

            return new HtmlString(htmlString);
        }
        public static HtmlString RenderRadioButton(HtmlHelper html, RadioButtonModel model)
        {
            model.htmlAttributes.MergeHtmlAttributes(html.GetUnobtrusiveValidationAttributes(model.htmlFieldName, model.metadata));

            if (!string.IsNullOrEmpty(model.id))
                model.htmlAttributes.AddOrReplace("id", model.id);

            var validationMessage = "";

            if (model.displayValidationMessage)
            {
                var validation = html.ValidationMessage(model.htmlFieldName).ToHtmlString();
                validationMessage = new HelpText(validation, model.validationMessageStyle).ToHtmlString();
            }

            return
                new HtmlString(
                    html.RadioButton(model.htmlFieldName, model.value, model.isChecked, model.htmlAttributes.FormatHtmlAttributes())
                        .ToHtmlString() + validationMessage);
        }
Exemplo n.º 7
0
 public string GetUsage()
 {
     return(HelpText.AutoBuild(this, current => HelpText.DefaultParsingErrorsHandler(this, current)));
 }
Exemplo n.º 8
0
        public static HtmlString RenderTextBox(HtmlHelper html, TextBoxModel model, bool isPassword)
        {
            var combinedHtml = "{0}{1}{2}";

            model.htmlAttributes.MergeHtmlAttributes(html.GetUnobtrusiveValidationAttributes(model.htmlFieldName, model.metadata));

            if (!string.IsNullOrEmpty(model.id))
                model.htmlAttributes.Add("id", model.id);

            if (!string.IsNullOrEmpty(model.placeholder))
                model.htmlAttributes.Add("placeholder", model.placeholder);

            if (model.size != Size._NotSet)
                model.htmlAttributes.AddOrMergeCssClass("class", $"input-{model.size.ToName()}");

            model.htmlAttributes.AddOrMergeCssClass("class", "form-control");

            var input = isPassword
                ? html.Password(model.htmlFieldName, null, model.htmlAttributes.FormatHtmlAttributes()).ToHtmlString()
                : html.TextBox(model.htmlFieldName, model.value, model.format, model.htmlAttributes.FormatHtmlAttributes())
                    .ToHtmlString();

            // account for appendString, prependString, and AppendButtons
            if (!string.IsNullOrEmpty(model.prependString) || !string.IsNullOrEmpty(model.appendString) ||
                model.iconPrepend != Icons._not_set
                || model.iconAppend != Icons._not_set || !string.IsNullOrEmpty(model.iconPrependCustomClass) ||
                !string.IsNullOrEmpty(model.iconAppendCustomClass))
            {
                var appendPrependContainer = new TagBuilder("div");
                appendPrependContainer.AddOrMergeCssClass("input-group");
                appendPrependContainer.AddOrMergeCssClass("mar-btm");

                var addOnPrependString = "";
                var addOnAppendString = "";
                var addOnPrependIcon = "";
                var addOnAppendIcon = "";

                var addOn = new TagBuilder("span");
                addOn.AddCssClass("input-group-addon");

                if (!string.IsNullOrEmpty(model.prependString))
                {
                    addOn.InnerHtml = model.prependString;
                    addOnPrependString = addOn.ToString();
                }

                if (!string.IsNullOrEmpty(model.appendString))
                {
                    addOn.InnerHtml = model.appendString;
                    addOnAppendString = addOn.ToString();
                }

                if (model.iconPrepend != Icons._not_set)
                {
                    addOn.InnerHtml = new Icon(model.iconPrepend, model.iconPrependIsWhite).ToHtmlString();
                    addOnPrependIcon = addOn.ToString();
                }

                if (model.iconAppend != Icons._not_set)
                {
                    addOn.InnerHtml = new Icon(model.iconAppend, model.iconAppendIsWhite).ToHtmlString();
                    addOnAppendIcon = addOn.ToString();
                }

                if (!string.IsNullOrEmpty(model.iconPrependCustomClass))
                {
                    var i = new TagBuilder("i");
                    i.AddCssClass(model.iconPrependCustomClass);
                    addOn.InnerHtml = i.ToString(TagRenderMode.Normal);
                    addOnPrependIcon = addOn.ToString();
                }

                if (!string.IsNullOrEmpty(model.iconAppendCustomClass))
                {
                    var i = new TagBuilder("i");
                    i.AddCssClass(model.iconAppendCustomClass);
                    addOn.InnerHtml = i.ToString(TagRenderMode.Normal);
                    addOnAppendIcon = addOn.ToString();
                }

                appendPrependContainer.InnerHtml = addOnPrependIcon + addOnPrependString + "{0}" + addOnAppendString +
                                                   addOnAppendIcon;
                combinedHtml = appendPrependContainer.ToString(TagRenderMode.Normal) + "{1}{2}";
            }

            var helpText = model.helpText != null ? model.helpText.ToHtmlString() : string.Empty;
            var validationMessage = "";

            if (model.displayValidationMessage)
            {
                var validation = html.ValidationMessage(model.htmlFieldName).ToHtmlString();
                validationMessage = new HelpText(validation, model.validationMessageStyle).ToHtmlString();
            }

            var htmlTextBox = string.Format(combinedHtml, input, helpText, validationMessage);

            TagBuilder inputWrapper = null;

            if (!string.IsNullOrEmpty(model.inputElementWrapper))
            {
                inputWrapper = new TagBuilder(model.inputElementWrapper);

                if (model.inputElementWrapperAttributes != null)
                    inputWrapper.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(model.inputElementWrapperAttributes));

                inputWrapper.InnerHtml = htmlTextBox;
            }

            var htmlString = inputWrapper != null
                ? inputWrapper.ToString(TagRenderMode.Normal)
                : htmlTextBox;

            return new HtmlString(htmlString);
        }
Exemplo n.º 9
0
 public string Usage()
 {
     return(HelpText.AutoBuild(this, c => HelpText.DefaultParsingErrorsHandler(this, c)));
 }
Exemplo n.º 10
0
        // Parse all options for all plugins
        public static bool ParsePluginOptions(IEnumerable <string> pluginOptions, Type[] optionsTypes)
        {
            var hasErrors = false;

            // Run CommandLine parser on each set of plugin options
            foreach (var options in pluginOptions)
            {
                var selectedPlugin = options.Split(' ')[0].ToLower();

                // Cause an error on the first plugin arguments if no plugins are loaded
                if (optionsTypes.Length == 0)
                {
                    Console.Error.WriteLine($"The requested plugin '{selectedPlugin}' does not exist or is not loaded");
                    hasErrors = true;
                    continue;
                }

                // Parse plugin arguments
                var parser = new Parser(with => {
                    with.HelpWriter    = null;
                    with.CaseSensitive = false;
                    with.AutoHelp      = false;
                    with.AutoVersion   = false;
                });
                var result = parser.ParseArguments(options.Split(' '), optionsTypes);

                // Print plugin help if parsing failed
                if (result is NotParsed <object> notParsed)
                {
                    if (!(notParsed.Errors.First() is BadVerbSelectedError))
                    {
                        var helpText = HelpText.AutoBuild(result, h => {
                            h.Heading     = $"Usage for plugin '{selectedPlugin}':";
                            h.Copyright   = string.Empty;
                            h.AutoHelp    = false;
                            h.AutoVersion = false;
                            return(h);
                        }, e => e);
                        Console.Error.WriteLine(helpText);
                    }
                    else
                    {
                        Console.Error.WriteLine($"The requested plugin '{selectedPlugin}' does not exist or is not loaded");
                    }
                    hasErrors = true;
                    continue;
                }

                // Get plugin arguments and write them to plugin options class
                var optionsObject = (result as Parsed <object>).Value;
                var plugin        = PluginManager.AvailablePlugins.First(p => optionsObject.GetType().FullName == p.Id + "Options");

                foreach (var prop in optionsObject.GetType().GetProperties())
                {
                    var targetProp = plugin.Options.First(x => x.Name == prop.Name);
                    var value      = prop.GetValue(optionsObject);

                    // TODO: Use IPluginOption.SetFromString() instead

                    // Validate hex strings
                    if (targetProp is IPluginOptionNumber n && n.Style == PluginOptionNumberStyle.Hex)
                    {
                        try {
                            n.Value = Convert.ChangeType(Convert.ToInt64((string)value, 16), n.Value.GetType());
                        }
                        catch (Exception ex) when(ex is ArgumentException || ex is FormatException || ex is OverflowException)
                        {
                            Console.Error.WriteLine($"Plugin option error: {prop.Name} must be a hex value (optionally starting with '0x'), and less than the maximum value");
                            hasErrors = true;
                        }
                    }
Exemplo n.º 11
0
            public string GetUsage()
            {
                var help = new HelpText(new HeadingInfo("unittest", "1.9"));
                help.AdditionalNewLineAfterOption = true;
                help.Copyright = new CopyrightInfo("CommandLine.dll Author", 2005, 2011);

                // handling parsing error code
                string errors = help.RenderParsingErrorsText(this, 2); // indent with two spaces
                if (!string.IsNullOrEmpty(errors))
                {
                    help.AddPreOptionsLine(string.Concat(Environment.NewLine, "ERROR(S):"));
                    help.AddPreOptionsLine(errors);
                }

                help.AddPreOptionsLine("This is free software. You may redistribute copies of it under the terms of");
                help.AddPreOptionsLine("the MIT License <http://www.opensource.org/licenses/mit-license.php>.");
                help.AddPreOptionsLine("Usage: Please run the unit...");
                help.AddOptions(this);

                return help;
            }
Exemplo n.º 12
0
        public void PostOptionsLinesFeatureAdded()
        {
            var local = new HelpText("Heading Info.");
            local.AddPreOptionsLine("This is a first pre-options line.");
            local.AddPreOptionsLine("This is a second pre-options line.");
            local.AddOptions(new MockOptions());
            local.AddPostOptionsLine("This is a first post-options line.");
            local.AddPostOptionsLine("This is a second post-options line.");

            string help = local.ToString();

            string[] lines = help.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            Assert.AreEqual(lines[lines.Length - 2], "This is a first post-options line.");
            Assert.AreEqual(lines[lines.Length - 1], "This is a second post-options line.");
        }
Exemplo n.º 13
0
        static void Main(string[] args)
        {
            try
            {
                ParserResult = Parser.Default.ParseArguments <Options>(args);
                ParserResult.WithParsed <Options>(o =>
                {
                    Keyboard keyboard = null;

                    ConsoleLogger.Enabled = o.Verbose;

                    if (o.ShowAll || o.Profile > 0 || o.DefaultProfile || o.InitProfile > 0)
                    {
                        keyboard = new Keyboard();

                        if (o.ShowAll)
                        {
                            $"ShowAll".ConsoleLogLine();

                            keyboard?.ShowAllDevices();
                        }

                        if (o.Profile > 0 && o.DefaultProfile)
                        {
                            throw new InvalidOperationException("Cant specify default and numbered profiles");
                        }

                        if (o.Profile > 0)
                        {
                            $"Profile {o.Profile}".ConsoleLogLine();

                            ValidateProfile(o.Profile);
                            var profResponse = keyboard?.Connect()?.Result?.Device.SetProfile(o.Profile)?.Result;
                        }
                        else if (o.DefaultProfile)
                        {
                            $"DefaultProfile {o.DefaultProfile}".ConsoleLogLine();

                            int defaultProfile;
                            if (!int.TryParse(ConfigurationManager.AppSettings["DefaultProfile"], out defaultProfile))
                            {
                                ValidateProfile(0);
                            }
                            var defResponse = keyboard?.Connect()?.Result?.Device.SetProfile(defaultProfile)?.Result;
                        }
                        if (o.InitProfile > 0)
                        {
                            $"InitProfile {o.InitProfile}".ConsoleLogLine();

                            ValidateProfile(o.InitProfile);
                            keyboard.DefaultProfile = o.InitProfile;
                            keyboard.Listen();
                            while (true)
                            {
                                Thread.Sleep(1000);
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine(HelpText.AutoBuild(ParserResult, h => h, e => e));
                    }
                })
                .WithNotParsed(errs =>
                {
                    Console.WriteLine("Parser Fail");
                    errs.ConsoleLogLine();
                });
            }
            catch (Exception ex)
            {
                ConsoleLogger.Enabled = true;
                ex.ConsoleLogLine();
                throw;
            }
        }
Exemplo n.º 14
0
        public void Create_basic_instance()
        {
            var local = new HelpText();

            local.ToString().Should().Be("");
        }
Exemplo n.º 15
0
        private static void Main(string[] args)
        {
            var options = new TailFeatherCommandLineOptions();

            if (Parser.Default.ParseArguments(args, options) == false)
            {
                var autoBuild = HelpText.AutoBuild(options);
                HelpText.DefaultParsingErrorsHandler(options, autoBuild);
                Console.WriteLine(autoBuild.ToString());
                return;
            }

            var nodeName = options.NodeName ?? (Environment.MachineName + ":" + options.Port);

            Console.Title = string.Format("Node name: {0}, port: {1}", nodeName, options.Port);

            var kvso = StorageEnvironmentOptions.ForPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, options.DataPath, "KeyValue"));

            using (var statemachine = new KeyValueStateMachine(kvso))
            {
                var storageEnvironmentOptions = StorageEnvironmentOptions.ForPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, options.DataPath, "Raft"));
                var httpTransport             = new HttpTransport(nodeName);
                var raftEngineOptions         = new RaftEngineOptions(
                    new NodeConnectionInfo
                {
                    Name = nodeName,
                    Uri  = new Uri("http://" + Environment.MachineName + ":" + options.Port),
                },
                    storageEnvironmentOptions,
                    httpTransport,
                    statemachine
                    )
                {
                    ElectionTimeout              = 5 * 1000,
                    HeartbeatTimeout             = 1000,
                    MaxLogLengthBeforeCompaction = 25
                };

                if (options.Boostrap)
                {
                    PersistentState.ClusterBootstrap(raftEngineOptions);
                    Console.WriteLine("Setup node as the cluster seed, exiting...");
                    return;
                }

                using (var raftEngine = new RaftEngine(raftEngineOptions))
                {
                    using (WebApp.Start(new StartOptions
                    {
                        Urls = { "http://+:" + options.Port + "/" }
                    }, builder =>
                    {
                        var httpConfiguration = new HttpConfiguration();
                        httpConfiguration.Formatters.Remove(httpConfiguration.Formatters.XmlFormatter);
                        httpConfiguration.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
                        httpConfiguration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
                        RaftWebApiConfig.Load();
                        httpConfiguration.MapHttpAttributeRoutes();
                        httpConfiguration.Properties[typeof(HttpTransportBus)] = httpTransport.Bus;
                        httpConfiguration.Properties[typeof(RaftEngine)] = raftEngine;
                        builder.UseWebApi(httpConfiguration);
                    }))
                    {
                        Console.WriteLine("Ready @ http://" + Environment.MachineName + ":" + options.Port + "/, press ENTER to stop");

                        Console.ReadLine();
                    }
                }
            }
        }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            // Setup custom parser to set case sensitive off
            var parser = new Parser(settings =>
            {
                settings.CaseSensitive             = false;
                settings.CaseInsensitiveEnumValues = false;
                settings.HelpWriter = Console.Error;  // reroute back to Console.Error for messages
            });

            //            var result = Parser.Default.ParseArguments<Options>(args)
            var result = parser.ParseArguments <Options>(args)
                         .WithParsed(optionsChecker) // was .WithParsed(opt => options = opt) to just set options to parsed
                         .WithNotParsed(HandleParseError);

            if (options == null || Error == true)
            {
                if (!HelpShown)
                {
                    Console.WriteLine("HM-PS Control CMD Ver {0} by Mcken Mak 2020\nUse on HanmaTEK power Supply HM310P or lower model.",
                                      System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
                    Console.WriteLine("\n\n" + HelpText.AutoBuild(result, _ => _, _ => _) + "\nERROR - See above");
                    HelpShown = true;
                }
                return;
            }
            if (!options.Silent)
            {
                Console.WriteLine("HM-PS Control CMD Ver {0} by Mcken Mak 2020\nUse on HanmaTEK power Supply HM310P or lower model.",
                                  System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
            }

            psu = new HanmatekPS();
            try
            {
                // Options that do not operate PSU or will terminate
                if (options.ListCOMPorts)
                {
                    Console.WriteLine("\nList COM ports in the system:");
                    string[] ports = SerialPort.GetPortNames();
                    Array.Sort(ports, StringComparer.InvariantCulture);
                    foreach (string p1 in ports)
                    {
                        Console.Write("{0} ", p1);
                    }
                    Console.WriteLine("\n\nExit skips any PSU task.");
                    return;
                }

                // Start PSU operations
                if (!psu.Open(options.comPort))
                {
                    Console.WriteLine("Open COM port [{1}] Error: {0}", psu.getModbugStatus(), options.comPort);
                    return;
                }

                if (options.ShowPSU)
                {
                    ShowPSUInfo();
                }
                // Set Basics
                if (options.setVoltageStr != null && (options.setCurrentLimitStr != null))  // set both for faster performance
                {
                    ushort Volt = ConvCheckValue(options.setVoltageStr, 2, 0.0F, 32.0F, "SetVol");
                    ushort Curr = ConvCheckValue(options.setCurrentLimitStr, 3, 0.0F, 10.10F, "SetCur");
                    if (!options.Silent)
                    {
                        Console.WriteLine("Set both Vol[{0}/{1}]/Cur[{2}/{3}].", options.setVoltageStr, Volt, options.setCurrentLimitStr, Curr);
                    }
                    psu.setVoltageAndCurrent(Volt, Curr);
                }
                else
                {
                    if (options.setVoltageStr != null)
                    {
                        ushort val = ConvCheckValue(options.setVoltageStr, 2, 0.0F, 32.0F, "SetVol");

                        if (!options.Silent)
                        {
                            Console.WriteLine("Setting Voltage to [{0}]/{1}", options.setVoltageStr, val);
                        }
                        psu.setVoltage(val);
                    }
                    if (options.setCurrentLimitStr != null)
                    {
                        ushort val = ConvCheckValue(options.setCurrentLimitStr, 3, 0.0F, 10.10F, "SetCur");

                        if (!options.Silent)
                        {
                            Console.WriteLine("Setting Current limit to [{0}]/{1}", options.setCurrentLimitStr, val);
                        }
                        psu.setCurrent(val);
                    }
                }
                // Set Protections
                if (options.setOVPStr != null)
                {
                    ushort val = ConvCheckValue(options.setOVPStr, 2, 0.0F, 33.0F, "setOVP");

                    if (!options.Silent)
                    {
                        Console.WriteLine("Setting Over Voltage Protection to [{0}]/{1}, need to set manually", options.setOVPStr, val);
                    }
                    psu.setOVP(val);
                }
                if (options.setOCPStr != null)
                {
                    ushort val = ConvCheckValue(options.setOCPStr, 3, 0.0F, 10.50F, "setOCP");

                    if (!options.Silent)
                    {
                        Console.WriteLine("Setting Over Current Protection to [{0}]/{1}, need to set manually", options.setOCPStr, val);
                    }
                    psu.setOCP(val);
                }

                // Set Switches
                if (options.SetBuzzer != OnOffSwitch.__NotDefined__)
                {
                    if (!options.Silent)
                    {
                        Console.WriteLine("Buzzer set to [{0}]", options.SetBuzzer);
                    }
                    psu.setBuzzer(options.SetBuzzer == OnOffSwitch.On ? true : false);
                }


                if (options.SetPowerSwitch != OnOffSwitch.__NotDefined__)
                {
                    if (!options.Silent)
                    {
                        Console.WriteLine("Power set to [{0}]", options.SetPowerSwitch);
                    }
                    psu.setPower(options.SetPowerSwitch == OnOffSwitch.On ? true : false);
                }
                psu.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
            }
        }
Exemplo n.º 17
0
 public string GetUsage()
 {
     return("\n\t\tExcel格式转换和C#代码生成工具\n\n" + HelpText.AutoBuild(this, (HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current)));
 }
        public static HtmlString RenderInputListContainer(HtmlHelper html, string htmlFieldName, List<string> inputs,
			int? numberOfColumns, bool displayInColumnsCondition,
			int columnPixelWidth, bool displayInlineBlock, int marginRightPx, bool displayValidationMessage,
			HelpTextStyle validationMessageStyle, InputType inputType, CheckBoxRadioStyle inputStyle)
        {
            var cssClass = inputType == InputType.CheckBoxList ? "checkbox" : "radio";
            var displayStyle = inputStyle == CheckBoxRadioStyle.Block ? "form-block" : "form-inline";

            var container = new TagBuilder("div");
            container.AddCssClass($"{cssClass} {displayStyle}");

            if (displayValidationMessage)
            {
                container.AddCssStyle("display", "inline-block");
                container.AddCssStyle("vertical-align", "middle");
                container.AddCssStyle("margin-top", "4px");
            }

            if (numberOfColumns.HasValue && displayInColumnsCondition)
            {
                container.AddCssStyle("max-width", columnPixelWidth*numberOfColumns + "px");
                var columnedInputs = new List<string>();
                var columnDiv = new TagBuilder("div");

                columnDiv.AddCssClass("input-list-column");
                columnDiv.AddCssStyle("width", columnPixelWidth + "px");
                columnDiv.AddCssStyle("display", "inline-block");

                foreach (var input in inputs)
                {
                    columnDiv.InnerHtml = input;
                    columnedInputs.Add(columnDiv.ToString());
                }

                inputs = columnedInputs;
            }

            if (displayInlineBlock)
            {
                var columnedInputs = new List<string>();
                var columnDiv = new TagBuilder("div");
                columnDiv.AddCssClass("input-list-inline");
                columnDiv.AddCssStyle("display", "inline-block");
                columnDiv.AddCssStyle("margin-right", marginRightPx + "px");

                foreach (var input in inputs)
                {
                    columnDiv.InnerHtml = input;
                    columnedInputs.Add(columnDiv.ToString());
                }

                inputs = columnedInputs;
            }

            var inputsCombined = string.Empty;
            inputs.ForEach(c => inputsCombined += c);
            container.InnerHtml = inputsCombined;

            var validationMessage = "";

            if (displayValidationMessage)
            {
                var validation = html.ValidationMessage(htmlFieldName).ToHtmlString();
                validationMessage = new HelpText(validation, validationMessageStyle).ToHtmlString();
            }

            return new HtmlString(container.ToString(TagRenderMode.Normal) + validationMessage);
        }
Exemplo n.º 19
0
        private static async void App(Options options)
        {
            IMetastore <JObject> metastore            = null;
            KeyManagementService keyManagementService = null;

            if (options.Metastore == Metastore.ADO)
            {
                if (options.AdoConnectionString != null)
                {
                    logger.LogInformation("using ADO-based metastore...");
                    metastore = AdoMetastoreImpl
                                .NewBuilder(MySqlClientFactory.Instance, options.AdoConnectionString)
                                .Build();
                }
                else
                {
                    logger.LogError("ADO connection string is a mandatory parameter with Metastore Type: ADO");
                    Console.WriteLine(HelpText.AutoBuild(cmdOptions, null, null));
                    return;
                }
            }
            else if (options.Metastore == Metastore.DYNAMODB)
            {
                logger.LogInformation("using DynamoDB-based metastore...");
                AWSConfigs.AWSRegion = "us-west-2";
                metastore            = DynamoDbMetastoreImpl.NewBuilder().Build();
            }
            else
            {
                logger.LogInformation("using in-memory metastore...");
                metastore = new InMemoryMetastoreImpl <JObject>();
            }

            if (options.Kms == Kms.AWS)
            {
                if (options.PreferredRegion != null && options.RegionToArnTuples != null)
                {
                    Dictionary <string, string> regionToArnDictionary = new Dictionary <string, string>();
                    foreach (string regionArnPair in options.RegionToArnTuples)
                    {
                        string[] regionArnArray = regionArnPair.Split("=");
                        regionToArnDictionary.Add(regionArnArray[0], regionArnArray[1]);
                    }

                    logger.LogInformation("using AWS KMS...");
                    keyManagementService = AwsKeyManagementServiceImpl
                                           .NewBuilder(regionToArnDictionary, options.PreferredRegion).Build();
                }
                else
                {
                    logger.LogError("Preferred region and <region>=<arn> tuples are mandatory with  KMS Type: AWS");
                    Console.WriteLine(HelpText.AutoBuild(cmdOptions, null, null));
                    return;
                }
            }
            else
            {
                logger.LogInformation("using static KMS...");
                keyManagementService = new StaticKeyManagementServiceImpl("mysupersecretstaticmasterkey!!!!");
            }

            CryptoPolicy cryptoPolicy = BasicExpiringCryptoPolicy
                                        .NewBuilder()
                                        .WithKeyExpirationDays(KeyExpirationDays)
                                        .WithRevokeCheckMinutes(CacheCheckMinutes)
                                        .Build();

            // Setup metrics reporters and always include console.
            IMetricsBuilder metricsBuilder = new MetricsBuilder()
                                             .Report.ToConsole(consoleOptions => consoleOptions.FlushInterval = TimeSpan.FromSeconds(60));

            // CloudWatch metrics generation
            if (options.EnableCloudWatch)
            {
                // Fill in when we open source our App.Metrics cloudwatch reporter separately
            }

            IMetrics metrics = metricsBuilder.Build();

            // Create a session factory for this app. Normally this would be done upon app startup and the
            // same factory would be used anytime a new session is needed for a partition (e.g., shopper).
            // We've split it out into multiple using blocks to underscore this point.
            using (SessionFactory sessionFactory = SessionFactory
                                                   .NewBuilder("productId", "reference_app")
                                                   .WithMetastore(metastore)
                                                   .WithCryptoPolicy(cryptoPolicy)
                                                   .WithKeyManagementService(keyManagementService)
                                                   .WithMetrics(metrics)
                                                   .Build())
            {
                // Now create an actual session for a partition (which in our case is a pretend shopper id). This session is used
                // for a transaction and is disposed automatically after use due to the IDisposable implementation.
                using (Session <byte[], byte[]> sessionBytes =
                           sessionFactory.GetSessionBytes("shopper123"))
                {
                    const string originalPayloadString = "mysupersecretpayload";
                    foreach (int i in Enumerable.Range(0, options.Iterations))
                    {
                        string dataRowString;

                        // If we get a DRR as a command line argument, we want to directly decrypt it
                        if (options.Drr != null)
                        {
                            dataRowString = options.Drr;
                        }
                        else
                        {
                            // Encrypt the payload
                            byte[] dataRowRecordBytes =
                                sessionBytes.Encrypt(Encoding.UTF8.GetBytes(originalPayloadString));

                            // Consider this us "persisting" the DRR
                            dataRowString = Convert.ToBase64String(dataRowRecordBytes);
                        }

                        logger.LogInformation("dataRowRecord as string = {dataRow}", dataRowString);

                        byte[] newDataRowRecordBytes = Convert.FromBase64String(dataRowString);

                        // Decrypt the payload
                        string decryptedPayloadString =
                            Encoding.UTF8.GetString(sessionBytes.Decrypt(newDataRowRecordBytes));

                        logger.LogInformation("decryptedPayloadString = {payload}", decryptedPayloadString);
                        logger.LogInformation("matches = {result}", originalPayloadString.Equals(decryptedPayloadString));
                    }
                }
            }

            // Force final publish of metrics
            await Task.WhenAll(((IMetricsRoot)metrics).ReportRunner.RunAllAsync());
        }
Exemplo n.º 20
0
        public void Long_pre_and_post_lines_without_spaces()
        {
            var local = new HelpText("Heading Info.");
            local.MaximumDisplayWidth = 40;
            local.AddPreOptionsLine("Before 0123456789012345678901234567890123456789012 After");
            local.AddOptions(new MockOptions());
            local.AddPostOptionsLine("Before 0123456789012345678901234567890123456789 After");

            string help = local.ToString();

            string[] lines = help.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            lines[1].Should().Be("Before ");
            lines[2].Should().Be("0123456789012345678901234567890123456789");
            lines[3].Should().Be("012 After");
            lines[lines.Length - 3].Should().Be("Before ");
            lines[lines.Length - 2].Should().Be("0123456789012345678901234567890123456789");
            lines[lines.Length - 1].Should().Be(" After");
        }
Exemplo n.º 21
0
 public string DoHelpForVerb(string verbName)
 {
     return(HelpText.AutoBuild(this,
                               current => HelpText.DefaultParsingErrorsHandler(this, current),
                               true));
 }
Exemplo n.º 22
0
        public void When_help_text_is_longer_than_width_it_will_wrap_around_as_if_in_a_column()
        {
            var helpText = new HelpText(new HeadingInfo("CommandLine.Tests.dll", "1.9.4.131"));
            helpText.MaximumDisplayWidth = 40;
            helpText.AddOptions(new MockOptionsWithLongDescription());
            string help = helpText.ToString();

            string[] lines = help.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
            lines[2].Should().Be("  v, verbose    This is the description"); //"The first line should have the arguments and the start of the Help Text.");
            //string formattingMessage = "Beyond the second line should be formatted as though it's in a column.";
            lines[3].Should().Be("                of the verbosity to ");
            lines[4].Should().Be("                test out the wrapping ");
            lines[5].Should().Be("                capabilities of the ");
            lines[6].Should().Be("                Help Text.");
        }
Exemplo n.º 23
0
        public AppConfig()
        {
            // overwrite with application config
            if (Properties.Settings.Default.MachineId != "")
            {
                machineId = Properties.Settings.Default.MachineId;
            }
            if (Properties.Settings.Default.MasterIP != "")
            {
                masterIP = Properties.Settings.Default.MasterIP;
            }
            if (Properties.Settings.Default.MasterPort != 0)
            {
                masterPort = Properties.Settings.Default.MasterPort;
            }
            if (Properties.Settings.Default.SharedConfigFile != "")
            {
                sharedCfgFileName = Properties.Settings.Default.SharedConfigFile;
            }
            if (Properties.Settings.Default.LocalConfigFile != "")
            {
                localCfgFileName = Properties.Settings.Default.LocalConfigFile;
            }
            if (Properties.Settings.Default.StartupPlan != "")
            {
                startupPlanName = Properties.Settings.Default.StartupPlan;
            }
            if (Properties.Settings.Default.StartHidden != "")
            {
                startHidden = Properties.Settings.Default.StartHidden;
            }
            if (Properties.Settings.Default.Mode != "")
            {
                mode = Properties.Settings.Default.Mode;
            }
            if (Properties.Settings.Default.Mode != "")
            {
                mode = Properties.Settings.Default.Mode;
            }
            if (Properties.Settings.Default.IsMaster != "")
            {
                isMaster = Properties.Settings.Default.IsMaster;
            }
            if (Properties.Settings.Default.CLIPort != 0)
            {
                cliPort = Properties.Settings.Default.CLIPort;
            }

            // overwrite with command line options
            var    args = System.Environment.GetCommandLineArgs();
            string aaa  = HelpText.AutoBuild(options);

            if (CommandLine.Parser.Default.ParseArguments(args, options))
            {
                if (options.MachineId != "")
                {
                    machineId = options.MachineId;
                }
                if (options.MasterIP != "")
                {
                    masterIP = options.MasterIP;
                }
                if (options.MasterPort != 0)
                {
                    masterPort = options.MasterPort;
                }
                if (options.SharedConfigFile != "")
                {
                    sharedCfgFileName = options.SharedConfigFile;
                }
                if (options.LocalConfigFile != "")
                {
                    localCfgFileName = options.LocalConfigFile;
                }
                if (options.LogFile != "")
                {
                    logFileName = options.LogFile;
                }
                if (options.StartupPlan != "")
                {
                    startupPlanName = options.StartupPlan;
                }
                if (options.StartHidden != "")
                {
                    startHidden = options.StartHidden;
                }
                if (options.Mode != "")
                {
                    mode = options.Mode;
                }
                if (options.IsMaster != "")
                {
                    isMaster = options.IsMaster;
                }
                if (options.CLIPort != 0)
                {
                    cliPort = options.CLIPort;
                }
            }
            else
            {
                HadErrors = true;
            }


            if (logFileName != "")
            {
                SetLogFileName(Path.GetFullPath(logFileName));
            }

            if (sharedCfgFileName != "")
            {
                sharedCfgFileName = Path.GetFullPath(sharedCfgFileName);
                log.DebugFormat("Loading shared config file '{0}'", sharedCfgFileName);
                scfg = new SharedXmlConfigReader().Load(File.OpenText(sharedCfgFileName));
            }

            if (localCfgFileName != "")
            {
                localCfgFileName = Path.GetFullPath(localCfgFileName);
                log.DebugFormat("Loading local config file '{0}'", localCfgFileName);
                lcfg = new LocalXmlConfigReader().Load(File.OpenText(localCfgFileName));
            }
        }
        public static HtmlString RenderSelectElement(HtmlHelper html, SelectElementModel model, InputType inputType)
        {
            var combinedHtml = "{0}{1}{2}";
            var input = string.Empty;

            if (model.selectedValue != null)
            {
                foreach (var item in model.selectList)
                {
                    if (item.Value == model.selectedValue.ToString())
                        item.Selected = true;
                }
            }

            model.htmlAttributes.MergeHtmlAttributes(html.GetUnobtrusiveValidationAttributes(model.htmlFieldName, model.metadata));

            if (!string.IsNullOrEmpty(model.id)) model.htmlAttributes.AddOrReplace("id", model.id);

            if (model.size != Size._NotSet)
                model.htmlAttributes.AddOrMergeCssClass("class", $"input-{model.size.ToName()}");

            model.htmlAttributes.AddOrMergeCssClass("class", "form-control");

            // build html for input

            if (inputType == InputType.DropDownList)
                input =
                    html.DropDownList(model.htmlFieldName, model.selectList, model.optionLabel,
                        model.htmlAttributes.FormatHtmlAttributes()).ToHtmlString();

            if (inputType == InputType.ListBox)
                input =
                    html.ListBox(model.htmlFieldName, model.selectList, model.htmlAttributes.FormatHtmlAttributes()).ToHtmlString();

            // account for appendString, prependString, and AppendButtons

            if (!string.IsNullOrEmpty(model.prependString) || !string.IsNullOrEmpty(model.appendString))
            {
                var appendPrependContainer = new TagBuilder("div");
                var addOn = new TagBuilder("span");

                var addOnPrependString = "";
                var addOnAppendString = "";
                var addOnPrependButtons = "";
                var addOnAppendButtons = "";

                appendPrependContainer.AddOrMergeCssClass("input-group");
                addOn.AddCssClass("input-group-addon");

                if (!string.IsNullOrEmpty(model.prependString))
                {
                    addOn.InnerHtml = model.prependString;
                    addOnPrependString = addOn.ToString();
                }

                if (!string.IsNullOrEmpty(model.appendString))
                {
                    addOn.InnerHtml = model.appendString;
                    addOnAppendString = addOn.ToString();
                }

                appendPrependContainer.InnerHtml = addOnPrependButtons + addOnPrependString + "{0}" + addOnAppendString +
                                                   addOnAppendButtons;
                combinedHtml = appendPrependContainer.ToString(TagRenderMode.Normal) + "{1}{2}";
            }

            var helpText = model.helpText != null ? model.helpText.ToHtmlString() : string.Empty;
            var validationMessage = "";

            if (model.displayValidationMessage)
            {
                var validation = html.ValidationMessage(model.htmlFieldName).ToHtmlString();
                validationMessage = new HelpText(validation, model.validationMessageStyle).ToHtmlString();
            }

            var inputElement = string.Format(combinedHtml, input, helpText, validationMessage);

            TagBuilder inputWrapper = null;

            if (!string.IsNullOrEmpty(model.inputElementWrapper))
            {
                inputWrapper = new TagBuilder(model.inputElementWrapper);

                if (model.inputElementWrapperAttributes != null)
                    inputWrapper.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(model.inputElementWrapperAttributes));

                inputWrapper.InnerHtml = inputElement;
            }

            var htmlString = inputWrapper != null
                ? inputWrapper.ToString(TagRenderMode.Normal)
                : inputElement;

            return new HtmlString(htmlString);
        }
Exemplo n.º 25
0
        public string GetUsage()
        {
            var helpText = HelpText.AutoBuild(this, (HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current));

            return(helpText);
        }
Exemplo n.º 26
0
        public void CreateBasicInstance()
        {
            var local = new HelpText();

            local.ToString().Should().Equal("");
        }
Exemplo n.º 27
0
        private static int Main(string[] args)
        {
#if DEBUG // short command syntax
            if (args?.Length > 0)
            {
                switch (args[0])
                {
                case "f":
                {
                    ReplaceArgs("find");
                    break;
                }

                case "r":
                {
                    ReplaceArgs("replace");
                    break;
                }
                }

                void ReplaceArgs(string commandName)
                {
                    Array.Resize(ref args, args.Length + 1);

                    for (int i = args.Length - 1; i >= 2; i--)
                    {
                        args[i] = args[i - 1];
                    }

                    args[0] = commandName;
                    args[1] = "-c";
                }
            }
#endif
            try
            {
                Parser parser = CreateParser(ignoreUnknownArguments: true);

                if (args == null ||
                    args.Length == 0)
                {
                    HelpCommand.WriteCommandsHelp();
                    return(ExitCodes.Match);
                }

                var help = false;

                ParserResult <BaseCommandLineOptions> defaultResult = parser
                                                                      .ParseArguments <BaseCommandLineOptions>(args)
                                                                      .WithParsed(options =>
                {
                    if (!options.Help)
                    {
                        return;
                    }

                    string?commandName = args?.FirstOrDefault();
                    Command?command    = (commandName != null)
                            ? CommandLoader.LoadCommand(typeof(Program).Assembly, commandName)
                            : null;

                    ParseVerbosityAndOutput(options);
                    WriteArgs(args);

                    if (command != null)
                    {
                        HelpCommand.WriteCommandHelp(command);
                    }
                    else
                    {
                        HelpCommand.WriteCommandsHelp();
                    }

                    help = true;
                })
#if DEBUG
                                                                      .WithNotParsed(_ =>
                {
                });
#else
                ;
#endif

                if (help)
                {
                    return(ExitCodes.Match);
                }

                var success = true;

                parser = CreateParser();

                ParserResult <object> parserResult = parser.ParseArguments <
                    CopyCommandLineOptions,
                    DeleteCommandLineOptions,
                    EscapeCommandLineOptions,
                    FindCommandLineOptions,
                    HelpCommandLineOptions,
                    ListPatternsCommandLineOptions,
                    MatchCommandLineOptions,
                    MoveCommandLineOptions,
                    RenameCommandLineOptions,
                    ReplaceCommandLineOptions,
                    SplitCommandLineOptions
                    >(args);

                parserResult.WithNotParsed(_ =>
                {
                    var helpText = new HelpText(SentenceBuilder.Create(), HelpCommand.GetHeadingText());

                    helpText = HelpText.DefaultParsingErrorsHandler(parserResult, helpText);

                    VerbAttribute?verbAttribute = parserResult.TypeInfo.Current.GetCustomAttribute <VerbAttribute>();

                    if (verbAttribute != null)
                    {
                        helpText.AddPreOptionsText(Environment.NewLine + HelpCommand.GetFooterText(verbAttribute.Name));
                    }

                    Console.Error.WriteLine(helpText);

                    success = false;
                });

                if (!success)
                {
                    return(ExitCodes.Error);
                }

                parserResult.WithParsed <AbstractCommandLineOptions>(options =>
                {
                    success = ParseVerbosityAndOutput(options);
                    WriteArgs(args);
                });

                if (!success)
                {
                    return(ExitCodes.Error);
                }

                return(parserResult.MapResult(
                           (CopyCommandLineOptions options) => Copy(options),
                           (MoveCommandLineOptions options) => Move(options),
                           (DeleteCommandLineOptions options) => Delete(options),
                           (EscapeCommandLineOptions options) => Escape(options),
                           (FindCommandLineOptions options) => Find(options),
                           (HelpCommandLineOptions options) => Help(options),
                           (ListPatternsCommandLineOptions options) => ListPatterns(options),
                           (MatchCommandLineOptions options) => Match(options),
                           (RenameCommandLineOptions options) => Rename(options),
                           (ReplaceCommandLineOptions options) => Replace(options),
                           (SplitCommandLineOptions options) => Split(options),
                           _ => ExitCodes.Error));
            }
            catch (Exception ex)
            {
                WriteError(ex);
            }
            finally
            {
                Out?.Dispose();
                Out = null;
            }

            return(ExitCodes.Error);
        }
        public static HtmlString RenderRadioButtonPair(HtmlHelper html, RadioButtonPairModel model)
        {
            TagBuilder wrapper = null;
            var inputPairs = string.Empty;
            var fullHtmlFieldName = html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(model.htmlFieldName);
            var radioType = "form-icon";

            var pairOneValueIsSelected = false;
            var pairTwoValueIsSelected = false;

            if (model.metadata.Model != null)
            {
                pairOneValueIsSelected = model.inputPairOneValue.ToString() == model.metadata.Model.ToString();
                pairTwoValueIsSelected = model.inputPairOneValue.ToString() != model.metadata.Model.ToString();
            }

            if (model.RadioType != InputRadioCheckBoxType._NotSet)
                radioType = model.RadioType.ToName();

            var inputPairOne = RenderLabel(html, new LabelModel
            {
                htmlFieldName = model.htmlFieldName,
                labelText = model.labelPairOneText,
                metadata = model.metadata,
                htmlAttributes = model.htmlAttributesLabelPairOne.AddOrMergeCssClass("class", $"form-radio {radioType} form-text"),
                showRequiredStar = false,
                innerInputType = InputType.Radio,
                innerInputModel = new RadioButtonModel
                {
                    htmlFieldName = model.htmlFieldName,
                    value = model.inputPairOneValue,
                    metadata = model.metadata,
                    isChecked = pairOneValueIsSelected,
                    RadioType = model.RadioType,
                    htmlAttributes =
                        model.htmlAttributesInputPairOne.AddOrReplace("id", fullHtmlFieldName.FormatForMvcInputId() + "_pairOne")
                }
            });

            var inputPairTwo = RenderLabel(html, new LabelModel
            {
                htmlFieldName = model.htmlFieldName,
                labelText = model.labelPairTwoText,
                metadata = model.metadata,
                htmlAttributes = model.htmlAttributesLabelPairTwo.AddOrMergeCssClass("class", $"form-radio {radioType} form-text"),
                showRequiredStar = false,
                innerInputType = InputType.Radio,
                innerInputModel = new RadioButtonModel
                {
                    htmlFieldName = model.htmlFieldName,
                    value = model.inputPairTwoValue,
                    metadata = model.metadata,
                    isChecked = pairTwoValueIsSelected,
                    RadioType = model.RadioType,
                    htmlAttributes =
                        model.htmlAttributesInputPairTwo.AddOrReplace("id", fullHtmlFieldName.FormatForMvcInputId() + "_pairTwo")
                }
            });

            var helpText = model.helpText != null ? model.helpText.ToHtmlString() : string.Empty;
            var validationMessage = "";

            if (model.displayValidationMessage)
            {
                var validation = html.ValidationMessage(model.htmlFieldName).ToHtmlString();
                validationMessage = new HelpText(validation, model.validationMessageStyle).ToHtmlString();
            }

            if (model.RadioStyle == CheckBoxRadioStyle.Block)
            {
                var wrapperPairOne = new TagBuilder("div");
                var wrapperPairTwo = new TagBuilder("div");

                wrapperPairOne.AddCssClass("radio");
                wrapperPairOne.InnerHtml = inputPairOne.ToHtmlString();
                wrapperPairTwo.AddCssClass("radio");
                wrapperPairTwo.InnerHtml = inputPairTwo.ToHtmlString();

                inputPairs = wrapperPairOne + wrapperPairTwo.ToString();
            }
            else if (model.RadioStyle == CheckBoxRadioStyle.Inline)
            {
                var inputsWrapper = new TagBuilder("div");
                inputsWrapper.AddCssClass("radio");
                inputsWrapper.InnerHtml = inputPairOne.ToHtmlString() + inputPairTwo.ToHtmlString();

                inputPairs = inputsWrapper.ToString();
            }

            if (!string.IsNullOrEmpty(model.radioPairElementWrapper))
            {
                wrapper = new TagBuilder(model.radioPairElementWrapper);

                if (model.radioPairElementWrapperAttributes != null)
                    wrapper.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(model.radioPairElementWrapperAttributes));

                wrapper.InnerHtml = inputPairs;
            }

            var htmlString = wrapper != null
                ? wrapper.ToString(TagRenderMode.Normal)
                : inputPairs;

            return new HtmlString(htmlString);
        }
Exemplo n.º 29
0
        private static string RenderErrors(NotParsed <object> result)
        {
            var sentenceBuilder = SentenceBuilder.Create();

            return(HelpText.RenderParsingErrorsText(result, sentenceBuilder.FormatError, sentenceBuilder.FormatMutuallyExclusiveSetErrors, 2));
        }
Exemplo n.º 30
0
 protected void SetText(HelpText text)
 {
     TitleText.text = text.Title;
     InfoText.text  = text.Info;
 }
Exemplo n.º 31
0
        public static void MainCmd(string[] args)
        {
            CommandLineOptions clOptions             = null;
            ParserResult <CommandLineOptions> result = Parser.Default.ParseArguments <CommandLineOptions>(args).WithParsed(options => {
                clOptions = options;
            });

            if (result.Tag == ParserResultType.NotParsed)
            {
                HelpText.AutoBuild(result);
                return;
            }

            if (clOptions == null)
            {
                return;
            }

            BytePatchManager = new BytePatchManager(CustomConsoleWrite);

            List <InstallationPaths> applicationPaths = new List <InstallationPaths>();
            List <int> groups = new List <int>(clOptions.Groups);

            if (groups.Count == 0)
            {
                Console.WriteLine("Groups need to be defined. Use --help for help.");
                return;
            }

            if (!string.IsNullOrEmpty(clOptions.CustomPath))
            {
                if (!Directory.Exists(clOptions.CustomPath))
                {
                    Console.WriteLine("CustomPath not found");
                    return;
                }

                applicationPaths.AddRange(new CustomPath(clOptions.CustomPath).FindInstallationPaths());
            }
            else
            {
                applicationPaths.AddRange(new InstallationManager().FindAllChromiumInstallations());
            }

            foreach (GuiPatchGroupData patchData in BytePatchManager.PatchGroups)
            {
                if (!groups.Contains(patchData.Group))
                {
                    BytePatchManager.DisabledGroups.Add(patchData.Group);
                }
            }

            if (applicationPaths.Count == 0)
            {
                Console.WriteLine("Error: No patchable browser files found!");
            }

            try {
                PatcherInstaller installer = new PatcherInstaller(applicationPaths);
                installer.Install(Console.WriteLine);
            } catch (Exception ex) {
                Console.WriteLine("Error while installing patches: " + ex.Message);
            }

            if (!clOptions.NoWait)
            {
                Thread.Sleep(5000);                 // Wait a bit to let the user see the result
            }
        }
Exemplo n.º 32
0
        static void Main(string[] args)
        {
            try
            {
                var options = new ConsoleOptions();
                if (!Parser.Default.ParseArguments(args, options) || options.ShowHelp == true)
                {
                    if (options.LastParserState != null && options.LastParserState.Errors.Count > 0)
                    {
                        var help   = new HelpText();
                        var errors = help.RenderParsingErrorsText(options, 2); // indent with two spaces
                        Console.WriteLine("Jackett v" + Engine.ConfigService.GetVersion());
                        Console.WriteLine("Switch error: " + errors);
                        Console.WriteLine("See --help for further details on switches.");
                        Environment.ExitCode = 1;
                        return;
                    }
                    else
                    {
                        var text = HelpText.AutoBuild(options, (HelpText current) => HelpText.DefaultParsingErrorsHandler(options, current));
                        text.Copyright = " ";
                        text.Heading   = "Jackett v" + Engine.ConfigService.GetVersion() + " options:";
                        Console.WriteLine(text);
                        Environment.ExitCode = 1;
                        return;
                    }
                }
                else
                {
                    if (options.ListenPublic && options.ListenPrivate)
                    {
                        Console.WriteLine("You can only use listen private OR listen publicly.");
                        Environment.ExitCode = 1;
                        return;
                    }
                    /*  ======     Options    =====  */

                    // SSL Fix
                    Startup.DoSSLFix = options.SSLFix;

                    // Use curl
                    if (options.Client != null)
                    {
                        Startup.ClientOverride = options.Client.ToLowerInvariant();
                    }

                    // Use Proxy
                    if (options.ProxyConnection != null)
                    {
                        Startup.ProxyConnection = options.ProxyConnection.ToLowerInvariant();
                        Engine.Logger.Info("Proxy enabled. " + Startup.ProxyConnection);
                    }
                    // Logging
                    if (options.Logging)
                    {
                        Startup.LogRequests = true;
                    }

                    // Tracing
                    if (options.Tracing)
                    {
                        Startup.TracingEnabled = true;
                    }

                    // Log after the fact as using the logger will cause the options above to be used

                    if (options.Logging)
                    {
                        Engine.Logger.Info("Logging enabled.");
                    }

                    if (options.Tracing)
                    {
                        Engine.Logger.Info("Tracing enabled.");
                    }

                    if (options.SSLFix == true)
                    {
                        Engine.Logger.Info("SSL ECC workaround enabled.");
                    }
                    else if (options.SSLFix == false)
                    {
                        Engine.Logger.Info("SSL ECC workaround has been disabled.");
                    }

                    // Ignore SSL errors on Curl
                    Startup.IgnoreSslErrors = options.IgnoreSslErrors;
                    if (options.IgnoreSslErrors == true)
                    {
                        Engine.Logger.Info("Curl will ignore SSL certificate errors.");
                    }

                    // Choose Data Folder
                    if (!string.IsNullOrWhiteSpace(options.DataFolder))
                    {
                        Startup.CustomDataFolder = options.DataFolder.Replace("\"", string.Empty).Replace("'", string.Empty).Replace(@"\\", @"\");
                        Engine.Logger.Info("Jackett Data will be stored in: " + Startup.CustomDataFolder);
                    }

                    /*  ======     Actions    =====  */

                    // Install service
                    if (options.Install)
                    {
                        Engine.ServiceConfig.Install();
                        return;
                    }

                    // Uninstall service
                    if (options.Uninstall)
                    {
                        Engine.Server.ReserveUrls(doInstall: false);
                        Engine.ServiceConfig.Uninstall();
                        return;
                    }

                    // Reserve urls
                    if (options.ReserveUrls)
                    {
                        Engine.Server.ReserveUrls(doInstall: true);
                        return;
                    }

                    // Start Service
                    if (options.StartService)
                    {
                        if (!Engine.ServiceConfig.ServiceRunning())
                        {
                            Engine.ServiceConfig.Start();
                        }
                        return;
                    }

                    // Stop Service
                    if (options.StopService)
                    {
                        if (Engine.ServiceConfig.ServiceRunning())
                        {
                            Engine.ServiceConfig.Stop();
                        }
                        return;
                    }

                    // Migrate settings
                    if (options.MigrateSettings)
                    {
                        Engine.ConfigService.PerformMigration();
                        return;
                    }


                    // Show Version
                    if (options.ShowVersion)
                    {
                        Console.WriteLine("Jackett v" + Engine.ConfigService.GetVersion());
                        return;
                    }

                    /*  ======     Overrides    =====  */

                    // Override listen public
                    if (options.ListenPublic || options.ListenPrivate)
                    {
                        if (Engine.Server.Config.AllowExternal != options.ListenPublic)
                        {
                            Engine.Logger.Info("Overriding external access to " + options.ListenPublic);
                            Engine.Server.Config.AllowExternal = options.ListenPublic;
                            if (System.Environment.OSVersion.Platform != PlatformID.Unix)
                            {
                                if (ServerUtil.IsUserAdministrator())
                                {
                                    Engine.Server.ReserveUrls(doInstall: true);
                                }
                                else
                                {
                                    Engine.Logger.Error("Unable to switch to public listening without admin rights.");
                                    Environment.ExitCode = 1;
                                    return;
                                }
                            }

                            Engine.Server.SaveConfig();
                        }
                    }

                    // Override port
                    if (options.Port != 0)
                    {
                        if (Engine.Server.Config.Port != options.Port)
                        {
                            Engine.Logger.Info("Overriding port to " + options.Port);
                            Engine.Server.Config.Port = options.Port;
                            if (System.Environment.OSVersion.Platform != PlatformID.Unix)
                            {
                                if (ServerUtil.IsUserAdministrator())
                                {
                                    Engine.Server.ReserveUrls(doInstall: true);
                                }
                                else
                                {
                                    Engine.Logger.Error("Unable to switch ports when not running as administrator");
                                    Environment.ExitCode = 1;
                                    return;
                                }
                            }

                            Engine.Server.SaveConfig();
                        }
                    }
                }

                Engine.Server.Initalize();
                Engine.Server.Start();
                Engine.RunTime.Spin();
                Engine.Logger.Info("Server thread exit");
            }
            catch (Exception e)
            {
                Engine.Logger.Error(e, "Top level exception");
            }
        }
Exemplo n.º 33
0
        static void Main(string[] args)
        {
            var opts = new CommandLineOptions();

            if (!CommandLine.Parser.Default.ParseArguments(args, opts))
            {
                Console.WriteLine(HelpText.AutoBuild(opts));
                return;
            }

            if (opts.Debug)
            {
                System.Diagnostics.Debugger.Break();
            }

            ParsedFileCache cache = new ParsedFileCache(opts.SourceFolder);

            if (opts.ResetCache)
            {
                cache.ClearAll();
            }

            Console.CancelKeyPress += (sender, eventArgs) => {
                if (opts.CacheFileInfo)
                {
                    Console.WriteLine("Flushing cache to disk...");
                    cache.PersistCache();
                }
                Environment.Exit(-1);
            };


            if (string.IsNullOrEmpty(opts.SourceFolder))
            {
                opts.SourceFolder = System.Environment.CurrentDirectory;
            }



            DirectoryInfo destination = new DirectoryInfo(opts.DestinationFolder);

            if (!destination.Exists)
            {
                Console.WriteLine("Error: Destination folder doesn't exist.");
                return;
            }

            DirectoryInfo source = new DirectoryInfo(opts.SourceFolder);

            if (!source.Exists)
            {
                Console.WriteLine("Error: Source folder doesn't exist. Nothing to do.");
                return;
            }

            if (opts.ConflictBehavior == ExistingFileMode.Delete)
            {
                Console.Write("Delete source files on existing files in destination is enabled.\nTHIS MAY CAUSE DATA LOSS, are you sure? [Y/N]: ");
                var key = Console.ReadKey();
                if (!(key.KeyChar == 'y' || key.KeyChar == 'Y'))
                {
                    return;
                }
                Console.WriteLine();
            }

            FileOrganizer organizer = new FileOrganizer(destination, opts, cache);

            organizer.ProcessSourceFolder(source);
            if (cache.HasChanged)
            {
                cache.PersistCache();
            }
        }
Exemplo n.º 34
0
        static Task HandleErrorsAndShowHelp(ParserResult <object> parserResult, Type[] commands)
        {
            SentenceBuilder.Factory = () => new TweakedSentenceBuilder();

            using var parser = new Parser(cfg =>
            {
                cfg.IgnoreUnknownArguments = true;
                cfg.AutoHelp    = false;
                cfg.AutoVersion = false;
                cfg.HelpWriter  = null;
            });

            var result = parser.ParseArguments <GlobalOptions>(string.Empty.Split(' '));

            var htGlobals = new HelpText(
                "ElastiBuild " + ProductVersion,
                $"Copyright (c) {DateTime.Now.Year}, https://elastic.co")
            {
                AdditionalNewLineAfterOption = false,
                AutoHelp          = false,
                AutoVersion       = false,
                AddDashesToOption = true
            };

            htGlobals.AddPreOptionsLine(Environment.NewLine + "Global Flags:");
            htGlobals.AddOptions(result);
            Console.WriteLine(htGlobals.ToString());

            bool isGlobalHelp = parserResult.TypeInfo.Current == typeof(NullInstance);

            if (isGlobalHelp)
            {
                var htVerbs = new HelpText
                {
                    AddDashesToOption            = false,
                    AutoHelp                     = false,
                    AutoVersion                  = false,
                    AdditionalNewLineAfterOption = false,
                };

                htVerbs.AddPreOptionsLine("Available Commands:");
                htVerbs.AddVerbs(commands);

                Console.WriteLine(htVerbs.ToString());
            }

            var htOptions = new HelpText(string.Empty, string.Empty)
            {
                AddDashesToOption = true,
                AutoHelp          = false,
                AutoVersion       = false
            };

            string text = string.Empty;

            if (!isGlobalHelp)
            {
                htOptions.AddOptions(parserResult);

                text = htOptions.ToString();
                if (text.Length > 0)
                {
                    var cmdName = parserResult
                                  .TypeInfo.Current
                                  .GetCustomAttributes(typeof(VerbAttribute), true)
                                  .Cast <VerbAttribute>()
                                  .FirstOrDefault()
                                  ?.Name ?? throw new Exception("Something went horribly wrong. Command name is empty.");

                    Console.WriteLine(
                        $"{cmdName.ToUpper()} Flags:" + text);
                }

                text = HelpText.RenderUsageText(parserResult);
                if (text.Length > 0)
                {
                    Console.WriteLine(
                        "Usage Examples:" +
                        Environment.NewLine +
                        text +
                        Environment.NewLine);
                }
            }
            ;

            var tsb = SentenceBuilder.Factory();

            text =
                HelpText.RenderParsingErrorsText(
                    parserResult,
                    err => tsb.FormatError(err),
                    mex => tsb.FormatMutuallyExclusiveSetErrors(mex),
                    2);

            if (text.Length > 0)
            {
                Console.WriteLine("Error(s):" + Environment.NewLine + text);
            }

            return(Task.CompletedTask);
        }
Exemplo n.º 35
0
        static void Main(string[] args)
        {
            var optionsResult = Parser.Default.ParseArguments <ConsoleOptions>(args);

            optionsResult.WithNotParsed(errors =>
            {
                var text       = HelpText.AutoBuild(optionsResult);
                text.Copyright = " ";
                text.Heading   = "Jackett v" + EnvironmentUtil.JackettVersion + " options:";
                System.Console.WriteLine(text);
                Environment.ExitCode = 1;
                return;
            });

            optionsResult.WithParsed(options =>
            {
                try
                {
                    var runtimeSettings = options.ToRunTimeSettings();

                    // Initialize autofac, logger, etc. We cannot use any calls to Engine before the container is set up.
                    Engine.BuildContainer(runtimeSettings, new WebApi2Module());

                    if (runtimeSettings.LogRequests)
                    {
                        Engine.Logger.Info("Logging enabled.");
                    }

                    if (runtimeSettings.TracingEnabled)
                    {
                        Engine.Logger.Info("Tracing enabled.");
                    }

                    if (runtimeSettings.IgnoreSslErrors == true)
                    {
                        Engine.Logger.Info("Jackett will ignore SSL certificate errors.");
                    }

                    if (runtimeSettings.DoSSLFix == true)
                    {
                        Engine.Logger.Info("SSL ECC workaround enabled.");
                    }
                    else if (runtimeSettings.DoSSLFix == false)
                    {
                        Engine.Logger.Info("SSL ECC workaround has been disabled.");
                    }
                    // Choose Data Folder
                    if (!string.IsNullOrWhiteSpace(runtimeSettings.CustomDataFolder))
                    {
                        Engine.Logger.Info("Jackett Data will be stored in: " + runtimeSettings.CustomDataFolder);
                    }

                    if (!string.IsNullOrEmpty(runtimeSettings.ClientOverride))
                    {
                        if (runtimeSettings.ClientOverride != "httpclient" && runtimeSettings.ClientOverride != "httpclient2" && runtimeSettings.ClientOverride != "httpclientnetcore")
                        {
                            Engine.Logger.Error($"Client override ({runtimeSettings.ClientOverride}) has been deprecated, please remove it from your start arguments");
                            Environment.Exit(1);
                        }
                    }

                    // Use Proxy
                    if (options.ProxyConnection != null)
                    {
                        Engine.Logger.Info("Proxy enabled. " + runtimeSettings.ProxyConnection);
                    }

                    /*  ======     Actions    =====  */

                    // Install service
                    if (options.Install)
                    {
                        Engine.ServiceConfig.Install();
                        return;
                    }

                    // Uninstall service
                    if (options.Uninstall)
                    {
                        Engine.Server.ReserveUrls(doInstall: false);
                        Engine.ServiceConfig.Uninstall();
                        return;
                    }

                    // Reserve urls
                    if (options.ReserveUrls)
                    {
                        Engine.Server.ReserveUrls(doInstall: true);
                        return;
                    }

                    // Start Service
                    if (options.StartService)
                    {
                        if (!Engine.ServiceConfig.ServiceRunning())
                        {
                            Engine.ServiceConfig.Start();
                        }
                        return;
                    }

                    // Stop Service
                    if (options.StopService)
                    {
                        if (Engine.ServiceConfig.ServiceRunning())
                        {
                            Engine.ServiceConfig.Stop();
                        }
                        return;
                    }

                    // Migrate settings
                    if (options.MigrateSettings)
                    {
                        Engine.ConfigService.PerformMigration();
                        return;
                    }


                    // Show Version
                    if (options.ShowVersion)
                    {
                        System.Console.WriteLine("Jackett v" + EnvironmentUtil.JackettVersion);
                        return;
                    }

                    /*  ======     Overrides    =====  */

                    // Override listen public
                    if (options.ListenPublic || options.ListenPrivate)
                    {
                        if (Engine.ServerConfig.AllowExternal != options.ListenPublic)
                        {
                            Engine.Logger.Info("Overriding external access to " + options.ListenPublic);
                            Engine.ServerConfig.AllowExternal = options.ListenPublic;
                            if (System.Environment.OSVersion.Platform != PlatformID.Unix)
                            {
                                if (ServerUtil.IsUserAdministrator())
                                {
                                    Engine.Server.ReserveUrls(doInstall: true);
                                }
                                else
                                {
                                    Engine.Logger.Error("Unable to switch to public listening without admin rights.");
                                    Engine.Exit(1);
                                }
                            }

                            Engine.SaveServerConfig();
                        }
                    }

                    // Override port
                    if (options.Port != 0)
                    {
                        if (Engine.ServerConfig.Port != options.Port)
                        {
                            Engine.Logger.Info("Overriding port to " + options.Port);
                            Engine.ServerConfig.Port = options.Port;
                            if (System.Environment.OSVersion.Platform != PlatformID.Unix)
                            {
                                if (ServerUtil.IsUserAdministrator())
                                {
                                    Engine.Server.ReserveUrls(doInstall: true);
                                }
                                else
                                {
                                    Engine.Logger.Error("Unable to switch ports when not running as administrator");
                                    Engine.Exit(1);
                                }
                            }

                            Engine.SaveServerConfig();
                        }
                    }

                    Engine.Server.Initalize();
                    Engine.Server.Start();
                    Engine.RunTime.Spin();
                    Engine.Logger.Info("Server thread exit");
                }
                catch (Exception e)
                {
                    Engine.Logger.Error(e, "Top level exception");
                }
            });
        }
Exemplo n.º 36
0
        public void Long_help_text_without_spaces()
        {
            var helpText = new HelpText(new HeadingInfo("CommandLine.Tests.dll", "1.9.4.131"));
            helpText.MaximumDisplayWidth = 40;
            helpText.AddOptions(new MockOptionsWithLongDescriptionAndNoSpaces());
            string help = helpText.ToString();

            string[] lines = help.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            lines[2].Should().Be("  v, verbose    Before ");
            lines[3].Should().Be("                012345678901234567890123");
            lines[4].Should().Be("                After");
            lines[5].Should().Be("  input-file    Before ");
            lines[6].Should().Be("                012345678901234567890123");
            lines[7].Should().Be("                456789 After");
        }
Exemplo n.º 37
0
 public void DisplayHelpText()
 {
     HelpText.DisplayHelp(global::BuildXL.ToolSupport.HelpLevel.Standard);
     HelpText.DisplayHelp(global::BuildXL.ToolSupport.HelpLevel.Verbose);
 }
Exemplo n.º 38
0
        public void Post_options_lines_feature_added()
        {
            var local = new HelpText("Heading Info.");
            local.AddPreOptionsLine("This is a first pre-options line.");
            local.AddPreOptionsLine("This is a second pre-options line.");
            local.AddOptions(new MockOptions());
            local.AddPostOptionsLine("This is a first post-options line.");
            local.AddPostOptionsLine("This is a second post-options line.");

            string help = local.ToString();

            string[] lines = help.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            lines[lines.Length - 2].Should().Be("This is a first post-options line.");
            lines[lines.Length - 1].Should().Be("This is a second post-options line.");
        }
 public String GetUsage()
 {
     return(HelpText.AutoBuild(this));
 }
Exemplo n.º 40
0
 public void Add_an_empty_pre_options_line_is_allowed()
 {
     var helpText = new HelpText(new HeadingInfo("CommandLine.Tests.dll", "1.9.4.131"));
     helpText.AddPreOptionsLine(string.Empty);
 }
Exemplo n.º 41
0
        static void Main(string[] args)
        {
            //Parse command line arguments
            CommandLineOptions opts = new CommandLineOptions();
            var result = Parser.Default.ParseArguments <CommandLineOptions>(args).WithParsed(parsed => opts = parsed);
            var title  = new HeadingInfo("CobaltStrikeScan");


            // Option Processes -p
            if (opts.Processes)
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("Scanning processes for injected threads");
                Console.ResetColor();

                List <InjectedThread> injectedThreads = GetInjectedThreads.GetInjectedThreads.InjectedThreads();

                foreach (InjectedThread injectedThread in injectedThreads)
                {
                    // Output Thread details to console
                    OutputInjectedThreadToConsole(injectedThread, opts.Verbose);


                    // Check if option set for dumping process memory
                    if (opts.Dump)
                    {
                        injectedThread.WriteBytesToFile();
                    }

                    // Scan process memory for injected thread
                    Console.ForegroundColor = ConsoleColor.Yellow;
                    Console.WriteLine("Scanning injected thread for CobaltStrike beacon");
                    Console.ResetColor();

                    Dictionary <string, ulong> beaconMatchOffsets = CobaltStrikeScan.YaraScanBytes(injectedThread.ProcessBytes);

                    if (beaconMatchOffsets.Count > 0)
                    {
                        Beacon beacon = GetBeaconFromYaraScan(beaconMatchOffsets, injectedThread.ProcessBytes);

                        if (beacon != null)
                        {
                            beacon.OutputToConsole();
                        }
                    }
                    else
                    {
                        Console.WriteLine("Couldn't find CobaltStrike beacon in injected thread");
                    }
                }
            }

            // User supplied File option -f
            else if (!string.IsNullOrEmpty(opts.File))
            {
                if (File.Exists(opts.File))
                {
                    Dictionary <string, ulong> beaconMatchOffsets = CobaltStrikeScan.YaraScanFile(opts.File);

                    if (beaconMatchOffsets.Count > 0)
                    {
                        byte[] fileBytes = File.ReadAllBytes(opts.File);
                        Beacon beacon    = GetBeaconFromYaraScan(beaconMatchOffsets, fileBytes);

                        if (beacon != null)
                        {
                            beacon.OutputToConsole();
                        }
                    }
                    else
                    {
                        Console.WriteLine("Couldn't find CobaltStrike beacon in file");
                    }
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"File doesn't exist: {opts.File}\nExiting...");
                    Console.ResetColor();
                    System.Environment.Exit(1);
                }
            }
            else if (opts.InjectedThreads)
            {
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("Scanning processes for injected threads\n");
                Console.ResetColor();

                List <InjectedThread> injectedThreads = GetInjectedThreads.GetInjectedThreads.InjectedThreads();

                foreach (InjectedThread injectedThread in injectedThreads)
                {
                    // Output Thread details to console
                    OutputInjectedThreadToConsole(injectedThread, opts.Verbose);


                    // Check if option set for dumping process memory
                    if (opts.Dump)
                    {
                        injectedThread.WriteBytesToFile();
                    }
                }
            }
            else if (opts.Help)
            {
                Console.WriteLine(HelpText.AutoBuild(result, h => h, e => e));
            }
            else
            {
                Console.WriteLine(HelpText.AutoBuild(result, h => h, e => e));
            }
        }
Exemplo n.º 42
0
        public void CreateBasicInstance()
        {
            var local = new HelpText();

            Assert.AreEqual("", local.ToString());
        }
Exemplo n.º 43
0
 public string GetHelp()
 {
     return(HelpText.AutoBuild(this));
 }
Exemplo n.º 44
0
        public void MetaValue()
        {
            var local = new HelpText("Meta Value.");
            local.AddOptions(new MockOptionsWithMetaValue());

            string help = local.ToString();
            string[] lines = help.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            lines[lines.Length - 2].Should().Equal("  i FILE, input-file=FILE    Required. Specify input FILE to be processed.");
        }
Exemplo n.º 45
0
        static async Task <int> Main(string[] args)
        {
            var parsedArgsResult = Parser.ParseArguments <Options>(args);

            if (parsedArgsResult.Tag == ParserResultType.NotParsed)
            {
                var helpText = HelpText.AutoBuild(parsedArgsResult);
                WriteInfo(helpText.ToString());
                return(-1);
            }

            var options     = ((Parsed <Options>)parsedArgsResult).Value;
            var interactive = string.IsNullOrWhiteSpace(options.Action);

            string[] actionArgs = null;
            if (!interactive)
            {
                // Action mode
                actionArgs = GetActionArgs(options.Action, args);
            }

            if (interactive)
            {
                WriteInfo("Welcome to LIME");
            }

            IOnDemandClientChannel channel;

            using (var cts = CreateCancellationTokenSource(options.Timeout))
            {
                try
                {
                    channel = await EstablishChannelAsync(options.ToConnectionInformation(), cts.Token);
                }
                catch (Exception ex)
                {
                    WriteError(ex.Message);
                    return(-1);
                }
            }

            if (interactive)
            {
                WriteInfo("Channel established");
            }

            var actionsDictionary = GetActions();

            var resultStatus = 0;

            if (interactive)
            {
                await ExecuteInteractiveModeAsync(options, channel, actionsDictionary);
            }
            else if (!await ExecuteActionAsync(actionArgs, channel, actionsDictionary, options.Timeout))
            {
                resultStatus = -1;
            }

            using (var cts = CreateCancellationTokenSource(options.Timeout))
            {
                try
                {
                    await channel.FinishAsync(cts.Token);
                }
                catch (Exception ex)
                {
                    WriteError(ex.Message);
                    return(-1);
                }
            }

            if (interactive)
            {
                WriteInfo("Bye!");
            }

            return(resultStatus);
        }
Exemplo n.º 46
0
            public string GetUsage()
            {
                var text = @"SharpHound v1.0.0
Usage: SharpHound.exe <options>

Enumeration Options:
    -c , --CollectionMethod (Default: Default)
        Default - Enumerate Trusts, Sessions, Local Admin, and Group Membership
        Group - Enumerate Group Membership
        LocalGroup - Enumerate Local Admin
        Session - Enumerate Sessions
        SessionLoop - Continuously Enumerate Sessions
        LoggedOn - Enumerate Sessions using Elevation
        ComputerOnly - Enumerate Sessions and Local Admin
        Trusts - Enumerate Domain Trusts
        ACL - Enumerate ACLs
        ObjectProps - Enumerate Object Properties for Users/Computers
        Container - Collects GPO/OU Structure
        All - Performs all enumeration methods

        This can be a list of comma seperated valued as well to run multiple collection methods!

    -s , --SearchForest
        Search the entire forest instead of just current domain

    -d , --Domain (Default: "")
        Search a specific domain
    
    --SkipGCDeconfliction
        Skip Global Catalog deconfliction during session enumeration
        This option can result in more inaccuracies!

    --Stealth
        Use stealth collection options

    --Ou (Default: null)
        Ou to limit computer enumeration too. Requires a DistinguishedName (OU=Domain Controllers,DC=contoso,DC=local)

    --ComputerFile (Default: null)
        A file containing a list of computers to enumerate. This option can only be used with the following Collection Methods:
        Session, SessionLoop, LocalGroup, ComputerOnly, LoggedOn

    --DomainController (Default: null)
        Specify which Domain Controller to request data from. Defaults to closest DC using Site Names

    --ExcludeDC
        Exclude domain controllers from session queries. Useful for ATA environments which detect this behavior
   
Connection Options:
    --SecureLdap
        Uses secure LDAP (LDAPS) instead of regular

    --LdapPort
        Override the port used to connect to LDAP

    --IgnoreLdapCert
        Ignores the SSL certificate for LDAP. Use for self-signed certs

    --DisableKerbSigning
        Disables Kerberos signing on LDAP requests

Performance Tuning:
    -t , --Threads (Default: 10)
        The number of threads to use for Enumeration
    
    --PingTimeout (Default: 200)
        Timeout to use when pinging computers in milliseconds

    --SkipPing
        Skip pinging computers (will most likely be slower)
        Use this option if ping is disabled on the network

    --LoopTime
        Amount of time to wait in between session enumeration loops
        Use in conjunction with -c SessionLoop

    --MaxLoopTime
        Time to stop looping. Format is 0d0h0m0s or any variation of this.
        Use in conjunction with -c SessionLoop
        Default will loop infinitely

    --Throttle (Default: 0)
        Time in milliseconds to throttle between requests to computers

    --Jitter (Default: 0)
        Percent jitter to apply to throttle

Output Options
    --CSVFolder (Default: .)
        The folder in which to store CSV files

    --CSVPrefix (Default: """")
        The prefix to add to your CSV files

    --URI (Default: """")
        The URI for the Neo4j REST API
        Setting this option will disable CSV output
        Format is http(s)://SERVER:PORT

    --UserPass (Default: """")
        username:password for the Neo4j REST API

    --CompressData
        Compress CSVs into a zip file after run

    --RemoveCSV
        Removes CSVs after running. Only usable with the CompressData flag

Cache Options
    --NoSaveCache
        Dont save the cache to disk to speed up future runs

    --CacheFile (Default: BloodHound.bin)
        Filename for the BloodHound database to write to disk

    --Invalidate
        Invalidate the cache and build a new one

General Options
    --StatusInterval (Default: 30000)
        Interval to display progress during enumeration in milliseconds

    -v , --Verbose
        Display Verbose Output


";

                if (LastParserState?.Errors.Any() != true)
                {
                    return(text);
                }
                var errors = new HelpText().RenderParsingErrorsText(this, 2);

                text += errors;

                return(text);
            }
Exemplo n.º 47
0
 public void SetUp()
 {
     _helpText = new HelpText(new HeadingInfo("CommandLine.Tests.dll", "1.9.4.131"));
 }
Exemplo n.º 48
0
        public void LongPreAndPostLinesWithoutSpaces()
        {
            var local = new HelpText("Heading Info.");
            local.MaximumDisplayWidth = 40;
            local.AddPreOptionsLine("Before 0123456789012345678901234567890123456789012 After");
            local.AddOptions(new MockOptions());
            local.AddPostOptionsLine("Before 0123456789012345678901234567890123456789 After");

            string help = local.ToString();

            string[] lines = help.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            Assert.AreEqual("Before ", lines[1]);
            Assert.AreEqual("0123456789012345678901234567890123456789", lines[2]);
            Assert.AreEqual("012 After", lines[3]);
            Assert.AreEqual("Before ", lines[lines.Length - 3]);
            Assert.AreEqual("0123456789012345678901234567890123456789", lines[lines.Length - 2]);
            Assert.AreEqual(" After", lines[lines.Length - 1]);
        }
Exemplo n.º 49
0
        public void Invoking_RenderParsingErrorsText_returns_appropriate_formatted_text()
        {
            // Fixture setup
            var fakeResult = new NotParsed <object>(
                TypeInfo.Create(typeof(NullInstance)),
                new Error[]
            {
                new BadFormatTokenError("badtoken"),
                new MissingValueOptionError(new NameInfo("x", "switch")),
                new UnknownOptionError("unknown"),
                new MissingRequiredOptionError(new NameInfo("", "missing")),
                new SequenceOutOfRangeError(new NameInfo("s", "sequence")),
                new NoVerbSelectedError(),
                new BadVerbSelectedError("badverb"),
                new HelpRequestedError(),                     // should be ignored
                new HelpVerbRequestedError(null, null, false) // should be ignored
            });
            Func <Error, string> fakeRenderer = err =>
            {
                switch (err.Tag)
                {
                case ErrorType.BadFormatTokenError:
                    return("ERR " + ((BadFormatTokenError)err).Token);

                case ErrorType.MissingValueOptionError:
                    return("ERR " + ((MissingValueOptionError)err).NameInfo.NameText);

                case ErrorType.UnknownOptionError:
                    return("ERR " + ((UnknownOptionError)err).Token);

                case ErrorType.MissingRequiredOptionError:
                    return("ERR " + ((MissingRequiredOptionError)err).NameInfo.NameText);

                case ErrorType.SequenceOutOfRangeError:
                    return("ERR " + ((SequenceOutOfRangeError)err).NameInfo.NameText);

                case ErrorType.NoVerbSelectedError:
                    return("ERR no-verb-selected");

                case ErrorType.BadVerbSelectedError:
                    return("ERR " + ((BadVerbSelectedError)err).Token);

                default:
                    throw new InvalidOperationException();
                }
            };
            Func <IEnumerable <MutuallyExclusiveSetError>, string> fakeMutExclRenderer =
                _ => string.Empty;

            // Exercize system
            var errorsText = HelpText.RenderParsingErrorsText(fakeResult, fakeRenderer, fakeMutExclRenderer, 2);

            // Verify outcome
            var lines = errorsText.ToNotEmptyLines();

            lines[0].ShouldBeEquivalentTo("  ERR badtoken");
            lines[1].ShouldBeEquivalentTo("  ERR x, switch");
            lines[2].ShouldBeEquivalentTo("  ERR unknown");
            lines[3].ShouldBeEquivalentTo("  ERR missing");
            lines[4].ShouldBeEquivalentTo("  ERR s, sequence");
            lines[5].ShouldBeEquivalentTo("  ERR no-verb-selected");
            lines[6].ShouldBeEquivalentTo("  ERR badverb");
            // Teardown
        }
Exemplo n.º 50
0
 public void SetUp()
 {
     _helpText = new HelpText(new HeadingInfo(ThisAssembly.Title, ThisAssembly.Version));
 }
Exemplo n.º 51
0
 public string GetUsage(string verb)
 {
     return(HelpText.AutoBuild(this, verb));
 }
Exemplo n.º 52
0
        public void InstancingWithParameterlessConstructor()
        {
            var year = DateTime.Now.Year;
            var local = new HelpText();
            local.Heading = new HeadingInfo("Parameterless Constructor Test.");
            local.Copyright = new CopyrightInfo("Author", year);
            local.AddPreOptionsLine("Pre-Options.");
            local.AddOptions(new MockOptionsSimple());
            local.AddPostOptionsLine("Post-Options.");

            string help = local.ToString();

            Console.WriteLine(help);

            string[] lines = help.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
            Assert.AreEqual("Parameterless Constructor Test.", lines[0]);
            Assert.AreEqual(string.Format(CultureInfo.InvariantCulture, "Copyright (C) {0} Author", year), lines[1]);
            Assert.AreEqual("Pre-Options.", lines[2]);
            Assert.AreEqual("  s, something    Input something here.", lines[4]);
            Assert.AreEqual("Post-Options.", lines[6]);
        }
Exemplo n.º 53
0
        public static int Main(string[] args)
        {
            var mainTimer = new Stopwatch();

            mainTimer.Start();

            var save = Console.ForegroundColor;

            Telemetry.TrackEvent("CLI Start");

            using (var cancellationTokenSource = new CancellationTokenSource())
            {
                void cancelEventHandler(object sender, ConsoleCancelEventArgs e)
                {
                    // call methods to clean up
                    Console.ForegroundColor = save;
                    if (!cancellationTokenSource.IsCancellationRequested)
                    {
                        cancellationTokenSource.Cancel();
                    }
                }

                Console.CancelKeyPress += cancelEventHandler;
                var cancellationToken = cancellationTokenSource.Token;

                bool versionCheckEnabled = !EnvironmentVariables.GetAsBool("AGGREGATOR_NEW_VERSION_CHECK_DISABLED", false);
                if (versionCheckEnabled)
                {
                    var tempLogger = new ConsoleLogger(false);
                    var verChecker = new FunctionRuntimePackage(tempLogger);
                    (bool upgrade, string newversion) = verChecker.IsCliUpgradable().Result;
                    if (upgrade)
                    {
                        // bug user
                        tempLogger.WriteWarning($"A new version ({newversion}) of Aggregator CLI is available, please upgrade.");
                    }
                }

                var parser = new Parser(settings =>
                {
                    settings.CaseSensitive = false;
                    // fails see https://github.com/commandlineparser/commandline/issues/198
                    settings.CaseInsensitiveEnumValues = true;
                });
                var types = new Type[]
                {
                    typeof(CreateTestCommand), typeof(CleanupTestCommand),
                    typeof(LogonAzureCommand), typeof(LogonDevOpsCommand), typeof(LogoffCommand), typeof(LogonEnvCommand),
                    typeof(ListInstancesCommand), typeof(InstallInstanceCommand), typeof(UpdateInstanceCommand),
                    typeof(UninstallInstanceCommand), typeof(ConfigureInstanceCommand), typeof(StreamLogsCommand),
                    typeof(ListRulesCommand), typeof(AddRuleCommand), typeof(RemoveRuleCommand),
                    typeof(ConfigureRuleCommand), typeof(UpdateRuleCommand), typeof(InvokeRuleCommand),
                    typeof(ListMappingsCommand), typeof(MapRuleCommand), typeof(UnmapRuleCommand), typeof(UpdateMappingsCommand),
                    typeof(MapLocalRuleCommand)
                };
                var parserResult = parser.ParseArguments(args, types);
                int rc           = ExitCodes.Unexpected;
                parserResult
                .WithParsed <CreateTestCommand>(cmd => rc        = cmd.Run(cancellationToken))
                .WithParsed <CleanupTestCommand>(cmd => rc       = cmd.Run(cancellationToken))
                .WithParsed <LogonAzureCommand>(cmd => rc        = cmd.Run(cancellationToken))
                .WithParsed <LogonDevOpsCommand>(cmd => rc       = cmd.Run(cancellationToken))
                .WithParsed <LogoffCommand>(cmd => rc            = cmd.Run(cancellationToken))
                .WithParsed <LogonEnvCommand>(cmd => rc          = cmd.Run(cancellationToken))
                .WithParsed <ListInstancesCommand>(cmd => rc     = cmd.Run(cancellationToken))
                .WithParsed <InstallInstanceCommand>(cmd => rc   = cmd.Run(cancellationToken))
                .WithParsed <UpdateInstanceCommand>(cmd => rc    = cmd.Run(cancellationToken))
                .WithParsed <UninstallInstanceCommand>(cmd => rc = cmd.Run(cancellationToken))
                .WithParsed <ConfigureInstanceCommand>(cmd => rc = cmd.Run(cancellationToken))
                .WithParsed <ListRulesCommand>(cmd => rc         = cmd.Run(cancellationToken))
                .WithParsed <AddRuleCommand>(cmd => rc           = cmd.Run(cancellationToken))
                .WithParsed <RemoveRuleCommand>(cmd => rc        = cmd.Run(cancellationToken))
                .WithParsed <ConfigureRuleCommand>(cmd => rc     = cmd.Run(cancellationToken))
                .WithParsed <StreamLogsCommand>(cmd => rc        = cmd.Run(cancellationToken))
                .WithParsed <UpdateRuleCommand>(cmd => rc        = cmd.Run(cancellationToken))
                .WithParsed <InvokeRuleCommand>(cmd => rc        = cmd.Run(cancellationToken))
                .WithParsed <ListMappingsCommand>(cmd => rc      = cmd.Run(cancellationToken))
                .WithParsed <MapRuleCommand>(cmd => rc           = cmd.Run(cancellationToken))
                .WithParsed <UnmapRuleCommand>(cmd => rc         = cmd.Run(cancellationToken))
                .WithParsed <UpdateMappingsCommand>(cmd => rc    = cmd.Run(cancellationToken))
                .WithParsed <MapLocalRuleCommand>(cmd => rc      = cmd.Run(cancellationToken))
                .WithNotParsed(errs =>
                {
                    var helpText = HelpText.AutoBuild(parserResult);
                    Console.Error.Write(helpText);
                    rc = ExitCodes.InvalidArguments;
                });


                mainTimer.Stop();
                Telemetry.TrackEvent("CLI End", null,
                                     new Dictionary <string, double> {
                    { "RunDuration", mainTimer.ElapsedMilliseconds }
                });

                Telemetry.Shutdown();

                Console.ForegroundColor = save;
                Console.CancelKeyPress -= cancelEventHandler;
                return(rc);
            }
        }
Exemplo n.º 54
0
        static void Main(string[] args)
        {
            Args = args;
            if (Args.Contains("fn") || Args.Contains("pm") || Args.Contains("cr"))
            {
                SetLogger(new SerilogLogger(console: false, debug: true));
            }
            else if (Args.Contains("--debug"))
            {
                SetLogger(new SerilogLogger(console: true, debug: true));
            }
            else
            {
                SetLogger(new SerilogLogger(console: true, debug: false));
            }

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Console.CancelKeyPress += Console_CancelKeyPress;

            if (!args.Contains("fn") && !args.Contains("pm") && !args.Contains("cr"))
            {
                PrintLogo();
            }
            if (args.Contains("--debug"))
            {
                Info("Debug mode set.");
            }

            ParserResult <object> result = new Parser().ParseArguments <Options, SpeechRecognitionOptions, TTSOptions, FNOptions, PMOptions>(args);

            result.WithNotParsed((IEnumerable <Error> errors) =>
            {
                HelpText help  = GetAutoBuiltHelpText(result);
                help.Copyright = string.Empty;
                help.AddPreOptionsLine(string.Empty);

                if (errors.Any(e => e.Tag == ErrorType.VersionRequestedError))
                {
                    Exit(ExitResult.SUCCESS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.HelpVerbRequestedError))
                {
                    HelpVerbRequestedError error = (HelpVerbRequestedError)errors.First(e => e.Tag == ErrorType.HelpVerbRequestedError);
                    if (error.Type != null)
                    {
                        help.AddVerbs(error.Type);
                    }
                    else
                    {
                        help.AddVerbs(typeof(SpeechRecognitionOptions), typeof(TTSOptions), typeof(FNOptions), typeof(PMOptions));
                    }
                    Info(help);
                    Exit(ExitResult.SUCCESS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.HelpRequestedError))
                {
                    HelpRequestedError error = (HelpRequestedError)errors.First(e => e.Tag == ErrorType.HelpRequestedError);
                    help.AddVerbs(typeof(SpeechRecognitionOptions), typeof(TTSOptions), typeof(FNOptions), typeof(PMOptions));
                    Info(help);
                    Exit(ExitResult.SUCCESS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.NoVerbSelectedError))
                {
                    help.AddVerbs(typeof(SpeechRecognitionOptions), typeof(TTSOptions), typeof(FNOptions), typeof(PMOptions));
                    Info(help);
                    Exit(ExitResult.INVALID_OPTIONS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.MissingRequiredOptionError))
                {
                    MissingRequiredOptionError error = (MissingRequiredOptionError)errors.First(e => e.Tag == ErrorType.MissingRequiredOptionError);
                    Error("A required option is missing: {0}.", error.NameInfo.NameText);
                    Info(help);
                    Exit(ExitResult.INVALID_OPTIONS);
                }
                else if (errors.Any(e => e.Tag == ErrorType.UnknownOptionError))
                {
                    UnknownOptionError error = (UnknownOptionError)errors.First(e => e.Tag == ErrorType.UnknownOptionError);
                    help.AddVerbs(typeof(SpeechRecognitionOptions), typeof(TTSOptions));
                    Error("Unknown option: {error}.", error.Token);
                    Info(help);
                    Exit(ExitResult.INVALID_OPTIONS);
                }
                else
                {
                    Error("An error occurred parsing the program options: {errors}.", errors);
                    help.AddVerbs(typeof(SpeechRecognitionOptions), typeof(TTSOptions));
                    Info(help);
                    Exit(ExitResult.INVALID_OPTIONS);
                }
            })
            .WithParsed <SpeechRecognitionOptions>(o =>
            {
                ASR();
                Exit(ExitResult.SUCCESS);
            })
            .WithParsed <TTSOptions>(o =>
            {
                TTS(o.Text);
                Exit(ExitResult.SUCCESS);
            })
            .WithParsed <FNOptions>(o =>
            {
                FNController.Options = o;
                new FNController(o).Start();
                Exit(ExitResult.SUCCESS);
            })
            .WithParsed <PMOptions>(o =>
            {
                PMController.Options = o;
                new PMController(o).Start();
                Exit(ExitResult.SUCCESS);
            });
        }
Exemplo n.º 55
0
 public static string GetUsage(CommandLineOptions options)
 {
     return(HelpText.AutoBuild(options,
                               (HelpText current) => HelpText.DefaultParsingErrorsHandler(options, current)));
 }