Beispiel #1
0
        public void DisplayAttribute_Resourced_Properties()
        {
            DisplayAttribute attr = new DisplayAttribute();

            attr.ResourceType = typeof(DisplayAttribute_Resources);

            Assert.IsNull(attr.GetShortName());
            Assert.IsNull(attr.GetName());
            Assert.IsNull(attr.GetPrompt());
            Assert.IsNull(attr.GetDescription());
            Assert.IsNull(attr.GetGroupName());

            attr.ShortName   = "Resource1";
            attr.Name        = "Resource2";
            attr.Prompt      = "Resource3";
            attr.Description = "Resource4";
            attr.GroupName   = "Resource5";

            Assert.AreEqual("string1", attr.GetShortName());
            Assert.AreEqual("string2", attr.GetName());
            Assert.AreEqual("string3", attr.GetPrompt());
            Assert.AreEqual("string4", attr.GetDescription());
            Assert.AreEqual("string5", attr.GetGroupName());

            Assert.AreEqual("Resource1", attr.ShortName);
            Assert.AreEqual("Resource2", attr.Name);
            Assert.AreEqual("Resource3", attr.Prompt);
            Assert.AreEqual("Resource4", attr.Description);
            Assert.AreEqual("Resource5", attr.GroupName);
        }
        public void DisplayAttribute_Resourced_Properties() {
            DisplayAttribute attr = new DisplayAttribute();

            attr.ResourceType = typeof(DisplayAttribute_Resources);

            Assert.IsNull(attr.GetShortName());
            Assert.IsNull(attr.GetName());
            Assert.IsNull(attr.GetPrompt());
            Assert.IsNull(attr.GetDescription());
            Assert.IsNull(attr.GetGroupName());

            attr.ShortName = "Resource1";
            attr.Name = "Resource2";
            attr.Prompt = "Resource3";
            attr.Description = "Resource4";
            attr.GroupName = "Resource5";

            Assert.AreEqual("string1", attr.GetShortName());
            Assert.AreEqual("string2", attr.GetName());
            Assert.AreEqual("string3", attr.GetPrompt());
            Assert.AreEqual("string4", attr.GetDescription());
            Assert.AreEqual("string5", attr.GetGroupName());

            Assert.AreEqual("Resource1", attr.ShortName);
            Assert.AreEqual("Resource2", attr.Name);
            Assert.AreEqual("Resource3", attr.Prompt);
            Assert.AreEqual("Resource4", attr.Description);
            Assert.AreEqual("Resource5", attr.GroupName);
        }
Beispiel #3
0
        public string LocalizedFilterColumn(string filterColumn)
        {
            DisplayAttribute attr = null;

            if (filterColumn.Contains("."))
            {
                var  chain = filterColumn.Split('.');
                Type mt    = typeof(T);
                foreach (var segment in chain)
                {
                    var pi = mt.GetProperty(segment);
                    if (segment == chain.Last())
                    {
                        attr = mt.GetProperty(segment).GetCustomAttributes(typeof(DisplayAttribute), true).Cast <DisplayAttribute>().SingleOrDefault();
                        if (attr == null)
                        {
                            return(filterColumn);
                        }
                        return(attr.GetName());
                    }
                    mt = pi.PropertyType;
                }
                return(filterColumn);
            }
            else
            {
                attr = typeof(T).GetProperty(filterColumn).GetCustomAttributes(typeof(DisplayAttribute), true).Cast <DisplayAttribute>().SingleOrDefault();
                if (attr == null)
                {
                    return(filterColumn);
                }
                return(attr.GetName());
            }
        }
Beispiel #4
0
        public void DisplayAttribute_Reflection_Test()
        {
            Type t = typeof(DisplayAttribute_Sample);

            FieldInfo fInfo = t.GetField("stringField");

            Assert.IsNotNull(fInfo);
            Assert.IsNotNull(fInfo.GetCustomAttributes(true).OfType <DisplayAttribute>().SingleOrDefault());

            PropertyInfo pInfo = t.GetProperty("LiteralStringProperty");

            Assert.IsNotNull(pInfo);
            DisplayAttribute attr = pInfo.GetCustomAttributes(true).OfType <DisplayAttribute>().SingleOrDefault();

            Assert.IsNotNull(attr);

            Assert.IsNull(attr.ResourceType);

            Assert.AreEqual("theShortName", attr.ShortName);
            Assert.AreEqual("theName", attr.Name);
            Assert.AreEqual("thePrompt", attr.Prompt);
            Assert.AreEqual("theDescription", attr.Description);
            Assert.AreEqual("theGroupName", attr.GroupName);


            Assert.AreEqual("theShortName", attr.GetShortName());
            Assert.AreEqual("theName", attr.GetName());
            Assert.AreEqual("thePrompt", attr.GetPrompt());
            Assert.AreEqual("theDescription", attr.GetDescription());
            Assert.AreEqual("theGroupName", attr.GetGroupName());


            pInfo = t.GetProperty("ResourcedStringProperty");
            Assert.IsNotNull(pInfo);
            attr = pInfo.GetCustomAttributes(true).OfType <DisplayAttribute>().SingleOrDefault();
            Assert.IsNotNull(attr);

            Assert.AreEqual(typeof(DisplayAttribute_Resources), attr.ResourceType);

            Assert.AreEqual("string1", attr.GetShortName());
            Assert.AreEqual("Resource1", attr.ShortName);

            Assert.AreEqual("string2", attr.GetName());
            Assert.AreEqual("Resource2", attr.Name);

            Assert.AreEqual("string3", attr.GetPrompt());
            Assert.AreEqual("Resource3", attr.Prompt);

            Assert.AreEqual("string4", attr.GetDescription());
            Assert.AreEqual("Resource4", attr.Description);

            Assert.AreEqual("string5", attr.GetGroupName());
            Assert.AreEqual("Resource5", attr.GroupName);
        }
Beispiel #5
0
        public static string GetDisplayName(this Enum value)
        {
            FieldInfo        field    = value.GetType().GetField(value.ToString());
            DisplayAttribute atributo = field.GetCustomAttribute <DisplayAttribute>(inherit: false);

            if (atributo != null)
            {
                return(atributo.GetName() != string.Empty ? atributo.GetName() : field.Name);
            }
            return(field.Name);
        }
Beispiel #6
0
        private void LoadThead(KeyValuePair <string, PropertyInfo> pair, DisplayAttribute display, List <TagBuilder> list, object value)
        {
            var tag = new TagBuilder("td");

            if (display != null && !string.IsNullOrEmpty(display.GetName()))
            {
                tag.Attributes.Add("name", pair.Key);
                tag.SetInnerText(display.GetName());
            }


            list.Add(tag);
        }
        public static string GetDisplayName <TModel, TProperty>(this Expression <Func <TModel, TProperty> > field)
        {
            var member = field.Body as MemberExpression;
            DisplayAttribute display = member.Member.GetCustomAttribute(typeof(DisplayAttribute)) as DisplayAttribute;

            if (display != null && !string.IsNullOrEmpty(display.GetName()))
            {
                return(display.GetName());
            }
            else
            {
                return(member.Member.Name.SplitCamelCase());
            }
        }
Beispiel #8
0
        /// <summary>
        ///
        /// </summary>
        /// <typeparam name="T"> </typeparam>
        /// <param name="obj"> </param>
        /// <param name="propertyName"> </param>
        /// <returns> </returns>
        public static string GetPropertyDisplayName <T>(this T obj, string propertyName) where T : NotifyPropertyBase
        {
            if (string.IsNullOrEmpty(propertyName))
            {
                return(string.Empty);
            }
            Type         tp    = obj.GetType();
            PropertyInfo pi    = tp.GetProperty(propertyName);
            var          value = pi.GetValue(obj, null);

            object[] Attributes = pi.GetCustomAttributes(false);
            string   strName    = "";

            if (Attributes != null && Attributes.Length > 0)
            {
                foreach (object attribute in Attributes)
                {
                    if (attribute is DisplayAttribute)
                    {
                        try
                        {
                            DisplayAttribute vAttribute = attribute as DisplayAttribute;
                            strName = vAttribute.GetName();
                            break;
                        }
                        catch (Exception ex)
                        {
                            ex.ToString();
                        }
                    }
                }
            }
            return(strName);
        }
        public static string GetDisplayNameForProperty(Type containerType, string propertyName)
        {
            ICustomTypeDescriptor typeDescriptor     = GetTypeDescriptor(containerType);
            PropertyDescriptor    propertyDescriptor = typeDescriptor.GetProperties().Find(propertyName, true);

            if (propertyDescriptor == null)
            {
                throw new ArgumentException(string.Format("Property not found", new object[]
                {
                    containerType.FullName,
                    propertyName
                }));
            }
            IEnumerable <Attribute> source           = propertyDescriptor.Attributes.Cast <Attribute>();
            DisplayAttribute        displayAttribute = source.OfType <DisplayAttribute>().FirstOrDefault <DisplayAttribute>();

            if (displayAttribute != null)
            {
                return(displayAttribute.GetName());
            }
            DisplayNameAttribute displayNameAttribute = source.OfType <DisplayNameAttribute>().FirstOrDefault <DisplayNameAttribute>();

            if (displayNameAttribute != null)
            {
                return(displayNameAttribute.DisplayName);
            }
            return(propertyName);
        }
Beispiel #10
0
        public BsPanelHtmlBuilder SetPropertiesFromModel(PropertyInfo propertyInfo)
        {
            BsPanelAttribute panelAttr = null;

            if (ReflectionHelpers.TryGetAttribute(propertyInfo, out panelAttr))
            {
                DisplayAttribute displayAttr = null;

                ReflectionHelpers.TryGetAttribute(propertyInfo, out displayAttr);

                if (panelAttr != null)
                {
                    this.Id(panelAttr.Id);
                    this.Expandable(panelAttr.Expandable);
                    this.Editable(panelAttr.Editable);
                }

                if (displayAttr != null)
                {
                    this.Name(displayAttr.GetName());
                }
            }

            return(this);
        }
Beispiel #11
0
        public static string GetDisplay(this MemberInfo propertyInfo)
        {
            var declaring         = propertyInfo.DeclaringType;
            var metaData          = declaring.GetCustomAttribute <MetadataTypeAttribute>();
            DisplayAttribute attr = null;

            if (metaData != null)
            {
                var metaProperty =
                    metaData.MetadataClassType.GetProperties().FirstOrDefault(x => x.Name == propertyInfo.Name);
                if (metaProperty != null)
                {
                    attr = metaProperty.GetAttribute <DisplayAttribute>(false);
                }
            }
            if (attr == null)
            {
                attr = propertyInfo.GetAttribute <DisplayAttribute>(false);
            }

            if (attr == null)
            {
                return(propertyInfo.Name);
            }

            return(attr.GetName());
        }
        private static string GetDisplayNameForProperty(Type containerType, string propertyName)
        {
            ICustomTypeDescriptor typeDescriptor = GetTypeDescriptor(containerType);
            PropertyDescriptor    property       = typeDescriptor.GetProperties().Find(propertyName, true);

            if (property == null)
            {
                throw new ArgumentException(String.Format(CultureInfo.CurrentCulture,
                                                          "Property not found", containerType.FullName, propertyName));
            }
            IEnumerable <Attribute> attributes = property.Attributes.Cast <Attribute>();
            DisplayAttribute        display    = attributes.OfType <DisplayAttribute>().FirstOrDefault();

            if (display != null)
            {
                return(display.GetName());
            }
            DisplayNameAttribute displayName = attributes.OfType <DisplayNameAttribute>().FirstOrDefault();

            if (displayName != null)
            {
                return(displayName.DisplayName);
            }
            return(propertyName);
        }
Beispiel #13
0
 public VxSelectItem(DisplayAttribute displayAttribute, Enum value)
 {
     this.Order       = displayAttribute.GetOrder() ?? 0;
     this.Label       = displayAttribute.GetName();
     this.Key         = value.ToString();
     this.Description = displayAttribute.GetDescription();
 }
 private void LocalizeDisplayAttribute(ModelMetadata metadata, DisplayAttribute attribute)
 {
     metadata.DisplayName      = Localize(attribute.GetName());
     metadata.ShortDisplayName = Localize(attribute.GetShortName());
     metadata.Description      = Localize(attribute.GetDescription());
     metadata.Watermark        = Localize(attribute.GetPrompt());
 }
 internal static ValidationMetadata ParseMetadata(string bindingPath, object entity)
 {
     if ((entity != null) && !string.IsNullOrEmpty(bindingPath))
     {
         PropertyInfo property = GetProperty(GetCustomOrCLRType(entity), bindingPath);
         if (property != null)
         {
             ValidationMetadata metadata = new ValidationMetadata();
             foreach (object obj2 in property.GetCustomAttributes(false))
             {
                 RequiredAttribute attribute = obj2 as RequiredAttribute;
                 if (attribute != null)
                 {
                     metadata.IsRequired = true;
                 }
                 else
                 {
                     DisplayAttribute attribute2 = obj2 as DisplayAttribute;
                     if (attribute2 != null)
                     {
                         metadata.Description = attribute2.GetDescription();
                         metadata.Caption     = attribute2.GetName();
                     }
                 }
             }
             if (metadata.Caption == null)
             {
                 metadata.Caption = property.Name;
             }
             return(metadata);
         }
     }
     return(null);
 }
Beispiel #16
0
        public override string GetLabel(GraphProperty property)
        {
            DisplayAttribute displayAttribute = property.GetAttributes <DisplayAttribute>().FirstOrDefault();
            string           defaultLabel     = labelRegex.Replace(property.Name, " $1").Substring(1);

            return(displayAttribute != null?displayAttribute.GetName() : defaultLabel);
        }
Beispiel #17
0
        private void LoadBody(KeyValuePair <string, PropertyInfo> pair, DisplayAttribute display, List <TagBuilder> list, object value)
        {
            var tag = new TagBuilder("td");

            if (display != null && !string.IsNullOrEmpty(display.GetName()))
            {
                tag.AddCssClass(pair.Key);
                TreeTextAttribute  treeText  = pair.Value.GetCustomAttribute <TreeTextAttribute>();
                ClassNameAttribute className = pair.Value.GetCustomAttribute <ClassNameAttribute>();
                if (treeText != null)
                {
                    tag.InnerHtml = $"<label><input name=\"form-field-radio\" type=\"radio\" /><span class=\"text\">{pair.Value.GetValue(value)}</span></label> ";
                }
                else if (className != null)
                {
                    tag.InnerHtml = $"<span class='{pair.Value.GetValue(value)}'></span> ";
                }
                else
                {
                    tag.SetInnerText(pair.Value.GetValue(value).ToString());
                }
            }


            list.Add(tag);
        }
Beispiel #18
0
        public static SelectList ToSelectList <T>(this T enumeration, bool NotSelect = false, Type enumType = null)
        {
            var   items  = new Dictionary <object, string>();
            Array source = null;

            if (enumType != null)
            {
                source = Enum.GetValues(enumType);
            }
            else if (enumeration != null)
            {
                source = Enum.GetValues(enumeration.GetType());
            }
            else if (enumeration == null && typeof(T) != typeof(Enum))
            {
                source = Enum.GetValues(typeof(T));
            }
            else
            {
                source = new object[0];
            }
            var displayAttributeType = typeof(DisplayAttribute);

            foreach (var value in source)
            {
                FieldInfo        field = value.GetType().GetField(value.ToString());
                DisplayAttribute attrs = (DisplayAttribute)field.
                                         GetCustomAttributes(displayAttributeType, false).FirstOrDefault();
                items.Add(value, attrs == null?field.Name: attrs.GetName());
            }
            return(NotSelect?new SelectList(items, "Key", "Value"): new SelectList(items, "Key", "Value", enumeration));
        }
        protected override ModelMetadata CreateMetadata(IEnumerable <Attribute> attributes, Type containerType, Func <object> modelAccessor, Type modelType, string propertyName)
        {
            ModelMetadata res = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

            FormatAttribute formatAttribute = attributes.OfType <FormatAttribute>().FirstOrDefault();

            if (formatAttribute != null)
            {
                string clientFormat;
                string prefix;
                string postfix;
                formatAttribute.GetClientFormat(out prefix, out postfix, out clientFormat);
                res.AdditionalValues.Add("MVCControlsToolkit.ClientFormatString", clientFormat);
                res.AdditionalValues.Add("MVCControlsToolkit.ClientFormatPrefix", prefix);
                res.AdditionalValues.Add("MVCControlsToolkit.ClientFormatPostfix", postfix);
            }
            DisplayAttribute display = attributes.OfType <DisplayAttribute>().FirstOrDefault();
            string           name    = null;

            if (display != null)
            {
                res.Description      = display.GetDescription();
                res.ShortDisplayName = display.GetShortName();
                res.Watermark        = display.GetPrompt();


                name = display.GetName();
                if (!string.IsNullOrWhiteSpace(name))
                {
                    res.DisplayName = name;
                }
            }
            return(res);
        }
Beispiel #20
0
 protected void HookupValidationAttributes()
 {
     PropertyInfo[] propertyInfos = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
     foreach (PropertyInfo propertyInfo in propertyInfos)
     {
         Attribute[] custom = Attribute.GetCustomAttributes(propertyInfo, typeof(ValidationAttribute), true);
         foreach (Attribute attribute in custom)
         {
             PropertyInfo        property            = propertyInfo;
             ValidationAttribute validationAttribute = attribute as ValidationAttribute;
             if (validationAttribute == null)
             {
                 throw new NotSupportedException("validationAttribute variable should be inherited from ValidationAttribute type");
             }
             string           name             = property.Name;
             DisplayAttribute displayAttribute = Attribute.GetCustomAttributes(propertyInfo, typeof(DisplayAttribute)).FirstOrDefault() as DisplayAttribute;
             if (displayAttribute != null)
             {
                 name = displayAttribute.GetName();
             }
             string message = validationAttribute.FormatErrorMessage(name);
             AddValidationFor(propertyInfo.Name).When(x => {
                 object value            = property.GetGetMethod().Invoke(this, new object[] {});
                 ValidationResult result = validationAttribute.GetValidationResult(value, new ValidationContext(this, null, null)
                 {
                     MemberName = property.Name
                 });
                 return(result != ValidationResult.Success);
             }).Show(message);
         }
     }
 }
Beispiel #21
0
        private void GenerateCsvHeader(List <string> csvWorksheet, Dictionary <PropertyInfo, CsvColumnAttribute> propertyDictionary)
        {
            var csvLine = new StringBuilder();

            PropertyInfo[] propertyInfoArray = propertyDictionary.Select(pd => pd.Key).ToArray();

            for (int col = 1; col <= propertyInfoArray.Length; col++)
            {
                PropertyInfo currentPropertyInfo = propertyInfoArray[col - 1];

                DisplayAttribute displayAttribute = currentPropertyInfo.GetCustomAttribute <DisplayAttribute>();

                DisplayNameAttribute displayNameAttribute = currentPropertyInfo.GetCustomAttribute <DisplayNameAttribute>();

                var displayName = displayAttribute?.GetName() ?? displayNameAttribute?.DisplayName ?? currentPropertyInfo.Name;

                if (col < propertyInfoArray.Length)
                {
                    csvLine.Append(displayName).Append(",");
                }
                else
                {
                    csvLine.Append(displayName);
                }
            }

            csvWorksheet.Add(csvLine.ToString());
        }
Beispiel #22
0
        /// <summary>
        /// Gets the display name of the property.
        /// </summary>
        /// <param name="memberInfo">The member information.</param>
        /// <returns>The display name.</returns>
        public string GetDisplayName(MemberInfo memberInfo)
        {
            if (memberInfo == null)
            {
                throw new ArgumentNullException("memberInfo");
            }

            DisplayAttribute propertyDisplayAttribute = ReflectionUtils.GetCustomAttribute <DisplayAttribute>(memberInfo);
            string           propertyDisplayName      = null;

            if (propertyDisplayAttribute != null)
            {
                propertyDisplayName = propertyDisplayAttribute.GetName();
            }

            if (string.IsNullOrEmpty(propertyDisplayName))
            {
                DisplayNameAttribute propertyDisplayNameAttribute = ReflectionUtils.GetCustomAttribute <DisplayNameAttribute>(memberInfo);
                if (propertyDisplayNameAttribute != null)
                {
                    propertyDisplayName = propertyDisplayNameAttribute.DisplayName;
                }
            }

            if (string.IsNullOrEmpty(propertyDisplayName))
            {
                propertyDisplayName = memberInfo.Name;
            }

            return(propertyDisplayName);
        }
Beispiel #23
0
        public static string GetDisplayName(string propertyName, PropertyInfo propertyInfo)
        {
            string displayName;
            object custromAttribute = propertyInfo.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault <object>();

            if (custromAttribute == null)
            {
                custromAttribute = propertyInfo.GetCustomAttributes(typeof(DisplayNameAttribute), false).FirstOrDefault <object>();
                if (custromAttribute == null)
                {
                    displayName = propertyName;
                }
                else
                {
                    DisplayNameAttribute displayNameAttribute = custromAttribute as DisplayNameAttribute;
                    displayName = (displayNameAttribute != null ? displayNameAttribute.DisplayName : propertyName);
                }
            }
            else
            {
                DisplayAttribute displayAttribute = custromAttribute as DisplayAttribute;
                displayName = (displayAttribute != null ? displayAttribute.GetName() : propertyName);
            }
            return(displayName);
        }
Beispiel #24
0
        public static string DisplayForEnum <TModel>(Expression <Func <TModel, object> > expression)
        {
            try
            {
                ConstantExpression memberExpression = null;
                memberExpression = expression.Body.NodeType switch
                {
                    //Check https://stackoverflow.com/questions/3049825/given-a-member-access-lambda-expression-convert-it-to-a-specific-string-represe
                    ExpressionType.Convert or ExpressionType.ConvertChecked => ((expression.Body is UnaryExpression ue) ? ue.Operand : null) as ConstantExpression,
                    _ => expression.Body as ConstantExpression,
                };

                var enumType   = typeof(TModel);
                var memberInfo = enumType.GetMember(memberExpression.Value.ToString())
                                 .Single();
                DisplayAttribute displayAttribute = memberInfo.GetCustomAttribute <DisplayAttribute>();
                if (displayAttribute is null)
                {
                    throw new CustomValidationException($"Enum value '{memberExpression.Value}' of type " +
                                                        $"'{expression.Parameters.First().Type.FullName}' does not have a {nameof(DisplayAttribute)}");
                }
                var displayName = displayAttribute.GetName();
                return(displayName);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
Beispiel #25
0
        /// <summary>
        /// 添加页眉
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="propertyInfos"></param>
        private void GenerateExcelHandler(ExcelWorksheet sheet, PropertyInfo[] propertyInfos, ExcelSheetAttribute excelSheetAttribute)
        {
            //设置行高、列宽
            sheet.Row(1).Height   = excelSheetAttribute.RowHeight;
            sheet.Column(1).Width = excelSheetAttribute.ColumnWeight;
            sheet.TabColor        = Color.Yellow;
            //单元格自适应,设置此项,则不能设置单元格的宽高。否则跑出异常
            sheet.Cells.Style.ShrinkToFit = true;

            for (int col = 1; col <= propertyInfos.Length; col++)
            {
                //获得当前属性
                PropertyInfo currentPropertyInfo = propertyInfos[col - 1];
                //找到属性上的标签
                DisplayNameAttribute displayNameAttribute = currentPropertyInfo.GetCustomAttribute <DisplayNameAttribute>();
                DisplayAttribute     displayAttribute     = currentPropertyInfo.GetCustomAttribute <DisplayAttribute>();
                //判断标签是存在
                string displayName = displayNameAttribute?.DisplayName ?? displayAttribute?.GetName() ?? currentPropertyInfo.Name;
                //给第一行的当前列,赋值
                ExcelRange currentCell = sheet.Cells[1, col];
                currentCell.Value = displayName;
                //标头加粗
                currentCell.Style.Font.Bold = true;
                //标头水平方向居中
                currentCell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                //垂直方向居中
                currentCell.Style.VerticalAlignment = ExcelVerticalAlignment.Center;
                //设置背景颜色
                currentCell.Style.Fill.PatternType = ExcelFillStyle.Solid;
                currentCell.Style.Fill.BackgroundColor.SetColor(Color.Red);
            }
        }
Beispiel #26
0
        private static string GetName(Type enumType, string name)
        {
            DisplayAttribute displayAttribute =
                enumType.GetField(name).GetCustomAttributes(false).OfType <DisplayAttribute>().FirstOrDefault();

            return(displayAttribute != null?displayAttribute.GetName() : name);
        }
Beispiel #27
0
        public static List <EnumEntry <TEnum, TRaw> > ConvertEnumToEntryList <TEnum, TRaw>(IEnumerable <TEnum> excludes = null, Func <TRaw, string, string> func = null)
        {
            var enumType = typeof(TEnum);
            var list     = new List <EnumEntry <TEnum, TRaw> >();

            if (enumType.IsEnum == false)
            {
                return(list);
            }

            //
            TEnum[] aryEnum = Enum.GetValues(enumType) as TEnum[];
            if (aryEnum == null)
            {
                return(list);
            }

            var lstEnums = aryEnum;

            if (excludes != null)
            {
                lstEnums = aryEnum.Except(excludes).ToArray();
            }
            //
            foreach (var item in lstEnums)
            {
                string strEnum = item.ToString();
                TRaw   rawVal  = (TRaw)Convert.ChangeType(item, typeof(TRaw));
                Enum   objEnum = Enum.Parse(enumType, strEnum) as Enum;
                var    entry   = new EnumEntry <TEnum, TRaw>(item, rawVal, strEnum)
                {
                    Description = GetEnumDescription(objEnum)
                };
                //entry.DisplayName = GetEnumDisplay(objEnum);
                //entry.DisplayDesc = GetEnumDisplay(objEnum, 1);
                var disObj = GetEnumDisplayAttributs(objEnum);
                DisplayAttribute displayAttr = null;
                if (disObj != null)
                {
                    displayAttr = disObj.FirstOrDefault();
                }
                if (displayAttr != null)
                {
                    entry.DisplayName      = displayAttr.GetName();
                    entry.DisplayShortName = displayAttr.GetShortName();
                    entry.DisplayDesc      = displayAttr.GetDescription();
                    entry.DisplayOrder     = displayAttr.GetOrder() ?? 0;
                }
                if (func != null)
                {
                    entry.CustomName = func(rawVal, "");
                }

                list.Add(entry);
            }

            list = list.OrderBy(l => l.RawValue).ToList();
            return(list);
        }
Beispiel #28
0
        public static string GetDisplayName(this Enum value)
        {
            FieldInfo        field = value.GetType().GetField(value.ToString());
            DisplayAttribute attrs = (DisplayAttribute)field.
                                     GetCustomAttributes(typeof(DisplayAttribute), false).First();

            return(attrs.GetName());
        }
Beispiel #29
0
        public void DisplayAttribute_GetName_Does_Not_Fall_Back()
        {
            DisplayAttribute attr = new DisplayAttribute {
                ShortName = "ShortName", Description = "Description", Prompt = "Prompt", GroupName = "GroupName"
            };

            Assert.IsNull(attr.GetName(), "GetName should NOT fall back onto any other values");
        }
        /// <summary>
        /// Applies the display attributes.
        /// </summary>
        /// <param name="attr">The attribute.</param>
        /// <param name="pi">The property info.</param>
        private static void ApplyDisplayAttributes(this AttributeModel attr, PropertyInfo pi)
        {
            DisplayAttribute disp = (DisplayAttribute)pi.GetCustomAttribute(typeof(DisplayAttribute));

            attr.DisplayName      = disp == null ? pi.Name : disp.GetName();
            attr.DisplayGroupName = disp?.GetGroupName();
            attr.ShortName        = disp?.GetShortName();
            attr.Prompt           = disp?.GetPrompt();
        }
Beispiel #31
0
        /// <summary>
        /// Get the display name for the specified property.
        /// </summary>
        /// <param name="property">The property.</param>
        /// <returns>The display name of the property.</returns>
        private static string GetPropertyDisplay(PropertyInfo property)
        {
            DisplayAttribute attribute = property
                                         .GetCustomAttributes(typeof(DisplayAttribute), false)
                                         .Cast <DisplayAttribute>()
                                         .SingleOrDefault();

            return(attribute != null?attribute.GetName() : property.Name);
        }
        public void DisplayAttribute_Literal_Properties() {
            DisplayAttribute attr = new DisplayAttribute();

            Assert.IsNull(attr.ResourceType);
            Assert.IsNull(attr.ShortName);
            Assert.IsNull(attr.Name);
            Assert.IsNull(attr.Prompt);
            Assert.IsNull(attr.Description);
            Assert.IsNull(attr.GroupName);

            Assert.IsNull(attr.GetShortName());
            Assert.IsNull(attr.GetName());
            Assert.IsNull(attr.GetPrompt());
            Assert.IsNull(attr.GetDescription());
            Assert.IsNull(attr.GetGroupName());

            attr.ShortName = "theShortName";
            attr.Name = "theName";
            attr.Prompt = "thePrompt";
            attr.Description = "theDescription";
            attr.GroupName = "theGroupName";

            Assert.AreEqual("theShortName", attr.GetShortName());
            Assert.AreEqual("theName", attr.GetName());
            Assert.AreEqual("thePrompt", attr.GetPrompt());
            Assert.AreEqual("theDescription", attr.GetDescription());
            Assert.AreEqual("theGroupName", attr.GetGroupName());

            attr.ShortName = String.Empty;
            attr.Name = String.Empty;
            attr.Prompt = String.Empty;
            attr.Description = String.Empty;
            attr.GroupName = String.Empty;

            Assert.AreEqual(String.Empty, attr.GetShortName());
            Assert.AreEqual(String.Empty, attr.GetName());
            Assert.AreEqual(String.Empty, attr.GetPrompt());
            Assert.AreEqual(String.Empty, attr.GetDescription());
            Assert.AreEqual(String.Empty, attr.GetGroupName());
        }
        public void Ctor()
        {
            DisplayAttribute attribute = new DisplayAttribute();
            Assert.Null(attribute.ShortName);
            Assert.Null(attribute.GetShortName());

            Assert.Null(attribute.Name);
            Assert.Null(attribute.GetName());

            Assert.Null(attribute.Description);
            Assert.Null(attribute.GetDescription());

            Assert.Null(attribute.Prompt);
            Assert.Null(attribute.GetPrompt());

            Assert.Null(attribute.GroupName);
            Assert.Null(attribute.GetGroupName());

            Assert.Null(attribute.ResourceType);
        }
        public void DisplayAttribute_Resourced_Properties_Wrong_Keys() {
            DisplayAttribute attr = new DisplayAttribute();

            attr.ResourceType = typeof(DisplayAttribute_Resources);

            attr.ShortName = "notAKey1";
            attr.Name = "notAKey2";
            attr.Prompt = "notAKey3";
            attr.Description = "notAKey4";
            attr.GroupName = "notAKey5";

            Assert.AreEqual("notAKey1", attr.ShortName);
            Assert.AreEqual("notAKey2", attr.Name);
            Assert.AreEqual("notAKey3", attr.Prompt);
            Assert.AreEqual("notAKey4", attr.Description);
            Assert.AreEqual("notAKey5", attr.GroupName);

            string shortNameError = String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.LocalizableString_LocalizationFailed, "ShortName", attr.ResourceType.FullName, attr.ShortName);
            string nameError = String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.LocalizableString_LocalizationFailed, "Name", attr.ResourceType.FullName, attr.Name);
            string promptError = String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.LocalizableString_LocalizationFailed, "Prompt", attr.ResourceType.FullName, attr.Prompt);
            string descriptionError = String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.LocalizableString_LocalizationFailed, "Description", attr.ResourceType.FullName, attr.Description);
            string groupNameError = String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.LocalizableString_LocalizationFailed, "GroupName", attr.ResourceType.FullName, attr.GroupName);

            ExceptionHelper.ExpectException<InvalidOperationException>(() => { string s = attr.GetShortName(); }, shortNameError);
            ExceptionHelper.ExpectException<InvalidOperationException>(() => { string s = attr.GetName(); }, nameError);
            ExceptionHelper.ExpectException<InvalidOperationException>(() => { string s = attr.GetPrompt(); }, promptError);
            ExceptionHelper.ExpectException<InvalidOperationException>(() => { string s = attr.GetDescription(); }, descriptionError);
            ExceptionHelper.ExpectException<InvalidOperationException>(() => { string s = attr.GetGroupName(); }, groupNameError);
        }
        public void Name_Get_Set(string value)
        {
            DisplayAttribute attribute = new DisplayAttribute();
            attribute.Name = value;

            Assert.Equal(value, attribute.Name);
            Assert.Equal(value == null, attribute.GetName() == null);

            // Set again, to cover the setter avoiding operations if the value is the same
            attribute.Name = value;
            Assert.Equal(value, attribute.Name);
        }
 public void DisplayAttribute_GetName_Does_Not_Fall_Back() {
     DisplayAttribute attr = new DisplayAttribute { ShortName = "ShortName", Description = "Description", Prompt = "Prompt", GroupName = "GroupName" };
     Assert.IsNull(attr.GetName(), "GetName should NOT fall back onto any other values");
 }
        public void DisplayAttribute_Fail_No_Getter_Resource() {
            DisplayAttribute attr = new DisplayAttribute();
            attr.ResourceType = typeof(DisplayAttribute_Resources);
            attr.ShortName = "NoGetter";
            attr.Name = "NoGetter";
            attr.Prompt = "NoGetter";
            attr.Description = "NoGetter";
            attr.GroupName = "NoGetter";

            string shortNameError = String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.LocalizableString_LocalizationFailed, "ShortName", attr.ResourceType.FullName, attr.ShortName);
            string nameError = String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.LocalizableString_LocalizationFailed, "Name", attr.ResourceType.FullName, attr.Name);
            string promptError = String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.LocalizableString_LocalizationFailed, "Prompt", attr.ResourceType.FullName, attr.Prompt);
            string descriptionError = String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.LocalizableString_LocalizationFailed, "Description", attr.ResourceType.FullName, attr.Description);
            string groupNameError = String.Format(CultureInfo.CurrentCulture, Resources.DataAnnotationsResources.LocalizableString_LocalizationFailed, "GroupName", attr.ResourceType.FullName, attr.GroupName);

            ExceptionHelper.ExpectException<InvalidOperationException>(() => { string s = attr.GetShortName(); }, shortNameError);
            ExceptionHelper.ExpectException<InvalidOperationException>(() => { string s = attr.GetName(); }, nameError);
            ExceptionHelper.ExpectException<InvalidOperationException>(() => { string s = attr.GetPrompt(); }, promptError);
            ExceptionHelper.ExpectException<InvalidOperationException>(() => { string s = attr.GetDescription(); }, descriptionError);
            ExceptionHelper.ExpectException<InvalidOperationException>(() => { string s = attr.GetGroupName(); }, groupNameError);
        }