public static T GetRequestParameterValue <T> ([NotNull] this ModelBindingContext context, [NotNull] string key, [CanBeNull] T defaultValue, [NotNull] Func <string, T> parseFunc)
        {
            var value  = context.GetValue(key);
            var result = value.GetParameterValue(defaultValue, parseFunc);

            return(result);
        }
        /// <summary>
        /// Binds the model
        /// </summary>
        /// <param name="controllerContext"></param>
        /// <param name="bindingContext"></param>
        /// <returns></returns>
        public override object BindModel(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;

            HiveEntityUri nodeId = null;

            if (HiveEntityUri.TryParse(rawId, out nodeId))
            {
                //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(nodeId, nodeId.ToString(), null));
                }
            }

            return(nodeId);
        }
Esempio n. 3
0
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var models   = new List <CheckBoxListViewModel>();
            var formKeys = controllerContext.HttpContext.Request.Form.AllKeys.ToArray();

            var rootItems = formKeys.Where(s => s.StartsWith("hdrTitle")).ToList();

            if (rootItems.Count == 0)
            {
                return(null);
            }

            foreach (var item in rootItems)
            {
                var hdrValue  = item.Split('_')[1];
                var txtValues = formKeys.Where(s => s.StartsWith("lblLabel_" + hdrValue)).ToArray();
                var valValues = formKeys.Where(s => s.StartsWith("valValue_" + hdrValue)).ToArray();
                var hdnValues = formKeys.Where(s => s.StartsWith("hdnChk_" + hdrValue)).ToArray();

                var model = new CheckBoxListViewModel
                {
                    HeaderText = Regex.Replace(hdrValue, "([a-z])([A-Z])", "$1 $2"),
                    Items      = new List <CheckBoxListItem>()
                };
                for (var index = 0; index < txtValues.Count(); index++)
                {
                    var listItem = new CheckBoxListItem
                    {
                        Text      = bindingContext.GetValue(txtValues[index]),
                        Value     = bindingContext.GetValue(valValues[index]),
                        IsChecked = bool.Parse(bindingContext.GetValue(hdnValues[index]))
                    };

                    model.Items.Add(listItem);
                }

                models.Add(model);
            }

            return(rootItems.Count == 1 ? (object)models.First() : models);
        }
        public static List <T> RequestParameterValueAsList <T> ([NotNull] this ModelBindingContext context, [NotNull] string propertyName, [CanBeNull] T defaultValue, [NotNull] Func <string, T> parseFunc)
        {
            var value = context.GetValue(propertyName);

            if (string.IsNullOrWhiteSpace(value))
            {
                return(new List <T>());
            }

            var items = value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(item => GetParameterValue(item.Trim(), defaultValue, parseFunc))
                        .ToList();

            return(items);
        }
Esempio n. 5
0
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            CustomerKeyMoveParameter model = new CustomerKeyMoveParameter();

            var a = actionContext.Request.Content.ReadAsStringAsync().Result;

            model.OriginalSourceKey = bindingContext.GetValue("OriginalSourceKey").ToType <string>();
            model.OriginalSourceId  = bindingContext.GetValue("OriginalSourceId").ToType <string>();
            model.NewSourceKey      = bindingContext.GetValue("NewSourceKey").ToType <string>();
            model.NewSourceId       = bindingContext.GetValue("NewSourceId").ToType <string>();
            model.ToMoveSourceId    = bindingContext.GetValue("ToMoveSourceId").ToType <string>();
            model.ToMoveSourceKey   = bindingContext.GetValue("ToMoveSourceKey").ToType <string>();

            var validator = new CustomerKeyMoveParameterValidator();
            var result    = validator.Validate(model);

            foreach (var e in result.Errors)
            {
                bindingContext.ModelState.AddModelError(e.PropertyName, e.ErrorMessage);
            }

            bindingContext.Model = model;
            return(true);
        }
Esempio n. 6
0
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var postModel = new PostViewModel
            {
                Post =
                    new PostEntity
                {
                    PostID             = int.Parse(bindingContext.GetValue("Post.PostID")),
                    PostTitle          = bindingContext.GetValue("Post.PostTitle"),
                    PostContent        = bindingContext.GetValue("Post.PostContent"),
                    PostUrl            = bindingContext.GetValue("Post.PostUrl"),
                    PostAddedDate      = DateTime.Parse(bindingContext.GetValue("Post.PostAddedDate")),
                    UserCanAddComments = bool.Parse(bindingContext.GetValue("Post.UserCanAddComments")),
                    CanBeShared        = bool.Parse(bindingContext.GetValue("Post.CanBeShared")),
                    IsPrivate          = bool.Parse(bindingContext.GetValue("Post.IsPrivate")),
                    EntryType          = byte.Parse(bindingContext.GetValue("Post.EntryType")),
                    BitlyUrl           = bindingContext.GetValue("Post.BitlyUrl"),
                    BitlySourceUrl     = bindingContext.GetValue("Post.BitlySourceUrl")
                }
            };

            postModel.Post.Order = postModel.Post.EntryType == 2 ? (int?)GetOrder(bindingContext.GetValue("Post.Order")) : null;

            IModelBinder ckBinder = new CheckBoxListViewModelBinder();

            postModel.Categories = (CheckBoxListViewModel)ckBinder.BindModel(controllerContext, bindingContext);

            if (postModel.Post.EntryType == 1)
            {
                if (!postModel.Categories.Items.Any(c => c.IsChecked))
                {
                    var general = postModel.Categories.Items.SingleOrDefault(c => c.Value == "1");
                    if (general != null)
                    {
                        general.IsChecked = true;
                    }
                }

                postModel.Tags = bindingContext.GetValue("hdnAddedTags");
            }

            return(postModel);
        }
Esempio n. 7
0
        /// <summary>
        ///     Binds a datatable param object from the binding context
        /// </summary>
        /// <param name="controllerContext">
        ///     The controller context.
        /// </param>
        /// <param name="bindingContext">
        ///     The binding context.
        /// </param>
        /// <returns>
        ///     An instance of datatable param
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///     If the controllerContext or bindingContext is null, this method will fail
        /// </exception>
        public override 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 param = new DatatableParam
            {
                DatatableId         = bindingContext.GetValue <string>("datatableId"),
                DisplayStart        = bindingContext.GetValue <int>("iDisplayStart"),
                DisplayLength       = bindingContext.GetValue <int>("iDisplayLength"),
                ColumnsCount        = bindingContext.GetValue <int>("iColumns"),
                GlobalSearch        = bindingContext.GetValue <string>("sSearch"),
                SortingColumnsCount = bindingContext.GetValue <int>("iSortingCols"),
                Echo = bindingContext.GetValue <string>("sEcho")
            };

            param.Searchable     = new bool[param.ColumnsCount];
            param.Search         = new string[param.ColumnsCount];
            param.Regex          = new bool[param.ColumnsCount];
            param.Sortable       = new bool[param.ColumnsCount];
            param.DataProperties = new string[param.ColumnsCount];
            param.SortingColumns = new int[param.ColumnsCount];
            param.SortDirections = new string[param.ColumnsCount];

            for (int i = 0; i < param.ColumnsCount; i++)
            {
                param.Searchable[i]     = bindingContext.GetValue <bool>("bSearchable_" + i);
                param.Search[i]         = bindingContext.GetValue <string>("sSearch_" + i);
                param.Regex[i]          = bindingContext.GetValue <bool>("bRegex_" + i);
                param.Sortable[i]       = bindingContext.GetValue <bool>("bSortable_" + i);
                param.DataProperties[i] = bindingContext.GetValue <string>("mDataProp_" + i);
                param.SortingColumns[i] = bindingContext.GetValue <int>("iSortCol_" + i);
                param.SortDirections[i] = bindingContext.GetValue <string>("sSortDir_" + i);
            }

            return(param);
        }
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            KeyValueParameter model = new KeyValueParameter();

            var a = actionContext.Request.Content.ReadAsStringAsync().Result;

            model.KeyValue.Key   = bindingContext.GetValue("KeyValue.Key").ToType <string>();
            model.KeyValue.Value = bindingContext.GetValue("KeyValue.Value").ToType <string>();

            model.SuppressionOptions.IgnoreSuppression =
                string.IsNullOrEmpty(bindingContext.GetValue("SuppressionOptions.IgnoreSuppression")) || !bindingContext.GetValue("SuppressionOptions.IgnoreSuppression").IsBooleanString()
                ? true
                : bindingContext.GetValue("SuppressionOptions.IgnoreSuppression").ToType <bool>();

            var queryValuePairs = actionContext.Request.GetQueryNameValuePairs();
            var keyValuePairs   = queryValuePairs as KeyValuePair <string, string>[] ?? queryValuePairs.ToArray();
            var returnMeItems   = keyValuePairs.ToList();
            var items           = (from item in returnMeItems where item.Key.ToLower().Contains("returnme")
                                   select item.Key.Split('.')
                                   into splitItems
                                   select splitItems[1].ToLower()).ToList();

            // Get ReturnMe.XXX Items from the param list  - Get the XXX item names from the query params

            model.ReturnMe.CustomerKeys           = bindingContext.GetValue("ReturnMe.CustomerKeys") == null ? null : bindingContext.GetValue("ReturnMe.CustomerKeys").ToType <List <string> >();
            model.ReturnMe.Permissions.Required   = bindingContext.GetValue("ReturnMe.Permissions.Required") != null && bindingContext.GetValue("ReturnMe.Permissions.Required").ToType <bool>();
            model.ReturnMe.TravelSummary.Required = bindingContext.GetValue("ReturnMe.TravelSummary.Required") != null &&
                                                    bindingContext.GetValue("ReturnMe.TravelSummary.Required")
                                                    .ToType <bool>();
            if (model.ReturnMe.Permissions != null)
            {
                model.ReturnMe.Permissions.ResponseParameter   = bindingContext.GetValue("Returnme.Permissions.ResponseParameter").ToType <string>();
                model.ReturnMe.Permissions.PermissionParameter = bindingContext.GetValue("ReturnMe.Permissions.PermissionParameter").ToType <string>();
                model.ReturnMe.Permissions.Journey             = bindingContext.GetValue("ReturnMe.Permissions.Journey").ToType <string>();
            }

            model.ReturnMe.MembershipFlags.Required    = bindingContext.GetValue("ReturnMe.MembershipFlags.Required") != null && bindingContext.GetValue("ReturnMe.MembershipFlags.Required").ToType <bool>();
            model.ReturnMe.Membership.Required         = bindingContext.GetValue("ReturnMe.Membership.Required") != null && bindingContext.GetValue("ReturnMe.Membership.Required").ToType <bool>();
            model.ReturnMe.CustomerDetails.Required    = bindingContext.GetValue("Returnme.CustomerDetails.Required") != null && bindingContext.GetValue("Returnme.CustomerDetails.Required").ToType <bool>();
            model.ReturnMe.CustomerDetails.AddressType = bindingContext.GetValue("Returnme.CustomerDetails.AddressType").ToAddressType() ?? AddressType.Correspondence;

            if (items.Contains("mailinghistory"))
            {
                model.ReturnMe.MailingHistory = new MailingHistory();
            }
            if (model.ReturnMe.MailingHistory != null)
            {
                model.ReturnMe.MailingHistory.Product            = bindingContext.GetValue("Returnme.MailingHistory.Product").ToType <string>();
                model.ReturnMe.MailingHistory.FromDate           = bindingContext.GetValue("ReturnMe.MailingHistory.FromDate").ToType <DateTime>();
                model.ReturnMe.MailingHistory.ToDate             = bindingContext.GetValue("ReturnMe.MailingHistory.ToDate").ToType <DateTime>();
                model.ReturnMe.MailingHistory.FieldsTobeReturned = bindingContext.GetValue("ReturnMe.MailingHistory.FieldsTobeReturned").ToType <List <string> >();
            }

            // Note, following logic to extract actual returnme items from the get parameter collection so that processing can be easier in later stage.
            // if you add new ReturnMe item that value should be added to where clause x.Contains("NewRequestMe")
            var distinctreturnMeItems = items.Distinct().Where(x =>
                                                               x.ToLower().Contains("mailinghistory") ||
                                                               x.ToLower().Contains("customerkeys") ||
                                                               x.ToLower().Contains("permissions") ||
                                                               x.ToLower().Contains("membership") ||
                                                               x.ToLower().Contains("customerdetails") ||
                                                               x.ToLower().Contains("travelsummary") ||
                                                               x.ToLower().Contains("membershipflags"))
                                        .ToList();

            model.ResponseRequestedItems          = distinctreturnMeItems;
            model.AccessControl.CustomerKeyAccess = model.ReturnMe.CustomerKeys?.ToCustomerKeyGroupCodeEnum();
            model.AccessControl.ModuleAccess      = model.ResponseRequestedItems.ToGroupCodeEnum();


            var validator = new KeyValueParameterValidator();
            var result    = validator.Validate(model);

            foreach (var e in result.Errors)
            {
                bindingContext.ModelState.AddModelError(e.PropertyName, e.ErrorMessage);
            }

            bindingContext.Model = model;

            return(true);
        }
Esempio n. 9
0
        public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
        {
            try
            {
                GetParameters parameters = new GetParameters();
                parameters.RequestIdentification =
                    bindingContext.GetValue("RequestIdentification").ToType <string>();
                parameters.IwillSend                                  = bindingContext.GetValue("Iwillsend").ToType <string>();
                parameters.KeyValue.Key                               = bindingContext.GetValue("KeyValue.Key").ToType <string>();
                parameters.KeyValue.Value                             = bindingContext.GetValue("KeyValue.Value").ToType <string>();
                parameters.NameAndAddress.Title                       = bindingContext.GetValue("NameAndAdress.Title").ToType <string>();
                parameters.NameAndAddress.Surname                     = bindingContext.GetValue("NameAndAddress.Surname").ToType <string>();
                parameters.NameAndAddress.FirstName                   = bindingContext.GetValue("NameAndAddress.Firstname").ToType <string>();
                parameters.NameAndAddress.Dob                         = bindingContext.GetValue("NameAndAddress.Dob").ToType <DateTime>();
                parameters.NameAndAddress.Email                       = bindingContext.GetValue("NameAndAddress.Email").ToType <string>();
                parameters.NameAndAddress.Phone                       = bindingContext.GetValue("NameAndAddress.Phone").ToType <string>();
                parameters.NameAndAddress.Address.Address1            = bindingContext.GetValue("NameAndAddress.Address.Address1").ToType <string>();
                parameters.NameAndAddress.Address.Address2            = bindingContext.GetValue("NameAndAddress.Address.Address2").ToType <string>();
                parameters.NameAndAddress.Address.Address3            = bindingContext.GetValue("NameAndAddress.Address.Address3").ToType <string>();
                parameters.NameAndAddress.Address.Address4            = bindingContext.GetValue("NameAndAddress.Address.Address4").ToType <string>();
                parameters.NameAndAddress.Address.Postcode            = bindingContext.GetValue("NameAndAddress.Address.Postcode").ToType <string>();
                parameters.ReturnMe.MailingHistory.Product            = bindingContext.GetValue("Returnme.MailingHistory.Product").ToType <string>();
                parameters.ReturnMe.MailingHistory.FromDate           = bindingContext.GetValue("ReturnMe.MailingHistory.FromDate").ToType <DateTime>();
                parameters.ReturnMe.MailingHistory.ToDate             = bindingContext.GetValue("ReturnMe.MailingHistory.ToDate").ToType <DateTime>();
                parameters.ReturnMe.MailingHistory.FieldsTobeReturned = bindingContext.GetValue("ReturnMe.MailingHistory.FieldsTobeReturned").ToType <List <string> >();
                parameters.ReturnMe.CustomerKeys                      = bindingContext.GetValue("ReturnMe.CustomerKeys").ToType <List <string> >();

                parameters.Version = bindingContext.GetValue("Version").ToType <string>();
                if (string.IsNullOrEmpty(parameters.Version) || parameters.Version.ToLower() != "v1")
                {
                    bindingContext.ModelState.AddModelError("Version", "There is no version information found or has invalid version number in the URL");
                }

                // parameters.GroupCodes = parameters.ReturnMe.CustomerKeys.ToGroupCodeEnum();
                //Note, following logic to extract actual returnme items from the get parameter collection so that processing can be easier in later stage.
                // if you add new ReturnMe item that value should be added to where clause x.Contains("NewRequestMe")
                var returnMeItems         = actionContext.Request.GetQueryNameValuePairs().Where(x => x.Key.ToLower().Contains("returnme")).SelectMany(s => s.Key.Split('.')).ToList();
                var distinctreturnMeItems = returnMeItems.Distinct().Where(x =>
                                                                           x.ToLower().Contains("mailinghistory") || x.ToLower().Contains("customerkeys") ||
                                                                           x.ToLower().Contains("permissions") || x.ToLower().Contains("membership"))
                                            .ToList();
                parameters.ResponseRequestedItems = distinctreturnMeItems;
                parameters.ProcessStrategy        = bindingContext.GetValue("Iwillsend").ToType <string>();


                bindingContext.Model = parameters;
            }
            catch (Exception ex)
            {
                log.Error("GetParameterModelBinder: " + ex.Message, ex);
            }
            return(true);
        }