コード例 #1
0
        private Dictionary<String, Object> getActualArguments(CommandDescriptor commandDescriptor, CommandCallDescriptor commandCallDescriptor)
        {
            // order arguments by position
            var positionedArguments = commandCallDescriptor.ActualParameters
                                                           .OfType<PositionedCommandCallActualArgument>()
                                                           .OrderBy(argument => argument.Position);

            // try to match formal and actual arguments to each other
            var zippedArguments = commandDescriptor.Arguments.Zip(positionedArguments, (formalArg, actualArg) => new
            {
                FormalArgument = formalArg,
                ActualArgument = actualArg
            });

            // filter not matching types
            zippedArguments = zippedArguments.Where(arguments => {
                if (arguments.ActualArgument.Value == null)
                {
                    return arguments.FormalArgument.ArgumentType == typeof (Object);
                }

                return arguments.FormalArgument.ArgumentType == arguments.ActualArgument.Value.GetType() &&
                       arguments.FormalArgument.Position == arguments.ActualArgument.Position;
            });

            return zippedArguments.ToDictionary(
                arguments => arguments.FormalArgument.ArgumentName,
                arguments => arguments.ActualArgument.Value);
        }
コード例 #2
0
ファイル: HelpCommand.cs プロジェクト: Higea/Orchard
        private LocalizedString GetHelpText(CommandDescriptor descriptor) {
            if (string.IsNullOrEmpty(descriptor.HelpText)) {
                return T("{0}: no help text",
                         descriptor.MethodInfo.DeclaringType.FullName + "." + descriptor.MethodInfo.Name);
            }

            return T(descriptor.HelpText);
        }
コード例 #3
0
ファイル: HelpCommand.cs プロジェクト: nicklv/Orchard2
        private LocalizedString GetHelpText(CommandDescriptor descriptor)
        {
            if (string.IsNullOrEmpty(descriptor.HelpText)) {
                return T($"{descriptor.MethodInfo.DeclaringType?.FullName}.{descriptor.MethodInfo.Name}: no help text");
            }

            return T(descriptor.HelpText);
        }
コード例 #4
0
ファイル: HelpCommand.cs プロジェクト: zqb971/Orchard2
        private LocalizedString GetHelpText(CommandDescriptor descriptor)
        {
            if (string.IsNullOrEmpty(descriptor.HelpText))
            {
                return(T($"{descriptor.MethodInfo.DeclaringType?.FullName}.{descriptor.MethodInfo.Name}: no help text"));
            }

            return(T(descriptor.HelpText));
        }
コード例 #5
0
        private string CreateUsageCommandOptionsAndArgs(CommandDescriptor command)
        {
            var sb = new StringBuilder();

            sb.Append(_applicationMetadataProvider.GetExecutableName());

            if (!command.IsPrimaryCommand)
            {
                sb.Append(" ");
                sb.Append(command.Name);
            }

            if (command.Options.Any(x => !x.IsHidden))
            {
                foreach (var opt in command.Options.Where(x => !x.IsHidden))
                {
                    sb.Append(" ");
                    if (opt.OptionType == typeof(bool))
                    {
                        if (opt.DefaultValue.HasValue && opt.DefaultValue.Value.Equals(true))
                        {
                            sb.Append($"[--{opt.Name}=<true|false>]");
                        }
                        else
                        {
                            sb.Append($"[--{opt.Name}]");
                        }
                    }
                    else if (DynamicListHelper.IsArrayOrEnumerableLike(opt.OptionType))
                    {
                        sb.Append($"[--{opt.Name} <{opt.ValueName}>...]");
                    }
                    else
                    {
                        sb.Append($"[--{opt.Name} <{opt.ValueName}>]");
                    }
                }
            }

            if (command.Arguments.Any())
            {
                foreach (var arg in command.Arguments)
                {
                    sb.Append(" ");
                    if (arg.IsEnumerableLike)
                    {
                        sb.Append($"{arg.Name}0 ... {arg.Name}N");
                    }
                    else
                    {
                        sb.Append(arg.Name);
                    }
                }
            }

            return(sb.ToString());
        }
コード例 #6
0
        private LocalizedString GetHelpText(CommandDescriptor descriptor)
        {
            if (string.IsNullOrEmpty(descriptor.HelpText))
            {
                return(S["{0}.{1}: no help text", descriptor.MethodInfo.DeclaringType?.FullName, descriptor.MethodInfo.Name]);
            }

            return(S[descriptor.HelpText]);
        }
コード例 #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CommandContext{TCommand,TResult}"/> class.
        /// </summary>
        /// <param name="descriptor">The <see cref="CommandDescriptor"/>.</param>
        /// <param name="command">The command that is being processed.</param>
        public CommandContext(CommandDescriptor descriptor, TCommand command)
        {
            Ensure.Arg.NotNull(descriptor, nameof(descriptor));
            Ensure.Arg.OfType <TCommand>(descriptor.CommandType, nameof(descriptor));
            Ensure.Arg.NotNull(command, nameof(command));

            CommandDescriptor = descriptor;
            Command           = command;
        }
コード例 #8
0
ファイル: MenuHelper.cs プロジェクト: mff-uk/exolutio
        static MenuHelper()
        {
            /*
             * Create one instance of guiControllerCommand for each existing public command.
             * This instance is later used in every context menu (instances of commands are shared
             * among the existing menus)
             */
            foreach (List <CommandDescriptor> scopeCommands in PublicCommandsHelper.publicCommandsByScope.Values)
            {
                foreach (CommandDescriptor commandDescriptor in scopeCommands)
                {
                    guiControllerCommand guiC       = new guiControllerCommand();
                    CommandDescriptor    descriptor = commandDescriptor;
                    guiC.ControllerCommandFactoryMethod =
                        delegate
                    {
                        return(CommandSerializer.CreateCommandObject(descriptor.CommandType));
                    };
                    guiC.ControllerCommandType        = commandDescriptor.CommandType;
                    guiC.ControllerCommandDescription = commandDescriptor.CommandDescription;
                    guiCommandsForControllerCommands[commandDescriptor.CommandType] = guiC;
                }
            }

            foreach (Type t in typeof(guiScopeCommand).Assembly.GetTypes())
            {
                if (t.IsSubclassOf(typeof(guiScopeCommand)))
                {
                    ScopeAttribute a = (ScopeAttribute)t.GetCustomAttributes(typeof(ScopeAttribute), true).FirstOrDefault();
                    if (a != null)
                    {
                        #if SILVERLIGHT
                        foreach (ScopeAttribute.EScope scope in EnumHelper.GetValues(typeof(ScopeAttribute.EScope)))
                        #else
                        foreach (ScopeAttribute.EScope scope in Enum.GetValues(typeof(ScopeAttribute.EScope)))
                        #endif
                        {
                            if (scope == ScopeAttribute.EScope.None)
                            {
                                continue;
                            }
                            if (a.Scope.HasFlag(scope))
                            {
                                localCommandsByScope.CreateSubCollectionIfNeeded(scope);
                                localCommandsByScope[scope].Add((guiScopeCommand)t.GetConstructor(Type.EmptyTypes).Invoke(null));
                            }
                        }
                        if (a.Scope == ScopeAttribute.EScope.None)
                        {
                            localCommandsByScope.CreateSubCollectionIfNeeded(a.Scope);
                            localCommandsByScope[a.Scope].Add((guiScopeCommand)t.GetConstructor(Type.EmptyTypes).Invoke(null));
                        }
                    }
                }
            }
        }
コード例 #9
0
        public GenericCommandSet()
        {
            _keyPressCommand = new CommandDescriptor()
            {
                CreateCommandInstance = () => new KeyPressCommand(),
                ActionText = "Key Press"
            };

            _keyMapCommand = new CommandDescriptor()
            {
                CreateCommandInstance = () => new KeyMapCommand(),
                ActionText = "Key Map"
            };

            _mouseClickCommand = new CommandDescriptor()
            {
                CreateCommandInstance = () => new MouseClickCommand(),
                ActionText = "Mouse Click"
            };

            _mouseMoveCommand = new CommandDescriptor()
            {
                CreateCommandInstance = () => new MouseMoveCommand(),
                ActionText = "Mouse Move"
            };

            _mouseControlCommand = new CommandDescriptor()
            {
                CreateCommandInstance = () => new MouseControlCommand(),
                ActionText = "Control Mouse"
            };

            _upCommand = new CommandDescriptor()
            {
                CreateCommandInstance = () => new KeyMapCommand() { Key = System.Windows.Forms.Keys.Up, AllowUserProperties = false },
                ActionText = "Up"
            };

            _downCommand = new CommandDescriptor()
            {
                CreateCommandInstance = () => new KeyMapCommand() { Key = System.Windows.Forms.Keys.Down, AllowUserProperties = false },
                ActionText = "Down"
            };

            _leftCommand = new CommandDescriptor()
            {
                CreateCommandInstance = () => new KeyMapCommand() { Key = System.Windows.Forms.Keys.Left, AllowUserProperties = false },
                ActionText = "Left"
            };

            _rightCommand = new CommandDescriptor()
            {
                CreateCommandInstance = () => new KeyMapCommand() { Key = System.Windows.Forms.Keys.Right, AllowUserProperties = false },
                ActionText = "Right"
            };
        }
コード例 #10
0
        public void GetDescriptor_ReturnsRegisteredCommandUsingCommandAttribute()
        {
            CommandRegistry commandRegistry = new CommandRegistry();

            commandRegistry.Register(typeof(TestAttributedCommand));

            CommandDescriptor descriptor = commandRegistry.GetDescriptor("overridden", null);

            Assert.That(descriptor.Name, Is.EqualTo("overridden"));
        }
コード例 #11
0
        public void TestInitialValues()
        {
            CommandDescriptor descriptor = new CommandDescriptor();

            Assert.That(descriptor.Name, Is.Null);
            Assert.That(descriptor.CommandType, Is.Null);
            Assert.That(descriptor.Aliases, Is.Not.Null);
            Assert.That(descriptor.Arguments, Is.Not.Null);
            Assert.That(descriptor.SubCommands, Is.Not.Null);
        }
コード例 #12
0
        public void GetDescriptor_ReturnsRegisteredCommand()
        {
            CommandRegistry commandRegistry = new CommandRegistry();

            commandRegistry.Register(typeof(TestCommand));

            CommandDescriptor descriptor = commandRegistry.GetDescriptor("test", null);

            Assert.That(descriptor.Name, Is.EqualTo("test"));
        }
コード例 #13
0
        private static ICommandDescriptor CreateAddWaypointMenuItem(ConnectorUI ui)
        {
            var descriptor = new CommandDescriptor()
            {
                Name    = "Add Waypoint",
                Command = new DelegateCommand(ui.AddWaypoint)
            };

            return(descriptor);
        }
コード例 #14
0
        public SeveralOptionsAndArgumentsTestData()
        //                                string originalName,
        //                                string commandLineName,
        //                                string typeStringRepresentation,
        //                                string? description,
        //                                DefaultValueDescriptor? defaultValue)
            : base("SeveralOptionsAndArguments")
        {
            string sourceCode = $@"NOT YET IMPLEMENTED: Read corresponding file";

            var commandDescriptor = new CommandDescriptor(null, "MyClass", RawInfo.DummyClass)
            {
                Name = "my-class"
            };

            commandDescriptor.AddArguments(arguments: new List <ArgumentDescriptor>()
            {
                new ArgumentDescriptor(new ArgTypeInfoRoslyn(typeof(string)), null, "MyArgPropertyArg", RawInfo.DummyProperty)
                {
                    Name    = "MyArgPropertyArg",
                    CliName = "my-property-arg",
                },
            });

            commandDescriptor.AddOptions(options: new List <OptionDescriptor>()
            {
                new OptionDescriptor(null, "MyProperty", RawInfo.DummyProperty)
                {
                    Name    = "MyProperty",
                    CliName = "my-property",
                },
                new OptionDescriptor(null, "MyProperty2", RawInfo.DummyProperty)
                {
                    Name    = "MyProperty2",
                    CliName = "my-property2",
                },
                new OptionDescriptor(null, "MyProperty3", RawInfo.DummyProperty)
                {
                    Name    = "MyProperty3",
                    CliName = "my-property2",
                },
            });

            CliDescriptor = new CliDescriptor
            {
                GeneratedComandSourceNamespace  = "StarFruit2.Tests.TestSampleData.SeveralOptionsAndArguments",
                GeneratedCommandSourceClassName = "SeveralOptionsAndArgumentsCommandSource",
                CommandDescriptor = commandDescriptor,
            };

            CommandDefinitionSourceCode = sourceCode;

            // TODO: figure out appropriate test action for use in dotnet interactive
            //       it might be an action passed into constructor
        }
コード例 #15
0
        public void SetsBooleanFlagUsingLongName()
        {
            List <string>     args       = new List <string>(new[] { "--flag" });
            SimpleCommand     command    = new SimpleCommand();
            CommandDescriptor descriptor = descriptorBuilder.BuildDescriptor(typeof(SimpleCommand));

            parser.Apply(args, command, descriptor);

            Assert.That(args, Is.Empty);
            Assert.That(command.BoolFlag);
        }
コード例 #16
0
        public void SetDefaultCommand_UpdatesRegisteredCommandsDescriptor()
        {
            CommandRegistry commandRegistry = new CommandRegistry();

            commandRegistry.Register(typeof(TestCommand));
            commandRegistry.SetDefaultCommand(typeof(TestCommand));

            CommandDescriptor descriptor = commandRegistry.GetDescriptor("", null);

            Assert.That(descriptor.Name, Is.EqualTo("test"));
        }
コード例 #17
0
        protected virtual IEnumerable <CommandDescriptor> GetSubCommands(CommandDescriptor parent,
                                                                         INamedTypeSymbol parentSymbol)
        {
            IEnumerable <ISymbol> members = config.GetSubCommandMembers(parentSymbol);

            return(members.Select(s => s switch
            {
                IMethodSymbol x => CreateCommandDescriptor(parent, x),
                INamedTypeSymbol x => CreateCommandDescriptor(parent, x),
                _ => throw new NotImplementedException($"Not implemented for member in {nameof(RoslynDescriptionMaker)}.{nameof(GetSubCommands)}")
            }));
コード例 #18
0
        public static CommandMemberDescriptor[] GetMemberDescriptors(this MethodInfo methodInfo)
        {
            var memberList = new List <CommandMemberDescriptor>();

            foreach (var item in methodInfo.GetParameters())
            {
                if (item.ParameterType == typeof(CancellationToken))
                {
                    continue;
                }
                if (item.GetCustomAttribute <ParamArrayAttribute>() != null)
                {
                    memberList.Add(new CommandParameterArrayDescriptor(item));
                }
                else
                {
                    memberList.Add(new CommandParameterDescriptor(item));
                }
            }

            var methodAttr = methodInfo.GetCustomAttribute <CommandMethodPropertyAttribute>();

            if (methodAttr != null)
            {
                foreach (var item in methodAttr.PropertyNames)
                {
                    var memberDescriptor = CommandDescriptor.GetMemberDescriptors(methodInfo.DeclaringType)[item];
                    if (memberDescriptor == null)
                    {
                        throw new ArgumentException(string.Format(Resources.Exception_AttributeDoesNotExists_Format, item));
                    }
                    memberList.Add(memberDescriptor);
                }
            }

            var staticAttrs = methodInfo.GetCustomAttributes(typeof(CommandMethodStaticPropertyAttribute), true);

            foreach (var item in staticAttrs)
            {
                if (item is CommandMethodStaticPropertyAttribute attr)
                {
                    var memberDescriptors = CommandDescriptor.GetMemberDescriptors(attr.StaticType);
                    memberList.AddRange(memberDescriptors);
                }
            }

            var query = from item in memberList
                        orderby item.DefaultValue != DBNull.Value
                        orderby item.Usage
                        select item;

            return(query.ToArray());
        }
コード例 #19
0
        public void SetsMultiplePositionalArguments()
        {
            List <string>     args       = new List <string>(new[] { "http://example.org", @"C:\temp" });
            SimpleCommand     command    = new SimpleCommand();
            CommandDescriptor descriptor = descriptorBuilder.BuildDescriptor(typeof(SimpleCommand));

            parser.Apply(args, command, descriptor);

            Assert.That(args, Is.Empty);
            Assert.That(command.Remote, Is.EqualTo("http://example.org"));
            Assert.That(command.Local, Is.EqualTo(@"C:\temp"));
        }
コード例 #20
0
        public void GetDescriptor_ReturnsRegisteredSubCommand()
        {
            CommandRegistry commandRegistry = new CommandRegistry();

            commandRegistry.Register(typeof(RemoteCommand));

            CommandDescriptor remoteDescriptor = commandRegistry.GetDescriptor("remote", null);
            CommandDescriptor addDescriptor    = commandRegistry.GetDescriptor("add", remoteDescriptor);

            Assert.That(remoteDescriptor.Name, Is.EqualTo("remote"));
            Assert.That(addDescriptor.Name, Is.EqualTo("add"));
        }
コード例 #21
0
        private void Execute(List <string> args)
        {
            string commandName = string.Empty;

            if (args.Count >= 1 && Regex.IsMatch(args[0], "^[a-z]+$"))
            {
                commandName = args[0];
                args.RemoveAt(0); // Remove the argument we just used
            }

            // Attempt to find the command for the name
            CommandDescriptor commandDescriptor = commandRegistry.GetDescriptor(commandName, null);

            if (commandDescriptor == null)
            {
                throw new Exception(string.Format("Command '{0}' is not recognized.", commandName));
            }

            // Determine if this is a call for a sub command
            while (args.Count >= 1 && Regex.IsMatch(args[0], "^[a-z]+$"))
            {
                commandName = args[0];
                var subCommandDescriptor = commandRegistry.GetDescriptor(commandName, commandDescriptor);
                if (subCommandDescriptor == null)
                {
                    break;
                }

                commandDescriptor = subCommandDescriptor;
                args.RemoveAt(0); // Remove the argument we just used
            }

            // Create an instance of the required command
            ICommand command = commandFactory.Create(commandDescriptor.CommandType);

            // Parse the arguments and apply them to the command
            if (args.Count > 0)
            {
                foreach (IArgumentParser argumentParser in argumentParsers)
                {
                    argumentParser.Apply(args, command, commandDescriptor);
                }

                // Ensure that all the arguments have been parsed
                if (args.Count > 0)
                {
                    throw new Exception(string.Format("Unsupported argument '{0}'.", args[0]));
                }
            }

            // Execute the code of the command
            command.Execute();
        }
コード例 #22
0
        /// <summary>
        /// Displays a directory listing.
        /// </summary>
        private int CommandDirectory(CommandDescriptor descriptor, string[] args, CommandExecutor executor)
        {
            try
            {
                var path = args.Count() >= 2 ? args.ElementAt(1) : executor.GetCurrentWorkingDirectory();
                IEnumerable <string> directories = Directory.EnumerateDirectories(path); //FLAG
                IEnumerable <string> files       = Directory.EnumerateFiles(path);
                var targetDir = Path.GetFullPath(path);

                // Display the directory banner.
                executor.WriteOutputText("Directory of ");
                executor.WriteCommandLink($"{targetDir}\n", $"cd \"{targetDir}\"");

                // Display an output line for each directory in the listing.
                foreach (var directory in directories)
                {
                    var fullPath = Path.GetFullPath(directory);
                    var filespec = Path.GetFileName(fullPath);
                    var dirInfo  = new DirectoryInfo(directory);
                    if (dirInfo.Exists)
                    {
                        var lastUpdated = dirInfo.LastWriteTime;
                        executor.WriteOutputText($"{lastUpdated.ToString("MM/dd/yyyy")}  {lastUpdated.ToString("hh:mm tt")}    ");
                        executor.WriteCommandLink($"<DIR>", $"dir \"{fullPath}\"");
                        executor.WriteOutputText("          ");
                        executor.WriteCommandLink($"{filespec}\n", $"cd \"{fullPath}\"");
                    }
                }

                // Display an output line for each file in the listing.
                foreach (var file in files)
                {
                    var fullPath = Path.GetFullPath(file);
                    var filespec = Path.GetFileName(fullPath);
                    var fileInfo = new FileInfo(file);
                    if (fileInfo.Exists)
                    {
                        var lastUpdated = fileInfo.LastWriteTime;
                        var length      = fileInfo.Length;
                        executor.WriteOutputText($"{lastUpdated.ToString("MM/dd/yyyy")}  {lastUpdated.ToString("hh:mm tt")}    {length.ToString("##,###,###,###").PadLeft(14)} ");
                        executor.WriteCommandLink($"{filespec}\n", $"exec \"{fullPath}\"");
                    }
                }
            }
            catch (Exception ex)
            {
                executor.WriteInfoText($"Command failed: {ex.Message}\n");
                return(-1);
            }

            return(0);
        }
コード例 #23
0
        public void GetCommandReturnsCommand()
        {
            Type commandType = typeof(TestCommand);
            var  descriptor  = new CommandDescriptor(commandType, new Dictionary <string, object>());
            var  command     = new TestCommand();
            var  context     = new CommandContext <TestCommand, TestResult>(descriptor, command);

            context.Command.Should()
            .BeSameAs(command);

            ((ICommandContext)context).Command.Should()
            .BeSameAs(command);
        }
コード例 #24
0
        private void ParseCommands([NotNull] XElement commandsElement)
        {
            Debug.ArgumentNotNull(commandsElement, nameof(commandsElement));

            _commands.Clear();

            foreach (var element in commandsElement.Elements().OrderBy(e => e.Name.ToString()))
            {
                var command = new CommandDescriptor(element, element.GetAttributeValue("name"), element.GetAttributeValue("type"));

                _commands.Add(command);
            }
        }
コード例 #25
0
        public SeveralSubCommandsTestData()

            : base("SeveralSubCommands")
        {
            string sourceCode = $@"NOT YET IMPLEMENTED: Read corresponding file";

            var commandDescriptor = new CommandDescriptor(null, "MyClass", RawInfo.DummyClass)
            {
                Name = "my-class"
            };

            commandDescriptor.AddCommands(subCommands: new List <CommandDescriptor>()
            {
                new CommandDescriptor(null, "MyMethod2", RawInfo.DummyClass)
                {
                    Name    = "MyMethod2",
                    CliName = "my-mymethod2",
                },
                new CommandDescriptor(null, "MyMethod1", RawInfo.DummyClass)
                {
                    Name    = "MyMethod1",
                    CliName = "my-mymethod1",
                },
                new CommandDescriptor(null, "MyMethod3", RawInfo.DummyClass)
                {
                    Name    = "MyMethod3",
                    CliName = "my-mymethod3",
                },
            });

            commandDescriptor.SubCommands.First().AddArguments(arguments: new List <ArgumentDescriptor>()
            {
                new ArgumentDescriptor(new ArgTypeInfoRoslyn(typeof(int)), null, "myParam", RawInfo.DummyMethod)
                {
                    Name    = "myParam",
                    CliName = "my-param",
                },
            });

            CliDescriptor = new CliDescriptor
            {
                GeneratedComandSourceNamespace  = "StarFruit2.Tests.TestSampleData.SeveralSubCommands",
                GeneratedCommandSourceClassName = "SeveralSubCommandsCommandSource",
                CommandDescriptor = commandDescriptor,
            };

            CommandDefinitionSourceCode = sourceCode;

            // TODO: figure out appropriate test action for use in dotnet interactive
            //       it might be an action passed into constructor
        }
コード例 #26
0
        public BrowserCommandSet()
        {
            _backCommand = new CommandDescriptor()
            {
                CreateCommandInstance = () => new KeyPressCommand() { Key = System.Windows.Forms.Keys.BrowserBack, AllowUserProperties = false },
                ActionText = "Browse Back"
            };

            _forwardCommand = new CommandDescriptor()
            {
                CreateCommandInstance = () => new KeyPressCommand() { Key = System.Windows.Forms.Keys.BrowserForward, AllowUserProperties = false },
                ActionText = "Browse Forward"
            };

            _homeCommand = new CommandDescriptor()
            {
                CreateCommandInstance = () => new KeyPressCommand() { Key = System.Windows.Forms.Keys.BrowserHome, AllowUserProperties = false },
                ActionText = "Home Page"
            };

            _refreshCommand = new CommandDescriptor()
            {
                CreateCommandInstance = () => new KeyPressCommand() { Key = System.Windows.Forms.Keys.BrowserRefresh, AllowUserProperties = false },
                ActionText = "Refresh"
            };

            _favoritesCommand = new CommandDescriptor()
            {
                CreateCommandInstance = () => new KeyPressCommand() { Key = System.Windows.Forms.Keys.BrowserFavorites, AllowUserProperties = false },
                ActionText = "Favorites"
            };

            _searchCommand = new CommandDescriptor()
            {
                CreateCommandInstance = () => new KeyPressCommand() { Key = System.Windows.Forms.Keys.BrowserSearch, AllowUserProperties = false },
                ActionText = "Search"
            };

            _switchTabCommand = new CommandDescriptor()
            {
                CreateCommandInstance = () => new SwitchCommand()
                {
                    SwitchKey = System.Windows.Forms.Keys.Tab,
                    ModifierKey = System.Windows.Forms.Keys.ControlKey,
                    ReverseModifierKey = System.Windows.Forms.Keys.ShiftKey,
                    AllowUserProperties = false
                },

                ActionText = "Switch Tabs"
            };
        }
コード例 #27
0
        private void WriteCommandDefinition(TextWriter writer, string commandName, CommandDescriptor command)
        {
            var subCommands = command.SubCommands?.All.Where(x => !x.IsHidden && !x.IsPrimaryCommand).ToArray() ?? Array.Empty <CommandDescriptor>();

            writer.WriteLine($"__cocona_{_appName}_commands_{commandName}() {{");
            WriteZshArguments(writer, commandName, command, subCommands);
            writer.WriteLine("}");
            writer.WriteLine();

            foreach (var subCommand in subCommands)
            {
                WriteCommandDefinition(writer, $"{commandName}_{subCommand.Name}", subCommand);
            }
        }
コード例 #28
0
        private void Execute([NotNull] CommandDescriptor command)
        {
            Debug.ArgumentNotNull(command, nameof(command));

            var startPage = this.GetAncestor<StartPageViewer>();
            if (startPage == null)
            {
                return;
            }

            var context = new StartPageContext(startPage);

            command.Command.Execute(context);
        }
コード例 #29
0
        public void CtorThrowsIfCommandDoesNotMatchDescriptorType()
        {
            Type commandType = typeof(TestCommand);
            var  descriptor  = new CommandDescriptor(commandType, new Dictionary <string, object>());

            Action action = () =>
            {
                // ReSharper disable once ObjectCreationAsStatement
                new CommandContext <CancelableTestCommand, TestResult>(descriptor, new CancelableTestCommand());
            };

            action.Should()
            .Throw <ArgumentException>();
        }
コード例 #30
0
        public static bool Register(CommandDescriptor ThisCmdDescriptor)
        {
            //This is called WHEN initialised, NOT automatically! hooray for static class huh? :/
            //if (_Name == null | _Version == 0 | _Date == null | _Author == null | _Descrption == null | _Usage == null | _Commands == null | _Handler == null)
            //{
            //    return false;
            //}
            foreach (var ThisFieldVar in ThisCmdDescriptor.GetType().GetFields(System.Reflection.BindingFlags.Public).ToArray())
            {
                if (ThisFieldVar.GetValue(ThisCmdDescriptor) == null)
                {
                    Console.WriteLine("&cERROR: &eFailure to register command: \"" + ThisCmdDescriptor._Name + "\". The Field " + ThisFieldVar.Name + " is left Null.");
                    return(false);
                }
            }
            if (ThisCmdDescriptor._Disabled)
            {
                return(false);
            }
            foreach (string ThisString in ThisCmdDescriptor._Commands.ToArray())
            {
                if (ThisString.StartsWith("//") | ThisString.StartsWith("@") | ThisString.StartsWith("@@") | ThisString.EndsWith("."))
                {
                    Console.WriteLine("&cERROR: &eFailure to register command: \"" + ThisCmdDescriptor._Name + "\". There is an alias that uses illegal characters, that would conflict with the way OpenYS handles user chat (for example, stating with \"@\").");
                    return(false);
                }
                if (!ThisString.StartsWith("/"))
                {
                    Console.WriteLine("&cERROR: &eFailure to register command: \"" + ThisCmdDescriptor._Name + "\". There is an alias that does not start with the Command designator character: \"/\".");
                    return(false);
                }
            }

            if (Commands.List.Select(x => x._Name).Contains(ThisCmdDescriptor._Name))
            {
                foreach (double ThisDouble in Commands.List.Where(x => x._Name == ThisCmdDescriptor._Name).Select(y => y._Version).ToArray())
                {
                    if (ThisDouble > ThisCmdDescriptor._Version)
                    {
                        Console.WriteLine("&cERROR: &eFailure to register command: \"" + ThisCmdDescriptor._Name + "\". There is already a command by this name and it is of a newer version.");
                        return(false);
                    }
                }
                //Console.WriteLine("&aSucessfully updated registered command: \"" + ThisCmdDescriptor._Name + "\".");
            }
            //Console.WriteLine("&eSucessfully registered command: \"" + ThisCmdDescriptor._Name + "\".");
            Commands.List.RemoveAll(x => x._Name == ThisCmdDescriptor._Name);
            Commands.List.Add(ThisCmdDescriptor);
            return(true);
        }
コード例 #31
0
        /// <summary>
        /// Changes the working directory (may wish to tweak if multiple windows are controlled by the same processor)
        /// </summary>
        private int CommandCD(CommandDescriptor descriptor, string[] args, CommandExecutor executor)
        {
            try
            {
                Directory.SetCurrentDirectory(args[1]);
            }
            catch (Exception ex)
            {
                executor.WriteInfoText($"Command failed: {ex.Message}\n");
                //alternate exit status to be determined later
            }

            return(0);
        }
コード例 #32
0
        //https://stackoverflow.com/questions/33761/how-can-i-retrieve-a-list-of-parameters-from-a-stored-procedure-in-sql-server
        //https://stackoverflow.com/questions/3038364/get-stored-procedure-parameters-by-either-c-sharp-or-sql
        //SELECT * FROM sys.dm_exec_describe_first_result_set ('owner.sprocName', NULL, 0) ;
        //Select * from sys.objects where type = 'p' and name = (procedure name)
        //cmd.Execute(CommandBehaviour.SchemaOnly)
        public static CommandDescriptor GetParameters(string sqlCommand, string sqlConnection)
        {
            CommandDescriptor description = new CommandDescriptor()
            {
                parameters = null, tableValues = null
            };

            using (SqlConnection conn = new SqlConnection(sqlConnection))
                using (SqlCommand cmd = new SqlCommand(sqlCommand, conn)
                {
                    CommandType = CommandType.StoredProcedure
                })
                {
                    DataTable schemaTable = null;
                    try
                    {
                        conn.Open();
                        SqlCommandBuilder.DeriveParameters(cmd);

                        if (cmd.Parameters != null && cmd.Parameters.Count > 0)
                        {
                            description.parameters = new List <SqlParameter>();
                            foreach (SqlParameter parameter in cmd.Parameters)
                            {
                                description.parameters.Add(parameter);
                            }
                        }

                        using (SqlDataReader schemaReader = cmd.ExecuteReader(CommandBehavior.SchemaOnly))
                        {
                            schemaTable = schemaReader.GetSchemaTable();
                        }
                    }
                    finally
                    {
                        conn.Close();
                    }


                    if (schemaTable != null)
                    {
                        description.returnSchema = SchemaMap.Map(schemaTable);
                    }
                }

            return(description);
        }
コード例 #33
0
ファイル: Client.cs プロジェクト: MatanRad/Matbot
        public CommandDescriptor[] GetCommandDescriptors()
        {
            CommandDescriptor[] clientCommands = this.CustomCmdManger.GetCommandDescriptors();
            CommandDescriptor[] botCommands    = this.Bot.SharedManager.GetCommandDescriptors();

            if (clientCommands == null)
            {
                return(botCommands);
            }

            CommandDescriptor[] finArray = new CommandDescriptor[clientCommands.Length + botCommands.Length];

            Array.Copy(clientCommands, finArray, clientCommands.Length);
            Array.Copy(botCommands, 0, finArray, clientCommands.Length, botCommands.Length);

            return(finArray);
        }
コード例 #34
0
        protected virtual Class CommandSourceClass(CommandDescriptor cmd,
                                                   TypeRep baseClass,
                                                   CommandDescriptor?parent)
        {
            //  .Optional(parent is null, (cls) => cls.Member(parent is null, ParameterlessCtor(cmd))

            return(new Class(cmd.CommandSourceClassName())
                   .Base(baseClass)
                   .OptionalMember(parent is null, ParameterlessCtor(cmd))
                   .Constructor(GetCtor(cmd, cmd.Root, parent))
                   .BlankLine()
                   .Properties(cmd.GetChildren().Select(s => ChildProperty(s)))
                   .Properties(cmd.GetChildren(),
                               s => ChildProperty(s))
                   .BlankLine()
                   .Methods(cmd.GetOptionsAndArgs(),
                            s => ChildGetMethod(s)));
コード例 #35
0
        private void DoExecute()
        {
            CommandDescriptor commandDescriptor =
                PublicCommandsHelper.GetCommandDescriptor(ControllerCommandType);

            commandDescriptor.ClearParameterValues();
            OperationParametersControlCreator.ReadParameterValues(commandDescriptor, controls);
            foreach (ParameterDescriptor parameterDescriptor in commandDescriptor.Parameters)
            {
                if (parameterDescriptor.ParameterPropertyInfo == commandDescriptor.ScopeProperty)
                {
                    parameterDescriptor.ParameterValue = ((ExolutioObject)this.ScopeObject).ID;
                }
            }
            CreateControllerCommand();
            CommandSerializer.FillParameters(ControllerCommand, commandDescriptor);
            ControllerCommand.CanExecuteChanged -= OnControllerCommandCanExecuteChanged;
            if (!ControllerCommand.CanExecute())
            {
#if SILVERLIGHT
                ExolutioErrorMsgBox.Show("Command can not be executed", ControllerCommand.ErrorDescription);
#else
                ExolutioErrorMsgBox.Show("Command can not be executed", ControllerCommand.ErrorDescription);
#endif
            }
            else
            {
                if (ControllerCommand is StackedCommand)
                {
                    if (((StackedCommand)ControllerCommand).Controller == null)
                    {
                        ((StackedCommand)ControllerCommand).Controller = Current.Controller;
                    }
                }
                try
                {
                    ControllerCommand.Execute();
                }
                catch (ExolutioCommandException e)
                {
                    ExolutioErrorMsgBox.Show("Command " + e.Command.GetType().ToString() + " can not be executed", e.Command.ErrorDescription);
                }
            }
            ControllerCommand = null;
        }
コード例 #36
0
        private IEnumerable<CommandDescriptor> RetrieveCommandDescriptors(IEnumerable<Type> runnableTypes)
        {
            var runnables = runnableTypes.Where(runnableType => typeof (IRunnable).IsAssignableFrom(runnableType));

            foreach (var type in runnables)
            {
                var attributes = type.GetCustomAttributes<CommandDescriptorAttribute>(true).ToArray();

                if (!attributes.Any()) continue;
                if (attributes.Length > 1)
                    throw new Exception($"Only one {nameof(CommandDescriptorAttribute)} is allowed to be defined in {type.FullName} runnable.");

                var attribute = attributes.Single();
                var commandArguments = RetrieveCommandArguments(type);
                var descriptor = new CommandDescriptor(type.Name, attribute.Description ?? String.Empty, commandArguments, Array(attribute.CommandName));
                yield return descriptor;
            }
        }
コード例 #37
0
ファイル: ShowService.cs プロジェクト: AlexSneg/VIRD-1.0
        //void _controller_OnCheck(object sender, DeviceCheckResultEventArgs e)
        //{
        //    string result = e.Result;
        //}

        #region IShowCommon Members

        public string DoEquipmentCommand(CommandDescriptor cmd)
        {
            //_callback = OperationContext.Current.GetCallbackChannel<IShowNotifier>();

            if (cmd.EquipmentId < 0) return null;
            try
            {
                return _controller.Send(cmd);
            }
            catch (Exception ex)
            {
                _config.EventLog.WriteError(string.Format("ShowService.DoEquipmentCommand: \n{0}", ex));
                return null;
            }
        }
コード例 #38
0
ファイル: ShowService.cs プロジェクト: AlexSneg/VIRD-1.0
 protected List<CommandDescriptor> PreprocessingCommandList(List<CommandDescriptor> list)
 {
     List<LogicSetTieParameter> paramList = new List<LogicSetTieParameter>();
     List<CommandDescriptor> result = new List<CommandDescriptor>();
     foreach (CommandDescriptor commandDescriptor in list)
     {
         if (commandDescriptor.EquipmentId == 0  && 
             commandDescriptor.CommandName == "LogicSetTie" && 
             commandDescriptor.Parameters.Count == 3)
         {
             paramList.Add(new LogicSetTieParameter(
                 (int)commandDescriptor.Parameters[0],
                 (int)commandDescriptor.Parameters[1],
                 (int)commandDescriptor.Parameters[2]));
         }
         else result.Add(commandDescriptor);
     }
     if (paramList.Count > 0)
     {
         CommandDescriptor cmd = new CommandDescriptor(0, "LogicSetTies", paramList.Count);
         foreach (LogicSetTieParameter parameter in paramList)
         {
             cmd.Parameters.Add(parameter.Input);
             cmd.Parameters.Add(parameter.Output);
             cmd.Parameters.Add(parameter.State);
         }
         result.Add(cmd);
     }
     return result;
 }
コード例 #39
0
ファイル: ShowService.cs プロジェクト: AlexSneg/VIRD-1.0
        private void GeneralFullSceneListAndGeneralMarkedSceneListCommand(PresentationInfo info)
        {
            try
            {
                //GeneralFullSceneList
                string result;
                List<IConvertible> paramList = new List<IConvertible>(info.SlideCount << 1);
                paramList.Add(info.SlideCount);
                foreach (SlideInfo slideInfo in info.SlideInfoList)
                {
                    paramList.Add(slideInfo.Id);
                    paramList.Add(slideInfo.Name);
                    paramList.Add(String.IsNullOrEmpty(slideInfo.Comment) ? "" : slideInfo.Comment);
                }
                CommandDescriptor cmd = new CommandDescriptor(0, "GeneralFullSceneList", paramList.ToArray());
                result = _controller.Send(cmd);

                //GeneralMarkedSceneList
                paramList.Clear();
                int count = 0;
                foreach (SlideInfo slideInfo in info.SlideInfoList)
                {
                    if (slideInfo.LabelId == 0) continue;
                    // Копия чтобы решарпер не ругался
                    SlideInfo item = slideInfo;
                    Label label = _config.ModuleConfiguration.LabelList.FirstOrDefault(l => l.Id == item.LabelId);
                    if (label != null)
                    {
                        paramList.Add(label.Name);
                        paramList.Add(slideInfo.Name);
                        count++;
                    }
                }
                paramList.Insert(0, count);
                cmd = new CommandDescriptor(0, "GeneralMarkedSceneList", paramList.ToArray());
                result = _controller.Send(cmd);
            }
            catch (Exception ex)
            {
                _config.EventLog.WriteError(string.Format("ShowService.GeneralFullSceneListAndGeneralMarkedSceneListCommand:\n {0}", ex));
            }
        }
コード例 #40
0
ファイル: CommandManager.cs プロジェクト: venofox/AtomicCraft
 internal CommandRegisteredEventArgs( CommandDescriptor commandDescriptor )
 {
     CommandDescriptor = commandDescriptor;
 }
コード例 #41
0
ファイル: CommandManager.cs プロジェクト: fragmer/fCraft
 internal CommandRegisteringEventArgs( CommandDescriptor descriptor )
     : base( descriptor ) {
 }
コード例 #42
0
 protected void SendReply(CommandDescriptor cmd, string message)
 {
     iEngine.SendMessage(cmd.fromUser, message);
 }
コード例 #43
0
 public abstract void ProcessCommand(CommandDescriptor cmd);
コード例 #44
0
 /// <summary>
 /// Registers the specified descriptor.
 /// </summary>
 public void Register(CommandDescriptor descriptor)
 {
     commandDescriptors.Add(descriptor);
 }
コード例 #45
0
 public string Send(CommandDescriptor cmd)
 {
     throw new NotImplementedException();
 }
コード例 #46
0
ファイル: CommandManager.cs プロジェクト: fragmer/fCraft
 internal CommandCalledEventArgs( CommandReader command, CommandDescriptor descriptor, Player player ) {
     Command = command;
     Descriptor = descriptor;
     Player = player;
 }
コード例 #47
0
ファイル: CommandManager.cs プロジェクト: fragmer/fCraft
 internal CommandRegisteredEventArgs( CommandDescriptor descriptor ) {
     Descriptor = descriptor;
 }
コード例 #48
0
        private void loadFromFile(String fileName)
        {
            try
            {
                var reader = File.OpenRead(fileName);
                var descriptor = (DescriptorModel) serializer.ReadObject(reader);

                selectors.Clear();
                combinators.Clear();
                modifiers.Clear();
                commandDescriptors.Clear();

                foreach (var commandDescriptor in descriptor.CommandDescriptors)
                {
                    var arguments = commandDescriptor.Arguments.Select(argument => new ArgumentDescriptor
                    {
                        ArgumentName = argument.Name,
                        DefaultValue = argument.DefaultValue,
                        IsOptional = argument.IsOptional,
                        Position = argument.Position,
                        ArgumentType = findInAssemblies(argument.ArgumentType)
                    });

                    var desc = new CommandDescriptor(
                        commandDescriptor.Name,
                        commandDescriptor.Description,
                        arguments,
                        commandDescriptor.CommandNames
                    );

                    commandDescriptors.Add(desc);
                }

                foreach (var selectionDescriptors in descriptor.SelectionDescriptors)
                {
                    switch (selectionDescriptors.SelectorType)
                    {
                        case ELEMENT_TYPE_SELECTOR:
                        {
                            var type = findInAssemblies(selectionDescriptors.Type, DescriptorType.Selector);
                            selectors.Add(new SelectorDescriptor(selectionDescriptors.Name, selectionDescriptors.Value, type));
                            break;
                        }
                        case COMBINATOR_SELECTOR:
                        {
                            var type = findInAssemblies(selectionDescriptors.Type, DescriptorType.Combinator);
                            combinators.Add(new CombinatorDescriptor(selectionDescriptors.Name, selectionDescriptors.Value, type));
                            break;
                        }
                        case MODIFIER_SELECTOR:
                        {
                            var type = findInAssemblies(selectionDescriptors.Type, DescriptorType.ModifierSelector);

                            modifiers.Add(
                                new ModifierDescriptor(selectionDescriptors.Name,
                                                       selectionDescriptors.Value,
                                                       selectionDescriptors.Arguments, 
                                                       type,
                                                       selectionDescriptors.IsClassSelector));
                            break;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                throw new Exception(String.Format("Cannot parse descriptor file: {0}", fileName), exception);
            }
        }
コード例 #49
0
ファイル: CommandManager.cs プロジェクト: venofox/AtomicCraft
 internal CommandCalledEventArgs( Command command, CommandDescriptor commandDescriptor, Player player )
 {
     Command = command;
     CommandDescriptor = commandDescriptor;
     Player = player;
 }
コード例 #50
0
 public CustomCommandDescriptors(FixedDocumentViewerBase fixedDocumentViewerBase)
     : base(fixedDocumentViewerBase)
 {
     this.fitToWidthCommandDescriptor = new CommandDescriptor(new FitToWidthCommand(fixedDocumentViewerBase));
 }
コード例 #51
0
ファイル: CommandManager.cs プロジェクト: venofox/AtomicCraft
 internal CommandCallingEventArgs( Command command, CommandDescriptor commandDescriptor, Player player )
     : base(command, commandDescriptor, player)
 {
 }
コード例 #52
0
        public GenericCommandSet()
        {
            _keyPressCommand = new CommandDescriptor()
            {
                Name = "Key Press",
                CreateCommandInstance = () => new KeyPressCommand()
            };

            _keyMapCommand = new CommandDescriptor()
            {
                Name = "Key Map",
                CreateCommandInstance = () => new KeyMapCommand()
            };

            _mouseClickCommand = new CommandDescriptor()
            {
                Name = "Mouse Click",
                CreateCommandInstance = () => new MouseClickCommand()
            };

            _mouseMoveCommand = new CommandDescriptor()
            {
                Name = "Mouse Move",
                CreateCommandInstance = () => new MouseMoveCommand()
            };

            _upCommand = new CommandDescriptor()
            {
                Name = "Up",
                CreateCommandInstance = () => new KeyMapCommand() { Key = System.Windows.Forms.Keys.Up }
            };

            _downCommand = new CommandDescriptor()
            {
                Name = "Down",
                CreateCommandInstance = () => new KeyMapCommand() { Key = System.Windows.Forms.Keys.Down }
            };

            _leftCommand = new CommandDescriptor()
            {
                Name = "Left",
                CreateCommandInstance = () => new KeyMapCommand() { Key = System.Windows.Forms.Keys.Left }
            };

            _rightCommand = new CommandDescriptor()
            {
                Name = "Right",
                CreateCommandInstance = () => new KeyMapCommand() { Key = System.Windows.Forms.Keys.Right }
            };

            _selectCommand = new CommandDescriptor()
            {
                Name = "Select",
                CreateCommandInstance = () => new KeyPressCommand() { Key = System.Windows.Forms.Keys.Enter }
            };

            _backCommand = new CommandDescriptor()
            {
                Name = "Back",
                CreateCommandInstance = () => new KeyPressCommand() { Key = System.Windows.Forms.Keys.Back }
            };

            _nextTrackCommand = new CommandDescriptor()
            {
                Name = "Next Track",
                CreateCommandInstance = () => new KeyPressCommand() { Key = System.Windows.Forms.Keys.MediaNextTrack }
            };

            _previousTrackCommand = new CommandDescriptor()
            {
                Name = "Previous Track",
                CreateCommandInstance = () => new KeyPressCommand() { Key = System.Windows.Forms.Keys.MediaPreviousTrack }
            };

            _playPauseCommand = new CommandDescriptor()
            {
                Name = "Play/Pause",
                CreateCommandInstance = () => new KeyPressCommand() { Key = System.Windows.Forms.Keys.MediaPlayPause }
            };

            _volumeDownCommand = new CommandDescriptor()
            {
                Name = "Volume Down",
                CreateCommandInstance = () => new KeyMapCommand() { Key = System.Windows.Forms.Keys.VolumeDown }
            };

            _volumeUpCommand = new CommandDescriptor()
            {
                Name = "Volume Up",
                CreateCommandInstance = () => new KeyMapCommand() { Key = System.Windows.Forms.Keys.VolumeUp }
            };

            _volumeMuteCommand = new CommandDescriptor()
            {
                Name = "Mute",
                CreateCommandInstance = () => new KeyPressCommand() { Key = System.Windows.Forms.Keys.VolumeMute }
            };
        }
コード例 #53
0
ファイル: CommandManager.cs プロジェクト: venofox/AtomicCraft
 internal CommandRegistringEventArgs( CommandDescriptor commandDescriptor )
     : base(commandDescriptor)
 {
 }
コード例 #54
0
ファイル: ShowClient.cs プロジェクト: AlexSneg/VIRD-1.0
 public string DoEquipmentCommand(CommandDescriptor cmd)
 {
     try
     {
         if (!_created) return null;
         return _svc.Channel.DoEquipmentCommand(cmd);
     }
     catch (Exception ex)
     {
         _configuration.EventLog.WriteError(string.Format("ShowClient.DoEquipmentCommand: \n{0}", ex));
         return null;
     }
 }