public void AddValidation_DoesNotTrounceExistingAttributes() { // Arrange var provider = TestModelMetadataProvider.CreateDefaultProvider(); var metadata = provider.GetMetadataForProperty(typeof(Profile), "PhotoFileName"); var attribute = new FileExtensionsAttribute() { Extensions = "jpg" }; attribute.ErrorMessage = "{0} expects only the following extensions: {1}"; var adapter = new FileExtensionsAttributeAdapter(attribute, stringLocalizer: null); var context = new ClientModelValidationContext(new ActionContext(), metadata, provider, new Dictionary <string, string>()); context.Attributes.Add("data-val", "original"); context.Attributes.Add("data-val-fileextensions", "original"); context.Attributes.Add("data-val-fileextensions-extensions", "original"); // Act adapter.AddValidation(context); // Assert Assert.Collection( context.Attributes, kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("original", kvp.Value); }, kvp => { Assert.Equal("data-val-fileextensions", kvp.Key); Assert.Equal("original", kvp.Value); }, kvp => { Assert.Equal("data-val-fileextensions-extensions", kvp.Key); Assert.Equal("original", kvp.Value); }); }
public void ClientRule() { // Arrange var attribute = new FileExtensionsAttribute { Extensions = " FoO, .bar,baz " }; var provider = new Mock <ModelMetadataProvider>(); var metadata = new ModelMetadata( provider.Object, null, null, typeof(string), "PropertyName" ); // Act ModelClientValidationRule clientRule = attribute .GetClientValidationRules(metadata, null) .Single(); // Assert Assert.Equal("extension", clientRule.ValidationType); Assert.Equal( "The PropertyName field only accepts files with the following extensions: .foo, .bar, .baz", clientRule.ErrorMessage ); Assert.Single(clientRule.ValidationParameters); Assert.Equal("foo,bar,baz", clientRule.ValidationParameters["extension"]); }
public void AddValidation_WithoutLocalizationAndCustomFileExtensions(string extensions, string expectedExtensions) { // Arrange var provider = TestModelMetadataProvider.CreateDefaultProvider(); var metadata = provider.GetMetadataForProperty(typeof(Profile), nameof(Profile.PhotoFileName)); var attribute = new FileExtensionsAttribute() { Extensions = extensions }; attribute.ErrorMessage = "{0} expects only the following extensions: {1}"; // FileExtensionsAttribute formats the extension list for the error message var formattedExtensions = string.Join(", ", expectedExtensions.Split(',')); var expectedErrorMessage = string.Format(attribute.ErrorMessage, nameof(Profile.PhotoFileName), formattedExtensions); var adapter = new FileExtensionsAttributeAdapter(attribute, stringLocalizer: null); var context = new ClientModelValidationContext(new ActionContext(), metadata, provider, new Dictionary <string, string>()); // Act adapter.AddValidation(context); // Assert Assert.Collection( context.Attributes, kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("true", kvp.Value); }, kvp => { Assert.Equal("data-val-fileextensions", kvp.Key); Assert.Equal(expectedErrorMessage, kvp.Value); }, kvp => { Assert.Equal("data-val-fileextensions-extensions", kvp.Key); Assert.Equal(expectedExtensions, kvp.Value); }); }
public static void Extensions_Get_Set(string newValue, string expected) { var attribute = new FileExtensionsAttribute(); attribute.Extensions = newValue; Assert.Equal(expected, attribute.Extensions); }
public static void Ctor() { var attribute = new FileExtensionsAttribute(); Assert.Equal(DataType.Upload, attribute.DataType); Assert.Null(attribute.CustomDataType); Assert.Equal("png,jpg,jpeg,gif", attribute.Extensions); }
public FileUploadExtensionsAttribute() : base(DataType.Upload) { ErrorMessage = new FileExtensionsAttribute() { Extensions = this.Extensions }.ErrorMessage; }
public static void Ctor() { var attribute = new FileExtensionsAttribute(); Assert.Equal(DataType.Upload, attribute.DataType); Assert.Null(attribute.CustomDataType); Assert.Equal("png,jpg,jpeg,gif", attribute.Extensions); }
public void ErrorMessageTest() { var attribute = new FileExtensionsAttribute(); attribute.ErrorMessage = "SampleErrorMessage"; const string invalidValue = "a"; var result = attribute.GetValidationResult(invalidValue, new ValidationContext(0, null, null)); Assert.AreEqual("SampleErrorMessage", result.ErrorMessage); }
public void ErrorResourcesTest() { var attribute = new FileExtensionsAttribute(); attribute.ErrorMessageResourceName = "ErrorMessage"; attribute.ErrorMessageResourceType = typeof(ErrorResources); const string invalidValue = "a"; var result = attribute.GetValidationResult(invalidValue, new ValidationContext(0, null, null)); Assert.AreEqual(ErrorResources.ErrorMessage, result.ErrorMessage); }
public void GlobalizedErrorResourcesTest() { System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("es-MX"); var attribute = new FileExtensionsAttribute(); attribute.ErrorMessageResourceName = "ErrorMessage"; attribute.ErrorMessageResourceType = typeof(ErrorResources); const string invalidValue = "a"; var result = attribute.GetValidationResult(invalidValue, new ValidationContext(0, null, null)); Assert.AreEqual("mensaje de error", result.ErrorMessage); }
public void IsValidWithNoArgumentTests() { var attribute = new FileExtensionsAttribute(); Assert.IsTrue(attribute.IsValid(null)); // Optional values are always valid Assert.IsTrue(attribute.IsValid("foo.png")); Assert.IsTrue(attribute.IsValid("foo.jpeg")); Assert.IsTrue(attribute.IsValid("foo.jpg")); Assert.IsTrue(attribute.IsValid("foo.gif")); Assert.IsTrue(attribute.IsValid(@"C:\Foo\bar.png")); Assert.IsFalse(attribute.IsValid("foo")); Assert.IsFalse(attribute.IsValid("foo.doc")); Assert.IsFalse(attribute.IsValid("foo.txt")); Assert.IsFalse(attribute.IsValid("foo.png.txt")); }
public void IsValidWithCustomArgumentsTests() { var attribute = new FileExtensionsAttribute("pdf|doc|docx|rtf"); Assert.IsTrue(attribute.IsValid(null)); // Optional values are always valid Assert.IsTrue(attribute.IsValid("foo.pdf")); Assert.IsTrue(attribute.IsValid("foo.doc")); Assert.IsTrue(attribute.IsValid("foo.docx")); Assert.IsTrue(attribute.IsValid("foo.rtf")); Assert.IsTrue(attribute.IsValid(@"C:\Foo\bar.pdf")); Assert.IsFalse(attribute.IsValid("foo")); Assert.IsFalse(attribute.IsValid("foo.png")); Assert.IsFalse(attribute.IsValid("foo.jpeg")); Assert.IsFalse(attribute.IsValid("foo.doc.txt")); }
public void ClientRule() { // Arrange var attribute = new FileExtensionsAttribute { Extensions = " FoO, .bar,baz " }; var provider = new Mock<ModelMetadataProvider>(); var metadata = new ModelMetadata(provider.Object, null, null, typeof(string), "PropertyName"); // Act ModelClientValidationRule clientRule = attribute.GetClientValidationRules(metadata, null).Single(); // Assert Assert.AreEqual("accept", clientRule.ValidationType); Assert.AreEqual("The PropertyName field only accepts files with the following extensions: .foo, .bar, .baz", clientRule.ErrorMessage); Assert.AreEqual(1, clientRule.ValidationParameters.Count); Assert.AreEqual("foo,bar,baz", clientRule.ValidationParameters["exts"]); }
public void IsValidTests() { // Arrange var attribute = new FileExtensionsAttribute(); // Act & Assert Assert.IsTrue(attribute.IsValid(null)); // Optional values are always valid Assert.IsTrue(attribute.IsValid("foo.png")); Assert.IsTrue(attribute.IsValid("foo.jpeg")); Assert.IsTrue(attribute.IsValid("foo.jpg")); Assert.IsTrue(attribute.IsValid("foo.gif")); Assert.IsTrue(attribute.IsValid(@"C:\Foo\bar.jpg")); Assert.IsFalse(attribute.IsValid("foo")); Assert.IsFalse(attribute.IsValid("foo.png.pif")); Assert.IsFalse(attribute.IsValid(@"C:\foo.png\bar")); Assert.IsFalse(attribute.IsValid("\0foo.png")); // Illegal character }
public void IsValid() { var sla = new FileExtensionsAttribute() { Extensions = "txt,jpg" }; Assert.IsTrue(sla.IsValid(null), "#A1-1"); Assert.IsFalse(sla.IsValid(String.Empty), "#A1-2"); Assert.IsFalse(sla.IsValid("string"), "#A1-3"); Assert.IsTrue(sla.IsValid("file.txt"), "#A1-4"); Assert.IsTrue(sla.IsValid("file.jpg"), "#A1-5"); Assert.IsTrue(sla.IsValid("file.xxx.txt"), "#A-6"); Assert.IsFalse(sla.IsValid(true), "#A1-7"); Assert.IsFalse(sla.IsValid(DateTime.Now), "#A1-8"); }
public void IsValidTests() { // Arrange var attribute = new FileExtensionsAttribute(); // Act & Assert Assert.True(attribute.IsValid(null)); // Optional values are always valid Assert.True(attribute.IsValid("foo.png")); Assert.True(attribute.IsValid("foo.jpeg")); Assert.True(attribute.IsValid("foo.jpg")); Assert.True(attribute.IsValid("foo.gif")); Assert.True(attribute.IsValid(@"C:\Foo\baz.jpg")); Assert.False(attribute.IsValid("foo")); Assert.False(attribute.IsValid("foo.png.pif")); Assert.False(attribute.IsValid(@"C:\foo.png\bar")); Assert.False(attribute.IsValid("\0foo.png")); // Illegal character }
public void AddValidation_adds_ext_rule(string extensions) { // Arrange var attribute = new FileExtensionsAttribute { Extensions = extensions }; var adapter = new FileExtensionsAttributeAdapter(attribute); var context = new ClientModelValidationContextBuilder() .WithModelType <string>() .Build(); // Act adapter.AddValidation(context); // Assert context.Attributes.Keys.ShouldContain("v-validate"); context.Attributes["v-validate"].ShouldBe("{ext:['pdf','png','zip']}"); }
public void GetClientValidationRules_ReturnsEmptyRuleSet() { // Arrange var attribute = new FileExtensionsAttribute(); var validator = new DataAnnotationsModelValidator <FileExtensionsAttribute>(attribute); var metadata = _metadataProvider.GetMetadataForProperty( containerType: typeof(string), propertyName: nameof(string.Length)); var serviceCollection = new ServiceCollection(); var requestServices = serviceCollection.BuildServiceProvider(); var context = new ClientModelValidationContext(metadata, _metadataProvider, requestServices); // Act var results = validator.GetClientValidationRules(context); // Assert Assert.Empty(results); }
public static FileExtensionsAttribute CreateFileExtensionsAttribute(this XElement annotation) { const string NAME = "FileExtensions"; string name = annotation.Attribute(SchemaVocab.Name).Value; if (name != NAME) { throw new ArgumentException(string.Format(SchemaMessages.ExpectedBut, NAME, name)); } FileExtensionsAttribute attribute = new FileExtensionsAttribute(); string extensions = annotation.GetArgumentValue("Extensions"); if (extensions != null) { attribute.Extensions = extensions; } FillValidationAttribute(attribute, annotation); return(attribute); }
public void AddValidation_WithLocalization(string extensions, string expectedExtensions) { // Arrange var provider = TestModelMetadataProvider.CreateDefaultProvider(); var metadata = provider.GetMetadataForProperty(typeof(Profile), nameof(Profile.PhotoFileName)); var attribute = new FileExtensionsAttribute() { Extensions = extensions }; attribute.ErrorMessage = "{0} expects only the following extensions: {1}"; var formattedExtensions = string.Join(", ", expectedExtensions.Split(',')); var expectedProperties = new object[] { "PhotoFileName", formattedExtensions }; var expectedErrorMessage = $"{nameof(Profile.PhotoFileName)} expects only the following extensions: {formattedExtensions}"; var stringLocalizer = new Mock <IStringLocalizer>(); stringLocalizer .Setup(s => s[attribute.ErrorMessage, expectedProperties]) .Returns(new LocalizedString(attribute.ErrorMessage, expectedErrorMessage)); var adapter = new FileExtensionsAttributeAdapter(attribute, stringLocalizer: stringLocalizer.Object); var context = new ClientModelValidationContext(new ActionContext(), metadata, provider, new Dictionary <string, string>()); // Act adapter.AddValidation(context); // Assert Assert.Collection( context.Attributes, kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("true", kvp.Value); }, kvp => { Assert.Equal("data-val-fileextensions", kvp.Key); Assert.Equal(expectedErrorMessage, kvp.Value); }, kvp => { Assert.Equal("data-val-fileextensions-extensions", kvp.Key); Assert.Equal(expectedExtensions, kvp.Value); }); }
public static void Extensions_Get_Set(string newValue, string expected) { var attribute = new FileExtensionsAttribute(); attribute.Extensions = newValue; Assert.Equal(expected, attribute.Extensions); }
private void LoadAttributes(ModelMetadata metadata) { //TO-DO: Refazer os métodos para tornar-los mais dinâmicos... if (metadata != null) { MetadataAttribute commonAttribute = new MetadataAttribute() { AttributeName = "Common" + "Attribute", Property = new Dictionary <string, object>() { { "DisplayName", metadata.DisplayName }, { "ShortDisplayName", metadata.ShortDisplayName }, { "IsRequired", metadata.IsRequired }, { "IsReadOnly", metadata.IsReadOnly }, { "IsNullableValueType", metadata.IsNullableValueType }, { "Description", metadata.Description }, { "Watermark", metadata.Watermark }, { "ShowForDisplay", metadata.ShowForDisplay }, { "ShowForEdit", metadata.ShowForEdit }, { "DataTypeName", metadata.DataTypeName }, { "IsComplexType", metadata.IsComplexType }, { "EditFormatString", metadata.EditFormatString }, { "HideSurroundingHtml", metadata.HideSurroundingHtml }, { "HtmlEncode", metadata.HtmlEncode }, { "ConvertEmptyStringToNull", metadata.ConvertEmptyStringToNull }, { "NullDisplayText", metadata.NullDisplayText }, { "SimpleDisplayText", metadata.SimpleDisplayText }, { "TemplateHint", metadata.TemplateHint }, { "DisplayFormatString", metadata.DisplayFormatString }, } }; metadataAttributes.Add(commonAttribute); } HtmlAttributesAttribute htmlAttributesAttribute = GetModelMetadataAttributes(metadata).OfType <HtmlAttributesAttribute>().FirstOrDefault(); if (htmlAttributesAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "HtmlAttributes" + "Attribute", Property = new Dictionary <string, object>() { { "ID", htmlAttributesAttribute.ID }, { "Name", htmlAttributesAttribute.Name }, { "Class", htmlAttributesAttribute.Class }, { "Style", htmlAttributesAttribute.Style }, { "Width", htmlAttributesAttribute.Width }, { "Height", htmlAttributesAttribute.Height }, { "Placeholder", htmlAttributesAttribute.Placeholder }, } }; metadataAttributes.Add(metaAttribute); } DataTypeAttribute dataTypeAttribute = GetModelMetadataAttributes(metadata).OfType <DataTypeAttribute>().FirstOrDefault(); if (dataTypeAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "DataType" + "Attribute", Property = new Dictionary <string, object>() { { "DataType", dataTypeAttribute.DataType }, { "ErrorMessage", dataTypeAttribute.ErrorMessage }, { "ErrorMessageResourceName", dataTypeAttribute.ErrorMessageResourceName }, { "RequiresValidationContext", dataTypeAttribute.RequiresValidationContext }, } }; metadataAttributes.Add(metaAttribute); } DataTypeFieldAttribute dataTypeFieldAttribute = GetModelMetadataAttributes(metadata).OfType <DataTypeFieldAttribute>().FirstOrDefault(); if (dataTypeFieldAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "DataTypeField" + "Attribute", Property = new Dictionary <string, object>() { { "DataType", dataTypeFieldAttribute.DataType }, { "ErrorMessage", dataTypeFieldAttribute.ErrorMessage }, { "ErrorMessageResourceName", dataTypeFieldAttribute.ErrorMessageResourceName }, { "RequiresValidationContext", dataTypeFieldAttribute.RequiresValidationContext }, { "Cols", dataTypeFieldAttribute.Cols }, { "Rows", dataTypeFieldAttribute.Rows }, { "Wrap", (dataTypeFieldAttribute.HardWrap ? "hard" : null) }, { "MinLength", dataTypeFieldAttribute.MinLength }, { "MaxLength", dataTypeFieldAttribute.MaxLength }, } }; metadataAttributes.Add(metaAttribute); } RegularExpressionAttribute regularExpressionAttribute = GetModelMetadataAttributes(metadata).OfType <RegularExpressionAttribute>().FirstOrDefault(); if (regularExpressionAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "RegularExpression" + "Attribute", Property = new Dictionary <string, object>() { { "Pattern", regularExpressionAttribute.Pattern }, { "ErrorMessage", regularExpressionAttribute.ErrorMessage }, { "ErrorMessageResourceName", regularExpressionAttribute.ErrorMessageResourceName }, { "RequiresValidationContext", regularExpressionAttribute.RequiresValidationContext }, } }; metadataAttributes.Add(metaAttribute); } StringLengthAttribute stringLengthAttribute = GetModelMetadataAttributes(metadata).OfType <StringLengthAttribute>().FirstOrDefault(); if (stringLengthAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "StringLength" + "Attribute", Property = new Dictionary <string, object>() { { "MinimumLength", stringLengthAttribute.MinimumLength }, { "MaximumLength", stringLengthAttribute.MaximumLength }, { "ErrorMessage", stringLengthAttribute.ErrorMessage }, { "FormatErrorMessage", stringLengthAttribute.FormatErrorMessage(metadata.PropertyName) }, { "ErrorMessageResourceName", stringLengthAttribute.ErrorMessageResourceName }, { "RequiresValidationContext", stringLengthAttribute.RequiresValidationContext }, } }; metadataAttributes.Add(metaAttribute); } MinLengthAttribute minLengthAttribute = GetModelMetadataAttributes(metadata).OfType <MinLengthAttribute>().FirstOrDefault(); if (minLengthAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "MinLength" + "Attribute", Property = new Dictionary <string, object>() { { "Length", minLengthAttribute.Length }, { "TypeId", minLengthAttribute.TypeId }, { "ErrorMessage", minLengthAttribute.ErrorMessage }, { "ErrorMessageResourceName", minLengthAttribute.ErrorMessageResourceName }, { "RequiresValidationContext", minLengthAttribute.RequiresValidationContext }, } }; metadataAttributes.Add(metaAttribute); } MaxLengthAttribute maxLengthAttribute = GetModelMetadataAttributes(metadata).OfType <MaxLengthAttribute>().FirstOrDefault(); if (maxLengthAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "MaxLength" + "Attribute", Property = new Dictionary <string, object>() { { "Length", maxLengthAttribute.Length }, { "TypeId", maxLengthAttribute.TypeId }, { "ErrorMessage", maxLengthAttribute.ErrorMessage }, { "ErrorMessageResourceName", maxLengthAttribute.ErrorMessageResourceName }, { "RequiresValidationContext", maxLengthAttribute.RequiresValidationContext }, } }; metadataAttributes.Add(metaAttribute); } DisplayAttribute displayAttribute = GetModelMetadataAttributes(metadata).OfType <DisplayAttribute>().FirstOrDefault(); if (displayAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "Display" + "Attribute", Property = new Dictionary <string, object>() { { "ShortName", displayAttribute.ShortName }, { "Name", displayAttribute.Name }, { "Prompt", displayAttribute.Prompt }, { "GroupName", displayAttribute.GroupName }, { "Description", displayAttribute.Description }, } }; metadataAttributes.Add(metaAttribute); } RequiredAttribute requiredAttribute = GetModelMetadataAttributes(metadata).OfType <RequiredAttribute>().FirstOrDefault(); if (requiredAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "Required" + "Attribute", Property = new Dictionary <string, object>() { { "IsRequired", true }, { "AllowEmptyStrings", requiredAttribute.AllowEmptyStrings }, { "ErrorMessage", requiredAttribute.ErrorMessage }, { "ErrorMessageResourceName", requiredAttribute.ErrorMessageResourceName }, { "RequiresValidationContext", requiredAttribute.RequiresValidationContext }, } }; metadataAttributes.Add(metaAttribute); } RangeAttribute rangeAttribute = GetModelMetadataAttributes(metadata).OfType <RangeAttribute>().FirstOrDefault(); if (rangeAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "Range" + "Attribute", Property = new Dictionary <string, object>() { { "OperandType", rangeAttribute.OperandType }, { "AllowEmptyStrings", rangeAttribute.Minimum }, { "Maximum", rangeAttribute.Maximum }, { "ErrorMessage", rangeAttribute.ErrorMessage }, { "ErrorMessageResourceName", rangeAttribute.ErrorMessageResourceName }, { "RequiresValidationContext", rangeAttribute.RequiresValidationContext }, } }; metadataAttributes.Add(metaAttribute); } DisplayFormatAttribute displayFormatAttribute = GetModelMetadataAttributes(metadata).OfType <DisplayFormatAttribute>().FirstOrDefault(); if (displayFormatAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "DisplayFormat" + "Attribute", Property = new Dictionary <string, object>() { { "DataFormatString", displayFormatAttribute.DataFormatString }, { "ApplyFormatInEditMode", displayFormatAttribute.ApplyFormatInEditMode }, { "ConvertEmptyStringToNull", displayFormatAttribute.ConvertEmptyStringToNull }, { "HtmlEncode", displayFormatAttribute.HtmlEncode }, { "NullDisplayText", displayFormatAttribute.NullDisplayText }, { "IsDefault" + "Attribute", displayFormatAttribute.IsDefaultAttribute() }, } }; metadataAttributes.Add(metaAttribute); } CreditCardAttribute creditCardAttribute = GetModelMetadataAttributes(metadata).OfType <CreditCardAttribute>().FirstOrDefault(); if (creditCardAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "CreditCard" + "Attribute", Property = new Dictionary <string, object>() { { "DataType", creditCardAttribute.DataType }, { "CustomDataType", creditCardAttribute.CustomDataType }, { "DisplayFormat", creditCardAttribute.DisplayFormat }, { "ErrorMessage", creditCardAttribute.ErrorMessage }, { "FormatErrorMessage", stringLengthAttribute.FormatErrorMessage(metadata.PropertyName) }, { "ErrorMessageResourceName", creditCardAttribute.ErrorMessageResourceName }, { "ErrorMessageResourceType", creditCardAttribute.ErrorMessageResourceType }, { "RequiresValidationContext", creditCardAttribute.RequiresValidationContext }, } }; metadataAttributes.Add(metaAttribute); } CustomValidationAttribute customValidationAttribute = GetModelMetadataAttributes(metadata).OfType <CustomValidationAttribute>().FirstOrDefault(); if (customValidationAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "CustomValidation" + "Attribute", Property = new Dictionary <string, object>() { { "ValidatorType", customValidationAttribute.ValidatorType }, { "Method", customValidationAttribute.Method }, { "ErrorMessage", creditCardAttribute.ErrorMessage }, { "FormatErrorMessage", stringLengthAttribute.FormatErrorMessage(metadata.PropertyName) }, { "ErrorMessageResourceName", creditCardAttribute.ErrorMessageResourceName }, { "ErrorMessageResourceType", creditCardAttribute.ErrorMessageResourceType }, { "RequiresValidationContext", creditCardAttribute.RequiresValidationContext }, } }; metadataAttributes.Add(metaAttribute); } EmailAddressAttribute emailAddressAttribute = GetModelMetadataAttributes(metadata).OfType <EmailAddressAttribute>().FirstOrDefault(); if (emailAddressAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "EmailAddress" + "Attribute", Property = new Dictionary <string, object>() { { "DataType", emailAddressAttribute.DataType }, { "CustomDataType", emailAddressAttribute.CustomDataType }, { "DisplayFormat", emailAddressAttribute.DisplayFormat }, { "ErrorMessage", creditCardAttribute.ErrorMessage }, { "FormatErrorMessage", stringLengthAttribute.FormatErrorMessage(metadata.PropertyName) }, { "ErrorMessageResourceName", creditCardAttribute.ErrorMessageResourceName }, { "ErrorMessageResourceType", creditCardAttribute.ErrorMessageResourceType }, { "RequiresValidationContext", creditCardAttribute.RequiresValidationContext }, } }; metadataAttributes.Add(metaAttribute); } FileExtensionsAttribute fileExtensionsAttribute = GetModelMetadataAttributes(metadata).OfType <FileExtensionsAttribute>().FirstOrDefault(); if (fileExtensionsAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "FileExtensions" + "Attribute", Property = new Dictionary <string, object>() { { "DataType", emailAddressAttribute.DataType }, { "CustomDataType", emailAddressAttribute.CustomDataType }, { "DisplayFormat", emailAddressAttribute.DisplayFormat }, { "ErrorMessage", creditCardAttribute.ErrorMessage }, { "FormatErrorMessage", stringLengthAttribute.FormatErrorMessage(metadata.PropertyName) }, { "ErrorMessageResourceName", creditCardAttribute.ErrorMessageResourceName }, { "ErrorMessageResourceType", creditCardAttribute.ErrorMessageResourceType }, { "RequiresValidationContext", creditCardAttribute.RequiresValidationContext }, } }; metadataAttributes.Add(metaAttribute); } TimestampAttribute timestampAttribute = GetModelMetadataAttributes(metadata).OfType <TimestampAttribute>().FirstOrDefault(); if (timestampAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "FileExtensions" + "Attribute", Property = new Dictionary <string, object>() { { "TypeId", timestampAttribute.TypeId }, } }; metadataAttributes.Add(metaAttribute); } ViewDisabledAttribute viewDisabledAttribute = GetModelMetadataAttributes(metadata).OfType <ViewDisabledAttribute>().FirstOrDefault(); if (viewDisabledAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "ViewDisabled" + "Attribute", Property = new Dictionary <string, object>() { { "Declared", true }, } }; metadataAttributes.Add(metaAttribute); } TextAreaAttribute textAreaAttribute = GetModelMetadataAttributes(metadata).OfType <TextAreaAttribute>().FirstOrDefault(); if (textAreaAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "TextArea" + "Attribute", Property = new Dictionary <string, object>() { { "Cols", textAreaAttribute.Cols }, { "Rows", textAreaAttribute.Rows }, { "Wrap", (textAreaAttribute.HardWrap ? "hard" : null) }, { "MinLength", textAreaAttribute.MinLength }, { "MaxLength", textAreaAttribute.MaxLength }, } }; metadataAttributes.Add(metaAttribute); } OnlyNumberAttribute onlyNumberAttribute = GetModelMetadataAttributes(metadata).OfType <OnlyNumberAttribute>().FirstOrDefault(); if (onlyNumberAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "OnlyNumber" + "Attribute", Property = new Dictionary <string, object>() { { "Declared", true }, { "ClassDecorator", "onlyNumber" }, } }; metadataAttributes.Add(metaAttribute); } CurrencyAttribute currencyAttribute = GetModelMetadataAttributes(metadata).OfType <CurrencyAttribute>().FirstOrDefault(); if (currencyAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "Currency" + "Attribute", Property = new Dictionary <string, object>() { { "Declared", true }, { "ClassDecorator", "onlyNumber" }, { "Pattern", "currency" }, } }; metadataAttributes.Add(metaAttribute); } NoEspecialCharsAttribute noEspecialCharsAttribute = GetModelMetadataAttributes(metadata).OfType <NoEspecialCharsAttribute>().FirstOrDefault(); if (noEspecialCharsAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "NoEspecialChars" + "Attribute", Property = new Dictionary <string, object>() { { "Declared", true }, { "ClassDecorator", "noCaracEsp" }, } }; metadataAttributes.Add(metaAttribute); } ProgressAttribute progressAttribute = GetModelMetadataAttributes(metadata).OfType <ProgressAttribute>().FirstOrDefault(); if (progressAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "Progress" + "Attribute", Property = new Dictionary <string, object>() { { "MinValue", progressAttribute.MinValue }, { "MaxValue", progressAttribute.MaxValue }, { "Step", progressAttribute.Step }, } }; metadataAttributes.Add(metaAttribute); } PlaceHolderAttribute placeHolderAttribute = GetModelMetadataAttributes(metadata).OfType <PlaceHolderAttribute>().FirstOrDefault(); if (placeHolderAttribute != null) { MetadataAttribute metaAttribute = new MetadataAttribute() { AttributeName = "PlaceHolder" + "Attribute", Property = new Dictionary <string, object>() { { "Declared", true }, { "Text", placeHolderAttribute.Text }, } }; metadataAttributes.Add(metaAttribute); } }
private void writeObjectFolder(string filePath, object obj) { _ObjectStore.UnMarkSerialized(obj); Type objectType = obj.GetType(), stringType = typeof(String); string folderPath = Path.GetDirectoryName(filePath); HashSet <string> nestedProperties = new HashSet <string>(); List <Tuple <string, object, bool> > queued = new List <Tuple <string, object, bool> >(); IList <PropertyInfo> fields = this.GetFieldsOrdered(objectType); foreach (PropertyInfo propertyInfo in fields) { if (propertyInfo == null) { continue; } Type propertyType = propertyInfo.PropertyType; XmlArrayAttribute xmlArrayAttribute = propertyInfo.GetCustomAttribute <XmlArrayAttribute>(); XmlArrayItemAttribute xmlArrayItemAttribute = propertyInfo.GetCustomAttribute <XmlArrayItemAttribute>(); if (xmlArrayAttribute != null && xmlArrayItemAttribute != null) { bool isLeaf = xmlArrayItemAttribute != null && string.Compare(xmlArrayItemAttribute.DataType, "_leaf_", true) == 0; if (string.IsNullOrEmpty(xmlArrayItemAttribute.ElementName) && xmlArrayItemAttribute.NestingLevel > 0 && propertyType.IsGenericType && typeof(IEnumerable).IsAssignableFrom(propertyType.GetGenericTypeDefinition())) { Type genericType = propertyType.GetGenericArguments()[0]; PropertyInfo uniqueIdProperty = genericType.GetProperty("id", typeof(string)); PropertyInfo folderNameProperty = genericType.GetProperty("_folderName", typeof(string)); if (folderNameProperty == null) { folderNameProperty = uniqueIdProperty; } PropertyInfo nameProp = objectType.GetProperty("Name", typeof(string)); if (uniqueIdProperty != null) { IEnumerable enumerable = propertyInfo.GetValue(obj) as IEnumerable; if (enumerable != null) { bool allSaved = true, nestingValid = true;; int count = 0; foreach (object nested in enumerable) { if (nested == null) { continue; } count++; if (!_ObjectStore.isSerialized(nested)) { allSaved = false; } object objId = uniqueIdProperty.GetValue(nested); if (objId == null || string.IsNullOrEmpty(objId.ToString())) { nestingValid = false; break; } } if (nestingValid && !allSaved) { string nestedPath = Path.Combine(folderPath, removeInvalidFile(propertyInfo.Name)); Directory.CreateDirectory(nestedPath); nestedProperties.Add(propertyInfo.Name); if (xmlArrayItemAttribute.NestingLevel > 1) { string prefix = m_NominatedTypeFilePrefix.Count > 0 ? hasFilePrefix(genericType) : ""; IEnumerable <IGrouping <char, object> > groups = null; if (string.IsNullOrEmpty(prefix)) { groups = enumerable.Cast <object>().GroupBy(x => char.ToLower(uniqueIdProperty.GetValue(x).ToString()[0])); } else { int prefixLength = prefix.Length; groups = enumerable.Cast <object>().GroupBy(x => char.ToLower(initialChar(uniqueIdProperty.GetValue(x).ToString(), prefix, prefixLength))); } foreach (IGrouping <char, object> group in groups) { string alphaPath = Path.Combine(nestedPath, group.Key.ToString()); Directory.CreateDirectory(alphaPath); foreach (object nested in group) { _ObjectStore.MarkSerialized(nested); string nestedObjectPath = isLeaf ? alphaPath : Path.Combine(alphaPath, removeInvalidFile(folderNameProperty.GetValue(nested).ToString())); Directory.CreateDirectory(nestedObjectPath); string fileName = removeInvalidFile((isLeaf ? uniqueIdProperty.GetValue(nested).ToString() : nested.GetType().Name) + ".xml"); queued.Add(new Tuple <string, object, bool>(Path.Combine(nestedObjectPath, fileName), nested, isLeaf)); } } continue; } foreach (object nested in enumerable) { if (nested == null) { continue; } _ObjectStore.MarkSerialized(nested); string nestedObjectPath = isLeaf ? nestedPath : Path.Combine(nestedPath, removeInvalidFile(isLeaf ? uniqueIdProperty.GetValue(nested).ToString() : folderNameProperty.GetValue(nested).ToString())); Directory.CreateDirectory(nestedObjectPath); string fileName = removeInvalidFile((isLeaf ? uniqueIdProperty.GetValue(nested).ToString() : nested.GetType().Name) + ".xml"); queued.Add(new Tuple <string, object, bool>(Path.Combine(nestedObjectPath, fileName), nested, isLeaf)); } } } } } } else { object propertyObject = propertyInfo.GetValue(obj); if (propertyObject == null) { nestedProperties.Add(propertyInfo.Name); } else { DataType dataType = DataType.Custom; string fileExtension = ".txt", txt = ""; foreach (DataTypeAttribute dataTypeAttribute in propertyInfo.GetCustomAttributes <DataTypeAttribute>()) { FileExtensionsAttribute fileExtensionsAttribute = dataTypeAttribute as FileExtensionsAttribute; if (fileExtensionsAttribute != null && !string.IsNullOrEmpty(fileExtensionsAttribute.Extensions)) { fileExtension = fileExtensionsAttribute.Extensions; } if (dataTypeAttribute.DataType != DataType.Custom) { dataType = dataTypeAttribute.DataType; } } if (dataType == DataType.Html) { string html = propertyObject.ToString(); if (!string.IsNullOrEmpty(html)) { nestedProperties.Add(propertyInfo.Name); string htmlPath = Path.Combine(folderPath, propertyInfo.Name + ".html"); File.WriteAllText(htmlPath, html.TrimEnd() + Environment.NewLine, Encoding.UTF8); continue; } } else if (dataType == DataType.MultilineText) { byte[] byteArray = propertyObject as byte[]; if (byteArray != null) { nestedProperties.Add(propertyInfo.Name); txt = Encoding.ASCII.GetString(byteArray); } else { txt = propertyObject.ToString(); } if (!string.IsNullOrEmpty(txt)) { nestedProperties.Add(propertyInfo.Name); string txtPath = Path.Combine(folderPath, propertyInfo.Name + fileExtension); File.WriteAllText(txtPath, txt.TrimEnd() + Environment.NewLine, Encoding.UTF8); continue; } } } } } if (nestedProperties.Count < fields.Count) { _ObjectStore.UnMarkSerialized(obj); using (FileStream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { writeObject(fileStream, obj, nestedProperties); } } foreach (Tuple <string, object, bool> o in queued) { if (o.Item3) { _ObjectStore.UnMarkSerialized(o.Item2); using (FileStream fileStream = new FileStream(o.Item1, FileMode.Create, FileAccess.Write)) { writeObject(fileStream, o.Item2, new HashSet <string>()); } } else { writeObjectFolder(o.Item1, o.Item2); } } }
/// <summary> /// Checks if the file is allowed based on specific conditions. /// </summary> /// <param name="file"></param> /// <param name="allowedExtensions">Comma separated, e.g: "txt,pdf,doc,docx". You need to pass FileCheckLayers.CheckExtensions as one of the layers.</param> /// <param name="allowedContentTypes">Comma separated, e.g: "text/plain,application/pdf,application/msword". You need to pass FileCheckLayers.CheckContentType as one of the layers.</param> /// <param name="maxSingleFileSize">Accepted file size in bytes. You need to pass FileCheckLayers.CheckFileSize as one of the layers.</param> /// <param name="layers">The check-points that you want the file to go through.</param> /// <returns>true if the file is passed; otherwise false.</returns> public static bool IsFileAllowed(this IFormFile file, string allowedExtensions, string allowedContentTypes, long?maxSingleFileSize, params FileCheckLayers[] layers) { try { //Build the layers dictionay (since we will check the layers more than once). Dictionary <FileCheckLayers, bool> foundLayers = SetupLayersDictionary(layers); //Check null values. CheckNulls(file, allowedExtensions, allowedContentTypes, maxSingleFileSize, foundLayers); var allowedContentTypesArray = new string[] { }; if (!string.IsNullOrWhiteSpace(allowedContentTypes)) { allowedContentTypesArray = allowedContentTypes.Trim().Split(","); } bool foundAllLayers = foundLayers.TryGetValue(FileCheckLayers.AllLayers, out foundAllLayers); //FileCheckLayers.CheckExtensions bool foundCheckExtensions = foundLayers.TryGetValue(FileCheckLayers.CheckExtensions, out foundCheckExtensions); if (foundCheckExtensions || foundAllLayers) { var fileExtensionsAttribute = new FileExtensionsAttribute() { Extensions = allowedExtensions }; if (!fileExtensionsAttribute.IsValid(file?.FileName)) { throw new BusinessException(string.Format($"File extension {file?.FileName} could not be found in the {nameof(allowedExtensions)}.")); } ; } //Layer2 checker, check if the recieved content-type matches the given file name. bool foundCheckFileContentTypeToFileExtension = foundLayers.TryGetValue(FileCheckLayers.CheckFileContentTypeToFileExtension, out foundCheckFileContentTypeToFileExtension); if (foundCheckFileContentTypeToFileExtension || foundAllLayers) { MatchContentTypeToFileName(file?.FileName, file?.ContentType, allowedContentTypesArray, foundLayers, foundAllLayers); } //Layer3 checker, check if given content-type is allowed bool foundCheckContentType = foundLayers.TryGetValue(FileCheckLayers.CheckContentType, out foundCheckContentType); if (foundCheckContentType || foundAllLayers) { IsContentTypeAllowed(file?.ContentType, allowedContentTypesArray); } //Check file size. bool foundCheckFileSize = foundLayers.TryGetValue(FileCheckLayers.CheckFileSize, out foundCheckFileSize); if (foundCheckFileSize || foundAllLayers) { if (file?.Length > maxSingleFileSize) { throw new BusinessException(string.Format($"File size {file?.Length} exceeded the {nameof(maxSingleFileSize)}.")); } } } catch (BusinessException ex) { //TODO: add throw exception option. return(false); } return(true); }
private void WriteNestedObject(QueueData dataObject, Queue <QueueData> queue, ref int nextID) { object obj = dataObject.PayLoad; Type objectType = obj.GetType(), stringType = typeof(String); string folderPath = Path.GetDirectoryName(dataObject.FilePath); HashSet <string> nestedProperties = new HashSet <string>(); IList <PropertyInfo> fields = this.GetFieldsOrdered(objectType); foreach (PropertyInfo propertyInfo in fields) { if (propertyInfo == null) { continue; } Type propertyType = propertyInfo.PropertyType; XmlArrayAttribute xmlArrayAttribute = propertyInfo.GetCustomAttribute <XmlArrayAttribute>(); XmlAttributeAttribute xmlAttributeAttribute = propertyInfo.GetCustomAttribute <XmlAttributeAttribute>(); if (xmlArrayAttribute == null && xmlAttributeAttribute == null) { if (propertyType.IsGenericType && typeof(IEnumerable).IsAssignableFrom(propertyType.GetGenericTypeDefinition())) { Type genericType = propertyType.GetGenericArguments()[0]; PropertyInfo uniqueIdProperty = genericType.GetProperty("id", typeof(string)); PropertyInfo nameProp = objectType.GetProperty("Name", typeof(string)); if (uniqueIdProperty != null) { IEnumerable enumerable = propertyInfo.GetValue(obj) as IEnumerable; if (enumerable != null) { bool allSaved = true, nestingValid = true;; int count = 0; foreach (object nested in enumerable) { if (nested == null) { continue; } count++; if (string.IsNullOrEmpty(_ObjectStore.EncounteredId(nested))) { allSaved = false; } object objId = uniqueIdProperty.GetValue(nested); if (objId == null || string.IsNullOrEmpty(objId.ToString())) { nestingValid = false; break; } } if (nestingValid && !allSaved) { string nestedPath = Path.Combine(folderPath, removeInvalidFile(propertyInfo.Name)); Directory.CreateDirectory(nestedPath); nestedProperties.Add(propertyInfo.Name); //if(count > 500) //{ // string prefix = m_NominatedTypeFilePrefix.Count > 0 ? hasFilePrefix(genericType) : ""; // IEnumerable<IGrouping<char, object>> groups = null; // if (string.IsNullOrEmpty(prefix)) // groups = enumerable.Cast<object>().GroupBy(x => char.ToLower(uniqueIdProperty.GetValue(x).ToString()[0])); // else // { // int prefixLength = prefix.Length; // groups = enumerable.Cast<object>().GroupBy(x => char.ToLower(initialChar(uniqueIdProperty.GetValue(x).ToString(), prefix, prefixLength))); // } // if(groups.Count() > 2) // { // foreach(IGrouping<char,object> group in groups) // { // string alphaPath = Path.Combine(nestedPath, group.Key.ToString()); // Directory.CreateDirectory(alphaPath); // foreach (object nested in group) // { // mObjectStore.MarkEncountered(nested, ref nextID); // string nestedObjectPath = Path.Combine(alphaPath, removeInvalidFile(uniqueIdProperty.GetValue(nested).ToString())); // Directory.CreateDirectory(nestedObjectPath); // queue.Enqueue(new QueueData(Path.Combine(nestedObjectPath, removeInvalidFile(nested.GetType().Name) + ".xml"), nested)); // } // } // continue; // } //} foreach (object nested in enumerable) { if (nested == null) { continue; } _ObjectStore.MarkEncountered(nested, ref nextID); string nestedObjectPath = Path.Combine(nestedPath, removeInvalidFile(uniqueIdProperty.GetValue(nested).ToString())); Directory.CreateDirectory(nestedObjectPath); queue.Enqueue(new QueueData(Path.Combine(nestedObjectPath, removeInvalidFile(propertyInfo.Name) + ".xml"), nested)); } } } } } else { object propertyObject = propertyInfo.GetValue(obj); if (propertyObject == null) { nestedProperties.Add(propertyInfo.Name); } else { DataType dataType = DataType.Custom; string fileExtension = ".txt", txt = ""; foreach (DataTypeAttribute dataTypeAttribute in propertyInfo.GetCustomAttributes <DataTypeAttribute>()) { FileExtensionsAttribute fileExtensionsAttribute = dataTypeAttribute as FileExtensionsAttribute; if (fileExtensionsAttribute != null && !string.IsNullOrEmpty(fileExtensionsAttribute.Extensions)) { fileExtension = fileExtensionsAttribute.Extensions; } if (dataTypeAttribute.DataType != DataType.Custom) { dataType = dataTypeAttribute.DataType; } } if (dataType == DataType.Html) { string html = propertyObject.ToString(); if (!string.IsNullOrEmpty(html)) { nestedProperties.Add(propertyInfo.Name); string htmlPath = Path.Combine(folderPath, propertyInfo.Name + ".html"); File.WriteAllText(htmlPath, html); continue; } } else if (dataType == DataType.MultilineText) { byte[] byteArray = propertyObject as byte[]; if (byteArray != null) { nestedProperties.Add(propertyInfo.Name); txt = Encoding.ASCII.GetString(byteArray); } else { txt = propertyObject.ToString(); } if (!string.IsNullOrEmpty(txt)) { nestedProperties.Add(propertyInfo.Name); string txtPath = Path.Combine(folderPath, propertyInfo.Name + fileExtension); File.WriteAllText(txtPath, txt); continue; } } Type propertyObjectType = propertyObject.GetType(); if (!(propertyObjectType.IsValueType || propertyObjectType == stringType)) { if (string.IsNullOrEmpty(_ObjectStore.EncounteredId(obj))) { DataContractAttribute dataContractAttribute = propertyObjectType.GetCustomAttribute <DataContractAttribute>(true); if (dataContractAttribute == null || dataContractAttribute.IsReference) { string nestedPath = Path.Combine(folderPath, removeInvalidFile(propertyInfo.Name)); Directory.CreateDirectory(nestedPath); queue.Enqueue(new QueueData(Path.Combine(nestedPath, removeInvalidFile(propertyInfo.Name) + ".xml"), propertyObject)); nestedProperties.Add(propertyInfo.Name); _ObjectStore.MarkEncountered(propertyObject, ref nextID); } } } } } } } if (nestedProperties.Count < fields.Count) { _ObjectStore.RemoveEncountered(obj); using (FileStream fileStream = new FileStream(dataObject.FilePath, FileMode.Create, FileAccess.Write)) { writeObject(fileStream, obj, nestedProperties, ref nextID); } } }