public static void GetDataTypeName_ReturnsExpectedName(DataType dataType) { if (dataType != DataType.Custom) { DataTypeAttribute attribute = new DataTypeAttribute(dataType); Assert.Equal(Enum.GetName(typeof(DataType), dataType), attribute.GetDataTypeName()); } }
public static void Ctor_DataType(DataType dataType) { DataTypeAttribute attribute = new DataTypeAttribute(dataType); Assert.Equal(dataType, attribute.DataType); Assert.Null(attribute.CustomDataType); bool expectedNull = dataType != DataType.Date && dataType != DataType.Time && dataType != DataType.Currency; Assert.Equal(expectedNull, attribute.DisplayFormat == null); }
public void Constructor_Invalid() { var attr = new DataTypeAttribute(null); ExceptionHelper.ExpectException<InvalidOperationException>(delegate() { attr.IsValid(null); }, Resources.DataAnnotationsResources.DataTypeAttribute_EmptyDataTypeString); attr = new DataTypeAttribute(String.Empty); ExceptionHelper.ExpectException<InvalidOperationException>(delegate() { attr.IsValid(null); }, Resources.DataAnnotationsResources.DataTypeAttribute_EmptyDataTypeString); }
public static void Ctor_String(string customDataType) { DataTypeAttribute attribute = new DataTypeAttribute(customDataType); Assert.Equal(DataType.Custom, attribute.DataType); Assert.Equal(customDataType, attribute.CustomDataType); if (string.IsNullOrEmpty(customDataType)) { Assert.Throws<InvalidOperationException>(() => attribute.GetDataTypeName()); Assert.Throws<InvalidOperationException>(() => attribute.Validate(new object(), s_testValidationContext)); } else { Assert.Equal(customDataType, attribute.GetDataTypeName()); } }
public T[] GetAttributes <T>(Type type, MemberInfo memberInfo, bool inherit) where T : Attribute { if (typeof(T) == typeof(Sql.ExpressionAttribute) && (memberInfo.IsMethodEx() || memberInfo.IsPropertyEx())) { if (!_cache.TryGetValue(memberInfo, out var attrs)) { if (_sqlMethodAttributes.Length > 0) { if (memberInfo.IsMethodEx()) { var ma = _reader.GetAttributes <Attribute>(type, memberInfo, inherit) .Where(a => _sqlMethodAttributes.Any(_ => _.IsAssignableFrom(a.GetType()))) .ToArray(); if (ma.Length > 0) { var mi = (MethodInfo)memberInfo; var ps = mi.GetParameters(); var ex = mi.IsStatic ? string.Format("{0}::{1}({2})", memberInfo.DeclaringType !.Name.ToLower().StartsWith("sql") ? memberInfo.DeclaringType.Name.ToLower().Substring(3) : memberInfo.DeclaringType.Name.ToLower(), ((dynamic)ma[0]).Name ?? memberInfo.Name, string.Join(", ", ps.Select((_, i) => '{' + i.ToString() + '}'))) : string.Format("{{0}}.{0}({1})", ((dynamic)ma[0]).Name ?? memberInfo.Name, string.Join(", ", ps.Select((_, i) => '{' + (i + 1).ToString() + '}'))); attrs = new[] { (T)(Attribute) new Sql.ExpressionAttribute(ex) { ServerSideOnly = true } }; } else { attrs = Array <T> .Empty; } } else { var pi = (PropertyInfo)memberInfo; var gm = pi.GetGetMethod(); if (gm != null) { var ma = _reader.GetAttributes <Attribute>(type, gm, inherit) .Where(a => _sqlMethodAttributes.Any(_ => _.IsAssignableFrom(a.GetType()))) .ToArray(); if (ma.Length > 0) { var ex = $"{{0}}.{((dynamic)ma[0]).Name ?? memberInfo.Name}"; attrs = new[] { (T)(Attribute) new Sql.ExpressionAttribute(ex) { ServerSideOnly = true, ExpectExpression = true } }; } else { attrs = Array <T> .Empty; } } else { attrs = Array <T> .Empty; } } } else { attrs = Array <T> .Empty; } _cache[memberInfo] = attrs; } return((T[])attrs); } if (typeof(T) == typeof(DataTypeAttribute) && _sqlUserDefinedTypeAttributes.Length > 0) { var attrs = _reader.GetAttributes <Attribute>(memberInfo.GetMemberType(), inherit) .Where(a => _sqlUserDefinedTypeAttributes.Any(_ => _.IsAssignableFrom(a.GetType()))) .ToArray(); if (attrs.Length == 1) { var c = attrs[0]; var n = ((dynamic)c).Name ?? memberInfo.GetMemberType().Name; if (n.ToLower().StartsWith("sql")) { n = n.Substring(3); } var attr = new DataTypeAttribute(DataType.Udt, n); return(new[] { (T)(Attribute)attr }); } } return(Array <T> .Empty); }
private static IPasswordFacet Create(DataTypeAttribute attribute, ISpecification holder) { return(attribute != null && attribute.DataType == DataType.Password ? new PasswordFacet(holder) : null); }
/// <summary> /// 使用指定的字段模板名称初始化 <see cref="DataTypeValidatorAttribute"/> 类的新实例。 /// </summary> /// <param name="customDataType">要与数据字段关联的自定义字段模板的名称。</param> public DataTypeValidatorAttribute(string customDataType) { _dataTypeAttribute = new DataTypeAttribute(customDataType); }
public virtual string GetFieldTemplateVirtualPath(MetaColumn column, DataBoundControlMode mode, string uiHint) { // NO checks are made on parameters in .NET, but well "handle" the NREX // throws in the other methods DataBoundControlMode newMode = PreprocessMode(column, mode); // The algorithm is as follows: // // 1. If column has a DataTypeAttribute on it, get the data type // - if it's Custom data type, uiHint is used unconditionally // - if it's not a custom type, ignore uiHint and choose template based // on type // // 2. If #1 is false and uiHint is not empty, use uiHint if the template // exists // // 3. If #2 is false, look up type according to the following algorithm: // // 1. lookup column type's full name // 2. if #1 fails, look up short type name // 3. if #2 fails, map type to special type name (Int -> Integer, String // -> Text etc) // 4. if #3 fails, try to find a fallback type // 5. if #4 fails, check if it's a foreign key or child column // 6. if #5 fails, return null // // From: http://msdn.microsoft.com/en-us/library/cc488523.aspx (augmented) // DataTypeAttribute attr = column.DataTypeAttribute; bool uiHintPresent = !String.IsNullOrEmpty(uiHint); string templatePath = null; int step = uiHintPresent ? 0 : 1; Type columnType = column.ColumnType; if (!uiHintPresent && attr == null) { if (column is MetaChildrenColumn) { templatePath = GetExistingTemplateVirtualPath("Children", column, newMode); } else if (column is MetaForeignKeyColumn) { templatePath = GetExistingTemplateVirtualPath("ForeignKey", column, newMode); } } while (step < 6 && templatePath == null) { switch (step) { case 0: templatePath = GetExistingTemplateVirtualPath(uiHint, column, newMode); break; case 1: if (attr != null) { templatePath = GetTemplateForDataType(attr.DataType, attr.GetDataTypeName(), uiHint, column, newMode); } break; case 2: templatePath = GetExistingTemplateVirtualPath(columnType.FullName, column, newMode); break; case 3: templatePath = GetExistingTemplateVirtualPath(columnType.Name, column, newMode); break; case 4: templatePath = ColumnTypeToSpecialName(columnType, column, newMode); break; case 5: columnType = GetFallbackType(columnType, column, newMode); if (columnType == null) { step = 5; } else { step = uiHintPresent ? 0 : 1; } break; } step++; } return(templatePath); }
public static MvcHtmlString TextBoxPadraoFor <TModel, TValue>(this HtmlHelper <TModel> html, Expression <Func <TModel, TValue> > expression, IDictionary <string, object> htmlAttributes) { ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData); string id = ExpressionHelper.GetExpressionText(expression).Split('.').Last().ToLower(); string nome = id; //string placeHolder = metadata.Description ?? id; bool isRequired = false; if (metadata.ContainerType != null) { isRequired = metadata.ContainerType.GetProperty(metadata.PropertyName) .GetCustomAttributes(typeof(RequiredAttribute), false) .Length == 1; } TimestampAttribute time = (TimestampAttribute) Attribute.GetCustomAttribute( (expression.Body as MemberExpression ?? ((UnaryExpression)expression.Body).Operand as MemberExpression).Member, typeof(TimestampAttribute)); DataTypeAttribute date = (DataTypeAttribute) Attribute.GetCustomAttribute( (expression.Body as MemberExpression ?? ((UnaryExpression)expression.Body).Operand as MemberExpression).Member, typeof(DataTypeAttribute)); if (htmlAttributes == null) { htmlAttributes = new Dictionary <string, object>(); } string classe = ""; string tamanho = "col-sm-12"; string group_addon = ""; if ((expression.ReturnType == typeof(decimal)) || (expression.ReturnType == typeof(decimal?))) { group_addon = "<span class='input-group-addon'> R$ </span>"; classe = "form-control text-right valor"; //input-lg var placeHolder = "0,00"; htmlAttributes.Add("placeholder", placeHolder); } else if ((date != null) && Equals(date.GetDataTypeName(), "Date")) { if (!htmlAttributes.ContainsKey("filtrar")) { group_addon = "<span class='input-group-addon'><i class='fa fa-calendar'></i></span>"; } classe = "form-control datepicker "; // input-lg htmlAttributes.Add("maxlength", "10"); htmlAttributes.Add("data_dateformat", "dd/mm/yy"); htmlAttributes.Add("onkeypress", "mascaraDT(this, DATA)"); } else if (time != null) { // group_addon = "<span class='input-group-addon'><i class='fa fa-clock-o'></i></span>"; classe = "form-control "; // input-lg htmlAttributes.Add("maxlength", "5"); } else { classe = classe + "form-control "; // input-lg } htmlAttributes.Add("Name", nome.ToLower()); htmlAttributes.Add("id", id); if (isRequired == true) { if (classe == "") { classe = "requerido"; } else { classe = classe + " requerido"; } } htmlAttributes.Add("class", classe); if (htmlAttributes.ContainsKey("tamanho")) { tamanho += " " + htmlAttributes["tamanho"]; } htmlAttributes.Add("style", "text-transform:uppercase"); if ((expression.ReturnType == typeof(decimal)) || (expression.ReturnType == typeof(decimal?))) { /// refatorar StringBuilder str = new StringBuilder(); // str.Append("<div class='input-group'>"); str.Append(html.TextBoxFor(expression, htmlAttributes)); // str.Append(group_addon); // str.Append("</div>"); return(new MvcHtmlString(str.ToString())); } else if (((date != null) && Equals(date.GetDataTypeName(), "Date")) || (time != null)) { /// refatorar StringBuilder str = new StringBuilder(); if (!htmlAttributes.ContainsKey("filtrar")) { str.Append("<div class='input-group'>"); } str.Append(html.TextBoxFor(expression, htmlAttributes)); if (!htmlAttributes.ContainsKey("filtrar")) { str.Append(group_addon); str.Append("</div>"); } return(new MvcHtmlString(str.ToString())); } else { /// refatorar StringBuilder str = new StringBuilder(); // str.Append("<div class='col-md-10'>"); // str.Append("<div class='row'>"); // str.Append("<div class='"+ tamanho+ "'>"); str.Append(html.TextBoxFor(expression, htmlAttributes)); // str.Append("</div>"); // str.Append("</div>"); // str.Append("</div>"); return(new MvcHtmlString(str.ToString())); } }
/// <summary> /// Initializes a new instance of the DataTypeAttributeAdapter class. /// </summary> /// <param name="metadata">The model metadata.</param> /// <param name="context">The controller context.</param> /// <param name="attribute">The DataType attribute.</param> /// <param name="ruleName">The name of the client validation rule.</param> public LocalizedDataTypeAttributeAdapter(ModelMetadata metadata, ControllerContext context, DataTypeAttribute attribute, string ruleName) : base(metadata, context, attribute) { mRuleName = ruleName; }
/// <summary> /// 保存配置 /// </summary> /// <param name="model">数据</param> public ActionResult SaveConfig(WebConfigVM model) { try { //获取userKey string userKey = EG.Business.Common.ConfigCache.GetAppConfig("UserKey"); //获取配置文件 string configPath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; XDocument xdoc = XDocument.Load(configPath); XElement xeAppsetting = xdoc.Root.Element("appSettings"); foreach (var fieldInfo in typeof(WebConfigVM).GetProperties()) { //获取是否需要加密 bool IsNeedEncrypt = false; { EncryptFieldAttribute ef = Attribute.GetCustomAttribute(fieldInfo, typeof(EncryptFieldAttribute)) as EncryptFieldAttribute; if (ef != null) { IsNeedEncrypt = ef.NeedEncrypt; } } //获取数值 string value = ""; var rawValue = fieldInfo.GetValue(model); if (rawValue is string) { value = rawValue as string; } else if (rawValue is Enum) { value = rawValue.GetHashCode().ToString(); } //密码类型,如果空白则保持不变 { DataTypeAttribute da = Attribute.GetCustomAttribute(fieldInfo, typeof(DataTypeAttribute)) as DataTypeAttribute; if (da != null && da.DataType == DataType.Password && String.IsNullOrEmpty(value)) { value = EG.Business.Common.ConfigCache.GetAppConfig(fieldInfo.Name); } } //写入 WriteValue(xeAppsetting, fieldInfo.Name, value, IsNeedEncrypt ? userKey : null); } //最终一次性写入 xdoc.Save(configPath); //返回结果 return(Json(new { IsSuccess = true })); } catch (Exception ex) { //返回结果 return(Json(new { IsSuccess = false, Message = ex.Message })); } }
// This is a faster version of GetDataTypeName(). It internally calls ToString() on the enum // value, which can be quite slow because of value verification. internal static string ToDataTypeName(this DataTypeAttribute attribute, Func <DataTypeAttribute, Boolean> isDataType = null) { if (isDataType == null) { isDataType = t => t.GetType().Equals(typeof(DataTypeAttribute)); } // GetDataTypeName is virtual, so this is only safe if they haven't derived from DataTypeAttribute. // However, if they derive from DataTypeAttribute, they can help their own perf by overriding GetDataTypeName // and returning an appropriate string without invoking the ToString() on the enum. if (isDataType(attribute)) { switch (attribute.DataType) { case DataType.Currency: return(CurrencyTypeName); case DataType.Date: return(DateTypeName); case DataType.DateTime: return(DateTimeTypeName); case DataType.Duration: return(DurationTypeName); case DataType.EmailAddress: return(EmailAddressTypeName); case DataType.Html: return(HtmlTypeName); case DataType.ImageUrl: return(ImageUrlTypeName); case DataType.MultilineText: return(MultiLineTextTypeName); case DataType.Password: return(PasswordTypeName); case DataType.PhoneNumber: return(PhoneNumberTypeName); case DataType.Text: return(TextTypeName); case DataType.Time: return(TimeTypeName); case DataType.Url: return(UrlTypeName); case DataType.CreditCard: return(CreditCardTypeName); case DataType.PostalCode: return(PostalCodeTypeName); case DataType.Upload: return(UploadTypeName); } } return(attribute.GetDataTypeName()); }
public DataTypeAttributeRewriter(DataTypeAttribute dataTypeAttribute) { this.attribute = dataTypeAttribute; }
//public override IEnumerable<ModelMetadata> GetMetadataForProperties(object container, Type containerType) //{ // return base.GetMetadataForProperties(container, containerType); //} //public override ModelMetadata GetMetadataForType(Func<object> modelAccessor, Type modelType) //{ // return base.GetMetadataForType(modelAccessor, modelType); //} //public override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, string propertyName) //{ // return base.GetMetadataForProperty(modelAccessor, containerType, propertyName); //} //protected override ModelMetadata GetMetadataForProperty(Func<object> modelAccessor, Type containerType, System.ComponentModel.PropertyDescriptor propertyDescriptor) //{ // return base.GetMetadataForProperty(modelAccessor, containerType, propertyDescriptor); //} protected override ModelMetadata CreateMetadata(IEnumerable <Attribute> attributes, Type containerType, Func <object> modelAccessor, Type modelType, string propertyName) { //Reflected from base class List <Attribute> list = new List <Attribute>(attributes); DisplayColumnAttribute displayColumnAttribute = Enumerable.FirstOrDefault <DisplayColumnAttribute>(Enumerable.OfType <DisplayColumnAttribute>((IEnumerable)list)); DataAnnotationsModelMetadata annotationsModelMetadata = null; //brl additions //if this is a BOV backed object if (containerType != null && Attribute.IsDefined(containerType, typeof(DryLogicObjectAttribute)) && propertyName != "OI") { Object container = null; ObjectInstance oi = null; //By having this code here instead of in GetMetadataForProperty, some of the normal features like ui hint will work if (modelAccessor != null) { var rootModelType = modelAccessor.Target.GetType(); var field = rootModelType.GetField("container"); if (field != null) { container = field.GetValue(modelAccessor.Target); //if we don't have a reference to the container yet... if (container.GetType() != containerType) { //...then try to break down the expression to get it //get the expression as text, ie "model.EmployeeViewModel.MyEmployee" and split it var expressionParts = ((LambdaExpression)rootModelType.GetField("expression").GetValue(modelAccessor.Target)).Body.ToString().Split('.'); //var expressionParts = new string[] { }; //loop thru the parts in the middle for (int i = 1; i < expressionParts.Length - 1; i++) { container = container.GetType().GetProperty(expressionParts[i]).GetValue(container); } } //could use an attribute instead to identify the object instance oi = ObjectInstance.GetObjectInstance(container); if (oi != null)//not really sure how this woudl fail at this point { annotationsModelMetadata = new PropertyValueMetadata(this, containerType, modelAccessor, modelType, propertyName, displayColumnAttribute); annotationsModelMetadata.Container = container; //internally, setting model wipes out modelAccessor (caching of sorts) annotationsModelMetadata.Model = oi.PropertyValues[propertyName]; annotationsModelMetadata.TemplateHint = "PropertyValue"; } } } } if (annotationsModelMetadata == null) { annotationsModelMetadata = new DataAnnotationsModelMetadata(this, containerType, modelAccessor, modelType, propertyName, displayColumnAttribute); } HiddenInputAttribute hiddenInputAttribute = Enumerable.FirstOrDefault <HiddenInputAttribute>(Enumerable.OfType <HiddenInputAttribute>((IEnumerable)list)); if (hiddenInputAttribute != null) { annotationsModelMetadata.TemplateHint = "HiddenInput"; annotationsModelMetadata.HideSurroundingHtml = !hiddenInputAttribute.DisplayValue; } IEnumerable <UIHintAttribute> source = Enumerable.OfType <UIHintAttribute>((IEnumerable)list); UIHintAttribute uiHintAttribute = Enumerable.FirstOrDefault <UIHintAttribute>(source, (Func <UIHintAttribute, bool>)(a => string.Equals(a.PresentationLayer, "MVC", StringComparison.OrdinalIgnoreCase))) ?? Enumerable.FirstOrDefault <UIHintAttribute>(source, (Func <UIHintAttribute, bool>)(a => string.IsNullOrEmpty(a.PresentationLayer))); if (uiHintAttribute != null) { annotationsModelMetadata.TemplateHint = uiHintAttribute.UIHint; } DataTypeAttribute attribute = Enumerable.FirstOrDefault <DataTypeAttribute>(Enumerable.OfType <DataTypeAttribute>((IEnumerable)list)); if (attribute != null) { annotationsModelMetadata.DataTypeName = DataTypeUtil.ToDataTypeName(attribute, (Func <DataTypeAttribute, bool>)null); } EditableAttribute editableAttribute = Enumerable.FirstOrDefault <EditableAttribute>(Enumerable.OfType <EditableAttribute>((IEnumerable)attributes)); if (editableAttribute != null) { annotationsModelMetadata.IsReadOnly = !editableAttribute.AllowEdit; } else { ReadOnlyAttribute readOnlyAttribute = Enumerable.FirstOrDefault <ReadOnlyAttribute>(Enumerable.OfType <ReadOnlyAttribute>((IEnumerable)list)); if (readOnlyAttribute != null) { annotationsModelMetadata.IsReadOnly = readOnlyAttribute.IsReadOnly; } } DisplayFormatAttribute displayFormatAttribute = Enumerable.FirstOrDefault <DisplayFormatAttribute>(Enumerable.OfType <DisplayFormatAttribute>((IEnumerable)list)); if (displayFormatAttribute == null && attribute != null) { displayFormatAttribute = attribute.DisplayFormat; } if (displayFormatAttribute != null) { annotationsModelMetadata.NullDisplayText = displayFormatAttribute.NullDisplayText; annotationsModelMetadata.DisplayFormatString = displayFormatAttribute.DataFormatString; annotationsModelMetadata.ConvertEmptyStringToNull = displayFormatAttribute.ConvertEmptyStringToNull; if (displayFormatAttribute.ApplyFormatInEditMode) { annotationsModelMetadata.EditFormatString = displayFormatAttribute.DataFormatString; } if (!displayFormatAttribute.HtmlEncode && string.IsNullOrWhiteSpace(annotationsModelMetadata.DataTypeName)) { annotationsModelMetadata.DataTypeName = DataTypeUtil.HtmlTypeName; } } ScaffoldColumnAttribute scaffoldColumnAttribute = Enumerable.FirstOrDefault <ScaffoldColumnAttribute>(Enumerable.OfType <ScaffoldColumnAttribute>((IEnumerable)list)); if (scaffoldColumnAttribute != null) { annotationsModelMetadata.ShowForDisplay = annotationsModelMetadata.ShowForEdit = scaffoldColumnAttribute.Scaffold; } DisplayAttribute displayAttribute = Enumerable.FirstOrDefault <DisplayAttribute>(Enumerable.OfType <DisplayAttribute>((IEnumerable)attributes)); string str = (string)null; if (displayAttribute != null) { annotationsModelMetadata.Description = displayAttribute.GetDescription(); annotationsModelMetadata.ShortDisplayName = displayAttribute.GetShortName(); annotationsModelMetadata.Watermark = displayAttribute.GetPrompt(); annotationsModelMetadata.Order = displayAttribute.GetOrder() ?? 10000; str = displayAttribute.GetName(); } if (str != null) { annotationsModelMetadata.DisplayName = str; } else { DisplayNameAttribute displayNameAttribute = Enumerable.FirstOrDefault <DisplayNameAttribute>(Enumerable.OfType <DisplayNameAttribute>((IEnumerable)list)); if (displayNameAttribute != null) { annotationsModelMetadata.DisplayName = displayNameAttribute.DisplayName; } } if (Enumerable.FirstOrDefault <RequiredAttribute>(Enumerable.OfType <RequiredAttribute>((IEnumerable)list)) != null) { annotationsModelMetadata.IsRequired = true; } return((ModelMetadata)annotationsModelMetadata); }
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 static void SetFromDataTypeAndDisplayAttributes( DataAnnotationsModelMetadata result, DataTypeAttribute dataTypeAttribute, DisplayFormatAttribute displayFormatAttribute ) { if (dataTypeAttribute != null) { result.DataTypeName = dataTypeAttribute.ToDataTypeName(); } if (displayFormatAttribute == null && dataTypeAttribute != null) { displayFormatAttribute = dataTypeAttribute.DisplayFormat; // If DisplayFormat value was non-null and this [DataType] is of a subclass, assume the [DataType] // constructor used the protected DisplayFormat setter to override its default. Note deriving from // [DataType] but preserving DataFormatString and ApplyFormatInEditMode results in // HasNonDefaultEditFormat==true. if ( displayFormatAttribute != null && dataTypeAttribute.GetType() != typeof(DataTypeAttribute) ) { result.HasNonDefaultEditFormat = true; } } else if (displayFormatAttribute != null) { result.HasNonDefaultEditFormat = true; } if (displayFormatAttribute != null) { result.NullDisplayText = displayFormatAttribute.NullDisplayText; result.DisplayFormatString = displayFormatAttribute.DataFormatString; result.ConvertEmptyStringToNull = displayFormatAttribute.ConvertEmptyStringToNull; result.HtmlEncode = displayFormatAttribute.HtmlEncode; if (displayFormatAttribute.ApplyFormatInEditMode) { result.EditFormatString = displayFormatAttribute.DataFormatString; } if ( !displayFormatAttribute.HtmlEncode && String.IsNullOrWhiteSpace(result.DataTypeName) ) { result.DataTypeName = DataTypeUtil.HtmlTypeName; } // Regardless of HasNonDefaultEditFormat calculation above, treat missing EditFormatString as the // default. Note the corner case of a [DataType] subclass overriding a non-empty default to apply a // [DisplayFormat] lacking DataFormatString or with ApplyFormatInEditMode==false results in // HasNonDefaultEditFormat==false. if (String.IsNullOrEmpty(result.EditFormatString)) { result.HasNonDefaultEditFormat = false; } } }
public DataTypeAttributeAdapter(ModelMetadata metadata, AngularBindingContext context, DataTypeAttribute attribute, string ruleName) : base(metadata, context, attribute) { RuleName = ruleName; //?? attribute.DataType.ToString().ToLower(CultureInfo.CurrentCulture); _dataType = attribute.DataType; }
private static Rule GetRule(ValidationAttribute attribute) { Rule rule = null; if (attribute is RequiredAttribute) { rule = new Rule { Name = "required", Options = true }; } else if (attribute is RangeAttribute) { RangeAttribute rangeAttribute = (RangeAttribute)attribute; rule = new Rule { Name = "range", Options = new[] { rangeAttribute.Minimum, rangeAttribute.Maximum } }; } else if (attribute is StringLengthAttribute) { StringLengthAttribute stringLengthAttribute = (StringLengthAttribute)attribute; rule = new Rule { Name = "rangelength", Options = new[] { stringLengthAttribute.MinimumLength, stringLengthAttribute.MaximumLength } }; } else if (attribute is DataTypeAttribute) { DataTypeAttribute dataTypeAttribute = (DataTypeAttribute)attribute; switch (dataTypeAttribute.DataType) { case DataType.Date: case DataType.DateTime: rule = new Rule { Name = "date", Options = true }; break; case DataType.Time: rule = new Rule { Name = "time", Options = true }; break; case DataType.PhoneNumber: rule = new Rule { Name = "phoneUS", Options = true }; break; case DataType.EmailAddress: rule = new Rule { Name = "email", Options = true }; break; case DataType.Url: rule = new Rule { Name = "url", Options = true }; break; case DataType.Currency: case DataType.Text: case DataType.Html: case DataType.MultilineText: case DataType.Password: case DataType.Duration: case DataType.Custom: default: throw new ArgumentOutOfRangeException(); } } if (rule != null) { rule.Message = attribute.FormatErrorMessage(String.Empty); } return(rule); }
public TypePropertyMetadata(PropertyDescriptor descriptor) { this.Name = descriptor.Name; if (IsCollectionType(descriptor.PropertyType)) { Type type = TypeUtility.GetElementType(descriptor.PropertyType); // String is assignable from IEnumerable, but it is not an array in JavaScript. // Manually ignoring this if the type is the same as the descriptor.PropertyType this.IsArray = type.Equals(descriptor.PropertyType) ? false : true; this.TypeName = type.Name; this.TypeNamespace = type.Namespace; } else { this.IsArray = false; this.TypeName = descriptor.PropertyType.Name; this.TypeNamespace = descriptor.PropertyType.Namespace; } AttributeCollection propertyAttributes = descriptor.Attributes; ReadOnlyAttribute readonlyAttr = (ReadOnlyAttribute)propertyAttributes[typeof(ReadOnlyAttribute)]; this.IsReadOnly = (readonlyAttr != null) ? readonlyAttr.IsReadOnly : false; AssociationAttribute associationAttr = (AssociationAttribute)propertyAttributes[typeof(AssociationAttribute)]; if (associationAttr != null) { this.Association = new TypePropertyAssociationMetadata(associationAttr); } foreach (Attribute attribute in propertyAttributes) { if (attribute is RequiredAttribute) { this.validationRules.Add(new TypePropertyValidationRuleMetadata((RequiredAttribute)attribute)); } else if (attribute is RangeAttribute) { RangeAttribute rangeAttribute = (RangeAttribute)attribute; if (rangeAttribute.OperandType.Equals(typeof(Double)) || rangeAttribute.OperandType.Equals(typeof(Int16)) || rangeAttribute.OperandType.Equals(typeof(Int32)) || rangeAttribute.OperandType.Equals(typeof(Int64)) || rangeAttribute.OperandType.Equals(typeof(Single))) { this.validationRules.Add(new TypePropertyValidationRuleMetadata(rangeAttribute)); } } else if (attribute is StringLengthAttribute) { this.validationRules.Add(new TypePropertyValidationRuleMetadata((StringLengthAttribute)attribute)); } else if (attribute is DataTypeAttribute) { DataTypeAttribute dataTypeAttribute = (DataTypeAttribute)attribute; if (dataTypeAttribute.DataType.Equals(DataType.EmailAddress) || dataTypeAttribute.DataType.Equals(DataType.Url)) { this.validationRules.Add(new TypePropertyValidationRuleMetadata(dataTypeAttribute)); } } } }
protected override ModelMetadata CreateMetadata(IEnumerable <Attribute> attributes, Type containerType, Func <object> modelAccessor, Type modelType, string propertyName) { List <Attribute> attributeList = new List <Attribute>(attributes); DisplayColumnAttribute displayColumnAttribute = attributeList.OfType <DisplayColumnAttribute>().FirstOrDefault(); DataAnnotationsModelMetadata result = new DataAnnotationsModelMetadata(this, containerType, modelAccessor, modelType, propertyName, displayColumnAttribute); // Do [HiddenInput] before [UIHint], so you can override the template hint HiddenInputAttribute hiddenInputAttribute = attributeList.OfType <HiddenInputAttribute>().FirstOrDefault(); if (hiddenInputAttribute != null) { result.TemplateHint = "HiddenInput"; result.HideSurroundingHtml = !hiddenInputAttribute.DisplayValue; } // We prefer [UIHint("...", PresentationLayer = "MVC")] but will fall back to [UIHint("...")] IEnumerable <UIHintAttribute> uiHintAttributes = attributeList.OfType <UIHintAttribute>(); UIHintAttribute uiHintAttribute = uiHintAttributes.FirstOrDefault(a => String.Equals(a.PresentationLayer, "MVC", StringComparison.OrdinalIgnoreCase)) ?? uiHintAttributes.FirstOrDefault(a => String.IsNullOrEmpty(a.PresentationLayer)); if (uiHintAttribute != null) { result.TemplateHint = uiHintAttribute.UIHint; } DataTypeAttribute dataTypeAttribute = attributeList.OfType <DataTypeAttribute>().FirstOrDefault(); if (dataTypeAttribute != null) { result.DataTypeName = dataTypeAttribute.GetDataTypeName(); } ReadOnlyAttribute readOnlyAttribute = attributeList.OfType <ReadOnlyAttribute>().FirstOrDefault(); if (readOnlyAttribute != null) { result.IsReadOnly = readOnlyAttribute.IsReadOnly; } DisplayFormatAttribute displayFormatAttribute = attributeList.OfType <DisplayFormatAttribute>().FirstOrDefault(); if (displayFormatAttribute == null && dataTypeAttribute != null) { displayFormatAttribute = dataTypeAttribute.DisplayFormat; } if (displayFormatAttribute != null) { result.NullDisplayText = displayFormatAttribute.NullDisplayText; result.DisplayFormatString = displayFormatAttribute.DataFormatString; result.ConvertEmptyStringToNull = displayFormatAttribute.ConvertEmptyStringToNull; if (displayFormatAttribute.ApplyFormatInEditMode) { result.EditFormatString = displayFormatAttribute.DataFormatString; } } ScaffoldColumnAttribute scaffoldColumnAttribute = attributeList.OfType <ScaffoldColumnAttribute>().FirstOrDefault(); if (scaffoldColumnAttribute != null) { result.ShowForDisplay = result.ShowForEdit = scaffoldColumnAttribute.Scaffold; } DisplayNameAttribute displayNameAttribute = attributeList.OfType <DisplayNameAttribute>().FirstOrDefault(); if (displayNameAttribute != null) { result.DisplayName = displayNameAttribute.DisplayName; } RequiredAttribute requiredAttribute = attributeList.OfType <RequiredAttribute>().FirstOrDefault(); if (requiredAttribute != null) { result.IsRequired = true; } return(result); }
static string ToStataDo(Type collectionType, IEnumerable collection) { var convertedList = ToStringValues(collectionType, collection, new DataTypeOption(typeof(string),(s,attr) => ToStataString((string)s)), new DataTypeOption(typeof(char),(c,attr) => ToStataString(c.ToString())), new DataTypeOption(typeof(char[]),(c,attr) => ToStataString(new string((char[])c))), new DataTypeOption(typeof(DateTime),(d, atts)=> { var dataType = (DataTypeAttribute)atts.FirstOrDefault(a => a.GetType() == typeof(DataTypeAttribute)); if (dataType != null) { if (dataType.DataType == DataType.Date) { return TicksToStataDate(((DateTime)d).Ticks); } } return TicksToStataDateTime(((DateTime)d).Ticks); }), new DataTypeOption(typeof(TimeSpan),(ts,attr)=>((TimeSpan)ts).Milliseconds.ToString()), // note these 2 are not tested yet as they new DataTypeOption(typeof(DateTimeOffset), (d, attr) => TicksToStataDateTime(((DateTimeOffset)d).UtcTicks))); // are never used by myself within data repositories int rows = convertedList.StringValues.Length; StringBuilder sb = new StringBuilder(string.Format("set obs {0}\r\n", rows)); for (int c=0;c<convertedList.PropertiesDetail.Count;c++) { string propName = convertedList.PropertiesDetail[c].Name; Type baseType = convertedList.PropertiesDetail[c].BaseType; TypeCode propType = Type.GetTypeCode(baseType); if (propType == TypeCode.Object) { if (baseType == typeof(TimeSpan)) { propType = TypeCode.Double; } else if (baseType == typeof(DateTimeOffset)) { propType = TypeCode.DateTime; } else if (baseType == typeof(char[])) { propType = TypeCode.String; } } switch (propType) { case TypeCode.Byte: case TypeCode.Boolean: sb.AppendFormat("generate byte {0} = .\r\n", propName); break; case TypeCode.Char: sb.AppendFormat("generate str1 {0} = \"\"\r\n",propName); break; case TypeCode.String: sb.AppendFormat("generate str{0} {1} = \"\"\r\n", (new int[]{ 1, convertedList.StringValues.Max(r => r[c].Length) - StataStringChars}).Max(), propName); break; case TypeCode.Int16: sb.AppendFormat("generate int {0} = .\r\n",propName); break; case TypeCode.Int32: case TypeCode.Int64: sb.AppendFormat("generate long {0} = .\r\n",propName); break; case TypeCode.Single: sb.AppendFormat("generate float {0} = .\r\n",propName); break; case TypeCode.Double: sb.AppendFormat("generate double {0} = .\r\n",propName); break; case TypeCode.DateTime: DataTypeAttribute dataType = (DataTypeAttribute)convertedList.PropertiesDetail[c].Attributes.FirstOrDefault(a => a.GetType() == typeof(DataTypeAttribute)); if (dataType != null && dataType.DataType == DataType.Date) { sb.AppendFormat("generate long {0} = .\r\nformat {0} %td\r\n", propName); } else { sb.AppendFormat("generate double {0} = .\r\nformat {0} %tc\r\n",propName); } break; } DisplayAttribute display = (DisplayAttribute)convertedList.PropertiesDetail[c].Attributes.FirstOrDefault(a => a.GetType() == typeof(DisplayAttribute)); sb.AppendFormat("label variable {0} \"{1}\"\r\n",propName, (display==null || string.IsNullOrEmpty(display.Name)) ? propName.ToSeparatedWords() : display.Name); for (int r=0;r<rows;r++) { string nextVal = convertedList.StringValues[r][c]; if (nextVal != string.Empty) { sb.AppendFormat("replace {0} = {1} in {2}\r\n", propName, nextVal, r+1); } } } return sb.ToString(); }
public static Metadata Create(MemberInfo memberInfo) { if (memberInfo == null) { throw new ArgumentNullException("memberInfo"); } Metadata metadata = new Metadata(); // Name metadata.Name = memberInfo.Name; // DisplayAttribute DisplayAttribute displayAttribute = memberInfo.GetCustomAttribute <DisplayAttribute>(); if (displayAttribute != null) { metadata.DisplayName = displayAttribute.GetName(); metadata.ShortName = displayAttribute.GetShortName(); metadata.GroupName = displayAttribute.GetGroupName(); metadata.Description = displayAttribute.GetDescription(); int?order = displayAttribute.GetOrder(); if (order != null) { metadata.Order = order.Value; } } if (metadata.DisplayName == null) { metadata.DisplayName = ConvertUtilities.Decamelize(metadata.Name); } // DataType DataTypeAttribute dataTypeAttribute = memberInfo.GetCustomAttribute <DataTypeAttribute>(); if (dataTypeAttribute != null) { metadata.DataType = dataTypeAttribute.GetDataTypeName(); Fill(metadata, dataTypeAttribute.DisplayFormat); } if (metadata.DataType == null) { PropertyInfo pi = memberInfo as PropertyInfo; if (pi != null) { metadata.DataType = pi.PropertyType.AssemblyQualifiedName; } else { FieldInfo fi = memberInfo as FieldInfo; if (fi != null) { metadata.DataType = fi.FieldType.AssemblyQualifiedName; } } } // DisplayFormat DisplayFormatAttribute displayFormatAttribute = memberInfo.GetCustomAttribute <DisplayFormatAttribute>(); if (displayFormatAttribute != null) { Fill(metadata, displayFormatAttribute); } // ScaffoldColumnAttribute ScaffoldColumnAttribute scaffoldColumnAttribute = memberInfo.GetCustomAttribute <ScaffoldColumnAttribute>(); if (scaffoldColumnAttribute != null) { metadata.Hidden = scaffoldColumnAttribute.Scaffold; } return(metadata); }
private static IDataTypeFacet Create(DataTypeAttribute attribute, ISpecification holder) => attribute is null ? null : attribute.DataType == DataType.Custom ? new DataTypeFacetAnnotation(attribute.CustomDataType, holder) : new DataTypeFacetAnnotation(attribute.DataType, holder);
public TypePropertyMetadata(PropertyDescriptor descriptor) { Name = descriptor.Name; Type elementType = TypeUtility.GetElementType(descriptor.PropertyType); IsArray = !elementType.Equals(descriptor.PropertyType); // TODO: What should we do with nullable types here? TypeName = elementType.Name; TypeNamespace = elementType.Namespace; AttributeCollection propertyAttributes = TypeDescriptorExtensions.ExplicitAttributes(descriptor); // TODO, 336102, ReadOnlyAttribute for editability? RIA used EditableAttribute? ReadOnlyAttribute readonlyAttr = (ReadOnlyAttribute)propertyAttributes[typeof(ReadOnlyAttribute)]; IsReadOnly = (readonlyAttr != null) ? readonlyAttr.IsReadOnly : false; AssociationAttribute associationAttr = (AssociationAttribute)propertyAttributes[typeof(AssociationAttribute)]; if (associationAttr != null) { Association = new TypePropertyAssociationMetadata(associationAttr); } RequiredAttribute requiredAttribute = (RequiredAttribute)propertyAttributes[typeof(RequiredAttribute)]; if (requiredAttribute != null) { _validationRules.Add(new TypePropertyValidationRuleMetadata(requiredAttribute)); } RangeAttribute rangeAttribute = (RangeAttribute)propertyAttributes[typeof(RangeAttribute)]; if (rangeAttribute != null) { Type operandType = rangeAttribute.OperandType; operandType = Nullable.GetUnderlyingType(operandType) ?? operandType; if (operandType.Equals(typeof(Double)) || operandType.Equals(typeof(Int16)) || operandType.Equals(typeof(Int32)) || operandType.Equals(typeof(Int64)) || operandType.Equals(typeof(Single))) { _validationRules.Add(new TypePropertyValidationRuleMetadata(rangeAttribute)); } } StringLengthAttribute stringLengthAttribute = (StringLengthAttribute)propertyAttributes[typeof(StringLengthAttribute)]; if (stringLengthAttribute != null) { _validationRules.Add(new TypePropertyValidationRuleMetadata(stringLengthAttribute)); } DataTypeAttribute dataTypeAttribute = (DataTypeAttribute)propertyAttributes[typeof(DataTypeAttribute)]; if (dataTypeAttribute != null) { if (dataTypeAttribute.DataType.Equals(DataType.EmailAddress) || dataTypeAttribute.DataType.Equals(DataType.Url)) { _validationRules.Add(new TypePropertyValidationRuleMetadata(dataTypeAttribute)); } } }
protected override ModelMetadata CreateMetadata(IEnumerable <Attribute> attributes, Type containerType, Func <object> modelAccessor, Type modelType, string propertyName) { List <Attribute> attributeList = new List <Attribute>(attributes); DisplayColumnAttribute displayColumnAttribute = attributeList.OfType <DisplayColumnAttribute>().FirstOrDefault(); DataAnnotationsModelMetadata result = new DataAnnotationsModelMetadata(this, containerType, modelAccessor, modelType, propertyName, displayColumnAttribute); // Do [HiddenInput] before [UIHint], so you can override the template hint HiddenInputAttribute hiddenInputAttribute = attributeList.OfType <HiddenInputAttribute>().FirstOrDefault(); if (hiddenInputAttribute != null) { result.TemplateHint = "HiddenInput"; result.HideSurroundingHtml = !hiddenInputAttribute.DisplayValue; } // We prefer [UIHint("...", PresentationLayer = "MVC")] but will fall back to [UIHint("...")] IEnumerable <UIHintAttribute> uiHintAttributes = attributeList.OfType <UIHintAttribute>(); UIHintAttribute uiHintAttribute = uiHintAttributes.FirstOrDefault(a => String.Equals(a.PresentationLayer, "MVC", StringComparison.OrdinalIgnoreCase)) ?? uiHintAttributes.FirstOrDefault(a => String.IsNullOrEmpty(a.PresentationLayer)); if (uiHintAttribute != null) { result.TemplateHint = uiHintAttribute.UIHint; } EditableAttribute editable = attributes.OfType <EditableAttribute>().FirstOrDefault(); if (editable != null) { result.IsReadOnly = !editable.AllowEdit; } else { ReadOnlyAttribute readOnlyAttribute = attributeList.OfType <ReadOnlyAttribute>().FirstOrDefault(); if (readOnlyAttribute != null) { result.IsReadOnly = readOnlyAttribute.IsReadOnly; } } DataTypeAttribute dataTypeAttribute = attributeList.OfType <DataTypeAttribute>().FirstOrDefault(); DisplayFormatAttribute displayFormatAttribute = attributeList.OfType <DisplayFormatAttribute>().FirstOrDefault(); SetFromDataTypeAndDisplayAttributes(result, dataTypeAttribute, displayFormatAttribute); ScaffoldColumnAttribute scaffoldColumnAttribute = attributeList.OfType <ScaffoldColumnAttribute>().FirstOrDefault(); if (scaffoldColumnAttribute != null) { result.ShowForDisplay = result.ShowForEdit = scaffoldColumnAttribute.Scaffold; } DisplayAttribute display = attributes.OfType <DisplayAttribute>().FirstOrDefault(); string name = null; if (display != null) { result.Description = display.GetDescription(); result.ShortDisplayName = display.GetShortName(); result.Watermark = display.GetPrompt(); result.Order = display.GetOrder() ?? ModelMetadata.DefaultOrder; name = display.GetName(); } if (name != null) { result.DisplayName = name; } else { DisplayNameAttribute displayNameAttribute = attributeList.OfType <DisplayNameAttribute>().FirstOrDefault(); if (displayNameAttribute != null) { result.DisplayName = displayNameAttribute.DisplayName; } } RequiredAttribute requiredAttribute = attributeList.OfType <RequiredAttribute>().FirstOrDefault(); if (requiredAttribute != null) { result.IsRequired = true; } return(result); }
public DataTypeAttributeAdapter(ModelMetadata metadata, ControllerContext context, DataTypeAttribute attribute, string ruleName) : base(metadata, context, attribute) { if (String.IsNullOrEmpty(ruleName)) { throw new ArgumentException(MvcResources.Common_NullOrEmpty, "ruleName"); } RuleName = ruleName; }
private static IPasswordFacet Create(DataTypeAttribute attribute, ISpecification holder) => attribute is not null && attribute.DataType == DataType.Password ? new PasswordFacet(holder) : null;
public static void GetDataTypeName_InvalidDataType_ThrowsIndexOutOfRangeException(DataType dataType) { DataTypeAttribute attribute = new DataTypeAttribute(dataType); Assert.Throws <IndexOutOfRangeException>(() => attribute.GetDataTypeName()); }
public T[] GetAttributes <T>(MemberInfo memberInfo, bool inherit) where T : Attribute { if (typeof(T) == typeof(Sql.ExpressionAttribute) && (memberInfo.IsMethodEx() || memberInfo.IsPropertyEx())) { object attrs; if (!_cache.TryGetValue(memberInfo, out attrs)) { if (memberInfo.IsMethodEx()) { var ma = _reader.GetAttributes <SqlMethodAttribute>(memberInfo); if (ma.Length > 0) { var mi = (MethodInfo)memberInfo; var ps = mi.GetParameters(); var ex = mi.IsStatic ? "{0}::{1}({2})".Args( memberInfo.DeclaringType.Name.ToLower().StartsWith("sql") ? memberInfo.DeclaringType.Name.Substring(3) : memberInfo.DeclaringType.Name, ma[0].Name ?? memberInfo.Name, string.Join(", ", ps.Select((_, i) => '{' + i.ToString() + '}').ToArray())) : "{{0}}.{0}({1})".Args( ma[0].Name ?? memberInfo.Name, string.Join(", ", ps.Select((_, i) => '{' + (i + 1).ToString() + '}').ToArray())); attrs = new [] { (T)(Attribute) new Sql.ExpressionAttribute(ex) { ServerSideOnly = true } }; } else { attrs = Array <T> .Empty; } } else { var pi = (PropertyInfo)memberInfo; var gm = pi.GetGetMethod(); if (gm != null) { var ma = _reader.GetAttributes <SqlMethodAttribute>(gm); if (ma.Length > 0) { var ex = "{{0}}.{0}".Args(ma[0].Name ?? memberInfo.Name); attrs = new [] { (T)(Attribute) new Sql.ExpressionAttribute(ex) { ServerSideOnly = true, ExpectExpression = true } }; } else { attrs = Array <T> .Empty; } } else { attrs = Array <T> .Empty; } } _cache[memberInfo] = attrs; } return((T[])attrs); } if (typeof(T) == typeof(DataTypeAttribute)) { var attrs = _reader.GetAttributes <SqlUserDefinedTypeAttribute>(memberInfo.GetMemberType(), inherit); if (attrs.Length == 1) { var c = attrs[0]; var n = c.Name ?? memberInfo.GetMemberType().Name; if (n.ToLower().StartsWith("sql")) { n = n.Substring(3); } var attr = new DataTypeAttribute(DataType.Udt, n); return(new[] { (T)(Attribute)attr }); } } return(Array <T> .Empty); }
public static void GetDataTypeName_InvalidDataType_ThrowsIndexOutOfRangeException(DataType dataType) { DataTypeAttribute attribute = new DataTypeAttribute(dataType); Assert.Throws<IndexOutOfRangeException>(() => attribute.GetDataTypeName()); }
private static void CreateTableCommSetting(DataTypeAttribute dataTypeAttribute, ref StringBuilder sql) { sql.Append(dataTypeAttribute == null || dataTypeAttribute.IsNullable ? " NULL," : " NOT NULL,"); }
public static void DisplayFormat_ReturnsExpected(DataType dataType, string dataFormatString, bool applyFormatInEditMode) { DataTypeAttribute attribute = new DataTypeAttribute(dataType); Assert.Equal(dataFormatString, attribute.DisplayFormat.DataFormatString); Assert.Equal(applyFormatInEditMode, attribute.DisplayFormat.ApplyFormatInEditMode); }
/// <summary> /// 使用指定的类型名称初始化 <see cref="DataTypeValidatorAttribute"/> 类的新实例。 /// </summary> /// <param name="dataType">要与数据字段关联的类型的名称。</param> public DataTypeValidatorAttribute(DataType dataType) { _dataTypeAttribute = new DataTypeAttribute(dataType); }