public void LookupIsCaseInsensitive()
        {
            // Arrange
            var modelState = new ModelStateDictionary();
            modelState.AddModelError("key1", "x");

            // Act
            var serializableError = new SerializableError(modelState);

            // Assert
            var arr = Assert.IsType<string[]>(serializableError["KEY1"]);
            Assert.Equal("x", arr[0]);
        }
Ejemplo n.º 2
0
        public void WriteXml_WritesValidXml()
        {
            // Arrange
            var modelState = new ModelStateDictionary();
            modelState.AddModelError("key1", "Test Error 1");
            modelState.AddModelError("key1", "Test Error 2");
            modelState.AddModelError("key2", "Test Error 3");
            var serializableError = new SerializableError(modelState);
            var outputStream = new MemoryStream();

            // Act
            using (var xmlWriter = XmlWriter.Create(outputStream))
            {
                var dataContractSerializer = new DataContractSerializer(typeof(SerializableErrorWrapper));
                dataContractSerializer.WriteObject(xmlWriter, new SerializableErrorWrapper(serializableError));
            }
            outputStream.Position = 0;
            var res = new StreamReader(outputStream, Encoding.UTF8).ReadToEnd();

            // Assert
            var expectedContent =
                TestPlatformHelper.IsMono ?
                    "<?xml version=\"1.0\" encoding=\"utf-8\"?><Error xmlns:i=\"" +
                    "http://www.w3.org/2001/XMLSchema-instance\"><key1>Test Error 1 Test Error 2</key1>" +
                    "<key2>Test Error 3</key2></Error>" :
                    "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                    "<Error><key1>Test Error 1 Test Error 2</key1><key2>Test Error 3</key2></Error>";

            Assert.Equal(expectedContent, res);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SerializableErrorWrapper"/> class.
        /// </summary>
        /// <param name="error">The <see cref="SerializableError"/> object that needs to be wrapped.</param>
        public SerializableErrorWrapper(SerializableError error)
        {
            if (error == null)
            {
                throw new ArgumentNullException(nameof(error));
            }

            SerializableError = error;
        }
Ejemplo n.º 4
0
        public void DoesNotThrowOn_EmptyCollections_WrappableElementTypes()
        {
            // Arrange
            var errors = new SerializableError[] { };
            var delegatingEnumerable = new DelegatingEnumerable<SerializableErrorWrapper, SerializableError>(
                                                    errors, new SerializableErrorWrapperProvider());

            // Act and Assert
            Assert.Empty(delegatingEnumerable);
        }
        public void ConvertsModelState_To_Dictionary_AddsDefaultValuesWhenErrorsAreAbsent()
        {
            // Arrange
            var modelState = new ModelStateDictionary();
            modelState.AddModelError("key1", "");

            // Act
            var serializableError = new SerializableError(modelState);

            // Assert
            var arr = Assert.IsType<string[]>(serializableError["key1"]);
            Assert.Equal("The input was not valid.", arr[0]);
        }
Ejemplo n.º 6
0
        public IEnumerable<SerializableError> SerializableErrors()
        {
            List<SerializableError> errors = new List<SerializableError>();
            var error1 = new SerializableError();
            error1.Add("key1", "key1-error");
            error1.Add("key2", "key2-error");

            var error2 = new SerializableError();
            error2.Add("key3", "key1-error");
            error2.Add("key4", "key2-error");
            errors.Add(error1);
            errors.Add(error2);
            return errors;
        }
        public void Wraps_SerializableErrorInstance()
        {
            // Arrange
            var wrapperProvider = new SerializableErrorWrapperProvider();
            var serializableError = new SerializableError();

            // Act
            var wrapped = wrapperProvider.Wrap(serializableError);

            // Assert
            Assert.NotNull(wrapped);
            var errorWrapper = wrapped as SerializableErrorWrapper;
            Assert.NotNull(errorWrapper);
            Assert.Same(serializableError, errorWrapper.SerializableError);
        }
        public void WrappedSerializableErrorInstance_ReturnedFromProperty()
        {
            // Arrange
            var serializableError = new SerializableError();
            serializableError.Add("key1", "key1-error");

            // Act
            var wrapper = new SerializableErrorWrapper(serializableError);

            // Assert
            Assert.NotNull(wrapper.SerializableError);
            Assert.Same(serializableError, wrapper.SerializableError);
            Assert.Equal(1, wrapper.SerializableError.Count);
            Assert.True(wrapper.SerializableError.ContainsKey("key1"));
            Assert.Equal("key1-error", wrapper.SerializableError["key1"]);
        }
        public void DoesNotAddEntries_IfNoErrorsArePresent()
        {
            // Arrange
            var modelState = new ModelStateDictionary();
            modelState.Add(
                "key1",
                new ModelState() { Value = new ValueProviderResult("foo", "foo", CultureInfo.InvariantCulture) });
            modelState.Add(
                "key2",
                new ModelState() { Value = new ValueProviderResult("bar", "bar", CultureInfo.InvariantCulture) });

            // Act
            var serializableError = new SerializableError(modelState);

            // Assert
            Assert.Equal(0, serializableError.Count);
        }
Ejemplo n.º 10
0
        public void ConvertsModelState_To_Dictionary()
        {
            // Arrange
            var modelState = new ModelStateDictionary();
            modelState.AddModelError("key1", "Test Error 1");
            modelState.AddModelError("key1", "Test Error 2");
            modelState.AddModelError("key2", "Test Error 3");

            // Act
            var serializableError = new SerializableError(modelState);

            // Assert
            var arr = Assert.IsType<string[]>(serializableError["key1"]);
            Assert.Equal("Test Error 1", arr[0]);
            Assert.Equal("Test Error 2", arr[1]);
            Assert.Equal("Test Error 3", (serializableError["key2"] as string[])[0]);
        }
Ejemplo n.º 11
0
        public void DoesNotAddEntries_IfNoErrorsArePresent()
        {
            // Arrange
            var modelState = new ModelStateDictionary();
            modelState.Add(
                "key1",
                new ModelStateEntry());
            modelState.Add(
                "key2",
                new ModelStateEntry());

            // Act
            var serializableError = new SerializableError(modelState);

            // Assert
            Assert.Equal(0, serializableError.Count);
        }
Ejemplo n.º 12
0
        public void UpdateUserWithModelErrorReturnsValidationErrorMessage()
        {
            var userDTO = new UserDTO();
            // Arrange
            var            serviceMoq     = new Mock <IUserService>();
            UserController userController = new UserController(serviceMoq.Object, AutomapperSingleton.Mapper);

            userController.ModelState.AddModelError("Name", "Required");

            // Act
            BadRequestObjectResult result = (BadRequestObjectResult)userController.UpdateUser(userDTO);

            // Assert
            Assert.IsType <BadRequestObjectResult>(result);
            SerializableError errorMessages = (SerializableError)result.Value;

            Assert.Equal("Required", ((string[])errorMessages["Name"])[0]);
        }
Ejemplo n.º 13
0
        public void WrappedSerializableErrorInstance_ReturnedFromProperty()
        {
            // Arrange
            var serializableError = new SerializableError
            {
                { "key1", "key1-error" }
            };

            // Act
            var wrapper = new SerializableErrorWrapper(serializableError);

            // Assert
            Assert.NotNull(wrapper.SerializableError);
            Assert.Same(serializableError, wrapper.SerializableError);
            Assert.Single(wrapper.SerializableError);
            Assert.True(wrapper.SerializableError.ContainsKey("key1"));
            Assert.Equal("key1-error", wrapper.SerializableError["key1"]);
        }
Ejemplo n.º 14
0
        public void UpdateOrder_Fail_InvalidModelState()
        {
            // Setup Fixtures.
            const string key          = "key";
            const string errorMessage = TestValues.ExceptionMessage;

            // Execute SUT.
            this._sut.ModelState.AddModelError(key, errorMessage);
            IActionResult result = this._sut.UpdateOrder(null, TestValues.OrderUpdateDto);

            // Verify Results.
            BadRequestObjectResult badRequestResult = Assert.IsType <BadRequestObjectResult>(result);
            SerializableError      error            = Assert.IsType <SerializableError>(badRequestResult.Value);

            Assert.Single(error);
            string[] messages = Assert.IsType <string[]>(error[key]);
            Assert.Single(messages);
            Assert.Equal(errorMessage, messages[0]);
        }
Ejemplo n.º 15
0
    public void ConvertsModelState_To_Dictionary()
    {
        // Arrange
        var modelState = new ModelStateDictionary();

        modelState.AddModelError("key1", "Test Error 1");
        modelState.AddModelError("key1", "Test Error 2");
        modelState.AddModelError("key2", "Test Error 3");

        // Act
        var serializableError = new SerializableError(modelState);

        // Assert
        var arr = Assert.IsType <string[]>(serializableError["key1"]);

        Assert.Equal("Test Error 1", arr[0]);
        Assert.Equal("Test Error 2", arr[1]);
        Assert.Equal("Test Error 3", (serializableError["key2"] as string[])[0]);
    }
Ejemplo n.º 16
0
        public static ODataError CreateODataError(this SerializableError serializableError, bool isDevelopment)
        {
            var convertedError = SerializableErrorExtensions.CreateODataError(serializableError);
            var error          = new ODataError();

            if (isDevelopment)
            {
                error = convertedError;
            }
            else
            {
                error.Message = DefaultODataErrorMessage;
                error.Details = new[] { new ODataErrorDetail {
                                            Message = convertedError.Message
                                        } };
            }

            return(error);
        }
Ejemplo n.º 17
0
        public async Task GetPayment_ReturnsBadRequestObjectResult_WhenInvalidModelStateReturned()
        {
            // Arrange

            Guid id = Guid.NewGuid();

            PaymentRespModel paymentRespModel = null;

            ModelStateDictionary modelStateDictionary = new ModelStateDictionary();

            modelStateDictionary.AddModelError("UnitTest", "Error");

            mockPaymentManager.Setup(s => s.GetAsync(It.IsAny <Guid>(), It.IsAny <ModelStateDictionary>()))
            .Returns(Task.FromResult <(PaymentRespModel, ModelStateDictionary)>((paymentRespModel, modelStateDictionary)))
            .Verifiable();

            // Act

            ActionResult actionResult = await paymentController.Get(id) as ActionResult;

            // Assert

            Assert.IsNotNull(actionResult);
            Assert.IsInstanceOf <BadRequestObjectResult>(actionResult);

            BadRequestObjectResult badRequestObjectResult = actionResult as BadRequestObjectResult;

            Assert.IsNotNull(badRequestObjectResult);
            Assert.AreEqual(StatusCodes.Status400BadRequest, badRequestObjectResult.StatusCode);

            Assert.IsNotNull(badRequestObjectResult.Value);
            Assert.IsInstanceOf <SerializableError>(badRequestObjectResult.Value);

            SerializableError serializableError = badRequestObjectResult.Value as SerializableError;

            Assert.IsNotNull(serializableError);

            Assert.AreEqual(1, serializableError.Keys.Count());
            Assert.IsTrue(serializableError.ContainsKey("UnitTest"));

            mockPaymentManager.Verify(v => v.GetAsync(It.IsAny <Guid>(), It.IsAny <ModelStateDictionary>()));
        }
        public void CreateODataError_Creates_ODataError_UsingModelStateDictionary()
        {
            // Arrange & Act & Assert
            ModelStateDictionary modelState = new ModelStateDictionary();

            modelState.AddModelError("key1", "Test Error 1");
            modelState.AddModelError("key1", "Test Error 2");
            modelState.AddModelError("key3", "Test Error 3");
            SerializableError serializableError = new SerializableError(modelState);

            // Act
            ODataError error = SerializableErrorExtensions.CreateODataError(serializableError);

            // Assert
            Assert.NotNull(error);
            Assert.Equal("key1:\r\nTest Error 1\r\nTest Error 2\r\n\r\nkey3:\r\nTest Error 3", error.Message);
            Assert.Null(error.ErrorCode);
            Assert.Null(error.InnerError);
            Assert.Equal(3, error.Details.Count);
        }
Ejemplo n.º 19
0
 // This method gets called by the runtime. Use this method to add services to the container.
 // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
 public void ConfigureServices(IServiceCollection services)
 {
     // Applicatioin Services
     services.AddScoped <IAccountRepository, AccountRepository>();
     services.AddControllers();
     // Model validation error response
     services.Configure <ApiBehaviorOptions>(options =>
     {
         options.InvalidModelStateResponseFactory = context =>
         {
             var errors = new SerializableError(context.ModelState);
             var result = new UnprocessableEntityObjectResult(new { errors });
             return(result);
         };
     });
     // Register Swagger generator.
     services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo {
             Title = "Thought.API", Version = "v1"
         }); });
 }
Ejemplo n.º 20
0
        public async Task PostCategory_ReturnsBadRequestResult400_WhenModelStateIsInvalid()
        {
            //ARRANGE:  Alle methodes opgeroepen in de controller, moeten gemocked worden .

            //1. Aanmaak nieuwe DTO onnodig -> model voert validatie uit

            //2. Mocking van controller en alle controller methodes ()
            mockCategoryRepo.Setup(repo => repo.Create(It.IsAny <Category>()))
            //.Returns(Task.FromResult(mapper.ConvertTo_Entity(newTask, ref newTaskEntity))) //cutomised mapper
            .Returns(Task.FromResult(mapper.Map <CategoryEditCreateDTO, Category>(new CategoryEditCreateDTO())));
            var APIcontroller = new CategoriesController(mockCategoryRepo.Object, mockRepo.Object, mapper, null, memoryCache, null);

            //3. controleer of mockRepo opgeroepen werd;
            mockCategoryRepo.Verify();

            //ACT : controller oproepen met model error (must)
            APIcontroller.ModelState.AddModelError("CategoryName", "Required");

            var actionResult = await APIcontroller.PostCategory(new CategoryEditCreateDTO());

            var badReqObjResult = (BadRequestObjectResult)actionResult.Result;
            //BAdRequest(ModelState) kan geserializeerd worden.
            SerializableError badReqError = badReqObjResult.Value as SerializableError;

            //var JsonString = JsonConvert.SerializeObject(badReqError);

            //ASSERT
            Assert.IsInstanceOfType(badReqObjResult, typeof(BadRequestObjectResult));
            Assert.IsInstanceOfType(((BadRequestObjectResult)badReqObjResult).Value, typeof(SerializableError));
            Assert.AreEqual(400, badReqObjResult.StatusCode);
            //omzetten naar string[] om index te kunnen gebruiken
            Assert.AreEqual(((string[])badReqError["CategoryName"])[0], "Required");
            //alternatief: for lus
            foreach (var error in badReqError)
            {
                if (error.Key == "CategoryName")
                {
                    Assert.AreEqual(((string[])error.Value)[0], "Required");
                }
            }
        }
Ejemplo n.º 21
0
        public static SerializableError CreateSerializableErrorFromModelState(this ODataController controller)
        {
            // https://source.dot.net/#Microsoft.AspNetCore.Mvc.Core/SerializableError.cs,19bc9a1c61ce7ae0
            var serializableError = new SerializableError();

            foreach (var keyModelStatePair in controller.ModelState)
            {
                var key    = keyModelStatePair.Key;
                var errors = keyModelStatePair.Value.Errors;
                if (errors != null && errors.Count > 0)
                {
                    var errorMessages = errors.Select(error =>
                    {
                        return(string.IsNullOrEmpty(error.ErrorMessage) ? "The input was not valid." : error.ErrorMessage);
                    }).ToArray();

                    serializableError.Add(key, errorMessages);

                    foreach (var error in errors)
                    {
                        if (error.Exception != null)
                        {
                            // Add more error details.
                            // e.g.
                            // ```
                            // One or more errors occurred. (
                            //  One or more errors occurred. (
                            //   A null value was found for the property named 'UnitPrice', which has the expected type 'Edm.Decimal[Nullable=False]'.
                            //   The expected type 'Edm.Decimal[Nullable=False]' does not allow null values.
                            //  )
                            // )
                            // ```
                            serializableError.Add("MessageDetail", error.Exception.Message);
                        }
                    }
                }
            }

            return(serializableError);
        }
Ejemplo n.º 22
0
        public static ODataError CreateODataError(this SerializableError serializableError, bool isDevelopment)
        {
            // ReSharper disable once InvokeAsExtensionMethod
            var convertedError = SerializableErrorExtensions.CreateODataError(serializableError);
            var error          = new ODataError();

            if (isDevelopment)
            {
                error = convertedError;
            }
            else
            {
                // Sanitise the exposed data when in release mode.
                // We do not want to give the public access to stack traces, etc!
                error.Message = DefaultODataErrorMessage;
                error.Details = new[] { new ODataErrorDetail {
                                            Message = convertedError.Message
                                        } };
            }

            return(error);
        }
        public void CreateODataError_Creates_AdvancedODataError()
        {
            // Arrange & Act & Assert
            ModelStateDictionary modelState = new ModelStateDictionary();

            modelState.AddModelError("key1", "Test Error 1");
            SerializableError serializableError = new SerializableError(modelState);

            serializableError["ErrorCode"]        = "Error Code 1";
            serializableError["Message"]          = "Error Message 1";
            serializableError["ExceptionMessage"] = "Error ExceptionMessage 1";

            // Act
            ODataError error = SerializableErrorExtensions.CreateODataError(serializableError);

            // Assert
            Assert.NotNull(error);
            Assert.Equal("Error Message 1", error.Message);
            Assert.Equal("Error Code 1", error.ErrorCode);
            Assert.Equal("Error ExceptionMessage 1", error.InnerError.Message);
            Assert.Single(error.Details);
        }
Ejemplo n.º 24
0
 public void OnResultExecuting(ResultExecutingContext context)
 {
     if (context.Result is BadRequestObjectResult)
     {
         BadRequestObjectResult res = (BadRequestObjectResult)context.Result;
         SerializableError      obj = res.Value as SerializableError;
         StringBuilder          sb  = new StringBuilder();
         foreach (var item in obj)
         {
             var vals = item.Value as string[];
             if (vals != null)
             {
                 sb.AppendLine(vals[0]);
             }
         }
         context.Result = new JsonResult(new { Code = -3, Message = sb.ToString() })
         {
             StatusCode = 200
         };
         return;
     }
 }
Ejemplo n.º 25
0
        public async Task CanValidateModelFields_UpdateVehicle_ModelAndFeaturesDoNotExistInDb()
        {
            SaveVehicleResource vehicleResource = new SaveVehicleResource {
                Contact = new ContacResource {
                    Name  = "Person",
                    Email = "*****@*****.**",
                    Phone = "2222222"
                },
                LastUpdate   = DateTime.Now,
                IsRegistered = true,
                ModelId      = 1,
                Features     = new List <int> {
                    3, 5, 7, 9
                }
            };

            _vehiclesRepository.Setup(db => db.GetWithDependenciesAsync(123)).ReturnsAsync(_vehicleWithId123);
            _vehiclesRepository.Setup(db => db.IsModelExists(1)).ReturnsAsync(false);
            _vehiclesRepository.Setup(db => db.IsFeatureExists(It.IsInRange(5, 7, Range.Inclusive))).ReturnsAsync(true);
            _vehiclesRepository.Setup(db => db.IsFeatureExists(3)).ReturnsAsync(false);
            _vehiclesRepository.Setup(db => db.IsFeatureExists(9)).ReturnsAsync(false);

            IActionResult actual = await _controller.UpdateVehicleAsync(123, vehicleResource);

            _vehiclesRepository.Verify(db => db.GetWithDependenciesAsync(123), Times.Once);
            _vehiclesRepository.Verify(db => db.IsModelExists(1), Times.Once);
            _vehiclesRepository.Verify(db => db.IsFeatureExists(It.IsAny <int>()), Times.Exactly(4));
            _unitOfWork.Verify(u => u.CompeleteAsync(), Times.Never);

            Assert.IsInstanceOf <BadRequestObjectResult>(actual);
            BadRequestObjectResult result    = actual as BadRequestObjectResult;
            SerializableError      errorList = result?.Value as SerializableError;

            Assert.IsNotNull(errorList);
            Assert.AreEqual(2, errorList.Count);
            CollectionAssert.AreEqual(new[] { "Cannot find model with Id = 1" }, errorList["ModelId"] as string[]);
            CollectionAssert.AreEqual(new[] { "Cannot find feature with Id = 3", "Cannot find feature with Id = 9" }, errorList["Features"] as string[]);
        }
Ejemplo n.º 26
0
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            if (context.Result is ErrorableActionResult actionResult)
            {
                if (!actionResult.Result.Success)
                {
                    var localizer = context.HttpContext.RequestServices.GetRequiredService <IStringLocalizer <ErrorableResultFilterAttribute> >();
                    var error     = new SerializableError
                    {
                        { Errors, actionResult.Result.Messages.Select(m => localizer[m].Value) }
                    };

                    context.Result = new BadRequestObjectResult(error);
                    LogFailureResult(actionResult.Result, context
                                     .HttpContext
                                     .RequestServices
                                     .GetRequiredService <ILogger <ErrorableResultFilterAttribute> >());

                    return;
                }

                if (context.HttpContext.Request.Method == "DELETE")
                {
                    context.Result = new NoContentResult();

                    return;
                }

                if (actionResult.Result is IResult <object> objectResult)
                {
                    context.Result = new OkObjectResult(objectResult.Data);
                }
                else
                {
                    context.Result = new OkResult();
                }
            }
        }
        public void WriteXml_WritesValidXml()
        {
            // Arrange
            var modelState = new ModelStateDictionary();
            modelState.AddModelError("key1", "Test Error 1");
            modelState.AddModelError("key1", "Test Error 2");
            modelState.AddModelError("key2", "Test Error 3");
            var serializableError = new SerializableError(modelState);
            var outputStream = new MemoryStream();

            // Act
            using (var xmlWriter = XmlWriter.Create(outputStream))
            {
                var dataContractSerializer = new DataContractSerializer(typeof(SerializableErrorWrapper));
                dataContractSerializer.WriteObject(xmlWriter, new SerializableErrorWrapper(serializableError));
            }
            outputStream.Position = 0;
            var res = new StreamReader(outputStream, Encoding.UTF8).ReadToEnd();

            // Assert
            Assert.Equal("<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                "<Error><key1>Test Error 1 Test Error 2</key1><key2>Test Error 3</key2></Error>", res);
        }
        /// <summary>
        /// Converts the <paramref name="serializableError"/> to an <see cref="ODataError"/>.
        /// </summary>
        /// <param name="serializableError">The <see cref="SerializableError"/> instance to convert.</param>
        /// <returns>The converted <see cref="ODataError"/></returns>
        public static ODataError CreateODataError(this SerializableError serializableError)
        {
            if (serializableError == null)
            {
                throw Error.ArgumentNull("serializableError");
            }

            string message = serializableError.GetPropertyValue <string>(SerializableErrorKeys.MessageKey);
            string details = ConvertModelStateErrors(serializableError);

            return(new ODataError
            {
                Message = string.IsNullOrEmpty(message) ? details : message,
                ErrorCode = serializableError.GetPropertyValue <string>(SerializableErrorKeys.ErrorCodeKey),
                InnerError = ToODataInnerError(serializableError),
                Details = serializableError
                          .Select(kvp => new ODataErrorDetail()
                {
                    Message = kvp.Key + ":" + kvp.Value,
                })
                          .AsCollection(),
            });
        }
        private static ODataInnerError ToODataInnerError(SerializableError serializableError)
        {
            string innerErrorMessage = serializableError.GetPropertyValue <string>(SerializableErrorKeys.ExceptionMessageKey);

            if (innerErrorMessage == null)
            {
                string messageDetail = serializableError.GetPropertyValue <string>(SerializableErrorKeys.MessageDetailKey);
                if (messageDetail == null)
                {
                    SerializableError modelStateError = serializableError.GetPropertyValue <SerializableError>(SerializableErrorKeys.ModelStateKey);
                    return((modelStateError == null) ? null
                        : new ODataInnerError {
                        Message = ConvertModelStateErrors(modelStateError)
                    });
                }
                else
                {
                    return(new ODataInnerError()
                    {
                        Message = messageDetail
                    });
                }
            }
            else
            {
                ODataInnerError innerError = new ODataInnerError();
                innerError.Message    = innerErrorMessage;
                innerError.TypeName   = serializableError.GetPropertyValue <string>(SerializableErrorKeys.ExceptionTypeKey);
                innerError.StackTrace = serializableError.GetPropertyValue <string>(SerializableErrorKeys.StackTraceKey);
                SerializableError innerExceptionError = serializableError.GetPropertyValue <SerializableError>(SerializableErrorKeys.InnerExceptionKey);
                if (innerExceptionError != null)
                {
                    innerError.InnerError = ToODataInnerError(innerExceptionError);
                }
                return(innerError);
            }
        }
        public void CreateODataError_Creates_BasicODataError_WithoutModelStateDictionary()
        {
            // Arrange & Act & Assert
            ModelStateDictionary modelState = new ModelStateDictionary();

            modelState.AddModelError("key3", "Test Error 3");
            SerializableError innerSerializableError = new SerializableError(modelState);

            SerializableError serializableError = new SerializableError();

            serializableError["key1"]       = "Test Error 1";
            serializableError["key2"]       = "Test Error 2";
            serializableError["ModelState"] = innerSerializableError;

            // Act
            ODataError error = SerializableErrorExtensions.CreateODataError(serializableError);

            // Assert
            Assert.NotNull(error);
            Assert.Equal("key1:\r\nTest Error 1\r\n\r\nkey2:\r\nTest Error 2", error.Message);
            Assert.Null(error.ErrorCode);
            Assert.Equal("key3:\r\nTest Error 3", error.InnerError.Message);
            Assert.Equal(2, error.Details.Count);
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Create an error response.
        /// </summary>
        /// <param name="message">The message of the error.</param>
        /// <param name="exception">The error exception if any.</param>
        /// <returns>A SerializableError.</returns>
        /// <remarks>This function is recursive.</remarks>
        public static SerializableError CreateErrorResponse(string message, Exception exception = null)
        {
            // The key values mimic the behavior of HttpError in AspNet. It's a fine format
            // and many of the test cases expect it.
            SerializableError error = new SerializableError();

            if (!String.IsNullOrEmpty(message))
            {
                error.Add(SerializableErrorKeys.MessageKey, message);
            }

            if (exception != null)
            {
                error.Add(SerializableErrorKeys.ExceptionMessageKey, exception.Message);
                error.Add(SerializableErrorKeys.ExceptionTypeKey, exception.GetType().FullName);
                error.Add(SerializableErrorKeys.StackTraceKey, exception.StackTrace);
                if (exception.InnerException != null)
                {
                    error.Add(SerializableErrorKeys.InnerExceptionKey, CreateErrorResponse(String.Empty, exception.InnerException));
                }
            }

            return(error);
        }
Ejemplo n.º 32
0
        public void CanEnumerateOn_WrappableElementTypes()
        {
            // Arrange
            var error1 = new SerializableError();
            error1.Add("key1", "key1-error");
            var error2 = new SerializableError();
            error2.Add("key1", "key1-error");
            var errors = new[] { error1, error2 };
            var delegatingEnumerable = new DelegatingEnumerable<SerializableErrorWrapper, SerializableError>(
                                                    errors,
                                                    new SerializableErrorWrapperProvider());

            // Act and Assert
            Assert.Equal(errors.Length, delegatingEnumerable.Count());

            for (var i = 0; i < errors.Length; i++)
            {
                var errorWrapper = delegatingEnumerable.ElementAt(i);

                Assert.IsType<SerializableErrorWrapper>(errorWrapper);
                Assert.NotNull(errorWrapper);
                Assert.Same(errors[i], errorWrapper.SerializableError);
            }
        }
        public async Task CreateReturnsBadRequestIfRequestFailsValidation()
        {
            string invalidProperty = NewRandomString();
            string errorMessage    = NewRandomString();

            CreateProfilePatternRequest request = NewCreateRequest(_ =>
                                                                   _.WithPattern(NewProfilePattern()));

            ValidationResult expectedValidationResult = NewValidationResult(_ =>
                                                                            _.WithFailures(NewValidationFailure(vf => vf.WithPropertyName(invalidProperty)
                                                                                                                .WithErrorMessage(errorMessage))));

            GivenTheValidationResultForTheCreateRequest(request, expectedValidationResult);

            SerializableError serializableError = (await WhenTheProfilePatternIsCreated(request) as BadRequestObjectResult)?
                                                  .Value as SerializableError;

            serializableError?[invalidProperty]
            .Should()
            .BeEquivalentTo(new[] { errorMessage });

            AndNoProfilePatternsWereSaved();
            AndTheCacheWasNotInvalidated();
        }
        /// <summary>
        /// Applies the specified model.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="context">The context.</param>
        public void Apply(Schema model, SchemaFilterContext context)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

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

            if (context.SystemType == typeof(ModelStateDictionary))
            {
                var modelState = new ModelStateDictionary();
                modelState.AddModelError("Property1", "Error message 1");
                modelState.AddModelError("Property1", "Error message 2");
                modelState.AddModelError("Property2", "Error message 3");
                var serializableError = new SerializableError(modelState);

                model.Default = serializableError;
                model.Example = serializableError;
            }
        }
Ejemplo n.º 35
0
 public static void ContainsKeyAndErrorMessage(this SerializableError error, string key, string errorMessage)
 {
     error.Should().NotBeNull();
     error.ContainsKey(key).Should().BeTrue();
     ((string[])error[key])[0].Should().Be(errorMessage);
 }
Ejemplo n.º 36
0
 private static IDictionary <string, string[]> GetValidationErrors(SerializableError error)
 {
     return(error.Where(x => x.Value is string[]).ToDictionary(x => x.Key, x => (string[])x.Value));
 }
Ejemplo n.º 37
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SerializableErrorWrapper"/> class.
 /// </summary>
 /// <param name="error">The <see cref="SerializableError"/> object that needs to be wrapped.</param>
 public SerializableErrorWrapper([NotNull] SerializableError error)
 {
     SerializableError = error;
 }
Ejemplo n.º 38
0
 // Note: XmlSerializer requires to have default constructor
 public SerializableErrorWrapper()
 {
     SerializableError = new SerializableError();
 }
Ejemplo n.º 39
0
        /// <summary>
        /// Create an ODataError from an HttpError.
        /// </summary>
        /// <param name="error">The error to use.</param>
        /// <returns>an ODataError.</returns>
        internal static ODataError CreateODataError(object error)
        {
            SerializableError serializableError = error as SerializableError;

            return(serializableError.CreateODataError());
        }
Ejemplo n.º 40
0
 public SerializableError LogErrors([FromBody] SerializableError serializableError)
 {
     return(serializableError);
 }
Ejemplo n.º 41
0
        private async Task <WebApiResponse <TOutput> > GetHttpResponse <TOutput, TInput>(HttpVerb verb, string endPoint, TInput input, bool throwException = false)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(_baseAddress);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                StringContent content = null;
                // HTTP POST
                HttpResponseMessage response = null;

                switch (verb)
                {
                case HttpVerb.Get:
                    response = await client.GetAsync(endPoint);

                    break;

                case HttpVerb.Post:
                    content  = new StringContent(JsonSerializer.Serialize(input), Encoding.UTF8, "application/json");
                    response = await client.PostAsync(endPoint, content);

                    break;

                case HttpVerb.Put:
                    content  = new StringContent(JsonSerializer.Serialize(input), Encoding.UTF8, "application/json");
                    response = await client.PutAsync(endPoint, content);

                    break;

                case HttpVerb.Delete:
                    response = await client.DeleteAsync(endPoint);

                    break;

                default:
                    break;
                }

                //response.EnsureSuccessStatusCode();
                string data = await response.Content.ReadAsStringAsync();

                var result = new WebApiResponse <TOutput>();
                result.IsSucceded = response.IsSuccessStatusCode;
                result.StatusCode = response.StatusCode;

                try
                {
                    var serializeOptions = new JsonSerializerOptions
                    {
                        PropertyNamingPolicy        = JsonNamingPolicy.CamelCase,
                        PropertyNameCaseInsensitive = true
                    };
                    result.Response = JsonSerializer.Deserialize <TOutput>(data, serializeOptions);
                }
                catch (Exception ex)
                {
                    // ignored
                }

                if (!response.IsSuccessStatusCode)
                {
                    SerializableError err = null;
                    try
                    {
                        err = JsonSerializer.Deserialize <SerializableError>(data);
                    }
                    catch (Exception)
                    {
                        // ignored
                    }

                    if (err?.Any() == true)
                    {
                        var message = err.First().Value.ToString();
                        if (throwException)
                        {
                            var ex = new Exception(message);
                            foreach (var item in err)
                            {
                                if (!ex.Data.Contains(item.Key))
                                {
                                    ex.Data.Add(item.Key, item.Value);
                                }
                            }
                            throw ex;
                        }
                        else
                        {
                            result.Message = message;
                            result.Errors  = new List <ErrorItem>();

                            foreach (var item in err)
                            {
                                if (result.Errors.All(x => x.Key != item.Key))
                                {
                                    result.Errors.Add(new ErrorItem
                                    {
                                        Key   = item.Key,
                                        Value = Convert.ToString(item.Value)
                                    });
                                }
                            }
                        }
                    }
                }

                return(result);
            }
        }
Ejemplo n.º 42
0
        /// <summary>
        /// Create a BadRequestObjectResult.
        /// </summary>
        /// <param name="message">The error message.</param>
        /// <param name="exception">The exception.</param>
        /// <returns>A BadRequestObjectResult.</returns>
        private static BadRequestObjectResult CreateBadRequestResult(string message, Exception exception)
        {
            SerializableError error = CreateErrorResponse(message, exception);

            return(new BadRequestObjectResult(error));
        }
Ejemplo n.º 43
0
 // Note: XmlSerializer requires to have default constructor
 public SerializableErrorWrapper()
 {
     SerializableError = new SerializableError();
 }
Ejemplo n.º 44
0
        public async Task CreateUser_ResponseStatus_400(CreateUserProfileRequest request, SerializableError expectedResult)
        {
            // Arrange
            var mockUserProfileService = new Mock <IUserProfileService>();
            var userProfileEntity      = Mapper.Map <UserProfileEntity>(request);

            mockUserProfileService.Setup(x => x.CreateUserAsync(It.IsAny <UserProfileEntity>())).Throws <UserNameExistsException>();

            var userController = new UserController(Mapper, mockUserProfileService.Object, null, null);

            MockModelState(request, userController);

            // Act
            var response = await userController.CreateUser(request);

            // Assert
            var badObjectResult = Assert.IsType <BadRequestObjectResult>(response.Result);
            var result          = Assert.IsType <SerializableError>(badObjectResult.Value);

            Assert.Equal(expectedResult, result);
        }