Beispiel #1
0
        /// <summary>
        /// Creates a new <see cref="DefaultMetadataDetails"/>.
        /// </summary>
        /// <param name="key">The <see cref="ModelMetadataIdentity"/>.</param>
        /// <param name="attributes">The set of model attributes.</param>
        public DefaultMetadataDetails(ModelMetadataIdentity key, ModelAttributes attributes)
        {
            if (attributes == null)
            {
                throw new ArgumentNullException(nameof(attributes));
            }

            Key = key;
            ModelAttributes = attributes;
        }
        /// <summary>
        /// Creates a new <see cref="DisplayMetadataProviderContext"/>.
        /// </summary>
        /// <param name="key">The <see cref="ModelMetadataIdentity"/> for the <see cref="ModelMetadata"/>.</param>
        /// <param name="attributes">The attributes for the <see cref="ModelMetadata"/>.</param>
        public DisplayMetadataProviderContext(
            ModelMetadataIdentity key,
            ModelAttributes attributes)
        {
            if (attributes == null)
            {
                throw new ArgumentNullException(nameof(attributes));
            }

            Key = key;
            Attributes = attributes.Attributes;
            PropertyAttributes = attributes.PropertyAttributes;
            TypeAttributes = attributes.TypeAttributes;

            DisplayMetadata = new DisplayMetadata();
        }
        public async Task UploadStudentWithChildIds_Returns_StudentWithChildIds()
        {
            var multipartFormDataFormatter = new MultipartFormDataFormatter();
            var formFileCollection         = new FormFileCollection();

            var childIds = Enumerable.Range(1, 3)
                           .Select(x => Guid.NewGuid())
                           .ToList();

            var models = new Dictionary <string, StringValues>();

            for (var index = 0; index < childIds.Count; index++)
            {
                models.Add($"{nameof(StudentViewModel.ChildIds)}[{index}]", childIds[index].ToString("D"));
            }

            var formCollection  = new FormCollection(models, formFileCollection);
            var httpContextMock = new Mock <HttpContext>();
            var httpRequestMock = new Mock <HttpRequest>();

            httpRequestMock.Setup(x => x.Form)
            .Returns(formCollection);

            httpRequestMock.Setup(x => x.ReadFormAsync(It.IsAny <CancellationToken>()))
            .ReturnsAsync(formCollection);

            httpContextMock.SetupGet(x => x.Request)
            .Returns(httpRequestMock.Object);

            var inputFormatter = new InputFormatterContext(httpContextMock.Object, string.Empty,
                                                           new ModelStateDictionary(), new EmptyModelMetaData(ModelMetadataIdentity.ForType(typeof(StudentViewModel))),
                                                           (stream, encoding) => TextReader.Null);

            var handledResult = await multipartFormDataFormatter
                                .ReadRequestBodyAsync(inputFormatter);

            Assert.IsInstanceOf <InputFormatterResult>(handledResult);

            var student = handledResult.Model as StudentViewModel;

            Assert.NotNull(student);

            for (var id = 0; id < childIds.Count; id++)
            {
                Assert.AreEqual(childIds[id].ToString("D"), student.ChildIds[id].ToString("D"));
            }
        }
Beispiel #4
0
    /// <summary>
    /// Creates a new <see cref="ModelMetadata"/>.
    /// </summary>
    /// <param name="identity">The <see cref="ModelMetadataIdentity"/>.</param>
    protected ModelMetadata(ModelMetadataIdentity identity)
    {
        Identity = identity;

        InitializeTypeInformation();
    }
 public MetadataBuilder(ModelMetadataIdentity key)
 {
     _key = key;
 }
Beispiel #6
0
 public FakeModelMetadata()
     : base(ModelMetadataIdentity.ForType(typeof(string)))
 {
 }
 public EmptyModelMetaData(ModelMetadataIdentity identity) : base(identity)
 {
 }
 public SubstitutedModelMetadata(ModelMetadata inner, Type substitutedModelType)
     : base(ModelMetadataIdentity.ForType(substitutedModelType)) => this.inner = inner;
Beispiel #9
0
 private ModelMetadata CreateMetada(Type type)
 {
     return(Substitute.For <ModelMetadata>(ModelMetadataIdentity.ForType(type)));
 }
Beispiel #10
0
 public ModelMetadataMock(Type type) : base(ModelMetadataIdentity.ForType(type))
 {
 }
        private static ApiDescription CreateApiDescription(RouteEndpoint routeEndpoint, HttpRule httpRule, MethodDescriptor methodDescriptor, string pattern, string verb)
        {
            var apiDescription = new ApiDescription();

            apiDescription.HttpMethod       = verb;
            apiDescription.ActionDescriptor = new ActionDescriptor
            {
                RouteValues = new Dictionary <string, string?>
                {
                    // Swagger uses this to group endpoints together.
                    // Group methods together using the service name.
                    ["controller"] = methodDescriptor.Service.FullName
                },
                EndpointMetadata = routeEndpoint.Metadata.ToList()
            };
            apiDescription.RelativePath = pattern.TrimStart('/');
            apiDescription.SupportedRequestFormats.Add(new ApiRequestFormat {
                MediaType = "application/json"
            });
            apiDescription.SupportedResponseTypes.Add(new ApiResponseType
            {
                ApiResponseFormats = { new ApiResponseFormat {
                                           MediaType = "application/json"
                                       } },
                ModelMetadata = new GrpcModelMetadata(ModelMetadataIdentity.ForType(methodDescriptor.OutputType.ClrType)),
                StatusCode    = 200
            });
            var explorerSettings = routeEndpoint.Metadata.GetMetadata <ApiExplorerSettingsAttribute>();

            if (explorerSettings != null)
            {
                apiDescription.GroupName = explorerSettings.GroupName;
            }

            var methodMetadata  = routeEndpoint.Metadata.GetMetadata <GrpcMethodMetadata>() !;
            var routeParameters = ServiceDescriptorHelpers.ResolveRouteParameterDescriptors(routeEndpoint.RoutePattern, methodDescriptor.InputType);

            foreach (var routeParameter in routeParameters)
            {
                var field         = routeParameter.Value.Last();
                var parameterName = ServiceDescriptorHelpers.FormatUnderscoreName(field.Name, pascalCase: true, preservePeriod: false);
                var propertyInfo  = field.ContainingType.ClrType.GetProperty(parameterName);

                // If from a property, create model as property to get its XML comments.
                var identity = propertyInfo != null
                    ? ModelMetadataIdentity.ForProperty(propertyInfo, MessageDescriptorHelpers.ResolveFieldType(field), field.ContainingType.ClrType)
                    : ModelMetadataIdentity.ForType(MessageDescriptorHelpers.ResolveFieldType(field));

                apiDescription.ParameterDescriptions.Add(new ApiParameterDescription
                {
                    Name          = routeParameter.Key,
                    ModelMetadata = new GrpcModelMetadata(identity),
                    Source        = BindingSource.Path,
                    DefaultValue  = string.Empty
                });
            }

            var bodyDescriptor = ServiceDescriptorHelpers.ResolveBodyDescriptor(httpRule.Body, methodMetadata.ServiceType, methodDescriptor);

            if (bodyDescriptor != null)
            {
                // If from a property, create model as property to get its XML comments.
                var identity = bodyDescriptor.PropertyInfo != null
                    ? ModelMetadataIdentity.ForProperty(bodyDescriptor.PropertyInfo, bodyDescriptor.Descriptor.ClrType, bodyDescriptor.PropertyInfo.DeclaringType !)
                    : ModelMetadataIdentity.ForType(bodyDescriptor.Descriptor.ClrType);

                // Or if from a parameter, create model as parameter to get its XML comments.
                var parameterDescriptor = bodyDescriptor.ParameterInfo != null
                    ? new ControllerParameterDescriptor {
                    ParameterInfo = bodyDescriptor.ParameterInfo
                }
                    : null;

                apiDescription.ParameterDescriptions.Add(new ApiParameterDescription
                {
                    Name                = "Input",
                    ModelMetadata       = new GrpcModelMetadata(identity),
                    Source              = BindingSource.Body,
                    ParameterDescriptor = parameterDescriptor !
                });
        public static string GetResourceKeyName(this ResourceManager resourceManager, ModelMetadataIdentity metadataIdentity, string resourceKeySuffix)
        {
            if (resourceManager == null)
            {
                throw new ArgumentNullException(nameof(resourceManager));
            }
            if (string.IsNullOrEmpty(metadataIdentity.Name))
            {
                return(null);
            }

            var fullPropertyName = !string.IsNullOrEmpty(metadataIdentity.ContainerType?.FullName)
                ? metadataIdentity.ContainerType.FullName + "." + metadataIdentity.Name
                : metadataIdentity.Name;

            if (string.IsNullOrWhiteSpace(resourceKeySuffix))
            {
                resourceKeySuffix = string.Empty;
            }
            else
            {
                resourceKeySuffix = "_" + resourceKeySuffix;
            }

            // Search by name from more specific to less specific
            var resourceKeyName = fullPropertyName.Replace('.', '_').Replace('+', '_');
            var namePartsCount  = resourceKeyName.Length - resourceKeyName.Replace("_", string.Empty).Length + 1;

            resourceKeyName += resourceKeySuffix;

            for (var i = 0; i < namePartsCount; i++)
            {
                // Get the resource key to lookup
                if (i > 0)
                {
                    resourceKeyName = resourceKeyName.Substring(resourceKeyName.IndexOf("_") + 1);
                }

                // Check if given value exists in resource
                if (resourceManager.GetString(resourceKeyName) != null)
                {
                    return(resourceKeyName);
                }
            }

            // Not found
            return(null);
        }
 public FakeModelMetadata(ModelMetadataIdentity identity) : base(identity)
 {
 }
 public ModelMetadata GetMetadataForType(Type modelType)
 {
     return(new FakeModelMetadata(ModelMetadataIdentity.ForType(typeof(string))));
 }
Beispiel #15
0
 public EntityMetadataDetails(ModelMetadataIdentity key, ModelAttributes attributes) : base(key, attributes)
 {
 }
            protected override DefaultMetadataDetails CreateTypeDetails(ModelMetadataIdentity key)
            {
                var entry = base.CreateTypeDetails(key);
                if (_attributes?.Length > 0)
                {
                    return new DefaultMetadataDetails(
                        key,
                        new ModelAttributes(_attributes.Concat(entry.ModelAttributes.TypeAttributes).ToArray()));
                }

                return entry;
            }
Beispiel #17
0
 /// <summary>
 /// Creates a new <see cref="ModelMetadata"/>.
 /// </summary>
 /// <param name="identity">The <see cref="ModelMetadataIdentity"/>.</param>
 protected ModelMetadata(ModelMetadataIdentity identity)
 {
     Identity = identity;
 }
 public RequestTypeMetadata(Type type, IEnumerable <ParameterMetadata> parameters) : base(ModelMetadataIdentity.ForType(type))
 {
     this.parameters = parameters;
 }
Beispiel #19
0
        protected override DefaultMetadataDetails[] CreatePropertyDetails(ModelMetadataIdentity key)
        {
            // Call the base implementation
            var propsDetails = base.CreatePropertyDetails(key);

            // Customize the label of Resource properties
            if (key.ModelType.IsSameOrSubClassOf <ResourceForSave>())
            {
                // Get the route data from http context
                // Loop over the properties and special treatment to the dynamic ones
                foreach (var propDetails in propsDetails)
                {
                    var defaultName = propDetails.ModelAttributes.PropertyAttributes
                                      .OfType <DisplayAttribute>().FirstOrDefault()?.Name ?? propDetails.Key.Name;

                    DisplayMetadata displayMetadata;

                    switch (propDetails.Key.Name)
                    {
                    case nameof(Resource.Identifier):
                        displayMetadata = LocalizeResourceProperty(
                            e => e.IdentifierVisibility, e => e.IdentifierLabel, e => e.IdentifierLabel2, e => e.IdentifierLabel3, defaultName);
                        break;

                    // All dynamically labelled properties
                    case nameof(Resource.Currency):
                    case nameof(Resource.CurrencyId):
                        displayMetadata = LocalizeResourceProperty(
                            e => e.CurrencyVisibility, e => e.CurrencyLabel, e => e.CurrencyLabel2, e => e.CurrencyLabel3, defaultName);
                        break;

                    case nameof(Resource.MonetaryValue):
                        displayMetadata = LocalizeResourceProperty(
                            e => e.MonetaryValueVisibility, e => e.MonetaryValueLabel, e => e.MonetaryValueLabel2, e => e.MonetaryValueLabel3, defaultName);
                        break;

                    case nameof(Resource.CountUnit):
                    case nameof(Resource.CountUnitId):
                        displayMetadata = LocalizeResourceProperty(
                            e => e.CountUnitVisibility, e => e.CountUnitLabel, e => e.CountUnitLabel2, e => e.CountUnitLabel3, defaultName);
                        break;

                    case nameof(Resource.Count):
                        displayMetadata = LocalizeResourceProperty(
                            e => e.CountVisibility, e => e.CountLabel, e => e.CountLabel2, e => e.CountLabel3, defaultName);
                        break;

                    case nameof(Resource.MassUnit):
                    case nameof(Resource.MassUnitId):
                        displayMetadata = LocalizeResourceProperty(
                            e => e.MassUnitVisibility, e => e.MassUnitLabel, e => e.MassUnitLabel2, e => e.MassUnitLabel3, defaultName);
                        break;

                    case nameof(Resource.Mass):
                        displayMetadata = LocalizeResourceProperty(
                            e => e.MassVisibility, e => e.MassLabel, e => e.MassLabel2, e => e.MassLabel3, defaultName);
                        break;

                    case nameof(Resource.VolumeUnit):
                    case nameof(Resource.VolumeUnitId):
                        displayMetadata = LocalizeResourceProperty(
                            e => e.VolumeUnitVisibility, e => e.VolumeUnitLabel, e => e.VolumeUnitLabel2, e => e.VolumeUnitLabel3, defaultName);
                        break;

                    case nameof(Resource.Volume):
                        displayMetadata = LocalizeResourceProperty(
                            e => e.VolumeVisibility, e => e.VolumeLabel, e => e.VolumeLabel2, e => e.VolumeLabel3, defaultName);
                        break;

                    case nameof(Resource.TimeUnit):
                    case nameof(Resource.TimeUnitId):
                        displayMetadata = LocalizeResourceProperty
                                              (e => e.TimeUnitVisibility, e => e.TimeUnitLabel, e => e.TimeUnitLabel2, e => e.TimeUnitLabel3, defaultName);
                        break;

                    case nameof(Resource.Time):
                        displayMetadata = LocalizeResourceProperty(
                            e => e.TimeVisibility, e => e.TimeLabel, e => e.TimeLabel2, e => e.TimeLabel3, defaultName);
                        break;

                    case nameof(Resource.AvailableSince):
                        displayMetadata = LocalizeResourceProperty(
                            e => e.AvailableSinceVisibility, e => e.AvailableSinceLabel, e => e.AvailableSinceLabel2, e => e.AvailableSinceLabel3, defaultName);
                        break;

                    case nameof(Resource.AvailableTill):
                        displayMetadata = LocalizeResourceProperty(
                            e => e.AvailableTillVisibility, e => e.AvailableTillLabel, e => e.AvailableTillLabel2, e => e.AvailableTillLabel3, defaultName);
                        break;

                    case nameof(Resource.Lookup1):
                    case nameof(Resource.Lookup1Id):
                        displayMetadata = LocalizeResourceProperty(
                            e => e.Lookup1Visibility, e => e.Lookup1Label, e => e.Lookup1Label2, e => e.Lookup1Label3, defaultName);
                        break;

                    case nameof(Resource.Lookup2):
                    case nameof(Resource.Lookup2Id):
                        displayMetadata = LocalizeResourceProperty(
                            e => e.Lookup2Visibility, e => e.Lookup2Label, e => e.Lookup2Label2, e => e.Lookup2Label3, defaultName);
                        break;

                    //case nameof(Resource.Lookup3):
                    //case nameof(Resource.Lookup3Id):
                    //    displayMetadata = LocalizeResourceProperty(e => e.Lookup3Visibility, e => e.Lookup3Label, e => e.Lookup3Label2, e => e.Lookup3Label3, defaultName);
                    //    break;

                    //case nameof(Resource.Lookup4):
                    //case nameof(Resource.Lookup4Id):
                    //    displayMetadata = LocalizeResourceProperty(e => e.Lookup4Visibility, e => e.Lookup4Label, e => e.Lookup4Label2, e => e.Lookup4Label3, defaultName);
                    //    break;

                    //case nameof(Resource.Lookup5):
                    //case nameof(Resource.Lookup5Id):
                    //    displayMetadata = LocalizeResourceProperty(e => e.Lookup5Visibility, e => e.Lookup5Label, e => e.Lookup5Label2, e => e.Lookup5Label3, defaultName);
                    //    break;

                    default:
                        displayMetadata = null;
                        break;
                    }

                    propDetails.DisplayMetadata = displayMetadata;
                }
            }

            // Customize the label of Agent properties
            if (key.ModelType.IsSameOrSubClassOf <AgentForSave>())
            {
                // Get the route data from http context
                // Loop over the properties and special treatment to the dynamic ones
                foreach (var propDetails in propsDetails)
                {
                    var defaultName = propDetails.ModelAttributes.PropertyAttributes
                                      .OfType <DisplayAttribute>().FirstOrDefault()?.Name ?? propDetails.Key.Name;
                    var displayMetadata = propDetails.Key.Name switch
                    {
                        // All dynamically labelled properties
                        nameof(Agent.TaxIdentificationNumber) => LocalizeAgentSpecificProperty(e => e.TaxIdentificationNumberVisibility, defaultName),
                        nameof(Agent.StartDate) => LocalizeAgentProperty(e => e.StartDateVisibility, e => e.StartDateLabel, e => e.StartDateLabel2, e => e.StartDateLabel3, defaultName),
                        nameof(Agent.JobId) => LocalizeAgentSpecificProperty(e => e.JobVisibility, defaultName),//  case nameof(Agent.Job): TODO
                        nameof(Agent.BasicSalary) => LocalizeAgentSpecificProperty(e => e.BasicSalaryVisibility, defaultName),
                        nameof(Agent.TransportationAllowance) => LocalizeAgentSpecificProperty(e => e.TransportationAllowanceVisibility, defaultName),
                        nameof(Agent.OvertimeRate) => LocalizeAgentSpecificProperty(e => e.OvertimeRateVisibility, defaultName),
                        nameof(Agent.BankAccountNumber) => LocalizeAgentSpecificProperty(e => e.BankAccountNumberVisibility, defaultName),
                        _ => null,
                    };
                    propDetails.DisplayMetadata = displayMetadata;
                }
            }

            // In general: append the language name to the labels of multilingual
            foreach (var propDetails in propsDetails)
            {
                var att = propDetails.ModelAttributes.PropertyAttributes
                          .OfType <MultilingualDisplayAttribute>().FirstOrDefault();

                if (att != null)
                {
                    var name = att.Name ?? "";
                    var lang = att.Language;

                    propDetails.DisplayMetadata = new DisplayMetadata
                    {
                        DisplayName = () =>
                        {
                            var info = _tenantInfoAccessor.GetCurrentInfo();
                            if (info == null)
                            {
                                // Developer mistake
                                throw new InvalidOperationException("TenantInfo is not set");
                            }

                            var result = lang switch
                            {
                                Language.Primary => _localizer[name] + PrimaryPostfix(info),
                                Language.Secondary => string.IsNullOrWhiteSpace(info.SecondaryLanguageId) ? Constants.HIDDEN_FIELD : _localizer[name] + SecondaryPostfix(info),
                                Language.Ternary => string.IsNullOrWhiteSpace(info.TernaryLanguageId) ? Constants.HIDDEN_FIELD : _localizer[name] + TernaryPostfix(info),
                                _ => _localizer[name],
                            };
                            ;

                            return(result);
                        }
                    };
                }
            }

            return(propsDetails);
        }

        DisplayMetadata LocalizeResourceProperty(
            Func <ResourceDefinitionForClient, string> visibilityFunc,
            Func <ResourceDefinitionForClient, string> s1Func,
            Func <ResourceDefinitionForClient, string> s2Func,
            Func <ResourceDefinitionForClient, string> s3Func,
            string defaultDisplayName)
        {
            return(LocalizeProperty(
                       (tenantId, definitionId) => _definitionsCache.GetDefinitionsIfCached(tenantId)?.Data?.Resources?.GetValueOrDefault(definitionId),
                       visibilityFunc, s1Func, s2Func, s3Func, defaultDisplayName));
        }

        DisplayMetadata LocalizeAgentProperty(
            Func <AgentDefinitionForClient, string> visibilityFunc,
            Func <AgentDefinitionForClient, string> s1Func,
            Func <AgentDefinitionForClient, string> s2Func,
            Func <AgentDefinitionForClient, string> s3Func,
            string defaultDisplayName)
        {
            return(LocalizeProperty(
                       (tenantId, definitionId) => _definitionsCache.GetDefinitionsIfCached(tenantId)?.Data?.Agents?.GetValueOrDefault(definitionId),
                       visibilityFunc, s1Func, s2Func, s3Func, defaultDisplayName));
        }

        DisplayMetadata LocalizeAgentSpecificProperty(
            Func <AgentDefinitionForClient, string> visibilityFunc,
            string defaultDisplayName)
        {
            return(LocalizeProperty(
                       (tenantId, definitionId) => _definitionsCache.GetDefinitionsIfCached(tenantId)?.Data?.Agents?.GetValueOrDefault(definitionId),
                       visibilityFunc, e => null, e => null, e => null, defaultDisplayName));
        }

        DisplayMetadata LocalizeProperty <TDefinitionForClient>(
            Func <int, string, TDefinitionForClient> definitionFunc,
            Func <TDefinitionForClient, string> visibilityFunc,
            Func <TDefinitionForClient, string> s1Func,
            Func <TDefinitionForClient, string> s2Func,
            Func <TDefinitionForClient, string> s3Func,
            string defaultDisplayName)
        {
            return(new DisplayMetadata
            {
                // Return a dynamic display name from the definitions, and fall back to
                // the default if non are available. Be as forgiving as possible
                DisplayName = () =>
                {
                    string result = _localizer[defaultDisplayName];
                    var routeData = _httpContextAccessor.HttpContext.GetRouteData();
                    var definitionId = routeData.Values["definitionId"]?.ToString();

                    if (!string.IsNullOrWhiteSpace(definitionId))
                    {
                        var tenantId = _tenantIdAccessor.GetTenantId();
                        var definition = definitionFunc(tenantId, definitionId);

                        if (definition != null)
                        {
                            if (visibilityFunc(definition) == null)
                            {
                                result = Constants.HIDDEN_FIELD;
                            }
                            else
                            {
                                result = _tenantInfoAccessor.GetCurrentInfo().Localize(
                                    s1Func(definition),
                                    s2Func(definition),
                                    s3Func(definition)) ?? result;
                            }
                        }
                    }

                    return result;
                }
            });
        }
 public JqGridMetadataProviderContext(
     ModelMetadataIdentity key,
     ModelAttributes attributes) : base(key, attributes)
 {
     JqGridMetadata = new JqGridMetadata();
 }
            public void Should_update_ErrorMessageResource_only_when_needed()
            {
                // Arrange
                var key = new ModelMetadataIdentity();
                var myAttributeNotToUpdate = new MyValidationAttribute
                {
                    ErrorMessage = "Some message"
                };
                var myAttributeToUpdate             = new MyValidationAttribute();
                var someOtherNonValidationAttribute = new MyNonValidationAttribute();

                var attributes = new ModelAttributes(new object[] {
                    myAttributeNotToUpdate,
                    myAttributeToUpdate,
                    someOtherNonValidationAttribute
                });
                var context = new ValidationMetadataProviderContext(key, attributes);
                var expectedErrorMessageResourceName = "SomeResourceName";

                MyMockAdapter
                .Setup(x => x.CanHandle(myAttributeNotToUpdate))
                .Returns(true)
                .Verifiable();
                MyMockAdapter
                .Setup(x => x.GetErrorMessageResourceName(myAttributeNotToUpdate))
                .Returns("Whatever")
                .Verifiable();

                MyMockAdapter
                .Setup(x => x.CanHandle(myAttributeToUpdate))
                .Returns(true);
                MyMockAdapter
                .Setup(x => x.GetErrorMessageResourceName(myAttributeToUpdate))
                .Returns(expectedErrorMessageResourceName)
                .Verifiable();


                // Act
                ProvierUnderTest.CreateValidationMetadata(context);

                // Assert
                Assert.Null(myAttributeNotToUpdate.ErrorMessageResourceName);
                Assert.Null(myAttributeNotToUpdate.ErrorMessageResourceType);
                Assert.Equal("Some message", myAttributeNotToUpdate.ErrorMessage);
                MyMockAdapter.Verify(
                    x => x.CanHandle(myAttributeNotToUpdate),
                    Times.Never
                    );
                MyMockAdapter.Verify(
                    x => x.GetErrorMessageResourceName(myAttributeNotToUpdate),
                    Times.Never
                    );

                Assert.Equal(
                    expectedErrorMessageResourceName,
                    myAttributeToUpdate.ErrorMessageResourceName
                    );
                Assert.Equal(
                    ProvierUnderTest.ErrorMessageResourceType,
                    myAttributeToUpdate.ErrorMessageResourceType
                    );
                MyMockAdapter.Verify(
                    x => x.CanHandle(myAttributeToUpdate),
                    Times.Once
                    );
                MyMockAdapter.Verify(
                    x => x.GetErrorMessageResourceName(myAttributeToUpdate),
                    Times.Once
                    );
            }
Beispiel #22
0
 public EndpointModelMetadata(ModelMetadataIdentity identity) : base(identity)
 {
     IsBindingAllowed = true;
 }
 public JqGridColumnModelMetadata(Type modelType, string name, Type containerType)
     : base(ModelMetadataIdentity.ForProperty(modelType, name, containerType))
 {
 }
        private static ApiDescription CreateApiDescription(RouteEndpoint routeEndpoint, HttpRule httpRule,
                                                           MethodDescriptor methodDescriptor, string pattern, string verb)
        {
            var apiDescription = new ApiDescription();

            apiDescription.HttpMethod       = verb;
            apiDescription.ActionDescriptor = new ActionDescriptor
            {
                RouteValues = new Dictionary <string, string>
                {
                    // Swagger uses this to group endpoints together.
                    // Group methods together using the service name.
                    ["controller"] = methodDescriptor.Service.FullName
                }
            };
            apiDescription.RelativePath = pattern.TrimStart('/');
            apiDescription.SupportedRequestFormats.Add(new ApiRequestFormat {
                MediaType = "application/json"
            });
            apiDescription.SupportedResponseTypes.Add(new ApiResponseType
            {
                ApiResponseFormats = { new ApiResponseFormat {
                                           MediaType = "application/json"
                                       } },
                ModelMetadata =
                    new GRpcModelMetadata(ModelMetadataIdentity.ForType(methodDescriptor.OutputType.ClrType)),
                StatusCode = 200
            });

            var routeParameters =
                ServiceDescriptorHelpers.ResolveRouteParameterDescriptors(routeEndpoint.RoutePattern,
                                                                          methodDescriptor.InputType);

            foreach (var routeParameter in routeParameters)
            {
                var field = routeParameter.Value.Last();

                apiDescription.ParameterDescriptions.Add(new ApiParameterDescription
                {
                    Name          = routeParameter.Key,
                    ModelMetadata =
                        new GRpcModelMetadata(
                            ModelMetadataIdentity.ForType(MessageDescriptorHelpers.ResolveFieldType(field))),
                    Source       = BindingSource.Path,
                    DefaultValue = string.Empty
                });
            }

            ServiceDescriptorHelpers.ResolveBodyDescriptor(httpRule.Body, methodDescriptor, out var bodyDescriptor,
                                                           out _, out _);
            if (bodyDescriptor != null)
            {
                apiDescription.ParameterDescriptions.Add(new ApiParameterDescription
                {
                    Name          = "Input",
                    ModelMetadata = new GRpcModelMetadata(ModelMetadataIdentity.ForType(bodyDescriptor.ClrType)),
                    Source        = BindingSource.Body
                });
            }

            return(apiDescription);
        }
Beispiel #25
0
 /// <summary>
 /// Creates a new <see cref="ModelMetadata"/>.
 /// </summary>
 /// <param name="identity">The <see cref="ModelMetadataIdentity"/>.</param>
 protected ModelMetadata([NotNull] ModelMetadataIdentity identity)
 {
     Identity = identity;
 }
 public GRpcModelMetadata(ModelMetadataIdentity identity) : base(identity)
 {
     IsBindingAllowed = true;
 }
        public async Task UploadStudentWithoutParentId_Returns_StudentWithNullParentId()
        {
            var multipartFormDataFormatter = new MultipartFormDataFormatter();
            var formFileCollection         = new FormFileCollection();

            var models = new Dictionary <string, StringValues>();

            var formCollection  = new FormCollection(models, formFileCollection);
            var httpContextMock = new Mock <HttpContext>();
            var httpRequestMock = new Mock <HttpRequest>();

            httpRequestMock.Setup(x => x.Form)
            .Returns(formCollection);

            httpRequestMock.Setup(x => x.ReadFormAsync(It.IsAny <CancellationToken>()))
            .ReturnsAsync(formCollection);

            httpContextMock.SetupGet(x => x.Request)
            .Returns(httpRequestMock.Object);

            var inputFormatter = new InputFormatterContext(httpContextMock.Object, string.Empty,
                                                           new ModelStateDictionary(), new EmptyModelMetaData(ModelMetadataIdentity.ForType(typeof(StudentViewModel))),
                                                           (stream, encoding) => TextReader.Null);

            var handledResult = await multipartFormDataFormatter
                                .ReadRequestBodyAsync(inputFormatter);

            Assert.IsInstanceOf <InputFormatterResult>(handledResult);

            var student = handledResult.Model as StudentViewModel;

            Assert.NotNull(student);
            Assert.IsNull(student.ParentId);
        }
        private static async Task <InputFormatterResult> ReadRequestBody(string sampleJson, ModelStateDictionary modelStateDictionary)
        {
            var formatter = new FhirJsonInputFormatter(new FhirJsonParser(), ArrayPool <char> .Shared);

            var metaData = new DefaultModelMetadata(new EmptyModelMetadataProvider(), new DefaultCompositeMetadataDetailsProvider(new IMetadataDetailsProvider[0]), new DefaultMetadataDetails(ModelMetadataIdentity.ForType(typeof(Observation)), ModelAttributes.GetAttributesForType(typeof(Observation))));
            var context  = new InputFormatterContext(
                new DefaultHttpContext(),
                KnownActionParameterNames.Resource,
                modelStateDictionary,
                metaData,
                (stream, encoding) => new StreamReader(new MemoryStream(encoding.GetBytes(sampleJson))));

            return(await formatter.ReadRequestBodyAsync(context));
        }
        public async Task UploadIdIntoProfile_Returns_StudentProfileWithId()
        {
            var multipartFormDataFormatter = new MultipartFormDataFormatter();
            var formFileCollection         = new FormFileCollection();

            var id = Guid.NewGuid().ToString("D");

            var models = new Dictionary <string, StringValues>();

            models.Add($"{nameof(StudentViewModel.Profile)}[{nameof(ProfileViewModel.Id)}]", id);

            var formCollection  = new FormCollection(models, formFileCollection);
            var httpContextMock = new Mock <HttpContext>();
            var httpRequestMock = new Mock <HttpRequest>();

            httpRequestMock.Setup(x => x.Form)
            .Returns(formCollection);

            httpRequestMock.Setup(x => x.ReadFormAsync(It.IsAny <CancellationToken>()))
            .ReturnsAsync(formCollection);

            httpContextMock.SetupGet(x => x.Request)
            .Returns(httpRequestMock.Object);

            var inputFormatter = new InputFormatterContext(httpContextMock.Object, string.Empty,
                                                           new ModelStateDictionary(), new EmptyModelMetaData(ModelMetadataIdentity.ForType(typeof(StudentViewModel))),
                                                           (stream, encoding) => TextReader.Null);

            var handledResult = await multipartFormDataFormatter
                                .ReadRequestBodyAsync(inputFormatter);

            Assert.IsInstanceOf <InputFormatterResult>(handledResult);

            var student = handledResult.Model as StudentViewModel;

            Assert.IsNotNull(student?.Profile);
            Assert.AreEqual(id, student.Profile.Id.ToString("D"));
        }
Beispiel #30
0
 public TestModelMetadata(Type modelType)
     : base(ModelMetadataIdentity.ForType(modelType))
 {
 }
Beispiel #31
0
 public TestModelMetadata(ParameterInfo parameter)
     : base(ModelMetadataIdentity.ForParameter(parameter))
 {
 }
Beispiel #32
0
 public TestModelMetadata(PropertyInfo propertyInfo, Type modelType, Type containerType)
     : base(ModelMetadataIdentity.ForProperty(propertyInfo, modelType, containerType))
 {
 }
 protected override DefaultMetadataDetails[] CreatePropertyDetails(ModelMetadataIdentity key)
 {
     var entries = base.CreatePropertyDetails(key);
     return entries.Select(e =>
     {
         return new DefaultMetadataDetails(
             e.Key,
             new ModelAttributes(_attributes.Concat(e.ModelAttributes.PropertyAttributes), e.ModelAttributes.TypeAttributes));
     })
     .ToArray();
 }
Beispiel #34
0
 public TestModelMetadata(Type modelType, string propertyName, Type containerType)
     : base(ModelMetadataIdentity.ForProperty(modelType, propertyName, containerType))
 {
 }