public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelType == typeof(AddSheduleViewModel))
            {
                HttpRequestBase request = controllerContext.HttpContext.Request;
                var model = base.BindModel(controllerContext, bindingContext) as AddSheduleViewModel;
                bindingContext.ModelState.Clear();
                var shedule = request.Form["Shedule"];
                    Regex reg = new Regex(@"\d{1,2}:\d{1,2}");
                    MatchCollection matches = reg.Matches(shedule);
                if (matches.Count != 0)
                {
                    try
                {

                        model.Shedule = matches.Cast<Match>().Select(x => TimeSpan.Parse(x.Value)).ToList();

                }
                catch(Exception ex)
                {
                        NLog.LogManager.GetCurrentClassLogger().Error(ex);
                        bindingContext.ModelState.AddModelError("", "Неверно заполнено расписание");
                }
                }
                return model;

            }
            else
            {
                return base.BindModel(controllerContext, bindingContext);
            }
        }
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var obj = new DataTablesParam();
            var request = controllerContext.HttpContext.Request.Params;

            obj.iDisplayStart = Convert.ToInt32(request["iDisplayStart"]);
            obj.iDisplayLength = Convert.ToInt32(request["iDisplayLength"]);
            obj.iColumns = Convert.ToInt32(request["iColumns"]);
            obj.sSearch = request["sSearch"];
            obj.bEscapeRegex = Convert.ToBoolean(request["bEscapeRegex"]);
            obj.iSortingCols = Convert.ToInt32(request["iSortingCols"]);
            obj.sEcho = int.Parse(request["sEcho"]);

            for (int i = 0; i < obj.iColumns; i++)
            {
                obj.bSortable.Add(Convert.ToBoolean(request["bSortable_" + i]));
                obj.bSearchable.Add(Convert.ToBoolean(request["bSearchable_" + i]));
                obj.sSearchColumns.Add(request["sSearch_" + i]);
                obj.bEscapeRegexColumns.Add(Convert.ToBoolean(request["bEscapeRegex_" + i]));
                obj.iSortCol.Add(Convert.ToInt32(request["iSortCol_" + i]));
                obj.sSortDir.Add(request["sSortDir_" + i]);
            }

            return obj;
        }
Пример #3
0
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (controllerContext == null)
                throw new ArgumentNullException("controllerContext", "controllerContext is null.");
            if (bindingContext == null)
                throw new ArgumentNullException("bindingContext", "bindingContext is null.");

            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (value == null) return null;

            bindingContext.ModelState.SetModelValue(bindingContext.ModelName, value);

            try
            {
                var date = value.ConvertTo(typeof(DateTime), CurrentRequestData.CultureInfo);

                return date;
            }
            catch (Exception ex)
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, ex);
                return null;
            }
        }
Пример #4
0
        public override object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
        {
            var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
            var value         = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (value.AttemptedValue == "TBD")
            {
                return(null);
            }
            if (!string.IsNullOrEmpty(displayFormat) && value != null)
            {
                DateTime date;
                displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
                // use the format specified in the DisplayFormat attribute to parse the date
                if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
                {
                    // we always work with UTC times, only in UI we display in local time
                    return(DateTime.SpecifyKind(date, DateTimeKind.Utc));
                }
                else
                {
                    bindingContext.ModelState.AddModelError(
                        bindingContext.ModelName,
                        string.Format("{0} is an invalid date format", value.AttemptedValue)
                        );
                }
            }

            return(base.BindModel(controllerContext, bindingContext));
        }
Пример #5
0
        public override object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
        {
            var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
            var value         = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            /*
             * if (!string.IsNullOrEmpty(displayFormat) && value != null)
             * {
             *  DateTime date;
             *  displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
             *  // use the format specified in the DisplayFormat attribute to parse the date
             *  if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
             *  {
             *      return date;
             *  }
             *  else
             *  {
             *      bindingContext.ModelState.AddModelError(
             *          bindingContext.ModelName,
             *          string.Format("{0} no es un formato de fecha válido", value.AttemptedValue)
             *      );
             *  }
             * }
             */

            return(base.BindModel(controllerContext, bindingContext));
        }
Пример #6
0
 public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
 {
     var stringified = controllerContext.HttpContext.Request[bindingContext.ModelName];
     if (string.IsNullOrEmpty(stringified))
         return null;
     return Serializer.Deserialize(stringified, bindingContext.ModelType);
 }
Пример #7
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);
    }
 private static void CheckPropertyFilter(ModelBindingContext bindingContext)
 {
     if (bindingContext.ModelType.GetProperties().Select(p => p.Name).Any(name => !bindingContext.PropertyFilter(name)))
     {
         throw new InvalidOperationException(MvcResources.ExtensibleModelBinderAdapter_PropertyFilterMustNotBeSet);
     }
 }
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            CheckPropertyFilter(bindingContext);
            ExtensibleModelBindingContext newBindingContext = CreateNewBindingContext(bindingContext, bindingContext.ModelName);

            IExtensibleModelBinder binder = Providers.GetBinder(controllerContext, newBindingContext);
            if (binder == null && !String.IsNullOrEmpty(bindingContext.ModelName)
                && bindingContext.FallbackToEmptyPrefix && bindingContext.ModelMetadata.IsComplexType)
            {
                // fallback to empty prefix?
                newBindingContext = CreateNewBindingContext(bindingContext, String.Empty /* modelName */);
                binder = Providers.GetBinder(controllerContext, newBindingContext);
            }

            if (binder != null)
            {
                bool boundSuccessfully = binder.BindModel(controllerContext, newBindingContext);
                if (boundSuccessfully)
                {
                    // run validation and return the model
                    newBindingContext.ValidationNode.Validate(controllerContext, null /* parentNode */);
                    return newBindingContext.Model;
                }
            }

            return null; // something went wrong
        }
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            IPhotoService<User, PhotoAlbum, Photo, Friend> myPhotoService = new PhotoService<User, PhotoAlbum, Photo, Friend>(new FriendService<User, Friend>(new EntityHAVFriendRepository()), new EntityHAVPhotoAlbumRepository(), new EntityHAVPhotoRepository());
            User myUserInfo = HAVUserInformationFactory.GetUserInformation().Details;

            int myUserId = Int32.Parse(BinderHelper.GetA(bindingContext, "UserId"));
            int myAlbumId = Int32.Parse(BinderHelper.GetA(bindingContext, "AlbumId"));
            string myProfilePictureURL = BinderHelper.GetA(bindingContext, "ProfilePictureURL");
            string selectedProfilePictureIds = BinderHelper.GetA(bindingContext, "SelectedProfilePictureId").Trim();

            IEnumerable<Photo> myPhotos = myPhotoService.GetPhotos(SocialUserModel.Create(myUserInfo), myAlbumId, myUserId);

            string[] splitIds = selectedProfilePictureIds.Split(',');
            List<int> selectedProfilePictures = new List<int>();

            foreach (string id in splitIds) {
                if (id != string.Empty) {
                    selectedProfilePictures.Add(Int32.Parse(id));
                }
            }

            return new PhotosModel() {
                UserId = myUserId,
                ProfilePictureURL = myProfilePictureURL,
                Photos = myPhotos,
                SelectedPhotos = selectedProfilePictures
            };
        }
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            object result = null;
            var args = new BindModelEvent(controllerContext, bindingContext);
            StrixPlatform.RaiseEvent(args);

            if (args.IsBound)
            {
                result = args.Result;
            }
            else
            {
                result = base.BindModel(controllerContext, bindingContext);

                if (bindingContext.ModelMetadata.Container == null && result != null && result.GetType().Equals(typeof(string)))
                {
                    if (controllerContext.Controller.ValidateRequest)
                    {
                        int index;

                        if (IsDangerousString((string)result, out index))
                        {
                            throw new HttpRequestValidationException("Dangerous Input Detected");
                        }
                    }

                    result = GetSafeValue((string)result);
                }
            }

            return result;
        }
Пример #12
0
        GetModelProperties(ControllerContext controllerContext,
                           System.Web.Mvc.ModelBindingContext bindingContext)
        {
            var toReturn = base.GetModelProperties(controllerContext, bindingContext);

            List <PropertyDescriptor> additional = new List <PropertyDescriptor>();

            //now look for any aliasable properties in here
            foreach (var p in
                     this.GetTypeDescriptor(controllerContext, bindingContext)
                     .GetProperties().Cast <PropertyDescriptor>())
            {
                foreach (var attr in p.Attributes.OfType <BindAliasAttribute>())
                {
                    additional.Add(new AliasedPropertyDescriptor(attr.Alias, p));

                    if (bindingContext.PropertyMetadata.ContainsKey(p.Name))
                    {
                        bindingContext.PropertyMetadata.Add(attr.Alias,
                                                            bindingContext.PropertyMetadata[p.Name]);
                    }
                }
            }

            return(new PropertyDescriptorCollection
                       (toReturn.Cast <PropertyDescriptor>().Concat(additional).ToArray()));
        }
Пример #13
0
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.Model != null)
                throw new InvalidOperationException("Cannot update instances");

            if(controllerContext.RouteData.Values.ContainsKey("r"))
            {
                return new ReturnUrl
                           {
                               Url = controllerContext.RouteData.Values["r"].ToString()
                           };
            }
            else if(controllerContext.HttpContext.Request.QueryString["r"] != null)
            {
                return new ReturnUrl
                           {
                               Url = controllerContext.HttpContext.Request.QueryString["r"]
                           };
            }
            else if (controllerContext.HttpContext.Request.UrlReferrer != null)
            {
                return new ReturnUrl
                           {
                               Url = controllerContext.HttpContext.Request.UrlReferrer.PathAndQuery
                           };
            }

            return new ReturnUrl();
        }
Пример #14
0
        public object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
        {
            var request = controllerContext.HttpContext.Request;
            var values  = request.Headers.GetValues("BoxGentle");

            return(JsonConvert.DeserializeObject <Employee>(values.First()));
        }
        public object BindModel(ControllerContext controllerContext,
            ModelBindingContext bindingContext)
        {
            //get the car from the session

            Cart cart = null;
            if (controllerContext.HttpContext.Session != null)
            {
                cart = (Cart)controllerContext.HttpContext.Session[sessionKey];
            }

            //create the Cart if there wasn't one in the session data

            if(cart == null)
            {
                cart = new Cart();

                if (controllerContext.HttpContext.Session != null)
                {
                    controllerContext.HttpContext.Session[sessionKey] = cart;
                }
            }

            return cart;
        }
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException("bindingContext");
            }

            DetectionGroup obj = null;

            string groupId = ModelBinderHelper.FromPostedData<String>(bindingContext, "Key");
            if (string.IsNullOrEmpty(groupId))
            {
                groupId = Guid.NewGuid().ToString("N");
                obj = (DetectionGroup)(bindingContext.Model ?? new DetectionGroup(groupId,
                    RepositoryFactory.GetRepository<IDetectionCompanyRepository, DetectionCompany>().FindBy(ModelBinderHelper.FromPostedData<String>(bindingContext, "DetectionCompany")),
                    DetectionGroupCategory.Misc));
                obj.IsLocked = false;
            }
            else
            {
                obj = RepositoryFactory.GetRepository<IDetectionGroupRepository, DetectionGroup>().FindBy(groupId);
            }

            obj.Name = ModelBinderHelper.FromPostedData<String>(bindingContext, "Name");
            obj.Telephone = ModelBinderHelper.FromPostedData<String>(bindingContext, "Telephone");

            return obj;
        }
Пример #17
0
		void ValidateModel(object model, ModelBindingContext bindingContext, List<int> validatedObjects = null)
		{
			validatedObjects = validatedObjects ?? new List<int>();
			
			var typeDescriptor = GetTypeDescriptor(model, model.GetType());
			
			// validate the model
			foreach (ValidationAttribute attribute in typeDescriptor.GetAttributes().OfType<ValidationAttribute>()) {
				if (!attribute.IsValid (bindingContext.Model)) {
                    bindingContext.ModelState.AddModelError(bindingContext.ModelName, attribute.FormatErrorMessage(bindingContext.ModelName));
                }
				validatedObjects.Add (model.GetHashCode());
            }
			
			// validate properties, recurse if necessary
			foreach (PropertyDescriptor property in typeDescriptor.GetProperties()) {
				var propInstance = property.GetValue (model);
				
                foreach (ValidationAttribute attribute in property.Attributes.OfType<ValidationAttribute>()) {
                    if (!attribute.IsValid(propInstance)) {
                        bindingContext.ModelState.AddModelError(property.Name, attribute.FormatErrorMessage(property.Name));
                        if (propInstance != null) {
                            validatedObjects.Add(propInstance.GetHashCode());
                        }
                    }
                    else if (propInstance != null) {
                        ValidateModel(propInstance, bindingContext, validatedObjects);
                    }
                }
			}
		}
Пример #18
0
        public object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
        {
            var pageRequest = new DataTablesRequest
            {
                Echo          = BindDataTablesRequestParam <Int32>(bindingContext, "sEcho"),
                DisplayStart  = BindDataTablesRequestParam <Int32>(bindingContext, "iDisplayStart"),
                DisplayLength = BindDataTablesRequestParam <Int32>(bindingContext, "iDisplayLength"),
                ColumnNames   = BindDataTablesRequestParam <string>(bindingContext, "sColumns"),
                Columns       = BindDataTablesRequestParam <Int32>(bindingContext, "iColumns"),
                Search        = BindDataTablesRequestParam <string>(bindingContext, "sSearch"),
                Regex         = BindDataTablesRequestParam <bool>(bindingContext, "bRegex"),
                SortingCols   = BindDataTablesRequestParam <Int32>(bindingContext, "iSortingCols"),
                DataProp      = BindDataTablesRequestParam <string>(controllerContext.HttpContext.Request, "mDataProp_"),
                RegexColumns  = BindDataTablesRequestParam <bool>(controllerContext.HttpContext.Request, "bRegex_"),
                Searchable    = BindDataTablesRequestParam <bool>(controllerContext.HttpContext.Request, "bSearchable_"),
                Sortable      = BindDataTablesRequestParam <bool>(controllerContext.HttpContext.Request, "bSortable_"),
                SortCol       = BindDataTablesRequestParam <Int32>(controllerContext.HttpContext.Request, "iSortCol_"),
                SearchColumns = BindDataTablesRequestParam <string>(controllerContext.HttpContext.Request, "sSearch_"),
                SortDir       = BindDataTablesRequestParam <string>(controllerContext.HttpContext.Request, "sSortDir_"),

                CategoryId = BindDataTablesRequestParamstring(bindingContext, "CategoryId"),
                VendorId   = BindDataTablesRequestParamstring(bindingContext, "VendorId")
            };

            return(pageRequest);
        }
Пример #19
0
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            ProjectNewViewModel model = (ProjectNewViewModel)bindingContext.Model ??
                (ProjectNewViewModel)DependencyResolver.Current.GetService(typeof(ProjectNewViewModel));
            bool hasPrefix = bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName);
            string searchPrefix = (hasPrefix) ? bindingContext.ModelName + ".":"";

            //since viewmodel contains custom types like project make sure project is not null and to pass key arround for value providers
            //use Project.Name even if your makrup dont have Project prefix
            model.Project = new Project();
            //populate the fields of the model
            model.Project.ProjectId = 0;
            model.Project.Name = GetValue(bindingContext, searchPrefix, "Project.Name");
            model.Project.Url = GetValue(bindingContext, searchPrefix, "Project.Url");
            model.Project.CreatedOn  =  DateTime.Now;
            model.Project.UpdatedOn = DateTime.Now;
            model.Project.isDisabled = GetCheckedValue(bindingContext, searchPrefix, "Project.isDisabled");
            model.Project.isFeatured = GetCheckedValue(bindingContext, searchPrefix, "Project.isFeatured");
            model.Project.GroupId = int.Parse(GetValue(bindingContext, searchPrefix, "Project.GroupId"));
            model.Project.Tags = new List<Tag>();

            foreach (var tagid in GetValue(bindingContext, searchPrefix, "Tags").Split(','))
            {
                var tag = new Tag { TagId = int.Parse(tagid)};
                model.Project.Tags.Add(tag);
            }

            var total = model.Project.Tags.Count;

            return model;
        }
        /// <summary>
        /// Binds the model to a value by using the specified controller context and binding context.
        /// </summary>
        /// <param name="controllerContext">The controller context.</param>
        /// <param name="bindingContext">The binding context.</param>
        /// <returns>
        /// The bound value.
        /// </returns>
        public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            FacebookClient client = _config.ClientProvider.CreateClient();
            dynamic signedRequest = FacebookRequestHelpers.GetSignedRequest(
                controllerContext.HttpContext,
                rawSignedRequest =>
                {
                    return client.ParseSignedRequest(rawSignedRequest);
                });
            if (signedRequest != null)
            {
                string accessToken = signedRequest.oauth_token;
                string userId = signedRequest.user_id;
                client.AccessToken = accessToken;
                return new FacebookContext
                {
                    Client = client,
                    SignedRequest = signedRequest,
                    AccessToken = accessToken,
                    UserId = userId,
                    Configuration = _config
                };
            }
            else
            {
                bindingContext.ModelState.AddModelError(bindingContext.ModelName, Resources.MissingSignedRequest);
            }

            return null;
        }
        public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext == null) {
                throw new ArgumentNullException("bindingContext");
            }

            ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            // case 1: there was no <input ... /> element containing this data
            if (valueResult == null) {
                return null;
            }

            string value = valueResult.AttemptedValue;

            // case 2: there was an <input ... /> element but it was left blank
            if (String.IsNullOrEmpty(value)) {
                return null;
            }

            // Future proofing. If the byte array is actually an instance of System.Data.Linq.Binary
            // then we need to remove these quotes put in place by the ToString() method.
            string realValue = value.Replace("\"", String.Empty);
            return Convert.FromBase64String(realValue);
        }
Пример #22
0
        public override object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
        {
            var request        = controllerContext.HttpContext.Request;
            var requestWrapper = new MvcPagingParameters(new NameValueCollection(request.Params));

            return(requestWrapper);
        }
Пример #23
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);
        }
Пример #24
0
        public object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
        {
            var contentType = controllerContext.HttpContext.Request.ContentType;

            if (!contentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
            {
                return(null);
            }

            string jsonString;

            using (var stream = controllerContext.HttpContext.Request.InputStream)
            {
                stream.Seek(0, SeekOrigin.Begin);
                using (var reader = new StreamReader(stream))
                    jsonString = reader.ReadToEnd();
            }

            if (string.IsNullOrEmpty(jsonString))
            {
                return(null);
            }

            DynamicComplexObject ExtraData = new DynamicComplexObject();

            ExtraData.Details = new JavaScriptSerializer().Deserialize <dynamic>(jsonString);

            return(ExtraData);
        }
Пример #25
0
		public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
		{
			// Bind normally
			var model = base.BindModel(controllerContext, bindingContext);

			if (model == null)
				return null;

			// get a validator for the viewmodel
			var validator = GetValidator(model);
			if (validator == null)
				return model;

			// validate!
			var validationReport = validator.Validate(model);

			// valid?
			if (!validationReport.IsValid)
			{
				var violationPropertyNameResolver = new MvcViolationPropertyNameResolver();

				foreach (var violation in validationReport.Violations)
				{
					// add errors to modelstate
					bindingContext.ModelState.AddModelError(violationPropertyNameResolver.ResolvePropertyName(violation),
					                                        violation.ErrorMessage);
				}
			}

			return model;
		}
 /// <summary>
 /// Binds the model to a value by using the specified controller context and binding context.
 /// </summary>
 /// <param name="controllerContext"></param>
 /// <param name="bindingContext"></param>
 /// <returns></returns>
 public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
 {
     if (!controllerContext.HttpContext.Request.IsAuthenticated)
         return null;
     var identity = _authenticationService.GetIdentityFromTicket(controllerContext.HttpContext);
     return identity;
 }
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            string modelName = bindingContext.ModelName;
            NameValueCollection col = controllerContext.HttpContext.Request.Form;

            return (List<Guid>)Ext.Net.JSON.Deserialize(col[modelName], typeof(List<Guid>));
        }
Пример #28
0
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

            if (!string.IsNullOrEmpty(displayFormat) && value != null)
            {
                DateTime date;
                displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
                // use the format specified in the DisplayFormat attribute to parse the date
                if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
                {
                    return date;
                }
                else
                {
                    bindingContext.ModelState.AddModelError(
                        bindingContext.ModelName,
                        string.Format("{0} is an invalid date format", value.AttemptedValue)
                    );
                }
            }

            return base.BindModel(controllerContext, bindingContext);
        }
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            var date = value.ConvertTo(typeof(DateTime), CultureInfo.CurrentCulture);

            return date;
        }
Пример #30
0
        public override object BindModel(ControllerContext controllerContext,
                                         System.Web.Mvc.ModelBindingContext bindingContext)
        {
            object result = null;

            var name  = bindingContext.ModelName;
            var value = bindingContext.ValueProvider.GetValue(name);

            if (dateFormat == null)
            {
                EvolutionEntities db = new EvolutionEntities();
                var mms = new MembershipManagementService.MembershipManagementService(db);

                var user = mms.User;
                dateFormat = user.DateFormat;
            }

            if (value != null && !string.IsNullOrEmpty(value.AttemptedValue))
            {
                DateTimeOffset date;
                if (DateTimeOffset.TryParseExact(value.AttemptedValue, dateFormat + " HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out date))
                {
                    result = date;
                }
                else if (DateTimeOffset.TryParseExact(value.AttemptedValue, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out date))
                {
                    result = date;
                }
                else
                {
                    result = base.BindModel(controllerContext, bindingContext);
                }
            }
            return(result);
        }
Пример #31
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 (!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;
        }
        protected override bool OnPropertyValidating(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }

            if (bindingContext == null)
            {
                throw new ArgumentNullException("bindingContext");
            }

            if (propertyDescriptor == null)
            {
                throw new ArgumentNullException("propertyDescriptor");
            }

            if (value is string && controllerContext.HttpContext.Request.ContentType.StartsWith(WebConstants.APPLICATIONJSON, StringComparison.OrdinalIgnoreCase))
            {
                if (controllerContext.Controller.ValidateRequest && bindingContext.PropertyMetadata[propertyDescriptor.Name].RequestValidationEnabled)
                {
                    int index;

                    if (IsDangerousString(value.ToString(), out index))
                    {
                        throw new HttpRequestValidationException("Dangerous Input Detected");
                    }
                }
            }

            return base.OnPropertyValidating(controllerContext, bindingContext, propertyDescriptor, value);
        }
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }
            if (bindingContext == null)
            {
                throw new ArgumentNullException("bindingContext");
            }

            try
            {
                var message = WSFederationMessage.CreateFromUri(controllerContext.HttpContext.Request.Url);

                if (!bindingContext.ModelType.IsInstanceOfType(message))
                {
                    throw new WSFederationMessageException();
                }

                return message;
            }
            catch (WSFederationMessageException ex)
            {
                bindingContext.ModelState.AddModelError("", ex);
                return null;
            }
        }
Пример #34
0
                public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
                    if (controllerContext == null) {
                        throw new ArgumentNullException("controllerContext");
                    }

                    return new FormCollection(controllerContext.HttpContext.Request.Form);
                }
Пример #35
0
        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            string dataRuleTypeStr;

            string dataruleTypeName = !string.IsNullOrWhiteSpace(bindingContext.ModelName) ? (bindingContext.ModelName + ".DataRuleType") : "DataRuleType";

            dataRuleTypeStr = controllerContext.HttpContext.Request[dataruleTypeName];

            if (string.IsNullOrEmpty(dataRuleTypeStr))
            {
                return null;
            }
            var dataRuleInt = Int32.Parse(dataRuleTypeStr);
            DataRuleType dataRuleTypeEnum = (DataRuleType)dataRuleInt;
            object model = null;
            switch (dataRuleTypeEnum)
            {
                case DataRuleType.Folder:
                    model = new FolderDataRule();
                    break;
                case DataRuleType.Schema:
                    model = new SchemaDataRule();
                    break;
                case DataRuleType.Category:
                    model = new CategoryDataRule();
                    break;
            }
            bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());
            return model;
        }
        /// <summary>
        /// Binds the specified property by using the specified controller context and binding context and the specified property descriptor.
        /// </summary>
        /// <param name="controllerContext">The context within which the controller operates. The context information includes the controller, HTTP content, request context, and route data.</param>
        /// <param name="bindingContext">The context within which the model is bound. The context includes information such as the model object, model name, model type, property filter, and value provider.</param>
        /// <param name="propertyDescriptor">Describes a property to be bound. The descriptor provides information such as the component type, property type, and property value. It also provides methods to get or set the property value.</param>
        protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
        {
            if (propertyDescriptor.PropertyType == typeof(AggregateReference<>) || propertyDescriptor.PropertyType == typeof(AggregateReference<>))
            {
                var ag = new AggregateReference();
                var form = controllerContext.HttpContext.Request.Form;
                var name = form.AllKeys.SingleOrDefault(x => x.Equals(propertyDescriptor.Name, StringComparison.InvariantCultureIgnoreCase));

                if (!string.IsNullOrEmpty(name))
                {
                    var value = form.Get(name);

                    if(value.IsValidGuid())
                    {
                        ag.Guid = value;
                    }
                }

                SetProperty(controllerContext, bindingContext, propertyDescriptor, ag.ToTypedReference());
            }
            else
            {
                base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
            }
        }
Пример #37
0
        private ToDoController CreateToDoController(object ViewModel = null, bool isAuthorized = true)
        {
            MockingHelper.InitMocking();
            ToDoController toDoController;

            if (isAuthorized)
            {
                toDoController = new ToDoController(MockingHelper.DBContext, MockingHelper.ApplicationManager);
            }
            else
            {
                var userStore = new Mock <IUserStore <ApplicationUser> >();
                var applicationUserManager = new Mock <UserManager <ApplicationUser> >(userStore.Object);
                toDoController = new ToDoController(MockingHelper.DBContext, applicationUserManager.Object);
            }

            toDoController.ControllerContext = MockingHelper.ControllerContext;
            if (ViewModel != null)
            {
                var modelBinder = new System.Web.Mvc.ModelBindingContext()
                {
                    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => ViewModel, ViewModel.GetType()),
                    ValueProvider = new NameValueCollectionValueProvider(new NameValueCollection(), CultureInfo.InvariantCulture)
                };
                var binder = new DefaultModelBinder().BindModel(toDoController.ControllerContext, modelBinder);
                toDoController.ModelState.Clear();
                toDoController.ModelState.Merge(modelBinder.ModelState);
            }
            return(toDoController);
        }
Пример #38
0
        public object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
        {
            var result = new AdvancedSearchContainerField();

            result.Id = int.Parse(bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".Id").AttemptedValue);

            ValueProviderResult value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".IsMultiple");

            if (value != null)
            {
                result.IsMultiple = bool.Parse(((IEnumerable <string>)value.RawValue).FirstOrDefault());
            }

            value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".IsAutoComplete");
            if (value != null)
            {
                result.IsAutoComplete = bool.Parse(((IEnumerable <string>)value.RawValue).FirstOrDefault());
            }

            value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".IsDropdown");
            if (value != null)
            {
                result.IsDropdown = bool.Parse(((IEnumerable <string>)value.RawValue).FirstOrDefault());
            }
            value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName + ".SelectedDisplayOption");
            if (value != null)
            {
                result.SelectedDisplayOption = (eDisplayOption)Enum.Parse(typeof(eDisplayOption), ((IEnumerable <string>)value.RawValue).FirstOrDefault());
            }
            return(result);
        }
Пример #39
0
        public object BindModel(System.Web.Mvc.ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
        {
            Dictionary <string, string> dic = null;

            if (bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName))
            {
                dic = new Dictionary <string, string>();
                string prefix = bindingContext.ModelName + ".";
                var    form   = controllerContext.RequestContext.HttpContext.Request.Unvalidated().Form;
                foreach (var item in form.AllKeys)
                {
                    if (item.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
                    {
                        var fieldName = item.Substring(prefix.Length);
                        var value     = form[item];
                        if (value == "true,false")
                        {
                            value = "true";
                        }
                        dic[fieldName] = value;
                    }
                }
            }
            return(dic);
        }
Пример #40
0
        protected override object CreateModel(ModelBindingContext bindingContext, Type modelType)
        {
            if (IsBasicType(modelType))
            {
                return base.GetValue(controllerContext, modelName, modelType, modelState);
            }

            if (IsSimpleType(modelType))
            {
                ModelBinderResult
            }

            var instance = Activator.CreateInstance(modelType);

            foreach (PropertyDescriptor descriptor in TypeDescriptor.GetProperties(instance))
            {
                if (IsBasicType(descriptor.PropertyType))
                {
                    var obj = GetBinder(descriptor.PropertyType).GetValue(controllerContext, descriptor.Name, descriptor.PropertyType, modelState);
                    descriptor.SetValue(instance, obj);
                }
                else
                {
                    descriptor.SetValue(instance, Activator.CreateInstance(descriptor.PropertyType));
                    BindComplexType(controllerContext, descriptor.PropertyType, descriptor.GetValue(instance), modelState);
                }
            }
            return instance;
        }
		/// <summary>
		/// Binds the model to a value by using the specified controller context and binding context.
		/// </summary>
		/// <param name="controllerContext">The controller context.</param>
		/// <param name="bindingContext">The binding context.</param>
		/// <returns>The bound value.</returns>
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
		  
		    var parameters = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
            var sp = parameters != null ? parameters.RawValue as SearchParameters : null;
		    if (sp == null)
		    {
            var qs = GetParams(controllerContext);
            var qsDict = NvToDict(qs);
            var facets = qsDict.Where(k => FacetRegex.IsMatch(k.Key)).Select(k => k.WithKey(FacetRegex.Replace(k.Key, ""))).ToDictionary(x=>x.Key, y=>y.Value.Split(','));

		    sp = new SearchParameters
            {
                FreeSearch = qs["q"].EmptyToNull(),
                PageIndex = qs["p"].TryParse(1),
                PageSize = qs["pageSize"].TryParse(0),
                Sort = qs["sort"].EmptyToNull(),
		        SortOrder = qs["sortorder"].EmptyToNull(),
                Facets = facets
            };
		        if (!string.IsNullOrEmpty(sp.FreeSearch))
		        {
		            sp.FreeSearch = sp.FreeSearch.EscapeSearchTerm();
		        }
		    }
            return sp;
        }
 protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
 {
     base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
     switch (propertyDescriptor.Name)
     {
         case "ClientName" :
             if (string.IsNullOrEmpty((string)value))
             {
                 bindingContext.ModelState.AddModelError("ClientName", "");
             }
             break;
         case "Date":
             if((bindingContext.ModelState.IsValidField("Date")) && (DateTime.Now>(DateTime)value))
             {
                 bindingContext.ModelState.AddModelError("Date", "");
             }
             break;
         case "TermsAccepted":
             if (!(bool)value)
             {
                 bindingContext.ModelState.AddModelError("TermsAccepted", "");
             }
             break;
     }
 }
Пример #43
0
        public static object PerformBindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var idName = string.IsNullOrEmpty(bindingContext.ModelName) ? "id" : bindingContext.ModelName;


            var valueProviderResult = bindingContext.GetValue(idName);
            if (valueProviderResult == null)
            {
                return null;
            }

            var rawId = valueProviderResult.ConvertTo(typeof(string)) as string;

            var parseResult = HiveId.TryParse(rawId);
            if (parseResult.Success)
            {
                //add the bound value to model state if it's not already there, generally only simple props will be there
                if (!bindingContext.ModelState.ContainsKey(idName))
                {
                    bindingContext.ModelState.Add(idName, new ModelState());
                    bindingContext.ModelState.SetModelValue(idName, new ValueProviderResult(parseResult.Result, parseResult.Result.ToString(), null));
                }
            }

            return parseResult.Result;
        }
Пример #44
0
        protected override object CreateModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext, Type modelType)
        {
            Employee e = new Employee();

            e.FirstName = controllerContext.RequestContext.HttpContext.Request.Form["FName"];
            e.LastName  = controllerContext.RequestContext.HttpContext.Request.Form["LName"];
            e.Salary    = int.Parse(controllerContext.RequestContext.HttpContext.Request.Form["Salary"]);
            return(e);
        }
Пример #45
0
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var model = (AddressSummary)bindingContext.Model ?? new AddressSummary();

            model.City    = GetValue(bindingContext, "City");
            model.Country = GetValue(bindingContext, "Country");

            return(model);
        }
Пример #46
0
        private static string BindDataTablesRequestParamstring(System.Web.Mvc.ModelBindingContext context, string propertyName)
        {
            string value = string.Empty;

            if (context.ValueProvider.GetValue(propertyName) != null)
            {
                value = context.ValueProvider.GetValue(propertyName).AttemptedValue;
            }
            return(value);
        }
Пример #47
0
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var model = new LoginModel
            {
                Login    = controllerContext.HttpContext.Request.Form["Login"],
                Password = controllerContext.HttpContext.Request.Form["Password"]
            };

            return(model);
        }
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var file      = controllerContext.HttpContext.Request.Files["file"];
            var firstName = controllerContext.HttpContext.Request["firstName"];

            return(new Model
            {
                File = file,
                FirstName = firstName
            });
        }
Пример #49
0
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            Grade grade = controllerContext.HttpContext.Session[GradeSessionKey] as Grade; //<= cookie, niet session

            if (grade == null)
            {
                grade = new Grade();
                controllerContext.HttpContext.Session[GradeSessionKey] = grade;
            }
            return(grade);
        }
Пример #50
0
        public object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingcontext)
        {
            Cart cart = (Cart)controllerContext.HttpContext.Session[sessionKey];

            if (cart == null)
            {
                cart = new Cart();
                controllerContext.HttpContext.Session[sessionKey] = cart;
            }
            return(cart);
        }
Пример #51
0
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var appUser = UserManager.FindById(controllerContext.HttpContext.User.Identity.GetUserId());
            var webUser = new WebUser()
            {
                Id       = appUser.Id,
                UserName = appUser.UserName
            };

            return(webUser);
        }
Пример #52
0
        public Object BindModel(ControllerContext mbctx, System.Web.Mvc.ModelBindingContext bctx)
        {
            CarroCompra carroCompra = (CarroCompra)mbctx.HttpContext.Session[ID_SESSION_CARRO];

            if (carroCompra == null)
            {
                carroCompra = new CarroCompra();
                mbctx.HttpContext.Session[ID_SESSION_CARRO] = carroCompra;
            }
            return(carroCompra);
        }
 public object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
 {
     try
     {
         var result = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
         return(result == null ? ObjectId.Empty : ObjectId.Parse((string)result.ConvertTo(typeof(string))));
     }
     catch
     {
         return(ObjectId.Empty);
     }
 }
Пример #54
0
 protected override void SetProperty(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
 {
     if (propertyDescriptor.PropertyType == typeof(string))
     {
         var stringValue = (string)value;
         if (!string.IsNullOrEmpty(stringValue))
         {
             stringValue = stringValue.Trim();
         }
         value = stringValue;
     }
     base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
 }
Пример #55
0
        string GetValue(ModelBindingContext context, string name)
        {
            name = (context.ModelName == string.Empty ? string.Empty : context.ModelName + ".") + name;

            var result = context.ValueProvider.GetValue(name);

            if (result == null || result.AttemptedValue == string.Empty)
            {
                return("<Not Specified>");
            }

            return(result.AttemptedValue);
        }
Пример #56
0
        /// <summary>
        /// Recupera o valor da propriedade.
        /// </summary>
        /// <param name="controllerContext"></param>
        /// <param name="bindingContext"></param>
        /// <param name="descriptor"></param>
        /// <param name="loader"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        protected object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.ICustomTypeDescriptor descriptor, string propertyName)
        {
            var propertyMetadata       = bindingContext.PropertyMetadata[propertyName];
            var property               = descriptor.GetProperties()[propertyName];
            var propertyBinder         = this.Binders.GetBinder(property.PropertyType);
            var propertyBindingContext = new System.Web.Mvc.ModelBindingContext(bindingContext)
            {
                ModelMetadata = propertyMetadata,
                ModelName     = CreatePropertyModelName(bindingContext.ModelName, propertyMetadata.PropertyName)
            };

            return(propertyBinder.BindModel(controllerContext, propertyBindingContext));
        }
Пример #57
0
        /// <summary>
        /// Binds the value to the model.
        /// </summary>
        /// <param name="controllerContext">The current controller context.</param>
        /// <param name="bindingContext">The binding context.</param>
        /// <returns>The new model.</returns>

        public object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
        {
            var culture = GetUserCulture(controllerContext);

            string value = bindingContext.ValueProvider
                           .GetValue(bindingContext.ModelName)
                           .ConvertTo(typeof(string)) as string;

            double result = 0;

            double.TryParse(value, NumberStyles.Any, culture, out result);

            return(result);
        }
Пример #58
0
        private static List <T> BindDataTableRequestJsonParam <T>(System.Web.Mvc.ModelBindingContext context, string keyPrefix)
        {
            List <T> value = new List <T>();

            if (context.ValueProvider.GetValue(keyPrefix) != null)
            {
                string JsonValue = context.ValueProvider.GetValue(keyPrefix).AttemptedValue;
                if (JsonValue != string.Empty && JsonValue != null)
                {
                    value = (ClsWebCommon.JsonDeserialize <List <T> >(JsonValue)) as List <T>;
                }
            }
            return(value);
        }
        public object BindModel(ControllerContext controllerContext,
                                System.Web.Mvc.ModelBindingContext binderContext)
        {
            //get the cart from the session
            Cart cart = (Cart)controllerContext.HttpContext.Session[sessionKey];

            if (cart == null)
            {
                cart = new Cart();
                controllerContext.HttpContext.Session[sessionKey] = cart;
            }
            //return the cart
            return(cart);
        }
Пример #60
0
        /// <summary>
        /// To bind the Model to the controller. Checks if the data is indeed json type and deserialiizes it. A global entry has been made in application_start()
        /// </summary>
        /// <param name="controllerContext"></param>
        /// <param name="bindingContext"></param>
        /// <returns></returns>
        public override object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
        {
            if (!IsJSONRequest(controllerContext))
            {
                return(base.BindModel(controllerContext, bindingContext));
            }

            // Get the JSON data that's been posted
            var request        = controllerContext.HttpContext.Request;
            var jsonStringData = new StreamReader(request.InputStream).ReadToEnd();

            //Use the built-in serializer
            return(new JavaScriptSerializer().Deserialize(jsonStringData, bindingContext.ModelMetadata.ModelType));
        }