示例#1
0
    /// <summary>
    /// Gets a comma separated string with the column names. Meant to build queries.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public static string GetColumnNames(Type type)
    {
        //getting properties in a specific order
        Dictionary <string, string> Mapping = new Dictionary <string, string>();
        TypeInfo            typeInfo        = type.GetTypeInfo();
        List <PropertyInfo> properties      = new List <PropertyInfo>();
        PropertyInfo        idPropertyInfo  = typeInfo.GetProperty("Id");

        if (idPropertyInfo != null)
        {
            properties.Add(typeInfo.GetProperty("Id"));                          //TODO: this is because Join reader always assume Id comes first
        }
        properties.AddRange(typeInfo.GetProperties().Where(p => p.Name != "Id" && !p.CustomAttributes.Any(x => x.AttributeType == typeof(NotMappedAttribute))).OrderBy(p => p.Name).ToList());
        foreach (PropertyInfo p in properties)
        {
            ColumnNameAttribute cma = p.GetCustomAttribute <ColumnNameAttribute>();
            TableAliasAttribute taa = p.GetCustomAttribute <TableAliasAttribute>();
            if (taa == null)
            {
                throw new Exception("Table alias must be defined for each mapped attribute.");
            }
            Mapping.Add(p.Name, cma != null ? $"{taa.Alias}.{cma.ColumnName}" : $"{taa.Alias}.{p.Name}");
        }
        return(String.Join(", ", Mapping.Values));
    }
示例#2
0
        public void ColumnName_Is_As_Expected()
        {
            const string columnName = "TestColumnName";
            var attribute = new ColumnNameAttribute(columnName);

            Assert.AreEqual(columnName, attribute.ColumnName);
        }
示例#3
0
        protected override Expression VisitMemberAccess(MemberExpression m)
        {
            if (m.Expression != null && m.Expression.NodeType == ExpressionType.Parameter)
            {
                object entity              = Expression.Lambda <Func <object> >(Expression.Convert(Expression.New(m.Expression.Type), typeof(object))).Compile()();
                var    property            = (PropertyInfo)m.Member;
                ColumnNameAttribute Column = entity.GetType().GetTypeInfo().GetProperty(property.Name).GetCustomAttribute <ColumnNameAttribute>();
                string ColumnName          = Column == null?entity.GetType().GetProperty(property.Name).Name : Column.ColumnName;

                if (IgnoreAliases)
                {
                    sb.Append("[" + ColumnName + "]");
                }
                else
                {
                    sb.Append(m.Expression + "." + "[" + ColumnName + "]");
                }
                return(m);
            }
            if (m.Expression != null && (m.Expression.NodeType == ExpressionType.Constant || m.Expression.NodeType == ExpressionType.MemberAccess))
            {
                var    f             = Expression.Lambda(m).Compile();
                var    value         = f.DynamicInvoke();
                string parameterName = "@P" + (predicate.Parameters.Count + Initial);
                sb.Append(parameterName);
                predicate.Parameters.Add(parameterName, value);
                return(m);
            }
            throw new NotSupportedException(string.Format("The member '{0}' is not supported", m.Member.Name));
        }
示例#4
0
        public void SetFromReader(ref SqlDataReader reader)
        {
            _currentField = (T)Activator.CreateInstance(typeof(T));

            Attribute member = typeof(T).GetCustomAttribute <SPBP.Connector.Attributes.DbObjectAttribute>();

            if (member != null)
            {
                IEnumerable <PropertyInfo> specialProps =
                    typeof(T).GetRuntimeProperties()
                    .Where(
                        p =>
                        p.GetCustomAttributes <SPBP.Connector.Attributes.ColumnNameAttribute>(true).Any());

                foreach (PropertyInfo prop in specialProps)
                {
                    ColumnNameAttribute atr = prop.GetCustomAttribute(typeof(ColumnNameAttribute)) as ColumnNameAttribute;

                    if (atr != null && atr.HasValue)
                    {
                        prop.SetValue(_currentField, Convert.ChangeType(reader[atr.Value], prop.PropertyType));
                    }
                    else
                    {
                        prop.SetValue(_currentField, Convert.ChangeType(reader[prop.Name], prop.PropertyType));
                    }
                }

                _objects.Add(_currentField);
            }
            else
            {
                throw new AttributeMissMatchException();
            }
        }
示例#5
0
        public void ColumnName_Is_As_Expected()
        {
            const string columnName = "TestColumnName";
            var          attribute  = new ColumnNameAttribute(columnName);

            Assert.AreEqual(columnName, attribute.ColumnName);
        }
示例#6
0
    public static Dictionary <string, ColumnInfo> GetTableMapping <T>()
    {
        //getting properties in a specific order
        Dictionary <string, ColumnInfo> TableMapping = new Dictionary <string, ColumnInfo>();
        TypeInfo            typeInfo       = typeof(T).GetTypeInfo();
        List <PropertyInfo> properties     = new List <PropertyInfo>();
        PropertyInfo        idPropertyInfo = typeInfo.GetProperty("Id");

        if (idPropertyInfo != null)
        {
            properties.Add(typeInfo.GetProperty("Id"));                          //TODO: this is because Join reader always assume Id comes first
        }
        properties.AddRange(typeof(T).GetTypeInfo().GetProperties().Where(p => p.Name != "Id").OrderBy(p => p.Name).ToList());
        foreach (PropertyInfo p in properties)
        {
            NotMappedAttribute nm = p.GetCustomAttribute <NotMappedAttribute>();
            if (nm == null)
            {
                ColumnNameAttribute cma = p.GetCustomAttribute <ColumnNameAttribute>();
                TableMapping.Add(p.Name, new ColumnInfo {
                    ColumnName = cma != null ? cma.ColumnName : p.Name, ColumnType = p.PropertyType
                });
            }
        }
        return(TableMapping);
    }
示例#7
0
        public void GetTypeWithAdditionalDataViewTypeAttributes()
        {
            var a = new DataViewAlienBodyType(7788);
            var b = new AlienTypeAttributeAttribute(8877);
            var c = new ColumnNameAttribute("foo");
            var d = new AlienTypeAttributeAttribute(8876);


            DataViewTypeManager.Register(a, typeof(AlienBody), b);
            Assert.True(DataViewTypeManager.Knows(a));
            Assert.True(DataViewTypeManager.Knows(typeof(AlienBody), new Attribute[] { b, c }));
            // "a" is associated with typeof(AlienBody) with "b," so the call below should return true.
            Assert.Equal(a, DataViewTypeManager.GetDataViewType(typeof(AlienBody), new Attribute[] { b, c }));
            Assert.Throws <ArgumentOutOfRangeException>(() => DataViewTypeManager.Knows(typeof(AlienBody), new Attribute[] { b, d }));
        }
示例#8
0
        public static string GetDisplayName(this PropertyInfo property)
        {
            ColumnNameAttribute  columnName  = property.GetAttribute <ColumnNameAttribute>();
            DisplayNameAttribute displayName = property.GetAttribute <DisplayNameAttribute>();

            if (displayName.IsNotNull())
            {
                return(displayName.DisplayName);
            }
            if (columnName.IsNotNull())
            {
                return(columnName.ColumnName);
            }

            return(property.Name.AsReadable());
        }
示例#9
0
文件: Query.cs 项目: Fandradec/Dook
        private void GetTableData()
        {
            TableMapping = new Dictionary <string, string>();
            PropertyInfo[] properties = typeof(T).GetTypeInfo().GetProperties();
            foreach (PropertyInfo p in properties)
            {
                NotMappedAttribute nm = p.GetCustomAttribute <NotMappedAttribute>();
                if (nm == null)
                {
                    ColumnNameAttribute cma = p.GetCustomAttribute <ColumnNameAttribute>();
                    TableMapping.Add(p.Name, cma != null ? cma.ColumnName : p.Name);
                }
            }
            TableNameAttribute tableNameAtt = typeof(T).GetTypeInfo().GetCustomAttribute <TableNameAttribute>();

            TableName = tableNameAtt != null ? tableNameAtt.TableName : typeof(T).Name + "s";
            alias     = TableName.First().ToString().ToLower();
        }
示例#10
0
        public ImportColumnProperty(PropertyInfo property, ColumnNameAttribute attr)
        {
            this.Name         = attr.Name;
            this.PropertyInfo = property;
            if (property.GetCustomAttribute(typeof(ColumnRegexAttribute)) is ColumnRegexAttribute attr2)
            {
                this.SetRegexData(attr2);
            }

            if (property.GetCustomAttribute(typeof(ColumnRequiredAttribute)) is ColumnRequiredAttribute attr3)
            {
                this.SetRequiredData(attr3);
            }

            if (property.GetCustomAttribute(typeof(ColumnUniqueAttribute)) is ColumnUniqueAttribute)
            {
                this.IsUnique = true;
            }
        }
示例#11
0
        //取得要class要放在Excel的欄位名稱
        public List <string> GetExcelColumn()
        {
            List <string> column = new List <string>();
            //取得類別的ColumnNameAttribute
            var p       = typeof(Park);
            var headers = p.GetProperties();

            foreach (PropertyInfo prop in headers)
            {
                //取得所有自訂屬性陣列
                object[] attrs = prop.GetCustomAttributes(true);
                foreach (var attr in attrs)
                {
                    ColumnNameAttribute customAttr = attr as ColumnNameAttribute;
                    column.Add(customAttr?.Description);
                }
            }
            return(column);
        }
示例#12
0
        /// <summary>
        /// Создать шаблон таблицы на основе типа
        /// </summary>
        /// <param name="TableName">Имя таблицы</param>
        /// <param name="WrappedType">Тип, размеченный аттрибутами ColumnName (и ему подобными)</param>
        /// <returns>Таблица</returns>
        public static DataTable GenTable(string TableName, Type WrappedType)
        {
            DataTable result = new DataTable(TableName);

            foreach (PropertyInfo var in WrappedType.GetProperties())
            {
                ColumnNameAttribute name = (ColumnNameAttribute)Attribute.GetCustomAttribute(var, typeof(ColumnNameAttribute));
                if (name != null)
                {
                    DataColumn          column = new DataColumn(name.ColumnName, var.PropertyType);
                    ColumnTextAttribute text   = (ColumnTextAttribute)Attribute.GetCustomAttribute(var, typeof(ColumnTextAttribute));
                    if (text != null)
                    {
                        column.Caption = text.ColumnText;
                    }
                    result.Columns.Add(column);
                }
            }
            return(result);
        }
示例#13
0
        private void AddPropertyChangedHandler()
        {
            this.propertyChanged += (s, e) =>
            {
                if (e.PropertyName.Equals("AssociatedProperty") ||
                    e.PropertyName.Equals("Tag"))
                {
                    if (this.AssociatedProperty.IsNull())
                    {
                        this.Text = "Column";
                    }
                    else
                    {
                        ColumnNameAttribute columnName = this.AssociatedProperty.GetAttribute <ColumnNameAttribute>();
                        this.Text = (columnName.IsNotNull()) ? columnName.ColumnName : this.AssociatedProperty != null?this.AssociatedProperty.Name.AsReadable() : "Column";

                        this.Name = string.Format("dch{0}", this.AssociatedProperty.Name);
                    }
                }
            };
        }
示例#14
0
        /// <summary>
        /// Распарсить строку в объект
        /// </summary>
        /// <typeparam name="T">Тип объекта</typeparam>
        /// <param name="Row">Строка</param>
        /// <returns>Объект</returns>
        public static T GenObjectFromRow <T>(DataRow Row) where T : new()
        {
            T result = new T();

            foreach (PropertyInfo var in result.GetType().GetProperties())
            {
                ColumnNameAttribute name = (ColumnNameAttribute)Attribute.GetCustomAttribute(var, typeof(ColumnNameAttribute));
                if (name != null)
                {
                    if (Row.Table.Columns.Contains(name.ColumnName))
                    {
                        MethodInfo mi = var.GetSetMethod();
                        if (mi != null)
                        {
                            mi.Invoke(result, new object[] { Row[name.ColumnName] });
                        }
                    }
                }
            }
            return(result);
        }
示例#15
0
        private ColumnFieldDefinition GetColumnFieldDefByProprty(PropertyInfo prop)
        {
            object[]            attrs       = prop.GetCustomAttributes(true);
            var                 ret         = new ColumnFieldDefinition();
            ColumnNameAttribute colNameAttr = null;
            ColumnTypeAttribute colTypeAttr = null;

            foreach (object attr in attrs)
            {
                if (attr.GetType().Equals(typeof(ColumnNameAttribute)))
                {
                    colNameAttr = attr as ColumnNameAttribute;
                }
                if (attr.GetType().Equals(typeof(ColumnTypeAttribute)))
                {
                    colTypeAttr = attr as ColumnTypeAttribute;
                }
            }
            AsignColNameAttrToDef(ret, colNameAttr, prop);
            AsignColTypeAttrToDef(ret, colTypeAttr, prop);
            return(ret);
        }
示例#16
0
        /// <summary>
        /// Сгенерить строку таблицы на основе объекта
        /// </summary>
        /// <param name="Value">Объект, по которому генерится строка</param>
        /// <param name="Table">Таблица, для которой генерится строка</param>
        /// <returns>Строка</returns>
        public static DataRow GenRowFromObject(object Value, DataTable Table)
        {
            DataRow result = Table.NewRow();

            foreach (PropertyInfo var in Value.GetType().GetProperties())
            {
                ColumnNameAttribute name = (ColumnNameAttribute)Attribute.GetCustomAttribute(var, typeof(ColumnNameAttribute));
                if (name != null)
                {
                    if (Table.Columns.Contains(name.ColumnName))
                    {
                        MethodInfo mi = var.GetGetMethod();
                        if (mi != null)
                        {
                            Object obj = mi.Invoke(Value, null);
                            result[name.ColumnName] = obj;
                        }
                    }
                }
            }
            return(result);
        }
示例#17
0
        /// <summary>
        /// Наполнить ячейки данными из объекта.
        /// </summary>
        /// <param name="cells">Коллекция ячеек</param>
        /// <param name="obj">Объект, откуда брать данные</param>
        /// <param name="dgv">Грида, в которой всё происходит</param>
        /// <param name="withTagFilling">Пихать ли в <c>DataGridViewCell.Tag</c> ссылку на данные</param>
        public static void ParseAllPropsIntoCells(DataGridViewCellCollection cells, object obj, DataGridView dgv, bool withTagFilling)
        {
            foreach (PropertyInfo prop in obj.GetType().GetProperties())
            {
                ColumnNameAttribute attName = (ColumnNameAttribute)Attribute.GetCustomAttribute(prop, typeof(ColumnNameAttribute));
                if (attName != null)
                {
                    if (dgv.Columns.Contains(attName.ColumnName))
                    {
                        cells[ToIndex(attName.ColumnName, dgv)].Value = prop.GetGetMethod().Invoke(obj, null).ToString();
                        if (withTagFilling)
                        {
                            cells[ToIndex(attName.ColumnName, dgv)].Tag = prop.GetGetMethod().Invoke(obj, null);
                        }

                        StyleFormatAttribute attSt = (StyleFormatAttribute)Attribute.GetCustomAttribute(prop, typeof(StyleFormatAttribute));
                        if (attSt != null)
                        {
                            cells[ToIndex(attName.ColumnName, dgv)].Style.Format = attSt.StyleFormat;
                        }
                    }
                }
            }
        }
示例#18
0
        protected virtual Field GenerateField(ITable table, PropertyRoute route, NameSequence preName, bool forceNull, bool inMList)
        {
            KindOfField kof = GetKindOfField(route).ThrowIfNull(() => "Field {0} of type {1} has no database representation".FormatWith(route, route.Type.Name));

            if (kof == KindOfField.MList && inMList)
            {
                throw new InvalidOperationException("Field {0} of type {1} can not be nested in another MList".FormatWith(route, route.Type.TypeName(), kof));
            }

            //field name generation
            NameSequence        name;
            ColumnNameAttribute vc = Settings.FieldAttribute <ColumnNameAttribute>(route);

            if (vc != null && vc.Name.HasText())
            {
                name = NameSequence.Void.Add(vc.Name);
            }
            else if (route.PropertyRouteType != PropertyRouteType.MListItems)
            {
                name = preName.Add(GenerateFieldName(route, kof));
            }
            else if (kof == KindOfField.Enum || kof == KindOfField.Reference)
            {
                name = preName.Add(GenerateMListFieldName(route, kof));
            }
            else
            {
                name = preName;
            }

            switch (kof)
            {
            case KindOfField.PrimaryKey:
                return(GenerateFieldPrimaryKey((Table)table, route, name));

            case KindOfField.Ticks:
                return(GenerateFieldTicks((Table)table, route, name));

            case KindOfField.Value:
                return(GenerateFieldValue(table, route, name, forceNull));

            case KindOfField.Reference:
            {
                Implementations at = Settings.GetImplementations(route);
                if (at.IsByAll)
                {
                    return(GenerateFieldImplementedByAll(route, table, name, forceNull));
                }
                else if (at.Types.Only() == route.Type.CleanType())
                {
                    return(GenerateFieldReference(table, route, name, forceNull));
                }
                else
                {
                    return(GenerateFieldImplementedBy(table, route, name, forceNull, at.Types));
                }
            }

            case KindOfField.Enum:
                return(GenerateFieldEnum(table, route, name, forceNull));

            case KindOfField.Embedded:
                return(GenerateFieldEmbedded(table, route, name, forceNull, inMList));

            case KindOfField.MList:
                return(GenerateFieldMList((Table)table, route, name));

            default:
                throw new NotSupportedException(EngineMessage.NoWayOfMappingType0Found.NiceToString().FormatWith(route.Type));
            }
        }
示例#19
0
 private void AsignColNameAttrToDef(ColumnFieldDefinition colunmF,
                                    ColumnNameAttribute colNameAttr, PropertyInfo prop)
 {
     colunmF.ColumnName = colNameAttr == null ? prop.Name : colNameAttr.ColumnName;
 }
示例#20
0
        /// <summary>
        /// Наполнить колонки на основе типа.
        /// </summary>
        /// <param name="columns">Коллекция колонок</param>
        /// <param name="type">Тип, размеченный аттрибутами</param>
        public static void ParseAllPropsIntoColumns(DataGridViewColumnCollection columns, Type type)
        {
            PropertyInfo[] props      = type.GetProperties();
            ArrayList      propsNames = new ArrayList(props.Length);

            foreach (PropertyInfo prop in props)
            {
                PropertyOrderAttribute att = (PropertyOrderAttribute)Attribute.GetCustomAttribute(prop, typeof(PropertyOrderAttribute));
                if (att != null)
                {
                    propsNames.Add(new PropertyOrderPair(prop.Name, att.Order));
                }
                else
                {
                    propsNames.Add(new PropertyOrderPair(prop.Name, 0));
                }
            }

            propsNames.Sort();

            DataGridViewCell cell = new DataGridViewTextBoxCell();

            for (int i = 0; i < propsNames.Count; ++i)
            {
                PropertyInfo prop = type.GetProperty((propsNames[i] as PropertyOrderPair).Name);

                ColumnNameAttribute attName = (ColumnNameAttribute)Attribute.GetCustomAttribute(prop, typeof(ColumnNameAttribute));
                if (attName != null)
                {
                    DataGridViewColumn column = new DataGridViewColumn();
                    column.Name         = attName.ColumnName;
                    column.CellTemplate = cell;

                    ColumnWidthAttribute attWidth = (ColumnWidthAttribute)Attribute.GetCustomAttribute(prop, typeof(ColumnWidthAttribute));
                    if (attWidth != null)
                    {
                        column.Width = attWidth.ColumnWidth;
                    }
                    else
                    {
                        column.Width = 100;
                    }

                    ColumnTextAttribute attText = (ColumnTextAttribute)Attribute.GetCustomAttribute(prop, typeof(ColumnTextAttribute));
                    if (attText != null)
                    {
                        column.HeaderText = attText.ColumnText;
                    }
                    else
                    {
                        column.HeaderText = attName.ColumnName;
                    }

                    if (prop.GetSetMethod() != null)
                    {
                        ReadOnlyAttribute attRO = (ReadOnlyAttribute)Attribute.GetCustomAttribute(prop, typeof(ReadOnlyAttribute));
                        if (attRO != null)
                        {
                            column.ReadOnly = attRO.IsReadOnly;
                        }
                    }

                    ContentAlignmentAttribute attAl = (ContentAlignmentAttribute)Attribute.GetCustomAttribute(prop, typeof(ContentAlignmentAttribute));
                    if (attAl != null)
                    {
                        column.HeaderCell.Style.Alignment = (DataGridViewContentAlignment)(attAl.Alignment);
                    }

                    columns.Add(column);
                }
            }
        }
示例#21
0
        public T Read <T>(T obj)
        {
            try
            {
                SqlDataReader readDataBase = CommandSQL.ExecuteReader();
                while (readDataBase.Read())
                {
                    if (obj == null)
                    {
                        obj = Activator.CreateInstance <T>();
                    }

                    var keys = obj.GetType().GetProperties();
                    for (int i = 0; i < keys.Length; i++)
                    {
                        PropertyInfo key      = keys[i];
                        string       keyName  = key.Name;
                        PropertyInfo prop     = obj.GetType().GetProperty(keyName);
                        Type         propType = key.PropertyType;

                        ColumnNameAttribute attr = key.GetCustomAttribute <ColumnNameAttribute>();
                        if (attr != null)
                        {
                            keyName = attr.ColumnName;
                        }
                        var    db    = readDataBase[keyName].ToString();
                        object value = null;

                        // Números:
                        if (propType == typeof(int))
                        {
                            value = Convert.ToInt32(db);
                        }
                        if (propType == typeof(decimal))
                        {
                            value = decimal.Parse(db);
                        }
                        if (propType == typeof(double))
                        {
                            value = double.Parse(db);
                        }
                        if (propType == typeof(float))
                        {
                            value = float.Parse(db);
                        }
                        if (propType == typeof(long))
                        {
                            value = long.Parse(db);
                        }

                        // Texto:
                        if (propType == typeof(char))
                        {
                            value = char.Parse(db);
                        }
                        if (propType == typeof(string))
                        {
                            value = db.ToString();
                        }

                        // Data:
                        if (propType == typeof(DateTime))
                        {
                            value = DateTime.Parse(db);
                        }

                        // Boleano:
                        if (propType == typeof(bool))
                        {
                            value = bool.Parse(db);
                        }

                        // Enum:
                        if (propType == typeof(Enum))
                        {
                            value = null;
                        }

                        prop.SetValue(obj, value, null);
                    }
                }
                return(obj);
            }

            catch (SqlException Ex) { throw Ex; }
            catch (Exception Ex) { throw Ex; }
            finally { if (ConnectionSQL.State == System.Data.ConnectionState.Open)
                      {
                          ConnectionSQL.Close();
                      }
            }
        }