public void GetDisplayName() { var name = "test name"; var attribute = new DisplayNameAttribute(name); Assert.Equal(name, attribute.DisplayName); }
public void CorrectlySetsValues() { var displayNameAttribute = new DisplayNameAttribute("FirstName"); Assert.AreEqual("FirstName", displayNameAttribute.DisplayName); displayNameAttribute = new DisplayNameAttribute("First Name"); Assert.AreEqual("First Name", displayNameAttribute.DisplayName); }
/// <summary> /// 获取成员元数据的Description特性描述信息 /// </summary> /// <param name="member">成员元数据对象</param> /// <param name="inherit">是否搜索成员的继承链以查找描述特性</param> /// <returns>返回Description特性描述信息,如不存在则返回成员的名称</returns> public static string GetDescription(this MemberInfo member, bool inherit = true) { DescriptionAttribute desc = member.GetAttribute <DescriptionAttribute>(inherit); if (desc != null) { return(desc.Description); } DisplayNameAttribute displayName = member.GetAttribute <DisplayNameAttribute>(inherit); if (displayName != null) { return(displayName.DisplayName); } DisplayAttribute display = member.GetAttribute <DisplayAttribute>(inherit); if (display != null) { return(display.Name); } return(member.Name); }
private string GetTidyParameters(TidyOptions aTidyOptions, TidyChecks aTidyChecks) { string parameters = string.Empty; if (null != aTidyOptions.TidyChecks && 0 < aTidyOptions.TidyChecks.Length) { parameters = $",{String.Join(",", aTidyOptions.TidyChecks)}"; } else { foreach (PropertyInfo prop in aTidyChecks.GetType().GetProperties()) { object[] propAttrs = prop.GetCustomAttributes(false); object clangCheckAttr = propAttrs.FirstOrDefault(attr => typeof(ClangCheckAttribute) == attr.GetType()); object displayNameAttrObj = propAttrs.FirstOrDefault(attr => typeof(DisplayNameAttribute) == attr.GetType()); if (null == clangCheckAttr || null == displayNameAttrObj) { continue; } DisplayNameAttribute displayNameAttr = (DisplayNameAttribute)displayNameAttrObj; var value = prop.GetValue(aTidyChecks, null); if (Boolean.TrueString != value.ToString()) { continue; } parameters = $"{parameters},{displayNameAttr.DisplayName}"; } } if (string.Empty != parameters) { parameters = string.Format("{0} ''-*{1}''", aTidyOptions.Fix ? ScriptConstants.kTidyFix : ScriptConstants.kTidy, parameters); } return(parameters); }
protected virtual void Query() { dic.Clear(); if (dataGridView1.DataSource == null) { return; } Type type = dataGridView1.DataSource.GetType().GetGenericArguments()[0]; PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo property in properties) { DisplayNameAttribute displayAttr = property.GetCustomAttribute(typeof(DisplayNameAttribute)) as DisplayNameAttribute; MODEL.ORM.VisableAttribute visableAttr = property.GetCustomAttribute(typeof(MODEL.ORM.VisableAttribute)) as MODEL.ORM.VisableAttribute; if (visableAttr != null && visableAttr.visable == false) { dataGridView1.Columns[property.Name].Visible = false; } if (displayAttr != null) { string key = property.Name; string value = displayAttr.DisplayName; dic.Add(new KeyValuePair <string, string>(key, value)); } } comboBox1.DataSource = dic.ToArray(); comboBox1.DisplayMember = "value"; comboBox1.ValueMember = "key"; comboBox2.DataSource = dic.ToArray(); comboBox2.DisplayMember = "value"; comboBox2.ValueMember = "key"; comboBox3.DataSource = dic.ToArray(); comboBox3.DisplayMember = "value"; comboBox3.ValueMember = "key"; }
protected override ModelMetadata CreateMetadata( IEnumerable <Attribute> attributes, Type containerType, Func <object> modelAccessor, Type modelType, string propertyName) { if (string.IsNullOrEmpty(propertyName)) { return(base.CreateMetadata( attributes, containerType, modelAccessor, modelType, propertyName)); } var newAttributes = new List <Attribute>(attributes); if (newAttributes.All( x => x.GetType() != typeof(DisplayNameAttribute))) { var value = Labels.ResourceManager.GetString(propertyName); if (!string.IsNullOrEmpty(value)) { var attribute = new DisplayNameAttribute(value); newAttributes.Add(attribute); } } return(base.CreateMetadata( newAttributes, containerType, modelAccessor, modelType, propertyName)); }
public static string ResolvedLabelText(this MemberInfo member) { DisplayAttribute attribute = member .GetCustomAttributes(typeof(DisplayAttribute), false) .Cast <DisplayAttribute>() .FirstOrDefault(); string resolvedLabelText = attribute?.Name; if (resolvedLabelText != null) { return(resolvedLabelText); } DisplayNameAttribute displayNameAttribute = member .GetCustomAttributes(typeof(DisplayNameAttribute), false) .Cast <DisplayNameAttribute>() .FirstOrDefault(); resolvedLabelText = displayNameAttribute?.DisplayName; return(resolvedLabelText); }
public static string ToHtmlTable <T>(this List <T> obj, bool selectAll, string tableAttr = "", string tableStyle = "border-collapse: collapse; font-family:Arial;", string rowStyle = "", string thStyle = "background-color:#006CC2; color:white; padding:10px;", string tdStyle = "border-bottom:solid 1px #aaa; padding: 10px;") { System.Text.StringBuilder htmlTable = new System.Text.StringBuilder(); htmlTable.Append($"<table {tableAttr} style=\" { tableStyle } \">"); foreach (PropertyInfo rowHeader in obj.FirstOrDefault().GetType().GetProperties().Where(prop => selectAll ? true : Attribute.IsDefined(prop, typeof(Common.Utility.AddToTableAttribute)))) { DisplayNameAttribute displayAttribute = ((DisplayNameAttribute)rowHeader.GetCustomAttribute(typeof(DisplayNameAttribute), true)); htmlTable.Append($"<th style=\"{ thStyle}\">{(displayAttribute == null ? rowHeader.Name : displayAttribute.DisplayName)}</th>"); } foreach (T row in obj) { htmlTable.Append($"<tr style=\" { rowStyle } \">"); foreach (PropertyInfo td in row.GetType().GetProperties().Where(prop => selectAll ? true : Attribute.IsDefined(prop, typeof(Common.Utility.AddToTableAttribute)))) { htmlTable.Append($"<td style=\"{ tdStyle}\">{td.GetValue(row, null).ToString()}</td>"); } htmlTable.Append("</tr>"); } htmlTable.Append("</table>"); return(htmlTable.ToString()); }
public static IDictionary <string, string> GetNameAndDisplayNameProperty(this object myObject) { IDictionary <string, string> result = new Dictionary <string, string>(); PropertyInfo[] properties = typeof(object).GetProperties(); foreach (PropertyInfo prop in properties) { object[] attrs = prop.GetCustomAttributes(true); foreach (object attr in attrs) { DisplayNameAttribute displayName = attr as DisplayNameAttribute; if (displayName != null) { result.Add(prop.Name, displayName.DisplayName); } } } return(result); }
public EnumEditor(object @object, PropertyInfo info) : base(@object, info) { Type type = info.PropertyType; foreach (FieldInfo fi in type.GetFields()) { if (!fi.IsStatic || fi.FieldType != type) { continue; } string name = fi.Name; DisplayNameAttribute dispname = Util.GetAttribute <DisplayNameAttribute>(fi, false); if (dispname != null) { name = dispname.DisplayName; } object value = fi.GetValue(null); this.mStore.AppendValues(new EnumValue(value, name)); } this.mCombo = new ComboBox(this.mStore); CellRendererText renderer = new CellRendererText(); this.mCombo.PackStart(renderer, true); this.mCombo.SetCellDataFunc(renderer, ComboFunc); this.mCombo.Show(); this.Add(this.mCombo); this.mCombo.Changed += this.OnComboChanged; this.Revert(); }
public static void MoveSplitterToLongestDisplayName(PropertyGrid propertyGrid, int iPadding) { try { Type pgObjectType = propertyGrid.SelectedObject.GetType(); string longestDisplayName = ""; // Iterate through all the properties of the class. foreach (PropertyInfo mInfo in pgObjectType.GetProperties()) { // Iterate through all the Attributes for each property. foreach (Attribute attr in mInfo.GetCustomAttributes(typeof(DisplayNameAttribute), false)) { if (attr.GetType() == typeof(DisplayNameAttribute)) { DisplayNameAttribute displayNameAttr = (DisplayNameAttribute)attr; if (displayNameAttr.DisplayName.Length > longestDisplayName.Length) { longestDisplayName = displayNameAttr.DisplayName; } } } } Size textSize = TextRenderer.MeasureText(longestDisplayName, propertyGrid.Font); PropertyGridManipulator.MoveSplitter(propertyGrid, textSize.Width + iPadding); } catch (Exception exception1) { MessageBox.Show(exception1.Message); //do nothing for now -- //if exception was thrown the private method MoveSplitterTo //of the C# version 2.0 framework's PropertyGrid's //PropertyGridView probably is no //longer named the same or has a different //method signature in the current C# framework } }
/// <summary> /// Generates the change menu item. /// </summary> /// <returns></returns> private ToolStripMenuItem GenerateChangeMenu() { ToolStripMenuItem menuItem = new ToolStripMenuItem("Change to"); menuItem.Image = CCNetConfig.Properties.Resources.securitychange_16x16; List <Type> allowedItems = CoreUtil.GetAllItemsOfType(source.ItemType); foreach (Type allowedItem in allowedItems) { // Retrieve the display name of the security mode string displayName = allowedItem.Name; DisplayNameAttribute attribute = CoreUtil.GetCustomAttribute <DisplayNameAttribute>(allowedItem); if (attribute != null) { displayName = attribute.DisplayName; } // Add the actual menu item ToolStripMenuItem securityMenuItem = new ToolStripMenuItem(displayName); securityMenuItem.Image = CCNetConfig.Properties.Resources.applications_16x16; securityMenuItem.Tag = allowedItem; menuItem.DropDownItems.Add(securityMenuItem); securityMenuItem.Click += delegate(object sender, EventArgs e) { // Generate the new instance and update the display ICCNetObject value = Activator.CreateInstance((sender as ToolStripMenuItem).Tag as Type) as ICCNetObject; DataItem = value; ChangeDataValue(value); UpdateDisplay(); Nodes.Clear(); ReflectionHelper.GenerateChildNodes(this, DataItem); }; } return(menuItem); }
public GenericFactory(Assembly ass, Type assignableType, string nameSpace) { this.assembly = ass; Type at = typeof(object); foreach (Type t in ass.GetTypes()) { if (((nameSpace != null && t.FullName.StartsWith(nameSpace)) || nameSpace == null) && assignableType.IsAssignableFrom(t)) { object[] attrs = t.GetCustomAttributes(typeof(DisplayNameAttribute), false); if (attrs.Length > 0) { DisplayNameAttribute dna = (DisplayNameAttribute)attrs[0]; typeHash.Add(dna.Name, t); } else { typeHash.Add(t.Name, t); } } } }
/// <summary> /// Create a <label> tag for a validation-enabled control created from Html.<control>For()<br/> /// The inner text is determined by the [DisplayName] attribute on the model property or an overload. /// </summary> /// <param name="markupName">Set as the 'For' property on the label element.</param> /// <param name="name">Must be the property name on the Model object</param> /// <param name="model">The model itself.</param> /// <param name="htmlProperties">An anonymous object whose properties are applied to the element.<br/> /// ie: new { Class = "cssClass", onchange = "jsFunction()" } </param> /// <param name="displayName">Override the display name (inner text) of the label.</param> /// <returns>Returns a label control.</returns> public string LabelFor(string markupName, string name, object model, object htmlProperties, string displayName) { string dispName = ""; PropertyInfo pi = model.GetType().GetProperties().FirstOrDefault(p => p.Name == name); if (pi == null) { throw new Exception("[" + name + "] public property not found on object [" + model.GetType().Name + "]"); } if (String.IsNullOrEmpty(displayName)) { DisplayNameAttribute datt = pi.GetCustomAttributes(false).OfType <DisplayNameAttribute>().FirstOrDefault(); if (datt != null) { dispName = datt.DisplayName ?? pi.Name; } else { dispName = pi.Name; } } else { dispName = displayName; } HtmlTag lbl = new HtmlTag("label", new { For = markupName }) { InnerText = dispName }; lbl.MergeObjectProperties(htmlProperties); lbl = PreProcess(lbl, _MetaData, TagTypes.Label, markupName, name, model); return(lbl.Render()); }
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 {0} {1}", containerType.FullName, propertyName)); } IEnumerable <Attribute> attributes = property.Attributes.Cast <Attribute>().ToArray(); 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); }
private static string GetDisplayNameForProperty(Type containerType, string propertyName) { string displayName = propertyName; PropertyInfo propertyInfo = containerType.GetProperty(propertyName); if (propertyInfo == null) { throw new NullReferenceException(nameof(propertyInfo)); } DisplayAttribute displayAttribute = propertyInfo.GetCustomAttribute <DisplayAttribute>(); if (displayAttribute != null) { propertyName = displayAttribute.GetName(); return(propertyName); } DisplayNameAttribute displayNameProperty = propertyInfo.GetCustomAttribute <DisplayNameAttribute>(); if (displayNameProperty != null) { displayName = displayNameProperty.DisplayName; } return(displayName); }
/// <summary> /// 验证 /// </summary> /// <param name="model">模型</param> /// <param name="property">属性</param> /// <param name="value">值</param> /// <returns>返回信息</returns> public BasicReturnInfo Vali(object model, PropertyInfo property, object value) { BasicReturnInfo returnInfo = new BasicReturnInfo(); ValiAttrT valiAttr = property.GetCustomAttribute <ValiAttrT>(); if (valiAttr == null) { return(returnInfo); } DisplayNameAttribute displayName = property.GetCustomAttribute <DisplayNameAttribute>(); string name = displayName != null ? displayName.DisplayName : property.Name; string errMsg = ExecVali(model, value, name, valiAttr); if (string.IsNullOrWhiteSpace(errMsg)) { return(returnInfo); } returnInfo.SetFailureMsg(errMsg); return(returnInfo); }
private static void AddMultiplayerOptionsProperties(RectTransform container) { List <PropertyInfo> properties = AccessTools.GetDeclaredProperties(typeof(MultiplayerOptions)); Vector2 anchorPosition = new Vector2(30, -20); foreach (var prop in properties) { DisplayNameAttribute displayAttr = prop.GetCustomAttribute <DisplayNameAttribute>(); if (displayAttr != null) { if (prop.PropertyType == typeof(bool)) { CreateBooleanControl(displayAttr, prop, anchorPosition); } else if (prop.PropertyType == typeof(int) || prop.PropertyType == typeof(float) || prop.PropertyType == typeof(ushort)) { CreateNumberControl(displayAttr, prop, anchorPosition); } else if (prop.PropertyType == typeof(string)) { CreateStringControl(displayAttr, prop, anchorPosition); } else if (prop.PropertyType.IsEnum) { CreateEnumControl(displayAttr, prop, anchorPosition); } else { Log.Warn($"MultiplayerOption property \"${prop.Name}\" of type \"{prop.PropertyType}\" not supported."); continue; } anchorPosition = new Vector2(anchorPosition.x, anchorPosition.y - 40); } } }
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 byte[] GenerateExcel <T>(string path, string sheetName, List <T> records, Dictionary <string, KeyValuePair <string, string> > columns, Dictionary <int, List <KeyValuePair <string, string> > > introductionRows = null) { var stream = new MemoryStream(); var wb = new XLWorkbook(); wb.RightToLeft = true; var ws = wb.Worksheets.Add(sheetName); //set introduction Row: int rowIdex = 1; int cellIndex = 1; if (introductionRows != null) { for (int i = 0; i < introductionRows.Count; i++) { var introductionRow = introductionRows[i]; cellIndex = 1; foreach (var prop in introductionRow) { ws.Cell(rowIdex, cellIndex).Value = prop.Key; ws.Cell(rowIdex, cellIndex).WorksheetColumn().Width = 15; ws.Cell(rowIdex, cellIndex).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right; if (prop.Value == "red") { ws.Cell(rowIdex, cellIndex).Style.Font.FontColor = XLColor.Red; } if (prop.Value == "title") { ws.Cell(rowIdex, cellIndex).Style.Font.Bold = true; ws.Cell(rowIdex, cellIndex).Style.Font.FontSize = 14; } cellIndex++; } rowIdex++; } } cellIndex = 1; foreach (PropertyInfo prop in typeof(T).GetProperties()) { if (columns != null && !columns.ContainsKey(prop.Name)) { continue; } DisplayNameAttribute attr = (DisplayNameAttribute)Attribute.GetCustomAttribute(prop, typeof(DisplayNameAttribute)); var propName = columns != null ? columns[prop.Name].Key : prop.Name; ws.Cell(rowIdex, cellIndex).Value = propName; ws.Cell(rowIdex, cellIndex).Value = propName; ws.Cell(rowIdex, cellIndex).WorksheetColumn().Width = 19; ws.Cell(rowIdex, cellIndex).Style.Font.Bold = true; ws.Cell(rowIdex, cellIndex).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right; cellIndex++; } foreach (var record in records) { Type myType = record.GetType(); IList <PropertyInfo> props = new List <PropertyInfo>(myType.GetProperties()); cellIndex = 1; rowIdex++; foreach (PropertyInfo prop in props) { if (columns != null && !columns.ContainsKey(prop.Name)) { continue; } object propValue = prop.GetValue(record, null); string cellValue = propValue != null?propValue.ToString() : "N/A"; if (propValue != null && columns != null && columns[prop.Name].Value != null) { cellValue = string.Format(columns[prop.Name].Value.ToString(), propValue); } ws.Cell(rowIdex, cellIndex).SetValue <string>(cellValue); ws.Cell(rowIdex, cellIndex).WorksheetColumn().Width = 19; ws.Cell(rowIdex, cellIndex).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right; cellIndex++; } } wb.SaveAs(path); byte[] result = File.ReadAllBytes(path); return(result); }
private static void CreateNumberControl(DisplayNameAttribute control, PropertyInfo prop, Vector2 anchorPosition) { UIRangeAttribute rangeAttr = prop.GetCustomAttribute <UIRangeAttribute>(); bool sliderControl = rangeAttr != null && rangeAttr.Slider; RectTransform element = Object.Instantiate(sliderControl ? sliderTemplate : inputTemplate, multiplayerContent, false); SetupUIElement(element, control, prop, anchorPosition); bool isFloatingPoint = prop.PropertyType == typeof(float) || prop.PropertyType == typeof(double); if (sliderControl) { Slider slider = element.GetComponentInChildren <Slider>(); slider.minValue = rangeAttr.Min; slider.maxValue = rangeAttr.Max; slider.wholeNumbers = !isFloatingPoint; Text sliderThumbText = slider.GetComponentInChildren <Text>(); slider.onValueChanged.RemoveAllListeners(); slider.onValueChanged.AddListener((value) => { prop.SetValue(tempMultiplayerOptions, value, null); sliderThumbText.text = value.ToString("0"); }); tempToUICallbacks[prop.Name] = () => { slider.value = (float)prop.GetValue(tempMultiplayerOptions, null); sliderThumbText.text = slider.value.ToString("0"); }; } else { InputField input = element.GetComponentInChildren <InputField>(); input.onValueChanged.RemoveAllListeners(); input.onValueChanged.AddListener((str) => { try { var converter = TypeDescriptor.GetConverter(prop.PropertyType); System.IComparable value = (System.IComparable)converter.ConvertFromString(str); if (rangeAttr != null) { System.IComparable min = (System.IComparable)System.Convert.ChangeType(rangeAttr.Min, prop.PropertyType); System.IComparable max = (System.IComparable)System.Convert.ChangeType(rangeAttr.Max, prop.PropertyType); if (value.CompareTo(min) < 0) { value = min; } if (value.CompareTo(max) > 0) { value = max; } input.text = value.ToString(); } prop.SetValue(tempMultiplayerOptions, value, null); } catch { // If the char is not a number, rollback to previous value input.text = prop.GetValue(tempMultiplayerOptions, null).ToString(); } }); tempToUICallbacks[prop.Name] = () => { input.text = prop.GetValue(tempMultiplayerOptions, null).ToString(); }; } }
public void GetHashCode_NullDisplayName_ThrowsNullReferenceException() { var attribute = new DisplayNameAttribute(null); Assert.Throws <NullReferenceException>(() => attribute.GetHashCode()); }
static void Main(string[] args) { Person p = new Person(); p.Id = Guid.NewGuid(); p.Name = "刘小情"; p.Age = 22; Type t = p.GetType(); //获取type上标注的ObsoleteAttribute object[] obsoletes = t.GetCustomAttributes(typeof(ObsoleteAttribute), false); if (obsoletes.Length > 0) { Console.WriteLine("此类已过时"); } else { Console.WriteLine("此类没有过时"); } Console.WriteLine("================================"); foreach (PropertyInfo item in t.GetProperties()) { //获得属性名称 string name = item.Name; #region DisPlayNameAttribute //获得item上标注的DisPlayNameAttribute类型的Attribute对象 DisplayNameAttribute displayNameAtt = (DisplayNameAttribute)item.GetCustomAttribute(typeof(DisplayNameAttribute)); string displayName = string.Empty; if (displayNameAtt == null)//如果为空就没有标注这样一个Attribute { displayName = null; } else { //获得displayattribute对象的DisPalyName的值 displayName = displayNameAtt.DisplayName; } #endregion JPAttribute jPAttribute = (JPAttribute)item.GetCustomAttribute(typeof(JPAttribute)); string jpName = string.Empty; if (jPAttribute == null) { jpName = "无"; } else { jpName = jPAttribute.DispayName; } //获得属性名的值 object value = item.GetValue(p); Console.WriteLine(name + "(" + displayName + ")" + "(日文:" + jpName + ")=" + value); } Console.ReadKey(); }
/// <summary> /// Set the metadata of display. /// </summary> /// <param name="display">Display name attribute.</param> protected virtual void SetDisplay(DisplayNameAttribute display) { if (display == null) throw new ArgumentNullException("display"); Name = display.DisplayName; }
/// <summary> /// Writes a data type and all public instance properties. /// Such type may correspond to an IFC entity or a ConceptRoot of a model view definition (which may also correspond to a property set) /// The type is nested according to namespace tokens. /// The type is linked to superclass according to base type. /// The type is expanded into subclasses if the last property is an enumeration for a classification (e.g. PredefinedType). /// Any referenced types are also retrieved and written if they don't yet exist. /// Localized names and descriptions are extracted from .NET resources. /// </summary> /// <param name="type"></param> public void WriteType(Type type) { if (type == null) { return; } if (m_mapTypes.ContainsKey(type)) { return; // already written } string name = type.Name; DisplayNameAttribute attrName = (DisplayNameAttribute)type.GetCustomAttribute <DisplayNameAttribute>(); if (attrName != null) { name = attrName.DisplayName; } string desc = null; DescriptionAttribute attrDesc = (DescriptionAttribute)type.GetCustomAttribute <DescriptionAttribute>(); if (attrDesc != null) { desc = attrDesc.Description; } IfdConceptTypeEnum conctype = IfdConceptTypeEnum.SUBJECT; IfdRelationshipTypeEnum relbase = IfdRelationshipTypeEnum.SPECIALIZES; if (type.Name.StartsWith("Pset") || type.Name.StartsWith("Qto")) { // hack conctype = IfdConceptTypeEnum.BAG; relbase = IfdRelationshipTypeEnum.ASSIGNS_COLLECTIONS; } else if (type.IsValueType || type.IsEnum) { conctype = IfdConceptTypeEnum.MEASURE; } // retrieve existing -- enable once final uploaded correctly! #if false IfdConcept conc = SearchConcept(type.Name, conctype); if (conc != null) { this.m_mapTypes.Add(type, conc.guid); return; } #endif DisplayAttribute[] localize = (DisplayAttribute[])type.GetCustomAttributes(typeof(DisplayAttribute), false); IfdBase ifdThis = CreateConcept(type.Name, name, desc, conctype, localize); if (ifdThis == null) { return; } this.m_mapTypes.Add(type, ifdThis.guid); // get namespace string[] namespaces = type.Namespace.Split('.'); string guidSchemaParent = null; string guidSchemaChild = null; for (int iNS = 0; iNS < namespaces.Length; iNS++) { string ns = namespaces[iNS]; if (!this.m_mapNamespaces.TryGetValue(ns, out guidSchemaChild)) { StringBuilder sbQual = new StringBuilder(); for (int x = 0; x <= iNS; x++) { if (x > 0) { sbQual.Append("."); } sbQual.Append(namespaces[x]); } string qualname = sbQual.ToString(); // call server to find namespace IfdConcept ifdNamespace = SearchConcept(qualname, IfdConceptTypeEnum.BAG); if (ifdNamespace != null) { guidSchemaChild = ifdNamespace.guid; } else { IfdBase ifdNS = CreateConcept(qualname, ns, String.Empty, IfdConceptTypeEnum.BAG, null); guidSchemaChild = ifdNS.guid; } this.m_mapNamespaces.Add(ns, guidSchemaChild); if (guidSchemaParent != null) { CreateRelationship(guidSchemaParent, guidSchemaChild, IfdRelationshipTypeEnum.COLLECTS); } } if (iNS == namespaces.Length - 1) { CreateRelationship(guidSchemaChild, ifdThis.guid, IfdRelationshipTypeEnum.COLLECTS); } guidSchemaParent = guidSchemaChild; } // get base type if (type.IsClass && type.BaseType != typeof(object)) { WriteType(type.BaseType); string guidbase = null; if (m_mapTypes.TryGetValue(type.BaseType, out guidbase)) { CreateRelationship(guidbase, ifdThis.guid, relbase); } } //PropertyInfo[] props = type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public); //foreach (PropertyInfo prop in props) FieldInfo[] fields = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public); foreach (FieldInfo prop in fields) { // write the property itself // resolve property type Type typeProp = prop.FieldType; if (typeProp.IsGenericType && typeProp.GetGenericTypeDefinition() == typeof(Nullable <>)) { typeProp = typeProp.GetGenericArguments()[0]; } if (typeProp.IsGenericType && typeProp.GetGenericTypeDefinition() == typeof(IList <>)) { typeProp = typeProp.GetGenericArguments()[0]; } if (typeProp.IsGenericType && typeProp.GetGenericTypeDefinition() == typeof(ISet <>)) { typeProp = typeProp.GetGenericArguments()[0]; } if (typeProp.IsArray) { typeProp = typeProp.GetElementType(); } // special case for specialization if (prop.Name.Equals("_PredefinedType")) { FieldInfo[] enumvals = typeProp.GetFields(BindingFlags.Public | BindingFlags.Static); foreach (FieldInfo f in enumvals) { if (f.Name != "USERDEFINED" && f.Name != "NOTDEFINED") { string fname = f.Name; DisplayNameAttribute attrFName = (DisplayNameAttribute)f.GetCustomAttribute <DisplayNameAttribute>(); if (attrName != null) { fname = attrName.DisplayName; } string fdesc = null; DescriptionAttribute attrFDesc = (DescriptionAttribute)f.GetCustomAttribute <DescriptionAttribute>(); if (attrDesc != null) { fdesc = attrDesc.Description; } DisplayAttribute[] localizePredef = (DisplayAttribute[])f.GetCustomAttributes(typeof(DisplayAttribute), false); IfdBase ifdPredef = CreateConcept(type.Name + "." + f.Name, fname, fdesc, IfdConceptTypeEnum.SUBJECT, localizePredef); if (ifdPredef != null) { CreateRelationship(ifdThis.guid, ifdPredef.guid, IfdRelationshipTypeEnum.SPECIALIZES); } } } } else if (conctype == IfdConceptTypeEnum.BAG)// psetprop.FieldType.IsValueType) //!!! { name = type.Name; attrName = (DisplayNameAttribute)prop.GetCustomAttribute <DisplayNameAttribute>(); if (attrName != null) { name = attrName.DisplayName; } desc = null; attrDesc = (DescriptionAttribute)prop.GetCustomAttribute <DescriptionAttribute>(); if (attrDesc != null) { desc = attrDesc.Description; } string propidentifier = type.Name + "." + prop.Name.Substring(1); IfdBase ifdProp = CreateConcept(propidentifier, name, desc, IfdConceptTypeEnum.PROPERTY, null); if (ifdProp == null) { return; } // include the property CreateRelationship(ifdThis.guid, ifdProp.guid, IfdRelationshipTypeEnum.COLLECTS); WriteType(typeProp); if (typeProp.IsValueType) { string guidDataType = null; if (m_mapTypes.TryGetValue(typeProp, out guidDataType)) { CreateRelationship(ifdProp.guid, guidDataType, IfdRelationshipTypeEnum.ASSIGNS_MEASURES);//...verify } } } } }
public static void PrintHelpInfo(ICommandOutlet output, ICommand command) { if (output == null || command == null) { return; } DisplayNameAttribute displayName = (DisplayNameAttribute)TypeDescriptor.GetAttributes(command)[typeof(DisplayNameAttribute)]; DescriptionAttribute description = (DescriptionAttribute)TypeDescriptor.GetAttributes(command)[typeof(DescriptionAttribute)]; output.Write(CommandOutletColor.Blue, command.Name + " "); if (!command.Enabled) { output.Write(CommandOutletColor.DarkGray, "({0})", ResourceUtility.GetString("${Text.Disabled}")); } if (displayName == null || string.IsNullOrWhiteSpace(displayName.DisplayName)) { output.Write(ResourceUtility.GetString("${Text.Command}")); } else { output.Write(ResourceUtility.GetString(displayName.DisplayName, command.GetType().Assembly)); } CommandOptionAttribute[] optionAttributes = (CommandOptionAttribute[])command.GetType().GetCustomAttributes(typeof(CommandOptionAttribute), true); if (optionAttributes != null && optionAttributes.Length > 0) { output.WriteLine("," + ResourceUtility.GetString("${Text.CommandUsages}"), optionAttributes.Length); output.WriteLine(); string commandName = command.Name; output.Write(CommandOutletColor.Blue, commandName + " "); foreach (var optionAttribute in optionAttributes) { if (optionAttribute.Required) { output.Write("<-"); output.Write(CommandOutletColor.DarkYellow, optionAttribute.Name); output.Write("> "); } else { output.Write("[-"); output.Write(CommandOutletColor.DarkYellow, optionAttribute.Name); output.Write("] "); } } output.WriteLine(); int maxOptionLength = GetMaxOptionLength(optionAttributes) + 2; foreach (var optionAttribute in optionAttributes) { int optionPadding = maxOptionLength - optionAttribute.Name.Length; output.Write("\t-"); output.Write(CommandOutletColor.DarkYellow, optionAttribute.Name); if (optionAttribute.Type != null) { output.Write(":"); output.Write(CommandOutletColor.Magenta, GetSimpleTypeName(optionAttribute.Type)); optionPadding -= (GetSimpleTypeName(optionAttribute.Type).Length + 1); } output.Write(" (".PadLeft(optionPadding)); if (optionAttribute.Required) { output.Write(CommandOutletColor.DarkRed, ResourceUtility.GetString("${Text.Required}")); } else { output.Write(CommandOutletColor.DarkGreen, ResourceUtility.GetString("${Text.Optional}")); } output.Write(") "); if (!string.IsNullOrWhiteSpace(optionAttribute.Description)) { output.Write(ResourceUtility.GetString(optionAttribute.Description, command.GetType().Assembly)); } if (optionAttribute.Type != null && optionAttribute.Type.IsEnum) { var entries = Zongsoft.Common.EnumUtility.GetEnumEntries(optionAttribute.Type, false); var maxEnumLength = entries.Max(entry => string.IsNullOrWhiteSpace(entry.Alias) ? entry.Name.Length : entry.Name.Length + entry.Alias.Length + 2); foreach (var entry in entries) { var enumPadding = maxEnumLength - entry.Name.Length; output.WriteLine(); output.Write("\t".PadRight(optionAttribute.Name.Length + 3)); output.Write(CommandOutletColor.DarkMagenta, entry.Name.ToLowerInvariant()); if (!string.IsNullOrWhiteSpace(entry.Alias)) { output.Write(CommandOutletColor.DarkGray, "("); output.Write(CommandOutletColor.DarkMagenta, entry.Alias); output.Write(CommandOutletColor.DarkGray, ")"); enumPadding -= entry.Alias.Length + 2; } if (!string.IsNullOrWhiteSpace(entry.Description)) { output.Write(new string(' ', enumPadding + 1) + entry.Description); } } } output.WriteLine(); } } if (description != null && !string.IsNullOrWhiteSpace(description.Description)) { output.WriteLine(); output.WriteLine(CommandOutletColor.DarkYellow, ResourceUtility.GetString(description.Description, command.GetType().Assembly)); } output.WriteLine(); }
/// <summary> /// Generates the add menu item. /// </summary> /// <returns></returns> public ToolStripMenuItem GenerateAddMenu() { string menuText = string.Format("Add new {0}", source.ItemType.Name); if (!string.IsNullOrEmpty(source.AddMenuText)) { menuText = source.AddMenuText; } ToolStripMenuItem menuItem = new ToolStripMenuItem(menuText); // Set the menu image Bitmap image = Properties.Resources.add_16x16; if (!string.IsNullOrEmpty(source.ImageKey)) { try { image = Properties.Resources.ResourceManager.GetObject(source.ImageKey) as Bitmap; } catch (MissingManifestResourceException) { } } menuItem.Image = image; List <Type> itemTypes = CoreUtil.GetAllItemsOfType(source.ItemType); foreach (Type itemType in itemTypes) { if (!itemType.IsAbstract) { // Retrieve the display name of the item string displayName = itemType.Name; DisplayNameAttribute attribute = CoreUtil.GetCustomAttribute <DisplayNameAttribute>(itemType); if (attribute != null) { displayName = attribute.DisplayName; } // Add the actual menu item ToolStripMenuItem itemMenuItem = new ToolStripMenuItem(displayName); itemMenuItem.Image = CCNetConfig.Properties.Resources.applications_16x16; itemMenuItem.Tag = itemType; menuItem.DropDownItems.Add(itemMenuItem); itemMenuItem.Click += delegate(object sender, EventArgs e) { IList data = RetrieveDataList(); if (data != null) { object newItem = Activator.CreateInstance( (sender as ToolStripMenuItem).Tag as Type); data.Add(newItem); TreeView.SelectedNode = AddItemNode(newItem); TreeView.SelectedNode.EnsureVisible(); } else { MessageBox.Show("Unable to add to parent, list has not be initialised", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); } }; } } return(menuItem); }
public void NameTests(DisplayNameAttribute attribute, string name) { Assert.Equal(name, attribute.DisplayName); }
private void CacheAttributes(IEnumerable<Attribute> attributes) { Contract.Requires(attributes != null); this.Display = attributes.OfType<DisplayAttribute>().FirstOrDefault(); this.DisplayName = attributes.OfType<DisplayNameAttribute>().FirstOrDefault(); }
/// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="table"></param> /// <returns></returns> public static IEnumerable <T> ConvertTableToObjects <T>(this ExcelTable table) where T : new() { //DateTime Conversion var convertDateTime = new Func <double, DateTime>(excelDate => { if (excelDate < 1) { throw new ArgumentException("Excel dates cannot be smaller than 0."); } var dateOfReference = new DateTime(1900, 1, 1); if (excelDate > 60d) { excelDate = excelDate - 2; } else { excelDate = excelDate - 1; } return(dateOfReference.AddDays(excelDate)); }); var getPropertyName = new Func <PropertyInfo, String>( prop => { DisplayNameAttribute attribute = prop.GetCustomAttributes(typeof(DisplayNameAttribute), false).FirstOrDefault() as DisplayNameAttribute; return(attribute?.DisplayName ?? prop.Name); }); //Get the properties of T var tprops = (new T()) .GetType() .GetProperties() .ToList(); //Get the cells based on the table address var start = table.Address.Start; var end = table.Address.End; var cells = new List <ExcelRangeBase>(); //Have to use for loops insteadof worksheet.Cells to protect against empties for (var r = start.Row; r <= end.Row; r++) { for (var c = start.Column; c <= end.Column; c++) { cells.Add(table.WorkSheet.Cells[r, c]); } } var groups = cells .GroupBy(cell => cell.Start.Row) .ToList(); //Assume the second row represents column data types (big assumption!) //var types = groups // .Skip(1) // .First() // .Select(rcell => rcell.Value.GetType()) // .ToList(); var types = tprops.Select(x => new { Name = getPropertyName(x), Type = x.PropertyType }).ToList(); //Assume first row has the column names var colnames = groups .First() .Select((hcell, idx) => new { Name = hcell.Value.ToString(), index = idx }) .Where(o => tprops.Select(p => getPropertyName(p)).Contains(o.Name)) .ToList(); //Everything after the header is data var rowvalues = groups .Skip(1) //Exclude header .Select(cg => cg.Select(c => c.Value).ToList()); //Create the collection container var collection = rowvalues .Select(row => { var tnew = new T(); colnames.ForEach(colname => { //This is the real wrinkle to using reflection - Excel stores all numbers as double including int var val = row[colname.index]; var type = types.First(p => p.Name == colname.Name).Type; //[colname.index]; var prop = tprops.First(p => getPropertyName(p) == colname.Name); //If it is numeric it is a double since that is how excel stores all numbers if (type == typeof(double) || type == typeof(Int32) || type == typeof(DateTime) || type == typeof(double?) || type == typeof(Int32?) || type == typeof(DateTime?)) { if (!string.IsNullOrWhiteSpace(val?.ToString())) { //Unbox it var unboxedVal = (double)val; //FAR FROM A COMPLETE LIST!!! if (prop.PropertyType == typeof(Int32) || prop.PropertyType == typeof(Int32?)) { prop.SetValue(tnew, (int)unboxedVal); } else if (prop.PropertyType == typeof(double) || prop.PropertyType == typeof(double?)) { prop.SetValue(tnew, unboxedVal); } else if (prop.PropertyType == typeof(DateTime) || prop.PropertyType == typeof(DateTime?)) { prop.SetValue(tnew, convertDateTime(unboxedVal)); } else { throw new NotImplementedException(String.Format("Type '{0}' not implemented yet!", prop.PropertyType.Name)); } } } else { //Its a string prop.SetValue(tnew, val); } }); return(tnew); }); //Send it back return(collection); }
public void TestDisplayNameAttribute_BlankArg() { var attribute = new DisplayNameAttribute(UnitTestHelper.BLANK_STRING); Assert.AreEqual("", attribute.DisplayName); Assert.AreEqual("", new DisplayNameAttribute("").DisplayName); }
private Type DiscoverRecordFields(Type recordType, string declaringMember, bool optIn = false, List <ChoYamlRecordFieldConfiguration> recordFieldConfigurations = null, bool isTop = false) { if (recordType == null) { return(recordType); } if (!recordType.IsDynamicType()) { Type pt = null; if (ChoTypeDescriptor.GetProperties(recordType).Where(pd => pd.Attributes.OfType <ChoYamlRecordFieldAttribute>().Any()).Any()) { foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(recordType)) { pt = pd.PropertyType.GetUnderlyingType(); bool optIn1 = ChoTypeDescriptor.GetProperties(pt).Where(pd1 => pd1.Attributes.OfType <ChoYamlRecordFieldAttribute>().Any()).Any(); if (optIn1 && !pt.IsSimple() && !typeof(IEnumerable).IsAssignableFrom(pt) && FlatToNestedObjectSupport) { DiscoverRecordFields(pt, declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name), optIn1, recordFieldConfigurations, false); } else if (pd.Attributes.OfType <ChoYamlRecordFieldAttribute>().Any()) { var obj = new ChoYamlRecordFieldConfiguration(pd.Name, pd.Attributes.OfType <ChoYamlRecordFieldAttribute>().First(), pd.Attributes.OfType <Attribute>().ToArray()); obj.FieldType = pt; obj.PropertyDescriptor = pd; obj.DeclaringMember = declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name); if (recordFieldConfigurations != null) { if (!recordFieldConfigurations.Any(c => c.Name == pd.Name)) { recordFieldConfigurations.Add(obj); } } } } } else { if (isTop) { if (typeof(IList).IsAssignableFrom(recordType)) { throw new ChoParserException("Record type not supported."); } else if (typeof(IDictionary <string, object>).IsAssignableFrom(recordType)) { recordType = typeof(ExpandoObject); return(recordType); } else if (typeof(IDictionary).IsAssignableFrom(recordType)) { recordType = typeof(ExpandoObject); return(recordType); } } if (recordType.IsSimple()) { var obj = new ChoYamlRecordFieldConfiguration("Value", "$.Value"); obj.FieldType = recordType; recordFieldConfigurations.Add(obj); return(recordType); } foreach (PropertyDescriptor pd in ChoTypeDescriptor.GetProperties(recordType)) { ChoYamlIgnoreAttribute jiAttr = pd.Attributes.OfType <ChoYamlIgnoreAttribute>().FirstOrDefault(); if (jiAttr != null) { continue; } pt = pd.PropertyType.GetUnderlyingType(); if (pt != typeof(object) && !pt.IsSimple() && !typeof(IEnumerable).IsAssignableFrom(pt) && FlatToNestedObjectSupport) { DiscoverRecordFields(pt, declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name), optIn, recordFieldConfigurations, false); } else { var obj = new ChoYamlRecordFieldConfiguration(pd.Name, (string)null); obj.FieldType = pt; obj.PropertyDescriptor = pd; obj.DeclaringMember = declaringMember == null ? pd.Name : "{0}.{1}".FormatString(declaringMember, pd.Name); StringLengthAttribute slAttr = pd.Attributes.OfType <StringLengthAttribute>().FirstOrDefault(); if (slAttr != null && slAttr.MaximumLength > 0) { obj.Size = slAttr.MaximumLength; } //ChoUseYamlSerializationAttribute sAttr = pd.Attributes.OfType<ChoUseYamlSerializationAttribute>().FirstOrDefault(); //if (sAttr != null) // obj.UseYamlSerialization = sAttr.Flag; ChoYamlPathAttribute jpAttr = pd.Attributes.OfType <ChoYamlPathAttribute>().FirstOrDefault(); if (jpAttr != null) { obj.YamlPath = jpAttr.YamlPath; } ChoYamPropertyAttribute jAttr = pd.Attributes.OfType <ChoYamPropertyAttribute>().FirstOrDefault(); if (jAttr != null && !jAttr.PropertyName.IsNullOrWhiteSpace()) { obj.FieldName = jAttr.PropertyName; } else { DisplayNameAttribute dnAttr = pd.Attributes.OfType <DisplayNameAttribute>().FirstOrDefault(); if (dnAttr != null && !dnAttr.DisplayName.IsNullOrWhiteSpace()) { obj.FieldName = dnAttr.DisplayName.Trim(); } else { DisplayAttribute dpAttr = pd.Attributes.OfType <DisplayAttribute>().FirstOrDefault(); if (dpAttr != null) { if (!dpAttr.ShortName.IsNullOrWhiteSpace()) { obj.FieldName = dpAttr.ShortName; } else if (!dpAttr.Name.IsNullOrWhiteSpace()) { obj.FieldName = dpAttr.Name; } obj.Order = dpAttr.Order; } else { ColumnAttribute clAttr = pd.Attributes.OfType <ColumnAttribute>().FirstOrDefault(); if (clAttr != null) { obj.Order = clAttr.Order; if (!clAttr.Name.IsNullOrWhiteSpace()) { obj.FieldName = clAttr.Name; } } } } } DisplayFormatAttribute dfAttr = pd.Attributes.OfType <DisplayFormatAttribute>().FirstOrDefault(); if (dfAttr != null && !dfAttr.DataFormatString.IsNullOrWhiteSpace()) { obj.FormatText = dfAttr.DataFormatString; } if (dfAttr != null && !dfAttr.NullDisplayText.IsNullOrWhiteSpace()) { obj.NullValue = dfAttr.NullDisplayText; } if (recordFieldConfigurations != null) { if (!recordFieldConfigurations.Any(c => c.Name == pd.Name)) { recordFieldConfigurations.Add(obj); } } } } } } return(recordType); }
public void TestDisplayNameAttribute() { var attribute = new DisplayNameAttribute(SAMPLE_DISPLAY_NAME); Assert.AreEqual(SAMPLE_DISPLAY_NAME, attribute.DisplayName); Assert.AreEqual("123", new DisplayNameAttribute(" 123\t\t\n").DisplayName); }
public DisplayNameAttribute Constructor(string displayName) { var target = new DisplayNameAttribute(displayName); Assert.AreEqual(target.DisplayName,displayName); return target; }
/// <summary> /// Deploys values according to values found in attributes /// </summary> /// <param name="propAttributes">The property attributes.</param> public void deployAttributes(Object[] propAttributes) { foreach (Object propAtt in propAttributes) { descAttribute = propAtt as DescriptionAttribute; if (descAttribute != null) { description = descAttribute.Description; } displayNameAttribute = propAtt as DisplayNameAttribute; if (displayNameAttribute != null) { displayName = displayNameAttribute.DisplayName; } catAttribute = propAtt as CategoryAttribute; if (catAttribute != null) { categoryName = catAttribute.Category.ToUpper(); if (categoryName.Contains(",")) { groups.AddRange(categoryName.getStringTokens()); } else { groups.Add(categoryName); } } if (propAtt is DisplayAttribute) { DisplayAttribute displayAttribute_DisplayAttribute = (DisplayAttribute)propAtt; description += displayAttribute_DisplayAttribute.Description.toStringSafe(""); displayName = displayAttribute_DisplayAttribute.Name.toStringSafe(displayName); letter = displayAttribute_DisplayAttribute.ShortName.toStringSafe(letter); // priority = (int)displayAttribute_DisplayAttribute.Order; categoryName = displayAttribute_DisplayAttribute.GroupName.toStringSafe(categoryName); } if (propAtt is RangeAttribute) { RangeAttribute rng = (RangeAttribute)propAtt; range_defined = true; range_min = Convert.ToDouble((object)rng.Minimum); range_max = Convert.ToDouble((object)rng.Maximum); } if (propAtt is DisplayFormatAttribute) { DisplayFormatAttribute dFormat = (DisplayFormatAttribute)propAtt; escapeValueString = dFormat.HtmlEncode; format = dFormat.DataFormatString; } if (propAtt is DisplayColumnAttribute) { DisplayColumnAttribute dColumn = (DisplayColumnAttribute)propAtt; displayName = dColumn.DisplayColumn; } if (propAtt is XmlIgnoreAttribute) { IsXmlIgnore = true; } if (propAtt is imbAttribute imbAt) { switch (imbAt.nameEnum) { case imbAttributeName.DataTableExport: templateFieldDataTable dtc = (templateFieldDataTable)imbAt.objMsg; Object dtc_val = imbAt.objExtra; deploy(dtc, dtc_val); //propAtt_imbAttribute.objExtra break; case imbAttributeName.reporting_aggregation: aggregation[(dataPointAggregationAspect)imbAt.objExtra] = (dataPointAggregationType)imbAt.objMsg; break; } deploy(imbAt.nameEnum, imbAt.getMessage().toStringSafe()); if (!attributes.ContainsKey(imbAt.nameEnum)) { attributes.Add(imbAt.nameEnum, imbAt); } else { } } } }
/// <summary> /// Gets the display name from the attribute. /// </summary> /// <param name="attribute">The attribute.</param> /// <returns>System.String.</returns> protected string GetDisplayName(DisplayNameAttribute attribute) { var languageService = LanguageService; if (languageService != null) { attribute.LanguageService = languageService; } return attribute.DisplayName; }
//--------------------------------------------------------------------------------------------------------- /// <summary> /// Получение данных описание свойства с его атрибутов /// </summary> //--------------------------------------------------------------------------------------------------------- protected void ApplyInfoFromAttributes() { if (mInfo != null) { DisplayNameAttribute display_name = mInfo.GetAttribute <DisplayNameAttribute>(); if (display_name != null && String.IsNullOrEmpty(mDisplayName)) { mDisplayName = display_name.DisplayName; } DescriptionAttribute description = mInfo.GetAttribute <DescriptionAttribute>(); if (description != null && String.IsNullOrEmpty(mDescription)) { mDescription = description.Description; } CubeXPropertyOrderAttribute property_order = mInfo.GetAttribute <CubeXPropertyOrderAttribute>(); if (property_order != null) { mPropertyOrder = property_order.Order; } CubeXAutoOrderAttribute auto_order = mInfo.GetAttribute <CubeXAutoOrderAttribute>(); if (auto_order != null) { mPropertyOrder = auto_order.Order; } CategoryAttribute category = mInfo.GetAttribute <CategoryAttribute>(); if (category != null && String.IsNullOrEmpty(mCategory)) { mCategory = category.Category; } CubeXCategoryOrderAttribute category_order = mInfo.GetAttribute <CubeXCategoryOrderAttribute>(); if (category_order != null) { mCategoryOrder = category_order.Order; } ReadOnlyAttribute read_only = mInfo.GetAttribute <ReadOnlyAttribute>(); if (read_only != null) { mIsReadOnly = read_only.IsReadOnly; } if (mInfo.CanWrite == false) { mIsReadOnly = true; } DefaultValueAttribute default_value = mInfo.GetAttribute <DefaultValueAttribute>(); if (default_value != null) { mDefaultValue = default_value.Value; } CubeXListValuesAttribute list_values = mInfo.GetAttribute <CubeXListValuesAttribute>(); if (list_values != null) { mListValues = list_values.ListValues; mListValuesMemberName = list_values.MemberName; mListValuesMemberType = list_values.MemberType; } CubeXNumberFormatAttribute format_value = mInfo.GetAttribute <CubeXNumberFormatAttribute>(); if (format_value != null && String.IsNullOrEmpty(mFormatValue)) { mFormatValue = format_value.FormatValue; } CubeXButtonAttribute button_method = mInfo.GetAttribute <CubeXButtonAttribute>(); if (button_method != null && button_method.MethodName.IsExists()) { mButtonCaption = button_method.Label; mButtonMethodName = button_method.MethodName; } } }
public void Initialize() { if (isInitialized) { return; } lock (this.initializeLock) { Dictionary <string, FieldInfo> rowFields; Dictionary <string, PropertyInfo> rowProperties; GetRowFieldsAndProperties(out rowFields, out rowProperties); foreach (var fieldInfo in this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public)) { if (fieldInfo.FieldType.IsSubclassOf(typeof(Field))) { var field = (Field)fieldInfo.GetValue(this); PropertyInfo property; if (!rowProperties.TryGetValue(fieldInfo.Name, out property)) { property = null; } ColumnAttribute column = null; DisplayNameAttribute display = null; SizeAttribute size = null; ExpressionAttribute expression = null; ScaleAttribute scale = null; MinSelectLevelAttribute selectLevel = null; ForeignKeyAttribute foreignKey = null; LeftJoinAttribute foreignJoin = null; DefaultValueAttribute defaultValue = null; TextualFieldAttribute textualField = null; DateTimeKindAttribute dateTimeKind = null; FieldFlags addFlags = (FieldFlags)0; FieldFlags removeFlags = (FieldFlags)0; if (property != null) { column = property.GetCustomAttribute <ColumnAttribute>(false); display = property.GetCustomAttribute <DisplayNameAttribute>(false); size = property.GetCustomAttribute <SizeAttribute>(false); expression = property.GetCustomAttribute <ExpressionAttribute>(false); scale = property.GetCustomAttribute <ScaleAttribute>(false); selectLevel = property.GetCustomAttribute <MinSelectLevelAttribute>(false); foreignKey = property.GetCustomAttribute <ForeignKeyAttribute>(false); foreignJoin = property.GetCustomAttributes <LeftJoinAttribute>(false).FirstOrDefault(x => x.ToTable == null && x.OnCriteria == null); defaultValue = property.GetCustomAttribute <DefaultValueAttribute>(false); textualField = property.GetCustomAttribute <TextualFieldAttribute>(false); dateTimeKind = property.GetCustomAttribute <DateTimeKindAttribute>(false); var insertable = property.GetCustomAttribute <InsertableAttribute>(false); var updatable = property.GetCustomAttribute <UpdatableAttribute>(false); if (insertable != null && !insertable.Value) { removeFlags |= FieldFlags.Insertable; } if (updatable != null && !updatable.Value) { removeFlags |= FieldFlags.Updatable; } foreach (var attr in property.GetCustomAttributes <SetFieldFlagsAttribute>(false)) { addFlags |= attr.Add; removeFlags |= attr.Remove; } } if (ReferenceEquals(null, field)) { if (property == null) { throw new InvalidProgramException(String.Format( "Field {0} in type {1} is null and has no corresponding property in entity!", fieldInfo.Name, rowType.Name)); } object[] prm = new object[7]; prm[0] = this; // owner prm[1] = column == null ? property.Name : (column.Name.TrimToNull() ?? property.Name); prm[2] = display != null ? new LocalText(display.DisplayName) : null; prm[3] = size != null ? size.Value : 0; prm[4] = (FieldFlags.Default ^ removeFlags) | addFlags; prm[5] = null; prm[6] = null; FieldInfo storage; if (rowFields.TryGetValue("_" + property.Name, out storage) || rowFields.TryGetValue("m_" + property.Name, out storage) || rowFields.TryGetValue(property.Name, out storage)) { prm[5] = CreateFieldGetMethod(storage); prm[6] = CreateFieldSetMethod(storage); } field = (Field)Activator.CreateInstance(fieldInfo.FieldType, prm); fieldInfo.SetValue(this, field); } else { if (size != null) { throw new InvalidProgramException(String.Format( "Field size '{0}' in type {1} can't be overridden by Size attribute!", fieldInfo.Name, rowType.Name)); } if (display != null) { field.Caption = new LocalText(display.DisplayName); } if ((int)addFlags != 0 || (int)removeFlags != 0) { field.Flags = (field.Flags ^ removeFlags) | addFlags; } if (column != null && String.Compare(column.Name, field.Name, StringComparison.OrdinalIgnoreCase) != 0) { throw new InvalidProgramException(String.Format( "Field name '{0}' in type {1} can't be overridden by Column name attribute!", fieldInfo.Name, rowType.Name)); } } if (scale != null) { field.Scale = scale.Value; } if (defaultValue != null) { field.DefaultValue = defaultValue.Value; } if (selectLevel != null) { field.MinSelectLevel = selectLevel.Value; } if (expression != null) { field.Expression = expression.Value; } if (foreignKey != null) { field.ForeignTable = foreignKey.Table; field.ForeignField = foreignKey.Field; } if (foreignJoin != null) { field.ForeignJoinAlias = new LeftJoin(this.joins, field.ForeignTable, foreignJoin.Alias, new Criteria(foreignJoin.Alias, field.ForeignField) == new Criteria(field)); } if (textualField != null) { field.textualField = textualField.Value; } if (dateTimeKind != null && field is DateTimeField) { ((DateTimeField)field).DateTimeKind = dateTimeKind.Value; } if (property != null) { if (property.PropertyType != null && field is IEnumTypeField) { if (property.PropertyType.IsEnum) { (field as IEnumTypeField).EnumType = property.PropertyType; } else { var nullableType = Nullable.GetUnderlyingType(property.PropertyType); if (nullableType != null && nullableType.IsEnum) { (field as IEnumTypeField).EnumType = nullableType; } } } foreach (var attr in property.GetCustomAttributes <LeftJoinAttribute>()) { if (attr.ToTable != null && attr.OnCriteria != null) { new LeftJoin(this.joins, attr.ToTable, attr.Alias, new Criteria(attr.Alias, attr.OnCriteria) == new Criteria(field)); } } field.PropertyName = property.Name; this.byPropertyName[field.PropertyName] = field; field.CustomAttributes = property.GetCustomAttributes(false); } } } foreach (var attr in this.rowType.GetCustomAttributes <LeftJoinAttribute>()) { new LeftJoin(this.joins, attr.ToTable, attr.Alias, new Criteria(attr.OnCriteria)); } foreach (var attr in this.rowType.GetCustomAttributes <OuterApplyAttribute>()) { new OuterApply(this.joins, attr.InnerQuery, attr.Alias); } var propertyDescriptorArray = new PropertyDescriptor[this.Count]; for (int i = 0; i < this.Count; i++) { var field = this[i]; propertyDescriptorArray[i] = new FieldDescriptor(field); } this.propertyDescriptors = new PropertyDescriptorCollection(propertyDescriptorArray); InferTextualFields(); AfterInitialize(); } isInitialized = true; }
/// <summary> /// 获取成员元数据的DisplayName特性描述信息 /// </summary> /// <param name="member">成员元数据对象</param> /// <param name="inherit">是否搜索成员的继承链以查找描述特性</param> /// <returns>返回DisplayName特性描述信息,如不存在则返回成员的名称</returns> public static string ToDisplayName(this MemberInfo member, bool inherit = false) { DisplayNameAttribute attr = member.GetCustomAttribute <DisplayNameAttribute>(inherit); return(attr?.DisplayName); }
public MetaTableMetadata(MetaTable table) { Debug.Assert(table != null); Attributes = table.BuildAttributeCollection(); _readOnlyAttribute = Attributes.FirstOrDefault<ReadOnlyAttribute>(); _displayNameAttribute = Attributes.FirstOrDefault<DisplayNameAttribute>(); DisplayColumnAttribute = Attributes.FirstOrDefault<DisplayColumnAttribute>(); ScaffoldTable = Attributes.GetAttributePropertyValue<ScaffoldTableAttribute, bool?>(a => a.Scaffold, null); }