Пример #1
0
 internal UriTemplatePart(string part, MappingAttribute source, ICustomAttributeProvider member, bool hasDefaultValue = false)
 {
     Part            = ((source is FromQueryStringAttribute) && (part[0] == '&') ? part.Substring(1) : part);
     Source          = source;
     Member          = member;
     HasDefaultValue = hasDefaultValue;
 }
Пример #2
0
            internal override void Add(string part, MappingAttribute source, ICustomAttributeProvider member, bool hasDefaultValue = false)
            {
                base.Add(part, source, member, hasDefaultValue);
                if (ControlledEntityType == null)
                {
                    return;
                }

                int  indexOf = -1;
                Type implementation;
                var  identifierSegment = this
                                         .Where((item, index) => (item.Source is FromUrlAttribute) && (item.Member is ParameterInfo) &&
                                                ((implementation = ControlledEntityType.GetInterfaces().First(@interface => (@interface.IsGenericType) && (@interface.GetGenericTypeDefinition() == typeof(IControlledEntity <>)))) != null) &&
                                                (((ParameterInfo)item.Member).ParameterType == implementation.GetProperty("Key").PropertyType) &&
                                                ((indexOf = index) != -1))
                                         .FirstOrDefault();

                if ((indexOf <= 1) || ((indexOf > 1) && (!(this[indexOf - 1].Member is MethodInfo))))
                {
                    return;
                }

                this[indexOf]     = this[indexOf - 1];
                this[indexOf - 1] = identifierSegment;
            }
Пример #3
0
        private Row ConvertToRow <T>(T entity, int rowIndex, Dictionary <string, Cell> cellMapping)
        {
            if (entity == null)
            {
                throw new ArgumentException("Please confirm whether curren entity is null!");
            }

            Row row = new Row()
            {
                RowIndex = (uint)rowIndex
            };
            Type type = entity.GetType();

            PropertyInfo[] properties = type.GetProperties();
            foreach (PropertyInfo property in properties)
            {
                object[] attrs = property.GetCustomAttributes(typeof(MappingAttribute), true);
                if (attrs == null || attrs.Length <= 0)
                {
                    continue;
                }
                MappingAttribute attr  = (MappingAttribute)attrs[0];
                object           value = property.FastGetValue(entity);
                if (value == null)
                {
                    value = string.Empty;
                }
                string cellAddress = GetCellAddressByMapping(rowIndex, attr, cellMapping);
                Cell   resultCell  = row.CreateCell(cellAddress);
                resultCell.SetCellText(value);
                SetStyleIndexByCellFormatOption(resultCell, value, cellFormatOption, attr);
            }
            return(row);
        }
Пример #4
0
        private static Property GetGroupingProperty(TypeInfo modelType, MappingAttribute attribData)
        {
            var propertyName = attribData?.GroupBy;

            if (string.IsNullOrWhiteSpace(propertyName))
            {
                return(null);
            }

            var propData = modelType.GetProperty(propertyName);

            if (propData == null)
            {
                return(null);
            }

            var propAttrib = propData.GetCustomAttribute <MappingAttribute>();

            var property = new Property
            {
                PropertyName   = propData.Name,
                ColumnName     = propAttrib?.ColumnName ?? propData.Name,
                PropertyInfo   = propData,
                UnderlyingType = propData.GetActualType()
            };

            property.UnderlyingTypeInfo = property.UnderlyingType.GetTypeInfo();
            property.Mapper             = property.UnderlyingTypeInfo.GetPropertyMapper();

            return(property);
        }
Пример #5
0
        private string GetDbType(Type type, MappingAttribute attribute)
        {
            int length = attribute.Length == 0 ? 255 : attribute.Length;

            if (type == typeof(string))
            {
                return(string.Format("VARCHAR({0})", length));
            }
            if (type == typeof(int))
            {
                return("INT");
            }
            if (type == typeof(bool))
            {
                return("SMALLINT(6)");
            }
            if (type == typeof(long))
            {
                return("BIGINT(20)");
            }
            if (type == typeof(Guid))
            {
                return("CHAR(36)");
            }
            if (type == typeof(DateTime))
            {
                return("DATETIME");
            }
            return(string.Format("VARCHAR({0})", length));
        }
Пример #6
0
        private Dictionary <string, Cell> GetHeaderCellMapping(Type type)
        {
            Dictionary <string, Cell> results = new Dictionary <string, Cell>();
            var sharedTablePart = document.GetSharedStringTable();
            var headerCell      = worksheet.GetRow(header).Elements <Cell>();

            if (headerCell == null)
            {
                throw new NullReferenceException("Check that the header information exist!");
            }
            PropertyInfo[] properties = type.GetProperties();
            foreach (PropertyInfo property in properties)
            {
                foreach (Cell cell in headerCell)
                {
                    object[] attrs = property.GetCustomAttributes(typeof(MappingAttribute), true);
                    if (attrs == null || attrs.Length <= 0)
                    {
                        continue;
                    }
                    MappingAttribute attr = (MappingAttribute)attrs[0];
                    if (attr.MappingKey == worksheet.GetCellValue(cell, sharedTablePart))
                    {
                        results.Add(attr.MappingKey, cell); break;
                    }
                }
            }
            return(results);
        }
Пример #7
0
        private void GenResult(ILGenerator ilGen, MappingAttribute attribute, Type returnType, int index)
        {
            var resultDto = attribute.Dto;
            var valueType = resultDto.IsValueType;

            ilGen.DeclareLocal(resultDto);
            ilGen.Emit(valueType ? OpCodes.Unbox_Any : OpCodes.Castclass, attribute.Dto);
            ilGen.Emit(OpCodes.Stloc_1);
            ilGen.Emit(OpCodes.Ldsfld, typeof(MethodInformation).GetFields()[0]);
            ilGen.Emit(OpCodes.Ldc_I4_S, index);
            ilGen.Emit(OpCodes.Callvirt, typeof(List <Delegate>).GetMethod("get_Item"));
            ilGen.Emit(OpCodes.Ldc_I4_1);
            ilGen.Emit(OpCodes.Newarr, typeof(object));
            ilGen.Emit(OpCodes.Dup);
            ilGen.Emit(OpCodes.Ldc_I4_0);
            ilGen.Emit(OpCodes.Ldloc_1);
            if (valueType)
            {
                ilGen.Emit(OpCodes.Box, resultDto);
            }

            ilGen.Emit(OpCodes.Stelem_Ref);
            ilGen.Emit(OpCodes.Callvirt, typeof(Delegate).GetMethod("DynamicInvoke"));
            ilGen.Emit(OpCodes.Castclass, returnType);
        }
Пример #8
0
        private static void GenResult(ILGenerator ilGen, MappingAttribute mappingAttribute)
        {
            var property = mappingAttribute.Dto;

            if (!property.IsValueType)
            {
                ilGen.Emit(OpCodes.Castclass, mappingAttribute.Dto);
            }
            var propertyNames = mappingAttribute.Path.Split('.').Where(s => !s.Equals("")).ToArray();

            for (var i = 0; i < propertyNames.Length; ++i)
            {
                var propertyName = propertyNames[i];
                if (property.IsValueType)
                {
                    ilGen.DeclareLocal(property);
                    if (i == 0)
                    {
                        ilGen.Emit(OpCodes.Unbox_Any, property);
                    }
                    ilGen.Emit(OpCodes.Stloc, i + 1);
                    ilGen.Emit(OpCodes.Ldloca_S, i + 1);
                }

                var aux = property?.GetProperty(propertyName);
                ilGen.Emit(OpCodes.Call, aux?.GetGetMethod());
                property = aux?.PropertyType;
            }
        }
Пример #9
0
        public PropertyMapper(PropertyInfo propertyInfo, MappingAttribute mappingAttribute)
        {
            if (propertyInfo == null)
            {
                throw new MappingException("PropertyMapping must contain the PropertyInfo or else it cant map the property");
            }

            if (mappingAttribute == null)
            {
                throw new MappingException("A PropertyMapping must have a mapping attribute specified");
            }

            Info        = propertyInfo;
            MappingInfo = mappingAttribute;
            _mapper     = new Mapper();

            if (mappingAttribute.Mapping == MappingType.Relationship && mappingAttribute.ToSingle == false)
            {
                ListElementType = Info.PropertyType.GetGenericArguments().FirstOrDefault();

                Type genericListType = typeof(List <>);
                GeneratedListType = genericListType.MakeGenericType(new[] { ListElementType });
                AddMethod         = GeneratedListType.GetMethod(AddMethodName);
            }
        }
Пример #10
0
        public MethodInformation ProcessMethod(MethodInfo method)
        {
            MappingAttribute mappingAttribute = null;
            GetAttribute     getAttribute     = null;
            IList <Type>     args             = method.GetParameters().Select(arg => arg.ParameterType).ToList();

            foreach (var attr in method.GetCustomAttributes <Attribute>())
            {
                switch (attr)
                {
                case MappingAttribute ma:
                    mappingAttribute = ma;
                    break;

                case GetAttribute ga:
                    getAttribute = ga;
                    break;
                }
            }

            var info = new MethodInformation {
                Name = method.Name, ReturnType = method.ReturnType, Args = args
            };

            if (mappingAttribute != null)
            {
                info.Mapping = mappingAttribute;
            }
            if (getAttribute != null)
            {
                info.Get = getAttribute;
            }
            info.MethodAttrs = method.Attributes;
            return(info);
        }
Пример #11
0
        protected virtual XElement VisitMemberAccess(MemberExpression member)
        {
            if (member.Expression != null && member.Expression.NodeType == ExpressionType.Constant)
            {
                LambdaExpression lambda = Expression.Lambda(member);
                Delegate         fn     = lambda.Compile();
                return(VisitConstant(Expression.Constant(fn.DynamicInvoke(null), member.Type)));
            }
            else
            {
                CurrentMember = member.Member;
                if (member.Member.DeclaringType == typeof(DateTime) || member.Member.DeclaringType == typeof(Nullable <DateTime>))
                {
                    switch (member.Member.Name)
                    {
                    case "Now":
                    case "Today":
                        return(new XElement("Value", new XAttribute("Type", "DateTime"), new XElement("Today")));

                    default:
                        LambdaExpression lambda = Expression.Lambda(member);
                        Delegate         fn     = lambda.Compile();
                        return(VisitConstant(Expression.Constant(fn.DynamicInvoke(null), member.Type)));
                    }
                }
                else if (member.Expression is MemberExpression)
                {
                    try
                    {
                        MappingAttribute currentMappingAttribute = ((MappingAttribute)MappingAttribute.GetMappingAttribute(((MemberExpression)member.Expression).Member));
                        if (currentMappingAttribute.TypeAsText == "Lookup")
                        {
                            CurrentMember = (member.Expression as MemberExpression).Member;
                            if (member.Member.Name == "Id")
                            {
                                return(new XElement("FieldRef", new XAttribute("Name", CurrentMembersMappingAttribute.ColumnName), new XAttribute("LookupId", "TRUE")));
                            }
                            else
                            {
                                return(new XElement("FieldRef", new XAttribute("Name", CurrentMembersMappingAttribute.ColumnName)));
                            }
                        }
                    }
                    catch (PropertyNotMappedException)
                    {
                        if ((member.Expression as MemberExpression).Member.Name != QueryParameter.Name)
                        {
                            LambdaExpression lambda = Expression.Lambda(member);
                            Delegate         fn     = lambda.Compile();
                            return(VisitConstant(Expression.Constant(fn.DynamicInvoke(null), member.Type)));
                        }
                    }
                    //Get parent member as current member is primitive
                }
                return(new XElement("FieldRef", new XAttribute("Name", CurrentMembersMappingAttribute.ColumnName)));
            }
        }
Пример #12
0
 /// <summary>
 /// 获取泛型类中指定属性值
 /// </summary>
 /// <returns></returns>
 public static string GetFullTypeName(this Type type)
 {
     object[] attrList = type.GetCustomAttributes(typeof(MappingAttribute), false);
     if (attrList != null)
     {
         MappingAttribute categoryInfo = (MappingAttribute)attrList[0];
         return(categoryInfo.FullTypeName);
     }
     return("");
 }
Пример #13
0
        internal void Add(string part, MappingAttribute source, ICustomAttributeProvider member, bool hasDefaultValue = false)
        {
            part = (_isRegexMode ? ((source is FromQueryStringAttribute) ? part.Replace("=[^&]+", String.Empty) : part) : part).Trim('/');
            if (part.Length == 0)
            {
                return;
            }

            (source is FromQueryStringAttribute ? (UriTemplatePartList)_queryString : _segments).Add(part, source, member, hasDefaultValue);
        }
Пример #14
0
        private string GetTableName(Type type)
        {
            MappingAttribute table     = GetEntityAttribute <MappingAttribute>(type);
            string           tableName = type.Name;

            if (table != null)
            {
                tableName = table.Name;
            }
            return(tableName);
        }
Пример #15
0
        private T ConvertToGeneric <T>(int rowIndex, SharedStringTablePart sharedTablePart, Dictionary <string, Cell> cellMapping, ConstructorInfo constructorInfo)
        {
            T    target = (T)constructorInfo.Invoke(null);
            Type type   = target.GetType();

            PropertyInfo[] properties = type.GetProperties();
            foreach (PropertyInfo property in properties)
            {
                object[]         attrs         = property.GetCustomAttributes(typeof(MappingAttribute), true);
                MappingAttribute attr          = (MappingAttribute)attrs[0];
                string           cellValue     = GetCellValueWithMapping(rowIndex, attr, cellMapping, sharedTablePart);
                object           propertyValue = ParserFromString(property.PropertyType, cellValue);
            }
            return(target);
        }
Пример #16
0
        private static List <PropertyMappingInfo> LoadPropertyMappingInfo(Type objType)
        {
            List <PropertyMappingInfo> mapInfoList = new List <PropertyMappingInfo>();

            foreach (PropertyInfo info in objType.GetProperties())
            {
                MappingAttribute mapAttr = (MappingAttribute)Attribute.GetCustomAttribute(info, typeof(MappingAttribute));
                if (mapAttr == null && (System.Type.GetTypeCode(info.PropertyType) != TypeCode.Object || info.PropertyType == new System.TimeSpan().GetType()))
                {
                    //mapAttr = new MappingAttribute(string.Concat(info.Name, ",un-insert,un-update"));
                    mapAttr = new MappingAttribute(info.Name);
                }
                if (mapAttr != null)
                {
                    PropertyMappingInfo mapInfo = new PropertyMappingInfo(mapAttr.DataFieldName, mapAttr.NullValue, info);
                    mapInfoList.Add(mapInfo);
                }
            }
            return(mapInfoList);
        }
Пример #17
0
        public object Request(params object[] args)
        {
            StackTrace stackTrace = new StackTrace();
            MethodInfo callSite   = (MethodInfo)stackTrace.GetFrame(1).GetMethod();

            /*
             * The callsite is the caller method.
             */

            //Get the path
            GetAttribute get = (GetAttribute)callSite.GetCustomAttribute(typeof(GetAttribute));

            String path = get.path;

            //Replace the variables in the string with their values
            int i = 0;

            foreach (ParameterInfo param in callSite.GetParameters())
            {
                path = path.Replace("{" + param.Name + "}", args[i++].ToString());
            }

            //Get The Map Attribute
            MappingAttribute map = (MappingAttribute)callSite.GetCustomAttribute(typeof(MappingAttribute));

            //Get the object path
            String[] paths = map.path.Split('.');

            //http request
            object objToReturn = req.Get(path, map.dest);

            //Return the desired object based on path
            for (int j = 1; j < paths.Length; j++)
            {
                PropertyInfo pi = objToReturn.GetType().GetProperty(paths[j]);

                objToReturn = pi.GetValue(objToReturn);
            }

            return(objToReturn);
        }
Пример #18
0
        private string GetCellAddressByMapping(int rowIndex, MappingAttribute attribute, Dictionary <string, Cell> cellMapping)
        {
            int    cellIndex   = 1;
            string cellAddress = string.Empty;

            switch (attribute.MappingOption)
            {
            case MappingOption.FieldName:
                cellIndex   = cellMapping[attribute.MappingKey].GetCellIndex();
                cellAddress = SpreadsheetExtender.ToCellAddress(rowIndex, cellIndex);
                break;

            case MappingOption.ColumnName:
                cellAddress = attribute.MappingKey + rowIndex; break;

            case MappingOption.ColumnIndex:
                cellAddress = SpreadsheetExtender.ToCellAddress(rowIndex, int.Parse(attribute.MappingKey));
                break;
            }
            return(cellAddress);
        }
Пример #19
0
        private string GetMethodUrl(string method, object[] objParams)
        {
            string methodUrl = "";

            MemberInfo[] arr = typeof(T).GetMethods();
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i].Name.Equals(method))
                {
                    MappingAttribute mapUrl = (MappingAttribute)arr[i].GetCustomAttributes(typeof(MappingAttribute), false)[0];
                    methodUrl = mapUrl.MethodUrl;
                    break;
                }
            }

            for (int i = 0; i < objParams.Length; i++)
            {
                methodUrl = methodUrl.Replace("{" + i + "}", objParams[i].ToString());
            }
            return(methodUrl);
        }
Пример #20
0
        public TEntity Load <TEntity>(object id) where TEntity : new()
        {
            if (id is SqlPredicate)
            {
                throw new ArgumentException("Entity id was expected but SqlPredicate found. You probably wanted to use Load<TEntity>(QueryBuilder.Create().SetWhereStatement(sqlPredicate)).");
            }

            MappingAttribute identityMapping = FindIdentity <TEntity>();

            if (identityMapping == null)
            {
                throw new Exception(string.Format("Entity {0} has no primary key defined.", typeof(TEntity).Name));
            }
            var results = Load <TEntity>(QueryBuilder.Create().SetWhereStatement(QB.Eq(identityMapping.Name, id)));

            if (results.Count > 1)
            {
                throw new Exception(string.Format("There is more than one record with id {0} of entity {1}.", id, typeof(TEntity).Name));
            }
            return(results.FirstOrDefault());
        }
Пример #21
0
        private static void GenResult(ILGenerator ilGen, MappingAttribute mappingAttribute, Type returnType)
        {
            var resultDto = mappingAttribute.Dto;

            if (mappingAttribute.With != null) //MODE WITH
            {
                var resultWith = mappingAttribute.With;
                var funcType   = typeof(Func <object>);
                ilGen.Emit(OpCodes.Ldftn, resultDto.GetMethod(resultWith));
                ilGen.Emit(OpCodes.Newobj, funcType.GetConstructors()[0]);
                ilGen.Emit(OpCodes.Callvirt, funcType.GetMethod("Invoke"));
                ilGen.Emit(OpCodes.Castclass, returnType);
            }
            else //MODE PATH
            {
                if (!resultDto.IsValueType)
                {
                    ilGen.Emit(OpCodes.Castclass, mappingAttribute.Dto);
                }
                var propertyNames = mappingAttribute.Path.Split('.').Where(s => s.Length > 0).ToList();
                for (var i = 0; i < propertyNames.Count; ++i)
                {
                    var propertyName = propertyNames[i];
                    if (resultDto.IsValueType)
                    {
                        ilGen.DeclareLocal(resultDto);
                        if (i == 0)
                        {
                            ilGen.Emit(OpCodes.Unbox_Any, resultDto);
                        }
                        ilGen.Emit(OpCodes.Stloc, i + 1);
                        ilGen.Emit(OpCodes.Ldloca_S, i + 1);
                    }

                    var aux = resultDto?.GetProperty(propertyName);
                    ilGen.Emit(OpCodes.Call, aux?.GetGetMethod());
                    resultDto = aux?.PropertyType;
                }
            }
        }
Пример #22
0
        private static void SetPropertyFromCell(object entity, string columnName, object cellValue)
        {
            if (entity == null)
            {
                throw new ArgumentNullException("entity");
            }

            var properties = entity.GetType().GetRuntimeProperties();

            foreach (var property in properties)
            {
                MappingAttribute attribute = property.GetCustomAttributes(typeof(MappingAttribute), true).Cast <MappingAttribute>().FirstOrDefault();
                if (attribute == null)
                {
                    continue;
                }
                if (attribute.Name == columnName)
                {
                    if (property.PropertyType == typeof(bool) && cellValue is short)
                    {
                        cellValue = (short)cellValue != 0;
                    }
                    if (property.PropertyType == typeof(bool) && cellValue is int)
                    {
                        cellValue = (int)cellValue != 0;
                    }
                    if (property.PropertyType == typeof(bool) && cellValue is long)
                    {
                        cellValue = (long)cellValue != 0;
                    }
                    if (cellValue == DBNull.Value)
                    {
                        cellValue = null;
                    }

                    property.SetValue(entity, cellValue, null);
                }
            }
        }
Пример #23
0
        private string GetCellValueWithMapping(int rowIndex, MappingAttribute attribute, Dictionary <string, Cell> cellMapping, SharedStringTablePart sharedTablePart)
        {
            string cellValue = string.Empty;

            switch (attribute.MappingOption)
            {
            case MappingOption.FieldName:
                Cell cell      = cellMapping[attribute.MappingKey];
                int  cellIndex = cell.GetCellIndex();
                cellValue = worksheet.GetCellValue(rowIndex, cellIndex, sharedTablePart);
                break;

            case MappingOption.ColumnName:
                cellValue = worksheet.GetCellValue(attribute.MappingKey + rowIndex.ToString(), sharedTablePart);
                break;

            case MappingOption.ColumnIndex:
                cellValue = worksheet.GetCellValue(rowIndex, int.Parse(attribute.MappingKey), sharedTablePart);
                break;
            }
            return(cellValue);
        }
Пример #24
0
        public override DbCommand GetInsertCommand(object entity)
        {
            MappingAttribute typeAttribute = entity.GetType().GetCustomAttributes(typeof(MappingAttribute), true).FirstOrDefault() as MappingAttribute;

            if (typeAttribute == null)
            {
                throw new Exception(string.Format("Nazwa tabeli nie została określona dla typu {0}.", entity.GetType().Name));
            }

            MySqlCommand command = Connection.CreateCommand() as MySqlCommand;

            StringBuilder sb = new StringBuilder();

            sb.Append("INSERT INTO ");
            sb.Append(typeAttribute.Name);
            sb.Append(" (");
            bool first      = true;
            var  properties = entity.GetType().GetOrderedProperties().ToList();

            foreach (var property in properties)
            {
                if (property.GetValue(entity) == null)
                {
                    continue;
                }
                MappingAttribute attribute = property.GetCustomAttributes(typeof(MappingAttribute), true).FirstOrDefault() as MappingAttribute;
                if (attribute == null)
                {
                    continue;
                }
                if (attribute.IsSpecialColumn)
                {
                    continue;
                }
                if (!first)
                {
                    sb.Append(", ");
                }
                sb.Append(string.Format("{0}", attribute.Name));
                first = false;
            }
            sb.Append(") VALUES (");
            first = true;
            int parameter = 0;

            foreach (var property in properties)
            {
                if (property.GetValue(entity) == null)
                {
                    continue;
                }
                MappingAttribute attribute = property.GetCustomAttributes(typeof(MappingAttribute), true).FirstOrDefault() as MappingAttribute;
                if (attribute == null)
                {
                    continue;
                }
                if (attribute.IsSpecialColumn)
                {
                    continue;
                }
                if (!first)
                {
                    sb.Append(", ");
                }
                sb.Append(string.Format("@P{0}", parameter));
                command.Parameters.Add(string.Format("@P{0}", parameter), property.GetValue(entity));
                first = false;
                parameter++;
            }
            sb.Append(")");

            command.CommandText = sb.ToString();
            return(command);
        }
Пример #25
0
        public override DbCommand GetUpdateCommand(object entity)
        {
            MappingAttribute typeAttribute = entity.GetType().GetCustomAttributes(typeof(MappingAttribute), true).FirstOrDefault() as MappingAttribute;

            if (typeAttribute == null)
            {
                throw new Exception(string.Format("Nazwa tabeli nie została określona dla typu {0}.", entity.GetType().Name));
            }

            MySqlCommand command = Connection.CreateCommand() as MySqlCommand;

            StringBuilder sb = new StringBuilder();

            sb.Append("UPDATE ");
            sb.Append(typeAttribute.Name);
            sb.Append(" SET ");
            bool         first      = true;
            PropertyInfo idProperty = null;
            int          parameter  = 0;

            foreach (var property in entity.GetType().GetOrderedProperties())
            {
                if (property.GetValue(entity) == null)
                {
                    continue;
                }
                MappingAttribute attribute = property.GetCustomAttributes(typeof(MappingAttribute), true).FirstOrDefault() as MappingAttribute;
                if (attribute == null)
                {
                    continue;
                }
                if (attribute.IsSpecialColumn)
                {
                    continue;
                }
                if (attribute.IsPrimaryKey)
                {
                    idProperty = property;
                    continue;
                }
                if (!first)
                {
                    sb.Append(", ");
                }
                sb.Append(string.Format("{0} = @P{1}", attribute.Name, parameter));
                command.Parameters.Add(string.Format("@P{0}", parameter), property.GetValue(entity));
                first = false;
                parameter++;
            }
            if (idProperty == null)
            {
                throw new Exception("Brak kolumny id.");
            }
            MappingAttribute idAttribute = idProperty.GetCustomAttributes(typeof(MappingAttribute), true).FirstOrDefault() as MappingAttribute;

            sb.Append(string.Format(" WHERE {0}=@P{1};", idAttribute.Name, parameter));
            command.Parameters.Add(string.Format("@P{0}", parameter), idProperty.GetValue(entity));
            parameter++;

            command.CommandText = sb.ToString();
            return(command);
        }
Пример #26
0
        public override DbCommand GetUpdateSchemaCommand(Type entityType)
        {
            MappingAttribute typeAttribute = entityType.GetCustomAttributes(typeof(MappingAttribute), true).FirstOrDefault() as MappingAttribute;

            if (typeAttribute == null)
            {
                typeAttribute = new MappingAttribute(entityType.Name);
            }

            MySqlCommand command = Connection.CreateCommand() as MySqlCommand;

            command.CommandText = string.Format("SELECT * FROM information_schema.tables WHERE table_schema = '{0}' AND table_name = '{1}' LIMIT 1;", Connection.Database, typeAttribute.Name);
            MySqlDataAdapter adapter = new MySqlDataAdapter(command);
            DataTable        table   = new DataTable();

            adapter.Fill(table);
            bool tableExists = table.Rows.Count > 0;

            var properties = entityType.GetOrderedProperties().ToList();
            var sb         = new StringBuilder();

            if (tableExists)
            {
                command             = Connection.CreateCommand() as MySqlCommand;
                command.CommandText = string.Format("SHOW COLUMNS FROM {0}", typeAttribute.Name);
                adapter             = new MySqlDataAdapter(command);
                table = new DataTable();
                adapter.Fill(table);

                sb.AppendFormat("ALTER TABLE {0} ", typeAttribute.Name);
                bool first = true;
                bool newPropertiesExist = false;
                foreach (var property in properties)
                {
                    MappingAttribute attribute = property.GetCustomAttributes(typeof(MappingAttribute), true).FirstOrDefault() as MappingAttribute;
                    if (attribute == null)
                    {
                        continue;
                    }
                    if (attribute.IsSpecialColumn)
                    {
                        continue;
                    }
                    if (table.Rows.Cast <DataRow>().Any(r => (string)r["Field"] == attribute.Name))
                    {
                        continue;
                    }
                    if (!first)
                    {
                        sb.Append(",");
                    }
                    newPropertiesExist = true;
                    sb.AppendFormat(" ADD COLUMN {0} {1}", attribute.Name, GetDbType(property.PropertyType, attribute));
                    first = false;
                }
                if (!newPropertiesExist)
                {
                    return(null);
                }
            }
            else
            {
                sb.AppendFormat("CREATE TABLE {0} (", typeAttribute.Name);
                bool             first = true;
                MappingAttribute primaryKeyAttribute = null;
                var foreignKeyAttributes             = new List <MappingAttribute>();
                foreach (var property in properties)
                {
                    MappingAttribute attribute = property.GetCustomAttributes(typeof(MappingAttribute), true).FirstOrDefault() as MappingAttribute;
                    if (attribute == null)
                    {
                        continue;
                    }
                    if (attribute.IsSpecialColumn)
                    {
                        continue;
                    }
                    if (attribute.IsPrimaryKey)
                    {
                        primaryKeyAttribute = attribute;
                    }
                    if (!string.IsNullOrWhiteSpace(attribute.ForeignColumn) && !string.IsNullOrWhiteSpace(attribute.ForeignTable))
                    {
                        foreignKeyAttributes.Add(attribute);
                    }
                    if (!first)
                    {
                        sb.Append(",");
                    }
                    sb.AppendFormat(" {0} {1} {2}", attribute.Name, GetDbType(property.PropertyType, attribute), attribute.IsPrimaryKey || attribute.IsNotNull ? "NOT NULL" : "DEFAULT NULL");
                    first = false;
                }
                if (primaryKeyAttribute != null)
                {
                    if (!first)
                    {
                        sb.Append(",");
                    }
                    sb.AppendFormat(" PRIMARY KEY ({0}), UNIQUE KEY {0}_UNIQUE ({0})", primaryKeyAttribute.Name);
                }
                first = false;
                foreach (var attribute in foreignKeyAttributes)
                {
                    if (!first)
                    {
                        sb.Append(",");
                    }
                    sb.AppendFormat(" KEY FK_{0}_idx ({0}), CONSTRAINT FK_{0} FOREIGN KEY ({0}) REFERENCES {1} ({2}) ON DELETE NO ACTION ON UPDATE NO ACTION",
                                    attribute.Name, attribute.ForeignTable, attribute.ForeignColumn);
                }
                sb.Append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
            }

            command             = Connection.CreateCommand() as MySqlCommand;
            command.CommandText = sb.ToString();
            return(command);
        }
Пример #27
0
        private void SetStyleIndexByCellFormatOption(Cell cell, object value, CellFormatOption option, MappingAttribute attribute)
        {
            int styleIndex = 0;

            switch (cellFormatOption)
            {
            case CellFormatOption.KeepStyle:
                break;

            case CellFormatOption.OverWrite:
                styleIndex = SpreadsheetExtender.GetCellStyleIndex(styleSheet, value);
                cell.SetCellStyle(styleIndex);
                break;

            case CellFormatOption.ReferenceStyle:
                if (string.IsNullOrEmpty(attribute.ReferenceStyle))
                {
                    styleIndex = SpreadsheetExtender.GetCellStyleIndex(styleSheet, value);
                }
                else
                {
                    Cell refCell = SpreadsheetExtender.GetCell(worksheet, attribute.ReferenceStyle);
                    if (refCell == null)
                    {
                        throw new ArgumentException("Please confirm the cell to reference is not null!");
                    }
                    if (refCell.StyleIndex == null || (refCell.StyleIndex != null && !refCell.StyleIndex.HasValue))
                    {
                        styleIndex = SpreadsheetExtender.GetCellStyleIndex(styleSheet, value);
                    }
                    else
                    {
                        styleIndex = int.Parse(refCell.StyleIndex.ToString());
                    }
                    cell.SetCellStyle(styleIndex);
                } break;
            }
        }
Пример #28
0
        public override DbCommand GetSelectCommand <TEntity>(QueryBuilder builder)
        {
            int parameterCounter           = 0;
            MappingAttribute typeAttribute = typeof(TEntity).GetCustomAttributes(typeof(MappingAttribute), true).FirstOrDefault() as MappingAttribute;

            if (typeAttribute == null)
            {
                throw new Exception(string.Format("Nazwa tabeli nie została określona dla typu {0}.", typeof(TEntity).Name));
            }

            StringBuilder sb = new StringBuilder();

            sb.Append("SELECT ");
            bool first = true;

            //Jeśli kolumny nie są wyspecyfikowane, dodaj na podstawie propertiesów:
            if (!builder.AreColumnsSpecified)
            {
                foreach (PropertyInfo property in typeof(TEntity).GetOrderedProperties())
                {
                    MappingAttribute attribute = property.GetCustomAttributes(typeof(MappingAttribute), true).FirstOrDefault() as MappingAttribute;
                    if (attribute == null)
                    {
                        continue;
                    }
                    if (attribute.IsSpecialColumn)
                    {
                        continue;                               //Ta kolumna będzie dodana przez klasę SpecialColumn
                    }
                    if (!first)
                    {
                        sb.Append(", ");
                    }
                    sb.Append(string.Format("{0}", attribute.Name));
                    first = false;
                }
            }
            else
            {
                if (!builder.SpecialColumns.Any() && !builder.Columns.Any())
                {
                    sb.Append("*");                                                             //Nie ma żadnych kolumn, ale programista użył SpecifyColumns. Dodaj gwiazdkę.
                }
                else
                {
                    sb.Append(string.Join(", ", builder.Columns));   //Kolumny są wyspecyfikowane
                }
            }
            foreach (SpecialColumn specialColumn in builder.SpecialColumns)
            {
                if (!first)
                {
                    sb.Append(", ");
                }
                sb.Append(string.Format("{0} AS {1}", specialColumn.GetColumnStatement(), specialColumn.Alias));
                first = false;
            }
            sb.Append(string.Format(" FROM {0}", typeAttribute.Name));

            if (builder.WhereStatement != null)
            {
                string sql = builder.WhereStatement.GetSql(ref parameterCounter);
                if (!Extensions.IsNullOrWhiteSpaceOrEmptyParentheses(sql))
                {
                    sb.Append(" WHERE ");
                    sb.Append(sql);
                }
            }
            if (builder.SortModes.Count > 0)
            {
                sb.Append(" ORDER BY ");
                sb.Append(string.Join(", ", builder.SortModes.Select(sm => sm.GetOrderByStatement())));
            }

            if (builder.Limit > 0)
            {
                sb.Append(" LIMIT ");
                if (builder.Offset > 0)
                {
                    sb.Append(string.Format(" {0},", builder.Offset));
                }
                sb.Append(string.Format(" {0}", builder.Limit));
            }

            DbCommand command = Connection.CreateCommand();

            command.CommandText = sb.ToString();
            if (builder.WhereStatement != null)
            {
                int paramNumber = 0;
                foreach (var parameter in builder.WhereStatement.GetParameterValues())
                {
                    command.Parameters.Add(new MySqlParameter(string.Format("@P{0}", paramNumber), parameter));
                    paramNumber++;
                }
            }
            return(command);
        }
 public ItemMapper(PropertyInfo property, MappingAttribute attribute)
 {
     _property  = property;
     _attribute = attribute;
 }
Пример #30
0
 internal virtual void Add(string part, MappingAttribute source, ICustomAttributeProvider member, bool hasDefaultValue = false)
 {
     Add(new UriTemplatePart(part, source, member, hasDefaultValue));
 }