Пример #1
0
        public static StreamingRequest GetStreamingRequestWithAttachment(string conversationId)
        {
            var conId            = string.IsNullOrWhiteSpace(conversationId) ? Guid.NewGuid().ToString() : conversationId;
            var attachmentData   = "blah blah i am a stream!";
            var streamContent    = new MemoryStream(Encoding.UTF8.GetBytes(attachmentData));
            var attachmentStream = new AttachmentStream("botframework-stream", streamContent);

            var request = new StreamingRequest()
            {
                Verb = "POST",
                Path = $"/v3/directline/conversations/{conId}/activities",
            };
            var activity = new Schema.Activity()
            {
                Type       = "message",
                Text       = "hello",
                ServiceUrl = "urn:test:namedpipe:testPipes",
                From       = new Schema.ChannelAccount()
                {
                    Id   = "123",
                    Name = "Fred",
                },
                Conversation = new Schema.ConversationAccount(null, null, conId, null, null, null, null),
            };

            request.SetBody(activity);

            var contentStream = new StreamContent(attachmentStream.ContentStream);

            contentStream.Headers.TryAddWithoutValidation(HeaderNames.ContentType, attachmentStream.ContentType);
            request.AddStream(contentStream);

            return(request);
        }
        public async Task SendRequestAsync_WaitsTillAllDataSent()
        {
            var payLoadSender = new PayloadSender();
            var tcs           = new TaskCompletionSource <bool>();
            DisconnectedEventHandler eventHandler = (sender, args) =>
            {
                tcs.TrySetException(new Exception(args.Reason));
            };

            payLoadSender.Disconnected += eventHandler;
            payLoadSender.Connect(GetMockedTransportSender(tcs, TransportConstants.MaxPayloadLength * 4));
            var sendOperations = new SendOperations(payLoadSender);

            try
            {
                using (var stream = GetMockedStream(TransportConstants.MaxPayloadLength * 4))
                {
                    var request = new StreamingRequest();
                    request.AddStream(new StreamContent(stream));
                    await sendOperations.SendRequestAsync(Guid.NewGuid(), request);
                }

                await tcs.Task;
            }
            finally
            {
                payLoadSender.Disconnected -= eventHandler;
            }
        }
        public void Request_AddStream_Null_Throws()
        {
            var r = new StreamingRequest();

            Assert.ThrowsException <ArgumentNullException>(() =>
            {
                r.AddStream(null);
            });
        }
        public void Request_AddStream_Success()
        {
            var r = new StreamingRequest();
            var s = new StringContent("hi");

            r.AddStream(s);

            Assert.IsNotNull(r.Streams);
            Assert.AreEqual(1, r.Streams.Count);
            Assert.AreEqual(s, r.Streams[0].Content);
        }
        public async Task <ResourceResponse> UploadAttachmentsAsync(string conversationId, string userId, CancellationToken cancellationToken = default(CancellationToken), params AttachmentStream[] attachmentStreams)
        {
            if (SocketClient == null)
            {
                throw new InvalidOperationException("Connection is not opened.");
            }

            if (attachmentStreams == null || attachmentStreams.Length == 0)
            {
                throw new InvalidOperationException("Cannot send attachment streams, because no attachments were supplied.");
            }

            var request = new StreamingRequest()
            {
                Verb = "PUT",
                Path = $"/v3/directline/conversations/{conversationId}/users/{userId}/upload"
            };

            foreach (var stream in attachmentStreams)
            {
                var contentStream = new StreamContent(stream.ContentStream);
                contentStream.Headers.TryAddWithoutValidation(HeaderNames.ContentType, stream.ContentType);
                request.AddStream(contentStream);
            }

            var response = await SocketClient.SendAsync(request).ConfigureAwait(false);

            if (response.StatusCode != 200)
            {
                var body = await response.ReadBodyAsStringAsync().ConfigureAwait(false);

                var ex = new OperationException(
                    $"Operation returned an invalid status code '{response.StatusCode}'",
                    response.StatusCode,
                    body);
                throw ex;
            }

            var resourceResponse = await response.ReadBodyAsJsonAsync <ResourceResponse>().ConfigureAwait(false);

            return(resourceResponse);
        }
        public async Task <ResourceResponse> PostActivityAsync(string conversationId, Activity activity, CancellationToken cancellationToken = default(CancellationToken), params AttachmentStream[] attachmentStreams)
        {
            if (SocketClient == null)
            {
                throw new InvalidOperationException("Connection is not opened.");
            }

            var request = new StreamingRequest()
            {
                Verb = "POST",
                Path = $"/v3/directline/conversations/{conversationId}/activities"
            };

            request.SetBody(activity);

            if (attachmentStreams != null && attachmentStreams.Length > 0)
            {
                foreach (var stream in attachmentStreams)
                {
                    var contentStream = new StreamContent(stream.ContentStream);
                    contentStream.Headers.TryAddWithoutValidation(HeaderNames.ContentType, stream.ContentType);
                    request.AddStream(contentStream);
                }
            }

            var response = await SocketClient.SendAsync(request).ConfigureAwait(false);

            if (response.StatusCode != 200 && response.StatusCode != 204)
            {
                var body = await response.ReadBodyAsStringAsync().ConfigureAwait(false);

                var ex = new OperationException(
                    $"Operation returned an invalid status code '{response.StatusCode}'",
                    response.StatusCode,
                    body);
                throw ex;
            }

            var resourceResponse = await response.ReadBodyAsJsonAsync <ResourceResponse>().ConfigureAwait(false);

            return(resourceResponse);
        }
        public void Request_AddStream_ExistingList_Success()
        {
            var r  = new StreamingRequest();
            var s  = new StringContent("hi");
            var s2 = new StringContent("hello");

            r.Streams = new List <ResponseMessageStream> {
                new ResponseMessageStream()
                {
                    Content = s2
                }
            };

            r.AddStream(s);

            Assert.IsNotNull(r.Streams);
            Assert.AreEqual(2, r.Streams.Count);
            Assert.AreEqual(s2, r.Streams[0].Content);
            Assert.AreEqual(s, r.Streams[1].Content);
        }
Пример #8
0
        public async Task StreamingSession_SendRequest_ReceiveResponse(int streamLength, int streamCount, int chunkCount)
        {
            // Arrange
            var request = new StreamingRequest()
            {
                Verb    = "GET",
                Path    = "api/version",
                Streams = new List <ResponseMessageStream>()
            };

            request.AddStream(new StringContent("Hello human, I'm Bender!"));

            var requestHandler = new Mock <RequestHandler>();

            var requestCompletionSource = new TaskCompletionSource <bool>();

            requestHandler
            .Setup(r => r.ProcessRequestAsync(It.IsAny <ReceiveRequest>(), null, null, CancellationToken.None))
            .ReturnsAsync(() => new StreamingResponse()
            {
                StatusCode = 200
            })
            .Callback(() => requestCompletionSource.SetResult(true));

            var transportHandler = new Mock <TransportHandler>(new Mock <IDuplexPipe>().Object, NullLogger.Instance);

            var responseCompletionSource = new TaskCompletionSource <bool>();

            var transportHandlerSetup = transportHandler.Setup(t => t.SendRequestAsync(It.IsAny <Guid>(), It.IsAny <RequestModel>(), CancellationToken.None));

            var session = new StreamingSession(requestHandler.Object, transportHandler.Object, NullLogger.Instance);

            Header          responseHeader = null;
            ReceiveResponse response       = null;

            transportHandlerSetup.Callback(
                (Guid requestId, RequestModel requestPayload, CancellationToken cancellationToken) =>
            {
                responseHeader = new Header()
                {
                    Id = requestId, Type = PayloadTypes.Response
                };
                response = new ReceiveResponse()
                {
                    StatusCode = 200, Streams = StreamingDataGenerator.CreateStreams(requestId, streamLength, streamCount, chunkCount, PayloadTypes.Response)
                };

                session.ReceiveResponse(responseHeader, response);

                foreach (AugmentedStreamDefinition definition in response.Streams)
                {
                    var chunkList = definition.Chunks;

                    for (int i = 0; i < chunkCount; i++)
                    {
                        bool isLast = i == chunkCount - 1;

                        session.ReceiveStream(
                            new Header()
                        {
                            End = isLast, Id = definition.Id, PayloadLength = chunkList[i].Length, Type = PayloadTypes.Stream
                        },
                            chunkList[i]);
                    }
                }
            });

            // Act

            var responseTask        = session.SendRequestAsync(request, CancellationToken.None);
            var responseWithTimeout = await Task.WhenAny(responseTask, Task.Delay(TimeSpan.FromSeconds(5)));

            // Assert
            Assert.Equal(responseTask, responseWithTimeout);

            var receivedResponse = await responseTask;

            Assert.Equal(response.StatusCode, receivedResponse.StatusCode);
            Assert.Equal(response.Streams.Count, receivedResponse.Streams.Count);

            Assert.True(response.Streams.SequenceEqual(receivedResponse.Streams));
        }