// Get the full connection string from the web-config
 public static string GetConnectionString(DataBaseTypes dbType)
 {
     return(dbType == DataBaseTypes.Mssql ?
            @"Server=DESKTOP-Q2EP00O\SQLEXPRESS;Trusted_Connection=false; Database=CMStest; User Id=root; Password=root;" :
            (dbType == DataBaseTypes.Sqllight ? @"Data Source=E:\Projects\EntityWorker.Core\Source\EntityWorker.Core.test\LightData.CMS.Modules\app_data\LightDataTabletest.db" :
             "Host=localhost;Username=postgres;Password=root;Database=mydatabase"));
 }
Example #2
0
        // ReSharper disable once MemberCanBePrivate.Global
        public async Task <Response <CheckUpdateResponseModel> > CheckForUpdates(DataBaseTypes sourceType)
        {
            try
            {
                var checkUpdates = await _checkUpdates.CheckForUpdates(sourceType);

                if (checkUpdates.ResultCode != ResponseCodes.SUCCESS)
                {
                    throw new CustomException(checkUpdates.ResultCode,
                                              checkUpdates.Errors.FirstOrDefault()?.ResultMessage);
                }

                return(new Response <CheckUpdateResponseModel>(checkUpdates.Data));
            }
            catch (CustomException ce)
            {
                Console.WriteLine(ce.Errors.FirstOrDefault()?.ResultMessage);
                throw;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Example #3
0
 public Repository(DataBaseTypes dbType = DataBaseTypes.Mssql) : base(GetConnectionString(dbType), true, dbType)
 {
     if (!base.DataBaseExist())
     {
         base.CreateDataBase();
     }
 }
        /// <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;
            }
        }
Example #5
0
        public async Task <Response <List <DbFileModel> > > GetDbFile(DataBaseTypes sourceType)
        {
            var response = new Response <List <DbFileModel> >();

            try
            {
                var getDbFiles = await _lastDatesService.GetDbFile(sourceType);

                if (getDbFiles.ResultCode != ResponseCodes.SUCCESS)
                {
                    throw new CustomException(getDbFiles.ResultCode,
                                              getDbFiles.Errors.FirstOrDefault()?.ResultMessage);
                }

                response.Data = getDbFiles.Data;
                return(response);
            }
            catch (CustomException ce)
            {
                Console.WriteLine(ce.Errors.FirstOrDefault()?.ResultMessage);
                throw;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
        public async Task <Response <CheckUpdateResponseModel> > CheckForUpdates(DataBaseTypes sourceType)
        {
            try
            {
                string getHashAddress;
                switch (sourceType)
                {
                case DataBaseTypes.ASN:
                {
                    getHashAddress = AsnHashAddress;
                    break;
                }

                case DataBaseTypes.CITY:
                {
                    getHashAddress = CityHashAddress;
                    break;
                }

                default:
                {
                    throw new CustomException(ResponseCodes.INTERNAL_BAD_REQUEST, ErrorMessages.WrongSourceType);
                }
                }

                var getLastHash = await FileService.GetHash(getHashAddress);

                if (string.IsNullOrEmpty(getLastHash))
                {
                    throw new CustomException(ResponseCodes.INTERNAL_BAD_REQUEST, ErrorMessages.BadExternalResponse);
                }

                using (IDbService dbService = new DbService(_db).DbServiceInstance)
                {
                    var checkStoredHash = await dbService.GeoLiteHistory.CheckHash(getLastHash);

                    if (checkStoredHash.ResultCode != ResponseCodes.SUCCESS)
                    {
                        throw new CustomException(checkStoredHash.ResultCode,
                                                  checkStoredHash.Errors.FirstOrDefault()?.ResultMessage);
                    }

                    return(new Response <CheckUpdateResponseModel>(new CheckUpdateResponseModel
                    {
                        HistoryRecordKey = checkStoredHash.Data.Key,
                        LastHashValue = checkStoredHash.Data.Md5Sum
                    }));
                }
            }
            catch (CustomException ce)
            {
                Console.WriteLine(ce.Errors.FirstOrDefault()?.ResultMessage);
                throw;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Example #7
0
        public BaseDataAccess(DataBaseTypes InDBType, bool InUsePetaPoco = true)
        {
            switch (InDBType)
            {
            case DataBaseTypes.DATA:
            {
                this.ConnectionString = BaseConfig.GetDataConnectionString;
                break;
            }

            case DataBaseTypes.DATA_TEST:
            {
                this.ConnectionString = BaseConfig.GetDataTestConnectionString;
                break;
            }

            default:
            {
                throw new NotImplementedException(string.Format("DataBase of type [{0}] was not implemented.", InDBType.ToString()));
            }
            }
            if (InUsePetaPoco)
            {
                this.PetaPocoContext = new Database(this.ConnectionString, "System.Data.SqlClient");
            }
        }
Example #8
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);
            }
        }
Example #9
0
        internal static string GetValueByType(object value, DataBaseTypes dbType)
        {
            if (value == null)
            {
                return(string.Format("String[{0}]", "null"));
            }
            var type = value.GetType();

            if (Nullable.GetUnderlyingType(type) != null)
            {
                type = Nullable.GetUnderlyingType(type);
            }

            if (type == typeof(decimal) || type == typeof(double) || type == typeof(float) || type == typeof(int) || type == typeof(long) || type == typeof(bool))
            {
                if (type == typeof(bool) && (dbType == DataBaseTypes.Mssql || dbType == DataBaseTypes.Sqllight))
                {
                    return(Convert.ToInt16(value).ToString());
                }
                return(value.ToString().ToLower());
            }
            if (type == typeof(Guid))
            {
                return(string.Format("Guid[{0}]", value));
            }
            return(string.Format("String[{0}]", value));
        }
 public Repository(DataBaseTypes dbType = DataBaseTypes.Mssql) : base(GetConnectionString(dbType), true, dbType)
 {
     if (!base.DataBaseExist())
     {
         base.CreateDataBase(); /// Create the database if it dose not exist.
     }
 }
        public async Task <Response <List <DbFileModel> > > GetDbFile(DataBaseTypes sourceType)
        {
            var response = new Response <List <DbFileModel> >();

            try
            {
                string dbAddress;
                switch (sourceType)
                {
                case DataBaseTypes.ASN:
                {
                    dbAddress = AsnArchiveAddress;
                    break;
                }

                case DataBaseTypes.CITY:
                {
                    dbAddress = CityArchiveAddress;
                    break;
                }

                default:
                {
                    throw new CustomException(ResponseCodes.INTERNAL_BAD_REQUEST, ErrorMessages.WrongSourceType);
                }
                }

                var getLastArchive = await FileService.DownloadDbFile(dbAddress);

                if (getLastArchive.Length == 0)
                {
                    response.Data = new List <DbFileModel>();
                    return(response);
                }

                var unzipArchive = await ArchiveService.GetCsvFilesFromZip(getLastArchive);

                if (unzipArchive.Count > 0)
                {
                    response.Data = unzipArchive.Select(ua => new DbFileModel
                    {
                        FileData = ua.Data,
                        FileName = ua.Name
                    }).ToList();
                }
            }
            catch (CustomException ce)
            {
                Console.WriteLine(ce.Errors.FirstOrDefault()?.ResultMessage);
                throw;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            return(response);
        }
Example #12
0
 internal static string CleanValidSqlName(this string col, DataBaseTypes dbtype)
 {
     if (dbtype == DataBaseTypes.PostgreSql)
     {
         return(col.Replace("[", "").Replace("]", ""));
     }
     return(col);
 }
Example #13
0
 public LightDataLinqToNoSql(DataBaseTypes dataBaseTypes)
 {
     DataBaseTypes = dataBaseTypes;
     _columns      = new List <string>
     {
         (_obType.GetCustomAttribute <Table>()?.Name ?? _obType.Name) + ".*"
     };
     OrderBy = _obType.GetPrimaryKey().GetPropertyName();
 }
        public CustomerDAL(DataBaseTypes type)
        {
            Console.WriteLine("CustomerDAL.CustomerDAL()");

            if (type == DataBaseTypes.SqlDatabase)
                database = new CustomSqlDataBase("connection string for sql server db");
            else if(type == DataBaseTypes.MySqlDatabase)
                database = new CustomMySqlDataBase("connection string for sql server db");
        }
Example #15
0
 public string GetName(DataBaseTypes databaseTypes)
 {
     if (databaseTypes == DataBaseTypes.Sqllight || string.IsNullOrEmpty(Schema))
     {
         return($"[{Name}]");
     }
     else
     {
         return(FullName);
     }
 }
 public LightDataLinqToNoSql(DataBaseTypes dataBaseTypes)
 {
     DataBaseTypes = dataBaseTypes;
     if (!CachedColumns.ContainsKey(_obType))
     {
         _columns = CachedColumns.GetOrAdd(_obType, _transaction.GetColumnSchema(_obType).Select(x => $"[{_obType.TableName()}].[{x.Key}]").ToList());
     }
     else
     {
         _columns = CachedColumns[_obType];
     }
 }
Example #17
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="connectionString">Full connection string</param>
        /// <param name="dataBaseTypes">The type of the database Ms-sql, Sql-light or PostgreSql
        /// Not the nuget package specific for the enum needs to be installed.
        /// Mssql for "System.Data.SqlClient"
        /// Sqllight for "System.Data.SQLite"
        /// PostgreSql for "Npgsql"
        /// </param>
        public Transaction(string connectionString, DataBaseTypes dataBaseTypes) : base()
        {
            base._transaction = this;
            _attachedObjects  = new SafeValueType <string, object>();
            if (string.IsNullOrEmpty(connectionString))
            {
                if (string.IsNullOrEmpty(connectionString))
                {
                    throw new EntityException("ConnectionString can not be empty");
                }
            }

            if (!FirstRun)
            {
                FirstRun = true;
                ConfigrationManager.OnAttributeCollectionChanged = new Action <IFastDeepClonerProperty>((property) =>
                {
                    if (property.ContainAttribute <KnownType>())
                    {
                        if (property.PropertyType != property.PropertyType.GetActualType())
                        {
                            property.PropertyType = typeof(List <>).MakeGenericType(property.GetCustomAttribute <KnownType>().ObjectType);
                        }
                        else
                        {
                            property.PropertyType = property.GetCustomAttribute <KnownType>().ObjectType;
                        }
                    }
                });
            }

            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;
            }
        }
Example #18
0
 public LightDataLinqToNoSql(DataBaseTypes dataBaseTypes)
 {
     DataBaseTypes = dataBaseTypes;
     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];
     }
     OrderBy = _obType.GetPrimaryKey().GetPropertyName();
 }
Example #19
0
        public CustomerDAL(DataBaseTypes type)
        {
            Console.WriteLine("CustomerDAL.CustomerDAL()");

            if (type == DataBaseTypes.SqlDatabase)
            {
                database = new CustomSqlDataBase("connection string for sql server db");
            }
            else if (type == DataBaseTypes.MySqlDatabase)
            {
                database = new CustomMySqlDataBase("connection string for sql server db");
            }
        }
Example #20
0
        public LinqToSql(DataBaseTypes dataBaseTypes)
        {
            DataBaseTypes = 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];
            }
        }
Example #21
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();
        }
Example #22
0
        public async Task <Response <bool> > UpdateDb(DataBaseTypes sourceType)
        {
            var vResult = new Response <bool>(false);

            try
            {
                //TODO add logic for LAST_UPDATES_ALREADY_EXISTS
                var getLastHash = await CheckForUpdates(sourceType);

                if (getLastHash.Data?.HistoryRecordKey == null)
                {
                    throw new CustomException(ResponseCodes.LAST_UPDATES_ALREADY_EXISTS,
                                              ErrorMessages.DataBaseNoNeedUpdate);
                }

                var getFileFromExternalService = await GetDbFile(sourceType);

                if (getFileFromExternalService.Data?.Count < 1)
                {
                    throw new CustomException(ResponseCodes.FILE_NOT_SAVED, ErrorMessages.FileIsCorruptErrorMessage);
                }

                var updateDb =
                    await _updateDbService.SaveFilesToDb(sourceType, getFileFromExternalService.Data, getLastHash.Data);

                if (updateDb.ResultCode != ResponseCodes.SUCCESS)
                {
                    throw new CustomException(ResponseCodes.FILE_NOT_SAVED,
                                              ErrorMessages.InsertNewRowsIntoDbErrorMessage);
                }
            }
            catch (CustomException ce)
            {
                Console.WriteLine(ce.Errors.FirstOrDefault()?.ResultMessage);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }

            return(vResult);
        }
Example #23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="connectionString">Full connection string</param>
        /// <param name="enableMigration"></param>
        /// <param name="dataBaseTypes">The type of the database Ms-sql or Sql-light</param>
        public Transaction(string connectionString, bool enableMigration, DataBaseTypes dataBaseTypes)
        {
            EnableMigration  = enableMigration;
            _attachedObjects = new Dictionary <string, object>();
            if (string.IsNullOrEmpty(connectionString))
            {
                if (string.IsNullOrEmpty(connectionString))
                {
                    throw new Exception("connectionString cant be empty");
                }
            }

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

#if DEBUG
            _tableMigrationCheck = false;
#endif

            if (!_tableMigrationCheck && EnableMigration)
            {
                lock (MigrationLocker)
                {
                    this.CreateTable <DBMigration>(false);
                    this.SaveChanges();
                    var ass = this.GetType().Assembly;
                    IMigrationConfig config;
                    if (ass.DefinedTypes.Any(a => typeof(IMigrationConfig).IsAssignableFrom(a)))
                    {
                        config = Activator.CreateInstance(ass.DefinedTypes.First(a => typeof(IMigrationConfig).IsAssignableFrom(a))) as IMigrationConfig;
                    }
                    else
                    {
                        throw new Exception("EnableMigration is enabled but EntityWorker.Core could not find IMigrationConfig in the current Assembly " + ass.GetName());
                    }
                    MigrationConfig(config);
                }
            }
            _tableMigrationCheck = true;
        }
Example #24
0
        /// <summary>
        /// Convert System Type to SqlType
        /// </summary>
        /// <param name="prop"></param>
        /// <param name="dbType"></param>
        /// <returns></returns>
        public static string GetDbTypeByType(this IFastDeepClonerProperty prop, DataBaseTypes dbType)
        {
            var type = prop.PropertyType;

            if (prop.ContainAttribute <Stringify>() ||
                prop.ContainAttribute <DataEncode>() ||
                prop.ContainAttribute <ToBase64String>() ||
                prop.ContainAttribute <JsonDocument>() ||
                prop.ContainAttribute <XmlDocument>())
            {
                return(typeof(string).GetDbTypeByType(dbType));
            }

            if (prop.ContainAttribute <ColumnType>() && prop.Attributes.Any(x => x is ColumnType && !string.IsNullOrEmpty((x as ColumnType).DataType) && ((x as ColumnType).DataBaseTypes == dbType) || !(x as ColumnType).DataBaseTypes.HasValue))
            {
                return(prop.Attributes.Where(x => x is ColumnType && !string.IsNullOrEmpty((x as ColumnType).DataType) && ((x as ColumnType).DataBaseTypes == dbType) || !(x as ColumnType).DataBaseTypes.HasValue).Select(x => (x as ColumnType).DataType).First());
            }

            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);
            }
        }
Example #25
0
 internal static string GetValidSqlName(this DataBaseTypes dbtype, string col)
 {
     return(dbtype == DataBaseTypes.PostgreSql ? col : "[" + col + "]");
 }
Example #26
0
 public ManterArquivoTipoEnvio(string connectionString, DataBaseTypes dataBaseType)
 {
     oDao = new Dao(connectionString, dataBaseType);
 }
Example #27
0
        internal static ILightDataTable ReadData(this ILightDataTable data, DataBaseTypes dbType, IDataReader reader, DbCommandExtended command, string primaryKey = null, bool closeReader = true)
        {
            var i = 0;

            if (reader.FieldCount <= 0)
            {
                return(data);
            }
            data.TablePrimaryKey = primaryKey;

            if (reader.FieldCount <= 0)
            {
                if (closeReader)
                {
                    reader.Close();
                    reader.Dispose();
                }
                return(data);
            }
            if (command.TableType == null)
            {
                try
                {
                    var key = command?.TableType != null ? command.TableType.FullName : command.Command.CommandText;
                    if (!CachedSqlException.ContainsKey(command.Command.CommandText))
                    {
                        if (!CachedGetSchemaTable.ContainsKey(key))
                        {
                            CachedGetSchemaTable.Add(key, new LightDataTable(reader.GetSchemaTable()));
                        }

                        foreach (var item in CachedGetSchemaTable[key].Rows)
                        {
                            var columnName = item.Value <string>("ColumnName");
                            data.TablePrimaryKey = data.TablePrimaryKey == null && item.Columns.ContainsKey("IsKey") && item.TryValueAndConvert <bool>("IsKey", false) ? columnName : data.TablePrimaryKey;
                            var dataType = TypeByTypeAndDbIsNull(item["DataType"] as Type,
                                                                 item.TryValueAndConvert <bool>("AllowDBNull", true));
                            if (data.Columns.ContainsKey(columnName))
                            {
                                columnName = columnName + i;
                            }
                            data.AddColumn(columnName, dataType);

                            i++;
                        }
                    }
                    else
                    {
                        for (var col = 0; col < reader.FieldCount; col++)
                        {
                            var columnName = reader.GetName(col);
                            var dataType   = TypeByTypeAndDbIsNull(reader.GetFieldType(col) as Type, true);
                            if (data.Columns.ContainsKey(columnName))
                            {
                                columnName = columnName + i;
                            }
                            data.AddColumn(columnName, dataType);
                            i++;
                        }
                    }
                }
                catch (Exception e)
                {
                    if (!string.IsNullOrEmpty(command.Command.CommandText))
                    {
                        CachedSqlException.Add(command.Command.CommandText, e);
                    }
                    return(ReadData(data, dbType, reader, command, primaryKey));
                }
            }
            else
            {
                foreach (var c in command.DataStructure.Columns.Values)
                {
                    data.AddColumn(c.ColumnName, c.DataType, c.DefaultValue);
                }
            }

            while (reader.Read())
            {
                var row = data.NewRow();
                reader.GetValues(row._itemArray);
                data.AddRow(row);
            }

            if (closeReader)
            {
                reader.Close();
                reader.Dispose();
            }

            return(data);
        }
Example #28
0
 public ManterTaxa(string connectionString, DataBaseTypes dataBaseType)
 {
     oDao = new Dao(connectionString, dataBaseType);
 }
Example #29
0
 public ManterTipoEntidade(string connectionString, DataBaseTypes dataBaseType)
 {
     oDao = new Dao(connectionString, dataBaseType);
 }
 // Get the full connection string from the web-config
 public static string GetConnectionString(DataBaseTypes dbType)
 {
     return(dbType == DataBaseTypes.Mssql ? @"Server=.\SQLEXPRESS; Database=CMStest; User Id=root; Password=root;" :
            (dbType == DataBaseTypes.Sqllight ? @"Data Source=D:\Projects\LightData.CMS\source\LightData.CMS\App_Data\LightDataTabletest.db" :
             "Host=localhost;Username=postgres;Password=root;Database=mydatabase"));
 }
 public Repository(DataBaseTypes dbType = DataBaseTypes.Mssql) : base(GetConnectionString(dbType), dbType)
 {
 }