// 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)) { // Statically known dataTypes are handled separately for performance string name = KnownDataTypeToString(attribute.DataType); if (name == null) { // Unknown types fallback to a dictionary lookup. // 4.0 will not enter this code for statically known data types. // 4.5 will enter this code for the new data types added to 4.5. _dataTypeToName.Value.TryGetValue(attribute.DataType, out name); } if (name != null) { return(name); } } return(attribute.GetDataTypeName()); }
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 static void Ctor_String(string customDataType, bool valid) { DataTypeAttribute attribute = new DataTypeAttribute(customDataType); Assert.Equal(DataType.Custom, attribute.DataType); Assert.Equal(customDataType, attribute.CustomDataType); if (valid) { Assert.Equal(customDataType, attribute.GetDataTypeName()); } else { Assert.Throws <InvalidOperationException>(() => attribute.GetDataTypeName()); Assert.Throws <InvalidOperationException>(() => attribute.Validate(new object(), s_testValidationContext)); } }
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 GetDataTypeName_ReturnsExpectedName(DataType dataType) { if (dataType != DataType.Custom) { DataTypeAttribute attribute = new DataTypeAttribute(dataType); Assert.Equal(Enum.GetName(typeof(DataType), dataType), attribute.GetDataTypeName()); } }
// 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); } } return(attribute.GetDataTypeName()); }
internal static string ToDataTypeName(this DataTypeAttribute attribute, Func <DataTypeAttribute, bool> isDataType = null) { if (isDataType == null) { isDataType = (Func <DataTypeAttribute, bool>)(t => t.GetType().Equals(typeof(DataTypeAttribute))); } if (isDataType(attribute)) { string str = DataTypeUtil.KnownDataTypeToString(attribute.DataType); if (str == null) { DataTypeUtil._dataTypeToName.Value.TryGetValue((object)attribute.DataType, out str); } if (str != null) { return(str); } } return(attribute.GetDataTypeName()); }
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); }
public static void GetDataTypeName_InvalidDataType_ThrowsIndexOutOfRangeException(DataType dataType) { DataTypeAttribute attribute = new DataTypeAttribute(dataType); Assert.Throws <IndexOutOfRangeException>(() => attribute.GetDataTypeName()); }
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(); 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 { /// 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())); } }
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 void GetDataTypeName_InvalidDataType_ThrowsIndexOutOfRangeException(DataType dataType) { DataTypeAttribute attribute = new DataTypeAttribute(dataType); Assert.Throws<IndexOutOfRangeException>(() => attribute.GetDataTypeName()); }
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); }