private CommonQueryCriteria DesrializeCommonQueryCriteria(IValueProvider values)
        {
            var criteria = new CommonQueryCriteria();

            if (values.ContainsPrefix("$orderby"))
            {
                var value = values.GetValue("$orderby");
                criteria.OrderBy = value.AttemptedValue;
            }

            if (values.ContainsPrefix("$pageNumber"))
            {
                var pageNumber = (long)values.GetValue("$pageNumber").ConvertTo(typeof(long));
                int pageSize   = 10;
                if (values.ContainsPrefix("$pageSize"))
                {
                    pageSize = (int)values.GetValue("$pageSize").ConvertTo(typeof(int));
                }

                var pagingInfo = new PagingInfo(pageNumber, pageSize);
                criteria.PagingInfo = pagingInfo;
            }

            //filter
            //var jFilter = json.Property("$filter");
            //if (jFilter != null)
            //{
            //    var filter = jFilter.Value.Value<string>();
            //    ParseFilter(criteria, filter);
            //}

            return(criteria);
        }
        private ODataQueryCriteria Desrialize(IValueProvider values)
        {
            var criteria = new ODataQueryCriteria();

            var orderBy = values.GetValue("$orderby");
            if (orderBy != null)
            {
                criteria.OrderBy = orderBy.AttemptedValue;
            }

            var filter = values.GetValue("$filter");
            if (filter != null)
            {
                criteria.Filter = filter.AttemptedValue;
            }

            ParsePagingInfo(values, criteria);

            var expand = values.GetValue("$expand");
            if (expand != null)
            {
                criteria.Expand = expand.AttemptedValue;
            }

            return criteria;
        }
        public void GetValueProvider()
        {
            // Arrange
            HttpCookieCollection cookies = new HttpCookieCollection
            {
                new HttpCookie("foo", "fooValue"),
                new HttpCookie("bar.baz", "barBazValue"),
                new HttpCookie("", "emptyValue"),
                new HttpCookie(null, "nullValue")
            };

            Mock <ControllerContext> mockControllerContext = new Mock <ControllerContext>();

            mockControllerContext.Setup(o => o.HttpContext.Request.Cookies).Returns(cookies);

            CookieValueProviderFactory factory = new CookieValueProviderFactory();

            // Act
            IValueProvider provider = factory.GetValueProvider(mockControllerContext.Object);

            // Assert
            Assert.Null(provider.GetValue(""));
            Assert.True(provider.ContainsPrefix("bar"));
            Assert.Equal("fooValue", provider.GetValue("foo").AttemptedValue);
            Assert.Equal(CultureInfo.InvariantCulture, provider.GetValue("foo").Culture);
        }
Example #4
0
        /// <summary>
        /// Gets the list of order columns in request
        /// </summary>
        /// <param name="valueProvider"></param>
        /// <returns></returns>
        private IEnumerable <Order> TryGetOrders(IValueProvider valueProvider)
        {
            //order[0][column]:0
            //order[0][dir]:asc
            int          index  = 0;
            List <Order> orders = new List <Order>();

            do
            {
                if (valueProvider.GetValue($"order[{index}][column]") != null)
                {
                    TryParse <int>(valueProvider.GetValue($"order[{index}][column]"), out int column);
                    TryParse <string>(valueProvider.GetValue($"order[{index}][dir]"), out string dir);

                    orders.Add(new Order(column, dir));
                    index++;
                }
                else
                {
                    break;
                }
            } while (true);

            return(orders);
        }
Example #5
0
        public void GetValueProvider_SimpleArrayJsonObject()
        {
            const string             jsonString = @"
[ ""abc"", null, ""foobar"" ]
";
            ControllerContext        cc         = GetJsonEnabledControllerContext(jsonString);
            JsonValueProviderFactory factory    = new JsonValueProviderFactory();

            // Act & assert
            IValueProvider valueProvider = factory.GetValueProvider(cc);

            Assert.True(valueProvider.ContainsPrefix("[0]"));
            Assert.True(valueProvider.ContainsPrefix("[2]"));
            Assert.False(valueProvider.ContainsPrefix("[3]"));

            ValueProviderResult vpResult1 = valueProvider.GetValue("[0]");

            Assert.Equal("abc", vpResult1.AttemptedValue);
            Assert.Equal(CultureInfo.CurrentCulture, vpResult1.Culture);

            // null values should exist in the backing store as actual entries
            ValueProviderResult vpResult2 = valueProvider.GetValue("[1]");

            Assert.NotNull(vpResult2);
            Assert.Null(vpResult2.RawValue);
        }
Example #6
0
        /// <summary>
        /// For internal use only.
        /// Parse sort collection.
        /// </summary>
        /// <param name="columns">Column collection to use when parsing sort.</param>
        /// <param name="values">Request parameters.</param>
        /// <param name="names">Name convention for request parameters.</param>
        /// <returns></returns>
        private static IEnumerable <ISort> ParseSorting(IEnumerable <IColumn> columns, IValueProvider values, IRequestNameConvention names)
        {
            var sorting = new List <ISort>();

            for (int i = 0; i < columns.Count(); i++)
            {
                var sortField  = values.GetValue(String.Format(names.SortField, i));
                int _sortField = 0;
                if (!Parse <int>(sortField, out _sortField))
                {
                    break;
                }

                var column = columns.ElementAt(_sortField);

                var    sortDirection  = values.GetValue(String.Format(names.SortDirection, i));
                string _sortDirection = null;
                Parse <string>(sortDirection, out _sortDirection);

                if (column.SetSort(i, _sortDirection))
                {
                    sorting.Add(column.Sort);
                }
            }

            return(sorting);
        }
        public void GetValueProvider()
        {
            // Arrange
            NameValueCollection serverVars = new NameValueCollection
            {
                { "foo", "fooValue" },
                { "bar.baz", "barBazValue" }
            };

            Mock <ControllerContext> mockControllerContext = new Mock <ControllerContext>();

            mockControllerContext
            .Setup(o => o.HttpContext.Request.ServerVariables)
            .Returns(serverVars);

            ServerVariablesValueProviderFactory factory = new ServerVariablesValueProviderFactory();

            // Act
            IValueProvider provider = factory.GetValueProvider(mockControllerContext.Object);

            // Assert
            Assert.True(provider.ContainsPrefix("bar"));
            Assert.Equal("fooValue", provider.GetValue("foo").AttemptedValue);
            Assert.Equal(CultureInfo.InvariantCulture, provider.GetValue("foo").Culture);
        }
Example #8
0
        private ODataQueryCriteria Desrialize(IValueProvider values)
        {
            var criteria = new ODataQueryCriteria();

            var orderBy = values.GetValue("$orderby");

            if (orderBy != null)
            {
                criteria.OrderBy = orderBy.AttemptedValue;
            }

            var filter = values.GetValue("$filter");

            if (filter != null)
            {
                criteria.Filter = filter.AttemptedValue;
            }

            ParsePagingInfo(values, criteria);

            var expand = values.GetValue("$expand");

            if (expand != null)
            {
                criteria.Expand = expand.AttemptedValue;
            }

            return(criteria);
        }
Example #9
0
        public object GetValue(object target)
        {
            if (_type == typeof(string))
            {
                return(_valueProvider.GetValue(target) ?? string.Empty);
            }

            return(_valueProvider.GetValue(target));
        }
 public ValueProviderResult GetValue(string key)
 {
     if (key == _alias.OriginalPropertyName)
     {
         var original = _provider.GetValue(_alias.OriginalPropertyName);
         return(original.Values.Any() ? original : _provider.GetValue(_alias.AliasName));
     }
     return(_provider.GetValue(key));
 }
 public object GetValue(object target)
 {
     if (NullHandling.HasValue &&
         NullHandling.Value == NullValueHandling.Ignore &&
         Provider.GetValue(target) == null)
     {
         return(null);
     }
     return(Provider.GetValue(target) ?? "");
 }
Example #12
0
 /// <summary>
 /// Gets the search part of query
 /// </summary>
 /// <returns></returns>
 private Search TryGetSearch(IValueProvider valueProvider)
 {
     if (TryParse <string>(valueProvider.GetValue("search[value]"), out string searchValue) &&
         !string.IsNullOrEmpty(searchValue))
     {
         TryParse <bool>(valueProvider.GetValue("search[regex]"), out bool regex);
         return(new Search(searchValue, regex));
     }
     return(null);
 }
Example #13
0
 public ValueProviderResult GetValue(string key)
 {
     if (key == _originalName)
     {
         var          results = _allNamesToBind.Select(alias => _provider.GetValue(alias)).ToArray();
         StringValues values  = results.Aggregate(values, (current, r) => StringValues.Concat(current, r.Values));
         return(new ValueProviderResult(values, results.First().Culture));
     }
     return(_provider.GetValue(key));
 }
Example #14
0
        protected virtual async Task UpdateProperty(IValueProvider valueProvider, T entity, IPropertyMetadata property)
        {
            bool   handled  = false;
            bool   hasValue = valueProvider.Keys.Contains(property.ClrName);
            object value;

            if (hasValue)
            {
                if (property.IsFileUpload)
                {
                    value = valueProvider.GetValue <ISelectedFile>(property.ClrName);
                }
                else if (property.Type == CustomDataType.Password)
                {
                    value = valueProvider.GetValue <string>(property.ClrName);
                }
                else
                {
                    value = valueProvider.GetValue(property.ClrName, property.ClrType);
                }
                if (EntityPropertyUpdate != null)
                {
                    var arg = new EntityPropertyUpdateEventArgs <T>(entity, valueProvider, property, value);
                    await EntityPropertyUpdate(Context, arg);

                    handled = arg.IsHandled;
                }
            }
            else
            {
                value = property.GetValue(entity);
            }
            if (!handled)
            {
                if (value != null && !property.ClrType.IsAssignableFrom(value.GetType()))
                {
                    throw new NotImplementedException("未处理的属性“" + property.Name + "”。");
                }
                ValidationContext validationContext = new ValidationContext(entity, Context.DomainContext, null);
                validationContext.MemberName  = property.ClrName;
                validationContext.DisplayName = property.Name;
                var error = property.GetAttributes <ValidationAttribute>().Select(t => t.GetValidationResult(value, validationContext)).Where(t => t != ValidationResult.Success).ToArray();
                if (error.Length > 0)
                {
                    throw new ArgumentException(string.Join(",", error.Select(t => t.ErrorMessage)));
                }
                if (hasValue)
                {
                    property.SetValue(entity, value);
                }
            }
        }
        public void BindModel_Success_NoneResult_TestAsync()
        {
            string modelName = "model";

            fContext.ModelName.Returns(modelName);
            fContext.ModelType.Returns(typeof(ObjectId));
            fValueProvider.GetValue(Arg.Is(modelName)).Returns(ValueProviderResult.None);

            var binder = new ObjectIdBinder();
            var result = binder.BindModelAsync(fContext);

            Assert.True(result.IsCompleted);
        }
Example #16
0
        public override async Task OnActionExecutionAsync(ActionExecutingContext filterContext, ActionExecutionDelegate next)
        {
            IServiceProvider  serviceProvider   = filterContext.HttpContext.RequestServices;
            ControllerContext controllerContext = ((Controller)filterContext.Controller).ControllerContext;
            IValueProvider    valueProvider     = await CompositeValueProvider.CreateAsync(controllerContext);

            var stringEntityIDs = new List <string>();

            if (int.TryParse(valueProvider.GetValue(_entitySingleIdParamName).FirstValue, out int entityId))
            {
                stringEntityIDs.Add(entityId.ToString());
            }
            else
            {
                if (filterContext.ActionArguments.ContainsKey(_entityMultiIdParamName))
                {
                    if (filterContext.ActionArguments[_entityMultiIdParamName] is SelectedItemsViewModel selModel)
                    {
                        stringEntityIDs.AddRange(selModel.Ids.Select(id => id.ToString()));
                    }
                }
            }

            int?parentEntityId = null;

            if (int.TryParse(valueProvider.GetValue(_parentEntityIdParamName).FirstValue, out int parentId))
            {
                parentEntityId = parentId;
            }

            string actionCode = _actionCode;

            if (actionCode == null)
            {
                var getActionCode = serviceProvider.GetRequiredService <Func <string, IActionCode> >();
                var command       = (string)filterContext.RouteData.Values["command"];
                actionCode = getActionCode(command).ActionCode;
            }

            BackendActionContext.SetCurrent(actionCode, stringEntityIDs, parentEntityId);

            try
            {
                await next.Invoke();
            }
            finally
            {
                BackendActionContext.ResetCurrent();
            }
        }
        private Sponsor GetModelFromContext(IValueProvider provider)
        {
            string NAME     = nameof(Sponsor.Name);
            string EMAIL    = nameof(Sponsor.Email);
            string MOBILE   = nameof(Sponsor.Mobile);
            string LANGUAGE = nameof(Sponsor.Language);
            string COMMUNICATION_PREFRENCE = nameof(Sponsor.CommunicationPrefrence);
            string NOTES          = nameof(Sponsor.Notes);
            string PAYMENT_METHOD = nameof(Sponsor.PaymentMethod);
            string ADDRESS        = nameof(Sponsor.Address);
            string SPONSORED_KIDS = nameof(Sponsor.SponsoredKids);

            var name     = provider.GetValue(NAME).FirstValue;
            var email    = provider.GetValue(EMAIL).FirstValue;
            var mobile   = provider.GetValue(MOBILE).FirstValue;
            var language = provider.GetValue(LANGUAGE).FirstValue;
            var communicationPrefrence = provider.GetValue(COMMUNICATION_PREFRENCE).FirstValue;
            var notes         = provider.GetValue(NOTES).FirstValue;
            var paymentMethod = provider.GetValue(PAYMENT_METHOD).FirstValue;
            var address       = provider.GetValue(ADDRESS).FirstValue;

            var sponsoredKids = provider.GetValue(SPONSORED_KIDS).Values.ToString().Split(',');


            List <Kid> kids = new List <Kid>();

            foreach (var id in sponsoredKids)
            {
                bool isId = int.TryParse(id, out int intId);
                if (isId)
                {
                    var kid = new Kid()
                    {
                        Id = intId
                    };
                    kids.Add(kid);
                }
            }

            Sponsor sponsor = new Sponsor()
            {
                Name     = name,
                Email    = email,
                Mobile   = mobile,
                Language = GetReportLanguage(language),
                CommunicationPrefrence = communicationPrefrence,
                Notes         = notes,
                PaymentMethod = paymentMethod,
                Address       = address,
                SponsoredKids = kids
            };


            return(sponsor);
        }
Example #18
0
        public async Task <IPost> UpdatePost([FromService] IDatabaseContext databaseContext, [FromService] IAuthenticationProvider authenticationProvider, [FromValue(false)] string id, [FromValue(false)] string threadId)
        {
            IValueProvider valueProvider = Context.DomainContext.GetRequiredService <IValueProvider>();
            IPost          post;

            if (string.IsNullOrEmpty(id))
            {
                IThread thread;
                {
                    var context = databaseContext.GetWrappedContext <IThread>();
                    thread = await context.GetAsync(threadId);

                    if (thread == null)
                    {
                        throw new DomainServiceException(new KeyNotFoundException(threadId));
                    }
                }
                {
                    var context = databaseContext.GetWrappedContext <IPost>();
                    post        = context.Create();
                    post.Thread = thread;
                    post.Member = await authenticationProvider.GetAuthentication().GetUserAsync <IMember>();

                    post.Content = valueProvider.GetValue <string>("content");
                    var e = new EntityFilterEventArgs <IPost>(post);
                    await RaiseAsyncEvent(PostUpdateEvent, e);

                    context.Add(post);
                }
            }
            else
            {
                var context = databaseContext.GetWrappedContext <IPost>();
                post = await context.GetAsync(id);

                if (post == null)
                {
                    throw new DomainServiceException(new KeyNotFoundException(id));
                }
                post.Content = valueProvider.GetValue <string>("content");
                var e = new EntityFilterEventArgs <IPost>(post);
                await RaiseAsyncEvent(PostUpdateEvent, e);

                context.Update(post);
            }
            await databaseContext.SaveAsync();

            return(post);
        }
Example #19
0
        public object Write(IValueProvider value)
        {
            string result         = "";
            var    toStringMethod = GetToStringMethod(value);

            if (toStringMethod != null)
            {
                result = (string)toStringMethod.Invoke(value.GetValue <object>(), new object[] { CultureInfo.InvariantCulture });
            }
            else
            {
                result = value.GetValue <object>().ToString();
            }
            return(result);
        }
Example #20
0
        public object GetModel(ControllerContext controllerContext, Type modelType, IValueProvider valueProvider, string key)
        {
            if (!valueProvider.ContainsPrefix(key))
            {
                return null;
            }
            ModelMetadata modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, modelType);
            if (!modelMetadata.IsComplexType)
            {
                return valueProvider.GetValue(key).ConvertTo(modelType);
            }

            if (modelType.IsArray)
            {
                return GetArrayModel(controllerContext, modelType, valueProvider,key);
            }

            Type enumerableType = ExtractGenericInterface(modelType, typeof(IEnumerable<>));
            if (null != enumerableType)
            {
                return GetCollectionModel(controllerContext, modelType, valueProvider, key);
            }         
           
            if (modelMetadata.IsComplexType)
            {
                return GetComplexModel(controllerContext, modelType, valueProvider, key);
            }
            return null;
        }
Example #21
0
        public override object GetValue(IDomainExecutionContext executionContext, ParameterInfo parameter)
        {
            IValueProvider provider = executionContext.DomainContext.GetRequiredService <IValueProvider>();
            object         value    = provider.GetValue(Name ?? parameter.Name, EntityDescriptor.GetMetadata(parameter.ParameterType).KeyType);

            if (value == null)
            {
                throw new ArgumentNullException(parameter.Name, "获取" + (Name ?? parameter.Name) + "实体的值为空。");
            }
            var     databaseContext = executionContext.DomainContext.GetRequiredService <IDatabaseContext>();
            dynamic entityContext;
            //if (parameter.ParameterType.GetTypeInfo().IsInterface)
            //    entityContext = typeof(DatabaseContextExtensions).GetMethod("GetWrappedContext").MakeGenericMethod(parameter.ParameterType).Invoke(null, new object[] { databaseContext });
            //else
            var type = EntityDescriptor.GetMetadata(parameter.ParameterType).Type;

            entityContext = typeof(IDatabaseContext).GetMethod("GetContext").MakeGenericMethod(type).Invoke(databaseContext, new object[0]);
            object entity = entityContext.GetAsync(value).Result;

            if (IsRequired && entity == null)
            {
                throw new EntityNotFoundException(parameter.ParameterType, value);
            }
            return(entity);
        }
        private static void ParsePagingInfo(IValueProvider values, ODataQueryCriteria criteria)
        {
            var pn = values.GetValue("$pageNumber");
            var tc = values.GetValue("$inlinecount");
            if (pn != null || tc != null)
            {
                var pageNumber = pn != null ? (int)pn.ConvertTo(typeof(int)) : 1;
                var needCount = tc != null && !string.IsNullOrWhiteSpace(tc.AttemptedValue);

                var ps = values.GetValue("$pageSize");
                int pageSize = ps != null ? (int)ps.ConvertTo(typeof(int)) : 10;

                var pagingInfo = new PagingInfo(pageNumber, pageSize, needCount);
                criteria.PagingInfo = pagingInfo;
            }
        }
Example #23
0
        public void GetValueProviderReturnsChildActionValue()
        {
            // Arrange
            ChildActionValueProviderFactory factory = new ChildActionValueProviderFactory();

            ControllerContext controllerContext = new ControllerContext();

            controllerContext.RouteData = new RouteData();

            string conflictingKey = "conflictingKey";

            controllerContext.RouteData.Values["conflictingKey"] = 43;

            DictionaryValueProvider <object> explictValueDictionary = new DictionaryValueProvider <object>(new RouteValueDictionary {
                { conflictingKey, 42 }
            }, CultureInfo.InvariantCulture);

            controllerContext.RouteData.Values[ChildActionValueProvider.ChildActionValuesKey] = explictValueDictionary;

            // Act
            IValueProvider valueProvider = factory.GetValueProvider(controllerContext);

            // Assert
            Assert.Equal(typeof(ChildActionValueProvider), valueProvider.GetType());
            ValueProviderResult vpResult = valueProvider.GetValue(conflictingKey);

            Assert.NotNull(vpResult);
            Assert.Equal(42, vpResult.RawValue);
            Assert.Equal("42", vpResult.AttemptedValue);
            Assert.Equal(CultureInfo.InvariantCulture, vpResult.Culture);
        }
 private bool QuestionSelected(IValueProvider provider, int idx)
 {
     var valResult = provider.GetValue(ResultName(idx));
     return ((valResult != null)
         && !string.IsNullOrEmpty(valResult.AttemptedValue)
         && valResult.AttemptedValue.Contains("true"));
 }
Example #25
0
        public void GetValueProviderReturnsNullIfKeyIsNotInChildActionDictionary()
        {
            // Arrange
            ChildActionValueProviderFactory factory = new ChildActionValueProviderFactory();

            ControllerContext controllerContext = new ControllerContext();

            controllerContext.RouteData = new RouteData();
            controllerContext.RouteData.Values["forty-two"] = 42;

            DictionaryValueProvider <object> explictValueDictionary = new DictionaryValueProvider <object>(new RouteValueDictionary {
                { "forty-three", 42 }
            }, CultureInfo.CurrentUICulture);

            controllerContext.RouteData.Values[ChildActionValueProvider.ChildActionValuesKey] = explictValueDictionary;

            // Act
            IValueProvider valueProvider = factory.GetValueProvider(controllerContext);

            // Assert
            Assert.Equal(typeof(ChildActionValueProvider), valueProvider.GetType());
            ValueProviderResult vpResult = valueProvider.GetValue("forty-two");

            Assert.Null(vpResult);
        }
Example #26
0
        public IMappingOperation[] GetMappingOperations(Type from, Type to)
        {
            var members = ReflectionUtils.GetPublicFieldsAndProperties(to);

            return(members
                   .Select(m => new DestWriteOperation()
            {
                Destination = new MemberDescriptor(m),
                Getter =
                    (ValueGetter <object>)
                    (
                        (form, status) =>
                {
                    FormCollection forms = new FormCollection((NameValueCollection)form);
                    IValueProvider valueProvider = forms.ToValueProvider();
                    ValueProviderResult res = valueProvider.GetValue(m.Name);
                    if (res != null)
                    {
                        return ValueToWrite <object> .ReturnValue(res.ConvertTo(ReflectionUtils.GetMemberType(m)));
                    }
                    else
                    {
                        return ValueToWrite <object> .Skip();
                    }
                }
                    )
            }
                           )
                   .ToArray());
        }
        public void GetValueProvider()
        {
            // Arrange
            Mock <MockableUnvalidatedRequestValues> mockUnvalidatedValues =
                new Mock <MockableUnvalidatedRequestValues>();
            QueryStringValueProviderFactory factory = new QueryStringValueProviderFactory(
                _ => mockUnvalidatedValues.Object
                );

            Mock <ControllerContext> mockControllerContext = new Mock <ControllerContext>();

            mockControllerContext
            .Setup(o => o.HttpContext.Request.QueryString)
            .Returns(_backingStore);

            // Act
            IValueProvider valueProvider = factory.GetValueProvider(mockControllerContext.Object);

            // Assert
            Assert.Equal(typeof(QueryStringValueProvider), valueProvider.GetType());
            ValueProviderResult vpResult = valueProvider.GetValue("foo");

            Assert.NotNull(vpResult);
            Assert.Equal("fooValue", vpResult.AttemptedValue);
            Assert.Equal(CultureInfo.InvariantCulture, vpResult.Culture);
        }
            public object GetValue(object target)
            {
                Datum datum = target as Datum;

                if (datum == null)
                {
                    throw new SensusException("Attempted to anonymize a non-datum (or null) object.");
                }

                // if we're processing the Anonymized property, return true so that the output JSON properly reflects the fact that the datum has been passed through an anonymizer (this regardless of whether anonymization of data was actually performed)
                if (_property.DeclaringType == typeof(Datum) && _property.Name == "Anonymized")
                {
                    return(true);
                }
                else
                {
                    object propertyValue = _defaultMemberValueProvider.GetValue(datum);

                    // don't re-anonymize property values, don't anonymize when we don't have an anonymizer, and don't attempt anonymization if the property value is null
                    Anonymizer anonymizer;
                    if (datum.Anonymized || (anonymizer = _contractResolver.GetAnonymizer(datum.GetType().GetProperty(_property.Name))) == null || propertyValue == null)  // we re-get the PropertyInfo from the datum's type so that it matches our dictionary of PropertyInfo objects (the reflected type needs to be the most-derived, which doesn't happen leading up to this point for some reason).
                    {
                        return(propertyValue);
                    }
                    // anonymize!
                    else
                    {
                        return(anonymizer.Apply(propertyValue, _contractResolver.Protocol));
                    }
                }
            }
Example #29
0
        public string ConvertToString()
        {
            object propertyValue = this.GetCurrPropertyValue();

            //Fix for converting value srom serialization extensions
            //TODO - change this to use Extension Map, similar to DelegateParsingToExtender and so on
            IValueProvider valueProvider = propertyValue as IValueProvider;
            if (valueProvider != null)
            {
                propertyValue = valueProvider.GetValue();
            }

            if (converter != null)
            {
                return converter.ConvertToString(this.propertyOwner, this.Property, propertyValue);
            }
            else
                if (typeConverter != null)
                {
                    return typeConverter.ConvertToString(null, CultureInfo.InvariantCulture, propertyValue);
                }
                else
                    if (objectType == typeof(string))
                    {
                        return (string)propertyValue;
                    }

            return null;
        }
Example #30
0
        public async Task <IForum[]> ListForums([FromService] IDatabaseContext databaseContext)
        {
            var            context       = databaseContext.GetWrappedContext <IForum>();
            var            queryable     = context.Query().Include(t => t.Board);
            IValueProvider valueProvider = Context.DomainContext.GetRequiredService <IValueProvider>();
            string         id            = valueProvider.GetValue <string>("id");

            if (id != null)
            {
                var converter = TypeDescriptor.GetConverter(EntityDescriptor.GetMetadata <IBoard>().KeyType);
                var idObj     = converter.ConvertFrom(id);
                queryable = queryable.Where(t => t.Board.Index == idObj);
            }
            var e = new EntityQueryEventArgs <IForum>(queryable);

            await RaiseAsyncEvent(ForumQueryEvent, e);

            queryable = e.Queryable;
            var items = await queryable.ToArrayAsync();

            var obj = _ForumCastMethod.Invoke(null, new object[] { items });

            obj = _ForumToArrayMethod.Invoke(null, new object[] { obj });
            return((IForum[])obj);
        }
Example #31
0
        public object Write(IValueProvider value)
        {
            object   instance = value.GetValue <object>();
            XElement result   = new XElement(value.Name);

            var discoveryStrategy = ValueDiscoveryStrategy.Get(instance.GetType()) ?? valueDiscovery;
            var values            = discoveryStrategy.GetValues(instance);

            foreach (var property in values)
            {
                object serialized = SerializationService.Instance.Write(property);

                if (serialized is string)
                {
                    XAttribute attribute = new XAttribute(property.Name, serialized.ToString());
                    result.Add(attribute);
                }
                else if (serialized is XElement)
                {
                    result.Add(new XElement(property.Name, serialized));
                }
            }

            return(result);
        }
Example #32
0
        public object GetValue(object target)
        {
            var    value             = valueProvider.GetValue(target);
            string serializedMessage = GetSerializedMessage(value, propertyInfo);

            return(serializedMessage);
        }
Example #33
0
        public static IAssertionResult <T, TSource> Assertion <T, TSource>(IValueProvider <T, TSource> valueProvider, IAssertionConfiguration <T> configuration)
        {
            var stopwatch = Stopwatch.StartNew();

            while (true)
            {
                try
                {
                    var actualValue = valueProvider.GetValue();
                    configuration.Assertion.Assert(actualValue);
                    return(new AssertionResult <T, TSource>(valueProvider));
                }
                catch (Exception exception)
                {
                    var isAssertionException = AssertionExceptionHelper.IsAssertionException(exception);

                    if (configuration.Timeout > 0 && configuration.Timeout > stopwatch.ElapsedMilliseconds)
                    {
                        if (isAssertionException || configuration.ExceptionMatcher.RetryOnException(exception))
                        {
                            Thread.Sleep(configuration.Interval);
                            continue;
                        }
                    }

                    if (!isAssertionException)
                    {
                        throw;
                    }

                    var message = $"[timeout: {configuration.Timeout}]\n{valueProvider.GetMessage()}\n\n{exception.Message}";
                    throw AssertionExceptionHelper.CreateException(message);
                }
            }
        }
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            string         prefix         = bindingContext.ModelName;
            IValueProvider valueProvider  = bindingContext.ValueProvider;
            bool           containsPrefix = valueProvider.ContainsPrefix(prefix);

            //如果ValueProvider的数据容器中不包含指定前缀的数据
            //并且启用“去除前缀后的二次绑定”,会将ModelName设置为Null
            if (!containsPrefix)
            {
                if (!bindingContext.FallbackToEmptyPrefix)
                {
                    return(null);
                }
                bindingContext.ModelName = null;
            }
            else
            {
                //采用针对简单类型的数据绑定
                ValueProviderResult valueProviderResult = valueProvider.GetValue(prefix);
                if (null != valueProviderResult)
                {
                    return(this.BindSimpleModel(controllerContext, bindingContext, valueProviderResult));
                }
            }

            if (bindingContext.ModelMetadata.IsComplexType)
            {
                //采用针对复杂类型的数据绑定
                return(this.BindComplexModel(controllerContext, bindingContext));
            }
            return(null);
        }
Example #35
0
 public object GetModel(ControllerContext controllerContext, Type modelType, IValueProvider valueProvider, string key)
 {
     if (!valueProvider.ContainsPrefix(key))
     {
         return null;
     }
     return valueProvider.GetValue(key).ConvertTo(modelType);
 }
 private void UpdatePageStatus(CmsPage page, IValueProvider valueProvider)
 {
     int pageStatusId;
     if (Int32.TryParse(valueProvider.GetValue("Page.Status.Id").AttemptedValue, out pageStatusId))
     {
         Status pageStatus = pageService.LoadPageType(pageStatusId);
         page.Status = pageStatus;
     }
 }
Example #37
0
		string GetFormField(string key, IValueProvider provider) {
			ValueProviderResult result = provider.GetValue(key);

			if(result != null) {
				return (string)result.ConvertTo(typeof(string));
			}

			return null;
		}
        public static string GetCurrentValue(this IGridDataKey dataKey, IValueProvider valueProvider)
        {
            var value = valueProvider.GetValue(dataKey.RouteKey);

            if (value != null)
            {
                return value.AttemptedValue;
            }

            return null;
        }
 private static void BindValue(dynamic shape, IValueProvider valueProvider, string prefix) {
     // if the shape has a Name property, look for a value in
     // the ValueProvider
     var name = shape.Name;
     if (name != null) {
         ValueProviderResult value = valueProvider.GetValue(prefix + name);
         if (value != null) {
             shape.Value = value.AttemptedValue;
         }
     }
 }
Example #40
0
        private static IEnumerable<UavTypeDTO> GetSupportedUavs(IValueProvider valueProvider)
        {
            if (valueProvider.GetValue("UavType") == null)
                throw new Exception("UavTypes is NULL");

            var types = (string[]) valueProvider.GetValue("UavType").ConvertTo(typeof (string[]));

            return types.Select(item => new UavTypeDTO()
            {
                Id = int.Parse(item)
            }).ToList();
        }
Example #41
0
 protected virtual object GetArrayModel( ControllerContext controllerContext, Type modelType, IValueProvider valueProvider, string prefix)
 {
     if (valueProvider.ContainsPrefix(prefix) && !string.IsNullOrEmpty(prefix))
     {
         ValueProviderResult result = valueProvider.GetValue(prefix);
         if (null != result)
         {
             return result.ConvertTo(modelType);
         }
     }
     return null;
 }  
Example #42
0
        /// <summary>
        /// 在表单上应用指定值提供程序的值
        /// </summary>
        /// <param name="form">要应用的表单</param>
        /// <param name="valueProvider">提供值的 ValueProvider 实例</param>
        /// <returns>返回表单,便于链式调用</returns>
        public static HtmlForm ApplyValues( this HtmlForm form, IValueProvider valueProvider )
        {
            foreach ( var key in form.InputControls.Select( c => c.Name ) )
              {
            if ( valueProvider.ContainsPrefix( key ) )
            {
              form[key].TrySetValue( valueProvider.GetValue( key ).AttemptedValue );
            }
              }

              return form;
        }
Example #43
0
    /// <summary>
    /// 在表单上应用指定值提供程序的值
    /// </summary>
    /// <param name="form">要应用的表单</param>
    /// <param name="valueProvider">提供值的 ValueProvider 实例</param>
    /// <returns>返回表单,便于链式调用</returns>
    public static HtmlForm ApplyValues( this HtmlForm form, IValueProvider valueProvider )
    {

      foreach ( var control in form.Controls )
      {
        if ( valueProvider.ContainsPrefix( control.Name ) )
          control.Value = valueProvider.GetValue( control.Name ).AttemptedValue;
      }

      return form;

    }
		private static IValueSet BindDataSource(IValueProvider provider)
		{
			ValueDictionary values = new ValueDictionary();
			foreach (string key in provider.Keys)
			{
				ValueProviderResult result = provider.GetValue(key);
				if (result == null)
					continue;

				values.Add(key, result.Value);
			}
			return values;
		}
        public void TestInit()
        {
            _actionContext = new HttpActionContext();

            _valueProvider = Mock.Create<IValueProvider>(Behavior.Loose);
            Mock.Arrange(() => _valueProvider.GetValue("process")).Returns(new ValueProviderResult(ProcessName, ProcessName, null));

            _bindingContext = new ModelBindingContext
                                  {
                                      ValueProvider = _valueProvider,
                                      ModelMetadata =
                                          new ModelMetadata(new EmptyModelMetadataProvider(), null, null, typeof(SearchParameters), null)
                                  };
        }
Example #46
0
 public virtual string Populate(string formula, IValueProvider valueProvider)
 {
     if (string.IsNullOrEmpty(formula))
     {
         return null;
     }
     var matches = Regex.Matches(formula, "{(?<Name>[^{^}]+)}");
     var s = formula;
     foreach (Match match in matches)
     {
         var value = valueProvider.GetValue(match.Groups["Name"].Value);
         var htmlValue = value == null ? "" : value.ToString();
         s = s.Replace(match.Value, htmlValue);
     }
     return s;
 }
Example #47
0
        public static string GetActualValue(this IGridDataKey dataKey, IValueProvider provider)
        {
            if (dataKey == null)
            {
                throw new ArgumentNullException("dataKey");
            }

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

            var value = provider.GetValue(dataKey.RouteKey);

            return value != null ? value.AttemptedValue : null;
        }
Example #48
0
 public object GetModel(ControllerContext controllerContext, Type modelType, IValueProvider valueProvider, string key)
 {
     if (!valueProvider.ContainsPrefix(key))
     {
         return null;
     }
     ModelMetadata modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, modelType);
     if (!modelMetadata.IsComplexType)
     {
         return valueProvider.GetValue(key).ConvertTo(modelType);
     }
     if (modelMetadata.IsComplexType)
     {
         return GetComplexModel(controllerContext, modelType, valueProvider, key);
     }
     return null;
 }
Example #49
0
 private static void BindValue(dynamic shape, IValueProvider valueProvider, string prefix) {
     // if the shape has a Name property, look for a value in
     // the ValueProvider
     var name = shape.Name;
     if (name != null) {
         ValueProviderResult value = valueProvider.GetValue(prefix + name);
         if (value != null) {
             if (shape.Metadata.Type == "Checkbox" || shape.Metadata.Type == "Radio") {
                 shape.Checked = Convert.ToString(shape.Value) == Convert.ToString(value.AttemptedValue);
             }
             else {
                 shape.Value = value.AttemptedValue;
             }
             
         }
     }
 }
Example #50
0
 public static string GetFieldValue(string field, IValueProvider valueProvider, out string fieldName)
 {
     fieldName = "";
     if (string.IsNullOrEmpty(field))
     {
         return field;
     }
     if (field.StartsWith("{{") && field.EndsWith("}}"))
     {
         return "{" + field.Substring(2, field.Length - 4) + "}";
     }
     if (field.StartsWith("{") && field.EndsWith("}"))
     {
         fieldName = field.Substring(1, field.Length - 2);
         var value = valueProvider.GetValue(fieldName);
         return value == null ? null : value.ToString();
     }
     return field;
 }
Example #51
0
        private static PropertyValue GetPropertyValueForFile(
            Property property,
            IValueProvider valueProvider,
            HttpFileCollectionBase files)
        {
            var propertyValue = new PropertyValue(property);

            var file = files[property.Name];
            propertyValue.Raw = file;
            if (property.TypeInfo.IsFileStoredInDb == false &&
                property.FileOptions.NameCreation == NameCreation.UserInput)
            {
                var providedName = (string)valueProvider.GetValue(property.Name)
                    .ConvertTo(typeof(string), CultureInfo.CurrentCulture);
                propertyValue.Additional = providedName;
            }
            var isDeleted = false;

            if (file == null || file.ContentLength > 0)
            {
                isDeleted = false;
            }
            else
            {
                var isDeletedKey = property.Name + "_delete";
                if (valueProvider.ContainsPrefix(isDeletedKey))
                {
                    isDeleted =
                       ((bool?)
                           valueProvider.GetValue(isDeletedKey)
                               .ConvertTo(typeof(bool), CultureInfo.CurrentCulture)).GetValueOrDefault();
                }
            }

            if (isDeleted)
            {
                propertyValue.DataBehavior = DataBehavior.Clear;
                propertyValue.Additional = null;
            }

            return propertyValue;
        }
Example #52
0
        private static PropertyValue GetPropertyValue(
            Property property,
            IValueProvider valueProvider,
            Func<Property, object> defaultValueResolver = null)
        {
            var propertyValue = new PropertyValue(property);

            var value = valueProvider.GetValue(property.Name);
            if (value != null)
            {
                if (property.IsForeignKey && property.TypeInfo.IsCollection)
                {
                    propertyValue.Values = value.AttemptedValue
                        .Split(',').OfType<object>().ToList();
                }
                else if (property.TypeInfo.DataType == DataType.DateTime)
                {
                    propertyValue.Raw = ParseDateTime(property, (string)value.ConvertTo(typeof(string)));
                }
                else
                {
                    propertyValue.Raw = value.ConvertTo(
                        property.TypeInfo.OriginalType,
                        CultureInfo.CurrentCulture);
                }
            }

            if (defaultValueResolver != null)
            {
                var defaultValue = defaultValueResolver(property);

                if (defaultValue is ValueBehavior ||
                    (propertyValue.Raw == null && defaultValue != null))
                {
                    propertyValue.Raw = defaultValue;
                }
            }

            return propertyValue;
        }
Example #53
0
        public virtual string Populate(string formula, IValueProvider valueProvider)
        {
            if (string.IsNullOrEmpty(formula))
            {
                return null;
            }
            var matches = Regex.Matches(formula, "{(?<Name>[^{^}]+)}");
            var s = formula;
            foreach (Match match in matches)
            {
                var key = match.Groups["Name"].Value;
                int intKey;
                //ignore {0},{1}... it is the format string.
                if (!int.TryParse(key, out intKey))
                {
                    var value = valueProvider.GetValue(match.Groups["Name"].Value);
                    var htmlValue = value == null ? "" : value.ToString();
                    s = s.Replace(match.Value, htmlValue);
                }

            }
            return s;
        }
		public static void ReadForm(object message, IValueProvider valueProvider, Func<PropertyDescriptor, bool> shouldBypass)
		{
			Type objectType = message.GetType();
			ICustomTypeDescriptor typeDescriptor = TypeDescriptor.GetProvider(objectType).GetTypeDescriptor(objectType);

			foreach (PropertyDescriptor propertyDescriptor in typeDescriptor.GetProperties())
			{
				if (shouldBypass != null && shouldBypass(propertyDescriptor))
					continue;

				if (propertyDescriptor.Attributes.Cast<Attribute>().OfType<JsonIgnoreAttribute>().Count() == 0)
				{
					JsonPropertyAttribute propAttr = propertyDescriptor.Attributes.Cast<Attribute>().OfType<JsonPropertyAttribute>().SingleOrDefault();
					string propertyName = propAttr != null ? propAttr.PropertyName : propertyDescriptor.Name;

					ValueProviderResult valueResult = valueProvider.GetValue(propertyName);
					if (valueResult != null)
					{
						object convertedValue = valueResult.ConvertTo(propertyDescriptor.PropertyType);
						propertyDescriptor.SetValue(message, convertedValue);
					}
				}
			}
		}
Example #55
0
        private void BindScriptLines(IValueProvider provider, string attribute, EditorController controller, IEditableScripts originalScript, ElementSaveData.ScriptsSaveData result, string ignoreExpression)
        {
            if (originalScript == null) return;
            int count = 0;
            foreach (IEditableScript script in originalScript.Scripts)
            {
                ElementSaveData.ScriptSaveData scriptLine = new ElementSaveData.ScriptSaveData();
                scriptLine.IsSelected = (bool)provider.GetValue(string.Format("selected-{0}-{1}", attribute, count)).ConvertTo(typeof(bool));

                if (script.Type != ScriptType.If)
                {
                    IEditorDefinition definition = controller.GetEditorDefinition(script);
                    foreach (IEditorControl ctl in definition.Controls.Where(c => c.Attribute != null))
                    {
                        string key = string.Format("{0}-{1}-{2}", attribute, count, ctl.Attribute);

                        if (ctl.ControlType == "script")
                        {
                            IEditorData scriptEditorData = controller.GetScriptEditorData(script);
                            IEditableScripts originalSubScript = (IEditableScripts)scriptEditorData.GetAttribute(ctl.Attribute);
                            ElementSaveData.ScriptsSaveData scriptResult = new ElementSaveData.ScriptsSaveData();
                            BindScriptLines(provider, key, controller, originalSubScript, scriptResult, ignoreExpression);
                            scriptLine.Attributes.Add(ctl.Attribute, scriptResult);
                        }
                        else if (ctl.ControlType == "scriptdictionary")
                        {
                            IEditorData dictionaryData = controller.GetScriptEditorData(script);
                            IEditableDictionary<IEditableScripts> dictionary = (IEditableDictionary<IEditableScripts>)dictionaryData.GetAttribute(ctl.Attribute);
                            ElementSaveData.ScriptSaveData switchResult = BindScriptDictionary(provider, controller, ignoreExpression, dictionary, key);
                            scriptLine.Attributes.Add(ctl.Attribute, switchResult);
                        }
                        else if (ctl.ControlType == "list")
                        {
                            // do nothing
                        }
                        else
                        {
                            object value = GetScriptParameterValue(
                                scriptLine,
                                controller,
                                provider,
                                key,
                                ctl.ControlType,
                                ctl.GetString("simpleeditor") ?? "textbox",
                                ctl.GetString("usetemplates"),
                                (string)script.GetParameter(ctl.Attribute),
                                ignoreExpression
                            );
                            scriptLine.Attributes.Add(ctl.Attribute, value);
                        }
                    }
                }
                else
                {
                    EditableIfScript ifScript = (EditableIfScript)script;

                    object expressionValue = GetScriptParameterValue(
                        scriptLine,
                        controller,
                        provider,
                        string.Format("{0}-{1}-expression", attribute, count),
                        "expression",
                        null,
                        "if",
                        (string)ifScript.GetAttribute("expression"),
                        ignoreExpression
                    );

                    scriptLine.Attributes.Add("expression", expressionValue);

                    ElementSaveData.ScriptsSaveData thenScriptResult = new ElementSaveData.ScriptsSaveData();
                    BindScriptLines(provider, string.Format("{0}-{1}-then", attribute, count), controller, ifScript.ThenScript, thenScriptResult, ignoreExpression);
                    scriptLine.Attributes.Add("then", thenScriptResult);

                    int elseIfCount = 0;
                    foreach (EditableIfScript.EditableElseIf elseIf in ifScript.ElseIfScripts)
                    {
                        object elseIfExpressionValue = GetScriptParameterValue(
                            scriptLine,
                            controller,
                            provider,
                            string.Format("{0}-{1}-elseif{2}-expression", attribute, count, elseIfCount),
                            "expression",
                            null,
                            "if",
                            elseIf.Expression,
                            ignoreExpression
                        );

                        scriptLine.Attributes.Add(string.Format("elseif{0}-expression", elseIfCount), elseIfExpressionValue);

                        ElementSaveData.ScriptsSaveData elseIfScriptResult = new ElementSaveData.ScriptsSaveData();
                        BindScriptLines(provider, string.Format("{0}-{1}-elseif{2}", attribute, count, elseIfCount), controller, elseIf.EditableScripts, elseIfScriptResult, ignoreExpression);
                        scriptLine.Attributes.Add(string.Format("elseif{0}-then", elseIfCount), elseIfScriptResult);
                        elseIfCount++;
                    }

                    if (ifScript.ElseScript != null)
                    {
                        ElementSaveData.ScriptsSaveData elseScriptResult = new ElementSaveData.ScriptsSaveData();
                        BindScriptLines(provider, string.Format("{0}-{1}-else", attribute, count), controller, ifScript.ElseScript, elseScriptResult, ignoreExpression);
                        scriptLine.Attributes.Add("else", elseScriptResult);
                    }
                }

                result.ScriptLines.Add(scriptLine);
                count++;
            }
        }
Example #56
0
 private List<object> GetListModel(ControllerContext controllerContext, Type modelType, Type elementType, IValueProvider valueProvider, string prefix)
 {
     List<object> list = new List<object>();
     if (!string.IsNullOrEmpty(prefix) && valueProvider.ContainsPrefix(prefix))
     {
         ValueProviderResult result = valueProvider.GetValue(prefix);
         if (null != result)
         {
             IEnumerable enumerable = result.ConvertTo(modelType) as IEnumerable;
             foreach (var value in enumerable)
             {
                 list.Add(value);
             }
         }
     }
     bool numericIndex;
     IEnumerable<string> indexes = GetIndexes(prefix, valueProvider, out numericIndex);
     foreach (var index in indexes)
     {
         string indexPrefix = prefix + "[" + index + "]";
         if (!valueProvider.ContainsPrefix(indexPrefix) && numericIndex)
         {
             break;
         }
         list.Add(GetModel(controllerContext, elementType, valueProvider, indexPrefix));
     }
     return list;
 }
Example #57
0
 private IEnumerable<string> GetIndexes(string prefix, IValueProvider valueProvider, out bool numericIndex)
 {
     string key = string.IsNullOrEmpty(prefix) ? "index" : prefix + "." + "index";
     ValueProviderResult result = valueProvider.GetValue(key);
     if (null != result)
     {
         string[] indexes = result.ConvertTo(typeof(string[])) as string[];
         if (null != indexes)
         {
             numericIndex = false;
             return indexes;
         }
     }
     numericIndex = true;
     return GetZeroBasedIndexes();
 }
Example #58
0
        private object GetScriptParameterValue(ElementSaveData.ScriptSaveData scriptLine, EditorController controller, IValueProvider provider, string attributePrefix, string controlType, string simpleEditor, string templatesFilter, string oldValue, string ignoreExpression)
        {
            if (attributePrefix == ignoreExpression) return new IgnoredValue();

            if (controlType == "expression")
            {
                if (templatesFilter == null)
                {
                    string dropdownKey = string.Format("{0}-expressioneditordropdown", attributePrefix);
                    ValueProviderResult dropdownKeyValueResult = provider.GetValue(dropdownKey);
                    string dropdownKeyValue = (dropdownKeyValueResult != null) ? dropdownKeyValueResult.ConvertTo(typeof(string)) as string : null;
                    if (dropdownKeyValue == "expression" || dropdownKeyValue == null)
                    {
                        string key = string.Format("{0}-expressioneditor", attributePrefix);
                        return GetAndValidateValueProviderString(provider, key, oldValue, scriptLine, controller);
                    }
                    else
                    {
                        if (simpleEditor == "boolean")
                        {
                            return dropdownKeyValue == "yes" ? "true" : "false";
                        }
                        else
                        {
                            string key = string.Format("{0}-simpleeditor", attributePrefix);
                            string simpleValue = GetValueProviderString(provider, key);
                            if (simpleValue == null) return string.Empty;

                            switch (simpleEditor)
                            {
                                case "objects":
                                case "number":
                                case "numberdouble":
                                    return simpleValue;
                                default:
                                    return EditorUtility.ConvertFromSimpleStringExpression(simpleValue);
                            }
                        }
                    }
                }
                else
                {
                    string dropdownKey = string.Format("{0}-templatedropdown", attributePrefix);
                    string dropdownKeyValue = provider.GetValue(dropdownKey).ConvertTo(typeof(string)) as string;
                    if (dropdownKeyValue == "expression")
                    {
                        string key = attributePrefix;
                        return GetAndValidateValueProviderString(provider, key, oldValue, scriptLine, controller);
                    }
                    else
                    {
                        IEditorDefinition editorDefinition = controller.GetExpressionEditorDefinition(oldValue, templatesFilter);
                        IEditorData data = controller.GetExpressionEditorData(oldValue, templatesFilter, null);

                        foreach (IEditorControl ctl in editorDefinition.Controls.Where(c => c.Attribute != null))
                        {
                            string key = attributePrefix + "-" + ctl.Attribute;
                            object value = GetScriptParameterValue(scriptLine, controller, provider, key, ctl.ControlType, ctl.GetString("simpleeditor") ?? "textbox", null, null, ignoreExpression);
                            data.SetAttribute(ctl.Attribute, value);
                        }

                        return controller.GetExpression(data, null, null);
                    }
                }
            }
            else
            {
                string key = attributePrefix;
                return GetValueProviderString(provider, key);
            }
        }
Example #59
0
 private string GetValueProviderString(IValueProvider provider, string key)
 {
     try
     {
         ValueProviderResult value = provider.GetValue(key);
         return value == null ? null : (string)value.ConvertTo(typeof(string));
     }
     catch (HttpRequestValidationException)
     {
         // Workaround for "potentially dangerous" form values which may contain HTML
         Func<System.Collections.Specialized.NameValueCollection> formGetter;
         Func<System.Collections.Specialized.NameValueCollection> queryStringGetter;
         Microsoft.Web.Infrastructure.DynamicValidationHelper.ValidationUtility.GetUnvalidatedCollections(HttpContext.Current, out formGetter, out queryStringGetter);
         return formGetter().Get(key);
     }
 }
		private Type GetValueType(HashSet<string> keys, string prefix, IValueProvider valueProvider)
		{
			var typeKey = prefix + ".__Type__";
			if (keys.Contains(typeKey))
			{
				var type = Type.GetType(valueProvider.GetValue(typeKey).AttemptedValue, true);
				return type;
			}
			return typeof(object);
		}