Exemplo n.º 1
0
        public async Task ShouldUploadImageMultipartJson()
        {
            var client = _fixture.CreateClient();

            if (File.Exists("Image2.png"))
            {
                File.Delete("Image2.png");
            }

            using var fs = File.OpenRead("cybtan.png");


            var content = new MultipartFormDataContent("----WebKitFormBoundarymx2fSWqWSd0OxQq1");
            var json    = JsonConvert.SerializeObject(new { Size = fs.Length, Name = "Image2.png" });

            content.Add(new StringContent(json, Encoding.UTF8, "application/json"), "content");
            content.Add(new StreamContent(fs, (int)fs.Length), "Image", "Image.png");

            var response = await client.PostAsync("/api/order/upload", content);

            Assert.NotNull(response);
            Assert.True(response.IsSuccessStatusCode);

            var bytes = await response.Content.ReadAsByteArrayAsync();

            UploadImageResponse obj = BinaryConvert.Deserialize <UploadImageResponse>(bytes);

            fs.Seek(0, SeekOrigin.Begin);
            var hash = CryptoService.ToStringX2(new SymetricCryptoService().ComputeHash(fs));

            Assert.Equal(hash, obj.M5checksum);
        }
Exemplo n.º 2
0
        public void SerializeStream()
        {
            const int size       = 10 * 1024 * 1024;
            var       dataBuffer = CreateRandomBuffer(size);
            var       data       = new TestModel
            {
                Name   = "Test",
                Stream = new MemoryStream(dataBuffer)
            };

            var buffer = BinaryConvert.Serialize(data);

            Assert.NotNull(buffer);

            var result = BinaryConvert.Deserialize <TestModel>(buffer);

            Assert.Equal(result.Name, data.Name);
            Assert.NotNull(result.Stream);
            Assert.Equal(result.Stream.Length, size);

            var memory       = result.Stream as MemoryStream;
            var memoryBuffer = memory.ToArray();

            for (int i = 0; i < size; i++)
            {
                Assert.Equal(dataBuffer[i], memoryBuffer[i]);
            }
        }
Exemplo n.º 3
0
        public async Task <T> GetOrSet <T>(string key, Func <Task <T> > func, TimeSpan?expire = null)
            where T : class
        {
            T          cacheEntry;
            RedisValue entry = await _db.StringGetAsync(key).ConfigureAwait(false);

            if (!entry.HasValue)
            {
                cacheEntry = await func();

                if (cacheEntry == null)
                {
                    throw new InvalidOperationException($"Cache entry can not be null");
                }

                var bytes  = BinaryConvert.Serialize(cacheEntry);
                var result = await _db.StringSetAsync(key, bytes, expiry : expire).ConfigureAwait(false);

                if (!result)
                {
                    throw new InvalidOperationException("cache error");
                }

                return(cacheEntry);
            }

            return(BinaryConvert.Deserialize <T>(entry));
        }
Exemplo n.º 4
0
        public void BinarySerializeWithMetadataProvider()
        {
            var buffer = BinaryConvert.Serialize(_products);
            var result = BinaryConvert.Deserialize <List <Product> >(buffer);

            AssertProducts(result);
        }
Exemplo n.º 5
0
        public void BinarySerialize()
        {
            var buffer = BinaryConvert.Serialize(_modelA);
            var result = BinaryConvert.Deserialize <ModelA>(buffer);

            Assert(result);
        }
Exemplo n.º 6
0
        public async Task <T> Get <T>(string key)
            where T : class
        {
            RedisValue entry = await _db.StringGetAsync(key).ConfigureAwait(false);

            if (!entry.HasValue)
            {
                return(null);
            }

            return(BinaryConvert.Deserialize <T>(entry));
        }
Exemplo n.º 7
0
        public static ErrorInfo ToErrorInfo(this ApiException apiException)
        {
            ErrorInfo?result = null;

            if (apiException.Content != null)
            {
                if (apiException.ContentHeaders?.ContentType?.MediaType == BinarySerializer.MEDIA_TYPE)
                {
                    if (apiException.ContentHeaders.ContentType.CharSet == BinarySerializer.DefaultEncoding.WebName)
                    {
                        result = BinaryConvert.Deserialize <ValidationResult>(apiException.Content);
                    }
                    else
                    {
                        var encoding   = Encoding.GetEncoding(apiException.ContentHeaders.ContentType.CharSet);
                        var serializer = new BinarySerializer(encoding);
                        result = serializer.Deserialize <ValidationResult>(apiException.Content);
                    }
                }
                else if (IsJson(apiException.ContentHeaders?.ContentType?.MediaType))
                {
                    var encoding = apiException.ContentHeaders?.ContentType?.CharSet != null?
                                   Encoding.GetEncoding(apiException.ContentHeaders.ContentType.CharSet) :
                                       Encoding.UTF8;

                    var json = encoding.GetString(apiException.Content);
                    if (apiException.StatusCode == System.Net.HttpStatusCode.BadRequest)
                    {
                        var apiValidation = System.Text.Json.JsonSerializer.Deserialize <FluentValidationResult>(json);

                        result = new ValidationResult(apiValidation.title, apiValidation.errors)
                        {
                            ErrorCode = (int)apiException.StatusCode
                        };
                    }
                    else
                    {
                        result = System.Text.Json.JsonSerializer.Deserialize <ValidationResult>(json);
                    }
                }
            }

            if (result == null)
            {
                result = new ErrorInfo(apiException.Message)
                {
                    ErrorCode = (int)apiException.StatusCode
                };
            }

            return(result);
        }
Exemplo n.º 8
0
        private static ApiErrorInfo?ToErrorInfo(HttpStatusCode statusCode, HttpContentHeaders contentHeaders, byte[] content)
        {
            ApiErrorInfo?result = null;

            var contentType = contentHeaders.ContentType;

            if (content != null)
            {
                if (contentType?.MediaType == BinarySerializer.MEDIA_TYPE)
                {
                    if (contentHeaders.ContentType.CharSet == BinarySerializer.DefaultEncoding.WebName)
                    {
                        result = BinaryConvert.Deserialize <ApiErrorInfo>(content);
                    }
                    else
                    {
                        var encoding   = Encoding.GetEncoding(contentHeaders.ContentType.CharSet);
                        var serializer = new BinarySerializer(encoding);
                        result = serializer.Deserialize <ApiErrorInfo>(content);
                    }
                }
                else if (IsJson(contentType?.MediaType))
                {
                    var encoding = contentType?.CharSet != null?
                                   Encoding.GetEncoding(contentHeaders.ContentType.CharSet) :
                                       Encoding.UTF8;

                    var json = encoding.GetString(content);

                    if (statusCode == HttpStatusCode.BadRequest)
                    {
                        var apiValidation = System.Text.Json.JsonSerializer.Deserialize <JsonProblemResult>(json);

                        result = new ApiErrorInfo
                        {
                            ErrorMessage = apiValidation.title,
                            ErrorCode    = apiValidation.status,
                            Errors       = apiValidation.errors
                        };
                    }
                    else
                    {
                        result = System.Text.Json.JsonSerializer.Deserialize <ApiErrorInfo>(json);
                    }
                }
            }

            return(result);
        }
Exemplo n.º 9
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var response = await base.SendAsync(request, cancellationToken);

            if (!response.IsSuccessStatusCode)
            {
                if (response.Content != null)
                {
                    var bytes = await response.Content.ReadAsByteArrayAsync();

                    var errorInfo = BinaryConvert.Deserialize <ValidationResult>(bytes);
                    throw new ValidationException(errorInfo);
                }
            }

            return(response);
        }
        public void SerializeValidationResult()
        {
            var result = new ValidationResult("An error occurred while updating the entries. See the inner exception for details.\r\n----Inner Exception-- -\r\nSQLite Error 19: 'UNIQUE constraint failed: Ordes.Id'.\r\n")
            {
                StackTrace = "   at Cybtans.Entities.EntityFrameworkCore.EfUnitOfWork.SaveChangesAsyncInternal() in C:\\projects\\Cybtans\\cybtans-sdk\\CybtansSDK\\Cybtans.Entities.EntityFrameworkCore\\EfUnitOfWork.cs:line 122\r\n   at Cybtans.Entities.EntityFrameworkCore.EfUnitOfWork.SaveChangesAsync() in C:\\projects\\Cybtans\\cybtans-sdk\\CybtansSDK\\Cybtans.Entities.EntityFrameworkCore\\EfUnitOfWork.cs:line 143\r\n   at Cybtans.Entities.EventLog.EntityEventPublisher.PublishAll(IEnumerable`1 entityEvents) in C:\\projects\\Cybtans\\cybtans-sdk\\CybtansSDK\\Cybtans.Entities.EventLog\\EntityEventPublisher.cs:line 117\r\n   at Cybtans.Entities.EntityFrameworkCore.EfUnitOfWork.SaveChangesAsync() in C:\\projects\\Cybtans\\cybtans-sdk\\CybtansSDK\\Cybtans.Entities.EntityFrameworkCore\\EfUnitOfWork.cs:line 155\r\n   at Cybtans.Services.CrudService`8.Create(TEntityDto request) in C:\\projects\\Cybtans\\cybtans-sdk\\CybtansSDK\\Cybtans.Services\\CrudService.cs:line 339\r\n   at lambda_method(Closure , Object )\r\n   at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()\r\n   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)\r\n   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)\r\n   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)\r\n   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextExceptionFilterAsync>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)"
            };

            var bytes = BinaryConvert.Serialize(result);

            Assert.NotEmpty(bytes);

            var obj = BinaryConvert.Deserialize <ValidationResult>(bytes);

            Assert.NotNull(obj);
            Assert.NotEmpty(obj.ErrorMessage);
            Assert.NotEmpty(obj.StackTrace);
        }
Exemplo n.º 11
0
        public void SerializeTest()
        {
            ValidationResult result = new ValidationResult();

            result.AddError("Name", "Name is required");
            result.AddError("Name", "Name is not valid");
            result.AddError("Lastname", "LastName is required");

            var bytes = BinaryConvert.Serialize(result);

            result = BinaryConvert.Deserialize <ValidationResult>(bytes);
            Assert.True(result.HasErrors);
            Assert.Equal(2, result.Errors.Count);
            Assert.Equal(2, result.Errors["Name"].Count);
            Assert.Single(result.Errors["Lastname"]);

            Assert.Equal("Name is required", result.Errors["Name"][0]);
            Assert.Equal("Name is not valid", result.Errors["Name"][1]);

            Assert.Equal("LastName is required", result.Errors["Lastname"][0]);
        }