protected override async Task <ResponseCommand <T2> > Execute(RequestCommand <T, T2> context, Func <RequestCommand <T, T2>, Task <ResponseCommand <T2> > > next)
        {
            Request = context.RestRequest;
            var profile = context.Profile;

            Polly.AsyncPolicy <IRestResponse <T2> > policy = Policy.NoOpAsync <IRestResponse <T2> >();

            if (context.Authenticate)
            {
                policy = context.CustomPolicy ?? Policy.NoOpAsync <IRestResponse <T2> >();

                Polly.AsyncPolicy <IRestResponse <T2> > mainPolicy = Policy
                                                                     .HandleResult <IRestResponse <T2> >(resp => resp.StatusCode == System.Net.HttpStatusCode.Unauthorized)
                                                                     .RetryAsync(
                    retryCount: 1,
                    onRetryAsync: async(result, retryNumber, ctx) => await GetAuthorizationTokenAsync(profile, true)
                    );

                policy = mainPolicy.WrapAsync(policy);


                await GetAuthorizationTokenAsync(profile);
            }

            var response = await policy.ExecuteAsync(async() => await RestClient.ExecuteAsync <T2>(context.RestRequest));

            var responseCommand = new ResponseCommand <T2>
            {
                Response = response
            };

            return(responseCommand);
        }
Example #2
0
        private static void ReceiveAndPickResponse(Socket client, ICommand receivedCommand)
        {
            ICommand response;
            var      watch = Stopwatch.StartNew();

            while (true)
            {
                if (!Responses.TryDequeue(out response !))
                {
                    if (watch.ElapsedMilliseconds >= ResponseQueueTimeout)
                    {
                        response = new ResponseCommand(receivedCommand, "Timeout");
                        break;
                    }

                    continue;
                }

                watch.Restart();
                Console.WriteLine("Received a response...");

                if (CheckConsistency(response))
                {
                    break;
                }
            }

            client.SendCompletelyWithEof(response.ToBytes());
            Console.WriteLine($"Propagated {response}.");
        }
Example #3
0
        private static void SendResponse(Socket client, ICommand receivedCommand, ExecuteCommandVisitor visitor)
        {
            var response = new ResponseCommand(receivedCommand, visitor.Message);

            client.SendCompletelyWithEof(response.ToBytes());
            Console.WriteLine($"Responded with {response}.");
        }
Example #4
0
 private void ProcessReadAck(ResponseCommand cmd)
 {
     if (cmd.Model != Gateway.SensorKey)
     {
         GetOrAddDeviceByCommand(cmd);
     }
 }
Example #5
0
        private MiHomeDevice GetOrAddDeviceByCommand(ResponseCommand cmd)
        {
            if (_gateway != null && cmd.Sid == _gateway.Sid)
            {
                return(_gateway);
            }

            if (_devicesList.TryGetValue(cmd.Sid, out var miHomeDevice))
            {
                return(miHomeDevice);
            }

            var device = _devicesMap[cmd.Model](cmd.Sid);

            if (_namesMap != null && _namesMap.TryGetValue(cmd.Sid, out var deviceName))
            {
                device.Name = deviceName;
            }

            if (cmd.Data != null)
            {
                device.ParseData(cmd.Data);
            }

            _devicesList.TryAdd(cmd.Sid, device);

            return(device);
        }
Example #6
0
        public void Check_WaterLeakSensor_Raised_NoLeak()
        {
            // Arrange
            var cmd = Helpers
                      .CreateCommand("heartbeat", "sensor_wleak.aq1", "158d0001d561e2", 18101,
                                     new Dictionary <string, object>
            {
                { "voltage", "3005" }
            });

            // Act
            WaterLeakSensor device = _deviceFactory.GetDeviceByCommand <WaterLeakSensor>(cmd);

            bool noleakRaised = false;

            device.OnNoLeak += (_, __) => noleakRaised = true;;

            cmd = Helpers
                  .CreateCommand("report", "sensor_wleak.aq1", "158d0001d561e2", 18101,
                                 new Dictionary <string, object>
            {
                { "status", "no_leak" }
            });

            device.ParseData(ResponseCommand.FromString(cmd).Data);

            // Assert
            Assert.True(noleakRaised);
        }
Example #7
0
        public void Run()
        {
            Test.Initialize();

            Guid test = new Guid("8b265223-dc9e-4789-a6df-69d19f644ad7");

            /**
             * State sent to Saga
             * ***/
            SendCommand command = new SendCommand();
            command.RequestId = test;
            command.state = MyMessages.MessageParts.StateCodes.SentMyWCFClient;
            /**
             * State sent to WCF CLient
             * ***/
            ResponseCommand resp = new ResponseCommand();
            resp.RequestId = test;
            resp.state = MyMessages.MessageParts.StateCodes.CompleteMyWCFClient;

            Test.Saga<PaymentRequestSaga>()
                  .ExpectTimeoutToBeSetIn<SendCommand>((state, span) => span == TimeSpan.FromHours(3))
                .ExpectSend<SendCommand>()
                .ExpectReplyToOrginator<ResponseCommand>()
                .When(s => s.Handle(command));

            Test.Saga<PaymentRequestSaga>()
                 .ExpectReplyToOrginator<ResponseCommand>()
                 .When(s => s.Handle(resp));

            Test.Saga<PaymentRequestSaga>()
                 .ExpectSend<ResponseCommand>()
               .WhenSagaTimesOut();
        }
Example #8
0
        public void Check_DoorWindowSensor_Raised_Closed_Event()
        {
            // Arrange
            var cmd = Helpers
                      .CreateCommand("heartbeat", "magnet", "158d0001233529", 64996,
                                     new Dictionary <string, object>
            {
                { "voltage", 2985 }
            });

            // Act
            DoorWindowSensor device = _deviceFactory.GetDeviceByCommand <DoorWindowSensor>(cmd);

            bool closedRaised = false;

            device.OnClose += (_, __) => closedRaised = true;

            cmd = Helpers
                  .CreateCommand("report", "magnet", "158d0001233529", 64996,
                                 new Dictionary <string, object>
            {
                { "status", "close" }
            });

            device.ParseData(ResponseCommand.FromString(cmd).Data);

            // Assert
            Assert.True(closedRaised);
        }
Example #9
0
    internal async Task Send(ResponseCommand responseCommand)
    {
        var command = JsonConvert.SerializeObject(responseCommand);

        byte[] res = Encoding.UTF8.GetBytes(command);
        await client.SendAsync(new ArraySegment <byte>(res), WebSocketMessageType.Text, true, CancellationToken.None);
    }
Example #10
0
        public void Check_MotionSensor_Reports_NoMotion_Data()
        {
            // Arrange
            var cmd = Helpers
                      .CreateCommand("report", "motion", "158d00011c0", 52754,
                                     new Dictionary <string, object>
            {
                { "no_motion", "120" }
            });

            // Act
            MotionSensor device = _fixture.GetDeviceByCommand <MotionSensor>(cmd);

            var noMotionRaised  = false;
            var moMotionSeconds = 0;

            device.OnNoMotion += (_, args) =>
            {
                noMotionRaised  = true;
                moMotionSeconds = args.Seconds;
            };

            device.ParseData(ResponseCommand.FromString(cmd).Data);

            // Assert
            Assert.Equal("motion", device.Type);
            Assert.Equal("158d00011c0", device.Sid);
            Assert.Equal("no motion", device.Status);
            Assert.True(noMotionRaised);
            Assert.Equal(120, device.NoMotion);
        }
Example #11
0
 private void ProcessReadAck(ResponseCommand cmd)
 {
     if (cmd.Model != "gateway")
     {
         GetOrAddDeviceByCommand(cmd);
     }
 }
Example #12
0
        private void DiscoverGatewayAndDevices(ResponseCommand cmd)
        {
            if (_gatewaySid == null)
            {
                if (_gateway == null)
                {
                    _gateway = new Gateway(cmd.Sid, _transport);
                }

                _transport.SetToken(cmd.Token);
            }
            else if (_gatewaySid == cmd.Sid)
            {
                _gateway = new Gateway(cmd.Sid, _transport);
                _transport.SetToken(cmd.Token);
            }

            if (_gateway == null)
            {
                return;
            }

            _transport.SendCommand(new ReadDeviceCommand(cmd.Sid));

            foreach (var sid in JArray.Parse(cmd.Data))
            {
                _transport.SendCommand(new ReadDeviceCommand(sid.ToString()));

                Task.Delay(ReadDeviceInterval).Wait(); // need some time in order not to loose message
            }
        }
Example #13
0
        public void Check_MotionSensor_Reports_Motion_Data()
        {
            // Arrange
            var cmd = Helpers
                      .CreateCommand("report", "motion", "158d00011c0", 52754,
                                     new Dictionary <string, object>
            {
                { "status", "motion" }
            });

            // Act
            MotionSensor device = _fixture.GetDeviceByCommand <MotionSensor>(cmd);

            var motionRaised = false;

            device.OnMotion += (_, args) =>
            {
                motionRaised = true;
            };

            var timeDiff = DateTime.Now - device.MotionDate.Value;

            device.ParseData(ResponseCommand.FromString(cmd).Data);

            // Assert
            Assert.Equal("motion", device.Type);
            Assert.Equal("158d00011c0", device.Sid);
            Assert.Equal("motion", device.Status);
            Assert.True(timeDiff <= TimeSpan.FromSeconds(1));
            Assert.True(motionRaised);
        }
        public async Task <ResponseCommand> Handle(CreateLancamentoCommand command)
        {
            var response = new ResponseCommand();

            command.Validate();
            if (command.Invalid)
            {
                response.AddNotifications(command.Notifications);
                return(response);
            }

            var lancamento = new Models.Lancamento(
                command.NumeroContaOrigem,
                command.NumeroContaDestino,
                command.Valor);

            await _lancamentoRepository.GerarLancamento(lancamento);

            response.AddValue(new { Mensagem   = "Lançamento efetuado com sucesso.",
                                    Compovante = lancamento.Id,
                                    Origem     = lancamento.NumeroContaOrigem,
                                    Destino    = lancamento.NumeroContaDestino,
                                    Valor      = lancamento.Valor,
                                    Data       = lancamento.DataLancamento.ToString("dd-MM-yyyy") });

            return(response);
        }
Example #15
0
        private MiHomeDevice GetOrAddDeviceByCommand(ResponseCommand cmd)
        {
            if (_gateway != null && cmd.Sid == _gateway.Sid)
            {
                return(_gateway);
            }

            if (_devicesList.ContainsKey(cmd.Sid))
            {
                return(_devicesList[cmd.Sid]);
            }

            var device = _devicesMap[cmd.Model](cmd.Sid);

            if (_namesMap != null && _namesMap.ContainsKey(cmd.Sid))
            {
                device.Name = _namesMap[cmd.Sid];
            }

            if (cmd.Data != null)
            {
                device.ParseData(cmd.Data);
            }

            _devicesList.TryAdd(cmd.Sid, device);

            return(device);
        }
        public async Task <ResponseCommand> Handle(CreateUserCommand command)
        {
            var response = new ResponseCommand();

            command.Validate();
            if (command.Invalid)
            {
                response.AddNotifications(command.Notifications);
                return(response);
            }

            if (await _userRepository.UserExiste(command.Login) != null)
            {
                response.AddNotification(new Notification("Usuario", "Usuário já existe."));
                return(response);
            }

            var user = new Models.Usuario(command.Login, command.Senha);

            await _userRepository.Save(user);

            response.AddValue(new { Mensagem = "Usuário Cadastrado", Id = user.Id, Login = user.Login });

            return(response);
        }
Example #17
0
        private async Task StartReceivingMessagesAsync(CancellationToken ct)
        {
            // Receive messages
            while (!ct.IsCancellationRequested)
            {
                try
                {
                    var str = await _transport.ReceiveAsync().ConfigureAwait(false);

                    var respCmd = ResponseCommand.FromString(str);

                    if (LogRawCommands)
                    {
                        _logger?.LogInformation(str);
                    }

                    if (!_commandsToActions.TryGetValue(respCmd.Command, out var actionCommand))
                    {
                        _logger?.LogInformation($"Command '{respCmd.RawCommand}' is not a response command, skipping it");
                        continue;
                    }

                    actionCommand(respCmd);
                }
                catch (Exception e)
                {
                    _logger?.LogError(e, "Unexpected error");
                }
            }
        }
Example #18
0
        private void UpdateDevicesList(ResponseCommand cmd)
        {
            if (cmd.Model == "gateway")
            {
                return;                        // no need to add gateway to list of devices
            }
            var device = _devicesList.FirstOrDefault(x => x.Sid == cmd.Sid);

            if (device != null)
            {
                return;
            }

            device = _devicesMap[cmd.Model](cmd.Sid);

            if (_namesMap != null && _namesMap.ContainsKey(cmd.Sid))
            {
                device.Name = _namesMap[cmd.Sid];
            }

            if (cmd.Data != null)
            {
                device.ParseData(cmd.Data);
            }

            _devicesList.Add(device);
        }
Example #19
0
 public override void FinishStatesCallBack(Int32 message)
 {
     this.resCmd = (ResponseCommand)message;
     if (this.resCmd == ResponseCommand.RESPONSE_FINISH_GOBACK_FRONTLINE)
     {
     }
 }
Example #20
0
        public async Task <ResponseViewModel> UpdateAsync(UserUpdateRequestViewModel request)
        {
            using (_unitOfWork)
            {
                // Inicia a transação
                _unitOfWork.BeginTransaction();

                // Atualiza o Perfil
                ProfileUpdateCommand profileUpdateCommand  = new ProfileUpdateCommand(Convert.ToInt32(request.IdType), request.GuidProfile, request.Avatar, request.CpfCnpj, request.Address);
                ResponseCommand      profileUpdateResponse = await _mediator.Send(profileUpdateCommand, CancellationToken.None).ConfigureAwait(true);

                if (!profileUpdateResponse.Success)
                {
                    return(new ResponseViewModel(false, profileUpdateResponse.Object));
                }

                // Atualiza o Usuário
                UserUpdateCommand userUpdateCommand  = new UserUpdateCommand(request.GuidUser, request.Name, request.Email);
                ResponseCommand   userUpdateResponse = await _mediator.Send(userUpdateCommand, CancellationToken.None).ConfigureAwait(true);

                if (!userUpdateResponse.Success)
                {
                    return(new ResponseViewModel(false, userUpdateResponse.Object));
                }

                // Comita e Retorna
                _unitOfWork.CommitTransaction();
                return(new ResponseViewModel(true, "User updated"));
            }
        }
Example #21
0
        public async Task <ResponseViewModel> DeleteAsync(string guidUser, string guidProfile)
        {
            // Obs: Fiz pensando em ser um para um entre usuário e perfil, poderia ser um para muitos e ai neste caso não excluiria o perfil quando o usuário fosse excluido

            using (_unitOfWork)
            {
                // Inicia a transação
                _unitOfWork.BeginTransaction();

                // Remove o Usuário
                UserDeleteCommand userDeleteCommand = new UserDeleteCommand(guidUser);
                ResponseCommand   userAddResponse   = await _mediator.Send(userDeleteCommand, CancellationToken.None).ConfigureAwait(true);

                if (!userAddResponse.Success)
                {
                    return(new ResponseViewModel(false, userAddResponse.Object));
                }

                // Deleta o Perfil
                ProfileDeleteCommand profileDeleteCommand  = new ProfileDeleteCommand(guidProfile);
                ResponseCommand      profileDeleteResponse = await _mediator.Send(profileDeleteCommand, CancellationToken.None).ConfigureAwait(true);

                if (!profileDeleteResponse.Success)
                {
                    return(new ResponseViewModel(false, profileDeleteResponse.Object));
                }

                // Comita e Retorna
                _unitOfWork.CommitTransaction();
                return(new ResponseViewModel(true, "User deleted"));
            }
        }
        public void Check_SmokeSensor_Alarm_Event_Raised()
        {
            // Arrange
            var cmd = Helpers
                      .CreateCommand("report", "smoke", "158d0001d8f8f7", 25885,
                                     new Dictionary <string, object>
            {
                { "alarm", "0" },
            });

            // Act
            SmokeSensor device = _fixture.GetDeviceByCommand <SmokeSensor>(cmd);

            var alarmEventRaised = false;

            device.OnAlarm += (_, args) =>
            {
                alarmEventRaised = true;
            };

            var cmd1 = Helpers
                       .CreateCommand("report", "smoke", "158d0001d8f8f7", 25885,
                                      new Dictionary <string, object>
            {
                { "alarm", "1" },
            });

            device.ParseData(ResponseCommand.FromString(cmd1).Data);

            // Assert
            Assert.True(device.Alarm);
            Assert.True(alarmEventRaised);
        }
Example #23
0
        public void Send(ResponseCommand command)
        {
            UnityEngine.Debug.Assert(command != null, "command != null");
            UnityEngine.Debug.Assert(command.Recipient != null, $"command.Recipient != null, Type: {command.GetType().Name}");

            Send((Command)command);
        }
Example #24
0
        public void DadoUmComandoInvalidoDeveInterromperExecucao()
        {
            var             command = new CreateTodoCommand("", DateTime.Now, "");
            var             handle  = new TodoHandler(new FakeTodoRepository());
            ResponseCommand result  = (ResponseCommand)handle.Handle(command);

            Assert.AreEqual(result.Success, false);
        }
Example #25
0
 private void ProcessReport(ResponseCommand cmd)
 {
     if (_gateway != null && cmd.Sid == _gateway.Sid)
     {
         return;
     }
     GetOrAddDeviceByCommand(cmd).ParseData(cmd.Data);
 }
        public T GetDeviceByCommand <T>(string cmd) where T : MiHomeDevice
        {
            var respCmd = ResponseCommand.FromString(cmd);
            T   device  = MiHomeDeviceFactory.CreateByModel(respCmd.Model, respCmd.Sid) as T;

            device.ParseData(respCmd.Data);
            return(device);
        }
Example #27
0
        public void DadoUmComandoValidoDeveCriarTarefa()
        {
            var             command = new CreateTodoCommand("Titulo da Descrição", DateTime.Now, "Usuário");
            var             handle  = new TodoHandler(new FakeTodoRepository());
            ResponseCommand result  = (ResponseCommand)handle.Handle(command);

            Assert.AreEqual(result.Success, true);
        }
        public void Deve_Retornar_Mensagem_Sucesso()
        {
            ResponseCommand responseCommand = _anuncioHandler.Handle(_anuncioAdicionarCommand);

            Assert.IsTrue(Convert.ToInt32(responseCommand.Objeto) > 0);
            Assert.AreEqual(responseCommand.Sucesso, true);
            Assert.AreEqual(responseCommand.Mensagem, "Anuncio adicionado com sucesso");
        }
        public void CheckToken(string str, string token)
        {
            // Act
            var rcmd = ResponseCommand.FromString(str);

            // Assert
            Assert.Equal(token, rcmd.Token);
        }
Example #30
0
        public void Handle(SendTime message)
        {
            ResponseCommand command = new ResponseCommand();

            command.RequestId = message.RequestId;
            command.state     = StateCodes.ReceivedFromSaga;
            Bus.Send(command);
        }
        public virtual void LineEnableCallBack(Int32 message)
        {
            ResponseCommand resCmd = (ResponseCommand)message;

            if (resCmd == ResponseCommand.RESPONSE_START_DETECT_LINE && !robot.onFlagGoBackReady)
            {
                robot.SwitchToDetectLine(true);
            }
        }
Example #32
0
 public static bool VerifyChecksum(ResponseCommand command, string payload, string checksum)
 {
     var calculatedChecksum = GetChecksum(command.GetStringValue() + payload);
     return calculatedChecksum.Equals(checksum);
 }