Exemplo n.º 1
0
        public void When_GetClassCalledForValidState_ReturnCorrectClass()
        {
            var model  = new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary();
            var result = HtmlExtensions.GetClass("test", model);

            Assert.IsEmpty(result);
        }
Exemplo n.º 2
0
 /// <summary>
 /// The method would iterate through the errors
 /// </summary>
 /// <param name="modelState">The model state</param>
 /// <param name="prefix">The prefix to be used</param>
 public static void ClearModelErrors(this Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary modelState, string prefix)
 {
     foreach (var modelKey in modelState.Where(m => m.Key.StartsWith(prefix)))
     {
         modelKey.Value.Errors.Clear();
     }
 }
Exemplo n.º 3
0
        /// <summary>
        /// The method would validate the resultant model
        /// </summary>
        /// <param name="modelState">The model state</param>
        /// <param name="errorMessage">The error message to be thrown if validation fails</param>
        public static ValidationResultModel ToValidationResultModel(this Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary modelState, string errorMessage = "Validation Failed")
        {
            if (modelState != null)
            {
                if (modelState.IsValid)
                {
                    return(new ValidationResultModel {
                        IsValid = true
                    });
                }

                var result = new ValidationResultModel
                {
                    Message = errorMessage,
                    Errors  = modelState.Keys
                              .Where(key => modelState[key].ValidationState == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Invalid)
                              .SelectMany(key => modelState[key].ToValidationResults(key))
                              .ToList()
                };

                if (!result.Errors.Any())
                {
                    result.IsValid = true;
                }

                return(result);
            }
            return(null);
        }
Exemplo n.º 4
0
        public void When_GetClassCalledForErrorState_ReturnCorrectClass()
        {
            var model = new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary();

            model.AddModelError("test", "error");
            var result = HtmlExtensions.GetClass("test", model);

            Assert.AreEqual(ErrorClass, result);
        }
Exemplo n.º 5
0
        public static ActionResult Error(
            this ControllerBase controller,
            string error)
        {
            var dict = new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary();

            dict.AddModelError("error", error);
            return(controller.BadRequest(dict));
        }
Exemplo n.º 6
0
        public void When_DobVariableGetClassCalled_ReturnCorrectClass(string field, string expected)
        {
            var model = new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary();

            model.AddModelError(field, "error");
            var result = HtmlExtensions.GetDOBClass(DobField, DobDay, DobMonth, DobYear, model);

            Assert.AreEqual(result, expected);
        }
Exemplo n.º 7
0
        /// <summary>
        /// The method would clear all the model errors
        /// </summary>
        /// <param name="modelState">The model state</param>
        /// <param name="keyName">The key name</param>
        /// <param name="exactMatch">The exact match of the error</param>
        public static void ClearModelError(this Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary modelState, string keyName, bool exactMatch = false)
        {
            var modelKey = modelState.FirstOrDefault(m => exactMatch
                ? string.Compare(m.Key, keyName, true) == 0 : m.Key.Contains(keyName));

            if (!string.IsNullOrEmpty(modelKey.Key))
            {
                modelKey.Value.Errors.Clear();
            }
        }
Exemplo n.º 8
0
 // Remove any modelstate errors that don't pertain to the actual fields we are binding to
 public void ScrubModelState(string bindingFields, Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary mState)
 {
     string[] bindingKeys = bindingFields.Split(",");
     foreach (string key in mState.Keys)
     {
         if (!bindingKeys.Contains(key))
         {
             mState.Remove(key);
         }
     }
 }
Exemplo n.º 9
0
        /// <summary>
        /// Get Error Mesage for MVC Model State
        /// </summary>
        /// <param name="dictionary"></param>
        /// <returns></returns>
        public static string GetErrorMessage(this Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary dictionary)
        {
            string errmsg = "";

            foreach (var key in dictionary.Keys)
            {
                errmsg += dictionary[key].Errors.First().ErrorMessage + "<br/>";
            }

            return(errmsg);
        }
 //Gérer erreurs AJAX
 public static DataSourceResult ReturnError(Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary ModelState,
                                            ILogger _logger, LogLevel l, string error, string field, string user)
 {
     _logger.Log(l, user + ": " + error);
     ModelState.AddModelError(field, error);
     return(new DataSourceResult
     {
         Errors = error,
         Data = ModelState,
         Total = 1
     });
 }
Exemplo n.º 11
0
        public static ValidationMessages ToValidationMessages(
            this Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary modelState, bool camelCaseKeyName = true)
        {
            var errors = modelState
                         .Where(x => x.Value.Errors.Any())
                         .ToDictionary(
                kvp => CamelCasePropNames(kvp.Key),
                kvp => kvp.Value.Errors.Select(e => e.ErrorMessage)
                );

            return(new ValidationMessages(errors));
        }
Exemplo n.º 12
0
        private ActionResult MessagesResponse(string[] messages, enStatusCode statusCode)
        {
            var modelState = new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary();
            var prefix     = (statusCode == enStatusCode.Info ? "INFO" : "WARNING");

            foreach (var messageKey in messages)
            {
                var messageValue = this.GetTranslation(messageKey);
                modelState.AddModelError($"{prefix}_{messageKey}", messageValue);
            }
            return(new BadRequestObjectResult(modelState));
        }
Exemplo n.º 13
0
        public static ResponseList <T> GetList <T>(Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary modelState = null, string message = null)
            where T : class, new()
        {
            var apiResponse = new ResponseList <T>();

            apiResponse.Data   = null;
            apiResponse.Status = new ResponseStatus()
            {
                Message = message, Errors = ValidateModelState(modelState)
            };
            return(apiResponse);
        }
Exemplo n.º 14
0
        protected object ValidateModelResult(Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary modelState)
        {
            string res = null;

            if (!modelState.IsValid)
            {
                res = string.Join("\n", ModelState.Values.Select(v => string.Join("\n", v.Errors.Select(e => e.ErrorMessage))));
            }

            var json = new ErrorData(res);

            return(json);
        }
Exemplo n.º 15
0
        public IActionResult Process(ProcessPaymentModel orderInfo)
        {
            var emptyModelMetaDataProvider = new Microsoft.AspNetCore.Mvc.ModelBinding.EmptyModelMetadataProvider();
            var modelStateDictionary       = new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary();

            return(new ViewResult
            {
                ViewData = new ViewDataDictionary(emptyModelMetaDataProvider, modelStateDictionary)
                {
                    Model = $"IBox account number page  ||  customer ID: {orderInfo.CustomerId}  ||  Order ID: {orderInfo.OrderId}  ||  Total: {orderInfo.OrderSum}"
                }
            });
        }
        /// <summary>
        /// Generates a response with a message for each error in the <see cref="ModelStateDictionary"/>
        /// </summary>
        /// <param name="state">The state containing all error messages</param>
        public IActionResult InvalidModelState(Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary state)
        {
            var model = GenerateModel(ErrorCode.ParseError,
                                      state.Where(kv => kv.Value.Errors.Count > 0)
                                      .SelectMany(kv => kv.Value.Errors)
                                      .Select(err => GenerateModel(ErrorCode.ParseError, err.ToString()))
                                      .ToArray()
                                      );

            return(new ObjectResult(model)
            {
                StatusCode = 400
            });
        }
        public async Task Post_WithInvalidModel_ShouldReturnBadRequest()
        {
            //Arrange
            var usersController      = new UsersController(null, null);
            var modelStateDictionary = new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary();

            usersController.ModelState.AddModelError("", "error");

            //Act
            var result = await usersController.Post(null);

            //Assert
            Assert.IsTrue(result is BadRequestObjectResult);
        }
Exemplo n.º 18
0
 public MyRestResponse(
     System.Net.HttpStatusCode httpStatusCode,
     Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary myModelState,
     dynamic myrequestObject
     , string myrequestObjectNAME
     )
 {
     this._HRM                     = new HttpResponseMessage(httpStatusCode);
     this._MRO                     = new MyResponseObject(_HRM);
     this._myModelState            = myModelState;
     this._MyRequestObject         = myrequestObject;
     this.MyRequestObjectLocalName = _ControllersHelper.MemberInfoGetting.GetMemberName(() => myrequestObject); // maalesef doğası gereği böyle olamıyor
     this.MyRequestObjectLocalName = myrequestObjectNAME;                                                       // ok
 }
Exemplo n.º 19
0
        public IActionResult Process(ProcessPaymentModel orderInfo)
        {
            var emptyModelMetaDataProvider = new Microsoft.AspNetCore.Mvc.ModelBinding.EmptyModelMetadataProvider();
            var modelStateDictionary       = new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary();

            return(new ViewResult
            {
                ViewData = new ViewDataDictionary(emptyModelMetaDataProvider, modelStateDictionary)
                {
                    Model = "Success paid"
                },
                ViewName = "CardSuccess"
            });
        }
Exemplo n.º 20
0
        public static ModelStateDictionary ToModelStateDictionary(this string[] errors)
        {
            if (!errors.IsNullOrEmpty())
            {
                ModelStateDictionary modelStateDictionary = new ModelStateDictionary();

                foreach (string error in errors)
                {
                    modelStateDictionary.AddModelError("", error);
                }

                return(modelStateDictionary);
            }

            return(null);
        }
Exemplo n.º 21
0
        public static ModelStateDictionary ToModelStateDictionary(this ValidationResult validationResult)
        {
            if (!validationResult.IsValid)
            {
                ModelStateDictionary modelStateDictionary = new ModelStateDictionary();

                foreach (var error in validationResult.Errors)
                {
                    modelStateDictionary.AddModelError(error.PropertyName, error.ErrorMessage);
                }

                return(modelStateDictionary);
            }

            return(null);
        }
Exemplo n.º 22
0
        public static void ValidateStudent(Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary modelState, Student student, IUnitOfWork unitOfWork)
        {
            student.FirstName  = student.FirstName.Trim();
            student.LastName   = student.LastName.Trim();
            student.PersonalNr = student.PersonalNr.Trim();

            if (!String.IsNullOrWhiteSpace(student.PersonalNr) && unitOfWork.StudentRepository.Get(filter: c => c.PersonalNr == student.PersonalNr && c.Id != student.Id).Count() > 0)
            {
                modelState.AddModelError("PersonalNr", "ეს პირადი ნომერი უკვე დარეგისტრირებულია");
            }

            if (student.BirthDate.Date.AddYears(16) > DateTime.Now.Date)
            {
                modelState.AddModelError("BirthDate", "სტუდენტი არ შეიძლება იყოს 16 წელზე პატარა");
            }
        }
Exemplo n.º 23
0
        private static Dictionary <string, string> ValidateModelState(Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary modelState)
        {
            Dictionary <string, string> defaultErrors = new Dictionary <string, string>();

            foreach (var state in modelState)
            {
                foreach (var error in state.Value.Errors)
                {
                    if (!defaultErrors.ContainsKey(state.Key))
                    {
                        defaultErrors.Add(state.Key, state.Key + ErrorMessages.IsRequired);
                    }
                }
            }
            return(defaultErrors);
        }
Exemplo n.º 24
0
        public override void RunRules(IBaseEntity Entity
                                      , EntityRules entitiesRules
                                      , ModelStateDictionary modelState)
        {
            var subCategoryType = GetEntity <SubCategoryType>(entitiesRules);
            var subCategoryItem = GetEntity <SubCategoryClassItem>(entitiesRules);

            if (subCategoryType == null)
            {
                modelState.AddModelError("", "New Order SubCategory must contain one Sub Type");
            }
            if (subCategoryItem == null)
            {
                modelState.AddModelError("", "New Order SubCategory must contain one Sub Item");
            }
        }
Exemplo n.º 25
0
        private Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext GetActionExecutingContext()
        {
            var modelState    = new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary();
            var actionContext = new ActionContext(
                Mock.Of <HttpContext>(),
                Mock.Of <Microsoft.AspNetCore.Routing.RouteData>(),
                Mock.Of <Microsoft.AspNetCore.Mvc.Abstractions.ActionDescriptor>(),
                modelState
                );

            return(new Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext(
                       actionContext,
                       new List <IFilterMetadata>(),
                       new Dictionary <string, object>(),
                       Mock.Of <Microsoft.AspNetCore.Mvc.Controller>()
                       ));
        }
Exemplo n.º 26
0
        protected IActionResult HandleInvalidModelState(Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary model)
        {
            var errors = "";

            foreach (var state in ModelState)
            {
                foreach (var error in state.Value.Errors)
                {
                    errors += error.ErrorMessage + "; ";
                }
            }
            var authResponse = new { Status = new { Success = false, Result = errors.TrimEnd(new[] { ';', ' ' }) } };

            return(new ObjectResult(authResponse)
            {
                StatusCode = 404
            });
        }
Exemplo n.º 27
0
 internal static string GetModelError(Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary modelState)
 {
     System.Text.StringBuilder sb = new System.Text.StringBuilder();
     //获取每一个key对应的ModelStateDictionary
     foreach (var key in modelState.Keys)
     {
         if (modelState[key].ValidationState == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Invalid)
         {
             sb.Append(key);
             sb.Append(":");
             foreach (var err in modelState[key].Errors)
             {
                 sb.Append(err);
                 sb.Append(";");
             }
         }
     }
     return(sb.ToString());
 }
Exemplo n.º 28
0
        public override void RunRules(IBaseEntity Entity
                                      , EntityRules entitiesRules
                                      , ModelStateDictionary modelState)
        {
            var name = string.Empty;

            var SubCat = GetEntity <SubCategory>(entitiesRules);

            var exists = _ServiceHandlerFactory.Using <ISubCategoryHandler>().Get()
                         .Where(c => c.SubCategoryName.Value == SubCat.SubCategoryName.Value)
                         .AsEnumerable().Any(w => SubCat.IsNew ||
                                             (SubCat.OldPicture != null &&
                                              SubCat.OldPicture.SubCategoryName.Value != w.SubCategoryName.Value));


            if (exists)
            {
                modelState.AddModelError("", "Found Duplicate Sub Category Name");
            }
        }
        public async Task Post_WhenServiceReturnsNotFound_ShouldReturn404Status()
        {
            //Arrange
            var modelStateDictionary = new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary();

            var userPostDto = new UserPostDto
            {
                BankAccount = new BankAccountDto {
                    AccountNumber = "12345678", BankName = "ABank"
                },
                Email     = "*****@*****.**",
                FirstName = "Jason",
                LastName  = "Wilson",
                Username  = "******"
            };

            var mockUserService = new Mock <IUserService>();

            mockUserService.Setup(m => m.AddAsync(It.IsAny <UserCreateDto>()))
            .ReturnsAsync(
                new Core.Models.Result <Core.Models.User>
            {
                ErrorCategory = Core.Models.ErrorCategory.NotFound,
                Obj           = new Core.Models.User {
                }
            }
                );

            var usersController = new UsersController(mockUserService.Object, null);

            //Act
            var result = await usersController.Post(userPostDto);

            //Assert
            mockUserService.Verify(m => m.AddAsync(It.IsAny <UserCreateDto>()), Times.Once);
            var notFoundResult = result as NotFoundObjectResult;

            Assert.IsNotNull(notFoundResult);
            Assert.AreEqual(404, notFoundResult.StatusCode);
        }
        public async Task Post_WhenBadData_ShouldReturn400Status()
        {
            //Arrange
            var modelStateDictionary = new Microsoft.AspNetCore.Mvc.ModelBinding.ModelStateDictionary();

            var userPostDto = new UserPostDto
            {
                BankAccount = new BankAccountDto {
                    AccountNumber = "12345678", BankName = "ABank"
                },
                Email     = "*****@*****.**",
                FirstName = "Jason",
                LastName  = "Wilson",
                Username  = "******"
            };

            const string badDataMessage = "bad data";

            var mockUserService = new Mock <IUserService>();

            mockUserService.Setup(m => m.AddAsync(It.IsAny <UserCreateDto>()))
            .ReturnsAsync(
                new Core.Models.Result <Core.Models.User>
            {
                ErrorCategory = Core.Models.ErrorCategory.BadData,
                Message       = badDataMessage,
                Obj           = new Core.Models.User {
                }
            }
                );

            var usersController = new UsersController(mockUserService.Object, null);

            //Act
            var result = await usersController.Post(userPostDto);

            //Assert
            mockUserService.Verify(m => m.AddAsync(It.IsAny <UserCreateDto>()), Times.Once);
            Assert.IsTrue(result is BadRequestObjectResult);
        }