public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            var modelState = new ModelState { Value = valueResult };

            object actualValue = null;
            try
            {
                if (string.IsNullOrWhiteSpace(valueResult.AttemptedValue))
                    actualValue = bindingContext.ModelType == typeof(Date?) ? (object) null : default(Date);
                else
                    actualValue = new Date(Convert.ToDateTime(valueResult.AttemptedValue, CultureInfo.CurrentCulture));
            }
            catch (FormatException e)
            {
                var dateBinderMessage = GetBindingFailedMessge(bindingContext);

                if (!string.IsNullOrEmpty(dateBinderMessage))
                    modelState.Errors.Add(dateBinderMessage);
                else
                    modelState.Errors.Add(e);
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return actualValue;
        }
        public object BindModel(ControllerContext controllerContext,
                                        ModelBindingContext bindingContext)
        {
            ValueProviderResult valueResult = bindingContext.ValueProvider
                .GetValue(bindingContext.ModelName);
            ModelState modelState = new ModelState { Value = valueResult };
            object actualValue = null;
            try
            {
                if (valueResult != null)
                {
                    string valueToParse;

                    if (valueResult.AttemptedValue.Contains('.'))
                    {
                        valueToParse = valueResult.AttemptedValue.Replace('.', ',');
                    }
                    else
                    {
                        valueToParse = valueResult.AttemptedValue;
                    }
                    actualValue = Convert.ToDecimal(valueToParse, CultureInfo.CurrentCulture);
                }
            }
            catch (FormatException e)
            {
                modelState.Errors.Add(e);
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return actualValue;
        }
Esempio n. 3
0
        public object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
        {
            var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (string.IsNullOrEmpty(valueResult.AttemptedValue))
            {
                return(0m);
            }
            var modelState = new System.Web.Mvc.ModelState {
                Value = valueResult
            };
            object actualValue = null;

            try
            {
                actualValue = Convert.ToDecimal(
                    valueResult.AttemptedValue.Replace(",", "."),
                    CultureInfo.InvariantCulture
                    );
            }
            catch (FormatException e)
            {
                modelState.Errors.Add(e);
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return(actualValue);
        }
        public object BindModel(ControllerContext controllerContext,
                                ModelBindingContext bindingContext)
        {
            ValueProviderResult valueResult = bindingContext.ValueProvider
                .GetValue(bindingContext.ModelName);

            ModelState modelState = new ModelState {Value = valueResult};

            object actualValue = null;
            try
            {
                if (!string.IsNullOrEmpty(valueResult.AttemptedValue))
                {
                    actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
                                                CultureInfo.CurrentCulture);
                }
            }
            catch (FormatException e)
            {
                modelState.Errors.Add(e);
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return actualValue;
        }
        public void ErrorsProperty() {
            // Arrange
            ModelState modelState = new ModelState();

            // Act & Assert
            Assert.IsNotNull(modelState.Errors);
        }
Esempio n. 6
0
 private static Dictionary<string, object> SerializeModelState(ModelState modelState) => new Dictionary<string, object>
                                                                                         {
                                                                                             ["errors"] = (from error in modelState.Errors
                                                                                                           select
                                                                                                               GetErrorMessage(error, modelState))
                                                                                                 .ToArray()
                                                                                         };
Esempio n. 7
0
        public object BindModel(ControllerContext controllerContext,
            ModelBindingContext bindingContext)
        {
            ValueProviderResult valueResult = bindingContext.ValueProvider
                .GetValue(bindingContext.ModelName);
            ModelState modelState = new ModelState { Value = valueResult };
            object actualValue = null;
            try
            {
                //if with period use InvariantCulture
                if (valueResult.AttemptedValue.Contains("."))
                {
                    actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
                    System.Globalization.CultureInfo.InvariantCulture);
                }
                else
                {
                    //if with comma use CurrentCulture
                    actualValue = Convert.ToDecimal(valueResult.AttemptedValue,
                    System.Globalization.CultureInfo.CurrentCulture);
                }

            }
            catch (FormatException e)
            {
                modelState.Errors.Add(e);
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return actualValue;
        }
Esempio n. 8
0
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            object actualValue = null;
            var modelState = new ModelState();
            try
            {
                var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
                if (string.IsNullOrEmpty(valueResult.AttemptedValue))
                {
                    return 0m;
                }
                modelState.Value = valueResult;

                try
                {
                    actualValue = Convert.ToDecimal(
                        valueResult.AttemptedValue.Replace(",", "."),
                        CultureInfo.InvariantCulture
                    );
                }
                catch (FormatException e)
                {
                    modelState.Errors.Add(e);
                }
            }
            catch (Exception e)
            {
                modelState.Errors.Add(e);
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return actualValue;
        }
Esempio n. 9
0
        public object BindModel(ControllerContext controllerContext,
            ModelBindingContext bindingContext)
        {
            ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            ModelState modelState = new ModelState { Value = valueResult };
            object actualValue = null;
            try
            {
                //Check if this is a nullable decimal and a null or empty string has been passed
                var isNullableAndNull = (bindingContext.ModelMetadata.IsNullableValueType && (string.IsNullOrEmpty(valueResult?.AttemptedValue)));

                //If not nullable and null then we should try and parse the decimal
                if (!isNullableAndNull && valueResult != null)
                {
                    decimal d;
                    if(decimal.TryParse(valueResult.AttemptedValue, NumberStyles.Any, CultureInfo.CurrentCulture, out d))
                        actualValue = d;
                    else
                        throw new Exception($"cannot parse decimal value {valueResult.AttemptedValue}");
                }
            }
            catch (FormatException e)
            {
                modelState.Errors.Add(e);
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return actualValue;
        }
Esempio n. 10
0
        public object BindModel(ControllerContext controllerContext,
           ModelBindingContext bindingContext)
        {
            var valueResult = bindingContext.ValueProvider
                .GetValue(bindingContext.ModelName);

            var modelState = new ModelState { Value = valueResult };

            object actualValue = null;

            if (!string.IsNullOrWhiteSpace(valueResult.AttemptedValue))
            {
                try
                {
                    actualValue = DateTime.ParseExact(valueResult.AttemptedValue,
                            SiteSettings.DateFormatJS.Replace("D", "d").Replace("Y", "y"), CultureInfo.InvariantCulture);
                }
                catch (FormatException e)
                {
                    modelState.Errors.Add(e);
                }
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return actualValue;
        }
Esempio n. 11
0
        //to add to application, in the global.ascx
        //protected void Application_Start()
        //{
        //ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
        /// <summary>
        /// Bind Model (Interface Methods)  Model Binder For Decimal's. Problem in MVC 3 where decimal data type doesnt come through to the controller for javascript calls
        /// </summary>
        /// <param name="ControllerContextToUse">Controller Context</param>
        /// <param name="BindingContext">Binding Context</param>
        /// <returns>Value Of Parameter</returns>
        public object BindModel(ControllerContext ControllerContextToUse, System.Web.Mvc.ModelBindingContext BindingContext)
        {
            //grab the value
            var ValueResult = BindingContext.ValueProvider.GetValue(BindingContext.ModelName);

            //set the model state
            var ModelStateToUse = new System.Web.Mvc.ModelState { Value = ValueResult };

            //value to return
            object ActualValue = null;

            try
            {
                //let's go and try to convert the value
                ActualValue = Convert.ToDecimal(ValueResult.AttemptedValue);
            }
            catch (FormatException e)
            {
                //if we can't convert set the model state error
                ModelStateToUse.Errors.Add(e);
            }

            //add the model and model state
            BindingContext.ModelState.Add(BindingContext.ModelName, ModelStateToUse);

            //return the actual value
            return ActualValue;
        }
Esempio n. 12
0
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            object actualValue = null;
            if (valueResult != null)
            {
                ModelState modelState = new ModelState { Value = valueResult };

                try
                {
                    string valToCheck = valueResult.AttemptedValue;
                    if (valToCheck == string.Empty)
                    {
                        actualValue = null;
                    }
                    else
                    {
                        actualValue = Convert.ToDecimal(valToCheck.Replace("$", string.Empty).Replace("¥", string.Empty), CultureInfo.InvariantCulture);
                    }
                }
                catch (FormatException e)
                {
                    modelState.Errors.Add(e);
                }

            }
            return actualValue;
        }
Esempio n. 13
0
        public object BindModel(ControllerContext controllerContext,
            ModelBindingContext bindingContext)
        {
            var valueResult = bindingContext.ValueProvider
                .GetValue(bindingContext.ModelName);

            var modelState = new ModelState { Value = valueResult };

            object actualValue = null;

            try
            {
                var val = valueResult.AttemptedValue;
                if (string.IsNullOrWhiteSpace(val))
                {
                    val = "0";
                }

                actualValue = Convert.ToDecimal(val.Replace(" ", string.Empty), CultureInfo.CurrentCulture);
            }
            catch (FormatException e)
            {
                modelState.Errors.Add(e);
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return actualValue;
        }
Esempio n. 14
0
        public async Task<ActionResult> Create([Bind(Include = "Id,Name,Type,Price")] Food food, HttpPostedFileBase file)
        {
            if (file == null)
            {
                var modelState = new ModelState();
                modelState.Errors.Add("The file is required! Please choose some file from your computer.");
                ModelState.Add("FileName", modelState);
            }
            if (ModelState.IsValid)
            {
                string path = Server.MapPath("~/Uploads/");
                string newFileName = Guid.NewGuid() + Path.GetExtension(file?.FileName);
                var url = HttpContext.ApplicationInstance.Request.Url;
                string host = $"{url.Scheme}://{url.Authority}";
                string filePath = Path.Combine(path, newFileName);
                file?.SaveAs(filePath);
                food.Id = Guid.NewGuid();
                food.Picture = Path.Combine(host + "/Uploads/", newFileName);
                db.Foods.Add(food);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }

            return View(food);
        }
Esempio n. 15
0
        private static ModelState CreateErrorModelState(string field, string message)
        {
            var ms = new ModelState();
            ms.Errors.Add(message);

            return ms;
        }
Esempio n. 16
0
    /// <summary>
    /// Gets the decimal value from data received
    /// </summary>
    /// <param name="controllerContext">Controller context</param>
    /// <param name="bindingContext">Binding context</param>
    /// <returns>Parsed value</returns>
    public object BindModel(ControllerContext controllerContext,
                            System.Web.Mvc.ModelBindingContext bindingContext)
    {
        ValueProviderResult result = bindingContext.ValueProvider
                                     .GetValue(bindingContext.ModelName);
        var modelState = new System.Web.Mvc.ModelState {
            Value = result
        };
        object actualValue = null;
        var    culture     = CultureInfo.CurrentCulture;

        if (result.AttemptedValue != string.Empty)
        {
            try
            {
                // Try with your current culture
                actualValue = Convert.ToDecimal(result.AttemptedValue, culture);
            }
            catch (FormatException)
            {
                try
                {
                    // Try with invariant culture if current culture failed
                    actualValue = Convert.ToDecimal(result.AttemptedValue,
                                                    CultureInfo.InvariantCulture);
                }
                catch (FormatException ex)
                {
                    modelState.Errors.Add(ex);
                }
            }
        }
        bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
        return(actualValue);
    }
        public static MvcHtmlString ValidationBanner(this HtmlHelper htmlHelper, bool excludePropertyErrors, IDictionary<string, object> htmlAttributes)
        {
            if (htmlHelper == null) {
                throw new ArgumentNullException("htmlHelper");
            }

            FormContext formContext = htmlHelper.ViewContext.ClientValidationEnabled ?
                htmlHelper.ViewContext.FormContext :
                null;
            if (formContext == null && htmlHelper.ViewData.ModelState.IsValid) {
                return null;
            }

            IEnumerable<ModelState> modelStates = null;
            if (excludePropertyErrors) {
                ModelState ms;
                htmlHelper.ViewData.ModelState.TryGetValue(htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix, out ms);
                if (ms != null) {
                    modelStates = new ModelState[] { ms };
                }
            } else {
                modelStates = htmlHelper.ViewData.ModelState.Values;
            }

            string errorText = null;
            if (modelStates != null && modelStates.Any(x => x.Errors.Count > 0)) {
                errorText = modelStates.First(x => x.Errors.Count > 0)
                    .Errors.First().ErrorMessage;
            }

            TagBuilder errorLabelBuilder = new TagBuilder("strong");
            errorLabelBuilder.SetInnerText("ERROR: ");

            TagBuilder divBuilder = new TagBuilder("div");
            divBuilder.AddCssClass("alert alert-error");
            divBuilder.AddCssClass(htmlHelper.ViewData.ModelState.IsValid ?
                HtmlHelper.ValidationSummaryValidCssClassName :
                HtmlHelper.ValidationSummaryCssClassName);
            divBuilder.InnerHtml = errorLabelBuilder.ToString(TagRenderMode.Normal) +
                errorText;

            if (formContext != null) {
                if (htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled) {
                    if (!excludePropertyErrors) {
                        divBuilder.MergeAttribute("data-valmsg-banner", "true");
                    }
                } else {
                    divBuilder.GenerateId("validationSummary");
                    formContext.ValidationSummaryId = divBuilder.Attributes["id"];
                    formContext.ReplaceValidationSummary = !excludePropertyErrors;
                }
            }

            if (htmlAttributes != null) {
                divBuilder.MergeAttributes(htmlAttributes);
            }

            return MvcHtmlString.Create(divBuilder.ToString(TagRenderMode.Normal));
        }
 private static Dictionary<string, object> SerializeModelState(ModelState modelState)
 {
     var result = new Dictionary<string, object>();
     result["errors"] = modelState.Errors
                                  .Select(error => GetErrorMessage(error, modelState))
                                  .ToArray();
     return result;
 }
Esempio n. 19
0
        public object UpdateModel(object model, string[] fields)
        {
            System.Web.Mvc.ModelState currModelState = ModelState[string.Format("{1}.$${0}.$.Search", Index, modelName)];
            if (currModelState != null && currModelState.Errors.Count > 0)
            {
                currModelState.Errors.Clear();
                return(model);
            }
            if (!Selected)
            {
                return(model);
            }
            if (fields == null || fields.Length <= 0)
            {
                return(model);
            }
            PropertyAccessor pa = null;

            try
            {
                pa = new PropertyAccessor(fields[0], typeof(T));
            }
            catch { }
            if (pa == null)
            {
                return(model);
            }
            CanSortAttribute[] cs = pa[typeof(CanSortAttribute)] as CanSortAttribute[];
            if (cs == null || cs.Length == 0)
            {
                throw new NotAllowedColumnException(fields[0], typeof(T));
            }
            if (!cs[0].Allowed(Condition))
            {
                throw new NotAllowedFilteringException(Condition.ToString(), fields[0], typeof(T));
            }
            Expression <Func <T, bool> > previousFilter = model as Expression <Func <T, bool> >;
            FilterBuilder <T>            filterBuilder  = new FilterBuilder <T>();

            if (previousFilter != null)
            {
                filterBuilder.Add(true, previousFilter);
            }
            try
            {
                filterBuilder.Add(Condition, fields[0], new TypedConstant {
                    ConstantValue = Search, ConstantType = typeof(F)
                });
            }
            catch
            {
                return(model);
            }
            string key = modelName + "_Filter_" + fields[0] + "_Filter_" + fields[1];

            store[key] = this;
            return(filterBuilder.Get());
        }
Esempio n. 20
0
        private static string GetErrorMessage(ModelError error, ModelState modelState)
        {
            if (!IsNullOrEmpty(error.ErrorMessage))
                return error.ErrorMessage;

            return modelState.Value == null
                       ? error.ErrorMessage
                       : Format(CultureInfo.CurrentCulture, ValueNotValidForProperty, modelState.Value.AttemptedValue);
        }
 public static void SetError(this ViewContext viewContext, string name, string errorValue)
 {
     var modelerror = new ModelState()
                      {
                          Value = new ValueProviderResult(errorValue, errorValue, new CultureInfo("en-AU"))
                      };
     modelerror.Errors.Add("Error");
     viewContext.ViewData.ModelState.Add(name, modelerror);
 }
Esempio n. 22
0
 private void SetModelState(ModelBindingContext bindingContext, ValueProviderResult valueProviderResult)
 {
     ModelState modelState;
     if (!bindingContext.ModelState.TryGetValue(bindingContext.ModelName, out modelState))
     {
         bindingContext.ModelState.Add(bindingContext.ModelName, modelState = new ModelState());
     }
     modelState.Value = valueProviderResult;
 }
 private bool HasErrorMessage(ModelState modelState, string errorMessage)
 {
     foreach (var error in modelState.Errors)
     {
         if (error.ErrorMessage == errorMessage)
             return true;
     }
     return false;
 }
        /// <summary>
        /// Returns the value in model state for the specified <paramref name="key"/> converted the to <paramref name="destinationType"/>, or null if it is not found.
        /// </summary>
        /// <param name="modelStateDictionary">The instance of <see cref="System.Web.Mvc.ModelStateDictionary"/> that is being extended.</param>
        /// <param name="key">The key.</param>
        /// <param name="destinationType">The value type.</param>
        /// <param name="modelState">An instance <see cref="System.Web.Mvc.ModelState"/>, or null if it is not found.</param>
        /// <returns>The value in model state.</returns>
        public static object GetModelStateValue( this ModelStateDictionary modelStateDictionary, string key, Type destinationType, out ModelState modelState )
        {
            if( !modelStateDictionary.TryGetValue( key, out modelState ) || modelState.Value == null )
            {
                return null;
            }

            return modelState.Value.ConvertTo( destinationType, null );
        }
 public static void CreateValidationMessage(this ControllerBase controller, string key, string message)
 {
     controller.ViewData.ModelState.Remove(key);
     ModelState modalState = new ModelState
                                 {
                                     Value = controller.ValueProvider.GetValue(key)
                                 };
     modalState.Errors.Add(new ModelError(message));
     controller.ViewData.ModelState.Add(key, modalState);
 }
Esempio n. 26
0
        private static string GetUserErrorMessageOrDefault(HttpContextBase httpContext, ModelError error, ModelState modelState)
        {
            if (!string.IsNullOrEmpty(error.ErrorMessage))
                return error.ErrorMessage;

            if (modelState == null)
                return null;

            string value = (modelState.Value != null) ? modelState.Value.AttemptedValue : null;
            return string.Format(CultureInfo.CurrentCulture, "The value '{0}' is invalid.", value);
        }
Esempio n. 27
0
        private static string GetErrorMessage(ModelError error, ModelState modelState)
        {
            if (!string.IsNullOrEmpty(error.ErrorMessage))
                return error.ErrorMessage;

            if (modelState.Value == null)
                return error.ErrorMessage;

            var args = new object[] {modelState.Value.AttemptedValue};
            return string.Format("ValueNotValidForProperty=El valor '{0}' es invalido ", args);
        }
        public void GetValue_should_not_throw_exception_when_try_to_convert_value_from_ModelState()
        {
            result = new ValueProviderResult("11/22/2000", "11/22/2000", new CultureInfo("en-US"));
            state = new ModelState();
            state.Value = result;

            viewContext.ViewData.ModelState.Remove("DatePicker1");
            viewContext.ViewData.ModelState.Add("DatePicker1", state);

            System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");

            Assert.DoesNotThrow(() => datepicker.GetValue(o => (DateTime?)o));
        }
        public InputComponentExtensionsTests()
        {
            viewContext = TestHelper.CreateViewContext();
            datepicker = DatePickerTestHelper.CreateDatePicker(null, viewContext);
            datepicker.Name = "DatePicker1";

            result = new ValueProviderResult("s", "s", System.Threading.Thread.CurrentThread.CurrentCulture);
            state = new ModelState();
            state.Value = result;

            viewContext.ViewData.ModelState.Add("DatePicker1", state);
            currentCulture = CultureInfo.CurrentCulture;
        }
Esempio n. 30
0
 private static string GetErrorMessage(ModelError error, ModelState modelState)
 {
     if (!string.IsNullOrEmpty(error.ErrorMessage))
     {
         return error.ErrorMessage;
     }
     if (modelState.Value == null)
     {
         return error.ErrorMessage;
     }
     object[] args = new object[] { modelState.Value.AttemptedValue };
     return string.Format("ValueNotValidForProperty=The value '{0}' is invalid", args);
 }
        public void SerializeModelError()
        {
            var errors = new List<KeyValuePair<string, ModelState>>();
            var state = new ModelState();
            state.Errors.Add("some error");
            errors.Add(new KeyValuePair<string, ModelState>("Something", state));
            var modelError = new ModelStateJson(errors);
            var response = new JsonResponse(false, modelError);

            var actual = JsonConvert.SerializeObject(response);

            Assert.Equal(@"{""success"":false,""contentType"":""model-errors"",""body"":{""Something"":[""some error""]}}", actual);
        }
Esempio n. 32
0
        public object BindModel(ControllerContext controllerContext,
			ModelBindingContext bindingContext)
        {
            ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            ModelState modelState = new ModelState { Value = valueResult };
            object actualValue = null;
            if (valueResult != null) {
                string value = valueResult.AttemptedValue.ToString();

                actualValue = DataTypeHelper.ToDecimal(value);
            }
            return actualValue;
        }
Esempio n. 33
0
 protected bool CheckMemberInitStatus()
 {
     if (Startup.MemberInitSuccess)
     {
         return(true);
     }
     else
     {
         ModelState err = new System.Web.Mvc.ModelState();
         err.Errors.Add(ResourceUtils.GetString("8dde84756da744ecb1b23ecc193e8b25", "The membership data service is not setup or is not configured correctly!"));
         ModelState.Add(new KeyValuePair <string, ModelState>(ResourceUtils.GetString("cd4f3b92a1bfec06df534f9f6e65059a", "Member Service Failed"), err));
         return(false);
     }
 }
Esempio n. 34
0
        public async Task <ActionResult> ChangePassword(ChangePasswordViewModel model)
        {
            ActionResult actionResult;
            bool         flag = this.HasPassword();

            ((dynamic)this.ViewBag).HasLocalPassword = flag;
            ((dynamic)this.ViewBag).ReturnUrl        = this.Url.Action("Index", "Home");
            if (!flag)
            {
                System.Web.Mvc.ModelState item = this.ModelState["OldPassword"];
                if (item != null)
                {
                    item.Errors.Clear();
                }
                if (this.ModelState.IsValid)
                {
                    IdentityResult identityResult = await this.UserManager.AddPasswordAsync(this.GetGuid(this.User.Identity.GetUserId()), model.NewPassword);

                    IdentityResult identityResult1 = identityResult;
                    if (!identityResult1.Succeeded)
                    {
                        this.AddErrors(identityResult1);
                    }
                    else
                    {
                        this.Response.Cookies.Add(new HttpCookie("system_message", string.Format(MessageUI.UpdateSuccess, FormUI.Password)));
                        actionResult = this.View();
                        return(actionResult);
                    }
                }
            }
            else if (this.ModelState.IsValid)
            {
                IdentityResult identityResult2 = await this.UserManager.ChangePasswordAsync(this.GetGuid(this.User.Identity.GetUserId()), model.OldPassword, model.NewPassword);

                IdentityResult identityResult3 = identityResult2;
                if (!identityResult3.Succeeded)
                {
                    this.AddErrors(identityResult3);
                }
                else
                {
                    this.Response.Cookies.Add(new HttpCookie("system_message", string.Format(MessageUI.ErrorMessageWithFormat, FormUI.Password)));
                    actionResult = this.View();
                    return(actionResult);
                }
            }
            actionResult = this.View();
            return(actionResult);
        }
        private static string GetErrorMessage(ModelError error, ModelState modelState)
        {
            if (!error.ErrorMessage.HasValue())
            {
                if (modelState.Value == null)
                {
                    return error.ErrorMessage;
                }

                return Exceptions.ValueNotValidForProperty.FormatWith(modelState.Value.AttemptedValue);
            }

            return error.ErrorMessage;
        }
Esempio n. 36
0
        public async Task <ActionResult> ChangePassword(ChangePasswordViewModel model)
        {
            ActionResult action;
            bool         flag = this.HasPassword();

            ((dynamic)this.ViewBag).HasLocalPassword = flag;
            ((dynamic)this.ViewBag).ReturnUrl        = this.Url.Action("Index", "Home");
            if (!flag)
            {
                System.Web.Mvc.ModelState item = this.ModelState["OldPassword"];
                if (item != null)
                {
                    item.Errors.Clear();
                }
                if (this.ModelState.IsValid)
                {
                    IdentityResult identityResult = await this.UserManager.AddPasswordAsync(this.GetGuid(this.User.Identity.GetUserId()), model.NewPassword);

                    IdentityResult identityResult1 = identityResult;
                    if (!identityResult1.Succeeded)
                    {
                        this.AddErrors(identityResult1);
                    }
                    else
                    {
                        action = this.RedirectToAction("PostManagement", "Account", new { area = "" });
                        return(action);
                    }
                }
            }
            else if (this.ModelState.IsValid)
            {
                IdentityResult identityResult2 = await this.UserManager.ChangePasswordAsync(this.GetGuid(this.User.Identity.GetUserId()), model.OldPassword, model.NewPassword);

                if (!identityResult2.Succeeded)
                {
                    ((dynamic)this.ViewBag).Error = "Mật khẩu cũ không chính xác.";
                }
                else
                {
                    action = this.RedirectToAction("PostManagement", "Account", new { area = "" });
                    return(action);
                }
            }
            action = this.View();
            return(action);
        }
Esempio n. 37
0
        public object UpdateModel(object model, string[] fields)
        {
            System.Web.Mvc.ModelState currModelState = ModelState[string.Format("{1}.$${0}.$.Search", Index, modelName)];
            if (currModelState.Errors.Count > 0)
            {
                currModelState.Errors.Clear();
                return(model);
            }
            if (!Selected)
            {
                return(model);
            }
            if (fields == null || fields.Length <= 0)
            {
                return(model);
            }
            PropertyAccessor pa = null;

            try
            {
                pa = new PropertyAccessor(fields[0], typeof(T));
            }
            catch { }
            if (pa == null)
            {
                return(model);
            }
            CanSortAttribute[] cs = pa[typeof(CanSortAttribute)] as CanSortAttribute[];
            if (cs == null || cs.Length == 0)
            {
                return(model);
            }
            string key = modelName + "_Filter_" + fields[0] + "_Filter_" + fields[1];

            store[key] = this;
            Expression <Func <T, bool> > previousFilter = model as Expression <Func <T, bool> >;
            FilterBuilder <T>            filterBuilder  = new FilterBuilder <T>();

            if (previousFilter != null)
            {
                filterBuilder.Add(true, previousFilter);
            }
            filterBuilder.Add(Condition, fields[0], Search);
            return(filterBuilder.Get());
        }
Esempio n. 38
0
        public override object BindModel(
            Mvc.ControllerContext controllerContext,
            Mvc.ModelBindingContext bindingContext)
        {
            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            var modelState = new Mvc.ModelState {
                Value = valueProviderResult
            };

            var value = (valueProviderResult != null) ? valueProviderResult.AttemptedValue : null;

            var model = new ArticleId(value ?? string.Empty);

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);

            return(model);
        }
        public override object BindModel(
            Mvc.ControllerContext controllerContext,
            Mvc.ModelBindingContext bindingContext)
        {
            var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            var modelState = new Mvc.ModelState {
                Value = valueProviderResult
            };

            string value = (valueProviderResult != null) ? valueProviderResult.AttemptedValue : null;

            var model = !string.IsNullOrWhiteSpace(value) ? new ArticleRevisionDate(value) : ArticleRevisionDate.Empty;

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);

            return(model);
        }
Esempio n. 40
0
        /// <summary>
        /// Genera un objeto Json a partir de los valores del ModelState
        /// </summary>
        /// <param name="controller"></param>
        /// <returns>Devuelve una cadena con los valores del ModelState</returns>
        public static string ModelStateToJson(this Controller controller)
        {
            string          jsonResult = "{}";
            ModelStateItems results    = new ModelStateItems();

            for (int i = 0; i < controller.ModelState.Values.Count; i++)
            {
                System.Web.Mvc.ModelState state = controller.ModelState.Values.ToList()[i];
                string key = controller.ModelState.Keys.ToList()[0];
                foreach (ModelError errors in state.Errors)
                {
                    results.AddMessage(key, errors.ErrorMessage == "" ? errors.Exception.Message : errors.ErrorMessage);
                }
            }

            jsonResult = NetLibrary.Serialization.JSONEncode(results);
            return(jsonResult);
        }
Esempio n. 41
0
        /// <summary>
        /// Add error message
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="screen"></param>
        /// <param name="module"></param>
        /// <param name="code"></param>
        /// <param name="id"></param>
        /// <param name="param"></param>
        public void AddErrorMessage(string controller, string screen, string module, MessageUtil.MessageList code, string id, params string[] param)
        {
            try
            {
                if (_iValidatorUtil.ModelState != null)
                {
                    string template = string.Empty;

                    if (CommonUtil.IsNullOrEmpty(controller) == false)
                    {
                        template += controller;
                    }
                    template += SPLIT_TEMPLATE_MESSAGE;
                    if (CommonUtil.IsNullOrEmpty(screen) == false)
                    {
                        template += screen;
                    }
                    template += SPLIT_TEMPLATE_MESSAGE;

                    template += module + SPLIT_TEMPLATE_MESSAGE;
                    template += code.ToString() + SPLIT_TEMPLATE_MESSAGE;

                    if (param != null)
                    {
                        foreach (string pm in param)
                        {
                            template += pm + SPLIT_TEMPLATE_MESSAGE;
                        }
                    }
                    ModelState state = new System.Web.Mvc.ModelState();
                    state.Errors.Add(template);
                    _iValidatorUtil.ModelState.Add(id, state);
                    _iValidatorUtil.IsValid = false;
                    this.IsValid            = false;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
        {
            var valueResult = bindingContext.ValueProvider
                              .GetValue(bindingContext.ModelName);
            var modelState = new System.Web.Mvc.ModelState {
                Value = valueResult
            };
            Object actualValue = null;

            try
            {
                actualValue = Convert.ToDouble(valueResult.AttemptedValue.Replace(".", ","), CultureInfo.CurrentCulture);
            }
            catch (FormatException e)
            {
                modelState.Errors.Add(e);
            }

            bindingContext.ModelState.Add(bindingContext.ModelName, modelState);
            return(actualValue);
        }
Esempio n. 43
0
        public virtual PartialViewResult UpdateWebFormAjax(int?id, WebFormEditAdminViewModel WebFormEditAdminViewModel, WebFormFieldEditAdminViewModel[] WebFormFields, string FastAddField)
        {
            if (!id.HasValue)
            {
                return(HttpBadRequestPartial("id is null"));
            }

            if (WebFormEditAdminViewModel.WebFormId == 0)
            {
                return(HttpBadRequestPartial("Web Form Id in view model is 0"));
            }

            if (WebFormEditAdminViewModel.WebFormId != id.Value)
            {
                return(HttpBadRequestPartial("Web Form Id mismatch. Parameter value: '" + id.Value + "' != view model value: " + WebFormEditAdminViewModel.WebFormId));
            }

            StoreFront storeFront      = CurrentStoreFrontOrThrow;
            WebForm    webFormToUpdate = storeFront.Client.WebForms.SingleOrDefault(wf => wf.WebFormId == WebFormEditAdminViewModel.WebFormId);

            if (webFormToUpdate == null)
            {
                throw new ApplicationException("Web Form not found in client web forms. WebFormId: " + WebFormEditAdminViewModel.WebFormId + " Client '" + storeFront.Client.Name + "' [" + storeFront.ClientId + "]");
            }

            bool nameIsValid    = GStoreDb.ValidateWebFormName(this, WebFormEditAdminViewModel.Name, storeFront.ClientId, WebFormEditAdminViewModel.WebFormId);
            bool fastAddIsValid = false;

            if (!string.IsNullOrWhiteSpace(FastAddField))
            {
                fastAddIsValid = GStoreDb.ValidateWebFormFieldName(this, FastAddField, storeFront.ClientId, WebFormEditAdminViewModel.WebFormId, null);
            }

            if (nameIsValid && ModelState.IsValid)
            {
                WebForm webForm = null;
                try
                {
                    webForm = GStoreDb.UpdateWebForm(WebFormEditAdminViewModel, storeFront, CurrentUserProfileOrThrow);
                    WebFormEditAdminViewModel.UpdateWebForm(webForm);

                    if (WebFormFields != null && WebFormFields.Count() > 0)
                    {
                        foreach (WebFormFieldEditAdminViewModel field in WebFormFields)
                        {
                            GStoreDb.UpdateWebFormField(field, storeFront, CurrentUserProfileOrThrow);
                        }
                    }

                    if (fastAddIsValid)
                    {
                        WebFormField newField = GStoreDb.CreateWebFormFieldFastAdd(WebFormEditAdminViewModel, FastAddField, storeFront, CurrentUserProfileOrThrow);
                        AddUserMessage("Field Created!", "Field '" + newField.Name.ToHtml() + "' [" + newField.WebFormFieldId + "] created successfully.", UserMessageType.Success);
                        ModelState.Remove("FastAddField");
                    }

                    AddUserMessage("Web Form Changes Saved!", "Web Form '" + webForm.Name.ToHtml() + "' [" + webForm.WebFormId + "] saved successfully for Client '" + storeFront.Client.Name.ToHtml() + "' [" + storeFront.ClientId + "]", UserMessageType.Success);
                    this.ModelState.Clear();
                    WebFormEditAdminViewModel = new WebFormEditAdminViewModel(CurrentStoreFrontOrThrow, CurrentUserProfileOrThrow, webForm, isStoreAdminEdit: true, activeTab: WebFormEditAdminViewModel.ActiveTab, sortBy: WebFormEditAdminViewModel.SortBy, sortAscending: WebFormEditAdminViewModel.SortAscending);
                    return(PartialView("_WebFormEditPartial", WebFormEditAdminViewModel));
                }
                catch (Exception ex)
                {
                    string errorMessage = "An error occurred while saving your changes to Web Form '" + WebFormEditAdminViewModel.Name + "' [" + WebFormEditAdminViewModel.WebFormId + "] for Client: '" + storeFront.Client.Name + "' [" + storeFront.ClientId + "] \nError: '" + ex.GetType().FullName + "'";

                    if (CurrentUserProfileOrThrow.AspNetIdentityUserIsInRoleSystemAdmin())
                    {
                        errorMessage += " \nException.ToString(): '" + ex.ToString() + "'";
                    }
                    AddUserMessage("Error Saving Web Form!", errorMessage.ToHtmlLines(), UserMessageType.Danger);
                    ModelState.AddModelError("Ajax", errorMessage);
                }
            }
            else
            {
                AddUserMessage("Web Form Edit Error", "There was an error with your entry for Web Form " + WebFormEditAdminViewModel.Name.ToHtml() + " [" + WebFormEditAdminViewModel.WebFormId + "] for Client '" + storeFront.Client.Name.ToHtml() + "' [" + storeFront.ClientId + "]. Please correct it.", UserMessageType.Danger);
            }

            foreach (string key in this.ModelState.Keys.Where(k => k.StartsWith("WebFormFields[")).ToList())
            {
                string temp = key.Remove(0, ("WebFormFields[").Length);
                temp = temp.Remove(temp.IndexOf(']'));
                int index = int.Parse(temp);

                System.Web.Mvc.ModelState value = null;
                this.ModelState.TryGetValue(key, out value);
                if (value.Errors.Count == 0)
                {
                    this.ModelState.Remove(key);
                }
                else
                {
                    this.ModelState.AddModelError("", "There was an error with field #" + (index + 1) + ". Please correct it and save again.");
                }
            }


            WebFormEditAdminViewModel.FillFieldsFromViewModel(webFormToUpdate, WebFormFields);
            WebFormEditAdminViewModel.IsStoreAdminEdit = true;
            return(PartialView("_WebFormEditPartial", WebFormEditAdminViewModel));
        }
Esempio n. 44
0
 public FormFactoryModelState(System.Web.Mvc.ModelState ms)
 {
     _ms = ms;
 }