/// <summary>
 /// Processes a command throwing a <see cref="LimeException"/> in case of <see cref="CommandStatus.Failure"/> status and returns the response resource.
 /// </summary>
 public static Task <TResponseResource> ProcessCommandWithResponseResourceAsync <TRequestResource, TResponseResource>(
     this ICommandProcessor channel,
     CommandMethod method,
     LimeUri uri,
     TRequestResource resource,
     CancellationToken cancellationToken,
     Node from = null,
     Node to   = null,
     Node pp   = null,
     IDictionary <string, string> metadata = null)
     where TRequestResource : Document
     where TResponseResource : Document
 {
     return(ProcessCommandWithResponseResourceAsync <TResponseResource>(
                channel,
                new Command()
     {
         From = from,
         To = to,
         Pp = pp,
         Method = method,
         Uri = uri,
         Resource = resource,
         Metadata = metadata
     },
                cancellationToken));
 }
        public static bool Command(CommandMethod method,
                                   string docKeyForTrack,
                                   object fileId      = null,
                                   string callbackUrl = null,
                                   string[] users     = null,
                                   MetaData meta      = null)
        {
            Global.Logger.DebugFormat("DocService command {0} fileId '{1}' docKey '{2}' callbackUrl '{3}' users '{4}' meta '{5}'", method, fileId, docKeyForTrack, callbackUrl, users != null ? string.Join(", ", users) : null, JsonConvert.SerializeObject(meta));
            try
            {
                var commandResponse = CommandRequest(
                    FilesLinkUtility.DocServiceCommandUrl,
                    method,
                    GenerateRevisionId(docKeyForTrack),
                    callbackUrl,
                    users,
                    meta,
                    FileUtility.SignatureSecret);

                if (commandResponse.Error == CommandResponse.ErrorTypes.NoError)
                {
                    return(true);
                }

                Global.Logger.ErrorFormat("DocService command response: '{0}' {1}", commandResponse.Error, commandResponse.ErrorString);
            }
            catch (Exception e)
            {
                Global.Logger.Error("DocService command error", e);
            }
            return(false);
        }
        /// <summary>
        /// Processes a command throwing a <see cref="LimeException"/> in case of <see cref="CommandStatus.Failure"/> status.
        /// </summary>
        public static Task <Command> ProcessCommandOrThrowAsync <TRequestResource>(
            this ICommandProcessor channel,
            CommandMethod method,
            LimeUri uri,
            TRequestResource resource,
            CancellationToken cancellationToken,
            Node from = null,
            Node to   = null,
            Node pp   = null,
            IDictionary <string, string> metadata = null)
            where TRequestResource : Document
        {
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }
            if (resource == null)
            {
                throw new ArgumentNullException(nameof(resource));
            }

            return(ProcessCommandOrThrowAsync(
                       channel,
                       new Command()
            {
                From = from,
                To = to,
                Pp = pp,
                Method = method,
                Uri = uri,
                Resource = resource,
                Metadata = metadata
            },
                       cancellationToken));
        }
Example #4
0
        private void Execute(CommandMethod cmdMethod)
        {
            this.TryLaunchServer();
            var client = this.CreateClient();

            client.PlayBack(this.CreateMessage(cmdMethod));
        }
Example #5
0
        public void SelectCommand_RootRouteWithParameter_ReturnsMethod()
        {
            var commandMethod = new CommandMethod
            {
                Parameters = new List <ParameterInfo> {
                    new ParameterInfo
                    {
                        HasDefaultValue = false,
                        Name            = "param1",
                        Type            = typeof(string)
                    }
                }
            };

            var commandTable = new Mock <ICommandTable>();

            commandTable.Setup(c => c.TryGetValue("", out commandMethod)).Returns(true);

            var commandSelector = new DefaultCommandSelector();

            var selectedMethod = commandSelector.SelectCommand("bacon", commandTable.Object, out object[] extra);

            Assert.NotNull(selectedMethod);
            Assert.Equal(selectedMethod.Id, commandMethod.Id);
            Assert.Single(extra);
            Assert.Equal("bacon", extra[0]);
        }
Example #6
0
        private void ProcessScriptClass(Type type)
        {
            CommandClass cmdClass = new CommandClass();

            cmdClass.classType = type;

            foreach (MethodInfo methodInfo in type.GetMethods(BindingFlags.Instance | BindingFlags.Static |
                                                              BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.DeclaredOnly))
            {
                if (methodInfo.Name.StartsWith("get_") || methodInfo.Name.StartsWith("set_"))
                {
                    continue;
                }

                CommandMethod cmdMethod = new CommandMethod(cmdClass);
                cmdMethod.method = methodInfo;

                bool supported = true;
                foreach (ParameterInfo pi in methodInfo.GetParameters())
                {
                    if (!IsParameterSupported(pi))
                    {
                        supported = false;
                        break;
                    }
                }

                if (supported)
                {
                    foreach (NppDisplayNameAttribute n in methodInfo.GetCustomAttributes(typeof(NppDisplayNameAttribute), false))
                    {
                        cmdMethod.name = n.DisplayName;
                    }
                    if (string.IsNullOrEmpty(cmdMethod.name))
                    {
                        cmdMethod.name = methodInfo.Name;
                    }

                    cmdClass.methods.Add(cmdMethod);
                }
            }

            if (cmdClass.methods.Count > 0)
            {
                // Create an instance of this object.
                try
                {
                    cmdClass.instance = (NppScript)Activator.CreateInstance(cmdClass.classType, null);
                    cmdClass.instance.ScriptFileName = _fileName;
                    cmdClass.instance.InitEvents();
                    _classes.Add(cmdClass);
                }
                catch (Exception ex)
                {
                    Plugin.Output.WriteLine(OutputStyle.Error, Res.err_script_CreateInstance,
                                            cmdClass.classType.Name, _fileName, ex.ToString());
                    cmdClass.instance = null;
                }
            }
        }
Example #7
0
        /// <summary>
        /// Обращение к подписке на события с файлом в сервисе редактирования
        /// </summary>
        /// <param name="documentTrackerUrl">Url to the command service</param>
        /// <param name="method">Name of method</param>
        /// <param name="documentRevisionId">Key for caching on service, whose used in editor</param>
        /// <param name="callbackUrl">Url to the callback handler</param>
        /// <param name="users">users id for drop</param>
        /// <param name="status">saving status</param>
        /// <param name="version">server version</param>
        /// <returns>Response</returns>
        public CommandResultTypes CommandRequest(
            string documentTrackerUrl,
            CommandMethod method,
            string documentRevisionId,
            string callbackUrl,
            string users,
            string status,
            out string version)
        {
            var validateKey = GenerateValidateKey(documentRevisionId, string.Empty);

            var urlDocumentService = documentTrackerUrl + RequestTrackParams;
            var urlToTrack         = String.Format(urlDocumentService,
                                                   method.ToString().ToLower(CultureInfo.InvariantCulture),
                                                   documentRevisionId,
                                                   validateKey,
                                                   HttpUtility.UrlEncode(callbackUrl ?? ""),
                                                   HttpUtility.UrlEncode(users ?? ""),
                                                   status);

            var request = (HttpWebRequest)WebRequest.Create(urlToTrack);

            request.Method = "GET";

            // hack. http://ubuntuforums.org/showthread.php?t=1841740
            if (WorkContext.IsMono)
            {
                ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
            }

            string data;

            using (var response = request.GetResponse())
                using (var stream = response.GetResponseStream())
                {
                    if (stream == null)
                    {
                        throw new Exception("Response is null");
                    }

                    using (var reader = new StreamReader(stream))
                    {
                        data = reader.ReadToEnd();
                    }
                }

            var jResponse = JObject.Parse(data);

            try
            {
                version = jResponse.Value <string>("version");
            }
            catch (Exception)
            {
                version = "0";
            }

            return((CommandResultTypes)jResponse.Value <int>("error"));
        }
Example #8
0
        private async Task userJoined(SocketGuildUser user)
        {
            var guild   = user.Guild;
            var channel = guild.Channels.FirstOrDefault() as SocketTextChannel;
            await channel.SendMessageAsync($"Witaj, {user.Mention}");

            await user.SendMessageAsync(CommandMethod.GetWelcomeMsg());
        }
Example #9
0
 private CommandMethod CreateCommandMethodWrapper(CommandMethod cmdM)
 {
     return((ICli cli, IArgumentsInfo argInfo) =>
     {
         ++CallCount;
         return cmdM(cli, argInfo);
     });
 }
Example #10
0
 public static CommandMock CreateDefaultWrapper(CommandMethod innerCmd)
 {
     return(CreateWrapper(
                names: new string[] { "mockCommand" },
                innerCmd: innerCmd,
                description: new string[] { "A mock Command" }
                ));
 }
Example #11
0
 public Command(string name, List <CommandParameter> parameters, RuntimeType returnType, CommandMethod method, bool enqueuable)
 {
     Name         = name;
     Parameters   = parameters;
     ReturnType   = returnType;
     this.method  = method;
     IsEnqueuable = enqueuable;
 }
Example #12
0
        public void Init()
        {
            _mockSetting = new Mock <ISettings>();
            _service     = new ParameterService(_mockSetting.Object);

            _command           = new CommandMethod(typeof(MethodServiceTests).GetMethod("FakeMethod"));
            _nonCommand        = new CommandMethod(typeof(MethodServiceTests).GetMethod("FakeMethodNonCommand"));
            _collectionCommand = new CommandMethod(typeof(MethodServiceTests).GetMethod("FakeMethodWithCollections"));
        }
Example #13
0
 /// <summary>
 /// 绑定ViewModel的命令到窗体的按钮等控件上
 /// </summary>
 /// <param name="control">按钮等执行命令调用的控件</param>
 /// <param name="command">要执行的命令委托方法</param>
 public void BindCommandControls(Control control, CommandMethod command)
 {
     if (control is Button)
     {
         dictCommand.Add(control, command);
         ((Button)control).Click += (sender, e) => {
             dictCommand[sender]();
         };
     }
 }
Example #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="vCommands.Commands.MethodCommand"/> class with the given name and function.
        /// </summary>
        /// <param name="category">The named category under which the command goes.</param>
        /// <param name="name">The name of the command, used to find and invoke it.</param>
        /// <param name="description">The description of the command, for displaying in help text.</param>
        /// <param name="function">The underlying method to be invoked by the command.</param>
        /// <exception cref="System.ArgumentNullException">Thrown when either of the given arguments is null.</exception>
        public MethodCommand(string name, string category, string description, CommandMethod function)
            : base(name, category, description)
        {
            if (function == null)
            {
                throw new ArgumentNullException("function");
            }

            this.Method = function;
        }
        public static string SendCommand <T>(List <T> data, CommandMethod method, string modelData)
        {
            var          jdata = JsonConvert.SerializeObject(data);
            CommandModel cmd   = new CommandModel();

            cmd.Command = method.ToString();
            cmd.Model   = modelData;
            cmd.Data    = jdata;
            return(JsonConvert.SerializeObject(cmd));
        }
Example #16
0
 private void CommandEventMethod(object sender, EventArgs e, CommandMethod command)
 {
     try
     {
         command();
     }
     catch (Exception ex)
     {
         RaiseBinderError(sender, ex);
     }
 }
Example #17
0
 public static Command CreateCommand(Document resource = null, CommandMethod method = CommandMethod.Get, CommandStatus status = CommandStatus.Pending)
 {
     return(new Command()
     {
         From = CreateNode(),
         To = CreateNode(),
         Method = method,
         Status = status,
         Resource = resource
     });
 }
Example #18
0
        private string CreateMessage(CommandMethod commandMethod)
        {
            var dto = new ProxyParametersDTO
            {
                CommandMethod = commandMethod,
                ProgramInfo   = this._programInfo
            };
            string message = this._serializationManager.Serialize(dto);

            return(message);
        }
Example #19
0
 /// <summary>
 /// 绑定ViewModel的命令到窗体的按钮等控件上
 /// </summary>
 /// <param name="control">ButtonBase 按钮等执行命令调用的控件</param>
 /// <param name="command">要执行的命令委托方法</param>
 public void BindCommandControls(Control control, CommandMethod command)
 {
     if (control is ButtonBase)
     {
         //dictCommand.Add(control, command);
         ((ButtonBase)control).Click += (sender, e) =>
         {
             //((CommandMethod)dictCommand[sender])();
             CommandEventMethod(sender, e, command);
         };
     }
 }
Example #20
0
        /// <summary>
        /// 绑定ViewModel的命令到窗体的任意控件上
        /// </summary>
        /// <param name="control">窗体控件</param>
        /// <param name="controlEvent">控件事件名称</param>
        /// <param name="command">命令方法</param>
        public void BindCommandControls(Control control, string controlEvent, CommandMethod command)
        {
            EventHandler hander = new EventHandler(
                (object sender, EventArgs e) =>
            {
                CommandEventMethod(sender, e, command);
            });

            Type ctrType = control.GetType();

            ctrType.GetEvent(controlEvent).AddEventHandler(control, hander);
        }
Example #21
0
        /// <summary>
        /// 绑定一个命令控件到一个有参数的命令方法上
        /// </summary>
        /// <typeparam name="T">命令方法的参数类型</typeparam>
        /// <param name="control">命令控件</param>
        /// <param name="command">带参数的命令方法</param>
        public void BindCommandControls <T>(ICommandControl control, CommandMethod <T> command)
        {
            //dictCommand.Add(control, command);
            EventHandler hander = new EventHandler(
                (object sender, EventArgs e) => {
                CommandEventMethod <T>(sender, e, command);
            });

            Type ctrType = control.GetType();

            ctrType.GetEvent(control.ControlEvent).AddEventHandler(control, hander);
        }
Example #22
0
 public static Command CreateCommand(Document resource = null, CommandMethod method = CommandMethod.Get, CommandStatus status = CommandStatus.Pending, LimeUri uri = null)
 {
     return new Command()
     {
         From = CreateNode(),
         To = CreateNode(),
         Method = method,
         Status = status,
         Uri = uri,
         Resource = resource
     };
 }
Example #23
0
 public MessageModel(string m, ColorRequest r)
 {
     messageContent = m;
     if (m != null)
     {
         messageBuffer = Encoding.ASCII.GetBytes(m);
     }
     if (r != null)
     {
         requestTime   = r.requestTime.ToUniversalTime();
         commandMethod = r.requestMethod;
     }
 }
Example #24
0
        public void MethodParsing()
        {
            TestCommand command = new TestCommand(m_Console);

            command.ParseMethod();
            CommandMethod           method     = command.Method;
            List <CommandParameter> parameters = method.CopyParameters();

            Assert.AreEqual(3, method.ParameterCount);
            TestHelper.CheckParameter(parameters[0], "numbervalue", typeof(int), null);
            TestHelper.CheckParameter(parameters[1], "toggle", typeof(bool), null);
            TestHelper.CheckParameter(parameters[2], "str", typeof(string), "abc");
        }
 public CommandLogItem(
     CommandMethod method,
     DbCommand command,
     DbCommandInterceptionContext interceptionContext,
     object result = null)
 {
     Method      = method;
     CommandText = command.CommandText;
     Command     = command;
     Exception   = interceptionContext.Exception;
     TaskStatus  = interceptionContext.TaskStatus;
     IsAsync     = interceptionContext.IsAsync;
     Result      = result;
 }
Example #26
0
 public Command(string content, FunToaderCommandType commandType, CommandMethod commandMethod)
 {
     this.CommandContent = new CommandContent
     {
         Buffer  = Encoding.ASCII.GetBytes(content),
         Content = content
     };
     this.CommandDates = new CommandDates
     {
         Received = DateTime.Now.ToUniversalTime(),
         Sent     = null
     };
     this.CommandType   = commandType;
     this.CommandMethod = commandMethod;
 }
 public CommandLogItem(
     CommandMethod method,
     DbCommand command,
     Exception exception,
     TaskStatus taskStatus,
     bool isAsync,
     object result = null)
 {
     Method      = method;
     CommandText = command.CommandText;
     Command     = command;
     Exception   = exception;
     TaskStatus  = taskStatus;
     IsAsync     = isAsync;
     Result      = result;
 }
Example #28
0
    void Awake()
    {
        if (null == Commands)
        {
            Forward1    = new CommandMethod(ForwardOneCommand);
            Forward2    = new CommandMethod(ForwardTwoCommand);
            Forward3    = new CommandMethod(ForwardThreeCommand);
            RotateLeft  = new CommandMethod(RotateLeftCommand);
            RotateRight = new CommandMethod(RotateRightCommand);
            UTurn       = new CommandMethod(UTurnCommand);
            Backward1   = new CommandMethod(BackwardOneCommand);
            Commands    = new CommandMethod[] { () => { return(null); }, Forward1, Forward2, Forward3, RotateLeft, RotateRight, UTurn, Backward1 };
        }

        GameMaster.SharedInstance.RegisterRobot(this);
    }
Example #29
0
        public void SelectCommand_EmptyString_ReturnsMethod()
        {
            var commandMethod = new CommandMethod();

            var commandTable = new Mock <ICommandTable>();

            commandTable.Setup(c => c.TryGetValue("", out commandMethod)).Returns(true);
            commandTable.Setup(c => c.TryGetValue("test", out commandMethod)).Returns(true);

            var commandSelector = new DefaultCommandSelector();

            var selectedMethod = commandSelector.SelectCommand("", commandTable.Object, out object[] extra);

            Assert.NotNull(selectedMethod);
            Assert.Equal(selectedMethod.Id, commandMethod.Id);
            Assert.Empty(extra);
        }
        public void Init()
        {
            _mockParameterService = new Mock <IParameterService>();
            _mockMethodService    = new Mock <IMethodService>();
            _mockConsoleService   = new Mock <IConsoleService>();
            _mockSettings         = new Mock <ISettings>();
            _service = new CommandService(_mockParameterService.Object,
                                          _mockMethodService.Object,
                                          _mockConsoleService.Object,
                                          _mockSettings.Object);

            _command           = new CommandMethod(typeof(FakeController).GetMethod("FakeMethod"));
            _commandStatic     = new CommandMethod(typeof(FakeController).GetMethod("FakeStaticMethod"));
            _commandNoParams   = new CommandMethod(typeof(FakeController).GetMethod("FakeMethodNoParams"));
            _nonCommand        = new CommandMethod(typeof(FakeController).GetMethod("FakeMethodNonCommand"));
            _collectionCommand = new CommandMethod(typeof(FakeController).GetMethod("FakeMethodWithCollections"));
        }
Example #31
0
 public BasicCommand(CommandMethod method)
 {
     this._method = method;
 }
 public CommandLogItem(CommandMethod method, DbCommand command, object result = null)
 {
     Method = method;
     CommandText = command.CommandText;
     Result = result;
 }
Example #33
0
		private object InvokeCommandMethod(CommandMethod method, ICommandContext context)
		{
			var methodInfo = MethodBase.GetMethodFromHandle(method.MethodHandle);
			var parameterInfo = methodInfo.GetParameters();
			var args = new object[parameterInfo.Length];

			args[0] = context;

			for (var i = 1; i < parameterInfo.Length; i++)
			{
				var methodParamInfo = parameterInfo[i];
				var parameterName = methodParamInfo.Name;

				if (context.IsParameterExists(parameterName))
				{
					var parameter = context[parameterName];
					if (parameter != null)
					{
						var methodParameterType = methodParamInfo.ParameterType;
						try
						{
							args[i] = Convert(parameter, methodParameterType);
						}
						catch (ApplicationException exception)
						{
							throw new Exception(
								$"Параметр '{parameterName}' команды '{method.CommandInfo.Name}' не может быть конвертирован в "
								+ $"'{methodParameterType}', для передачи обработчику '{methodInfo.Name}'.",
								exception);
						}
					}
				}
				else if (!method.CommandInfo.GetParameter(parameterName).IsOptional)
					throw new ArgumentException(
						$"Параметр '{parameterName}' команды '{method.CommandInfo.Name}' не найден в контексте.",
						nameof(context));
			}

			return methodInfo.Invoke(this, args);
		}
Example #34
0
    void Awake()
    {
        if (null == Commands) {
            Forward1 = new CommandMethod(ForwardOneCommand);
            Forward2 = new CommandMethod(ForwardTwoCommand);
            Forward3 = new CommandMethod(ForwardThreeCommand);
            RotateLeft = new CommandMethod(RotateLeftCommand);
            RotateRight = new CommandMethod(RotateRightCommand);
            UTurn = new CommandMethod(UTurnCommand);
            Backward1 = new CommandMethod(BackwardOneCommand);
            Commands = new CommandMethod[] {() => {return null;}, Forward1, Forward2, Forward3, RotateLeft, RotateRight, UTurn, Backward1};
        }

        GameMaster.SharedInstance.RegisterRobot(this);
    }
 public CommandLogItem(
     CommandMethod method,
     DbCommand command,
     Exception exception,
     TaskStatus taskStatus,
     bool isAsync,
     object result = null)
 {
     Method = method;
     CommandText = command.CommandText;
     Command = command;
     Exception = exception;
     TaskStatus = taskStatus;
     IsAsync = isAsync;
     Result = result;
 }
Example #36
0
			public Command(Symbol name, string descr, CommandMethod cmd)
			{
				_name = name; _descr = descr; _cmd = cmd;
			}
Example #37
0
        private void ProcessScriptClass(Type type)
        {
            CommandClass cmdClass = new CommandClass();
            cmdClass.classType = type;

            foreach (MethodInfo methodInfo in type.GetMethods(BindingFlags.Instance | BindingFlags.Static |
                BindingFlags.Public | BindingFlags.InvokeMethod | BindingFlags.DeclaredOnly))
            {
                if (methodInfo.Name.StartsWith("get_") || methodInfo.Name.StartsWith("set_")) continue;

                CommandMethod cmdMethod = new CommandMethod(cmdClass);
                cmdMethod.method = methodInfo;

                bool supported = true;
                foreach (ParameterInfo pi in methodInfo.GetParameters())
                {
                    if (!IsParameterSupported(pi))
                    {
                        supported = false;
                        break;
                    }
                }

                if (supported)
                {
                    foreach (NppDisplayNameAttribute n in methodInfo.GetCustomAttributes(typeof(NppDisplayNameAttribute), false))
                    {
                        cmdMethod.name = n.DisplayName;
                    }
                    if (string.IsNullOrEmpty(cmdMethod.name)) cmdMethod.name = methodInfo.Name;

                    cmdClass.methods.Add(cmdMethod);
                }
            }

            if (cmdClass.methods.Count > 0)
            {
                // Create an instance of this object.
                try
                {
                    cmdClass.instance = (NppScript)Activator.CreateInstance(cmdClass.classType, null);
                    cmdClass.instance.ScriptFileName = _fileName;
                    cmdClass.instance.InitEvents();
                    _classes.Add(cmdClass);
                }
                catch (Exception ex)
                {
                    Plugin.Output.WriteLine(OutputStyle.Error, Res.err_script_CreateInstance,
                        cmdClass.classType.Name, _fileName, ex.ToString());
                    cmdClass.instance = null;
                }
            }
        }
 public CommandLogItem(
     CommandMethod method, 
     DbCommand command, 
     DbCommandInterceptionContext interceptionContext, 
     object result = null)
 {
     Method = method;
     CommandText = command.CommandText;
     Command = command;
     Exception = interceptionContext.Exception;
     TaskStatus = interceptionContext.TaskStatus;
     IsAsync = interceptionContext.IsAsync;
     Result = result;
 }