public async Task ProcessGetActionShouldSucceed()
        {
            // Arrange
            var command = new Command()
            {
                Id     = EnvelopeId.NewId(),
                Method = CommandMethod.Get,
                Uri    = new LimeUri("/ping")
            };

            var settings = JObject.FromObject(command, LimeSerializerContainer.Serializer);

            var variable = "responseBody";

            settings.TryAdd(nameof(variable), variable);

            var target = GetTarget();

            var responseCommand = new Command()
            {
                Method   = CommandMethod.Get,
                Status   = CommandStatus.Success,
                Resource = new JsonDocument()
            };

            BlipClient.ProcessCommandAsync(Arg.Any <Command>(), Arg.Any <CancellationToken>()).Returns(responseCommand);

            // Act
            await target.ExecuteAsync(Context, settings, CancellationToken);

            // Assert
            await BlipClient.Received(1).ProcessCommandAsync(Arg.Is <Command>(c => c.Uri.Equals(command.Uri)), Arg.Any <CancellationToken>());

            await Context.Received(1).SetVariableAsync(variable, JsonConvert.SerializeObject(responseCommand, LimeSerializerContainer.Serializer.Converters.ToArray()), Arg.Any <CancellationToken>());
        }
Ejemplo n.º 2
0
        public async Task <bool> HasRecipientAsync(string listName, Identity recipientIdentity, CancellationToken cancellationToken = new CancellationToken())
        {
            var listIdentity = GetListIdentity(listName);

            if (recipientIdentity == null)
            {
                throw new ArgumentNullException(nameof(recipientIdentity));
            }

            var requestCommand = new Command()
            {
                Id     = EnvelopeId.NewId(),
                To     = DistributionListAddress,
                Method = CommandMethod.Get,
                Uri    = new LimeUri($"/lists/{Uri.EscapeDataString(listIdentity.ToString())}/recipients/{Uri.EscapeDataString(recipientIdentity.ToString())}")
            };

            try
            {
                await ProcessCommandAsync(requestCommand, cancellationToken);

                return(true);
            }
            catch (LimeException ex) when(ex.Reason.Code == ReasonCodes.COMMAND_RESOURCE_NOT_FOUND)
            {
                return(false);
            }
        }
Ejemplo n.º 3
0
        public async Task NegotiateSessionAsync_NegotiatingState_CallsTransportAndReadsFromBuffer()
        {
            var target = GetTarget(EnvelopeId.NewId(), state: SessionState.Negotiating);

            var cancellationToken = Dummy.CreateCancellationToken();
            var compression       = SessionCompression.GZip;
            var encryption        = SessionEncryption.TLS;

            var session = Dummy.CreateSession(SessionState.Negotiating);

            session.Id = target.SessionId;

            _transport
            .Setup(t => t.ReceiveAsync(It.IsAny <CancellationToken>()))
            .Returns(() => Task.FromResult <Envelope>(session))
            .Verifiable();

            var actualSession = await target.NegotiateSessionAsync(compression, encryption, cancellationToken);

            _transport.Verify(
                t => t.SendAsync(It.Is <Session>(
                                     e => e.State == SessionState.Negotiating &&
                                     e.Id == target.SessionId &&
                                     e.Compression == compression &&
                                     e.Encryption == encryption),
                                 It.IsAny <CancellationToken>()),
                Times.Once());

            Assert.AreEqual(session, actualSession);
        }
        public async Task OnStateChanged_MultiplePendingMessagesAndRegisteredToNewChannel_SendsToNewChannel()
        {
            // Arrange
            var messageStorage = new MemoryMessageStorage();
            var messages       = new List <Message>();

            for (int i = 0; i < Dummy.CreateRandomInt(100) + 1; i++)
            {
                var message = Dummy.CreateMessage(Dummy.CreateTextContent());
                message.Id = EnvelopeId.NewId();
                messages.Add(message);
            }
            var target1      = GetTarget(messageStorage: messageStorage);
            var channel2Mock = CreateChannel(_channel.Object.LocalNode, _channel.Object.RemoteNode);

            // Act
            var actuals = new List <Message>();

            foreach (var message in messages)
            {
                var actual = await((IChannelModule <Message>)target1).OnSendingAsync(message, _cancellationToken);
                actuals.Add(actual);
            }
            target1.OnStateChanged(SessionState.Finished);
            var target2 = GetTarget(messageStorage: messageStorage, channel: channel2Mock);
            await Task.Delay(_resendMessageIntervalWithSafeMargin);

            // Assert
            foreach (var message in messages)
            {
                actuals.ShouldContain(message);
                _channel.Verify(c => c.SendMessageAsync(message, It.IsAny <CancellationToken>()), Times.Never);
                channel2Mock.Verify(c => c.SendMessageAsync(message, It.IsAny <CancellationToken>()), Times.Once);
            }
        }
Ejemplo n.º 5
0
        public async Task ProcessAsync_SessionCloseHeader_FinishTransport()
        {
            // Arrange
            var session = new Session()
            {
                Id    = EnvelopeId.NewId(),
                State = SessionState.Established
            };

            EmulatedTransport
            .Setup(e => e.GetSessionAsync(It.IsAny <CancellationToken>()))
            .ReturnsAsync(session);

            Processor1HttpRequest.Headers.Add(Constants.SESSION_HEADER, Constants.CLOSE_HEADER_VALUE);

            var processorResponse = new HttpResponse(Processor1HttpRequest.CorrelatorId, HttpStatusCode.OK);

            Processor1
            .Setup(p => p.ProcessAsync(Processor1HttpRequest, It.IsAny <UriTemplateMatch>(), It.IsAny <ITransportSession>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(processorResponse)
            .Verifiable();

            // Act
            await Target.StartAsync();

            HttpServerRequestBuffer.Post(Processor1HttpRequest);

            // Assert
            var actualResponse = await HttpServerResponse;

            Processor1.Verify();
            actualResponse.ShouldBe(processorResponse);
            EmulatedTransport.Verify(t => t.FinishAsync(It.IsAny <CancellationToken>()), Times.Once());
            HttpTransportProvider.Verify(h => h.GetTransport(Principal.Object, false), Times.Once());
        }
        public async Task SendAsync_FullSessionNegotiationWithTlsUpgrade_ShouldSucceed()
        {
            // Arrange
            ServerCertificate = CertificateUtil.GetOrCreateSelfSignedCertificate("localhost");
            ServerCertificateValidationCallback   = (sender, certificate, chain, errors) => true;
            var(clientTransport, serverTransport) = await GetAndOpenTargetsAsync();

            var clientChannel = new ClientChannel(clientTransport, TimeSpan.FromSeconds(30));
            var serverChannel = new ServerChannel(EnvelopeId.NewId(), "*****@*****.**", serverTransport, TimeSpan.FromSeconds(30));

            // Act
            var clientEstablishmentTask = clientChannel.EstablishSessionAsync(
                c => SessionCompression.None,
                e => SessionEncryption.TLS,
                "*****@*****.**",
                (schemes, authentication) => new GuestAuthentication(),
                EnvelopeId.NewId(),
                CancellationToken);
            var serverEstablishmentTask = serverChannel.EstablishSessionAsync(
                serverTransport.GetSupportedCompression(),
                serverTransport.GetSupportedEncryption(),
                new[] { AuthenticationScheme.Guest },
                (i, am, cancellationToken) => new AuthenticationResult(DomainRole.Member).AsCompletedTask(),
                (_, __, ___) => Task.FromResult(Node.Parse("[email protected]/instance")),
                CancellationToken);
            await Task.WhenAll(clientEstablishmentTask, serverEstablishmentTask);

            // Assert
            serverTransport.Encryption.ShouldBe(SessionEncryption.TLS);
            clientTransport.Encryption.ShouldBe(SessionEncryption.TLS);
            var session = await clientEstablishmentTask;

            session.State.ShouldBe(SessionState.Established);
        }
        public async Task OnSending_MultipleMessagesWithoutNotification_ShouldResendUntilLimit()
        {
            // Arrange
            var messages = new List <Message>();

            for (int i = 0; i < Dummy.CreateRandomInt(100) + 1; i++)
            {
                var message = Dummy.CreateMessage(Dummy.CreateTextContent());
                message.Id = EnvelopeId.NewId();
                messages.Add(message);
            }
            var target = GetTarget();

            // Act
            var actuals = new List <Message>();

            foreach (var message in messages)
            {
                var actual = await((IChannelModule <Message>)target).OnSendingAsync(message, _cancellationToken);
                actuals.Add(actual);
            }
            await Task.Delay(ResendLimit);

            // Assert
            foreach (var message in messages)
            {
                actuals.ShouldContain(message);
                _channel.Verify(c => c.SendMessageAsync(message, It.IsAny <CancellationToken>()), Times.Exactly(_resendMessageTryCount));
            }
        }
 public UserOwnerResolverTests()
 {
     TunnelExtension     = Substitute.For <ITunnelExtension>();
     UserIdentity        = new Identity("user", "domain");
     ApplicationIdentity = new Identity("application", "domain");
     Application         = new Application()
     {
         Identifier = ApplicationIdentity.Name,
         Domain     = ApplicationIdentity.Domain
     };
     Message = new Message()
     {
         From = UserIdentity.ToNode(),
         To   = ApplicationIdentity.ToNode()
     };
     BuilderConfiguration = new BuilderConfiguration();
     TunnelIdentity       = new Identity(EnvelopeId.NewId(), Take.Blip.Client.Extensions.Tunnel.TunnelExtension.TunnelAddress.Domain);
     TunnelOwner          = new Identity("owner", "domain");
     TunnelExtension
     .GetTunnelAsync(TunnelIdentity, CancellationToken)
     .Returns(new Tunnel()
     {
         Owner       = TunnelOwner,
         Originator  = UserIdentity.ToNode(),
         Destination = ApplicationIdentity
     });
 }
        public async Task SetupAsync()
        {
            _cancellationToken = TimeSpan.FromSeconds(10).ToCancellationToken();

            _clientTransport = new FakeTransport();
            _serverTransport = new FakeTransport();
            _serverTransport.ReceiveBuffer = _clientTransport.SendBuffer;
            _clientTransport.ReceiveBuffer = _serverTransport.SendBuffer;

            _sendTimeout   = TimeSpan.FromSeconds(60);
            _clientChannel = new ClientChannel(_clientTransport, _sendTimeout);
            _serverChannel = new ServerChannel(EnvelopeId.NewId(), Dummy.CreateNode(), _serverTransport, _sendTimeout);

            var clientEstablishSessionTask = Task.Run(() =>
                                                      _clientChannel.EstablishSessionAsync(
                                                          c => c[0],
                                                          e => e[0],
                                                          Dummy.CreateIdentity(),
                                                          (s, a) => new GuestAuthentication(),
                                                          Environment.MachineName,
                                                          _cancellationToken),
                                                      _cancellationToken);

            await Task.WhenAll(
                _serverChannel.EstablishSessionAsync(
                    new [] { SessionCompression.None, },
                    new [] { SessionEncryption.None },
                    new [] { AuthenticationScheme.Guest },
                    (i, authentication, cancellationToken) => new AuthenticationResult(DomainRole.Member).AsCompletedTask(),
                    (_, __, ___) => Task.FromResult(Dummy.CreateNode()),
                    _cancellationToken),
                clientEstablishSessionTask);
        }
        public async Task GetFromNonTunnelSenderShouldReturnNull()
        {
            // Arrange
            Message.From     = new Node(EnvelopeId.NewId(), "not.tunnel.net", "instance");
            Message.Metadata = new Dictionary <string, string>
            {
                { Take.Blip.Client.Extensions.Tunnel.TunnelExtension.TUNNEL_OWNER_METADATA_KEY, Owner },
                { Take.Blip.Client.Extensions.Tunnel.TunnelExtension.TUNNEL_ORIGINATOR_METADATA_KEY, Originator }
            };

            var target = GetTarget();

            // Act
            var actualOriginator = await target.GetVariableAsync("originator", Context, CancellationToken);

            var actualOwner = await target.GetVariableAsync("owner", Context, CancellationToken);

            var actualDestination = await target.GetVariableAsync("destination", Context, CancellationToken);

            var actualIdentity = await target.GetVariableAsync("identity", Context, CancellationToken);

            // Assert
            actualOriginator.ShouldBeNull();
            actualOwner.ShouldBeNull();
            actualDestination.ShouldBeNull();
            actualIdentity.ShouldBeNull();
        }
 public TunnelVariableProviderTests()
 {
     TunnelExtension      = Substitute.For <ITunnelExtension>();
     BuilderConfiguration = new BuilderConfiguration();
     Message      = new Message();
     UserIdentity = new Identity("user", "msging.net");
     LazyInput    = new LazyInput(
         Message,
         UserIdentity,
         BuilderConfiguration,
         Substitute.For <IDocumentSerializer>(),
         Substitute.For <IEnvelopeSerializer>(),
         Substitute.For <IArtificialIntelligenceExtension>(),
         CancellationToken);
     Context.Input.Returns(LazyInput);
     Owner               = new Identity("owner", "msging.net");
     Originator          = new Node("originator", "msging.net", "instance");
     TunnelIdentity      = new Identity(EnvelopeId.NewId(), Take.Blip.Client.Extensions.Tunnel.TunnelExtension.TunnelAddress.Domain);
     ApplicationIdentity = new Identity("application", "msging.net");
     Message.To          = ApplicationIdentity.ToNode();
     Tunnel              = new Tunnel()
     {
         Owner       = Owner,
         Originator  = Originator,
         Destination = ApplicationIdentity
     };
 }
        public async Task SetAndGetContactUnitTest(string authKey)
        {
            var id       = EnvelopeId.NewId();
            var identity = Identity.Parse($"{id}[email protected]");

            Command setResponse;
            Contact getResponse;

            var contact = new Contact
            {
                Name     = id,
                Identity = identity
            };

            if (authKey.Equals(""))
            {
                setResponse = await _contactService.SetAsync(contact, CancellationToken.None, _logger);

                getResponse = await _contactService.GetAsync(identity, CancellationToken.None, _logger);
            }
            else
            {
                var contactService = new ContactService(authKey);
                setResponse = await contactService.SetAsync(contact, CancellationToken.None, _logger);

                getResponse = await contactService.GetAsync(identity, CancellationToken.None, _logger);
            }

            setResponse.Status.ShouldBe(CommandStatus.Success);

            getResponse.ShouldNotBeNull();
            getResponse.Name.ShouldBe(id);
            getResponse.Identity.ShouldBe(identity);
            getResponse.GetMediaType().ToString().ShouldBe("application/vnd.lime.contact+json");
        }
Ejemplo n.º 13
0
        public async Task Unbind_MultiplePendingMessagesAndBoundToNewChannel_SendsToBoundChannel()
        {
            // Arrange
            var messages = new List <Message>();

            for (int i = 0; i < Dummy.CreateRandomInt(100) + 1; i++)
            {
                var message = Dummy.CreateMessage(Dummy.CreateTextContent());
                message.Id = EnvelopeId.NewId();
                messages.Add(message);
            }
            var target       = GetTarget();
            var channel2Mock = CreateChannel();

            // Act
            var actuals = new List <Message>();

            foreach (var message in messages)
            {
                var actual = await((IChannelModule <Message>)target).OnSendingAsync(message, _cancellationToken);
                actuals.Add(actual);
            }
            target.Unbind();
            target.Bind(channel2Mock.Object, true);
            await Task.Delay(_resendMessageIntervalWithSafeMargin);

            // Assert
            foreach (var message in messages)
            {
                actuals.ShouldContain(message);
                _channel.Verify(c => c.SendMessageAsync(message, It.IsAny <CancellationToken>()), Times.Never);
                channel2Mock.Verify(c => c.SendMessageAsync(message, It.IsAny <CancellationToken>()), Times.Once);
            }
        }
Ejemplo n.º 14
0
        public async Task AddQuestions(string intentId, Question[] questions)
        {
            if (questions == null)
            {
                throw new ArgumentNullException(nameof(questions));
            }

            try
            {
                var command = new Command
                {
                    Id       = EnvelopeId.NewId(),
                    To       = Node.Parse("*****@*****.**"),
                    Uri      = new LimeUri(Uri.EscapeUriString($"/intentions/{intentId}/questions")),
                    Method   = CommandMethod.Set,
                    Resource = new DocumentCollection
                    {
                        ItemType = Question.MediaType,
                        Items    = questions
                    }
                };

                var envelopeResult = await RunCommandAsync(command);

                EnsureCommandSuccess(envelopeResult);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
                throw;
            }
        }
Ejemplo n.º 15
0
        public Task SetVariableAsync <T>(Identity identity, string variableName, T document, CancellationToken cancellationToken,
                                         TimeSpan expiration = default(TimeSpan)) where T : Document
        {
            if (identity == null)
            {
                throw new ArgumentNullException(nameof(identity));
            }
            if (variableName == null)
            {
                throw new ArgumentNullException(nameof(variableName));
            }
            if (document == null)
            {
                throw new ArgumentNullException(nameof(document));
            }

            var uriPath = GetVariableRequestUri(identity, variableName);

            uriPath = AppendExpiration <T>(uriPath, expiration);

            var requestCommand = CreateSetCommandRequest(
                document,
                uriPath,
                id: $"disposable:{EnvelopeId.NewId()}"
                );

            return(ProcessCommandAsync(requestCommand, cancellationToken));
        }
        public async Task <DocumentCollection> GetAllDocumentKeysAsync(BucketNamespace bucketNamespace = BucketNamespace.Document)
        {
            string @namespace = GetNamespaceAsString(bucketNamespace);

            try
            {
                var command = new Command
                {
                    Id     = EnvelopeId.NewId(),
                    To     = Node.Parse("*****@*****.**"),
                    Uri    = new LimeUri($"/{@namespace}/"),
                    Method = CommandMethod.Get
                };

                var envelopeResult = await RunCommandAsync(command);

                return(envelopeResult.Resource as DocumentCollection);
            }
            catch (HttpRequestException e)
            {
                _logger.LogError(e, "\nException Caught!");
                _logger.LogError(e, "Message :{0} ", e.Message);
                return(null);
            }
        }
Ejemplo n.º 17
0
        public async Task ExecuteAsync(IContext context, JObject settings, CancellationToken cancellationToken)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings), $"The settings are required for '{nameof(ProcessCommandAction)}' action");
            }

            string variable = null;

            if (settings.TryGetValue(nameof(variable), out var variableToken))
            {
                variable = variableToken.ToString().Trim('"');
            }

            var command = settings.ToObject <Command>(LimeSerializerContainer.Serializer);

            command.Id = EnvelopeId.NewId();

            var resultCommand = await _sender.ProcessCommandAsync(command, cancellationToken);

            if (string.IsNullOrWhiteSpace(variable))
            {
                return;
            }

            var resultCommandJson = _envelopeSerializer.Serialize(resultCommand);
            await context.SetVariableAsync(variable, resultCommandJson, cancellationToken);
        }
        public async Task <string> AddEntity(Entity entity)
        {
            try
            {
                var command = new Command
                {
                    Id       = EnvelopeId.NewId(),
                    To       = Node.Parse("*****@*****.**"),
                    Uri      = new LimeUri("/entities"),
                    Method   = CommandMethod.Set,
                    Resource = new Entity
                    {
                        Name   = entity.Name,
                        Values = entity.Values
                    }
                };
                var envelopeResult = await RunCommandAsync(command);

                EnsureCommandSuccess(envelopeResult);

                var createdEntity = envelopeResult.Resource as Entity;
                return(createdEntity.Id);
            }
            catch (HttpRequestException e)
            {
                _logger.LogError(e, "\nException Caught!");
                _logger.LogError(e, "Message :{0} ", e.Message);
                return(null);
            }
        }
        protected override async Task FillEnvelopeAsync(Command envelope, HttpRequest request)
        {
            CommandMethod method;

            if (TryConvertToCommandMethod(request.Method, out method))
            {
                var limeUriFragment = request.Uri.Segments.Except(_exceptUriSegments).Aggregate((s1, s2) => s1 + s2);
                if (!string.IsNullOrWhiteSpace(limeUriFragment))
                {
                    if (envelope.Id.IsNullOrEmpty())
                    {
                        envelope.Id = EnvelopeId.NewId();
                    }
                    envelope.Method = method;
                    envelope.Uri    = new LimeUri(limeUriFragment);

                    if (envelope.Method == CommandMethod.Set ||
                        envelope.Method == CommandMethod.Observe)
                    {
                        envelope.Resource = await ParseDocumentAsync(request).ConfigureAwait(false);
                    }
                }
                else
                {
                    throw new LimeException(ReasonCodes.VALIDATION_INVALID_URI, "Invalid command URI");
                }
            }
            else
            {
                throw new LimeException(ReasonCodes.VALIDATION_INVALID_METHOD, "Invalid method");
            }
        }
        public async Task <string> AddIntent(string intentName, bool verbose = false)
        {
            try
            {
                var command = new Command
                {
                    Id       = EnvelopeId.NewId(),
                    To       = Node.Parse("*****@*****.**"),
                    Uri      = new LimeUri("/intentions"),
                    Method   = CommandMethod.Set,
                    Resource = new Intention
                    {
                        Name = intentName,
                    }
                };

                var envelopeResult = await RunCommandAsync(command);

                if (envelopeResult.Status == CommandStatus.Success)
                {
                    var createdIntention = envelopeResult.Resource as Intention;
                    return(createdIntention.Id);
                }

                LogVerboseLine($"{intentName}: {envelopeResult.Status} - {envelopeResult.Reason.Code} = {envelopeResult.Reason.Description}");
                return(null);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "\nException Caught!");
                _logger.LogError(e, "Message: {0} ", e.Message);
                return(null);
            }
        }
        public async Task OnSending_ReceivedNotificationAfterSecondResend_ShouldNotResendAgain()
        {
            // Arrange
            var message = Dummy.CreateMessage(Dummy.CreateTextContent());

            message.Id = EnvelopeId.NewId();
            var notification = Dummy.CreateNotification(Event.Received);

            notification.Id   = message.Id;
            notification.From = message.To;
            var channel   = CreateChannel();
            var target    = GetTarget(channel: channel);
            var callCount = 0;

            channel
            .Setup(c => c.SendMessageAsync(It.IsAny <Message>(), It.IsAny <CancellationToken>()))
            .Returns((Message m, CancellationToken c) => ((IChannelModule <Message>)target).OnSendingAsync(m, _cancellationToken))
            .Callback(async(Message m, CancellationToken c) =>
            {
                callCount++;
                if (callCount == 2)
                {
                    await((IChannelModule <Notification>)target).OnReceivingAsync(notification, _cancellationToken);
                }
            });


            // Act
            var actual = await((IChannelModule <Message>)target).OnSendingAsync(message, _cancellationToken);
            await Task.Delay(ResendLimit);

            // Assert
            actual.ShouldBe(message);
            channel.Verify(c => c.SendMessageAsync(message, It.IsAny <CancellationToken>()), Times.Exactly(2));
        }
        public async Task AddAnswers(string intentId, Answer[] answers)
        {
            if (answers == null)
            {
                throw new ArgumentNullException(nameof(answers));
            }

            try
            {
                var command = new Command
                {
                    Id       = EnvelopeId.NewId(),
                    To       = Node.Parse("*****@*****.**"),
                    Uri      = new LimeUri(Uri.EscapeUriString($"/intentions/{intentId}/answers")),
                    Method   = CommandMethod.Set,
                    Resource = new DocumentCollection
                    {
                        ItemType = Answer.MediaType,
                        Items    = answers
                    }
                };

                var envelopeResult = await RunCommandAsync(command);

                EnsureCommandSuccess(envelopeResult);
            }
            catch (HttpRequestException e)
            {
                _logger.LogError(e, "\nException Caught!");
                _logger.LogError(e, "Message :{0} ", e.Message);
                throw;
            }
        }
Ejemplo n.º 23
0
        public async Task ProcessAsync_InvalidSessionAuthentication_ReturnsUnauthorized()
        {
            // Arrange
            var session = new Session()
            {
                Id     = EnvelopeId.NewId().ToString(),
                State  = SessionState.Failed,
                Reason = new Reason()
                {
                    Code        = ReasonCodes.SESSION_AUTHENTICATION_FAILED,
                    Description = Dummy.CreateRandomString(50)
                }
            };

            EmulatedTransport
            .Setup(e => e.GetSessionAsync(It.IsAny <CancellationToken>()))
            .ReturnsAsync(session);

            // Act
            await Target.StartAsync();

            HttpServerRequestBuffer.Post(Processor1HttpRequest);

            // Assert
            var actualResponse = await HttpServerResponse;

            actualResponse.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
            actualResponse.StatusDescription.ShouldBe(session.Reason.Description);
        }
        public async Task <AnalysisResponse> AnalyseForMetrics(string analysisRequest)
        {
            if (analysisRequest == null)
            {
                throw new ArgumentNullException(nameof(analysisRequest));
            }

            try
            {
                var command = new Command
                {
                    Id       = EnvelopeId.NewId(),
                    To       = Node.Parse("*****@*****.**"),
                    Uri      = new LimeUri("/analysis"),
                    Method   = CommandMethod.Set,
                    Resource = new AnalysisRequest
                    {
                        TestingRequest = true,
                        Text           = analysisRequest
                    }
                };

                var envelopeResult = await RunCommandAsync(command);

                return(envelopeResult.Resource as AnalysisResponse);
            }
            catch (HttpRequestException e)
            {
                _logger.LogError(e, "\nException Caught!");
                _logger.LogError(e, "Message :{0} ", e.Message);
                return(null);
            }
        }
        public async Task ReceiveAsync(Message message, CancellationToken cancellationToken)
        {
            var receivedLocation = message.Content as Location;

            var textDocument = new PlainText {
                Text = "Um instante... ⏳ Estou procurando os postos, ${contact.name}."
            };

            var textMessage = new Message
            {
                To       = message.From,
                Content  = textDocument,
                Id       = EnvelopeId.NewId(),
                Metadata = new Dictionary <string, string>
                {
                    { "#message.replaceVariables", "true" }
                }
            };

            await _sender.SendMessageAsync(textMessage, cancellationToken);

            //Get GasStations
            var carousel = await _gasStationService.GetNearGasStationsAsync(receivedLocation);

            //Carousel with near gas stations
            textDocument.Text = "Pronto!Os postos próximos são esses aqui: ⬅️➡️";
            await _sender.SendMessageAsync(textDocument, message.From, cancellationToken);

            await _sender.SendMessageAsync(carousel, message.From, cancellationToken);
        }
        public async Task <KeyValuePair <string, Document>?> GetDocumentAsync(string key, BucketNamespace bucketNamespace)
        {
            try
            {
                string @namespace = GetNamespaceAsString(bucketNamespace);

                var pairsCollection = new List <KeyValuePair <string, Document> >();

                var command = new Command
                {
                    Id     = EnvelopeId.NewId(),
                    To     = Node.Parse("*****@*****.**"),
                    Uri    = new LimeUri($"/{@namespace}/{key}"),
                    Method = CommandMethod.Get
                };

                var envelopeResult = await RunCommandAsync(command);

                var document = envelopeResult.Resource;

                var value = new KeyValuePair <string, Document>(key.ToString(), document);

                return(value);
            }
            catch (HttpRequestException e)
            {
                _logger.LogError(e, "\nException Caught!");
                _logger.LogError(e, "Message :{0} ", e.Message);
                return(null);
            }
        }
Ejemplo n.º 27
0
        public override async Task ExecuteAsync(IContext context, SendMessageFromHttpSettings settings, CancellationToken cancellationToken)
        {
            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, settings.Uri);

            if (settings.Headers != null)
            {
                foreach (var header in settings.Headers)
                {
                    httpRequestMessage.Headers.TryAddWithoutValidation(header.Key, header.Value);
                }
            }
            else
            {
                httpRequestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(settings.Type));
            }

            using (var cts = new CancellationTokenSource(settings.RequestTimeout ?? DefaultRequestTimeout))
                using (var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, cts.Token))
                    using (var httpResponseMessage = await _httpClient.SendAsync(httpRequestMessage, linkedCts.Token).ConfigureAwait(false))
                    {
                        httpResponseMessage.EnsureSuccessStatusCode();

                        var body = await httpResponseMessage.Content.ReadAsStringAsync();

                        var message = new Message(EnvelopeId.NewId())
                        {
                            Id      = EnvelopeId.NewId(),
                            To      = context.Input.Message.From,
                            Content = _documentSerializer.Deserialize(body, settings.MediaType)
                        };

                        await _sender.SendMessageAsync(message, cancellationToken);
                    }
        }
        public async Task AddDocumentAsync(string key, Document document, BucketNamespace bucketNamespace = BucketNamespace.Document)
        {
            try
            {
                string @namespace = GetNamespaceAsString(bucketNamespace);

                var command = new Command
                {
                    Id       = EnvelopeId.NewId(),
                    To       = Node.Parse("*****@*****.**"),
                    Uri      = new LimeUri($"/{@namespace}/{key}"),
                    Method   = CommandMethod.Set,
                    Resource = document
                };

                var envelopeResult = await RunCommandAsync(command);

                EnsureCommandSuccess(envelopeResult);
            }
            catch (HttpRequestException e)
            {
                _logger.LogError(e, "\nException Caught!");
                _logger.LogError(e, "Message :{0} ", e.Message);
            }
        }
Ejemplo n.º 29
0
        public async Task AuthenticateSessionAsync_AuthenticatingState_CallsTransportAndReadsFromTransport()
        {
            var target = GetTarget(sessionId: EnvelopeId.NewId(), state: SessionState.Authenticating);

            var cancellationToken = Dummy.CreateCancellationToken();
            var localIdentity     = Dummy.CreateIdentity();
            var localInstance     = Dummy.CreateInstanceName();
            var authentication    = Dummy.CreateAuthentication(Security.AuthenticationScheme.Plain);

            var session = Dummy.CreateSession(SessionState.Established);

            session.Id = target.SessionId;

            var tcs = new TaskCompletionSource <Envelope>();

            _transport
            .SetupSequence(t => t.ReceiveAsync(It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult <Envelope>(session))
            .Returns(tcs.Task);

            var actualSession = await target.AuthenticateSessionAsync(localIdentity, authentication, localInstance, cancellationToken);

            _transport.Verify(
                t => t.SendAsync(It.Is <Session>(
                                     e => e.State == SessionState.Authenticating &&
                                     e.Id == target.SessionId &&
                                     e.From.ToIdentity().Equals(localIdentity) &&
                                     e.From.Instance.Equals(localInstance) &&
                                     e.Authentication == authentication),
                                 It.IsAny <CancellationToken>()),
                Times.Once());

            Assert.AreEqual(session, actualSession);
        }
        public async Task SendCommand_SingleCommand_ShouldWriteOnResponseStream()
        {
            // Arrange
            var message = new Command()
            {
                Id       = EnvelopeId.NewId(),
                Method   = CommandMethod.Set,
                Uri      = "/greeting",
                Resource = "Hello world"
            };
            var target = GetTarget();

            // Act
            await target.SendCommandAsync(message, CancellationTokenSource.Token);

            // Assert
            ResponseBody.Position.ShouldBePositive();
            ResponseBody.Position = 0;
            using var reader      = new StreamReader(ResponseBody, Encoding.UTF8);
            var json = await reader.ReadToEndAsync();

            var actualEnvelope = EnvelopeSerializer.Deserialize(json);
            var actualCommand  = actualEnvelope.ShouldBeOfType <Command>();

            actualCommand.Id.ShouldBe(message.Id);
            actualCommand.Method.ShouldBe(message.Method);
            actualCommand.Uri.ShouldBe(message.Uri);
            actualCommand.Type.ShouldBe(message.Type);
            actualCommand.Resource.ToString().ShouldBe(message.Resource.ToString());
        }