示例#1
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]);
            }
        }
示例#2
0
        public async Task ShouldUploadImageMultipartBinary()
        {
            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 bytes = BinaryConvert.Serialize(new { Size = fs.Length, Name = "Image2.png" });

            var byteArrayContent = new ByteArrayContent(bytes);

            byteArrayContent.Headers.ContentType = MediaTypeHeaderValue.Parse($"{BinarySerializer.MEDIA_TYPE}; charset={BinarySerializer.DefaultEncoding.WebName}");

            content.Add(byteArrayContent);
            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);
        }
示例#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));
        }
示例#4
0
        public void BinarySerializeWithMetadataProvider()
        {
            var buffer = BinaryConvert.Serialize(_products);
            var result = BinaryConvert.Deserialize <List <Product> >(buffer);

            AssertProducts(result);
        }
示例#5
0
        public void BinarySerialize()
        {
            var buffer = BinaryConvert.Serialize(_modelA);
            var result = BinaryConvert.Deserialize <ModelA>(buffer);

            Assert(result);
        }
示例#6
0
        public async Task Set(string key, object item, TimeSpan?expire = null)
        {
            var bytes  = BinaryConvert.Serialize(item);
            var result = await _db.StringSetAsync(key, bytes, expiry : expire).ConfigureAwait(false);

            if (!result)
            {
                throw new InvalidOperationException("cache error");
            }
        }
示例#7
0
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var response = new HttpResponseMessage
            {
                Content = new ByteArrayContent(BinaryConvert.Serialize(new Customer
                {
                    Id   = Guid.NewGuid(),
                    Name = ""
                })),
                StatusCode = System.Net.HttpStatusCode.OK
            };

            response.Content.Headers.ContentType = new MediaTypeHeaderValue(BinarySerializer.MEDIA_TYPE);
            return(Task.FromResult(response));
        }
示例#8
0
        public async Task Publish(object message, string?exchange, string?topic)
        {
            if (exchange == null || topic == null)
            {
                Type type    = message.GetType();
                var  binding = _subscriptionManager.GetBindingForType(type, exchange, topic);
                if (binding == null)
                {
                    throw new QueuePublishException($"Exchange not found for {message.GetType()}", message);
                }
                exchange = binding.Exchange;
                topic    = binding.Topic;
            }

            var data = BinaryConvert.Serialize(message);
            await _subscriptionManager.HandleMessage(exchange, topic, data).ConfigureAwait(false);
        }
        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);
        }
示例#10
0
        public Task Publish(object message, string?exchange, string?topic)
        {
            if (exchange == null || topic == null)
            {
                Type type    = message.GetType();
                var  binding = _subscriptionManager.GetBindingForType(type, exchange, topic);
                if (binding == null)
                {
                    throw new QueuePublishException($"Exchange not found for {message.GetType()}", message);
                }
                exchange = binding.Exchange;
                topic    = binding.Topic;
            }

            var bytes = BinaryConvert.Serialize(message);

            return(Task.Run(() => PublishInternal(exchange, topic, bytes)));
        }
        private async Task <EntityEventLog> PublishInternal(EntityEvent entityEvent)
        {
            entityEvent.CreateTime = DateTime.Now;
            var type = entityEvent.GetType();

            var            data = EntityUtilities.ToDictionary(entityEvent);
            EntityEventLog log  = new EntityEventLog
            {
                CreateTime      = DateTime.Now,
                Data            = BinaryConvert.Serialize(data),
                EntityEventType = type.FullName,
                State           = EventStateEnum.NotPublished
            };

            entityEvent.State = EventStateEnum.NotPublished;
            var binding = _messageQueue.GetBinding(type, entityEvent.Topic);

            if (binding == null)
            {
                throw new QueuePublishException($"Bindindg information not found for {type}");
            }

            log.Exchange = binding.Exchange;
            log.Topic    = binding.Topic;

            try
            {
                entityEvent.State = EventStateEnum.Published;
                log.State         = EventStateEnum.Published;

                await _messageQueue.Publish(log.Data, binding.Exchange, binding.Topic).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                entityEvent.State = EventStateEnum.NotPublished;
                log.State         = EventStateEnum.NotPublished;
                log.ErrorMessage  = ex.Message;

                _logger?.LogError(ex, $"Unable to publish event {type.Name} Exchange:{log.Exchange} Topic:{log.Topic}");
            }

            return(log);
        }
示例#12
0
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            HttpResponseMessage response;

            if (request.Headers.Authorization != null && request.Headers.Authorization.Parameter == null)
            {
                response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                {
                    ReasonPhrase   = "Access Token Expired",
                    RequestMessage = request,
                };
            }
            else
            {
                _retry++;
                if (_retry >= 3)
                {
                    var data = new GetAllOrderStateResponse
                    {
                        Items = Enumerable.Range(1, 100).Select(x => new OrderStateDto {
                            Id = x, Name = $"{x}"
                        }).ToList(),
                        Page       = 0,
                        TotalCount = 100,
                        TotalPages = 1
                    };
                    response         = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
                    response.Content = new ByteArrayContent(BinaryConvert.Serialize(data));
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue(BinarySerializer.MEDIA_TYPE);
                }
                else
                {
                    response = new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized)
                    {
                        ReasonPhrase   = "Access Token Expired",
                        RequestMessage = request,
                    };
                }
            }

            return(Task.FromResult(response));
        }
示例#13
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]);
        }
 private async Task HandleExceptionAsync(HttpContext context, Exception exception)
 {
     if (context.Request.Headers.ContainsKey("Accept") && context.Request.Headers["Accept"].FirstOrDefault() == BinarySerializer.MEDIA_TYPE)
     {
         context.Response.ContentType = BinarySerializer.MEDIA_TYPE;
         context.Response.StatusCode  = (int)HttpStatusCode.InternalServerError;
         await context.Response.BodyWriter.WriteAsync(BinaryConvert.Serialize(
                                                          new
         {
             context.Response.StatusCode,
             Message = $"Internal Server Error {exception.Message}",
         }));
     }
     else
     {
         context.Response.ContentType = "application/json";
         context.Response.StatusCode  = (int)HttpStatusCode.InternalServerError;
         await context.Response.WriteAsync(System.Text.Json.JsonSerializer.Serialize(new
         {
             context.Response.StatusCode,
             Message = $"Internal Server Error {exception.Message}",
         }));
     }
 }