コード例 #1
0
        /// <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));
            }
        }
コード例 #2
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);
            }
        }
コード例 #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());
        }
コード例 #4
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));
        }
コード例 #5
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));
            }
        }
コード例 #6
0
        public LinqToSql(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();
        }
コード例 #7
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))));
 }
コード例 #8
0
 /// <summary>
 /// Get the Primary key from type
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 public static IFastDeepClonerProperty GetPrimaryKey(this Type type)
 {
     type = type.GetActualType();
     if (CachedPrimaryKeys.ContainsKey(type))
     {
         return(CachedPrimaryKeys[type]);
     }
     return(CachedPrimaryKeys.GetOrAdd(type, DeepCloner.GetFastDeepClonerProperties(type).FirstOrDefault(x => x.ContainAttribute <PrimaryKey>())));
 }
コード例 #9
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()));
        }
コード例 #10
0
 /// <summary>
 ///
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <typeparam name="P"></typeparam>
 /// <param name="expression"></param>
 /// <returns></returns>
 public static MethodInformation GetInfo <T, P>(Expression <Func <T, P> > expression)
 {
     if (KeyValuePairs.ContainsKey(expression))
     {
         return(KeyValuePairs.Get(expression));
     }
     using (var m = new APIController <T>(_baseUrl))
         return(KeyValuePairs.GetOrAdd(expression, m.GetInfo(expression, true)));
 }
コード例 #11
0
 /// <summary>
 /// Get the ColumnSchema
 /// </summary>
 /// <param name="datatype"></param>
 /// <returns></returns>
 public SafeValueType <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 SafeValueType <string, ColumnSchema>();
         if (columns != null)
         {
             columns.ForEach(x => dic.Add(x.ColumnName, x));
         }
         _transaction.CounterException = 0;
         return(CachedColumnSchema.GetOrAdd(key, dic));
     }
     catch (Exception e)
     {
         if (_transaction.DataBaseTypes == DataBaseTypes.PostgreSql && _transaction.CounterException <= 3)
         {
             _transaction.CounterException++;
             _transaction.Renew();
             return(GetColumnSchema(datatype));
         }
         else
         {
             throw new EntityException(e.Message);
         }
     }
 }
コード例 #12
0
        private List <string> DeleteAbstract(object o, bool save)
        {
            object dbTrigger = null;

            GlobalConfiguration.Log?.Info("Delete", o);
            var type            = o.GetType().GetActualType();
            var props           = DeepCloner.GetFastDeepClonerProperties(type);
            var table           = type.TableName().GetName(_repository.DataBaseTypes);
            var primaryKey      = o.GetType().GetPrimaryKey();
            var primaryKeyValue = o.GetPrimaryKeyValue();
            var objectRules     = type.GetCustomAttribute <Rule>();

            if (primaryKeyValue.ObjectIsNew())
            {
                return(new List <string>());
            }
            var sql = new List <string>()
            {
                "DELETE " + (_repository.DataBaseTypes == DataBaseTypes.Sqllight || _repository.DataBaseTypes == DataBaseTypes.PostgreSql ? "From " : "") +
                table +
                Querys.Where(_repository.DataBaseTypes).Column(primaryKey.GetPropertyName()).Equal(primaryKeyValue).Execute()
            };

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

            try
            {
                _repository.CreateTransaction();
                if (objectRules != null)
                {
                    dbTrigger?.GetType().GetMethod("Delete").Invoke(dbTrigger, new List <object>()
                    {
                        _repository, o
                    }.ToArray());                                                                                                // Check the Rule before save
                }
            }
            catch
            {
                _repository.Rollback();
                throw;
            }



            foreach (var prop in props.Where(x => x.CanRead && !x.IsInternalType && x.GetCustomAttribute <IndependentData>() == null && !x.ContainAttribute <JsonDocument>() && !x.ContainAttribute <XmlDocument>() && x.GetCustomAttribute <ExcludeFromAbstract>() == null))
            {
                var value = prop.GetValue(o);

                if (value == null)
                {
                    continue;
                }
                var subSql       = new List <string>();
                var propType     = prop.PropertyType.GetActualType();
                var insertBefore = props.Any(x => x.GetCustomAttribute <ForeignKey>()?.Type == propType);
                if (DeepCloner.GetFastDeepClonerProperties(propType).All(x => x.GetCustomAttribute <ForeignKey>()?.Type != type))
                {
                    if (!insertBefore)
                    {
                        continue;
                    }
                }
                if (value is IList)
                {
                    foreach (var item in value as IList)
                    {
                        subSql.AddRange(DeleteAbstract(item, false));
                    }
                }
                else
                {
                    subSql.AddRange(DeleteAbstract(value, false));
                }

                if (insertBefore)
                {
                    sql.InsertRange(sql.Count - 1, subSql);
                }
                else
                {
                    sql.AddRange(subSql);
                }
            }

            if (!save)
            {
                return(sql);
            }
            try
            {
                _repository.CreateTransaction();

                var       i = sql.Count - 1;
                var       exceptionCount      = 0;
                Exception firstChanceExcepion = null;

                while (sql.Count > 0 && exceptionCount <= 10)
                {
                    try
                    {
                        if (i < 0)
                        {
                            i = sql.Count - 1;
                        }
                        var s   = sql[i];
                        var cmd = _repository.GetSqlCommand(s);
                        cmd.Command.ExecuteNonQuery();
                        sql.RemoveAt(i);
                        i--;
                    }
                    catch (Exception e)
                    {
                        firstChanceExcepion = e;
                        exceptionCount++;
                        i--;
                    }
                }

                if (exceptionCount >= 10)
                {
                    throw firstChanceExcepion;
                }
            }
            catch
            {
                _repository.Rollback();
                throw;
            }
            return(sql);
        }
コード例 #13
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) ? (DataBaseTypes == DataBaseTypes.PostgreSql ? "true" : "1") : (DataBaseTypes == DataBaseTypes.PostgreSql ? "false" : "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:

                    object value     = null;
                    Type   fieldType = null;
                    if (c.Value.GetType().GetFields(_bindingFlags).Length > 0 && (string.IsNullOrEmpty(memName) || c.Value.GetType().GetFields(_bindingFlags).Any(x => x.Name == memName)))
                    {
                        var field = string.IsNullOrEmpty(memName)
                                 ? c.Value.GetType().GetFields(_bindingFlags).FirstOrDefault()
                                 : c.Value.GetType().GetFields(_bindingFlags).FirstOrDefault(x => x.Name == memName);
                        fieldType = field?.FieldType;

                        value = field?.GetValue(c.Value);
                    }
                    else
                    {
                        var field = string.IsNullOrEmpty(memName)
                            ? c.Value.GetType().GetProperties().FirstOrDefault()
                            : c.Value.GetType().GetProperties().FirstOrDefault(x => x.Name == memName);
                        fieldType = field?.PropertyType;
                        value     = field?.GetValue(c.Value);
                    }



                    if (value == null && fieldType == null)
                    {
                        break;
                    }
                    CleanDecoder(ValuetoSql(value, isEnum, fieldType));
                    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);
        }
コード例 #14
0
        internal static IList DataReaderConverter(Transaction.Transaction repository, IDataReader reader, ISqlCommand 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 SafeValueType <int, string>();
                var pp       = new SafeValueType <int, 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 new EntityException(e.Message);
            }
            finally
            {
                reader.Close();
                reader.Dispose();
                if (repository.OpenedDataReaders.ContainsKey(reader))
                {
                    repository.OpenedDataReaders.Remove(reader);
                }
            }

            return(iList);
        }