public RemoteBoardButtonModel(RemoteCommand command)
        {
            this.ID   = command.ID;
            this.Name = command.Name;

            this.SetValuesFromCommand();
        }
示例#2
0
        public void SendCompressedCommand(RemoteCommand command, object obj, AppSession session)
        {
            LogHelper.WriteLog(typeof(RemoteCommand), "发送消息:" + command.ToString());
            var type = ((int)command).ToString().PadLeft(2, '0');

            byte[] typeByte = Encoding.UTF8.GetBytes(type);

            var str      = JsonConvert.SerializeObject(obj);
            var comp_str = CompressHelper.Compress(str);

            byte[] byteBuffer = Encoding.UTF8.GetBytes(comp_str);

            int len = byteBuffer.Length;

            byte[] length = BitConverter.GetBytes(len);

            var data = typeByte.Concat(length).Concat(byteBuffer).ToArray();

            if (type.Length != 2)
            {
                return;
            }
            try
            {
                session.Send(data, 0, data.Length);
            }
            catch (Exception)
            {
            }
        }
        public static async Task HandleAsync(RemoteCommand command, Socket socket)
        {
            switch (command)
            {
            case HelloCommand concrete:
                Logger.Info($"Hello [{concrete.Who}]!");
                break;

            case ListCommandsCommand concrete:
                await HandleListCommands(socket);

                break;

            case ShutdownCommand concrete:
                HandleShutdown(concrete);
                break;

            case ToggleSoundMuteCommand concrete:
                HandleToggleSoundMute(concrete);
                break;

            case AbortShutdownCommand concrete:
                HandleAbortShutdown(concrete);
                break;

            case RestartCommand concrete:
                HandleRestart(concrete);
                break;

            case ScreenOffCommand concrete:
                HandleScreenOff();
                break;

            case ScreenOnCommand concrete:
                HandleScreenOn();
                break;

            case LockScreenCommand concrete:
                HandleLockScreen();
                break;

            case LaunchProcessCommand concrete:
                HandleLaunchProcess(concrete);
                await Task.Delay(300);
                await HandleListCommands(socket);

                break;

            case KillProcessCommand concrete:
                HandleKillProcess(concrete);
                await Task.Delay(50);
                await HandleListCommands(socket);

                break;

            default:
                Logger.Warn($"Command [{command.CommandName}] is not handled.");
                break;
            }
        }
示例#4
0
        public async Task ShouldHandleCommand()
        {
            var command = new ChangeLoggingLevelCommand
            {
                MinimumLevel = LogEventLevel.Error
            };

            var remoteCommand = new RemoteCommand
            {
                Name = typeof(ChangeLoggingLevelCommand).FullName,
                Data = JsonConvert.SerializeObject(command)
            };

            ChangeLoggingLevelCommand capturedCommand = null;

            _commandHandlerMock.Setup(m => m.Handle(It.IsAny <ChangeLoggingLevelCommand>())).Returns(Task.CompletedTask)
            .Callback <ChangeLoggingLevelCommand>(c => capturedCommand = c);

            var guid = await _messageHub.Handle(remoteCommand);

            _commandHandlerMock.Verify(m => m.Handle(It.IsAny <ChangeLoggingLevelCommand>()), Times.Once);
            Assert.IsNotNull(capturedCommand);
            Assert.AreEqual(LogEventLevel.Error, capturedCommand.MinimumLevel);
            Assert.IsNotNull(guid);
        }
示例#5
0
        RemoteClient1()
        {
            try
            {
                //Reachability.ServerSinkProvider.StartWaitRedirectedMsg();
                remoteCommand        = new RemoteCommand();
                commandClient        = new RemoteCommandClient();
                commandClient.Sender = "WebAdminZ2";
                commandClient.ReceiveCommandResultEvent += new ReceiveCommandResultEventHandler(client_ReceiveCommandResultEvent);
                commandClient.DeviceOfflineEvent        += new DeviceOnlineOfflineEventHandler(client_DeviceOfflineEvent);
                commandClient.DeviceOnlineEvent         += new DeviceOnlineOfflineEventHandler(client_DeviceOnlineEvent);
                commandClient.LogOffEvent += new EventHandler(commandClient_LogOffEvent);
                //ObjRef or = RemotingServices.Marshal(commandClient as MarshalByRefObject);

                if (!remoteCommand.AttachClient(commandClient))
                {
                    status = false;
                    throw new Exception("登录失败,请查看日志!");
                }
                else
                {
                    status = true;
                }
            }
            catch (Exception ex)
            {
                status = false;
                //throw new Exception("连接服务器时出现异常,请重新尝试!异常信息" + ex.Message);
            }
        }
示例#6
0
        public RemoteResult ParseMessage(RemoteCommand remoteCommand)
        {
            var methods = _methodDictionaries.GetValueOrDefault(remoteCommand.RemoteProcedureDescriptor.ServiceHash);

            // Get the method to call on the service
            var lookup = methods.FindMethod(remoteCommand.RemoteProcedureDescriptor);

            var serviceType = methods.GetPrimaryInterface();
            var method      = lookup.Item2;

            // Get the actual service instance
            var service = _serviceProvider.GetService(serviceType);

            // Convert the parameters from the RemoteCommand into correct types
            var parameterTypes = method.GetParameters()
                                 .Select(p => p.ParameterType)
                                 .ToArray();

            var parameters = remoteCommand.Parameters
                             .Zip(parameterTypes, (o, t) => ConvertParameter(_serializer.ConvertObject(o, t), t))
                             .ToArray();

            try
            {
                var returnValue = method.Invoke(service, parameters);
                // Make the call

                var result = new RemoteResult
                {
                    RemoteSessionInformation = remoteCommand.RemoteSessionInformation,
                    Result = returnValue
                };

                var returnType = method.ReturnType;
                if (returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(Task <>))
                {
                    var task = ((Task)returnValue);
                    task.Wait();

                    var resultProperty = typeof(Task <>).MakeGenericType(returnType.GetGenericArguments()).GetProperty("Result");
                    result.Result = resultProperty.GetValue(task);
                }

                return(result);
            } catch (TargetInvocationException e)
            {
                return(new RemoteResult
                {
                    RemoteSessionInformation = remoteCommand.RemoteSessionInformation,
                    Exception = e.InnerException
                });
            } catch (Exception e)
            {
                return(new RemoteResult
                {
                    RemoteSessionInformation = remoteCommand.RemoteSessionInformation,
                    Exception = e
                });
            }
        }
示例#7
0
    void _ws_OnMessage(object sender, MessageEventArgs e)
    {
        JSONClass json = JSON.Parse(e.Data).AsObject;

#if UNITY_EDITOR
        UnityEngine.Debug.Log(e.Data);
#endif

        if (json.ContainsKey("E"))
        {
            UnityMainThreadDispatcher.Instance().Enqueue(() => onConnectionUpdate(ConnectionStatus.ERROR));
        }
        else
        {
            UnityMainThreadDispatcher.Instance().Enqueue(() => onConnectionUpdate(ConnectionStatus.CONNECTED));

            var msgs = SignalRMessage.FromJSON(json);
            foreach (var msg in msgs)
            {
                switch (msg.M)
                {
                case "remoteCommand":
                    RemoteCommand cmd   = (RemoteCommand)System.Enum.Parse(typeof(RemoteCommand), msg.A[0].ToUpper());
                    var           param = msg.A.Length > 1 ? msg.A[1] : string.Empty;
                    UnityMainThreadDispatcher.Instance().Enqueue(() => onRemoteCommand(cmd, param));
                    break;
                }
            }
        }
    }
        public async Task ConnectAndSendCommandsUsingBuilderAsync()
        {
            using (var remote = new SdrRemote(Config))
            {
                remote.IsConnected().ShouldBeTrue();

                var gainAudioCommand        = RemoteCommand.Create("Set", "AudioGain", 45);
                var detectorTypeCommand     = RemoteCommand.Create("Set", "DetectorType", "WFM");
                var filterBandwidthCommand  = RemoteCommand.Create("Set", "FilterBandwidth", 200000);
                var squelchEnabledCommand   = RemoteCommand.Create("Set", "SquelchEnabled", false);
                var SquelchThresholdCommand = RemoteCommand.Create("Set", "SquelchThreshold", 30);
                var fmStereoCommand         = RemoteCommand.Create("Set", "FmStereo", true);
                var frequencyCommand        = RemoteCommand.Create("Set", "Frequency", 99700000);

                await remote.AddCommand(gainAudioCommand)
                .AddCommand(detectorTypeCommand)
                .AddCommand(filterBandwidthCommand)
                .AddCommand(squelchEnabledCommand)
                .AddCommand(SquelchThresholdCommand)
                .AddCommand(fmStereoCommand)
                .AddCommand(frequencyCommand)
                .Execute();

                remote.ResponseLog.Count.ShouldBeGreaterThan(10);
                remote.ToString().ShouldNotBeNullOrWhiteSpace();
            }
        }
示例#9
0
        public Task <Guid> Handle(RemoteCommand remoteCommand)
        {
            var command = Unwrapp(remoteCommand);

            _mediator.Send(command);
            return(Task.FromResult(command.CorrelationId));
        }
示例#10
0
        public void CallVoidMethod(RemoteProcedureDescriptor descriptor, params object[] parameters)
        {
            if (_remoteProcedureCaller == null)
            {
                throw new InvalidOperationException();
            }

            var remoteCommand = new RemoteCommand
            {
                RemoteSessionInformation = new RemoteSessionInformation
                {
                    InstanceId = _remoteSessionInformation.InstanceId,
                    ScopeId    = _remoteSessionInformation.ScopeId,
                    ActionId   = Guid.NewGuid()
                },
                RemoteProcedureDescriptor = descriptor,
                Parameters = parameters
            };

            var result = _remoteProcedureCaller.CallMethod(remoteCommand);

            if (result.Exception != null)
            {
                throw new RemoteException("Remote Service threw an exception", ConvertResult <Exception>(result.Exception));
            }
        }
示例#11
0
        private void Window_KeyUp(object sender, KeyEventArgs e)
        {
            var command = new RemoteCommand(TypeCommand.KeyboardEvent, e.Convert());

            sendData.Enqueue(command.SerializeData());
            e.Handled = true;
        }
示例#12
0
        private RemoteCommandMockRepository()
        {
            var ledLightRemoteCommand = new RemoteCommand
            {
                Id         = 1,
                Name       = "LED Lights",
                SignalCode = "102",
            };
            var kettleLightRemoteCommand = new RemoteCommand
            {
                Id         = 2,
                Name       = "Kettle",
                SignalCode = "253",
            };
            var tvLightRemoteCommand = new RemoteCommand
            {
                Id         = 3,
                Name       = "TV",
                SignalCode = "156",
            };
            var selfDestructCommand = new RemoteCommand
            {
                Id         = 4,
                Name       = "Self Destruct",
                SignalCode = "1",
            };

            remoteCommands = new List <RemoteCommand>
            {
                ledLightRemoteCommand,
                kettleLightRemoteCommand,
                tvLightRemoteCommand,
                selfDestructCommand,
            };
        }
示例#13
0
        private async Task DialogAlertResumeAfter(IDialogContext context, IAwaitable <Alert> result)
        {
            this.alert = await result;
            var reply = context.MakeMessage();

            reply.Text = string.Format(WivaldyBotResources.AlertOK);
            switch (alert.AlertType)
            {
            case AlertEnum.Instant:
                reply.Text += string.Format(WivaldyBotResources.AlertChangeInstant, alert.Interval.TotalSeconds, alert.Threshold);
                break;

            case AlertEnum.Total:
                reply.Text += string.Format(WivaldyBotResources.AlertChangeTotal, alert.Interval.TotalSeconds, alert.Threshold);
                break;

            case AlertEnum.Switch:
                reply.Text += string.Format(WivaldyBotResources.AlertChangeSwitch, alert.Interval.TotalSeconds);
                break;

            default:
                break;
            }

            await context.PostAsync(reply);

            if (alert.AlertType == AlertEnum.Switch)
            {
                //initialize the last command
                var res = await myWivaldy.GetRemoteCommand();

                if (res != null)
                {
                    remoteCommand = res;
                }
            }
            StartAlert = DateTimeOffset.Now;
            tAlert     = new Timer(new TimerCallback(TimerEventAsync));
            tAlert.Change((int)alert.Interval.TotalMilliseconds, (int)alert.Interval.TotalMilliseconds);
            NumberAlerts = 0;
            try
            {
                var ret = ConversationStarter.Timers[context.Activity.Conversation.Id + context.Activity.ChannelId];
                ConversationStarter.Timers[context.Activity.Conversation.Id + context.Activity.ChannelId] = tAlert.GetHashCode();
            }
            catch (Exception)
            {
                ConversationStarter.Timers.Add(context.Activity.Conversation.Id + context.Activity.ChannelId, tAlert.GetHashCode());
            }

            //var url = HttpContext.Current.Request.Url;
            //We now tell the user that we will talk to them in a few seconds

            //reply.Text = "Hello! In a few seconds I'll send you a message proactively to demonstrate how bots can initiate messages. You can also make me send a message by accessing: " +
            //        url.Scheme + "://" + url.Host + ":" + url.Port + "/api/CustomWebApi";
            //await context.PostAsync(reply);

            await WelcomeMessageAsync(context);
        }
示例#14
0
 private void RemoteCommandsListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
     if (this.RemoteCommandsListView.SelectedItem != null)
     {
         RemoteCommand command = (RemoteCommand)this.RemoteCommandsListView.SelectedItem;
         this.CurrentlySelectedCommand = command;
     }
 }
示例#15
0
 public RemoteCommand OnCommandExecuting(RemoteCommand c)
 {
     if (CommandExecuting != null)
     {
         return(CommandExecuting(c) ?? c);
     }
     return(c);
 }
            public async void WhenRunningCommand_ShouldSendRunCommandRequestWithCommandToHost()
            {
                this.launcher.SendMessageAsync <RunCommandRequest, RunCommandResponse>(Arg.Any <RunCommandRequest>()).ReturnsTask(new RunCommandResponse("", new RunCommandResponseData()));
                var command = new RemoteCommand(true, "tar", new[] { "foo.zip" });

                var response = await proxy.RunCommandAsync(command);

                this.launcher.Received(x => x.SendMessageAsync <RunCommandRequest, RunCommandResponse>(Arg.Is <RunCommandRequest>(y => [email protected] == command.Command && [email protected] == command.Arguments)));
            }
        public virtual void SetValuesFromCommand()
        {
            RemoteCommand command = this.Command;

            if (command != null)
            {
                this.Name = command.Name;
            }
        }
示例#18
0
        private void Window_KeyDown(object sender, KeyEventArgs e)
        {
            var command = new RemoteCommand(TypeCommand.KeyboardEvent, e.Convert());

            sendData.Enqueue(command.SerializeData());
            e.Handled = true;

            System.Diagnostics.Debug.WriteLine($"Key:{e.Key}");
        }
示例#19
0
        public byte[] SerializeCommand(RemoteCommand remoteCommand)
        {
            var stream     = new MemoryStream();
            var serializer = new XmlSerializer(typeof(RemoteCommand));

            serializer.Serialize(stream, remoteCommand);

            stream.Flush();
            return(stream.GetBuffer());
        }
示例#20
0
文件: Program.cs 项目: MangoTwo2/gsub
 private static void Main(string[] args)
 {
     Parser.Default.ParseArguments <AddOptions, ListOptions, RemoveOptions, PullOptions, PushOptions, RemoteOptions, RenameOptions>(args).WithParsed <AddOptions>(t => AddCommand.TryExecute(t))
     .WithParsed <RemoveOptions>(t => RemoveCommand.TryExecute(t))
     .WithParsed <ListOptions>(t => ListCommand.TryExecute(t))
     .WithParsed <PullOptions>(t => PullCommand.TryExecute(t))
     .WithParsed <PushOptions>(t => PushCommand.TryExecute(t))
     .WithParsed <RemoteOptions>(t => RemoteCommand.TryExecute(t))
     .WithParsed <RenameOptions>(t => RenameCommand.TryExecute(t));
 }
示例#21
0
        private CommandBase Unwrapp(RemoteCommand remoteCommand)
        {
            if (!_commmandTypes.ContainsKey(remoteCommand.Name))
            {
                throw new ArgumentException($"Cannot find command with name: {remoteCommand.Name}");
            }
            var commandType = _commmandTypes[remoteCommand.Name];

            return((CommandBase)JsonConvert.DeserializeObject(remoteCommand.Data, commandType));
        }
示例#22
0
    IEnumerator RepeatRetrieveMessage(float waitTime)
    {
        bool checkSQS = true;

        while (checkSQS)
        {
            yield return(new WaitForSeconds(waitTime));

            if (!string.IsNullOrEmpty(queueUrl))
            {
                SqsClient.ReceiveMessageAsync(queueUrl, (result) => {
                    if (result.Exception == null)
                    {
                        //Read the message
                        var messages = result.Response.Messages;
                        messages.ForEach(m => {
                            RemoteCommand command = RemoteCommand.CreateFromJSON(m.Body);
                            Debug.Log(@"Target " + command.target);
                            int index = Int32.Parse(command.target);
                            activateCam(index);
                            Debug.Log(@"Done switching camera");

                            //Delete the message
                            var delRequest = new Amazon.SQS.Model.DeleteMessageRequest {
                                QueueUrl      = queueUrl,
                                ReceiptHandle = m.ReceiptHandle
                            };

                            SqsClient.DeleteMessageAsync(delRequest, (delResult) => {
                                if (delResult.Exception == null)
                                {
                                }
                                else
                                {
                                }
                            });


                            Debug.Log(@"Done processing message ");
                        });
                    }
                    else
                    {
                        Debug.Log(result.Exception);
                        Debug.LogException(result.Exception);
                    }
                });
            }
            else
            {
                Debug.Log(@"Queue Url is empty, make sure that the queue is created first");
            }
        }
    }
示例#23
0
 private void ResetSettings()
 {
     alert        = new Alert();
     NumberAlerts = 0;
     int.TryParse(ConfigurationManager.AppSettings["AlertMaxNumber"], out AlertMaxNumber);
     myWivaldy                 = new Wivaldy();
     me                        = new MessageDetails();
     remoteCommand             = new RemoteCommand();
     remoteCommand.date        = new Date();
     remoteCommand.date.millis = DateTimeOffset.Now.ToUnixTimeMilliseconds();
 }
示例#24
0
        protected override void OnMouseUp(MouseButtonEventArgs e)
        {
            base.OnMouseUp(e);

            Point p   = e.GetPosition(this);
            Point pos = new Point(p.X / imageSource.Width, p.Y / imageSource.Height);

            var command = new RemoteCommand(TypeCommand.MouseButtons, e.Convert(pos));

            sendData.Enqueue(command.SerializeData());
        }
示例#25
0
        private void CommandButtons_EditClicked(object sender, RoutedEventArgs e)
        {
            CommandButtonsControl commandButtonsControl = (CommandButtonsControl)sender;
            RemoteCommand         command = commandButtonsControl.GetCommandFromCommandButtons <RemoteCommand>(sender);

            if (command != null)
            {
                CommandWindow window = new CommandWindow(new RemoteCommandDetailsControl(command));
                window.Closed += Window_Closed;
                window.Show();
            }
        }
示例#26
0
 public void RemoteCommand(RemoteCommand remoteCommand)
 {
     try
     {
         commandService = new RemoteCommandService();
         commandService.Command(remoteCommand);
     }
     catch (Exception ex)
     {
         throw new RMSAppException(this, "0500", "RemoteCommand failed. " + ex.Message, ex, true);
     }
 }
            public async void WhenRunningCommand_StdErrIsReturned()
            {
                this.launcher.SendMessageAsync <RunCommandRequest, RunCommandResponse>(Arg.Any <RunCommandRequest>()).ReturnsTask(new RunCommandResponse("", new RunCommandResponseData()
                {
                    exitCode = 0, stdErr = "StdErrMessage"
                }));
                var command = new RemoteCommand(true, "tar", new[] { "foo.zip" });

                var response = await proxy.RunCommandAsync(command);

                Assert.Equal("StdErrMessage", response.StdErr);
            }
        public static void ExecuteCommand(RemoteCommand command)
        {
            InputSimulator sim = new InputSimulator();
            VirtualKeyCode?key = null;

            switch (command)
            {
            case RemoteCommand.LeftArrow:
                key = VirtualKeyCode.LEFT;
                break;

            case RemoteCommand.RightArrow:
                key = VirtualKeyCode.RIGHT;
                break;

            case RemoteCommand.VolumeUp:
                key = VirtualKeyCode.VOLUME_UP;
                break;

            case RemoteCommand.VolumeDown:
                key = VirtualKeyCode.VOLUME_DOWN;
                break;

            case RemoteCommand.Space:
                key = VirtualKeyCode.SPACE;
                break;

            case RemoteCommand.PlayPause:
                key = VirtualKeyCode.MEDIA_PLAY_PAUSE;
                break;

            case RemoteCommand.Previous:
                key = VirtualKeyCode.MEDIA_PREV_TRACK;
                break;

            case RemoteCommand.Next:
                key = VirtualKeyCode.MEDIA_NEXT_TRACK;
                break;

            case RemoteCommand.Shutdown:
                Process.Start(new ProcessStartInfo("shutdown", "/s /t 0 /f")
                {
                    CreateNoWindow = true, UseShellExecute = false
                });
                break;     //lol
            }

            if (key != null)
            {
                sim.Keyboard.KeyPress(key.Value);
            }
        }
示例#29
0
    public static RemoteCommand CreateFromJSON(string jsonString)
    {
        RemoteCommand cmd = null;

        try{
            cmd = JsonUtility.FromJson <RemoteCommand> (jsonString);
        }
        catch (System.Exception e) {
            Debug.Log(@"Something went wrong " + e);
        }

        return(cmd);
    }
        public override void SetValuesFromCommand()
        {
            base.SetValuesFromCommand();

            RemoteCommand command = this.Command;

            if (command != null)
            {
                this.BackgroundColor = command.BackgroundColor;
                this.TextColor       = command.TextColor;
                this.ImageName       = command.ImageName;
            }
        }
示例#31
0
        public void CommandComplete(string serverKey, RemoteCommand remoteCommand, List<string> keys = null )
        {
            using (var db = new MediaManagerDataContext())
            {
                var server = Loader.LoadServer(db, serverKey);

                if (server == null) return;

                var commandQueue = server.ServerCommandQueues.FirstOrDefault(a => a.InProgress && a.Command == remoteCommand);

                // update the server's current status
                if (remoteCommand != RemoteCommand.Transcode)
                {
                    server.CurrentCommand = RemoteCommand.NoCommand;
                    if (remoteCommand == RemoteCommand.CopyFromDrive) server.CopyFromDrive = null;
                    if (remoteCommand == RemoteCommand.CopyToDrive)
                    {
                        if (keys == null)
                        {
                            db.WishListFiles.DeleteAllOnSubmit(db.WishListFiles.Where(a => a.ServerMedia.ServerId == server.Id && a.Approved));
                        }
                        else
                        {
                            db.WishListFiles.DeleteAllOnSubmit(db.WishListFiles.Where(a => a.ServerMedia.ServerId == server.Id && a.Approved && keys.Contains(a.ServerMedia.FilePath)));
                        }
                        server.CopyToDrive = null;

                    }
                }
                else
                {
                    server.CurrentlyTranscoding = false;
                }

                if (commandQueue != null)
                {
                    db.ServerCommandQueues.DeleteOnSubmit(commandQueue);
                }

                db.SubmitChanges();
            }
        }
示例#32
0
 // this is a shortcut for MCML
 public void ProcessCommand(RemoteCommand command)
 {
     PlayableItem.PlaybackController.ProcessCommand(command);
 }
 // commands are not routed in this way ...
 public virtual void ProcessCommand(RemoteCommand command)
 {
     // dont do anything (only plugins need to handle this)
 }
示例#34
0
 // this is a shortcut for MCML
 public void ProcessCommand(RemoteCommand command)
 {
     Application.CurrentInstance.PlaybackController.ProcessCommand(command);
 }
示例#35
0
 public RemoteMessage(int delay, RemoteCommand remoteCommand)
 {
     this.Delay = delay;
     this.RemoteCommand = remoteCommand;
 }
示例#36
0
 public void CompleteCommand(RemoteCommand remoteCommand, List<string> keys = null )
 {
     var client = InitializeClient();
     client.CommandComplete(_serverKey, remoteCommand, keys == null ? new string[0] : keys.ToArray());
 }