public override bool IsValid(object value)
        {
            if (_ValueProvider == null)
            {
                throw new Exception("No value provider for context.");
            }
            string password = (_ValueProvider.KeyValue("Password") ?? new Object()).ToString();
            string confirm  = (_ValueProvider.KeyValue("ConfirmPassword") ?? new Object()).ToString();

            if (password == confirm)
            {
                return(true);
            }
            return(false);
        }
Пример #2
0
        /// <summary>
        /// Updates the specified model instance using values from the value provider.
        /// </summary>
        /// <typeparam name="TModel">The type of the model object.</typeparam>
        /// <param name="model">The model instance to update.</param>
        /// <param name="prefix">The prefix to use when looking up values in the value provider.</param>
        /// <param name="includeProperties">A list of properties of the model to update.</param>
        /// <param name="excludeProperties">A list of properties to explicitly exclude from the update. These are excluded even if they are listed in the includeProperties parameter list.</param>
        public static void UpdateModel <TModel>(IWFValueProvider valueprovider, TModel model, string prefix, string[] includeProperties, string[] excludeProperties)
        {
            if (model == null)
            {
                throw new Exception("Model cannot be null!");
            }
            Type t = typeof(TModel);

            PropertyInfo[] props = t.GetProperties();

            //var query = props.AsQueryable();
            var query = valueprovider.GetPropertyEnumerator();

            if (includeProperties != null)
            {
                query = query.Where(p => includeProperties.Contains(p));
            }
            if (excludeProperties != null && excludeProperties.Length > 0)
            {
                query = query.Where(p => !excludeProperties.Contains(p));
            }

            foreach (string s in query)
            {
                string propExpression = s;
                //When searching for the target property, we ignore the prefix
                if (!String.IsNullOrEmpty(prefix) && s.StartsWith(prefix))
                {
                    //If there is a prefix, and it is found in this string, remove it
                    propExpression = s.Substring(prefix.Length);
                }
                //Use the resulting string to find the target property without the prefix
                PropertyInfo pi           = WFUtilities.GetTargetProperty(propExpression, t, true);
                object       targetObject = WFUtilities.GetTargetObject(propExpression, model);
                if (pi != null)
                {
                    try {
                        if (pi.PropertyType.IsEnum)
                        {
                            pi.SetValue(targetObject, Enum.Parse(pi.PropertyType, valueprovider.KeyValue(prefix + s).ToString()), null);
                        }
                        else if (pi.PropertyType == typeof(Int32?) ||
                                 pi.PropertyType == typeof(Double?) ||
                                 pi.PropertyType == typeof(DateTime?))
                        {
                            object kV = valueprovider.KeyValue(prefix + s);
                            if (kV == null)
                            {
                                pi.SetValue(targetObject, null, null);
                            }
                            else
                            {
                                pi.SetValue(targetObject, WFUtilities.ParseNullable(pi.PropertyType, kV.ToString()), null);
                            }
                        }
                        else if (pi.PropertyType == typeof(Boolean?) || pi.PropertyType == typeof(bool))
                        {
                            string[] trueValues = new string[] { "true", "true,false", "on" };

                            object kV      = valueprovider.KeyValue(prefix + s);
                            string kString = (kV == null ? "" : kV.ToString()).Trim();

                            if (String.IsNullOrEmpty(kString) || kString.ToLower() == "null") //If the value passed is empty...
                            {
                                if (pi.PropertyType == typeof(Boolean?))                      //..and it is nullable, set to null.
                                {
                                    pi.SetValue(targetObject, null, null);
                                }
                                else if (pi.PropertyType == typeof(bool))                                            //..and not nullable, set to false.
                                {
                                    pi.SetValue(targetObject, false, null);
                                }
                            }
                            else if (kString == "off" || kString == "false") //If the value passed is false/off...
                            {
                                pi.SetValue(targetObject, false, null);      //...set to false.
                            }
                            else if (trueValues.Contains(kString))           //If the value passed is "true"...
                            {
                                pi.SetValue(targetObject, true, null);       //...set to true
                            }
                            else
                            {
                                //If all else fails, at least try to convert it to boolean
                                pi.SetValue(targetObject, Convert.ChangeType(kString, pi.PropertyType), null);
                            }
                        }
                        else
                        {
                            Type[] defaultTypes = new Type[]
                            { typeof(byte), typeof(short), typeof(int), typeof(long), typeof(float), typeof(double), typeof(decimal),
                              typeof(DateTime) };
                            if (defaultTypes.Contains(pi.PropertyType))
                            {
                                object kV = valueprovider.KeyValue(prefix + s);
                                if (kV != null && !String.IsNullOrEmpty(kV.ToString()))
                                {
                                    //Get the value
                                    pi.SetValue(targetObject, Convert.ChangeType((valueprovider.KeyValue(prefix + s).ToString()), pi.PropertyType), null);
                                }
                                else
                                {
                                    //Set default value
                                    if (pi.PropertyType == typeof(DateTime))
                                    {
                                        pi.SetValue(targetObject, default(DateTime), null);
                                    }
                                    else
                                    {
                                        pi.SetValue(targetObject, Activator.CreateInstance(pi.PropertyType), null); //Set to default value
                                    }
                                }
                            }
                            else
                            {
                                pi.SetValue(targetObject, Convert.ChangeType((valueprovider.KeyValue(prefix + s)), pi.PropertyType), null);
                            }
                        }
                    } catch (Exception ex) {
                        throw new Exception("An exception occurred updating a model from property [" + s + "] value supplied [" + (valueprovider.KeyValue(prefix + s) ?? "null/empty").ToString() + "]. InnerException may have additional information. The message was: " + ex.Message, ex);
                    }
                }
            }
        }
Пример #3
0
        /// <summary>
        /// Root TryValidateModel() method. Returns false if any validation errors are found.
        /// </summary>
        /// <param name="model">A pointer to the current model object</param>
        /// <param name="prefix">Optional. A prefix to search and filter values from the value provider.</param>
        /// <param name="values">A class implementing IWFValueProvider (examples include WFObjectValueProvider and WFHttpContextValueProvider)</param>
        /// <param name="metadata">Optional. Required to collect error data or show error markup on a page. The current WFModelMetaData object.</param>
        /// <param name="ruleProvider">A class implementing IWFRuleProvider (examples include WFTypeRuleProvider and WFXmlRuleSetRuleProvider).<br/>
        /// This object provides the rules (ie: DataAnnotations) that needed to be validated, and which properties to validate them against.<br/>
        /// All other properties are ignored.</param>
        /// <returns>Returns false if any validation errors were found.</returns>
        public static bool TryValidateModel(object model, string prefix, IWFValueProvider values, WFModelMetaData metadata, IWFRuleProvider ruleProvider)
        {
            bool validated = true;

            //Make sure we have metadata
            metadata        = metadata == null ? metadata = new WFModelMetaData() : metadata;
            metadata.Errors = new List <string>();

            //Create a rule provider if one was not provided. WFTypeRuleProvider will handle [MetadataType]
            ruleProvider = ruleProvider == null ? new WFTypeRuleProvider(model) : ruleProvider;

            validated = validateModelAttributes(model, ruleProvider.GetClassValidationAttributes(), metadata.Errors, ruleProvider.ModelDisplayName);

            if (metadata.Errors.Count > 0)
            {
                validated = false;
            }

            foreach (PropertyInfo pi in ruleProvider.GetProperties())
            {
                if (values.ContainsKey(prefix + pi.Name))
                {
                    WFModelMetaProperty metaprop = null;
                    foreach (ValidationAttribute attr in ruleProvider.GetPropertyValidationAttributes(pi.Name))
                    {
                        if (attr as IWFRequireValueProviderContext != null)
                        {
                            ((IWFRequireValueProviderContext)attr).SetValueProvider(values);
                        }

                        string displayName = ruleProvider.GetDisplayNameForProperty(pi.Name);
                        bool   isValid     = false;
                        if (attr.GetType() == typeof(RangeAttribute))
                        {
                            try { isValid = attr.IsValid(values.KeyValue(prefix + pi.Name)); } catch (Exception ex) {
                                if (ex.GetType() == typeof(FormatException))
                                {
                                    isValid = false;
                                }
                                else
                                {
                                    throw ex;
                                }
                            }
                        }
                        else
                        {
                            isValid = attr.IsValid(values.KeyValue(prefix + pi.Name));
                        }

                        if (!isValid)
                        {
                            validated = false;
                            metadata.Errors.Add(attr.FormatErrorMessage(displayName));

                            if (metaprop == null) // Try to find it ...
                            {
                                foreach (WFModelMetaProperty mx in metadata.Properties)
                                {
                                    if (mx.ModelObject == model && pi.Name.ToLower() == mx.PropertyName.ToLower())
                                    {
                                        metaprop = mx;
                                        break;
                                    }
                                }
                            }
                            if (metaprop == null) // Make a new one ...
                            {
                                metaprop              = new WFModelMetaProperty();
                                metaprop.ModelObject  = model;
                                metaprop.PropertyName = pi.Name;
                                metaprop.DisplayName  = displayName;
                                metaprop.MarkupName   = prefix + pi.Name;
                                metaprop.ValidationAttributes.Add(attr);

                                metadata.Properties.Add(metaprop);
                            }
                            metaprop.HasError = true;
                            metaprop.Errors.Add(attr.FormatErrorMessage(displayName));
                        }
                    }
                }
            }
            return(validated);
        }
Пример #4
0
        public static void ApplyModelToPage(Control pageControl, IWFValueProvider provider)
        {
            Dictionary <string, Control> webControls = FlattenPageControls(pageControl);

            foreach (KeyValuePair <string, Control> kvp in webControls)
            {
                if (provider.ContainsKey(kvp.Key))
                {
                    Control wc = kvp.Value;
                    if (wc.GetType() == typeof(TextBox))
                    {
                        ((TextBox)wc).Text = provider.KeyValue(kvp.Key, "").ToString();
                    }
                    else if (wc.GetType() == typeof(DropDownList))
                    {
                        DropDownList ddl = (DropDownList)wc;
                        if (ddl.Items != null && ddl.Items.Count > 0)
                        {
                            ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue(provider.KeyValue(kvp.Key, "").ToString()));
                        }
                    }
                    else if (wc.GetType() == typeof(ListBox))
                    {
                        ListBox lb = (ListBox)wc;
                        if (lb.Items != null && lb.Items.Count > 0)
                        {
                            if (lb.SelectionMode == ListSelectionMode.Single)
                            {
                                lb.SelectedIndex = lb.Items.IndexOf(lb.Items.FindByValue(provider.KeyValue(kvp.Key, "").ToString()));
                            }
                            else
                            {
                                object val = provider.KeyValue(kvp.Key, "");
                                if (val != null)
                                {
                                    if (val as IEnumerable != null &&
                                        val.GetType() != typeof(String))
                                    {
                                        foreach (var x in val as IEnumerable)
                                        {
                                            lb.Items.FindByValue(x.ToString()).Selected = true;
                                        }
                                    }
                                    else
                                    {
                                        lb.SelectedIndex = lb.Items.IndexOf(lb.Items.FindByValue(provider.KeyValue(kvp.Key, "").ToString()));
                                    }
                                }
                            }
                        }
                    }
                    else if (wc.GetType() == typeof(RadioButton))
                    {
                        RadioButton rb  = (RadioButton)wc;
                        object      val = provider.KeyValue(kvp.Key);
                        if (val != null)
                        {
                            string valStr = val.ToString();
                            if (String.IsNullOrEmpty(valStr))
                            {
                                rb.Checked = false;
                            }
                            else
                            {
                                string[] truth = { "1", "true", "true,false" };
                                if (truth.Contains(valStr.ToLower()))
                                {
                                    rb.Checked = true;
                                }
                            }
                        }
                        else
                        {
                            rb.Checked = false;
                        }
                    }
                    else if (wc.GetType() == typeof(CheckBox))
                    {
                        CheckBox cb  = (CheckBox)wc;
                        object   val = provider.KeyValue(kvp.Key);
                        if (val != null)
                        {
                            string valStr = val.ToString();
                            if (String.IsNullOrEmpty(valStr))
                            {
                                cb.Checked = false;
                            }
                            else
                            {
                                string[] truth = { "1", "true", "true,false" };
                                if (truth.Contains(valStr.ToLower()))
                                {
                                    cb.Checked = true;
                                }
                            }
                        }
                        else
                        {
                            cb.Checked = false;
                        }
                    }
                    else
                    {
                        //Not a known type, does it implement IWFControlValue?
                        if (wc as IWFControlValue != null)
                        {
                            //Set it through the interface
                            ((IWFControlValue)kvp.Value).SetControlValue(provider.KeyValue(kvp.Key));
                        }
                        else
                        {
                            //Not a known type and doesn't implement the interface. We don't know how to assign values to this control.
                            throw new Exception("Error trying to apply value to control " + wc.ID + " typeof [" + wc.GetType().Name + "]. It is not a known type and does not implement IWFControlValue.");
                        }
                    }
                }
            }
        }