/// <summary>
        /// Constructor
        /// </summary>
        /// <param name="connectionString">Full connection string</param>
        /// <param name="dataBaseTypes">The type of the database Ms-sql or Sql-light</param>
        public Transaction(string connectionString, DataBaseTypes dataBaseTypes) : base()
        {
            base._transaction = this;
            _attachedObjects  = new Custom_ValueType <string, object>();
            if (string.IsNullOrEmpty(connectionString))
            {
                if (string.IsNullOrEmpty(connectionString))
                {
                    throw new EntityException("ConnectionString can not be empty");
                }
            }

            ConnectionString = connectionString;
            DataBaseTypes    = dataBaseTypes;
            _dbSchema        = new DbSchema(this);

            if (!_moduleIni[dataBaseTypes])
            {
                lock (this)
                {
                    if (!_moduleIni[dataBaseTypes])
                    {
                        OnModuleConfiguration(new ModuleBuilder(dataBaseTypes));
                        OnModuleStart();
                        _moduleIni[dataBaseTypes] = true;
                    }
                }
            }
            else
            {
                _moduleIni[dataBaseTypes] = true;
            }
        }
예제 #2
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));
     }
 }
 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);
 }
예제 #4
0
        internal Dictionary <string, myPropInfo> Getproperties(Type type, string typename)
        {
            Dictionary <string, myPropInfo> sd = null;

            if (_propertycache.TryGetValue(typename, out sd))
            {
                return(sd);
            }
            else
            {
                sd = new Custom_ValueType <string, myPropInfo>();
                var pr = DeepCloner.GetFastDeepClonerProperties(type);
                foreach (var p in pr)
                {
                    if (!p.CanRead)// Property is an indexer
                    {
                        continue;
                    }

                    myPropInfo d = CreateMyProp(p.PropertyType, p.Name);
                    d.Property = p;
                    d.CanWrite = p.CanWrite;

                    foreach (var at in p.Attributes)
                    {
                        if (at is DataMemberAttribute)
                        {
                            var dm = (DataMemberAttribute)at;
                            if (dm.Name != "")
                            {
                                d.memberName = dm.Name;
                            }
                        }
                    }
                    if (d.memberName != null)
                    {
                        sd.Add(d.memberName, d);
                    }
                    else
                    {
                        sd.Add(p.Name.ToLowerInvariant(), d);
                    }
                }

                _propertycache.Add(typename, sd);
            }
            return(sd);
        }
 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));
            }
        }
예제 #7
0
        internal static DbCommandExtended ProcessSql(this IRepository repository, IDbConnection connection, IDbTransaction tran, string sql)
        {
            var             i       = 1;
            var             dicCols = new Custom_ValueType <string, Tuple <object, SqlDbType> >();
            MatchCollection matches = null;

            while ((matches = stringExp.Matches(sql)).Count > 0)
            {
                var    exp = matches[0];
                var    col = "@CO" + i + "L";
                object str = exp.Value.TrimEnd(']').Substring(@"String\[".Length - 1);
                sql = sql.Remove(exp.Index, exp.Value.Length);
                sql = sql.Insert(exp.Index, col);
                dicCols.TryAdd(col, new Tuple <object, SqlDbType>(str.ConvertValue <string>(), SqlDbType.NVarChar));
                i++;
            }

            while ((matches = dateExp.Matches(sql)).Count > 0)
            {
                var    exp = matches[0];
                var    col = "@CO" + i + "L";
                object str = exp.Value.TrimEnd(']').Substring(@"Date\[".Length - 1);
                sql = sql.Remove(exp.Index, exp.Value.Length);
                sql = sql.Insert(exp.Index, col);
                dicCols.TryAdd(col, new Tuple <object, SqlDbType>(str.ConvertValue <DateTime>(), SqlDbType.DateTime));
                i++;
            }

            while ((matches = guidExp.Matches(sql)).Count > 0)
            {
                var    exp = matches[0];
                var    col = "@CO" + i + "L";
                object str = exp.Value.TrimEnd(']').Substring(@"Guid\[".Length - 1);
                sql = sql.Remove(exp.Index, exp.Value.Length);
                sql = sql.Insert(exp.Index, col);
                dicCols.TryAdd(col, new Tuple <object, SqlDbType>(str.ConvertValue <Guid?>(), SqlDbType.UniqueIdentifier));
                i++;
            }

            sql = sql.CleanValidSqlName(repository.DataBaseTypes);
            DbCommand cmd = null;

            if (repository.DataBaseTypes == DataBaseTypes.Mssql)
            {
                cmd = tran != null ? new SqlCommand(sql, connection as SqlConnection, tran as SqlTransaction) : new SqlCommand(sql, connection as SqlConnection);
            }
            else if (repository.DataBaseTypes == DataBaseTypes.Sqllight)
            {
                cmd = tran == null ? new SQLiteCommand(sql, connection as SQLiteConnection) : new SQLiteCommand(sql, connection as SQLiteConnection, tran as SQLiteTransaction);
            }
            else
            {
                cmd = tran == null ? new NpgsqlCommand(sql, connection as NpgsqlConnection) : new NpgsqlCommand(sql, connection as NpgsqlConnection, tran as NpgsqlTransaction);
            }
            var dbCommandExtended = new DbCommandExtended(cmd, repository);

            foreach (var dic in dicCols)
            {
                repository.AddInnerParameter(dbCommandExtended, dic.Key, dic.Value.Item1, dic.Value.Item2);
            }
            return(dbCommandExtended);
        }
예제 #8
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);
        }