public SchemaCollection<StoredProcedureModel> Extract(
            DatabaseConfiguration configuration,
            StoredProcedureCollection procedures)
        {
            Dictionary<string, StoredProcedure> storedProcedureLookup = CreateLookup(procedures);

            using (var connection = new SqlConnection(_connectionStringProvider.ConnectionString))
            {
                connection.Open();

                var collection = new SchemaCollection<StoredProcedureModel>(
                    _schemaElementCollectionBuilder,
                    configuration.StoredProcedures.Namespace);

                foreach (var element in configuration.StoredProcedures.Elements)
                {
                    string escapedFullName = _nameConverter.EscapeDatabaseName(element.SchemaName, element.Name);
                    if (storedProcedureLookup.ContainsKey(escapedFullName))
                    {
                        StoredProcedure procedure = storedProcedureLookup[escapedFullName];
                        StoredProcedureModel model = ToModel(connection, configuration, procedure);
                        collection.AddElement(procedure.Schema, model);
                    }
                    else
                    {
                        throw new ArgumentException(string.Format("Unable to locate stored procedure '{0}'", escapedFullName));
                    }
                }

                return collection;
            }
        }
Beispiel #2
0
        public static void StartDatabase()
        {
            if (Utilities.ConfigurationManager.GetStringValue("SQLUsername") == "root")
            {
                Utilities.ConsoleStyle.Warning(@"'root' Username is not safe, please modify this for your security");
            }
            var config = new DatabaseConfiguration(DatabaseType.MySQL, Utilities.ConfigurationManager.GetStringValue("SQLHost"),
                                                    Utilities.ConfigurationManager.GetStringValue("SQLDB"),
                                                    Utilities.ConfigurationManager.GetStringValue("SQLUsername"), Utilities.ConfigurationManager.GetStringValue("SQLPassword"));

            var source = new InPlaceConfigurationSource();
            source.Add(typeof(ActiveRecordBase), config.GetProperties());

            ActiveRecordStarter.Initialize(source,
                            typeof(CharacterRecord), typeof(MapRecords),
                            typeof(TriggerRecord), typeof(ItemRecord), typeof(WorldItemRecord),
                            typeof(NpcRecord), typeof(NpcPositionRecord), typeof(NpcDialogRecord),
                            typeof(ZaapRecord), typeof(AccountDataRecord), typeof(OriginalBreedStartMapRecord),
                            typeof(IncarnamTeleportRecord), typeof(ExpFloorRecord), typeof(BaseSpellRecord),
                            typeof(MonstersTemplateRecord), typeof(MonsterLevelRecord), typeof(MountTemplateRecord),
                            typeof(GuildCreatorLocationRecord), typeof(SpellRecord), typeof(ShopItemRecord),
                            typeof(BreedRecord), typeof(GuildRecord), typeof(DungeonRoomRecord),
                            typeof(WorldMountRecord), typeof(PaddockRecord), typeof(DropRecord),
                            typeof(BannedAccountRecord), typeof(ElitesRecord), typeof(LiveActionRecord),
                            typeof(HotelRecord), typeof(ServerInfoRecord), typeof(ItemSetRecord),
                            typeof(IODataRecord), typeof(JobDataRecord), typeof(CraftRecord), typeof(ItemBagRecord),
                            typeof(AuctionHouseRecord), typeof(AuctionHouseItemRecord));
        }
        public void InsertMusicSheet(MusicSheet sheet)
        {
            var config = new DatabaseConfiguration("mongodb://*****:*****@staff.mongohq.com:10013/") { DatabaseName = "MusicCatalog" };

            var databaseAccess = new DatabaseAccess(config);

            databaseAccess.SaveOne(sheet);
        }
        public MusicSheet GetMusicSheetByFriendlyId(string friendlyId)
        {
            var config = new DatabaseConfiguration("mongodb://*****:*****@staff.mongohq.com:10013/") { DatabaseName = "MusicCatalog" };

            var databaseAccess = new DatabaseAccess(config);

            var sheet = databaseAccess.GetSingle<MusicSheet>(friendlyId);

            return sheet;
        }
Beispiel #5
0
 public static void StartDatabase()
 {
     var config = new DatabaseConfiguration(DatabaseType.MySQL, Utilities.ConfigurationManager.GetStringValue("SQLHost"),
                                             Utilities.ConfigurationManager.GetStringValue("SQLDB"),
                                             Utilities.ConfigurationManager.GetStringValue("SQLUsername"), Utilities.ConfigurationManager.GetStringValue("SQLPassword"));
     var source = new InPlaceConfigurationSource();
     source.Add(typeof(ActiveRecordBase), config.GetProperties());
     ActiveRecordStarter.Initialize(source, typeof(AccountRecord), typeof(GameServerRecord),
         typeof(AccountCharactersInformationsRecord));
 }
        public RepositoryFactory(DatabaseConfiguration databaseConfiguration, string dataDirectory)
        {
            var connectionStringBuilder = new MySqlConnectionStringBuilder();
            connectionStringBuilder.UserID = databaseConfiguration.Username;
            connectionStringBuilder.Password = databaseConfiguration.Password;
            connectionStringBuilder.Server = databaseConfiguration.Server;
            connectionStringBuilder.Database = databaseConfiguration.Database;
            connectionStringBuilder.Port = databaseConfiguration.Port;

            _connectionString = connectionStringBuilder.ToString();

            _dataDirectory = dataDirectory;
        }
Beispiel #7
0
        public MicroCore(DatabaseConfiguration dbConf, AssemblyManager assemblyLoader,
            MicroCoreEventDispatcher dispatcher, MicroBoot microBoot, I18NService i18nService,
            FileUpdate fileUpdate)
        {
            this.microBoot = microBoot;
            this.dbConf = dbConf;
            this.assemblyLoader = assemblyLoader;
            this.dispatcher = dispatcher;
            this.i18nService = i18nService;
            this.fileUpdate = fileUpdate;

            i18nService.ConfigureThreadI18n(System.Threading.Thread.CurrentThread);
            microBoot.coreShutdownEvent = new ManualResetEvent(false);
        }
 public ProjectManagerDbHelper(ApplicationManager app)
     : base(app)
 {
     Db = DatabaseConfiguration.Build().UsingConnectionString(Parameters.Parameters.ProjectManagerDbConnectionString)
          .UsingProvider(new PostgreSQLDatabaseProvider()).Create();
 }
Beispiel #9
0
 internal Database(uint dbi, IntPtr env, string name, Action <Database> disposed, DatabaseConfiguration config)
 {
     this.dbi      = dbi;
     this.env      = env;
     this.Name     = name;
     this.disposed = disposed;
     this.Config   = config;
 }
        public void TransactionShouldSupportCustomComparer()
        {
            Func<int, int, int> comparison = (l, r) => l.CompareTo(r);
            var options = new DatabaseConfiguration {Flags = DatabaseOpenFlags.Create};
            Func<byte[], byte[], int> compareWith =
                (l, r) => comparison(BitConverter.ToInt32(l, 0), BitConverter.ToInt32(r, 0));
            options.CompareWith(Comparer<byte[]>.Create(new Comparison<byte[]>(compareWith)));

            using (var txnT = _env.BeginTransaction())
            using (var db1 = txnT.OpenDatabase(configuration: options))
            {
                txnT.DropDatabase(db1);
                txnT.Commit();
            }

            var txn = _env.BeginTransaction();
            var db = txn.OpenDatabase(configuration: options);

            var keysUnsorted = Enumerable.Range(1, 10000).OrderBy(x => Guid.NewGuid()).ToList();
            var keysSorted = keysUnsorted.ToArray();
            Array.Sort(keysSorted, new Comparison<int>(comparison));

            GC.Collect();
            for (var i = 0; i < keysUnsorted.Count; i++)
                txn.Put(db, BitConverter.GetBytes(keysUnsorted[i]), BitConverter.GetBytes(i));

            using (var c = txn.CreateCursor(db))
            {
                int order = 0;
                while (c.MoveNext())
                    Assert.Equal(keysSorted[order++], BitConverter.ToInt32(c.Current.Key, 0));
            }
        }
Beispiel #11
0
 public EatingDayRepository(DatabaseConfiguration configuration) : base(configuration)
 {
 }
 public GlobalConfiguration(CommunicationConfiguration communicationConfiguration, DatabaseConfiguration databaseConfiguration, RouteConfiguration routeConfiguration)
 {
     CommunicationConfiguration = communicationConfiguration;
     DatabaseConfiguration      = databaseConfiguration;
     RouteConfiguration         = routeConfiguration;
 }
 public DatabaseConfigurationProvider(IOptions <DatabaseConfiguration> config)
 {
     _databaseConfiguration = config.Value;
 }
Beispiel #14
0
 public FileProcessed()
 {
     configuration = new DatabaseConfiguration();
     mapper        = new Mapper();
 }
        public void TransactionShouldSupportCustomComparer()
        {
            Func<int, int, int> comparison = (l, r) => -Math.Sign(l - r);

            var txn = _env.BeginTransaction();
            var options = new DatabaseConfiguration {Flags = DatabaseOpenFlags.Create};
            Func<byte[], byte[], int> compareWith = (l, r) => comparison(BitConverter.ToInt32(l, 0), BitConverter.ToInt32(r, 0));
            options.CompareWith(Comparer<byte[]>.Create(new Comparison<byte[]>(compareWith)));
            var db = txn.OpenDatabase(configuration: options);

            var keysUnsorted = new [] { 2, 10, 5 };
            var keysSorted = keysUnsorted.ToArray();
            Array.Sort(keysSorted, new Comparison<int>(comparison));

            for (var i = 0; i < keysUnsorted.Length; i++)
                txn.Put(db, BitConverter.GetBytes(keysUnsorted[i]), BitConverter.GetBytes(i));

            using (var c = txn.CreateCursor(db))
            {
                int order = 0;
                while (c.MoveNext())
                    Assert.Equal(keysSorted[order++], BitConverter.ToInt32(c.Current.Key, 0));
            }
        }
 /// <summary>
 /// Construct a <see cref="DatabaseContext{TParentContext}"/>
 /// </summary>
 /// <param name="dbContextOptions">The <see cref="DbContextOptions{TParentContext}"/> for the <see cref="DatabaseContext{TParentContext}"/></param>
 /// <param name="databaseConfigurationOptions">The <see cref="IOptions{TOptions}"/> containing the value of <see cref="DatabaseConfiguration"/></param>
 /// <param name="databaseSeeder">The value of <see cref="databaseSeeder"/></param>
 /// <param name="logger">The value of <see cref="Logger"/></param>
 public DatabaseContext(DbContextOptions <TParentContext> dbContextOptions, IOptions <DatabaseConfiguration> databaseConfigurationOptions, IDatabaseSeeder databaseSeeder, ILogger logger) : base(dbContextOptions)
 {
     DatabaseConfiguration = databaseConfigurationOptions?.Value ?? throw new ArgumentNullException(nameof(databaseConfigurationOptions));
     this.databaseSeeder   = databaseSeeder ?? throw new ArgumentNullException(nameof(databaseSeeder));
     Logger = logger ?? throw new ArgumentNullException(nameof(logger));
 }
 public Startup(IConfiguration configuration)
 {
     Configuration    = configuration;
     JwtConfiguration = new JwtConfiguration();
     DbConfiguration  = new DatabaseConfiguration();
 }
Beispiel #18
0
 public UserCredential()
 {
     configuration = new DatabaseConfiguration();
     mapper        = new Mapper();
 }
        /// <summary>
        /// Prompts the user to create a <see cref="DatabaseConfiguration"/>
        /// </summary>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the operation</param>
        /// <returns>A <see cref="Task{TResult}"/> resulting in the new <see cref="DatabaseConfiguration"/></returns>
                #pragma warning disable CA1502 // TODO: Decomplexify
        async Task <DatabaseConfiguration> ConfigureDatabase(CancellationToken cancellationToken)
        {
            bool firstTime = true;

            do
            {
                await console.WriteAsync(null, true, cancellationToken).ConfigureAwait(false);

                var databaseConfiguration = new DatabaseConfiguration
                {
                    DatabaseType = await PromptDatabaseType(firstTime, cancellationToken).ConfigureAwait(false)
                };
                firstTime = false;

                string serverAddress = null;
                ushort?serverPort    = null;

                bool isSqliteDB = databaseConfiguration.DatabaseType == DatabaseType.Sqlite;
                if (!isSqliteDB)
                {
                    do
                    {
                        await console.WriteAsync(null, true, cancellationToken).ConfigureAwait(false);

                        await console.WriteAsync("Enter the server's address and port [<server>:<port> or <server>] (blank for local): ", false, cancellationToken).ConfigureAwait(false);

                        serverAddress = await console.ReadLineAsync(false, cancellationToken).ConfigureAwait(false);

                        if (String.IsNullOrWhiteSpace(serverAddress))
                        {
                            serverAddress = null;
                        }
                        else if (databaseConfiguration.DatabaseType == DatabaseType.SqlServer)
                        {
                            var match = Regex.Match(serverAddress, @"^(?<server>.+):(?<port>.+)$");
                            if (match.Success)
                            {
                                serverAddress = match.Groups["server"].Value;
                                var portString = match.Groups["port"].Value;
                                if (UInt16.TryParse(portString, out var port))
                                {
                                    serverPort = port;
                                }
                                else
                                {
                                    await console.WriteAsync($"Failed to parse port \"{portString}\", please try again.", true, cancellationToken).ConfigureAwait(false);

                                    continue;
                                }
                            }
                        }

                        break;
                    }while (true);
                }

                await console.WriteAsync(null, true, cancellationToken).ConfigureAwait(false);

                await console.WriteAsync($"Enter the database {(isSqliteDB ? "file path" : "name")} (Can be from previous installation. Otherwise, should not exist): ", false, cancellationToken).ConfigureAwait(false);

                string databaseName;
                bool   dbExists = false;
                do
                {
                    databaseName = await console.ReadLineAsync(false, cancellationToken).ConfigureAwait(false);

                    if (!String.IsNullOrWhiteSpace(databaseName))
                    {
                        if (isSqliteDB)
                        {
                            dbExists = await ioManager.FileExists(databaseName, cancellationToken).ConfigureAwait(false);

                            if (!dbExists)
                            {
                                databaseName = await ValidateNonExistantSqliteDBName(databaseName, cancellationToken).ConfigureAwait(false);
                            }
                        }
                        else
                        {
                            dbExists = await PromptYesNo("Does this database already exist? If not, we will attempt to CREATE it. (y/n): ", cancellationToken).ConfigureAwait(false);
                        }
                    }

                    if (String.IsNullOrWhiteSpace(databaseName))
                    {
                        await console.WriteAsync("Invalid database name!", true, cancellationToken).ConfigureAwait(false);
                    }
                    else
                    {
                        break;
                    }
                }while (true);

                bool useWinAuth;
                if (databaseConfiguration.DatabaseType == DatabaseType.SqlServer && platformIdentifier.IsWindows)
                {
                    useWinAuth = await PromptYesNo("Use Windows Authentication? (y/n): ", cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    useWinAuth = false;
                }

                await console.WriteAsync(null, true, cancellationToken).ConfigureAwait(false);

                string username = null;
                string password = null;
                if (!isSqliteDB)
                {
                    if (!useWinAuth)
                    {
                        await console.WriteAsync("Enter username: "******"Enter password: "******"IMPORTANT: If using the service runner, ensure this computer's LocalSystem account has CREATE DATABASE permissions on the target server!", true, cancellationToken).ConfigureAwait(false);

                        await console.WriteAsync("The account it uses in MSSQL is usually \"NT AUTHORITY\\SYSTEM\" and the role it needs is usually \"dbcreator\".", true, cancellationToken).ConfigureAwait(false);

                        await console.WriteAsync("We'll run a sanity test here, but it won't be indicative of the service's permissions if that is the case", true, cancellationToken).ConfigureAwait(false);
                    }
                }

                await console.WriteAsync(null, true, cancellationToken).ConfigureAwait(false);

                DbConnection testConnection;
                void CreateTestConnection(string connectionString) =>
                testConnection = dbConnectionFactory.CreateConnection(
                    connectionString,
                    databaseConfiguration.DatabaseType);

                switch (databaseConfiguration.DatabaseType)
                {
                case DatabaseType.SqlServer:
                {
                    var csb = new SqlConnectionStringBuilder
                    {
                        ApplicationName = assemblyInformationProvider.VersionPrefix,
                        DataSource      = serverAddress ?? "(local)"
                    };

                    if (useWinAuth)
                    {
                        csb.IntegratedSecurity = true;
                    }
                    else
                    {
                        csb.UserID   = username;
                        csb.Password = password;
                    }

                    CreateTestConnection(csb.ConnectionString);
                    csb.InitialCatalog = databaseName;
                    databaseConfiguration.ConnectionString = csb.ConnectionString;
                }

                break;

                case DatabaseType.MariaDB:
                case DatabaseType.MySql:
                {
                    // MySQL/MariaDB
                    var csb = new MySqlConnectionStringBuilder
                    {
                        Server   = serverAddress ?? "127.0.0.1",
                        UserID   = username,
                        Password = password
                    };

                    if (serverPort.HasValue)
                    {
                        csb.Port = serverPort.Value;
                    }

                    CreateTestConnection(csb.ConnectionString);
                    csb.Database = databaseName;
                    databaseConfiguration.ConnectionString = csb.ConnectionString;
                }

                break;

                case DatabaseType.Sqlite:
                {
                    var csb = new SqliteConnectionStringBuilder
                    {
                        DataSource = databaseName,
                        Mode       = dbExists ? SqliteOpenMode.ReadOnly : SqliteOpenMode.ReadWriteCreate
                    };

                    CreateTestConnection(csb.ConnectionString);
                    databaseConfiguration.ConnectionString = csb.ConnectionString;
                }

                break;

                case DatabaseType.PostgresSql:
                {
                    var csb = new NpgsqlConnectionStringBuilder
                    {
                        ApplicationName = assemblyInformationProvider.VersionPrefix,
                        Host            = serverAddress ?? "127.0.0.1",
                        Password        = password,
                        Username        = username
                    };

                    if (serverPort.HasValue)
                    {
                        csb.Port = serverPort.Value;
                    }

                    CreateTestConnection(csb.ConnectionString);
                    csb.Database = databaseName;
                    databaseConfiguration.ConnectionString = csb.ConnectionString;
                }

                break;

                default:
                    throw new InvalidOperationException("Invalid DatabaseType!");
                }

                try
                {
                    await TestDatabaseConnection(testConnection, databaseConfiguration, databaseName, dbExists, cancellationToken).ConfigureAwait(false);

                    return(databaseConfiguration);
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch (Exception e)
                {
                    await console.WriteAsync(e.Message, true, cancellationToken).ConfigureAwait(false);

                    await console.WriteAsync(null, true, cancellationToken).ConfigureAwait(false);

                    await console.WriteAsync("Retrying database configuration...", true, cancellationToken).ConfigureAwait(false);
                }
            }while (true);
        }
        /// <summary>
        /// Ensure a given <paramref name="testConnection"/> works.
        /// </summary>
        /// <param name="testConnection">The test <see cref="DbConnection"/>.</param>
        /// <param name="databaseConfiguration">The <see cref="DatabaseConfiguration"/> may have derived data populated.</param>
        /// <param name="databaseName">The database name (or path in the case of a <see cref="DatabaseType.Sqlite"/> database).</param>
        /// <param name="dbExists">Whether or not the database exists.</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the operation.</param>
        /// <returns>A <see cref="Task"/> representing the running operation.</returns>
        async Task TestDatabaseConnection(
            DbConnection testConnection,
            DatabaseConfiguration databaseConfiguration,
            string databaseName,
            bool dbExists,
            CancellationToken cancellationToken)
        {
            bool isSqliteDB = databaseConfiguration.DatabaseType == DatabaseType.Sqlite;

            using (testConnection)
            {
                await console.WriteAsync("Testing connection...", true, cancellationToken).ConfigureAwait(false);

                await testConnection.OpenAsync(cancellationToken).ConfigureAwait(false);

                await console.WriteAsync("Connection successful!", true, cancellationToken).ConfigureAwait(false);

                if (databaseConfiguration.DatabaseType == DatabaseType.MariaDB ||
                    databaseConfiguration.DatabaseType == DatabaseType.MySql)
                {
                    await console.WriteAsync("Checking MySQL/MariaDB version...", true, cancellationToken).ConfigureAwait(false);

                    using var command   = testConnection.CreateCommand();
                    command.CommandText = "SELECT VERSION()";
                    var fullVersion = (string)await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false);

                    await console.WriteAsync(String.Format(CultureInfo.InvariantCulture, "Found {0}", fullVersion), true, cancellationToken).ConfigureAwait(false);

                    var splits = fullVersion.Split('-');
                    databaseConfiguration.MySqlServerVersion = splits.First();
                }

                if (!isSqliteDB && !dbExists)
                {
                    await console.WriteAsync("Testing create DB permission...", true, cancellationToken).ConfigureAwait(false);

                    using (var command = testConnection.CreateCommand())
                    {
                        // I really don't care about user sanitization here, they want to f**k their own DB? so be it
#pragma warning disable CA2100 // Review SQL queries for security vulnerabilities
                        command.CommandText = $"CREATE DATABASE {databaseName}";
#pragma warning restore CA2100 // Review SQL queries for security vulnerabilities
                        await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
                    }

                    await console.WriteAsync("Success!", true, cancellationToken).ConfigureAwait(false);

                    await console.WriteAsync("Dropping test database...", true, cancellationToken).ConfigureAwait(false);

                    using (var command = testConnection.CreateCommand())
                    {
#pragma warning disable CA2100 // Review SQL queries for security vulnerabilities
                        command.CommandText = $"DROP DATABASE {databaseName}";
#pragma warning restore CA2100 // Review SQL queries for security vulnerabilities
                        try
                        {
                            await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
                        }
                        catch (OperationCanceledException)
                        {
                            throw;
                        }
                        catch (Exception e)
                        {
                            await console.WriteAsync(e.Message, true, cancellationToken).ConfigureAwait(false);

                            await console.WriteAsync(null, true, cancellationToken).ConfigureAwait(false);

                            await console.WriteAsync("This should be okay, but you may want to manually drop the database before continuing!", true, cancellationToken).ConfigureAwait(false);

                            await console.WriteAsync("Press any key to continue...", true, cancellationToken).ConfigureAwait(false);

                            await console.PressAnyKeyAsync(cancellationToken).ConfigureAwait(false);
                        }
                    }
                }
            }

            if (isSqliteDB && !dbExists)
            {
                await Task.WhenAll(
                    console.WriteAsync("Deleting test database file...", true, cancellationToken),
                    ioManager.DeleteFile(databaseName, cancellationToken)).ConfigureAwait(false);
            }
        }
        public void PopulateDatabaseConfiguration(Dictionary <string, object> configValues,
                                                  out ICloneable configuration)
        {
            DatabaseConfiguration dbConf         = new DatabaseConfiguration();
            string databaseName                  = "";
            DatabaseConfiguration remoteDatabase = null;
            string errorMessage                  = null;

            if (_objType == DataDefinitionType.Alter)
            {
                if (configValues.ContainsKey(ConfigType.Name.ToString()))
                {
                    databaseName = configValues[ConfigType.Name.ToString()] as string;
                }

                #region Get Database Configuration from Configuraiton Server

                ClusterConfiguration clusterConfig = _session.GetDatabaseClusterConfiguration(_cluster);
                if (clusterConfig != null)
                {
                    if (clusterConfig.Databases != null)
                    {
                        if (clusterConfig.Databases.ContainsDatabase(databaseName))
                        {
                            remoteDatabase = clusterConfig.Databases.GetDatabase(databaseName);
                        }
                        else
                        {
                            errorMessage = string.Format("Specified database {0} does not exist.", databaseName);
                        }
                    }
                    else
                    {
                        errorMessage = string.Format("Specified database {0} does not exist.", databaseName);
                    }
                }
                else
                {
                    errorMessage = string.Format("No configuraiton exist for cluster {0}", _cluster);
                }

                if (remoteDatabase == null)
                {
                    throw new DatabaseException(ErrorCodes.Query.INVALID_DDL_CONFIGURATION, new string[] { errorMessage });
                }

                #endregion

                errorMessage = null;


                if (configValues.ContainsKey(ConfigType.MultiFile.ToString()) && errorMessage == null)
                {
                    long maxFileSize = GetInt64(ConfigType.MaxFileSize.ToString(), configValues[ConfigType.MaxFileSize.ToString()]);
                    if (maxFileSize * MB > long.MaxValue || maxFileSize * MB < long.MinValue)
                    {
                        throw new DatabaseException(ErrorCodes.Query.INVALID_DDL_CONFIGURATION, new string[] { "Value must be within the range of Int64 for attribute MaxFileSize." });
                    }

                    if (remoteDatabase.Storage.StorageProvider.MaxFileSize != MB * maxFileSize)
                    {
                        ;
                    }

                    errorMessage = "MultiFile";
                }

                if (configValues.ContainsKey(ConfigType.MaxFileSize.ToString()) && errorMessage == null)
                {
                    if (remoteDatabase.Storage.StorageProvider.MaxFileSize != MB *
                        GetInt64(ConfigType.MaxFileSize.ToString(), configValues[ConfigType.MaxFileSize.ToString()]))
                    {
                        errorMessage = "MaxFileSize";
                    }
                }

                if (configValues.ContainsKey(ConfigType.MaxCollections.ToString()) && errorMessage == null && remoteDatabase.Storage.StorageProvider.LMDBProvider != null)
                {
                    if (remoteDatabase.Storage.StorageProvider.LMDBProvider.MaxCollections !=
                        GetInt32(ConfigType.MaxCollections.ToString(), configValues[ConfigType.MaxCollections.ToString()]))
                    {
                        errorMessage = "MaxCollections";
                    }
                }

                if (configValues.ContainsKey(ConfigType.InitialSize.ToString()) && errorMessage == null && remoteDatabase.Storage.StorageProvider.LMDBProvider != null)
                {
                    long initialSize = GetInt64(ConfigType.InitialSize.ToString(), configValues[ConfigType.InitialSize.ToString()]);
                    if (initialSize * MB > long.MaxValue || initialSize * MB < long.MinValue)
                    {
                        throw new DatabaseException(ErrorCodes.Query.INVALID_DDL_CONFIGURATION, new string[] { "Value must be within the range of Int64 for attribute InitialSize." });
                    }
                }

                if (configValues.ContainsKey(ConfigType.CacheSize.ToString()) && errorMessage == null)
                {
                    long cacheSize = GetInt64(ConfigType.CacheSize.ToString(), configValues[ConfigType.CacheSize.ToString()]);
                    if (cacheSize * MB > long.MaxValue || cacheSize * MB < long.MinValue)
                    {
                        throw new DatabaseException(ErrorCodes.Query.INVALID_DDL_CONFIGURATION, new string[] { "Value must be within the range of Int64 for attribute CacheSize." });
                    }

                    if (remoteDatabase.Storage.CacheConfiguration.CacheSpace != MB * cacheSize)
                    {
                        errorMessage = "CacheSize";
                    }
                }

                if (errorMessage != null)
                {
                    throw new DatabaseException(ErrorCodes.Query.INVALID_DDL_CONFIGURATION, new string[] { "Configuration attribute " + errorMessage + " is not Modifiable." });
                }

                dbConf = remoteDatabase;
            }
            else
            {
                if (configValues.ContainsKey(ConfigType.Name.ToString()))
                {
                    dbConf.Name = configValues[ConfigType.Name.ToString()] as string;
                }

                dbConf.Storage = new StorageConfiguration
                {
                    Collections     = new CollectionConfigurations(),
                    StorageProvider = new StorageProviderConfiguration()
                };


                dbConf.Storage.StorageProvider.LMDBProvider        = new LMDBConfiguration();
                dbConf.Storage.StorageProvider.StorageProviderType = ProviderType.LMDB;


                if (configValues.ContainsKey(ConfigType.MultiFile.ToString()) && (!(bool)configValues[ConfigType.MultiFile.ToString()]))
                {
                    dbConf.Storage.StorageProvider.IsMultiFileStore = false;
                }
                else
                {
                    dbConf.Storage.StorageProvider.IsMultiFileStore = true;
                }

                if (configValues.ContainsKey(ConfigType.MaxFileSize.ToString()))
                {
                    long maxFileSize = GetInt64(ConfigType.MaxFileSize.ToString(), configValues[ConfigType.MaxFileSize.ToString()]);
                    if (maxFileSize * MB > long.MaxValue || maxFileSize * MB < long.MinValue)
                    {
                        throw new DatabaseException(ErrorCodes.Query.INVALID_DDL_CONFIGURATION, new string[] { "Value must be within the range of Int64 for attribute MaxFileSize." });
                    }

                    dbConf.Storage.StorageProvider.MaxFileSize = MB * maxFileSize;
                }
                else
                {
                    //50 Gb...
                    dbConf.Storage.StorageProvider.MaxFileSize = MB * 1024 * 50;
                }


                if (configValues.ContainsKey(ConfigType.MaxCollections.ToString()) && dbConf.Storage.StorageProvider.LMDBProvider != null)
                {
                    dbConf.Storage.StorageProvider.LMDBProvider.MaxCollections =
                        GetInt32(ConfigType.MaxCollections.ToString(), configValues[ConfigType.MaxCollections.ToString()]);
                }
                else if (dbConf.Storage.StorageProvider.LMDBProvider != null)
                {
                    dbConf.Storage.StorageProvider.LMDBProvider.MaxCollections = 1000;
                }


                dbConf.Storage.CacheConfiguration             = new CachingConfiguration();
                dbConf.Storage.CacheConfiguration.CachePolicy = "FCFS";

                if (configValues.ContainsKey(ConfigType.CacheSize.ToString()))
                {
                    long cacheSize = GetInt64(ConfigType.CacheSize.ToString(), configValues[ConfigType.CacheSize.ToString()]);
                    if (cacheSize * MB > long.MaxValue || cacheSize * MB < long.MinValue)
                    {
                        throw new DatabaseException(ErrorCodes.Query.INVALID_DDL_CONFIGURATION, new string[] { "Value must be within the range of Int64 for attribute CacheSize." });
                    }

                    dbConf.Storage.CacheConfiguration.CacheSpace = MB * cacheSize;
                }
            }
            configuration = dbConf;
        }
Beispiel #22
0
 protected bool Equals(DatabaseConfiguration other)
 {
     return(string.Equals(DatabasePath, other.DatabasePath));
 }
 private void WhenReadingFileThatExists()
 {
     _configuration = ConfigurationReader.Read("file");
 }
Beispiel #24
0
        /// <summary>
        ///     Configure et référence l'ORM.
        /// </summary>
        /// <param name="services">Liste des services.</param>
        /// <param name="configuration">Configuration.</param>
        /// <returns>Liste des services.</returns>
        internal static IServiceCollection AddORM(this IServiceCollection services, IConfiguration configuration)
        {
            return(services
                   .AddSingleton((provider) =>
            {
                // Récupération des options
                DatabaseConfiguration options = provider
                                                .GetService <IOptions <ApplicationConfiguration> >()
                                                .Value
                                                .Database;

                // Extraction des types
                var types = Assembly
                            .GetExecutingAssembly()
                            .GetExportedTypes();

                // Création du mappage
                var mapper = new ModelMapper();
                mapper.AddMappings(types);
                var hbm = mapper.CompileMappingForAllExplicitlyAddedEntities();

                // Création de la fabrique
                var pre = new Configuration();
                pre.DataBaseIntegration(
                    db =>
                {
                    // Informations initiales
                    db.ConnectionString = options.ConnectionString;
                    db.BatchSize = options.BatchSize;
                    db.Dialect <MsSql2012Dialect>();

                    // Gestion du schéma
                    switch (options.Action)
                    {
                    case "Create":
                        db.SchemaAction = SchemaAutoAction.Create;
                        break;

                    case "Recreate":
                        db.SchemaAction = SchemaAutoAction.Recreate;
                        break;

                    case "Update":
                        db.SchemaAction = SchemaAutoAction.Update;
                        break;

                    case "Validate":
                        db.SchemaAction = SchemaAutoAction.Validate;
                        break;

                    default:
                        throw new InternalException("Invalid database action '{0}'", options.Action);
                    }
                })
                .SetNamingStrategy(new NamingStrategy())
                .AddMapping(hbm);

                return pre.BuildSessionFactory();
            })
                   .AddScoped((provider) =>
            {
                return provider.GetService <ISessionFactory>().OpenSession();
            })
                   .AddScoped((provider) =>
            {
                return provider.GetService <ISessionFactory>().OpenStatelessSession();
            })
                   .AddScoped <IDbConnection>((provider) =>
            {
                return provider.GetService <IStatelessSession>().Connection;
            })
                   .AddScoped((provider) => new FieldDAO(provider.GetService <ISession>()))
                   .AddScoped((provider) => new TableDAO(provider.GetService <ISession>()))
                   .AddScoped((provider) => new UserDAO(provider.GetService <ISession>()))
                   .AddScoped((provider) => new ViewDAO(provider.GetService <ISession>())));
        }
Beispiel #25
0
        private static void DoTestImpl(LightningEnvironment env, bool useRandomKeys = false)
        {
            var numItemsToWrite = 1 * 1000; // One thousand
            //var numItemsToWrite = 10 * 1000; // Ten thousand
            //var numItemsToWrite = 100 * 1000; // One hundred thousand
            //var numItemsToWrite = 1 * 1000 * 1000; // 1 million
            //var numItemsToWrite = 10 * 1000 * 1000; // 10 million
            var randon = new Random(1773);
            Console.WriteLine("Using {0} keys", useRandomKeys ? "RANDOM" : "SEQUENTIAL");

            var writeTimer = Stopwatch.StartNew();
            // Need to specify DatabaseOpenFlags.IntegerKey if we want the items to be sorted, not entirely sure why though,
            // probably big/little endian related, see http://www.openldap.org/lists/openldap-bugs/201308/msg00050.html
            var dbConfig = new DatabaseConfiguration { Flags = DatabaseOpenFlags.Create | DatabaseOpenFlags.IntegerKey };
            using (var tx = env.BeginTransaction())
            using (var db = tx.OpenDatabase("test", dbConfig))
            {
                for (var i = 0; i < numItemsToWrite; ++i)
                {
                    var key = i;
                    if (useRandomKeys)
                        key = randon.Next();

                    //tx.Put(db, BitConverter.GetBytes(i), BitConverter.GetBytes(i));
                    var text = "Some Text plus: 'Key' = " + key.ToString("N0"); // + " " + new String('c', 1000);
                    var data = GetBinaryEncodedString(text);
                    tx.Put(db, BitConverter.GetBytes(key), data);
                }
                tx.Commit();
                var stats = tx.GetStats(db);
                Console.WriteLine("Stats\n  # Entries: {0:N0}\n  Depth: {1}\n  Page Size: {2}",
                                  stats.ms_entries.ToInt64(), stats.ms_depth, stats.ms_psize);
                Console.WriteLine("  Branch Pages: {0:N0}\n  Leaf Pages: {1}\n  Overflow Pages: {2}",
                                  stats.ms_branch_pages.ToInt64(), stats.ms_leaf_pages.ToInt64(), stats.ms_overflow_pages.ToInt64());
            }
            writeTimer.Stop();
            Console.WriteLine("Took {0,10:N2} ms ({1}) to WRITE {2,9:N0} values ({3,10:N0} WRITES/sec)",
                              writeTimer.Elapsed.TotalMilliseconds, writeTimer.Elapsed, numItemsToWrite,
                              numItemsToWrite / writeTimer.Elapsed.TotalMilliseconds * 1000.0);

            var readTimer = Stopwatch.StartNew();
            var readCounter = 0;
            using (var tx = env.BeginTransaction())
            using (var db = tx.OpenDatabase("test"))
            {
                tx.Get(db, BitConverter.GetBytes(int.MinValue));
                ValueStructure currentKey = default(ValueStructure);
                ValueStructure currentValue = default(ValueStructure);
                using (var cursor = tx.CreateCursor(db))
                {
                    while (cursor.MoveNext())
                    {
                        //var current = cursor.Current;
                        cursor.GetCurrent(out currentKey, out currentValue);
                        unsafe
                        {
                            var keyData = *((int*)(currentKey.data.ToPointer()));
                            int valueLengthSize;
                            var ptr = (byte*)currentValue.data.ToPointer();
                            var length = Read7BitEncodedInt(ptr, out valueLengthSize);
                            var text = new string((sbyte*)(ptr + valueLengthSize), 0, length, Encoding.UTF8);
                            //Console.WriteLine("{{ Key: {0:N0}, Value: \"{1}\" }}", keyData, text);
                        }
                        readCounter++;
                    }
                }
            }
            readTimer.Stop();
            Console.WriteLine("Took {0,10:N2} ms ({1}) to READ  {2,9:N0} values ({3,10:N0}  READS/sec)",
                              readTimer.Elapsed.TotalMilliseconds, readTimer.Elapsed, readCounter,
                              readCounter / readTimer.Elapsed.TotalMilliseconds * 1000.0);
            Console.WriteLine();
        }
 /// <summary>
 /// Construct a <see cref="DatabaseContext"/>
 /// </summary>
 /// <param name="options">The <see cref="DbContextOptions{TContext}"/> for the <see cref="DatabaseContext"/></param>
 /// <param name="databaseConfigurationOptions">The <see cref="IOptions{TOptions}"/> containing the value of <see cref="databaseConfiguration"/></param>
 /// <param name="loggerFactory">The value of <see cref="loggerFactory"/></param>
 /// <param name="hostingEnvironment">The value of <see cref="hostingEnvironment"/></param>
 public DatabaseContext(DbContextOptions <DatabaseContext> options, IOptions <DatabaseConfiguration> databaseConfigurationOptions, ILoggerFactory loggerFactory, IHostingEnvironment hostingEnvironment) : base(options)
 {
     databaseConfiguration   = databaseConfigurationOptions?.Value ?? throw new ArgumentNullException(nameof(databaseConfigurationOptions));
     this.loggerFactory      = loggerFactory ?? throw new ArgumentNullException(nameof(loggerFactory));
     this.hostingEnvironment = hostingEnvironment ?? throw new ArgumentNullException(nameof(hostingEnvironment));
 }
Beispiel #27
0
 public QuotationTypesRepositoryTests()
 {
     dbConfiguration          = new DatabaseConfiguration();
     session                  = dbConfiguration.GetSession();
     quotationTypesRepository = new QuotationTypesRepository(session);
 }
Beispiel #28
0
 internal static void Configure(DatabaseConfiguration configuration)
 {
     _configuration = configuration;
 }
Beispiel #29
0
 public Extension()
 {
     configuration = new DatabaseConfiguration();
     mapper        = new Mapper();
 }
        /// <summary>
        /// Prompts the user to create a <see cref="DatabaseConfiguration"/>
        /// </summary>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the operation</param>
        /// <returns>A <see cref="Task{TResult}"/> resulting in the new <see cref="DatabaseConfiguration"/></returns>
        async Task <DatabaseConfiguration> ConfigureDatabase(CancellationToken cancellationToken)
        {
            do
            {
                await console.WriteAsync(null, true, cancellationToken).ConfigureAwait(false);

                await console.WriteAsync("What SQL database type will you be using?", true, cancellationToken).ConfigureAwait(false);

                var databaseConfiguration = new DatabaseConfiguration();
                do
                {
                    await console.WriteAsync(String.Format(CultureInfo.InvariantCulture, "Please enter one of {0}, {1}, or {2}: ", DatabaseType.MariaDB, DatabaseType.SqlServer, DatabaseType.MySql), false, cancellationToken).ConfigureAwait(false);

                    var databaseTypeString = await console.ReadLineAsync(false, cancellationToken).ConfigureAwait(false);

                    if (Enum.TryParse <DatabaseType>(databaseTypeString, out var databaseType))
                    {
                        databaseConfiguration.DatabaseType = databaseType;
                        break;
                    }

                    await console.WriteAsync("Invalid database type!", true, cancellationToken).ConfigureAwait(false);
                }while (true);

                string serverAddress;
                uint?  mySQLServerPort = null;
                do
                {
                    await console.WriteAsync(null, true, cancellationToken).ConfigureAwait(false);

                    await console.WriteAsync("Enter the server's address and port [<server>:<port> or <server>] (blank for local): ", false, cancellationToken).ConfigureAwait(false);

                    serverAddress = await console.ReadLineAsync(false, cancellationToken).ConfigureAwait(false);

                    if (String.IsNullOrWhiteSpace(serverAddress))
                    {
                        serverAddress = null;
                        break;
                    }
                    else if (databaseConfiguration.DatabaseType != DatabaseType.SqlServer)
                    {
                        var m = Regex.Match(serverAddress, @"^(?<server>.+):(?<port>.+)$");
                        if (m.Success)
                        {
                            serverAddress = m.Groups["server"].Value;
                            if (uint.TryParse(m.Groups["port"].Value, out uint port))
                            {
                                mySQLServerPort = port;
                                break;
                            }
                            else
                            {
                                await console.WriteAsync($@"Failed to parse port ""{m.Groups["port"].Value}"", please try again.", true, cancellationToken).ConfigureAwait(false);
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }while (true);

                await console.WriteAsync(null, true, cancellationToken).ConfigureAwait(false);

                await console.WriteAsync("Enter the database name (Can be from previous installation. Otherwise, should not exist): ", false, cancellationToken).ConfigureAwait(false);

                string databaseName;
                do
                {
                    databaseName = await console.ReadLineAsync(false, cancellationToken).ConfigureAwait(false);

                    if (!String.IsNullOrWhiteSpace(databaseName))
                    {
                        break;
                    }
                    await console.WriteAsync("Invalid database name!", true, cancellationToken).ConfigureAwait(false);
                }while (true);

                var dbExists = await PromptYesNo("Does this database already exist? (y/n): ", cancellationToken).ConfigureAwait(false);

                bool useWinAuth;
                if (databaseConfiguration.DatabaseType == DatabaseType.SqlServer && platformIdentifier.IsWindows)
                {
                    useWinAuth = await PromptYesNo("Use Windows Authentication? (y/n): ", cancellationToken).ConfigureAwait(false);
                }
                else
                {
                    useWinAuth = false;
                }

                await console.WriteAsync(null, true, cancellationToken).ConfigureAwait(false);

                string username = null;
                string password = null;
                if (!useWinAuth)
                {
                    await console.WriteAsync("Enter username: "******"Enter password: "******"IMPORTANT: If using the service runner, ensure this computer's LocalSystem account has CREATE DATABASE permissions on the target server!", true, cancellationToken).ConfigureAwait(false);

                    await console.WriteAsync("The account it uses in MSSQL is usually \"NT AUTHORITY\\SYSTEM\" and the role it needs is usually \"dbcreator\".", true, cancellationToken).ConfigureAwait(false);

                    await console.WriteAsync("We'll run a sanity test here, but it won't be indicative of the service's permissions if that is the case", true, cancellationToken).ConfigureAwait(false);
                }

                await console.WriteAsync(null, true, cancellationToken).ConfigureAwait(false);

                DbConnection testConnection;
                void CreateTestConnection(string connectionString)
                {
                    testConnection = dbConnectionFactory.CreateConnection(connectionString, databaseConfiguration.DatabaseType);
                }

                if (databaseConfiguration.DatabaseType == DatabaseType.SqlServer)
                {
                    var csb = new SqlConnectionStringBuilder
                    {
                        ApplicationName = application.VersionPrefix,
                        DataSource      = serverAddress ?? "(local)"
                    };
                    if (useWinAuth)
                    {
                        csb.IntegratedSecurity = true;
                    }
                    else
                    {
                        csb.UserID   = username;
                        csb.Password = password;
                    }

                    CreateTestConnection(csb.ConnectionString);
                    csb.InitialCatalog = databaseName;
                    databaseConfiguration.ConnectionString = csb.ConnectionString;
                }
                else
                {
                    var csb = new MySqlConnectionStringBuilder
                    {
                        Server   = serverAddress ?? "127.0.0.1",
                        UserID   = username,
                        Password = password
                    };

                    if (mySQLServerPort.HasValue)
                    {
                        csb.Port = mySQLServerPort.Value;
                    }

                    CreateTestConnection(csb.ConnectionString);
                    csb.Database = databaseName;
                    databaseConfiguration.ConnectionString = csb.ConnectionString;
                }

                try
                {
                    using (testConnection)
                    {
                        await console.WriteAsync("Testing connection...", true, cancellationToken).ConfigureAwait(false);

                        await testConnection.OpenAsync(cancellationToken).ConfigureAwait(false);

                        await console.WriteAsync("Connection successful!", true, cancellationToken).ConfigureAwait(false);

                        if (databaseConfiguration.DatabaseType != DatabaseType.SqlServer)
                        {
                            await console.WriteAsync("Checking MySQL/MariaDB version...", true, cancellationToken).ConfigureAwait(false);

                            using (var command = testConnection.CreateCommand())
                            {
                                command.CommandText = "SELECT VERSION()";
                                var fullVersion = (string)await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false);

                                await console.WriteAsync(String.Format(CultureInfo.InvariantCulture, "Found {0}", fullVersion), true, cancellationToken).ConfigureAwait(false);

                                var splits = fullVersion.Split('-');
                                databaseConfiguration.MySqlServerVersion = splits[0];
                            }
                        }

                        if (!dbExists)
                        {
                            await console.WriteAsync("Testing create DB permission...", true, cancellationToken).ConfigureAwait(false);

                            using (var command = testConnection.CreateCommand())
                            {
                                // I really don't care about user sanitization here, they want to f**k their own DB? so be it
#pragma warning disable CA2100 // Review SQL queries for security vulnerabilities
                                command.CommandText = $"CREATE DATABASE {databaseName}";
#pragma warning restore CA2100 // Review SQL queries for security vulnerabilities
                                await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
                            }

                            await console.WriteAsync("Success!", true, cancellationToken).ConfigureAwait(false);

                            await console.WriteAsync("Dropping test database...", true, cancellationToken).ConfigureAwait(false);

                            using (var command = testConnection.CreateCommand())
                            {
#pragma warning disable CA2100 // Review SQL queries for security vulnerabilities
                                command.CommandText = $"DROP DATABASE {databaseName}";
#pragma warning restore CA2100 // Review SQL queries for security vulnerabilities
                                try
                                {
                                    await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
                                }
                                catch (OperationCanceledException)
                                {
                                    throw;
                                }
                                catch (Exception e)
                                {
                                    await console.WriteAsync(e.Message, true, cancellationToken).ConfigureAwait(false);

                                    await console.WriteAsync(null, true, cancellationToken).ConfigureAwait(false);

                                    await console.WriteAsync("This should be okay, but you may want to manually drop the database before continuing!", true, cancellationToken).ConfigureAwait(false);

                                    await console.WriteAsync("Press any key to continue...", true, cancellationToken).ConfigureAwait(false);

                                    await console.PressAnyKeyAsync(cancellationToken).ConfigureAwait(false);
                                }
                            }
                        }
                    }

                    return(databaseConfiguration);
                }
                catch (OperationCanceledException)
                {
                    throw;
                }
                catch (Exception e)
                {
                    await console.WriteAsync(e.Message, true, cancellationToken).ConfigureAwait(false);

                    await console.WriteAsync(null, true, cancellationToken).ConfigureAwait(false);

                    await console.WriteAsync("Retrying database configuration...", true, cancellationToken).ConfigureAwait(false);
                }
            }while (true);
        }
Beispiel #31
0
 public DiseaseRepository(DatabaseConfiguration databaseConfiguration) : base(databaseConfiguration)
 {
 }
 public UptimeCheckRepository(DocumentStoreFactory documentStoreFactory, DatabaseConfiguration databaseConfiguration)
 {
     _documentStoreFactory  = documentStoreFactory;
     _databaseConfiguration = databaseConfiguration;
 }
Beispiel #33
0
 public Startup(IConfiguration configuration)
 {
     Configuration          = configuration;
     _databaseConfiguration = new DatabaseConfiguration(configuration);
 }
 private List<ParameterModel> GetParameters(DatabaseConfiguration configuration, StoredProcedure procedure)
 {
     return
         procedure.Parameters
             .Cast<StoredProcedureParameter>()
             .Select(p => ToModel(configuration, p))
             .ToList();
 }
 public ShareRepository(DatabaseConfiguration databaseConfiguration) : base(databaseConfiguration)
 {
 }
 private StoredProcedureModel ToModel(SqlConnection connection, DatabaseConfiguration configuration, StoredProcedure procedure)
 {
     var model = new StoredProcedureModel();
     model.DatabaseName = CreateDatabaseName(procedure);
     model.TypeName = _typeNameBuilder.Build(configuration.StoredProcedures.Namespace, procedure.Name);
     model.Parameters = GetParameters(configuration, procedure);
     model.OutputParameters = model.Parameters.Where(p => p.IsOutput).ToList();
     model.Results = GetResults(connection, model);
     return model;
 }
		/// <summary>
		/// Loads this class form the given configuration node.
		/// </summary>
		/// <param name="node">The node.</param>
		public void LoadFromXml(
			XmlNode node )
		{
			if ( node != null )
			{
				XmlHelper.ReadAttribute(
					out applicationRegistryKeyName,
					node.Attributes[@"applicationRegistryKeyName"] );
				XmlHelper.ReadAttribute(
					out administratorEMailAddress,
					node.Attributes[@"administratorEMailAddress"] );
				XmlHelper.ReadAttribute(
					out disableLoggingPasswordProtection,
					node.Attributes[@"disableLoggingPasswordProtection"],
					false );
				XmlHelper.ReadAttribute(
					out smtpServer,
					node.Attributes[@"smtpServer"] );
				XmlHelper.ReadAttribute(
					out smtpServerPort,
					node.Attributes[@"smtpServerPort"] );
				XmlHelper.ReadAttribute(
					out smtpServerUserName,
					node.Attributes[@"smtpServerUserName"] );
				XmlHelper.ReadAttribute(
					out smtpServerPassword,
					node.Attributes[@"smtpServerPassword"] );

				string s;
				XmlHelper.ReadAttribute(
					out s,
					node.Attributes[@"deletedFilesFolderPath"] );

				if ( !string.IsNullOrEmpty( s ) )
				{
					deletedFilesFolderPath = new DirectoryInfo( s );
				}

				// --

				XmlNode databaseNode =
					node.SelectSingleNode( @"database" );

				if ( databaseNode != null )
				{
					string connectionStringString = null;
					int commandTimeoutSeconds = 0;
					bool traceSqlEnabled = false;
					string cacheSqlBehaviorText = null;
					DatabaseConfiguration.DatabaseCacheSqlBehavior
						cacheSqlBehavior =
						DatabaseConfiguration.DatabaseCacheSqlBehavior.Partially;

					XmlHelper.ReadAttribute(
						out connectionStringString,
						databaseNode.Attributes[@"connectionString"] );
					XmlHelper.ReadAttribute(
						out commandTimeoutSeconds,
						databaseNode.Attributes[@"commandTimeoutSeconds"] );
					XmlHelper.ReadAttribute(
						out cacheSqlBehaviorText,
						databaseNode.Attributes[@"cacheSqlBehavior"] );

					if ( !string.IsNullOrEmpty( cacheSqlBehaviorText ) )
					{
						cacheSqlBehavior =
							(DatabaseConfiguration.DatabaseCacheSqlBehavior)
							Enum.Parse(
							typeof( DatabaseConfiguration.DatabaseCacheSqlBehavior ),
							cacheSqlBehaviorText,
							true );
					}

					XmlHelper.ReadAttribute(
						out traceSqlEnabled,
						databaseNode.Attributes[@"traceSqlEnabled"] );

					database = new DatabaseConfiguration(
						connectionStringString,
						commandTimeoutSeconds,
						cacheSqlBehavior,
						traceSqlEnabled );
				}

				// --

				XmlNode webNode =
					node.SelectSingleNode( @"web" );

				if ( webNode != null )
				{
					bool useServerSideViewState = false;
					string replaceTildeFallback = null;
					string replaceTildeCompleteFallback = null;
					bool useCustomErrors = false;

					XmlHelper.ReadAttribute(
						out useServerSideViewState,
						webNode.Attributes[@"useServerSideViewState"] );
					XmlHelper.ReadAttribute(
						out replaceTildeFallback,
						webNode.Attributes[@"replaceTildeFallback"] );
					XmlHelper.ReadAttribute(
						out replaceTildeCompleteFallback,
						webNode.Attributes[@"replaceTildeCompleteFallback"] );
					XmlHelper.ReadAttribute(
						out useCustomErrors,
						webNode.Attributes[@"useCustomErrors"] );

					web = new WebConfiguration(
						useServerSideViewState,
						replaceTildeFallback,
						replaceTildeCompleteFallback,
						useCustomErrors );
				}

				// --

				/*
				<webProxy
					address=""
					bypassProxyOnLocal="" >
					<credentials 
						domain=""
						userName=""
						password="" />
					<bypassList>
						<bypass rx="" />
						<bypass rx="" />
						<bypass rx="" />
						<bypass rx="" />
					</bypassList>
				</webProxy>
				*/

				XmlNode webProxyNode =
					node.SelectSingleNode( @"webProxy" );

				if ( webProxyNode != null )
				{
					bool hasEnabled = false;
					bool enabled = false;
					string address = null;
					bool hasBypassProxyOnLocal = false;
					bool bypassProxyOnLocal = false;

					hasEnabled =
						webProxyNode.Attributes[@"enabled"] != null;
					XmlHelper.ReadAttribute(
						out enabled,
						webProxyNode.Attributes[@"enabled"] );
					XmlHelper.ReadAttribute(
						out address,
						webProxyNode.Attributes[@"address"] );
					hasBypassProxyOnLocal =
						webProxyNode.Attributes[@"bypassProxyOnLocal"] != null;
					XmlHelper.ReadAttribute(
						out bypassProxyOnLocal,
						webProxyNode.Attributes[@"bypassProxyOnLocal"] );

					// If no address is given, ignore everything else.
					if ( hasEnabled && enabled &&
						!string.IsNullOrEmpty( address ) )
					{
						WebProxy webProxy = new WebProxy();
						webProxy.Address = new Uri( address );

						if ( hasBypassProxyOnLocal )
						{
							webProxy.BypassProxyOnLocal = bypassProxyOnLocal;
						}

						XmlNode credentialsNode =
							webProxyNode.SelectSingleNode( @"credentials" );

						if ( credentialsNode != null )
						{
							string domain = null;
							string userName = null;
							string password = null;

							XmlHelper.ReadAttribute(
								out domain,
								credentialsNode.Attributes[@"domain"] );
							XmlHelper.ReadAttribute(
								out userName,
								credentialsNode.Attributes[@"userName"] );
							XmlHelper.ReadAttribute(
								out password,
								credentialsNode.Attributes[@"password"] );

							// If no user name is given, ignore the credentials.
							if ( userName != null && userName.Length > 0 )
							{
								NetworkCredential credentials =
									new NetworkCredential();

								credentials.UserName = userName;
								credentials.Password = password;
								credentials.Domain = domain;

								webProxy.Credentials = credentials;
							}
						}

						XmlNodeList bypassNodes =
							webProxyNode.SelectNodes( @"bypassList/bypass" );

						if ( bypassNodes != null && bypassNodes.Count > 0 )
						{
							List<string> bypassRXs = new List<string>();

							foreach ( XmlNode bypassNode in bypassNodes )
							{
								string rx = null;

								XmlHelper.ReadAttribute(
									out rx,
									bypassNode.Attributes[@"rx"] );

								if ( rx != null && rx.Length > 0 )
								{
									bypassRXs.Add( rx );
								}
							}

							if ( bypassRXs.Count > 0 )
							{
								webProxy.BypassList = bypassRXs.ToArray();
							}
						}

						this.webProxy = webProxy;
					}
				}
			}
		}
Beispiel #38
0
 public SiteCommunity()
 {
     configuration = new DatabaseConfiguration();
     mapper        = new Mapper();
 }
 /// <summary>
 /// Записать схемы базы данных
 /// </summary>
 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
     base.OnModelCreating(modelBuilder);
     DatabaseConfiguration.ApplyConfiguration(modelBuilder);
 }
Beispiel #40
0
 public SiteXsiDetail()
 {
     configuration = new DatabaseConfiguration();
     mapper        = new Mapper();
 }
 /// <summary>
 /// Записать параметры конфигурации
 /// </summary>
 protected override void OnConfiguring(DbContextOptionsBuilder builder) =>
 DatabaseConfiguration.ConfigureEnumsMapping();
 // private readonly string strGetUsersQuery = @"select first_name FirstName,last_name LastName,user_id UserId from security.user_account";
 #endregion
 public PostgresSqlRepository(IOptions <AppSettingsModel> Appstns)
 {
     this.appSettings = Appstns;
     db = DatabaseConfiguration.Build().UsingConnectionString(appSettings.Value.DefaultConnection).UsingProvider(new PostgreSQLDatabaseProvider()).Create();
     db.OpenSharedConnection();
 }
        public void TransactionShouldSupportCustomDupSorter()
        {
            Func<int, int, int> comparison = (l, r) => -Math.Sign(l - r);

            var txn = _env.BeginTransaction();
            var options = new DatabaseConfiguration {Flags = DatabaseOpenFlags.Create | DatabaseOpenFlags.DuplicatesFixed};
            Func<byte[], byte[], int> compareWith = (l, r) => comparison(BitConverter.ToInt32(l, 0), BitConverter.ToInt32(r, 0));
            options.FindDuplicatesWith(Comparer<byte[]>.Create(new Comparison<byte[]>(compareWith)));
            var db = txn.OpenDatabase(configuration: options);

            var valuesUnsorted = new [] { 2, 10, 5, 0 };
            var valuesSorted = valuesUnsorted.ToArray();
            Array.Sort(valuesSorted, new Comparison<int>(comparison));

            using (var c = txn.CreateCursor(db))
                c.PutMultiple(BitConverter.GetBytes(123), valuesUnsorted.Select(BitConverter.GetBytes).ToArray());

            using (var c = txn.CreateCursor(db))
            {
                int order = 0;

                while (c.MoveNext())
                    Assert.Equal(valuesSorted[order++], BitConverter.ToInt32(c.Current.Value, 0));
            }
        }
 public ExerciseRepository(DatabaseConfiguration configuration) : base(configuration)
 {
 }
 private ParameterModel ToModel(DatabaseConfiguration configuration, StoredProcedureParameter parameter)
 {
     return new ParameterModel
     {
         Scale = GetNumericScale(parameter.DataType),
         Precision = GetNumericPrecision(parameter.DataType),
         Size = GetSize(parameter.DataType),
         IsOutput = parameter.IsOutputParameter,
         //todo
         //SqlDataType = p.DataType.SqlDataType,
         SqlDbType = _typeConverter.ToSqlDbDataType(parameter.DataType),
         Column = new ColumnModel
         {
             DatabaseName = parameter.Name,
             ClrType = _typeConverter.ToClrType(parameter, configuration.TableTypeNamespaceFromStoredProcedure)
         }
     };
 }
        /// <summary>
        /// Saves a given <see cref="Configuration"/> set to <paramref name="userConfigFileName"/>
        /// </summary>
        /// <param name="userConfigFileName">The file to save the <see cref="Configuration"/> to</param>
        /// <param name="hostingPort">The hosting port to save</param>
        /// <param name="databaseConfiguration">The <see cref="DatabaseConfiguration"/> to save</param>
        /// <param name="newGeneralConfiguration">The <see cref="GeneralConfiguration"/> to save</param>
        /// <param name="fileLoggingConfiguration">The <see cref="FileLoggingConfiguration"/> to save</param>
        /// <param name="controlPanelConfiguration">The <see cref="ControlPanelConfiguration"/> to save</param>
        /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the operation</param>
        /// <returns>A <see cref="Task"/> representing the running operation</returns>
        async Task SaveConfiguration(string userConfigFileName, ushort?hostingPort, DatabaseConfiguration databaseConfiguration, GeneralConfiguration newGeneralConfiguration, FileLoggingConfiguration fileLoggingConfiguration, ControlPanelConfiguration controlPanelConfiguration, CancellationToken cancellationToken)
        {
            await console.WriteAsync(String.Format(CultureInfo.InvariantCulture, "Configuration complete! Saving to {0}", userConfigFileName), true, cancellationToken).ConfigureAwait(false);

            var map = new Dictionary <string, object>()
            {
                { DatabaseConfiguration.Section, databaseConfiguration },
                { GeneralConfiguration.Section, newGeneralConfiguration },
                { FileLoggingConfiguration.Section, fileLoggingConfiguration },
                { ControlPanelConfiguration.Section, controlPanelConfiguration }
            };

            if (hostingPort.HasValue)
            {
                map.Add("Kestrel", new
                {
                    EndPoints = new
                    {
                        Http = new
                        {
                            Url = String.Format(CultureInfo.InvariantCulture, "http://0.0.0.0:{0}", hostingPort)
                        }
                    }
                });
            }

            var json        = JsonConvert.SerializeObject(map, Formatting.Indented);
            var configBytes = Encoding.UTF8.GetBytes(json);

            try
            {
                await ioManager.WriteAllBytes(userConfigFileName, configBytes, cancellationToken).ConfigureAwait(false);
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception e)
            {
                await console.WriteAsync(e.Message, true, cancellationToken).ConfigureAwait(false);

                await console.WriteAsync(null, true, cancellationToken).ConfigureAwait(false);

                await console.WriteAsync("For your convienence, here's the json we tried to write out:", true, cancellationToken).ConfigureAwait(false);

                await console.WriteAsync(null, true, cancellationToken).ConfigureAwait(false);

                await console.WriteAsync(json, true, cancellationToken).ConfigureAwait(false);

                await console.WriteAsync(null, true, cancellationToken).ConfigureAwait(false);

                await console.WriteAsync("Press any key to exit...", true, cancellationToken).ConfigureAwait(false);

                await console.PressAnyKeyAsync(cancellationToken).ConfigureAwait(false);

                throw new OperationCanceledException();
            }

            await console.WriteAsync("Waiting for configuration changes to reload...", true, cancellationToken).ConfigureAwait(false);

            // we need to wait for the configuration's file system watcher to read and reload the changes
            await asyncDelayer.Delay(TimeSpan.FromSeconds(5), cancellationToken).ConfigureAwait(false);
        }