コード例 #1
0
    public async Task BindModelAsync(ModelBindingContext bindingContext)
    {
        var messageTypeModelName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, "messageType");
        var messageTypeResult    = bindingContext.ValueProvider.GetValue(messageTypeModelName);

        if (messageTypeResult == ValueProviderResult.None)
        {
            bindingContext.Result = ModelBindingResult.Failed();
            return;
        }

        IModelBinder binder;

        if (!_binders.TryGetValue(messageTypeResult.FirstValue, out binder))
        {
            bindingContext.Result = ModelBindingResult.Failed();
            return;
        }

        // Now know the type exists in the assembly.
        var type     = Type.GetType(messageTypeResult.FirstValue);
        var metadata = _metadataProvider.GetMetadataForType(type);

        ModelBindingResult result;

        using (bindingContext.EnterNestedScope(metadata, bindingContext.FieldName, bindingContext.ModelName, model: null))
        {
            await binder.BindModelAsync(bindingContext);

            result = bindingContext.Result;
        }

        bindingContext.Result = result;
    }
コード例 #2
0
        public void Validate_ReturnsExpectedResults_Collection()
        {
            // Arrange
            var validator = new DataSetValidator();
            var model     = DataSet <SampleModel> .Create();

            model.AddRow();

            var metadata = _metadataProvider.GetMetadataForProperty(
                typeof(SampleModelContainer),
                nameof(SampleModelContainer.SampleModel));
            var validationContext = new ModelValidationContext(
                new ActionContext(),
                metadata,
                _metadataProvider,
                container: null,
                model: model);

            // Act
            var results      = validator.Validate(validationContext);
            var resultsArray = results.ToArray();

            // Assert
            Assert.NotNull(results);
            Assert.Single(resultsArray);
            Assert.Equal(ModelNames.CreatePropertyModelName("[0]", nameof(SampleModel.ID)), resultsArray[0].MemberName);
        }
            public Task BindModelAsync(ModelBindingContext bindingContext)
            {
                if (bindingContext == null)
                {
                    throw new ArgumentNullException(nameof(bindingContext));
                }
                Debug.Assert(bindingContext.Result == null);

                if (bindingContext.ModelType != typeof(Address))
                {
                    return(TaskCache.CompletedTask);
                }

                var address = new Address()
                {
                    Street = "SomeStreet"
                };

                bindingContext.ModelState.SetModelValue(
                    ModelNames.CreatePropertyModelName(bindingContext.ModelName, "Street"),
                    new string[] { address.Street },
                    address.Street);

                bindingContext.Result = ModelBindingResult.Success(bindingContext.ModelName, address);
                return(TaskCache.CompletedTask);
            }
コード例 #4
0
            public bool MoveNext()
            {
                TValue value;

                while (true)
                {
                    if (!_keyMappingEnumerator.MoveNext())
                    {
                        return(false);
                    }

                    if (_model.TryGetValue(_keyMappingEnumerator.Current.Value, out value))
                    {
                        // Skip over entries that we can't find in the dictionary, they will show up as unvalidated.
                        break;
                    }
                }

                var key   = ModelNames.CreateIndexModelName(_key, _keyMappingEnumerator.Current.Key);
                var model = value;

                _entry = new ValidationEntry(_metadata, key, model);

                return(true);
            }
コード例 #5
0
        public async Task CollectionModelBinder_DoesNotCreateCollection_IfNotIsTopLevelObject(
            string prefix,
            bool allowValidatingTopLevelNodes,
            bool isBindingRequired)
        {
            // Arrange
            var binder = new CollectionModelBinder <string>(
                new StubModelBinder(result: ModelBindingResult.Failed()),
                NullLoggerFactory.Instance,
                allowValidatingTopLevelNodes);

            var bindingContext = CreateContext();

            bindingContext.ModelName = ModelNames.CreatePropertyModelName(prefix, "ListProperty");

            var metadataProvider = new TestModelMetadataProvider();

            metadataProvider
            .ForProperty(typeof(ModelWithListProperty), nameof(ModelWithListProperty.ListProperty))
            .BindingDetails(b => b.IsBindingRequired = isBindingRequired);
            bindingContext.ModelMetadata             = metadataProvider.GetMetadataForProperty(
                typeof(ModelWithListProperty),
                nameof(ModelWithListProperty.ListProperty));

            bindingContext.ValueProvider = new TestValueProvider(new Dictionary <string, object>());

            // Act
            await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.False(bindingContext.Result.IsModelSet);
            Assert.Equal(0, bindingContext.ModelState.ErrorCount);
        }
コード例 #6
0
        public async Task DictionaryModelBinder_DoesNotCreateCollection_IfNotIsTopLevelObject(string prefix)
        {
            // Arrange
            var binder = new DictionaryModelBinder <int, int>(
                new SimpleTypeModelBinder(typeof(int)),
                new SimpleTypeModelBinder(typeof(int)));

            var context = CreateContext();

            context.ModelName = ModelNames.CreatePropertyModelName(prefix, "ListProperty");

            var metadataProvider = new TestModelMetadataProvider();

            context.ModelMetadata = metadataProvider.GetMetadataForProperty(
                typeof(ModelWithDictionaryProperties),
                nameof(ModelWithDictionaryProperties.DictionaryProperty));

            context.ValueProvider = new TestValueProvider(new Dictionary <string, object>());

            // Act
            var result = await binder.BindModelResultAsync(context);

            // Assert
            Assert.Equal(default(ModelBindingResult), result);
        }
コード例 #7
0
        private void BindCollection(ModelStateDictionary modelState, IValueProvider valueProvider, string modelName, DataSet dataSet)
        {
            var indexNames = GetIndexNames(valueProvider, modelName);

            bool indexNamesIsFinite;

            if (indexNames != null)
            {
                indexNamesIsFinite = true;
            }
            else
            {
                indexNamesIsFinite = false;
                indexNames         = Enumerable.Range(0, int.MaxValue).Select(i => i.ToString(CultureInfo.InvariantCulture));
            }

            var currentIndex = 0;

            foreach (var indexName in indexNames)
            {
                var dataRowModelName = ModelNames.CreateIndexModelName(modelName, indexName);
                if (!valueProvider.ContainsPrefix(dataRowModelName) && !indexNamesIsFinite)
                {
                    break;
                }

                if (currentIndex >= dataSet.Count)
                {
                    dataSet.AddRow();
                }
                Bind(modelState, valueProvider, dataRowModelName, dataSet[currentIndex++]);
            }
        }
コード例 #8
0
        private void Bind(ModelStateDictionary modelState, IValueProvider valueProvider, string modelName, DataRow dataRow)
        {
            modelState.SetModelValue(modelName, dataRow, string.Empty);

            dataRow.SuspendValueChangedNotification();

            var model   = dataRow.Model;
            var columns = model.GetColumns();

            foreach (var column in columns)
            {
                if (column.IsReadOnly(dataRow))
                {
                    continue;
                }
                Bind(modelState, valueProvider, modelName, column, dataRow);
            }

            IReadOnlyList <DataSet> childDataSets = dataRow.ChildDataSets;

            foreach (var childDataSet in childDataSets)
            {
                Bind(modelState, valueProvider, ModelNames.CreatePropertyModelName(modelName, childDataSet.Model.GetName()), childDataSet, isScalar: false);
            }

            dataRow.ResumeValueChangedNotification();
        }
コード例 #9
0
        public List <ModelNames> GetAll()
        {
            List <ModelNames> models = new List <ModelNames>();

            using (var cn = new SqlConnection(Settings.GetConnectionString()))
            {
                SqlCommand cmd = new SqlCommand("ModelsSelectAll", cn);
                cmd.CommandType = CommandType.StoredProcedure;

                cn.Open();
                using (SqlDataReader dr = cmd.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        ModelNames currentRow = new ModelNames();
                        currentRow.MakeID    = (int)dr["MakeID"];
                        currentRow.MakeName  = dr["MakeName"].ToString();
                        currentRow.ModelID   = (int)dr["ModelID"];
                        currentRow.ModelName = dr["ModelName"].ToString();
                        currentRow.AddDate   = (DateTime)dr["AddDate"];
                        currentRow.UserID    = dr["UserID"].ToString();
                        currentRow.Email     = dr["Email"].ToString();

                        models.Add(currentRow);
                    }
                }
            }
            return(models);
        }
            public Task <ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
            {
                if (bindingContext.ModelType != typeof(Address))
                {
                    return(null);
                }

                var address = new Address()
                {
                    Street = "SomeStreet"
                };

                bindingContext.ModelState.SetModelValue(
                    ModelNames.CreatePropertyModelName(bindingContext.ModelName, "Street"),
                    new ValueProviderResult(
                        address.Street,
                        address.Street,
                        CultureInfo.CurrentCulture));

                var validationNode = new ModelValidationNode(
                    bindingContext.ModelName,
                    bindingContext.ModelMetadata,
                    address)
                {
                    ValidateAllProperties = true
                };

                return(Task.FromResult(new ModelBindingResult(address, bindingContext.ModelName, true, validationNode)));
            }
コード例 #11
0
            public async Task BindModelAsync(ModelBindingContext bindingContext)
            {
                if (bindingContext == null)
                {
                    throw new ArgumentNullException(nameof(bindingContext));
                }

                var fieldName = nameof(Model.Value);
                var modelName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, fieldName);
                ModelBindingResult valueResult;

                using (bindingContext.EnterNestedScope(
                           bindingContext.ModelMetadata.Properties[fieldName],
                           fieldName,
                           modelName,
                           model: null))
                {
                    await _binder.BindModelAsync(bindingContext);

                    valueResult = bindingContext.Result;
                }

                if (!valueResult.IsModelSet)
                {
                    return;
                }

                var model = new Model
                {
                    FieldName = bindingContext.FieldName,
                    Value     = (string)valueResult.Model,
                };

                bindingContext.Result = ModelBindingResult.Success(model);
            }
コード例 #12
0
        public async Task DictionaryModelBinder_DoesNotCreateCollection_IfNotIsTopLevelObject(string prefix)
        {
            // Arrange
            var binder = new DictionaryModelBinder <int, int>(
                new SimpleTypeModelBinder(typeof(int), NullLoggerFactory.Instance),
                new SimpleTypeModelBinder(typeof(int), NullLoggerFactory.Instance),
                NullLoggerFactory.Instance);

            var bindingContext = CreateContext();

            bindingContext.ModelName = ModelNames.CreatePropertyModelName(prefix, "ListProperty");

            var metadataProvider = new TestModelMetadataProvider();

            bindingContext.ModelMetadata = metadataProvider.GetMetadataForProperty(
                typeof(ModelWithDictionaryProperties),
                nameof(ModelWithDictionaryProperties.DictionaryProperty));

            bindingContext.ValueProvider = new TestValueProvider(new Dictionary <string, object>());

            // Act
            await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.False(bindingContext.Result.IsModelSet);
        }
コード例 #13
0
        public async Task KeyValuePairModelBinder_DoesNotCreateCollection_IfNotIsTopLevelObject(string prefix)
        {
            // Arrange
            var binder = new KeyValuePairModelBinder <string, string>(
                new SimpleTypeModelBinder(typeof(string)),
                new SimpleTypeModelBinder(typeof(string)));

            var bindingContext = CreateContext();

            bindingContext.ModelName = ModelNames.CreatePropertyModelName(prefix, "KeyValuePairProperty");

            var metadataProvider = new TestModelMetadataProvider();

            bindingContext.ModelMetadata = metadataProvider.GetMetadataForProperty(
                typeof(ModelWithKeyValuePairProperty),
                nameof(ModelWithKeyValuePairProperty.KeyValuePairProperty));

            bindingContext.ValueProvider = new TestValueProvider(new Dictionary <string, object>());

            // Act
            await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.False(bindingContext.Result.IsModelSet);
        }
コード例 #14
0
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var modelTypeValue = bindingContext.ValueProvider.GetValue(ModelNames.CreatePropertyModelName(bindingContext.ModelName, "ModelTypeName"));

            if (modelTypeValue != null && modelTypeValue.FirstValue != null)
            {
                Type modelType = Type.GetType(modelTypeValue.FirstValue);
                if (this.modelBuilderByType.TryGetValue(modelType, out var modelBinder))
                {
                    ModelBindingContext innerModelBindingContext = DefaultModelBindingContext.CreateBindingContext(
                        bindingContext.ActionContext,
                        bindingContext.ValueProvider,
                        this.modelMetadataProvider.GetMetadataForType(modelType),
                        null,
                        bindingContext.ModelName);

                    modelBinder.BindModelAsync(innerModelBindingContext);

                    bindingContext.Result = innerModelBindingContext.Result;
                    return(Task.CompletedTask);
                }
            }

            bindingContext.Result = ModelBindingResult.Failed();
            return(Task.CompletedTask);
        }
コード例 #15
0
            public bool MoveNext()
            {
                _index++;
                if (_index >= _properties.Count)
                {
                    return(false);
                }

                var property     = _properties[_index];
                var propertyName = property.BinderModelName ?? property.PropertyName;
                var key          = ModelNames.CreatePropertyModelName(_key, propertyName);

                if (_model == null)
                {
                    // Performance: Never create a delegate when container is null.
                    _entry = new ValidationEntry(property, key, model: null);
                }
                else if (IsMono)
                {
                    _entry = new ValidationEntry(property, key, () => GetModelOnMono(_model, property.PropertyName));
                }
                else
                {
                    _entry = new ValidationEntry(property, key, () => GetModel(_model, property));
                }

                return(true);
            }
コード例 #16
0
        // Used when the ValueProvider contains the collection to be bound as multiple elements, e.g. foo[0], foo[1].
        private Task <CollectionResult> BindComplexCollection(IndexModelBindingContext bindingContext)
        {
            var indexPropertyName        = ModelNames.CreatePropertyModelName(bindingContext.ModelName, "index");
            var valueProviderResultIndex = bindingContext.ValueProvider.GetValue(indexPropertyName);
            var indexNames = GetIndexNamesFromValueProviderResult(valueProviderResultIndex);

            return(BindComplexCollectionFromIndexes(bindingContext, indexNames));
        }
コード例 #17
0
        private async Task BindModelCoreAsync(ModelBindingContext bindingContext)
        {
            // Create model first (if necessary) to avoid reporting errors about properties when activation fails.
            if (bindingContext.Model == null)
            {
                bindingContext.Model = CreateModel(bindingContext);
            }

            for (var i = 0; i < bindingContext.ModelMetadata.Properties.Count; i++)
            {
                var property = bindingContext.ModelMetadata.Properties[i];
                if (!CanBindProperty(bindingContext, property))
                {
                    continue;
                }

                // Pass complex (including collection) values down so that binding system does not unnecessarily
                // recreate instances or overwrite inner properties that are not bound. No need for this with simple
                // values because they will be overwritten if binding succeeds. Arrays are never reused because they
                // cannot be resized.
                object propertyModel = null;
                if (property.PropertyGetter != null &&
                    property.IsComplexType &&
                    !property.ModelType.IsArray)
                {
                    propertyModel = property.PropertyGetter(bindingContext.Model);
                }

                var fieldName = property.BinderModelName ?? property.PropertyName;
                var modelName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, fieldName);

                ModelBindingResult result;
                using (bindingContext.EnterNestedScope(
                           modelMetadata: property,
                           fieldName: fieldName,
                           modelName: modelName,
                           model: propertyModel))
                {
                    await BindProperty(bindingContext);

                    result = bindingContext.Result;
                }

                if (result.IsModelSet)
                {
                    SetProperty(bindingContext, modelName, property, result);
                }
                else if (property.IsBindingRequired)
                {
                    var message = property.ModelBindingMessageProvider.MissingBindRequiredValueAccessor(fieldName);
                    bindingContext.ModelState.TryAddModelError(modelName, message);
                }
            }

            bindingContext.Result = ModelBindingResult.Success(bindingContext.Model);
            _logger.DoneAttemptingToBindModel(bindingContext);
        }
コード例 #18
0
        private static string GetName(string containerName, ApiParameterDescriptionContext metadata)
        {
            if (string.IsNullOrEmpty(metadata.BinderModelName))
            {
                return(ModelNames.CreatePropertyModelName(containerName, metadata.PropertyName));
            }

            return(metadata.BinderModelName);
        }
コード例 #19
0
ファイル: DefaultValidator.cs プロジェクト: xareas/framework
        /// <summary>
        /// Validates a single node in a model object graph.
        /// </summary>
        /// <returns><c>true</c> if the node is valid, otherwise <c>false</c>.</returns>
        protected virtual bool ValidateNode()
        {
            var state = ModelState.GetValidationState(Key);

            // Rationale: we might see the same model state key used for two different objects.
            // We want to run validation unless it's already known that this key is invalid.
            if (state != ModelValidationState.Invalid)
            {
                var validators = Cache.GetValidators(Metadata, ValidatorProvider);

                var count = validators.Count;
                if (count > 0)
                {
                    var context = new ModelValidationContext(
                        Context,
                        Metadata,
                        MetadataProvider,
                        Container,
                        Model);

                    var results = new List <ModelValidationResult>();
                    for (var i = 0; i < count; i++)
                    {
                        results.AddRange(validators[i].Validate(context));
                    }

                    var resultsCount = results.Count;
                    for (var i = 0; i < resultsCount; i++)
                    {
                        var result = results[i];
                        var key    = ModelNames.CreatePropertyModelName(Key, result.MemberName);

                        // It's OK for key to be the empty string here. This can happen when a top
                        // level object implements IValidatableObject.
                        ModelState.TryAddModelError(key, result.Message);
                    }
                }
            }

            state = ModelState.GetFieldValidationState(Key);
            if (state == ModelValidationState.Invalid)
            {
                return(false);
            }
            else
            {
                // If the field has an entry in ModelState, then record it as valid. Don't create
                // extra entries if they don't exist already.
                var entry = ModelState[Key];
                if (entry != null)
                {
                    entry.ValidationState = ModelValidationState.Valid;
                }

                return(true);
            }
        }
コード例 #20
0
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            var name = ModelNames.CreatePropertyModelName(
                bindingContext.ModelName,
                nameof(Device.Kind));

            var deviceKind = bindingContext.ValueProvider.GetValue(name).FirstValue;

            if (string.IsNullOrEmpty(deviceKind))
            {
                bindingContext.Result = ModelBindingResult.Failed();
                return(Task.CompletedTask);
            }

            Device result;

            if (deviceKind == "Laptop")
            {
                var modelName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, nameof(Laptop.CPUIndex));
                var cpuIndex  = bindingContext.ValueProvider.GetValue(modelName).FirstValue;
                result = new Laptop
                {
                    Kind     = deviceKind,
                    CPUIndex = cpuIndex,
                };
            }
            else if (deviceKind == "SmartPhone")
            {
                var modelName  = ModelNames.CreatePropertyModelName(bindingContext.ModelName, nameof(SmartPhone.ScreenSize));
                var screenSize = bindingContext.ValueProvider.GetValue(modelName).FirstValue;
                result = new SmartPhone
                {
                    Kind       = deviceKind,
                    ScreenSize = screenSize,
                };
            }
            else
            {
                bindingContext.ModelState.TryAddModelError(name, $"Unknown device kind '{deviceKind}'.");

                bindingContext.Result = ModelBindingResult.Failed();
                return(Task.CompletedTask);
            }

            bindingContext.Result = ModelBindingResult.Success(result);

            // Add a ValidationStateEntry with the "correct" ModelMetadata so validation executes on the actual type, not the declared type.
            var modelMetadataProvider = bindingContext.HttpContext.RequestServices.GetRequiredService <IModelMetadataProvider>();

            bindingContext.ValidationState.Add(result, new ValidationStateEntry
            {
                Metadata = modelMetadataProvider.GetMetadataForType(result.GetType()),
            });

            return(Task.CompletedTask);
        }
コード例 #21
0
ファイル: Extensions.cs プロジェクト: aTiKhan/RDO.Net
        private static string ResolveMemberName(DataSet dataSet, bool isScalar, Column column, DataRow dataRow)
        {
            if (column.GetParent() == dataSet.Model)
            {
                return(isScalar ? column.Name : ModelNames.CreatePropertyModelName(ModelNames.CreateIndexModelName(string.Empty, dataRow.Index), column.Name));
            }

            Debug.Assert(dataRow != null);
            return(ResolveMemberName(dataSet, isScalar, dataRow, column.Name));
        }
コード例 #22
0
ファイル: ModelBindingHelper.cs プロジェクト: zt97/Mvc
        private static Expression <Func <ModelBindingContext, string, bool> > GetPredicateExpression <TModel>
            (string prefix, Expression <Func <TModel, object> > expression)
        {
            var propertyName = GetPropertyName(expression.Body);
            var property     = ModelNames.CreatePropertyModelName(prefix, propertyName);

            return
                ((context, modelPropertyName) =>
                 property.Equals(ModelNames.CreatePropertyModelName(context.ModelName, modelPropertyName),
                                 StringComparison.OrdinalIgnoreCase));
        }
コード例 #23
0
ファイル: Extensions.cs プロジェクト: aTiKhan/RDO.Net
        private static string ResolveMemberName(DataSet dataSet, bool isScalar, DataRow dataRow, string memberName)
        {
            if (dataRow.Model == dataSet.Model)
            {
                return(isScalar ? memberName : ModelNames.CreatePropertyModelName(ModelNames.CreateIndexModelName(string.Empty, dataRow.Index), memberName));
            }

            memberName = ModelNames.CreatePropertyModelName(ModelNames.CreateIndexModelName(dataRow.Model.GetName(), dataRow.Index), memberName);
            Debug.Assert(dataRow.ParentDataRow != null);
            return(ResolveMemberName(dataSet, isScalar, dataRow.ParentDataRow, memberName));
        }
コード例 #24
0
 private static IEnumerable <ModelValidationResult> ValidateCollection(string prefix, DataSet dataSet)
 {
     for (int index = 0; index < dataSet.Count; index++)
     {
         var dataRowPrefix = ModelNames.CreateIndexModelName(prefix, index);
         foreach (var result in Validate(dataRowPrefix, dataSet[index]))
         {
             yield return(result);
         }
     }
 }
コード例 #25
0
        /// <inheritdoc />
        public async Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            _logger.AttemptingToBindModel(bindingContext);

            var keyModelName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, "Key");
            var keyResult    = await TryBindStrongModel <TKey>(bindingContext, _keyBinder, "Key", keyModelName);

            var valueModelName = ModelNames.CreatePropertyModelName(bindingContext.ModelName, "Value");
            var valueResult    = await TryBindStrongModel <TValue>(bindingContext, _valueBinder, "Value", valueModelName);

            if (keyResult.IsModelSet && valueResult.IsModelSet)
            {
                var model = new KeyValuePair <TKey, TValue>(
                    ModelBindingHelper.CastOrDefault <TKey>(keyResult.Model),
                    ModelBindingHelper.CastOrDefault <TValue>(valueResult.Model));

                bindingContext.Result = ModelBindingResult.Success(model);
                _logger.DoneAttemptingToBindModel(bindingContext);
                return;
            }

            if (!keyResult.IsModelSet && valueResult.IsModelSet)
            {
                bindingContext.ModelState.TryAddModelError(
                    keyModelName,
                    bindingContext.ModelMetadata.ModelBindingMessageProvider.MissingKeyOrValueAccessor());
                _logger.DoneAttemptingToBindModel(bindingContext);
                return;
            }

            if (keyResult.IsModelSet && !valueResult.IsModelSet)
            {
                bindingContext.ModelState.TryAddModelError(
                    valueModelName,
                    bindingContext.ModelMetadata.ModelBindingMessageProvider.MissingKeyOrValueAccessor());
                _logger.DoneAttemptingToBindModel(bindingContext);
                return;
            }

            // If we failed to find data for a top-level model, then generate a
            // default 'empty' model and return it.
            if (bindingContext.IsTopLevelObject)
            {
                var model = new KeyValuePair <TKey, TValue>();
                bindingContext.Result = ModelBindingResult.Success(model);
            }
            _logger.DoneAttemptingToBindModel(bindingContext);
        }
コード例 #26
0
 private static string GetName(string containerName, ApiParameterDescriptionContext metadata)
 {
     if (!string.IsNullOrEmpty(metadata.BinderModelName))
     {
         // Name was explicitly provided
         return(metadata.BinderModelName);
     }
     else
     {
         return(ModelNames.CreatePropertyModelName(containerName, metadata.PropertyName));
     }
 }
コード例 #27
0
        private IList <ModelValidationNode> GetChildNodes(ValidationContext context, ModelExplorer modelExplorer)
        {
            var validationNode = context.ValidationNode;

            // This is the trivial case where the node-tree that was built-up during binding already has
            // all of the nodes we need.
            if (validationNode.ChildNodes.Count != 0 ||
                !validationNode.ValidateAllProperties ||
                validationNode.Model == null)
            {
                return(validationNode.ChildNodes);
            }

            var childNodes      = new List <ModelValidationNode>(validationNode.ChildNodes);
            var elementMetadata = modelExplorer.Metadata.ElementMetadata;

            if (elementMetadata == null)
            {
                foreach (var property in validationNode.ModelMetadata.Properties)
                {
                    var propertyExplorer    = modelExplorer.GetExplorerForProperty(property.PropertyName);
                    var propertyBindingName = property.BinderModelName ?? property.PropertyName;
                    var childKey            = ModelNames.CreatePropertyModelName(validationNode.Key, propertyBindingName);
                    var childNode           = new ModelValidationNode(childKey, property, propertyExplorer.Model)
                    {
                        ValidateAllProperties = true
                    };
                    childNodes.Add(childNode);
                }
            }
            else
            {
                var enumerableModel = (IEnumerable)modelExplorer.Model;

                // An integer index is incorrect in scenarios where there is a custom index provided by the user.
                // However those scenarios are supported by createing a ModelValidationNode with the right keys.
                var index = 0;
                foreach (var element in enumerableModel)
                {
                    var elementExplorer = new ModelExplorer(_modelMetadataProvider, elementMetadata, element);
                    var elementKey      = ModelNames.CreateIndexModelName(validationNode.Key, index);
                    var childNode       = new ModelValidationNode(elementKey, elementMetadata, elementExplorer.Model)
                    {
                        ValidateAllProperties = true
                    };

                    childNodes.Add(childNode);
                    index++;
                }
            }

            return(childNodes);
        }
コード例 #28
0
        /// <summary>
        /// Validates a single node in a model object graph.
        /// </summary>
        /// <returns><c>true</c> if the node is valid, otherwise <c>false</c>.</returns>
        protected virtual bool ValidateNode()
        {
            var state = _modelState.GetValidationState(_key);

            if (state == ModelValidationState.Unvalidated)
            {
                var validators = GetValidators(_metadata);

                var count = validators.Count;
                if (count > 0)
                {
                    var context = new ModelValidationContext()
                    {
                        Container = _container,
                        Model     = _model,
                        Metadata  = _metadata,
                    };

                    var results = new List <ModelValidationResult>();
                    for (var i = 0; i < count; i++)
                    {
                        results.AddRange(validators[i].Validate(context));
                    }

                    var resultsCount = results.Count;
                    for (var i = 0; i < resultsCount; i++)
                    {
                        var result = results[i];
                        var key    = ModelNames.CreatePropertyModelName(_key, result.MemberName);
                        _modelState.TryAddModelError(key, result.Message);
                    }
                }
            }

            state = _modelState.GetFieldValidationState(_key);
            if (state == ModelValidationState.Invalid)
            {
                return(false);
            }
            else
            {
                // If the field has an entry in ModelState, then record it as valid. Don't create
                // extra entries if they don't exist already.
                var entry = _modelState[_key];
                if (entry != null)
                {
                    entry.ValidationState = ModelValidationState.Valid;
                }

                return(true);
            }
        }
コード例 #29
0
ファイル: Reply.cs プロジェクト: vijayamazon/ezbob
        public ModelOutput GetParsedModel(ModelNames name)
        {
            if (this.parsedModels.ContainsKey(name))
            {
                return(this.parsedModels[name]);
            }

            this.parsedModels[name] = this.HasModels()
                                ? JsonConvert.DeserializeObject <ModelOutput>(Inference.Decision.Models[name])
                                : null;

            return(this.parsedModels[name]);
        }         // GetParsedModel
コード例 #30
0
        public void CanAddModel()
        {
            ModelNames modelToAdd = new ModelNames();
            var        repo       = new ModelsRepositoryADO();

            modelToAdd.MakeID   = 1;
            modelToAdd.MakeName = "Prius";
            modelToAdd.UserID   = "48207816-600d-4d87-a87a-96722dad81cc";

            repo.Insert(modelToAdd);

            Assert.AreEqual("Prius", modelToAdd.MakeName);
        }