internal LocalPipeline(System.Management.Automation.Runspaces.LocalRunspace runspace, CommandCollection command, bool addToHistory, bool isNested, ObjectStreamBase inputStream, ObjectStreamBase outputStream, ObjectStreamBase errorStream, PSInformationalBuffers infoBuffers) : base(runspace, command, addToHistory, isNested, inputStream, outputStream, errorStream, infoBuffers) { this._historyIdForThisPipeline = -1L; this._invokeHistoryIds = new List<long>(); this._stopper = new PipelineStopper(this); this.InitStreams(); }
/// <summary> /// Create a Pipeline with an existing command string. /// Caller should validate all the parameters. /// </summary> /// <param name="runspace"> /// The LocalRunspace to associate with this pipeline. /// </param> /// <param name="command"> /// The command to invoke. /// </param> /// <param name="addToHistory"> /// If true, add the command to history. /// </param> /// <param name="isNested"> /// If true, mark this pipeline as a nested pipeline. /// </param> /// <param name="inputStream"> /// Stream to use for reading input objects. /// </param> /// <param name="errorStream"> /// Stream to use for writing error objects. /// </param> /// <param name="outputStream"> /// Stream to use for writing output objects. /// </param> /// <param name="infoBuffers"> /// Buffers used to write progress, verbose, debug, warning, information /// information of an invocation. /// </param> /// <exception cref="ArgumentNullException"> /// Command is null and add to history is true /// </exception> /// <exception cref="ArgumentNullException"> /// 1. InformationalBuffers is null /// </exception> protected PipelineBase(Runspace runspace, CommandCollection command, bool addToHistory, bool isNested, ObjectStreamBase inputStream, ObjectStreamBase outputStream, ObjectStreamBase errorStream, PSInformationalBuffers infoBuffers) : base(runspace, command) { Dbg.Assert(null != inputStream, "Caller Should validate inputstream parameter"); Dbg.Assert(null != outputStream, "Caller Should validate outputStream parameter"); Dbg.Assert(null != errorStream, "Caller Should validate errorStream parameter"); Dbg.Assert(null != infoBuffers, "Caller Should validate informationalBuffers parameter"); Dbg.Assert(null != command, "Command cannot be null"); // Since we are constructing this pipeline using a commandcollection we dont need // to add cmd to CommandCollection again (Initialize does this).. because of this // I am handling history here.. Initialize(runspace, null, false, isNested); if (true == addToHistory) { // get command text for history.. string cmdText = command.GetCommandStringForHistory(); HistoryString = cmdText; AddToHistory = addToHistory; } //Initialize streams InputStream = inputStream; OutputStream = outputStream; ErrorStream = errorStream; InformationalBuffers = infoBuffers; }
public String psexceptionhandler(Exception e, bool iscommand = true, CommandCollection commands = null) { String rtn = ""; if (iscommand) { rtn += Environment.NewLine; } else { rtn += "Script Failed to Run!" + Environment.NewLine + Environment.NewLine; } switch (e.GetType().Name) { case "PSSecurityException": rtn += PSSecurityException((System.Management.Automation.PSSecurityException)e); break; case "CmdletInvocationException": rtn += CmdletInvocationException((System.Management.Automation.CmdletInvocationException)e); break; case "ParameterBindingException": rtn += ParameterBindingException((System.Management.Automation.ParameterBindingException)e); break; case "ParameterBindingValidationException": rtn += ParameterBindingValidationException((System.Management.Automation.ParameterBindingException)e); break; case "CommandNotFoundException": rtn += CommandNotFoundException((System.Management.Automation.CommandNotFoundException)e); break; default: rtn += PSException(e); break; } return rtn; }
public CommandCollection<ExtensionCommand> GetNodes() { var cc = new CommandCollection<ExtensionCommand>(); foreach (var type in AddinManager.NodesAssembly.GetTypes()) { if (reference != null) { foreach (XmlNode child in reference.ChildNodes) { if (child.Name == type.Name) { var ec = new ExtensionCommand { Name = child.Name, atts = child.Attributes, reference = child }; ec.Ass = AddinManager.NodesAssembly; cc.Add((ExtensionCommand)ec.Populate(type)); } } } } return cc; }
private RemotePipeline(RemoteRunspace runspace, bool addToHistory, bool isNested) : base(runspace) { this._syncRoot = new object(); this._pipelineStateInfo = new System.Management.Automation.Runspaces.PipelineStateInfo(PipelineState.NotStarted); this._commands = new CommandCollection(); this._executionEventQueue = new Queue<ExecutionEventQueueItem>(); this._performNestedCheck = true; this._addToHistory = addToHistory; this._isNested = isNested; this._isSteppable = false; this._runspace = runspace; this._computerName = ((RemoteRunspace) this._runspace).ConnectionInfo.ComputerName; this._runspaceId = this._runspace.InstanceId; this._inputCollection = new PSDataCollection<object>(); this._inputCollection.ReleaseOnEnumeration = true; this._inputStream = new PSDataCollectionStream<object>(Guid.Empty, this._inputCollection); this._outputCollection = new PSDataCollection<PSObject>(); this._outputStream = new PSDataCollectionStream<PSObject>(Guid.Empty, this._outputCollection); this._errorCollection = new PSDataCollection<ErrorRecord>(); this._errorStream = new PSDataCollectionStream<ErrorRecord>(Guid.Empty, this._errorCollection); this._methodExecutorStream = new ObjectStream(); this._isMethodExecutorStreamEnabled = false; base.SetCommandCollection(this._commands); this._pipelineFinishedEvent = new ManualResetEvent(false); }
public void SetUp() { _log = new Mock<ILog>(); _padlock = new Mock<IInstallationPadLock>(); _collection = new CommandCollection(_log.Object, _padlock.Object); _command = new Mock<IFeatureCommand>(); }
/// <summary> /// </summary> /// <param name="setting"></param> /// <param name="commands"></param> public CommandSet(ExecuteSetting setting, IList<ICommand> commands) { if (setting == null) throw new ArgumentNullException("setting"); if (commands == null) throw new ArgumentNullException("commands"); _executeSettings.Add(DefaultExecuteSetting, setting); _commands = new CommandCollection(commands); ; _commnadIds = new List<string>(); }
internal Pipeline(System.Management.Automation.Runspaces.Runspace runspace, CommandCollection command) { this._setPipelineSessionState = true; if (runspace == null) { PSTraceSource.NewArgumentNullException("runspace"); } this._pipelineId = runspace.GeneratePipelineId(); this._commands = command; }
internal PSCommand(PSCommand commandToClone) { this.commands = new CommandCollection(); foreach (Command command in commandToClone.Commands) { Command item = command.Clone(); this.commands.Add(item); this.currentCommand = item; } }
/// <summary> /// Internal copy constructor /// </summary> /// <param name="commandToClone"></param> internal PSCommand(PSCommand commandToClone) { _commands = new CommandCollection(); foreach (Command command in commandToClone.Commands) { Command clone = command.Clone(); // Attach the cloned Command to this instance. _commands.Add(clone); _currentCommand = clone; } }
/// <summary> /// Gets the value of the Commands attached property /// </summary> /// <param name="dependencyObject">dependency object to get the value</param> /// <returns>Instance of the command collection</returns> public static CommandCollection GetCommands(DependencyObject dependencyObject) { CommandCollection collection = (CommandCollection)dependencyObject.GetValue(CommandsProperty); if (collection == null) { collection = new CommandCollection(); dependencyObject.SetValue(CommandsProperty, collection); } return collection; }
public void op_Do_whenTrue() { var command = new Mock<ICommand>(); command .Setup(x => x.Act()) .Returns(true); var obj = new CommandCollection { command.Object }; Assert.True(obj.Do()); }
/// <summary> /// Create a Pipeline with an existing command string. /// Caller should validate all the parameters. /// </summary> /// <param name="runspace"> /// The LocalRunspace to associate with this pipeline. /// </param> /// <param name="command"> /// The command to execute. /// </param> /// <param name="addToHistory"> /// If true, add the command(s) to the history list of the runspace. /// </param> /// <param name="isNested"> /// If true, mark this pipeline as a nested pipeline. /// </param> /// <param name="inputStream"> /// Stream to use for reading input objects. /// </param> /// <param name="errorStream"> /// Stream to use for writing error objects. /// </param> /// <param name="outputStream"> /// Stream to use for writing output objects. /// </param> /// <param name="infoBuffers"> /// Buffers used to write progress, verbose, debug, warning, information /// information of an invocation. /// </param> internal LocalPipeline(LocalRunspace runspace, CommandCollection command, bool addToHistory, bool isNested, ObjectStreamBase inputStream, ObjectStreamBase outputStream, ObjectStreamBase errorStream, PSInformationalBuffers infoBuffers) : base(runspace, command, addToHistory, isNested, inputStream, outputStream, errorStream, infoBuffers) { _stopper = new PipelineStopper(this); InitStreams(); }
public void op_Equals_object() { var obj = new CommandCollection { new DerivedCommand() }; var comparand = new CommandCollection { new DerivedCommand() }; Assert.True(obj.Equals(comparand)); }
public OptionsForm() { InitializeComponent(); Panels.Add(new General()); foreach (ExtensionNode node in AddinManager.GetExtensionObjects("/EcIDE/Options")) { cmd = node.CreateInstances<IOptionPage>(); cmd.ForEach(c => c.Init(new ServiceContainer())); cmd.ForEach(c => Panels.Add(c.GetPage())); } }
private String CmdletInvocationException(System.Management.Automation.CmdletInvocationException e, CommandCollection commands = null) { String rtn = ""; rtn += "There was an error in your script or command. Please see the error message below." + Environment.NewLine + Environment.NewLine; rtn += "Error Message:" + Environment.NewLine; rtn += e.Message.ToString() + Environment.NewLine; rtn += e.ErrorRecord.ScriptStackTrace.Replace(Strings.StringValue.ScriptBlockNoFile, ""); if (commands != null) { rtn += "Commands: " + Environment.NewLine; foreach (Command cmd in commands) { rtn += cmd.CommandText.ToString() + Environment.NewLine; } } return rtn; }
protected PipelineBase(System.Management.Automation.Runspaces.Runspace runspace, CommandCollection command, bool addToHistory, bool isNested, ObjectStreamBase inputStream, ObjectStreamBase outputStream, ObjectStreamBase errorStream, PSInformationalBuffers infoBuffers) : base(runspace, command) { this._pipelineStateInfo = new System.Management.Automation.Runspaces.PipelineStateInfo(System.Management.Automation.Runspaces.PipelineState.NotStarted); this._performNestedCheck = true; this._executionEventQueue = new Queue<ExecutionEventQueueItem>(); this._syncRoot = new object(); this.Initialize(runspace, null, false, isNested); if (addToHistory) { string commandStringForHistory = command.GetCommandStringForHistory(); this._historyString = commandStringForHistory; this._addToHistory = addToHistory; } this._inputStream = inputStream; this._outputStream = outputStream; this._errorStream = errorStream; this._informationalBuffers = infoBuffers; }
public FormEventHandler(System.Windows.Forms.Form form) { #if ASSERT if (form == null) { throw new ArgumentNullException("form"); } #endif commandCollection = new CommandCollection(); this.form = form; keyState = new Dictionary<System.Windows.Forms.Keys, KeyState>(); mouseButtonState = new Dictionary<System.Windows.Forms.MouseButtons, MouseButtonState>(); mouseState = new MouseState(); form.KeyDown += KeyDownEvent; form.KeyUp += KeyUpEvent; form.MouseDown += MouseButtonDownEvent; form.MouseUp += MouseButtonUpEvent; // Put mouse in center of screen immediately, otherwise the first frame is way off System.Windows.Forms.Cursor.Position = new System.Drawing.Point(form.Width / 2, form.Height / 2); }
/// <summary> /// 执行事务 /// </summary> /// <param name="commands">命令集合</param> /// <returns></returns> public static Task <bool> ExecuteSqlTranAsync(CommandCollection commands) { return(DbProvider.ExecuteSqlTranAsync(commands)); }
public MainWindow() { #if !DEBUG // try { #endif InitializeComponent(); MainDescription.MainFrm = this; Application.Current.Resources["ThemeDictionary"] = new ResourceDictionary(); // this.SetCurrentTheme("ShinyBlue"); ; if (ConfigurationManager.AppSettings["PluginLocationRelative"] == "true") { pluginPosition = MainStartUpLocation + ConfigurationManager.AppSettings["MainPluginLocation"]; } else { pluginPosition = ConfigurationManager.AppSettings["MainPluginLocation"]; } XmlConfigurator.Configure(new FileInfo("log4net.config")); string icon = ConfigurationManager.AppSettings["Icon"]; try { Icon = new BitmapImage(new Uri(pluginPosition + icon, UriKind.Absolute)); } catch (Exception ex) { XLogSys.Print.Error(Core.Properties.Resources.IconNotExist); } PluginManager = new PluginManager(); #if !DEBUG Dispatcher.UnhandledException += (s, e) => { if (MessageBox.Show("是否保存当前工程的内容?您只有一次机会这样做,", "警告信息", MessageBoxButton.YesNoCancel) == MessageBoxResult.Yes) { dynamic process = PluginDictionary["模块管理"]; process.SaveCurrentTasks(); } MessageBox.Show("系统出现异常" + e.Exception); XLogSys.Print.Fatal(e.Exception); }; #endif ViewDictionary = new List <ViewItem>(); Title = ConfigurationManager.AppSettings["Title"]; // this.myDebugSystemUI.MainFrmUI = this; PluginManager.MainFrmUI = this; // this.myDebugSystemUI.Init(); PluginManager.Init(new[] { MainStartUpLocation }); PluginManager.LoadPlugins(); PluginManager.LoadView(); DataContext = this; foreach (ICommand action in CommandCollection.Concat(Commands)) { SetCommandKeyBinding(action); } XLogSys.Print.Info(Title + Core.Properties.Resources.Start); Closing += (s, e) => { if (MessageBox.Show(Core.Properties.Resources.Closing, Core.Properties.Resources.Tips, MessageBoxButton.OKCancel) == MessageBoxResult.OK) { PluginManager.Close(); PluginManager.SaveConfigFile(); Process.GetCurrentProcess().Kill(); } else { e.Cancel = true; } }; // TestCode(); #if !DEBUG } // catch (Exception ex) { // MessageBox.Show(ex.ToString()); } #endif }
internal Collection <PSObject> ExecuteCommandHelper(Pipeline tempPipeline, out Exception exceptionThrown, ExecutionOptions options) { Dbg.Assert(tempPipeline != null, "command should have a value"); exceptionThrown = null; Collection <PSObject> results = null; if ((options & ExecutionOptions.AddOutputter) > 0) { if (tempPipeline.Commands.Count < 2) { if (tempPipeline.Commands.Count == 1) { // Tell the script command to merge it's output and error streams. tempPipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); } // Add Out-Default to the pipeline to render. tempPipeline.Commands.Add(GetOutDefaultCommand(endOfStatement: false)); } else { // For multiple commands/scripts we need to insert Out-Default at the end of each statement. CommandCollection executeCommands = new CommandCollection(); foreach (var cmd in tempPipeline.Commands) { executeCommands.Add(cmd); if (cmd.IsEndOfStatement) { // End of statement needs to pipe to Out-Default. cmd.IsEndOfStatement = false; executeCommands.Add(GetOutDefaultCommand(endOfStatement: true)); } } var lastCmd = executeCommands.Last(); if (!((lastCmd.CommandText != null) && (lastCmd.CommandText.Equals("Out-Default", StringComparison.OrdinalIgnoreCase))) ) { // Ensure pipeline output goes to Out-Default. executeCommands.Add(GetOutDefaultCommand(endOfStatement: false)); } tempPipeline.Commands.Clear(); foreach (var cmd in executeCommands) { tempPipeline.Commands.Add(cmd); } } } Executor oldCurrent = CurrentExecutor; CurrentExecutor = this; lock (_instanceStateLock) { Dbg.Assert(_pipeline == null, "no other pipeline should exist"); _pipeline = tempPipeline; } try { // blocks until all results are retrieved. results = tempPipeline.Invoke(); } catch (Exception e) { exceptionThrown = e; } finally { // Once we have the results, or an exception is thrown, we throw away the pipeline. _parent.ui.ResetProgress(); CurrentExecutor = oldCurrent; Reset(); } return(results); }
private void Initialize(string command, bool isScript, bool? useLocalScope) { this.commands = new CommandCollection(); if (command != null) { this.currentCommand = new Command(command, isScript, useLocalScope); this.commands.Add(this.currentCommand); } }
public GetQuotecommand(string identifier, CommandCollection collection) { Register(identifier, collection); }
public Message(IDescriptor description, CommandCollection commands) { Description = description; Commands = commands; }
private static bool GetCompandMode( CommandCollection commands, CommandParser parser, CultureInfo culture) => parser.ParseValue <bool>(commands.GetValueOrDefault(Compand), culture);
private static ResizeMode GetMode( CommandCollection commands, CommandParser parser, CultureInfo culture) => parser.ParseValue <ResizeMode>(commands.GetValueOrDefault(Mode), culture);
/// <inheritdoc/> public bool RequiresTrueColorPixelFormat(CommandCollection commands, CommandParser parser, CultureInfo culture) { ResizeMode mode = parser.ParseValue <ResizeMode>(commands.GetValueOrDefault(Mode), culture); return(mode is ResizeMode.Pad or ResizeMode.BoxPad); }
public DistanceCommand(string identifier, CommandCollection collection) { Register(identifier, collection); }
public EmbedReplaceCommand(string identifier, CommandCollection collection) : base() { Register(identifier, collection); }
protected override CommandGroupCollection GetCommandGroups() { /////////////////////////////////////////////////////////////////// var rulesInImperialAgeOnly = new EachAgesCommandCollection(GroupType.ImperialAge, "帝王の時代にのみ適用するルール") { new InitImperialAge(), //帝王の時代の初期設定 new TrainVillager(200), //町の人を指定人数まで生産 new BuildMonastery(5), //神殿の建設 new BuildSiegeWorkshop(20), //包囲攻撃訓練所の建設 new TrainArcherLine(40), //射手の生産 new AttackNow(60, 90), //攻撃 new ImperialAgeGathererPercentages(), //帝王の時代の資源収集割合 new ExtendTownSizeForBuildings(1, 100), //建物を建てるために町のサイズを拡張する new TrainScorpion(), //スコーピオンの生産 new ResearchCoinage(), //貨幣制度の研究 new ResearchBanking(), //銀行取引 new ResearchGuilds(), //組合 new ResearchSpiesTreason(), //謀報/反逆の研究 new ResearchFervor(), //篤信の研究 new ResearchRedemption(), //贖い new ResearchAtonement(), //償い new ResearchHerbalMedicine(), //薬草学 new ResearchHeresy(), //異端 new ResearchStonecutting(), //人力起重機 new ResearchGuardTower(), //監視塔 }; /////////////////////////////////////////////////////////////////// var internalAffairsInImperial = new CommandCollection("帝王の時代の内政") { new ResearchTwoManSaw(), //両ひきのこぎりの研究 new ResearchCropRotation(), //輪作の研究 new SellSurplusCommodity(commodity.food, 1200, 1200), //食料があまっていたら売る new SellSurplusCommodity(commodity.wood, 1200, 1200), //木があまっていたら売る new SellSurplusCommodity(commodity.stone, 1200, 1200), //石があまっていたら売る //金が余ったら買う new BuyShortageCommodity(commodity.food, 1200, 1200), new BuyShortageCommodity(commodity.wood, 1200, 1200), new BuyShortageCommodity(commodity.stone, 1200, 650), }; /////////////////////////////////////////////////////////////////// var militaryInCastleAge = new CommandCollection("帝王の時代の軍事") { new ResearchRingArcherArmor(), //射手用鎖の鎧研究 new ResearchBracer(), //小手の研究 new ResearchBlastFurnace(), //高温溶鉱炉の研究 new ResearchPlateBarding(), //騎馬用甲冑の研究 new ResearchPlateMail(), //歩兵用甲冑の研究 new TrainHandCannoneer(), //砲撃手の生産 new ResearchArbalest(), //重石弓射手の研究 new ResearchParthianTactics(), //パルティアン戦術の研究 new ResearchHalberdier(), //矛槍兵の研究 new ResearchTwoHandedSwordsman(), //重剣剣士の研究 new ResearchChanpion(), //近衛剣士の研究 new ResearchHussar(), //ハサーの研究 new ResearchCavalier(), //重騎士の研究 new ResearchPaladin(), //近衛騎士の研究 new TrainBombardCannon(), //大砲の生産 new ResearchCappedRam(), //強化破城槌の研究 new ResearchSiegeRam(), //改良強化破城槌の研究 new ResearchOnager(), //改良型投石機の研究 new ResearchSiegeOnager(), //破城投石機の研究 new ResearchHeavyScorpion(), //ヘビースコーピオンの研究 new ResearchFaith(), //信仰の研究 new ResearchIllumination(), //啓蒙の研究 new ResearchBlockPrinting(), //活版印刷 new ResearchTheocracy(), //神政 }; /////////////////////////////////////////////////////////////////// var endOfInperialAge = new CommandCollection("帝王の時代中終盤") { new ResearchConscription(), //徴用の研究 new ResearchChemistry(), //化学 new ResearchArchitecture(), //建築学 new ResearchSiegeEngineers(), //包囲攻撃技術 new ResearchKeep(), //防御塔 new ResearchBombardTower(), //砲台 new ResearchUniqueUnitUpgrade(), //ユニークユニットの研究 new ResearchUniqueResearch(), //ユニークテクノロジの研究 new TrainTrebuchet(), //遠投投石機の生産 new ResearchHoardings(), //城壁強化の研究 new ResearchSappers(), //土木技術の研究 }; /////////////////////////////////////////////////////////////////// return(new CommandGroupCollection() { rulesInImperialAgeOnly, internalAffairsInImperial, militaryInCastleAge, endOfInperialAge }); }
public SetMacroCommand(string identifier, CommandCollection collection) { Register(identifier, collection); }
private String CmdletInvocationException(System.Management.Automation.CmdletInvocationException e, CommandCollection commands = null) { String rtn = ""; rtn += "There was an error in your script or command. Please see the error message below." + Environment.NewLine + Environment.NewLine; rtn += "Error Message:" + Environment.NewLine; rtn += e.Message.ToString() + Environment.NewLine; rtn += e.ErrorRecord.ScriptStackTrace.Replace(Strings.StringValue.ScriptBlockNoFile, ""); if (commands != null) { rtn += "Commands: " + Environment.NewLine; foreach (Command cmd in commands) { rtn += cmd.CommandText.ToString() + Environment.NewLine; } } return(rtn); }
/// <summary> /// Stop recording commands and added as a command. /// </summary> public void EndRecordCommands() { if (--recordingNestCount != 0) return; // Added recorded commands to commands. // If recording commands recored one command, we just add that command to // main commands. if (recordingCommands.Count != 0) { if (recordingCommands.Count == 1) m_undoableActions.Add(recordingCommands[0]); else m_undoableActions.AddRange(recordingCommands); if (Changed != null) Changed(this, EventArgs.Empty); } recordingCommands = null; }
/// <summary> /// Constructor to initialize both Runspace and Command to invoke. /// Caller should make sure that "command" is not null. /// </summary> /// <param name="runspace"> /// Runspace to use for the command invocation. /// </param> /// <param name="command"> /// command to Invoke. /// Caller should make sure that "command" is not null. /// </param> internal Pipeline(Runspace runspace, CommandCollection command) { if (runspace == null) { PSTraceSource.NewArgumentNullException("runspace"); } // This constructor is used only internally. // Caller should make sure the input is valid Dbg.Assert(null != command, "Command cannot be null"); InstanceId = runspace.GeneratePipelineId(); Commands = command; // Reset the AMSI session so that it is re-initialized // when the next script block is parsed. AmsiUtils.CloseSession(); }
/// <summary> /// Server Main Entry Point - Initialize as many things as possible here. /// Order is important here, any additional initialization should be place at the bottom. /// </summary> /// <param name="Directory">Start Directory.</param> public static void Start(string Directory) { try { // Initialize Setting Setting = new Setting(Directory); // Initialize Logger. Logger = new LoggerCollection(); Logger.Start(); if (Setting.Load()) { Setting.Save(); } else { Setting.Save(); Environment.Exit(0); return; } // Initialize Updater if (Setting.CheckForUpdate) { Updater = new Updater(); Updater.Update(); } if (Setting.MainEntryPoint == Setting.MainEntryPointType.jianmingyong_Server) { // Initialize Listener. Listener = new Server_Client_Listener.Servers.Listener(); Listener.Start(); // Initialize RCONListener. if (Setting.RCONEnable) { RCONListener = new RCON_Client_Listener.Servers.Listener(); RCONListener.Start(); } // Initialize SCONListener. if (Setting.SCONEnable) { SCONListener = new SCON_Client_Listener.Servers.ModuleSCON(); SCONListener.Start(); //Logger.Log("SCON have been disabled due to incompatible update. Sorry for the inconvience caused.", Server_Client_Listener.Loggers.Logger.LogTypes.Info); } // Initialize Nancy. if (Setting.NancyEnable) { var dataApi = new NancyData(); dataApi.Add("online", GetOnlineClients); NancyImpl.SetDataApi(dataApi); NancyImpl.Start(Setting.NancyHost, Setting.NancyPort); } } // Initialize Command. Command = new CommandCollection(); Command.AddCommand(); } catch (Exception ex) { ex.CatchError(); } }
/// <summary> /// Sets the command collection. /// </summary> /// <param name="commands">command collection to set</param> /// <remarks>called by ClientRemotePipeline</remarks> internal void SetCommandCollection(CommandCollection commands) { Commands = commands; }
internal Collection<PSObject> ExecuteCommandHelper(Pipeline tempPipeline, out Exception exceptionThrown, ExecutionOptions options) { Dbg.Assert(tempPipeline != null, "command should have a value"); exceptionThrown = null; Collection<PSObject> results = null; if ((options & ExecutionOptions.AddOutputter) > 0) { if (tempPipeline.Commands.Count < 2) { if (tempPipeline.Commands.Count == 1) { // Tell the script command to merge it's output and error streams. tempPipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); } // Add Out-Default to the pipeline to render. tempPipeline.Commands.Add(GetOutDefaultCommand(endOfStatement: false)); } else { // For multiple commands/scripts we need to insert Out-Default at the end of each statement. CommandCollection executeCommands = new CommandCollection(); foreach (var cmd in tempPipeline.Commands) { executeCommands.Add(cmd); if (cmd.IsEndOfStatement) { // End of statement needs to pipe to Out-Default. cmd.IsEndOfStatement = false; executeCommands.Add(GetOutDefaultCommand(endOfStatement: true)); } } var lastCmd = executeCommands.Last(); if (!((lastCmd.CommandText != null) && (lastCmd.CommandText.Equals("Out-Default", StringComparison.OrdinalIgnoreCase))) ) { // Ensure pipeline output goes to Out-Default. executeCommands.Add(GetOutDefaultCommand(endOfStatement: false)); } tempPipeline.Commands.Clear(); foreach (var cmd in executeCommands) { tempPipeline.Commands.Add(cmd); } } } Executor oldCurrent = CurrentExecutor; CurrentExecutor = this; lock (_instanceStateLock) { Dbg.Assert(_pipeline == null, "no other pipeline should exist"); _pipeline = tempPipeline; } try { // blocks until all results are retrieved. results = tempPipeline.Invoke(); } catch (Exception e) { ConsoleHost.CheckForSevereException(e); exceptionThrown = e; } finally { // Once we have the results, or an exception is thrown, we throw away the pipeline. _parent.ui.ResetProgress(); CurrentExecutor = oldCurrent; Reset(); } return results; }
private ApplicationModel() { _paintDocument = new PaintDocument(); _commands = new CommandCollection(); }
public WorkFlow Load(string fileName) { if (File.Exists(fileName)) { XmlSerializer mySerializer = new XmlSerializer(typeof(WorkFlow)); FileStream myFileStream = new FileStream(fileName, FileMode.Open); WorkFlow flow = (WorkFlow)mySerializer.Deserialize(myFileStream); myFileStream.Close(); WorkFlow resflow = Instance.CreateWorkFlow(); resflow.Id = flow.Id; resflow.Name = flow.Name; resflow.Description = flow.Description; resflow.Version = flow.Version; resflow.Properties.CopyValuesFrom(flow.Properties); foreach (Variable variable in flow.Variables.Items) { if (resflow.Variables[variable.Name] != null) { resflow.Variables[variable.Name].Value = variable.Value; } else { resflow.Variables.Items.Add(variable); } } foreach (var flowEvent in flow.Events) { IEventPlugin plugin = Instance.GetEventPlugin(flowEvent.PluginInfo.Class); WorkFlowEvent event_ = plugin.CreateEvent(); event_.Parent = resflow; event_.Instance = plugin; event_.PluginInfo = flowEvent.PluginInfo; event_.Name = flowEvent.Name; event_.Properties.CopyValuesFrom(flowEvent.Properties); foreach (var flowCommand in flowEvent.CommandCollection.Items) { IWorkflowCommand commandPlugin = Instance.GetCommandPlugin(flowCommand.PluginInfo.Class); var wCommand = commandPlugin.CreateCommand(); wCommand.Instance = commandPlugin; wCommand.PluginInfo = flowCommand.PluginInfo; wCommand.Name = flowCommand.Name; wCommand.Properties.CopyValuesFrom(flowCommand.Properties); event_.CommandCollection.Items.Add(wCommand); } resflow.Events.Add(event_); } foreach (var _view in flow.Views) { IViewPlugin plugin = Instance.GetViewPlugin(_view.PluginInfo.Class); WorkFlowView view = plugin.CreateView(); view.Parent = resflow; view.Instance = plugin; view.PluginInfo = _view.PluginInfo; view.Name = _view.Name; view.Properties.CopyValuesFrom(_view.Properties); foreach (var viewElement in _view.Elements) { IViewElementPlugin elementplugin = Instance.GetElementPlugin(viewElement.PluginInfo.Class); WorkFlowViewElement element = elementplugin.CreateElement(view); element.Parent = view; element.Instance = elementplugin; element.PluginInfo = viewElement.PluginInfo; element.Name = viewElement.Name; element.Properties.CopyValuesFrom(viewElement.Properties); view.Elements.Add(element); foreach (var commandCollection in element.Events) { CommandCollection loadedcommand = null; foreach (var collection in viewElement.Events) { if (collection.Name == commandCollection.Name) { loadedcommand = collection; } } if (loadedcommand != null) { foreach (var flowCommand in loadedcommand.Items) { IWorkflowCommand commandPlugin = Instance.GetCommandPlugin(flowCommand.PluginInfo.Class); var wCommand = commandPlugin.CreateCommand(); wCommand.Instance = commandPlugin; wCommand.PluginInfo = flowCommand.PluginInfo; wCommand.Name = flowCommand.Name; wCommand.Properties.CopyValuesFrom(flowCommand.Properties); commandCollection.Items.Add(wCommand); } } } } foreach (var commandCollection in view.Events) { CommandCollection loadedcommand = null; foreach (var collection in _view.Events) { if (collection.Name == commandCollection.Name) { loadedcommand = collection; } } if (loadedcommand != null) { foreach (var flowCommand in loadedcommand.Items) { IWorkflowCommand commandPlugin = Instance.GetCommandPlugin(flowCommand.PluginInfo.Class); var wCommand = commandPlugin.CreateCommand(); wCommand.Instance = commandPlugin; wCommand.PluginInfo = flowCommand.PluginInfo; wCommand.Name = flowCommand.Name; wCommand.Properties.CopyValuesFrom(flowCommand.Properties); commandCollection.Items.Add(wCommand); } } } resflow.Views.Add(view); } return(resflow); } return(null); }
/** * lua调用 */ /*public void sendMessageByString(int type, LuaStringBuffer str) * { * sendMessage((ProtoTypeEnum)type, str.buffer); * }*/ public void sendMessageByGeneratedMessage(int type, object obj) { byte[] cust = CommandCollection.getDataModelToByteArray((ProtoTypeEnum)type, obj); sendMessage((ProtoTypeEnum)type, cust); }
/// <summary> /// Runs a command on this database and returns the result as a TCommandResult. /// </summary> /// <param name="commandResultType">The command result type.</param> /// <param name="command">The command object.</param> /// <returns>A TCommandResult</returns> public virtual CommandResult RunCommandAs(Type commandResultType, IMongoCommand command) { return(CommandCollection.RunCommandAs(commandResultType, command)); }
/// <summary> /// 执行事务 /// </summary> /// <param name="commands">命令集合</param> /// <returns></returns> public static bool ExecuteSqlTran(CommandCollection commands) { return(DbProvider.ExecuteSqlTran(commands)); }
public void Generate(string target, TextWriter writer, CommandCollection commandCollection) { var provider = _providers.First(x => x.Targets.Contains(target)); provider.Generate(writer, commandCollection); }
/// <summary> /// Creates a PSCommand from the specified command /// </summary> /// <param name="command">Command object to use.</param> internal PSCommand(Command command) { _currentCommand = command; _commands = new CommandCollection(); _commands.Add(_currentCommand); }
public HelpCommand(CommandCollection commands) { _commands = commands; }
public PSCommand() { commands = new CommandCollection(); }
private void PacketExecute(object state) { try { KeyValuePair<ServerConnection, Packet> order = (KeyValuePair<ServerConnection, Packet>)state; BinaryReader reader = new BinaryReader(order.Value.Request); Message msgRequest = Message.Deserialize(reader, (id) => StorageEngine.Find(id)); IDescriptor clientDescription = msgRequest.Description; CommandCollection resultCommands = new CommandCollection(1); try { var commands = msgRequest.Commands; if (msgRequest.Description != null) // XTable commands { XTablePortable table = (XTablePortable)StorageEngine.OpenXTablePortable(clientDescription.Name, clientDescription.KeyDataType, clientDescription.RecordDataType); table.Descriptor.Tag = clientDescription.Tag; for (int i = 0; i < commands.Count - 1; i++) { ICommand command = msgRequest.Commands[i]; CommandsIIndexExecute[command.Code](table, command); } ICommand resultCommand = CommandsIIndexExecute[msgRequest.Commands[commands.Count - 1].Code](table, msgRequest.Commands[commands.Count - 1]); if (resultCommand != null) resultCommands.Add(resultCommand); table.Flush(); } else //Storage engine commands { ICommand command = msgRequest.Commands[commands.Count - 1]; var resultCommand = CommandsStorageEngineExecute[command.Code](command); if (resultCommand != null) resultCommands.Add(resultCommand); } } catch (Exception e) { resultCommands.Add(new ExceptionCommand(e.Message)); } MemoryStream ms = new MemoryStream(); BinaryWriter writer = new BinaryWriter(ms); Descriptor responseClientDescription = new Descriptor(-1, "", StructureType.RESERVED, DataType.Boolean, DataType.Boolean, null, null, DateTime.Now, DateTime.Now, DateTime.Now, null); Message msgResponse = new Message(msgRequest.Description == null ? responseClientDescription : msgRequest.Description, resultCommands); msgResponse.Serialize(writer); ms.Position = 0; order.Value.Response = ms; order.Key.PendingPackets.Add(order.Value); } catch (Exception exc) { TcpServer.LogError(exc); } }
/// <inheritdoc/> public bool RequiresTrueColorPixelFormat(CommandCollection commands, CommandParser parser, CultureInfo culture) => false;
/// <summary> /// Record multiple commands as one command. /// </summary> public void BeginRecordCommands() { if (recordingNestCount++ == 0) recordingCommands = new CommandCollection(); }
public HelpMessage CreateCommandsIndexHelp(CommandCollection commandCollection, IReadOnlyList <CommandDescriptor> subCommandStack) { var help = new HelpMessage(); // Usage var usageSection = new HelpSection(HelpSectionId.Usage); var subCommandParams = (subCommandStack.Count > 0) ? string.Join(" ", subCommandStack.Select(x => x.Name)) + " " : ""; if (commandCollection.All.Count != 1) { usageSection.Children.Add(new HelpUsage($"Usage: {_applicationMetadataProvider.GetExecutableName()} {subCommandParams}[command]")); } if (commandCollection.Primary != null && (commandCollection.All.Count == 1 || commandCollection.Primary.Options.Any() || commandCollection.Primary.Arguments.Any())) { usageSection.Children.Add(new HelpUsage($"Usage: {CreateUsageCommandOptionsAndArgs(commandCollection.Primary, subCommandStack)}")); } help.Children.Add(usageSection); // Description var description = !string.IsNullOrWhiteSpace(commandCollection.Description) ? commandCollection.Description : !string.IsNullOrWhiteSpace(commandCollection.Primary?.Description) ? commandCollection.Primary?.Description : !string.IsNullOrWhiteSpace(_applicationMetadataProvider.GetDescription()) ? _applicationMetadataProvider.GetDescription() : string.Empty; if (!string.IsNullOrWhiteSpace(description)) { help.Children.Add(new HelpSection(HelpSectionId.Description, new HelpDescription(description !))); } // Commands var commandsExceptPrimary = commandCollection.All.Where(x => !x.IsPrimaryCommand && !x.IsHidden).ToArray(); if (commandsExceptPrimary.Any()) { help.Children.Add(new HelpSection(HelpSectionId.Commands, new HelpHeading("Commands:"), new HelpSection( new HelpLabelDescriptionList( commandsExceptPrimary .Select((x, i) => new HelpLabelDescriptionListItem(x.Name, x.Description) ) .ToArray() ) ) )); } // Show helps for primary command. if (commandCollection.Primary != null) { // Arguments AddHelpForCommandArguments(help, commandCollection.Primary.Arguments); // Options AddHelpForCommandOptions(help, commandCollection.Primary.Options.OfType <ICommandOptionDescriptor>().Concat(commandCollection.Primary.OptionLikeCommands)); } // Transform help document if (commandCollection.Primary != null) { var transformers = FilterHelper.GetFilters <ICoconaHelpTransformer>(commandCollection.Primary.Method, _serviceProvider); // TODO: This is ad-hoc workaround for default primary command. if (BuiltInPrimaryCommand.IsBuiltInCommand(commandCollection.Primary)) { transformers = commandCollection.All .Select(x => x.CommandType) .Distinct() .SelectMany(x => FilterHelper.GetFilters <ICoconaHelpTransformer>(x, _serviceProvider)) .ToArray(); } foreach (var transformer in transformers) { transformer.TransformHelp(help, commandCollection.Primary); } } return(help); }
/// <summary> /// Sets the value of the Commands attached property /// </summary> /// <param name="dependencyObject">dependency object to set the value</param> /// <param name="value">Instance of the command collection</param> public static void SetCommands(DependencyObject dependencyObject, CommandCollection value) { dependencyObject.SetValue(CommandsProperty, value); }
public MainWindow() { #if !DEBUG // try { #endif InitializeComponent(); MainDescription.MainFrm = this; notifier = new Notifier(cfg => { cfg.PositionProvider = new WindowPositionProvider(Application.Current.MainWindow, Corner.TopRight, 10, 10); cfg.LifetimeSupervisor = new TimeAndCountBasedLifetimeSupervisor( TimeSpan.FromSeconds(2), MaximumNotificationCount.FromCount(3)); cfg.Dispatcher = Application.Current.Dispatcher; }); ToolTipService.ShowDurationProperty.OverrideMetadata( typeof(DependencyObject), new FrameworkPropertyMetadata(60000)); Application.Current.Resources["ThemeDictionary"] = new ResourceDictionary(); // this.SetCurrentTheme("ShinyBlue"); ; if (ConfigurationManager.AppSettings["PluginLocationRelative"] == "true") { MainPluginLocation = MainStartUpLocation + ConfigurationManager.AppSettings["MainPluginLocation"]; } else { MainPluginLocation = ConfigurationManager.AppSettings["MainPluginLocation"]; } XmlConfigurator.Configure(new FileInfo("log4net.config")); var icon = ConfigurationManager.AppSettings["Icon"]; try { Icon = new BitmapImage(new Uri(MainPluginLocation + icon, UriKind.Absolute)); } catch (Exception) { XLogSys.Print.Error(GlobalHelper.Get("IconNotExist")); } PluginManager = new PluginManager(); #if !DEBUG Dispatcher.UnhandledException += (s, e) => { if (MessageBox.Show(GlobalHelper.Get("key_0"), GlobalHelper.Get("key_1"), MessageBoxButton.YesNoCancel) == MessageBoxResult.Yes) { dynamic process = PluginDictionary["DataProcessManager"]; process.SaveCurrentTasks(); } MessageBox.Show(GlobalHelper.Get("key_2") + e.Exception); XLogSys.Print.Fatal(e.Exception); }; #endif AppHelper.LoadLanguage(); ViewDictionary = new List <ViewItem>(); Title = ConfigurationManager.AppSettings["Title"]; // this.myDebugSystemUI.MainFrmUI = this; PluginManager.MainFrmUI = this; // this.myDebugSystemUI.Init(); PluginManager.Init(new[] { MainStartUpLocation }); PluginManager.LoadPlugins(); PluginManager.LoadView(); DataContext = this; foreach (var action in CommandCollection.Concat(Commands)) { SetCommandKeyBinding(action); } XLogSys.Print.Info(Title + GlobalHelper.Get("Start")); AutoUpdater.Start("https://raw.githubusercontent.com/ferventdesert/Hawk/global/Hawk/autoupdate.xml"); Closing += (s, e) => { List <IDataProcess> revisedTasks; var processmanager = PluginDictionary["DataProcessManager"] as DataProcessManager; revisedTasks = processmanager.GetRevisedTasks().ToList(); if (!revisedTasks.Any()) { if ( MessageBox.Show(GlobalHelper.Get("Closing"), GlobalHelper.Get("Tips"), MessageBoxButton.OKCancel) == MessageBoxResult.OK) { PluginManager.Close(); PluginManager.SaveConfigFile(); } else { e.Cancel = true; } } else { var result = MessageBox.Show(GlobalHelper.FormatArgs( "RemaindSave", " ".Join(revisedTasks.Select(d => d.Name).ToArray())), GlobalHelper.Get("Tips"), MessageBoxButton.YesNoCancel); if (result == MessageBoxResult.Yes || result == MessageBoxResult.No) { if (result == MessageBoxResult.Yes) { revisedTasks.Execute(d => processmanager.SaveTask(d, false)); } PluginManager.Close(); PluginManager.SaveConfigFile(); } else { e.Cancel = true; } } }; //File.WriteAllText("helper.md", ETLHelper.GetTotalMarkdownDoc()); // var md = ETLHelper.GetAllToolMarkdownDoc(); // File.WriteAllText("HawkDoc.md", md); // TestCode(); #if !DEBUG } // catch (Exception ex) { // MessageBox.Show(ex.ToString()); } #endif }
internal PSCommand(Command command) { this.currentCommand = command; this.commands = new CommandCollection(); this.commands.Add(this.currentCommand); }
/// <summary> /// 显示菜单、命令到主窗口中 /// </summary> /// <param name="modelID">模块</param> /// <returns></returns> public static void ShowMenuAtMainForm(String modelID, ToolStripMenuItem[] ExistingMenuItem) { if (Cache.CustomCache.Contains(SystemString.菜单栏)) { MenuStrip MainMenu = (MenuStrip)Cache.CustomCache[SystemString.菜单栏]; Dictionary <string, ToolStripItem[]> MenuCollection = null; if (Cache.CustomCache.Contains(MenuKey)) { MenuCollection = (Dictionary <string, ToolStripItem[]>)Cache.CustomCache[MenuKey]; } else { MenuCollection = new Dictionary <string, ToolStripItem[]>(); Cache.CustomCache.Add(MenuKey, MenuCollection); } MainMenu.Items.Clear(); MainMenu.Items.AddRange(ExistingMenuItem); ToolStripItem[] WillAddedItems = null; if (MenuCollection.ContainsKey(modelID)) { WillAddedItems = MenuCollection[modelID]; } if (WillAddedItems != null) { for (int i = 0; i < WillAddedItems.Length; i++) { WillAddedItems[i].ImageTransparentColor = Color.White; MainMenu.Items.Insert(0, WillAddedItems[i]); } } } if (Cache.CustomCache.Contains(SystemString.工具栏)) { ToolStrip MainTool = (ToolStrip)Cache.CustomCache[SystemString.工具栏]; Dictionary <string, ToolStripItem[]> CommandCollection = null; if (Cache.CustomCache.Contains(CommandKey)) { CommandCollection = Cache.CustomCache[CommandKey] as Dictionary <string, ToolStripItem[]>; } else { CommandCollection = new Dictionary <string, ToolStripItem[]>(); Cache.CustomCache.Add(CommandKey, CommandCollection); } MainTool.Items.Clear(); ToolStripItem[] WillAddedCommands = null; if (CommandCollection.ContainsKey(modelID)) { WillAddedCommands = CommandCollection[modelID]; } if (WillAddedCommands != null) { MainTool.SuspendLayout(); for (int i = 0; i < WillAddedCommands.Length; i++) { WillAddedCommands[i].TextImageRelation = TextImageRelation.ImageAboveText; WillAddedCommands[i].ImageTransparentColor = Color.White; WillAddedCommands[i].Font = new Font("宋体", 9); MainTool.Items.Add(WillAddedCommands[i]); } MainTool.ResumeLayout(); } } }
// internals internal Pipeline() { Commands = new CommandCollection(); }
private void SetResult(CommandCollection commands, CommandCollection resultCommands) { var command = commands[commands.Count - 1]; if (!command.IsSynchronous) { return; } var resultOperation = resultCommands[resultCommands.Count - 1]; try { switch (command.Code) { case CommandCode.TRY_GET: ((TryGetCommand)command).Record = ((TryGetCommand)resultOperation).Record; break; case CommandCode.FORWARD: ((ForwardCommand)command).List = ((ForwardCommand)resultOperation).List; break; case CommandCode.BACKWARD: ((BackwardCommand)command).List = ((BackwardCommand)resultOperation).List; break; case CommandCode.FIND_NEXT: ((FindNextCommand)command).KeyValue = ((FindNextCommand)resultOperation).KeyValue; break; case CommandCode.FIND_AFTER: ((FindAfterCommand)command).KeyValue = ((FindAfterCommand)resultOperation).KeyValue; break; case CommandCode.FIND_PREV: ((FindPrevCommand)command).KeyValue = ((FindPrevCommand)resultOperation).KeyValue; break; case CommandCode.FIND_BEFORE: ((FindBeforeCommand)command).KeyValue = ((FindBeforeCommand)resultOperation).KeyValue; break; case CommandCode.FIRST_ROW: ((FirstRowCommand)command).Row = ((FirstRowCommand)resultOperation).Row; break; case CommandCode.LAST_ROW: ((LastRowCommand)command).Row = ((LastRowCommand)resultOperation).Row; break; case CommandCode.COUNT: ((CountCommand)command).Count = ((CountCommand)resultOperation).Count; break; case CommandCode.STORAGE_ENGINE_COMMIT: break; case CommandCode.EXCEPTION: throw new Exception(((ExceptionCommand)command).Exception); default: break; } } catch (Exception e) { throw new Exception(e.ToString()); } }
private void PacketExecute(object state) { try { KeyValuePair <ServerConnection, Packet> order = (KeyValuePair <ServerConnection, Packet>)state; BinaryReader reader = new BinaryReader(order.Value.Request); Message msgRequest = Message.Deserialize(reader, (id) => StorageEngine.Find(id)); IDescriptor clientDescription = msgRequest.Description; CommandCollection resultCommands = new CommandCollection(1); try { var commands = msgRequest.Commands; if (msgRequest.Description != null) // XTable commands { XTable table = (XTable)StorageEngine.OpenXTable(clientDescription.Name, clientDescription.KeyDataType, clientDescription.RecordDataType); table.Descriptor.Tag = clientDescription.Tag; for (int i = 0; i < commands.Count - 1; i++) { ICommand command = msgRequest.Commands[i]; CommandsIIndexExecute[command.Code](table, command); } ICommand resultCommand = CommandsIIndexExecute[msgRequest.Commands[commands.Count - 1].Code](table, msgRequest.Commands[commands.Count - 1]); if (resultCommand != null) { resultCommands.Add(resultCommand); } table.Flush(); } else //Storage engine commands { ICommand command = msgRequest.Commands[commands.Count - 1]; var resultCommand = CommandsStorageEngineExecute[command.Code](command); if (resultCommand != null) { resultCommands.Add(resultCommand); } } } catch (Exception e) { resultCommands.Add(new ExceptionCommand(e.Message)); } MemoryStream ms = new MemoryStream(); BinaryWriter writer = new BinaryWriter(ms); Descriptor responseClientDescription = new Descriptor(-1, "", StructureType.RESERVED, DataType.Boolean, DataType.Boolean, null, null, DateTime.Now, DateTime.Now, DateTime.Now, null); Message msgResponse = new Message(msgRequest.Description == null ? responseClientDescription : msgRequest.Description, resultCommands); msgResponse.Serialize(writer); ms.Position = 0; order.Value.Response = ms; order.Key.PendingPackets.Add(order.Value); } catch (Exception exc) { TcpServer.LogError(exc); } }
private CommandCollection GetWrappedCommandCollection(CommandCollection commandCollection, int depth = 0) { var commands = commandCollection.All; // If the collection has multiple-commands without primary command, use built-in primary command. if (commandCollection.All.Count > 1 && commandCollection.Primary == null) { commands = commands.Append(BuiltInPrimaryCommand.GetCommand(string.Empty)).ToArray(); } // Rewrite all command names as lower-case and inject built-in help and version help var newCommands = new CommandDescriptor[commands.Count]; for (var i = 0; i < commands.Count; i++) { var command = commands[i]; newCommands[i] = new CommandDescriptor( command.Method, command.Name, command.Aliases, command.Description, command.Parameters, command.Options, command.Arguments, command.Overloads, BuildOptionLikeCommands(command), command.Flags, (command.SubCommands != null && command.SubCommands != commandCollection) ? GetWrappedCommandCollection(command.SubCommands, depth + 1) : command.SubCommands ); } IReadOnlyList <CommandOptionLikeCommandDescriptor> BuildOptionLikeCommands(CommandDescriptor command) { IEnumerable <CommandOptionLikeCommandDescriptor> optionLikeCommands = command.OptionLikeCommands; // NOTE: ToHashSet() requires .NET Standard 2.1 var allNames = new HashSet <string>(command.Options.Select(x => x.Name).Concat(command.OptionLikeCommands.Select(x => x.Name))); var allShortNames = new HashSet <char>(command.Options.SelectMany(x => x.ShortName).Concat(command.OptionLikeCommands.SelectMany(x => x.ShortName))); if (!allNames.Contains(BuiltInOptionLikeCommands.Help.Name) && !allShortNames.Overlaps(BuiltInOptionLikeCommands.Help.ShortName)) { optionLikeCommands = optionLikeCommands.Append(BuiltInOptionLikeCommands.Help); } if (command.IsPrimaryCommand && depth == 0) { if (_enableShellCompletionSupport) { // --completion-candidates, --completion, ... original ..., --version optionLikeCommands = optionLikeCommands.Prepend(BuiltInOptionLikeCommands.Completion).Prepend(BuiltInOptionLikeCommands.CompletionCandidates); } if (!allNames.Contains(BuiltInOptionLikeCommands.Version.Name) && !allShortNames.Overlaps(BuiltInOptionLikeCommands.Version.ShortName)) { optionLikeCommands = optionLikeCommands.Append(BuiltInOptionLikeCommands.Version); } } return(optionLikeCommands.ToArray()); } return(new CommandCollection(newCommands)); }