public ActionResult(HttpStatusCode status, System.Web.Http.ModelBinding.ModelStateDictionary state) : this(status, null, default(T)) { foreach (var item in state.Values) { Message += item.Errors.FirstOrDefault()?.ErrorMessage + Environment.NewLine; } }
public void SetModelStateError(System.Web.Http.ModelBinding.ModelStateDictionary modelState) { if (!string.IsNullOrEmpty(error)) { modelState.AddModelError("error", error); } }
protected override bool CommonValidation(System.Web.Http.ModelBinding.ModelStateDictionary validationDictionary, Client currentClient, BookingStep entity, object param, params object[] additionalObjects) { BookingStep temp = null; if (entity.BookingStepNext != null) { temp = BookingStepRepository.GetBookingStepById(entity.BookingStepNext.Id, currentClient.Id); } if (temp != null) { if (entity.BookingStepConfig != null && temp.BookingStepConfig.Id != entity.BookingStepConfig.Id) { validationDictionary.AddModelError(String.Format(GenericNames.MODEL_STATE_FORMAT, TypeOfName.GetNameFromType <BookingStep>(), "BookingStepNext"), GenericError.INVALID_GIVEN_PARAMETER); } if (entity.BookingArchived && !temp.BookingArchived) { validationDictionary.AddModelError(String.Format(GenericNames.MODEL_STATE_FORMAT, TypeOfName.GetNameFromType <BookingStep>(), "BookingStepNext.BookingArchived"), GenericError.INVALID_GIVEN_PARAMETER); } } if (entity.BookingStepPrevious != null) { temp = BookingStepRepository.GetBookingStepById(entity.BookingStepPrevious.Id, currentClient.Id); } if (temp != null) { if (entity.BookingStepConfig != null && temp.BookingStepConfig.Id != entity.BookingStepConfig.Id) { validationDictionary.AddModelError(String.Format(GenericNames.MODEL_STATE_FORMAT, TypeOfName.GetNameFromType <BookingStep>(), "BookingStepPrevious"), GenericError.INVALID_GIVEN_PARAMETER); } } return(validationDictionary.IsValid); }
public ModelStateException(System.Web.Http.ModelBinding.ModelStateDictionary modelState, string message = "Bad request body.") : base(message, ReasonBadRequestBody) { base.LogAsError = true; ModelStateErrors = modelState.AsString(); //WebHelper method base.Data[KeyModelStateErrors] = this.ModelStateErrors; //to automatically include in ToLogString() representation }
public static string Convert(System.Web.Http.ModelBinding.ModelStateDictionary modelState) { List <string> errorList = modelState.Values.SelectMany(m => m.Errors).Select(e => e.ErrorMessage).ToList(); string json = JsonConvert.SerializeObject(errorList); return(json); }
public static string GetError(this System.Web.Http.ModelBinding.ModelStateDictionary state) { string error = string.Empty; foreach (var ms in state.Values) { foreach (var e in ms.Errors) { if (!string.IsNullOrWhiteSpace(e.ErrorMessage)) { error = string.Concat(error, e.ErrorMessage, ";"); } else if (e.Exception != null) { var exp = e.Exception; if (exp is JsonReaderException) { error = string.Concat(error, "wrong json format!!"); } else { error = string.Concat(error, e.Exception.Message, ";"); } } } } return(error); }
public static MailboxNameData.Parsed Parse(this MailboxNameData target) { var modelStateDictionary = new System.Web.Http.ModelBinding.ModelStateDictionary(); MailboxName parsed0 = null; if (!MailboxName.IsEmpty(target.MailboxName)) { System.Collections.Generic.IReadOnlyCollection <string> parsed0Errors; if (!MailboxName.TryParse(target.MailboxName, out parsed0, out parsed0Errors)) { var modelState = new System.Web.Http.ModelBinding.ModelState(); foreach (var errorMessage in parsed0Errors) { modelState.Errors.Add(errorMessage); } modelStateDictionary.Add("MailboxName", modelState); } } else { var modelState = new System.Web.Http.ModelBinding.ModelState(); modelState.Errors.Add("Value required"); modelStateDictionary.Add("MailboxName", modelState); } if (!modelStateDictionary.IsValid) { throw new Fifthweek.Api.Core.ModelValidationException(modelStateDictionary); } return(new MailboxNameData.Parsed( parsed0)); }
public static String JsonValidation(this System.Web.Http.ModelBinding.ModelStateDictionary state) { return(JsonConvert.SerializeObject( state.Where(x => x.Value.Errors.Count > 0) .Select(e => new { Name = e.Key, Errors = e.Value.Errors.Select(x => x.ErrorMessage) .Concat(e.Value.Errors.Where(x => x.Exception != null).Select(x => x.Exception.Message)) }) )); //return new JsonResult //{ // Data = new // { // Tag = "ValidationError", // State = from e in state // where e.Value.Errors.Count > 0 // select new // { // Name = e.Key, // Errors = e.Value.Errors.Select(x => x.ErrorMessage) // .Concat(e.Value.Errors.Where(x => x.Exception != null).Select(x => x.Exception.Message)) // } // } //}; }
private IHttpActionResult ReturnCustomError(System.Web.Http.ModelBinding.ModelStateDictionary modleState, CustomValidationException customEx) { foreach (var dicItem in customEx.ErrorCollection) { modleState.AddModelError(dicItem.Key, dicItem.Value); } return(BadRequest(modleState)); }
public bool UploadValidationAfterProvider(System.Web.Http.ModelBinding.ModelStateDictionary validationDictionary, Client currentClient, MultipartFileData file) { if (file == null || String.IsNullOrEmpty(file.Headers.ContentDisposition.FileName)) { validationDictionary.AddModelError(String.Format(GenericNames.MODEL_STATE_FORMAT, TypeOfName.GetNameFromType <Document>(), "File"), GenericError.FORBIDDEN_RESOURCE_OR_DOES_NO_EXIST); } return(validationDictionary.IsValid); }
protected override bool ValidatePut(System.Web.Http.ModelBinding.ModelStateDictionary validationDictionary, Client currentClient, Document entity, object param, params object[] additionalObjects) { NullCheckValidation.NullValidation(TypeOfName.GetNameFromType <Document>(), new Dictionary <String, Object>() { { "Hide", entity.Hide } }, validationDictionary); return(CommonValidation(validationDictionary, currentClient, entity, param, additionalObjects)); }
/* ** Entity Validations */ protected override bool CommonValidation(System.Web.Http.ModelBinding.ModelStateDictionary validationDictionary, Client currentClient, Document entity, object param, params object[] additionalObjects) { if (entity.Title != null && !extensionFilter.Any(s => entity.Title.EndsWith(s, StringComparison.OrdinalIgnoreCase))) { validationDictionary.AddModelError(String.Format(GenericNames.MODEL_STATE_FORMAT, TypeOfName.GetNameFromType <Document>(), "Title"), GenericError.DOES_NOT_MEET_REQUIREMENTS); } return(validationDictionary.IsValid); }
public static IEnumerable <string> GetErrors(this System.Web.Http.ModelBinding.ModelStateDictionary modelState) { //return modelState.Values.SelectMany(v => v.Errors) // .Select(v => v.ErrorMessage + " " + v.Exception).ToList(); var errorsList = modelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage /* + " " + x.Exception*/); return(errorsList); }
protected override bool ValidatePost(System.Web.Http.ModelBinding.ModelStateDictionary validationDictionary, Client currentClient, MailModel entity, object param, params object[] additionalObjects) { IMailConfigRepository repo = (IMailConfigRepository)additionalObjects[0]; List <string> recipients = (List <string>)additionalObjects[1]; List <Document> attachments = (List <Document>)additionalObjects[2]; MailController.AdditionalRepositories addRepo = (MailController.AdditionalRepositories)param; NullCheckValidation.NullValidation(TypeOfName.GetNameFromType <MailModel>(), new Dictionary <String, Object>() { { "Body", entity.Body }, { "Subject", entity.Subject }, { "Password", entity.Password } }, validationDictionary); if (repo.GetMailConfigById(entity.MailConfigId, currentClient.Id) == null) { validationDictionary.AddModelError(String.Format(GenericNames.MODEL_STATE_FORMAT, TypeOfName.GetNameFromType <MailModel>(), "MailConfigId"), GenericError.FORBIDDEN_RESOURCE_OR_DOES_NO_EXIST); } if (entity.To.Count == 0) { validationDictionary.AddModelError(String.Format(GenericNames.MODEL_STATE_FORMAT, TypeOfName.GetNameFromType <MailModel>(), "To"), GenericError.CANNOT_BE_NULL_OR_EMPTY); } try { Encoding.UTF8.GetString(Convert.FromBase64String(entity.Password)); } catch (Exception) { validationDictionary.AddModelError(String.Format(GenericNames.MODEL_STATE_FORMAT, TypeOfName.GetNameFromType <MailModel>(), "Password"), GenericError.DOES_NOT_MEET_REQUIREMENTS); } foreach (int cur in entity.To) { People p = addRepo.PeopleRepo.GetPeopleById(cur, currentClient.Id); if (p == null) { validationDictionary.AddModelError(String.Format(GenericNames.MODEL_STATE_FORMAT, TypeOfName.GetNameFromType <MailModel>(), "To"), GenericError.FORBIDDEN_RESOURCE_OR_DOES_NO_EXIST); return(false); } if (p.AcceptMailing == true && p.Email != null) { recipients.Add(p.Email); } } if (entity.Attachments != null) { foreach (int cur in entity.Attachments) { Document d = addRepo.DocumentRepo.GetDocumentById(cur, currentClient.Id); if (d == null) { validationDictionary.AddModelError(String.Format(GenericNames.MODEL_STATE_FORMAT, TypeOfName.GetNameFromType <MailModel>(), "Attachments"), GenericError.FORBIDDEN_RESOURCE_OR_DOES_NO_EXIST); return(false); } attachments.Add(d); } } return(validationDictionary.IsValid); }
protected override bool ValidatePut(System.Web.Http.ModelBinding.ModelStateDictionary validationDictionary, Client currentClient, PeopleBooking entity, object param, params object[] additionalObjects) { NullCheckValidation.NullValidation(TypeOfName.GetNameFromType <PeopleBooking>(), new Dictionary <string, object>() { { "DateBegin", entity.DateBegin }, { "DateEnd", entity.DateEnd }, }, validationDictionary); return(CommonValidation(validationDictionary, currentClient, entity, param, additionalObjects)); }
/// <summary> /// Adds the error to model state correctly for a property so we can use it on the client side. /// </summary> /// <param name="modelState"></param> /// <param name="result"></param> /// <param name="propertyAlias"></param> /// <param name="culture">The culture for the property, if the property is invariant than this is empty</param> internal static void AddPropertyError(this System.Web.Http.ModelBinding.ModelStateDictionary modelState, ValidationResult result, string propertyAlias, string culture = "") { if (culture == null) { culture = ""; } modelState.AddValidationError(result, "_Properties", propertyAlias, culture); }
public static IEnumerable Errors(this System.Web.Http.ModelBinding.ModelStateDictionary modelState) { if (!modelState.IsValid) { return(modelState.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Errors .Select(e => e.ErrorMessage).ToArray()) .Where(m => m.Value.Any())); } return(null); }
/// <summary> /// Adds a generic culture error for use in displaying the culture validation error in the save/publish/etc... dialogs /// </summary> /// <param name="modelState"></param> /// <param name="culture"></param> /// <param name="segment"></param> /// <param name="errMsg"></param> internal static void AddVariantValidationError(this System.Web.Http.ModelBinding.ModelStateDictionary modelState, string culture, string segment, string errMsg) { var key = "_content_variant_" + (culture.IsNullOrWhiteSpace() ? "invariant" : culture) + "_" + (segment.IsNullOrWhiteSpace() ? "null" : segment) + "_"; if (modelState.ContainsKey(key)) { return; } modelState.AddModelError(key, errMsg); }
/// <summary> /// Adds the error to model state correctly for a property so we can use it on the client side. /// </summary> /// <param name="modelState"></param> /// <param name="result"></param> /// <param name="propertyAlias"></param> /// <param name="culture">The culture for the property, if the property is invariant than this is empty</param> internal static void AddPropertyError(this System.Web.Http.ModelBinding.ModelStateDictionary modelState, ValidationResult result, string propertyAlias, string culture = "") { if (culture == null) { culture = ""; } modelState.AddValidationError(result, "_Properties", propertyAlias, //if the culture is null, we'll add the term 'invariant' as part of the key culture.IsNullOrWhiteSpace() ? "invariant" : culture); }
/// <summary> /// Adds a generic culture error for use in displaying the culture validation error in the save/publish/etc... dialogs /// </summary> /// <param name="modelState"></param> /// <param name="culture"></param> /// <param name="errMsg"></param> internal static void AddCultureValidationError(this System.Web.Http.ModelBinding.ModelStateDictionary modelState, string culture, string errMsg) { var key = "_content_variant_" + culture + "_"; if (modelState.ContainsKey(key)) { return; } modelState.AddModelError(key, errMsg); }
public static List <string> GetErrorListFromModelState (ModelStateDictionary modelState) { var query = from state in modelState.Values from error in state.Errors select error.ErrorMessage; var errorList = query.ToList(); return(errorList); }
protected override bool ValidatePost(System.Web.Http.ModelBinding.ModelStateDictionary validationDictionary, Client currentClient, Period entity, object param, params object[] additionalObjects) { if (param != null && entity != null && entity.End != null && entity.Begin != null && entity.Days > 0) { List <Period> periodList = PeriodRepository.GetPeriodByDates(entity.Begin, entity.End, currentClient.Id).ToList(); if (PeriodUtils.IsDaysCross(periodList, entity)) { validationDictionary.AddModelError(TypeOfName.GetNameFromType <Period>(), GenericError.ALREADY_EXISTS); } } return(CommonValidation(validationDictionary, currentClient, entity, param, additionalObjects)); }
public ApiResponse(System.Web.Http.ModelBinding.ModelStateDictionary modelState) { var errors = new List <string>(); foreach (var model in modelState.Values) { if (model.Errors.Any()) { errors.AddRange(model.Errors.Select(error => error.ErrorMessage)); } } }
/// <summary> /// Envoyer un message d'échec de la validation de la vue modèle après le ModelState /// </summary> /// <param name="modelState">Dictionnaire état de la validation</param> /// <returns>Vue modèle message en erreur avec informations de validation à afficher au client</returns> public static MessageCoreVm SendModelStateFailed(System.Web.Http.ModelBinding.ModelStateDictionary modelState) { return(new MessageCoreVm() { Success = false, ErrorObject = new ErrorVm() { ErrorCode = (int)CustomExceptionErrorCode.ModelStateFailed }, ErrorValidation = ProcessModelState(modelState) }); }
/// <summary> /// Processes the specified model state. /// </summary> /// <param name="modelState">State of the model.</param> /// <param name="result">The result.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns> public static bool Process(this System.Web.Http.ModelBinding.ModelStateDictionary modelState, IValidationContainer result) { foreach (var r in result.ValidationErrors) { foreach (var e in r.Value) { modelState.AddModelError(r.Key, e); } } return(modelState.IsValid); }
public static ValidationMessages ToValidationMessages( this System.Web.Http.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)); }
public bool CheckSizeUpload(System.Web.Http.ModelBinding.ModelStateDictionary validationDictionary, DocumentLog log) { if (log == null) { validationDictionary.AddModelError(String.Format(GenericNames.MODEL_STATE_FORMAT, TypeOfName.GetNameFromType <Document>(), "DocumentLog"), GenericError.FORBIDDEN_RESOURCE_OR_DOES_NO_EXIST); } else if (log.CurrentSize > log.ResourceConfig.LimitBase) { validationDictionary.AddModelError(String.Format(GenericNames.MODEL_STATE_FORMAT, TypeOfName.GetNameFromType <Document>(), "LimitBase"), GenericError.UPLOAD_LIMIT); } return(validationDictionary.IsValid); }
public static NewChannelData.Parsed Parse(this NewChannelData target) { var modelStateDictionary = new System.Web.Http.ModelBinding.ModelStateDictionary(); ValidChannelName parsed0 = null; if (!ValidChannelName.IsEmpty(target.Name)) { System.Collections.Generic.IReadOnlyCollection <string> parsed0Errors; if (!ValidChannelName.TryParse(target.Name, out parsed0, out parsed0Errors)) { var modelState = new System.Web.Http.ModelBinding.ModelState(); foreach (var errorMessage in parsed0Errors) { modelState.Errors.Add(errorMessage); } modelStateDictionary.Add("Name", modelState); } } else { var modelState = new System.Web.Http.ModelBinding.ModelState(); modelState.Errors.Add("Value required"); modelStateDictionary.Add("Name", modelState); } ValidChannelPrice parsed1 = null; System.Collections.Generic.IReadOnlyCollection <string> parsed1Errors; if (!ValidChannelPrice.TryParse(target.Price, out parsed1, out parsed1Errors)) { var modelState = new System.Web.Http.ModelBinding.ModelState(); foreach (var errorMessage in parsed1Errors) { modelState.Errors.Add(errorMessage); } modelStateDictionary.Add("Price", modelState); } if (!modelStateDictionary.IsValid) { throw new Fifthweek.Api.Core.ModelValidationException(modelStateDictionary); } return(new NewChannelData.Parsed( target.BlogId, parsed0, parsed1, target.IsVisibleToNonSubscribers)); }
private List <string> GetModelStateErrors(System.Web.Http.ModelBinding.ModelStateDictionary modelState) { var errors = new List <string>(); foreach (var state in modelState) { foreach (var error in state.Value.Errors) { errors.Add(error.ErrorMessage == ""?error.Exception.Message:error.ErrorMessage); } } return(errors); }
public static void HandleModelState(this System.Web.Http.ModelBinding.ModelStateDictionary modelState) { if (!modelState.IsValid) { var errors = new Dictionary <string, string>(); modelState.Where(k => k.Value.Errors.Count > 0).ToList().ForEach(i => { var er = string.Join(", ", i.Value.Errors.Select(e => e.ErrorMessage).ToArray()); errors.Add(i.Key, er); }); throw new EntityValidationException(errors); } }