//[Fact]
        public async void ShouldBeSerialized()
        {
            var mockHttp = new MockHttpMessageHandler();

            mockHttp.When(HttpMethod.Post, "http://local.sketch7.io:5000/api/heroes/azmodan")
            .Respond("application/json", "{ 'name': 'Azmodan', 'title': 'Lord of Sin' }");

            var fluentHttpClientFactory = ServiceTestUtil.GetNewClientFactory();

            fluentHttpClientFactory.CreateBuilder("sketch7")
            .WithBaseUrl("http://local.sketch7.io:5000")
            .Register();

            var httpClient     = fluentHttpClientFactory.Get("sketch7");
            var requestBuilder = httpClient.CreateRequest("/api/heroes/azmodan");
            var response       = await requestBuilder.ReturnAsResponse();

            var serializer = new HttpResponseSerializer();
            var message    = await serializer.Serialize <HttpResponseStore>(response);

            Assert.Equal("http://local.sketch7.io:5000/api/heroes/azmodan", message.Url);

            var response2 = await serializer.Deserialize(message);

            var hero = await response2.Content.ReadAsAsync <Hero>();

            Assert.NotNull(hero);
            Assert.Equal("Lord of Sin", hero.Title);
            Assert.Equal(HttpStatusCode.OK, response2.StatusCode);
            Assert.Equal(response.Headers.Count(), response2.Headers.Count());
            Assert.Equal(response.Message.RequestMessage.RequestUri.ToString(), response2.Message.RequestMessage.RequestUri.ToString());
        }
        public void Http_SerializeHttpRequest()
        {
            var request  = new HttpRequest();
            var response = new HttpResponse
            {
                StatusCode = HttpStatusCode.BadRequest,
                Body       = Encoding.UTF8.GetBytes("{\"text\":1234}"),
                MimeType   = MimeTypeProvider.PlainText
            };

            response.Headers["A"] = 1.ToString();
            response.Headers["B"] = "x";

            var serializer     = new HttpResponseSerializer();
            var buffer         = serializer.SerializeResponse(new HttpContext(request, response));
            var requiredBuffer = Convert.FromBase64String("SFRUUC8xLjEgNDAwIEJhZFJlcXVlc3QNCkE6MQ0KQjp4DQpDb250ZW50LVR5cGU6dGV4dC9wbGFpbjsgY2hhcnNldD11dGYtOA0KQ29udGVudC1MZW5ndGg6MTMNCg0KeyJ0ZXh0IjoxMjM0fQ==");

            Assert.IsTrue(buffer.SequenceEqual(requiredBuffer));
        }
Esempio n. 3
0
        public void Serialize_HttpRequest()
        {
            var request = new HttpRequest(HttpMethod.Get, "", new Version(1, 1), "", new HttpHeaderCollection(), "", 0);

            var response = new HttpResponse();

            response.StatusCode   = HttpStatusCode.BadRequest;
            response.Body         = new PlainTextBody().WithContent("{\"text\":1234}");
            response.Headers["A"] = 1.ToString();
            response.Headers["B"] = "x";

            var serializer = new HttpResponseSerializer();

            byte[] buffer         = serializer.SerializeResponse(new HttpContext(request, response));
            byte[] requiredBuffer = { 72, 84, 84, 80, 47, 49, 46, 49, 32, 52, 48, 48, 32, 66, 97, 100, 32, 82, 101, 113, 117, 101, 115, 116, 13, 10, 65, 58, 49, 13, 10, 66, 58, 120, 13, 10, 67, 111, 110, 116, 101, 110, 116, 45, 84, 121, 112, 101, 58, 116, 101, 120, 116, 47, 112, 108, 97, 105, 110, 59, 32, 99, 104, 97, 114, 115, 101, 116, 61, 117, 116, 102, 45, 56, 13, 10, 67, 111, 110, 116, 101, 110, 116, 45, 76, 101, 110, 103, 116, 104, 58, 49, 51, 13, 10, 13, 10, 123, 34, 116, 101, 120, 116, 34, 58, 49, 50, 51, 52, 125 };

            bool matching = buffer.SequenceEqual(requiredBuffer);

            matching.ShouldBeEquivalentTo(true);
        }
Esempio n. 4
0
        private async Task ExecuteCommand(TargetId id, IServiceProvider services, CommandInfo commandInfo, TasksMachineStatus status, Guid executionId, CancellationToken cancellationToken)
        {
            var executorType = _executorTypes[commandInfo];

            if (executorType == null)
            {
                return;
            }

            var service = services.GetService(executorType);

            if (service == null)
            {
                return;
            }

            var commandName   = commandInfo.GetType().Name.TrimEnd("CommandInfo", StringComparison.Ordinal);
            var commandResult = new CommandResultDto
            {
                CommandResultId = Guid.NewGuid(),
                TaskExecutionId = executionId,
                CommandName     = commandName
            };

            var commandProcessDto = new CommandProcessDto
            {
                CommandResultId = commandResult.CommandResultId, TaskExecutionId = executionId, CommandName = commandName
            };

            Task UpdateStatus(CommandProcessDto arg)
            {
                commandProcessDto.StatusMessage = arg.StatusMessage;
                commandProcessDto.Progress      = arg.Progress;

                return(_hubContext.Clients.All.SendAsync(HubEventNames.TaskCommandProcess, commandProcessDto, cancellationToken));
            }

            var executionMethod = _executionMethods[executorType];

            status.Processes.TryAdd(commandProcessDto.CommandResultId, commandProcessDto);
            try
            {
                using (var context = new DefaultTaskExecutionContext(_taskSession, _mazeTask, services, UpdateStatus))
                {
                    context.ReportProgress(null); //important to notify about the start of the operation

                    var task = (Task <HttpResponseMessage>)executionMethod.Invoke(service,
                                                                                  new object[] { commandInfo, id, context, cancellationToken });
                    var response = await task;

                    using (var memoryStream = new MemoryStream())
                    {
                        await HttpResponseSerializer.Format(response, memoryStream);

                        commandResult.Result = Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
                        commandResult.Status = (int)response.StatusCode;
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogWarning(e, "An error occurred when executing {method}", executorType.FullName);
                commandResult.Result = e.ToString();
            }
            finally
            {
                status.Processes.TryRemove(commandProcessDto.CommandResultId, out _);
            }

            commandResult.FinishedAt = DateTimeOffset.UtcNow;

            try
            {
                await _taskResultStorage.CreateCommandResult(commandResult);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Executing CreateCommandResult failed.");
            }

            await _hubContext.Clients.All.SendAsync(HubEventNames.TaskCommandResultCreated, commandResult);
        }