Exemplo n.º 1
0
        /// <summary>
        /// Convert System Type to SqlType
        /// </summary>
        /// <param name="type"></param>
        /// <param name="dbType"></param>
        /// <returns></returns>
        public static string GetDbTypeByType(this Type type, DataBaseTypes dbType)
        {
            if (type.GetTypeInfo().IsEnum)
            {
                type = typeof(long);
            }


            if (Nullable.GetUnderlyingType(type) != null)
            {
                type = Nullable.GetUnderlyingType(type);
            }
            if (dbType == DataBaseTypes.Mssql)
            {
                return(DbMsSqlMapper.ContainsKey(type) ? DbMsSqlMapper[type].First() : null);
            }
            else if (dbType == DataBaseTypes.Sqllight)
            {
                return(DbSQLiteMapper.ContainsKey(type) ? DbSQLiteMapper[type].First() : null);
            }
            else
            {
                return(DbPostGresqlMapper.ContainsKey(type) ? DbPostGresqlMapper[type].First() : null);
            }
        }
        /// <summary>
        /// Attach object to WorkEntity to track changes
        /// </summary>
        /// <param name="objcDbEntity"></param>
        /// <param name="overwrite"></param>
        internal void Attach(object objcDbEntity, bool overwrite = false)
        {
            var key = objcDbEntity.EntityKey();

            GlobalConfiguration.Log?.Info("Attaching", key);
            if (objcDbEntity == null)
            {
                throw new EntityException("DbEntity cant be null");
            }
            if (Extension.ObjectIsNew(objcDbEntity.GetPrimaryKeyValue()))
            {
                throw new EntityException("Id is IsNullOrEmpty, it cant be attached");
            }


            if (_attachedObjects.ContainsKey(key))
            {
                if (overwrite)
                {
                    _attachedObjects.GetOrAdd(key, this.Clone(objcDbEntity, CloneLevel.FirstLevelOnly), true);
                }
            }
            else
            {
                _attachedObjects.GetOrAdd(key, this.Clone(objcDbEntity, CloneLevel.FirstLevelOnly));
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Get all by object
        /// PrimaryKey attr must be set ins Where
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="repository"></param>
        /// <param name="query"></param>
        /// <returns></returns>

        public List <T> Select <T>(string query = null)
        {
            if (query == null || !CachedSql.ContainsKey(query))
            {
                var type = typeof(T);
                if (string.IsNullOrEmpty(query))
                {
                    query = Querys.Select(type, _repository.DataBaseTypes).Execute();
                }
                CachedSql.GetOrAdd(query, query);
            }
            return(_repository.DataReaderConverter <T>(_repository.GetSqlCommand(CachedSql[query])).Execute());
        }
 public LightDataLinqToNoSql(Type type, Transaction.Transaction transaction)
 {
     _transaction = transaction;
     _obType      = type.GetActualType();
     if (!CachedColumns.ContainsKey(_obType))
     {
         _columns = CachedColumns.GetOrAdd(_obType, _transaction.GetColumnSchema(_obType).Select(x => $"[{_obType.TableName()}].[{x.Key}]").ToList());
     }
     else
     {
         _columns = CachedColumns[_obType];
     }
     _primaryId = _obType.GetPrimaryKey()?.GetPropertyName();
 }
Exemplo n.º 5
0
 public LightDataLinqToNoSql(Type type, Transaction.Transaction transaction)
 {
     _transaction = transaction;
     _obType      = type.GetActualType();
     if (!CachedColumns.ContainsKey(_obType))
     {
         _columns = CachedColumns.GetOrAdd(_obType, _transaction._dbSchema.ObjectColumns(_obType).Rows.Select(x => $"[{_obType.TableName()}].[{x.Value<string>("column_name")}]").ToList());
     }
     else
     {
         _columns = CachedColumns[_obType];
     }
     _primaryId = OrderBy = _obType.GetPrimaryKey()?.GetPropertyName();
 }
Exemplo n.º 6
0
        public ILightDataTable ObjectColumns(Type type)
        {
            var key = type.FullName + _repository.DataBaseTypes.ToString();

            try
            {
                if (CachedObjectColumn.ContainsKey(key))
                {
                    return(CachedObjectColumn[key]);
                }
                var table = type.TableName();
                var cmd   = _repository.GetSqlCommand(_repository.DataBaseTypes == DataBaseTypes.Mssql || _repository.DataBaseTypes == DataBaseTypes.PostgreSql
                    ? $"SELECT COLUMN_NAME as column_name, data_type FROM INFORMATION_SCHEMA.COLUMNS WHERE LOWER(TABLE_NAME) = LOWER(String[{table}])"
                    : $"SELECT name as column_name, type as data_type  FROM pragma_table_info(String[{table}]);");
                var data = _repository.GetLightDataTable(cmd, "column_name");
                if (data.Rows.Any())
                {
                    return(CachedObjectColumn.GetOrAdd(key, data));
                }
                else
                {
                    return(data);
                }
            }
            catch (NpgsqlException)
            {
                _repository.Renew();
                return(ObjectColumns(type));
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Get Internal type of IList
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static Type GetActualType(this Type type)
        {
            if (CachedActualType.ContainsKey(type))
            {
                return(CachedActualType[type]);
            }

            if (type.GetTypeInfo().IsArray)
            {
                CachedActualType.TryAdd(type, type.GetElementType());
            }
            else if (type.GenericTypeArguments.Any())
            {
                CachedActualType.TryAdd(type, type.GenericTypeArguments.First());
            }
            else if (type.FullName?.Contains("List`1") ?? false)
            {
                CachedActualType.TryAdd(type, type.GetRuntimeProperty("Item").PropertyType);
            }
            else
            {
                CachedActualType.TryAdd(type, type);
            }

            return(CachedActualType.Get(type));
        }
 internal static Type GetIListType(this Type type)
 {
     if (CachedTypes.ContainsKey(type))
     {
         return(CachedTypes[type]);
     }
     if (type.IsArray)
     {
         return(CachedTypes.GetOrAdd(type, type.GetElementType()));
     }
     else
     {
         if (type.GenericTypeArguments.Any())
         {
             return(CachedTypes.GetOrAdd(type, typeof(List <>).MakeGenericType(type.GenericTypeArguments.First())));
         }
         else if (type.FullName.Contains("List`1"))
         {
             return(CachedTypes.GetOrAdd(type, typeof(List <>).MakeGenericType(type.GetRuntimeProperty("Item").PropertyType)));
         }
         else
         {
             return(CachedTypes.GetOrAdd(type, type));
         }
     }
 }
Exemplo n.º 9
0
 /// <summary>
 /// Get the ColumnSchema
 /// </summary>
 /// <param name="datatype"></param>
 /// <returns></returns>
 public Custom_ValueType <string, ColumnSchema> GetColumnSchema(Type datatype)
 {
     try
     {
         var key = datatype.FullName + _transaction.DataBaseTypes.ToString();
         if (CachedColumnSchema.ContainsKey(key))
         {
             return(CachedColumnSchema[key]);
         }
         datatype = datatype.GetActualType();
         var tableName = datatype.TableName();
         var sql       = $"SELECT COLUMN_NAME as columnname, data_type as datatype ,TABLE_CATALOG as db,TABLE_NAME as tb , IS_NULLABLE as isnullable FROM INFORMATION_SCHEMA.COLUMNS WHERE LOWER(TABLE_NAME) = LOWER(String[{tableName.Name}])";
         if (_transaction.DataBaseTypes == DataBaseTypes.Sqllight)
         {
             sql = $"SELECT name  as columnname, type as datatype FROM pragma_table_info(String[{tableName.Name}])";
         }
         var columns = (List <ColumnSchema>)_transaction.DataReaderConverter(_transaction.GetSqlCommand(sql), typeof(ColumnSchema));
         var dic     = new Custom_ValueType <string, ColumnSchema>();
         if (columns != null)
         {
             columns.ForEach(x => dic.Add(x.ColumnName, x));
         }
         return(CachedColumnSchema.GetOrAdd(key, dic));
     }
     catch (NpgsqlException)
     {
         _transaction.Renew();
         return(GetColumnSchema(datatype));
     }
 }
Exemplo n.º 10
0
        public static string SerializaName(JsonFormatting jsonFormatting, string name)
        {
            var key = jsonFormatting.ToString() + name;

            if (_chachedNames.ContainsKey(key))
            {
                return(_chachedNames[key]);
            }
            string value = null;

            lock (_chachedNames)
            {
                switch (jsonFormatting)
                {
                case JsonFormatting.Auto:
                    value = name;
                    break;

                case JsonFormatting.CamelCase:
                    var s = name.Substring(1, name.Length - 1);
                    value = $"{name[0].ToString().ToLower()}{s}";
                    break;

                case JsonFormatting.LowerCase:
                    value = name.ToLower();
                    break;
                }
                return(_chachedNames.GetOrAdd(key, value));
            }
        }
Exemplo n.º 11
0
 /// <summary>
 /// The value of attribute Table
 /// </summary>
 /// <typeparam name="type"></typeparam>
 /// <returns></returns>
 public static Table TableName(this Type type)
 {
     if (CachedTableNames.ContainsKey(type))
     {
         return(CachedTableNames[type]);
     }
     return(CachedTableNames.GetOrAdd(type, (type.GetCustomAttribute <Table>() ?? new Table(type.Name))));
 }
        public LightDataLinqToNoSql(Type type, Transaction.Transaction transaction)
        {
            _transaction  = transaction;
            _obType       = type.GetActualType();
            DataBaseTypes = transaction.DataBaseTypes;
            var key = _obType.FullName + DataBaseTypes;

            if (!CachedColumns.ContainsKey(key))
            {
                _columns = CachedColumns.GetOrAdd(key, _transaction.GetColumnSchema(_obType).Select(x => $"{_obType.TableName().GetName(DataBaseTypes)}.[{x.Key}]").ToList());
            }
            else
            {
                _columns = CachedColumns[key];
            }
            _primaryId = _obType.GetPrimaryKey()?.GetPropertyName();
        }
Exemplo n.º 13
0
 /// <summary>
 /// Get the Primary key from type
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 public static IFastDeepClonerProperty GetPrimaryKey(this Type type)
 {
     if (CachedPrimaryKeys.ContainsKey(type))
     {
         return(CachedPrimaryKeys[type]);
     }
     return(CachedPrimaryKeys.GetOrAdd(type, DeepCloner.GetFastDeepClonerProperties(type).FirstOrDefault(x => x.ContainAttribute <PrimaryKey>())));
 }
 internal static bool GetField(this FieldInfo field, Custom_ValueType <string, IFastDeepClonerProperty> properties)
 {
     if (!properties.ContainsKey(field.Name))
     {
         return(properties.TryAdd(field.Name, new FastDeepClonerProperty(field)));
     }
     return(true);
 }
Exemplo n.º 15
0
 /// <summary>
 /// The value of attribute Table
 /// </summary>
 /// <typeparam name="type"></typeparam>
 /// <returns></returns>
 public static String TableName(this Type type)
 {
     if (CachedTableNames.ContainsKey(type))
     {
         return(CachedTableNames[type]);
     }
     return(CachedTableNames.GetOrAdd(type, (type.GetCustomAttribute <Table>()?.Name ?? type.Name).CleanName()));
 }
Exemplo n.º 16
0
        /// <summary>
        /// Get PropertyName from the cashed Properties
        /// </summary>
        /// <param name="prop"></param>
        /// <returns></returns>
        public static string GetPropertyName(this IFastDeepClonerProperty prop)
        {
            if (CachedPropertyNames.ContainsKey(prop))
            {
                return(CachedPropertyNames[prop]);
            }

            return(CachedPropertyNames.GetOrAdd(prop, (prop.GetCustomAttribute <PropertyName>()?.Name ?? prop.Name).CleanName()));
        }
Exemplo n.º 17
0
        /// <summary>
        /// Attach object to WorkEntity to track changes
        /// </summary>
        /// <param name="objcDbEntity"></param>
        /// <param name="overwrite"></param>
        public void Attach(object objcDbEntity, bool overwrite = false)
        {
            if (objcDbEntity == null)
            {
                throw new NullReferenceException("DbEntity cant be null");
            }
            if (Extension.ObjectIsNew(objcDbEntity.GetPrimaryKeyValue()))
            {
                throw new NullReferenceException("Id is IsNullOrEmpty, it cant be attached");
            }
            var key = objcDbEntity.EntityKey();

            if (_attachedObjects.ContainsKey(key))
            {
                if (overwrite)
                {
                    _attachedObjects.GetOrAdd(key, this.Clone(objcDbEntity, CloneLevel.FirstLevelOnly), true);
                }
            }
            else
            {
                _attachedObjects.GetOrAdd(key, this.Clone(objcDbEntity, CloneLevel.FirstLevelOnly));
            }
        }
 internal static Dictionary <string, IFastDeepClonerProperty> GetFastDeepClonerProperties(this Type primaryType)
 {
     if (!CachedPropertyInfo.ContainsKey(primaryType))
     {
         var properties = new Custom_ValueType <string, IFastDeepClonerProperty>();
         if (primaryType.GetTypeInfo().BaseType != null && primaryType.GetTypeInfo().BaseType.Name != "Object")
         {
             primaryType.GetRuntimeProperties().Where(x => x.GetField(properties)).ToList();
             primaryType.GetTypeInfo().BaseType.GetRuntimeProperties().Where(x => x.GetField(properties)).ToList();
         }
         else
         {
             primaryType.GetRuntimeProperties().Where(x => x.GetField(properties)).ToList();
         }
         CachedPropertyInfo.Add(primaryType, properties);
     }
     return(CachedPropertyInfo[primaryType]);
 }
        internal static object Creator(this Type type)
        {
            if (!DefaultConstructor.ContainsKey(type))
            {
                DefaultConstructor.Add(type, type.GetConstructor(Type.EmptyTypes));
            }


            if (DefaultConstructor[type] != null)
            {
#if NETSTANDARD2_0 || NETSTANDARD1_3 || NETSTANDARD1_5
                if (CachedConstructor.ContainsKey(type))
                {
                    return(CachedConstructor[type].Invoke());
                }
                return(CachedConstructor.GetOrAdd(type, Expression.Lambda <Func <object> >(Expression.New(type)).Compile()).Invoke());
#else
                if (CachedDynamicMethod.ContainsKey(type))
                {
                    return(CachedDynamicMethod[type]());
                }

                var emptyConstructor = DefaultConstructor[type];
                var dynamicMethod    = new System.Reflection.Emit.DynamicMethod("CreateInstance", type, Type.EmptyTypes, true);
                System.Reflection.Emit.ILGenerator ilGenerator = dynamicMethod.GetILGenerator();
                ilGenerator.Emit(System.Reflection.Emit.OpCodes.Nop);
                ilGenerator.Emit(System.Reflection.Emit.OpCodes.Newobj, emptyConstructor);
                ilGenerator.Emit(System.Reflection.Emit.OpCodes.Ret);
                return(CachedDynamicMethod.GetOrAdd(type, (ObjectActivator)dynamicMethod.CreateDelegate(typeof(ObjectActivator)))());
#endif
            }
            else
            {
                return(FormatterServices.GetUninitializedObject(type));
            }
        }
Exemplo n.º 20
0
        protected Expression VisitConstantFixed(ConstantExpression c, string memName = "")
        {
            IQueryable q             = c.Value as IQueryable;
            var        StringifyText = StringyFyExp.Matches(sb.ToString()).Cast <Match>().FirstOrDefault();
            var        isEnum        = StringifyText != null;
            string     type          = null;

            if (isEnum)
            {
                type = CleanText();
            }
            if (q == null && c.Value == null)
            {
                sb.Append("NULL");
            }
            else if (q == null)
            {
                switch (Type.GetTypeCode(c.Value.GetType()))
                {
                case TypeCode.Boolean:
                    sb.Append(((bool)c.Value) ? 1 : 0);
                    break;

                case TypeCode.String:
                    CleanDecoder(string.Format("String[{0}]", c.Value));
                    break;

                case TypeCode.DateTime:
                    CleanDecoder(string.Format("Date[{0}]", c.Value));
                    break;

                case TypeCode.Object:

                    var field = string.IsNullOrEmpty(memName)
                            ? c.Value.GetType().GetFields().FirstOrDefault()
                            : c.Value.GetType().GetFields().FirstOrDefault(x => x.Name == memName);

                    object value = null;
                    value = field?.GetValue(c.Value) ?? c.Value.GetType().GetFields().FirstOrDefault()?.GetValue(c.Value);

                    if (value == null)
                    {
                        break;
                    }
                    CleanDecoder(ValuetoSql(value, isEnum));
                    break;

                default:
                    if (isEnum && SavedTypes.ContainsKey(type))
                    {
                        var enumtype = SavedTypes[type];
                        var v        = c.Value.ConvertValue(enumtype);
                        CleanDecoder(ValuetoSql(v, isEnum));
                        break;
                    }
                    CleanDecoder(ValuetoSql(c.Value, isEnum));
                    break;
                }
            }

            return(c);
        }
Exemplo n.º 21
0
        private object Save(object o, bool isIndependentData, bool updateOnly = false)
        {
            try
            {
                GlobalConfiguration.Log?.Info("Save", o);
                _repository.CreateTransaction();
                var props      = DeepCloner.GetFastDeepClonerProperties(o.GetType());
                var primaryKey = o.GetPrimaryKey();

                if (primaryKey == null)
                {
                    throw new EntityException("Object must have a PrimaryKey");
                }

                var primaryKeyId        = !Extension.ObjectIsNew(o.GetPrimaryKeyValue()) ? o.GetPrimaryKeyValue() : null;
                var availableColumns    = ObjectColumns(o.GetType());
                var objectRules         = o.GetType().GetCustomAttribute <Rule>();
                var tableName           = o.GetType().TableName();
                var primaryKeySubstitut = !primaryKey.GetCustomAttribute <PrimaryKey>().AutoGenerate ? primaryKeyId : null;

                object dbTrigger = null;
                if (objectRules != null && !CachedIDbRuleTrigger.ContainsKey(o.GetType()))
                {
                    dbTrigger = objectRules.RuleType.CreateInstance(true);
                    CachedIDbRuleTrigger.Add(o.GetType(), dbTrigger);
                }
                else if (objectRules != null || CachedIDbRuleTrigger.ContainsKey(o.GetType()))
                {
                    dbTrigger = CachedIDbRuleTrigger[o.GetType()];
                }

                if (primaryKeyId != null && !updateOnly) // lets attach the object
                {
                    var data = GetById(primaryKeyId, o.GetType());
                    if (data == null)
                    {
                        primaryKeyId = null;
                        o.SetPrimaryKeyValue();
                    }
                    else
                    {
                        if (!_repository.IsAttached(o))
                        {
                            _repository.Attach(data);
                        }

                        var changes = _repository.GetObjectChanges(o);
                        foreach (var item in props.Where(x => x.CanRead && !changes.Any(a => a.PropertyName == x.Name) && x.IsInternalType))
                        {
                            item.SetValue(o, item.GetValue(data));
                        }
                    }
                }

                if (!updateOnly)
                {
                    dbTrigger?.GetType().GetMethod("BeforeSave").Invoke(dbTrigger, new List <object>()
                    {
                        _repository, o
                    }.ToArray());                                                                                                    // Check the Rule before save
                }
                object tempPrimaryKey = null;
                var    sql            = "UPDATE [" + (o.GetType().TableName()) + "] SET ";
                var    cols           = props.FindAll(x => (availableColumns.FindByPrimaryKey <bool>(x.GetPropertyName()) || availableColumns.FindByPrimaryKey <bool>(x.GetPropertyName().ToLower())) && x.IsInternalType && !x.ContainAttribute <ExcludeFromAbstract>() && x.GetCustomAttribute <PrimaryKey>() == null);
                if (primaryKeyId == null)
                {
                    if (primaryKey.PropertyType.IsNumeric() && primaryKey.GetCustomAttribute <PrimaryKey>().AutoGenerate)
                    {
                        sql  = "INSERT INTO [" + tableName + "](" + string.Join(",", cols.Select(x => "[" + x.GetPropertyName() + "]")) + ") Values(";
                        sql += string.Join(",", cols.Select(x => "@" + x.GetPropertyName())) + ");";
                        sql += _repository.DataBaseTypes == DataBaseTypes.Sqllight ? " select last_insert_rowid();" : (_repository.DataBaseTypes != DataBaseTypes.PostgreSql ? " SELECT IDENT_CURRENT('" + tableName + "');" : " SELECT currval('" + string.Format("{0}_{1}_seq", tableName, primaryKey.GetPropertyName()) + "');");
                    }
                    else
                    {
                        var colList = new List <IFastDeepClonerProperty>();
                        tempPrimaryKey = primaryKeySubstitut == null?Guid.NewGuid() : primaryKeySubstitut;

                        if (primaryKeySubstitut == null && primaryKey.PropertyType.IsNumeric())
                        {
                            tempPrimaryKey = _repository.ExecuteScalar(_repository.GetSqlCommand(String.Format("SELECT MAX([{0}]) FROM [{1}]", primaryKey.GetPropertyName(), tableName))).ConvertValue <long>() + 1;
                        }
                        else if (primaryKey.PropertyType == typeof(string))
                        {
                            tempPrimaryKey = tempPrimaryKey.ToString();
                        }
                        colList.Insert(0, primaryKey);
                        colList.AddRange(cols);
                        sql  = "INSERT INTO [" + tableName + "](" + string.Join(",", colList.Select(x => "[" + x.GetPropertyName() + "]")) + ") Values(";
                        sql += string.Join(",", colList.Select(x => "@" + x.GetPropertyName())) + "); select '" + tempPrimaryKey + "'";
                    }
                }
                else
                {
                    sql += string.Join(",", cols.Select(x => "[" + x.GetPropertyName() + "]" + " = @" + x.GetPropertyName()));
                    sql += Querys.Where(_repository.DataBaseTypes).Column(o.GetType().GetActualType().GetPrimaryKey().GetPropertyName()).Equal(primaryKeyId).Execute();
                }

                var cmd = _repository.GetSqlCommand(sql);
                if ((!primaryKey.PropertyType.IsNumeric() || !primaryKey.GetCustomAttribute <PrimaryKey>().AutoGenerate) && primaryKeyId == null)
                {
                    _repository.AddInnerParameter(cmd, primaryKey.GetPropertyName(), tempPrimaryKey, _repository.GetSqlType(primaryKey.PropertyType));
                }


                foreach (var col in cols)
                {
                    var v = col.GetValue(o);
                    var defaultOnEmpty = col.GetCustomAttribute <DefaultOnEmpty>();
                    if (col.ContainAttribute <ForeignKey>() && (v?.ObjectIsNew() ?? true))
                    {
                        var ob              = props.FirstOrDefault(x => x.PropertyType == col.GetCustomAttribute <ForeignKey>().Type&& (string.IsNullOrEmpty(col.GetCustomAttribute <ForeignKey>().PropertyName) || col.GetCustomAttribute <ForeignKey>().PropertyName == x.Name));
                        var obValue         = ob?.GetValue(o);
                        var independentData = ob?.GetCustomAttribute <IndependentData>() != null;
                        if (obValue != null)
                        {
                            v = obValue.GetType().GetPrimaryKey().GetValue(obValue)?.ObjectIsNew() ?? true?
                                Save(obValue, independentData) :
                                    obValue.GetType().GetPrimaryKey().GetValue(obValue);

                            col.SetValue(o, v);
                        }
                    }

                    if (col.ContainAttribute <ToBase64String>())
                    {
                        if (!v?.ConvertValue <string>().IsBase64String() ?? false)
                        {
                            v = MethodHelper.EncodeStringToBase64(v.ConvertValue <string>());
                        }
                    }

                    if (col.ContainAttribute <Stringify>() || col.ContainAttribute <DataEncode>())
                    {
                        v = v?.ConvertValue <string>();
                    }

                    if (col.ContainAttribute <DataEncode>())
                    {
                        if (col.PropertyType != typeof(string))
                        {
                            throw new EntityException(string.Format("Property {0} Contain DataEncode. PropertyType must be of type String .", col.FullName));
                        }
                        v = new DataCipher(col.GetCustomAttribute <DataEncode>().Key, col.GetCustomAttribute <DataEncode>().KeySize).Encrypt(v.ToString());
                    }

                    if (col.ContainAttribute <NotNullable>() && v == null && defaultOnEmpty == null)
                    {
                        throw new EntityException(string.Format("Property {0} dose not allow null.", col.FullName));
                    }


                    if (v == null && defaultOnEmpty != null)
                    {
                        v = defaultOnEmpty.Value.ConvertValue(col.PropertyType);
                    }

                    _repository.AddInnerParameter(cmd, col.GetPropertyName(), v, (col.ContainAttribute <Stringify>() || col.ContainAttribute <DataEncode>() || col.ContainAttribute <ToBase64String>() ? _repository.GetSqlType(typeof(string)) : _repository.GetSqlType(col.PropertyType)));
                }

                if (primaryKeyId == null)
                {
                    primaryKeyId = _repository.ExecuteScalar(cmd).ConvertValue(primaryKey.PropertyType);
                }
                else
                {
                    _repository.ExecuteNonQuery(cmd);
                }
                var oState = dbTrigger != null?DeepCloner.Clone(o) : null;

                if (updateOnly)
                {
                    return(primaryKeyId);
                }
                dbTrigger?.GetType().GetMethod("AfterSave").Invoke(dbTrigger, new List <object>()
                {
                    _repository, o, primaryKeyId
                }.ToArray());                                                                                                                 // Check the Rule before save

                foreach (var prop in props.Where(x => !x.IsInternalType && !x.ContainAttribute <ExcludeFromAbstract>()))
                {
                    var independentData = prop.GetCustomAttribute <IndependentData>() != null;
                    var type            = prop.PropertyType.GetActualType();
                    var oValue          = prop.GetValue(o);
                    if (oValue == null)
                    {
                        continue;
                    }
                    var vList = oValue is IList ? (IList)oValue : new List <object>()
                    {
                        oValue
                    };

                    foreach (var item in vList)
                    {
                        var foreignKey = DeepCloner.GetFastDeepClonerProperties(item.GetType()).FirstOrDefault(x => x.GetCustomAttribute <ForeignKey>()?.Type == o.GetType() && string.IsNullOrEmpty(x.GetCustomAttribute <ForeignKey>().PropertyName));
                        foreignKey?.SetValue(item, primaryKeyId);
                        var res = Save(item, independentData);
                        foreignKey = props.FirstOrDefault(x => x.GetCustomAttribute <ForeignKey>()?.Type == type && (x.GetCustomAttribute <ForeignKey>().PropertyName == prop.Name || string.IsNullOrEmpty(x.GetCustomAttribute <ForeignKey>().PropertyName)));
                        if (foreignKey == null || !foreignKey.GetValue(o).ObjectIsNew())
                        {
                            continue;
                        }
                        if (o.GetType() == foreignKey.GetCustomAttribute <ForeignKey>().Type)
                        {
                            continue;
                        }
                        foreignKey.SetValue(o, res);
                    }
                }


                if (oState != null && _repository.GetObjectChanges(o, oState).Count > 0) // a change has been made outside the function Save then resave
                {
                    o.SetPrimaryKeyValue(primaryKeyId);
                    Save(o, false, true);
                }
                o.SetPrimaryKeyValue(primaryKeyId);
                _repository.Attach(o, true);
                return(primaryKeyId);
            }
            catch (Exception e)
            {
                GlobalConfiguration.Log?.Error(e);
                _repository.Rollback();
                throw;
            }
        }
Exemplo n.º 22
0
        internal static IList DataReaderConverter(Transaction.Transaction repository, IDataReader reader, DbCommandExtended command, Type type)
        {
            var tType        = type.GetActualType();
            var attachable   = tType.GetPrimaryKey() != null;
            var baseListType = typeof(List <>);
            var listType     = baseListType.MakeGenericType(tType);
            var iList        = DeepCloner.CreateInstance(listType) as IList;
            var props        = DeepCloner.GetFastDeepClonerProperties(tType);

            try
            {
                var colNames = new Custom_ValueType <int, string>();
                var pp       = new Custom_ValueType <int, FastDeepCloner.IFastDeepClonerProperty>();
                while (reader.Read())
                {
                    object item   = null;
                    object clItem = null;

                    item   = DeepCloner.CreateInstance(tType);
                    clItem = attachable ? DeepCloner.CreateInstance(tType) : null;
                    var col = 0;

                    while (col < reader.FieldCount)
                    {
                        string columnName;
                        if (colNames.ContainsKey(col))
                        {
                            columnName = colNames[col];
                        }
                        else
                        {
                            columnName = reader.GetName(col);
                            colNames.TryAdd(col, columnName);
                        }

                        var value = reader[columnName];

                        IFastDeepClonerProperty prop;
                        if (!pp.ContainsKey(col))
                        {
                            prop = DeepCloner.GetProperty(tType, columnName);
                            if (prop == null)
                            {
                                prop = props.FirstOrDefault(x => string.Equals(x.GetPropertyName(), columnName, StringComparison.CurrentCultureIgnoreCase) || x.GetPropertyName().ToLower() == columnName);
                            }
                            pp.TryAdd(col, prop);
                        }
                        else
                        {
                            prop = pp[col];
                        }
                        if (prop != null && value != DBNull.Value && value != null && prop.CanRead)
                        {
                            if (value as byte[] != null && prop.PropertyType.FullName.Contains("Guid"))
                            {
                                value = new Guid(value as byte[]);
                            }

                            var dataEncode = prop.GetCustomAttribute <DataEncode>();
                            if (prop.ContainAttribute <ToBase64String>())
                            {
                                if (value.ConvertValue <string>().IsBase64String())
                                {
                                    value = MethodHelper.DecodeStringFromBase64(value.ConvertValue <string>());
                                }
                                else
                                {
                                    value = MethodHelper.ConvertValue(value, prop.PropertyType);
                                }
                            }
                            else if (dataEncode != null)
                            {
                                value = new DataCipher(dataEncode.Key, dataEncode.KeySize).Decrypt(value.ConvertValue <string>());
                            }
                            else if (prop.ContainAttribute <JsonDocument>())
                            {
                                value = value?.ToString().FromJson(prop.PropertyType);
                            }
                            else if (prop.ContainAttribute <XmlDocument>())
                            {
                                value = value?.ToString().FromXml();
                            }
                            else
                            {
                                value = MethodHelper.ConvertValue(value, prop.PropertyType);
                            }

                            prop.SetValue(item, value);
                            if (attachable)
                            {
                                prop.SetValue(clItem, value);
                            }
                        }
                        col++;
                    }

                    if (clItem != null && !(repository?.IsAttached(clItem) ?? true))
                    {
                        repository?.AttachNew(clItem);
                    }
                    iList.Add(item);
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                reader.Close();
                reader.Dispose();
                if (repository.OpenedDataReaders.ContainsKey(reader))
                {
                    repository.OpenedDataReaders.Remove(reader);
                }
            }

            return(iList);
        }