Esempio n. 1
0
 /// <summary>
 /// Constructor...
 /// </summary>
 public Database(DatabaseConfig config)
 {
     _config = config;
     // Tests that the connection is valid. SqlException thrown if not.
     try
     {
         using (MySqlConnection conn = getAConnection()) { }
     }
     catch (SqlException ex)
     {
         if (!handleDBError(new Delegates.DatabaseArgs(ex)))
             throw ex;
     }
 }
Esempio n. 2
0
 public CustomerQueries(EventStreamCollection <Customer> eventStreamManagersCollection)
 {
     this.dbConfig = AppConfig.Get.EventStreamDotNet.Database;
     managers      = eventStreamManagersCollection;
 }
    protected void Save_Click(object sender, EventArgs e)
    {
        HROneSaaSConfig SaaSconfig = HROneSaaSConfig.GetCurrentConfig();
        string          HROnePath  = new System.IO.FileInfo(SaaSconfig.HROneConfigFullPath).Directory.FullName;

        ECompanyDatabase c      = new ECompanyDatabase();
        Hashtable        values = new Hashtable();

        binding.toValues(values);

        PageErrors errors = PageErrors.getErrors(db, Page.Master);

        errors.clear();


        db.validate(errors, values);

        if (!errors.isEmpty())
        {
            return;
        }

        db.parse(values, c);

        if (!chkAutoCreateID.Checked && string.IsNullOrEmpty(c.CompanyDBClientCode))
        {
            errors.addError("Client ID is required");
            return;
        }



        HROne.ProductKey key = new HROne.ProductKey();
        key.ProductType    = HROne.ProductKey.ProductLicenseType.HROneSaaS;
        key.NumOfCompanies = Convert.ToUInt16(c.CompanyDBMaxCompany);
        key.NumOfUsers     = Convert.ToUInt16(c.CompanyDBMaxUser);
        if (c.CompanyDBHasIMGR)
        {
            key.IsLeaveManagement = true;
            key.IsPayroll         = true;
            key.IsTaxation        = true;
        }
        if (c.CompanyDBHasIStaff)
        {
            key.IsESS = true;
        }

        if (string.IsNullOrEmpty(c.CompanyDBClientCode))
        {
            const int MAX_LENGTH = 8;
            string    prefix     = CreateClientCodePrefix(c.CompanyDBClientName);
            //if (c.CompanyDBClientBank.Equals("HSBC", StringComparison.CurrentCultureIgnoreCase))
            //    prefix = "H";
            //else if (c.CompanyDBClientBank.Equals("HangSeng", StringComparison.CurrentCultureIgnoreCase))
            //    prefix = "X";
            int idx = 0;
            if (prefix.Length >= MAX_LENGTH)
            {
                prefix = prefix.Substring(0, MAX_LENGTH);
            }
            else
            {
                idx++;
                string idxString = idx.ToString().Trim();
                prefix = prefix.PadRight(MAX_LENGTH - idxString.Length, '0') + idxString;
            }
            c.CompanyDBClientCode = prefix;
            while (!AppUtils.checkDuplicate(dbConn, ECompanyDatabase.db, c, new PageErrors(), "CompanyDBClientCode"))
            {
                idx++;
                string idxString = idx.ToString().Trim();
                c.CompanyDBClientCode = prefix.Substring(0, MAX_LENGTH - idxString.Length) + idxString;
            }
        }
        if (!AppUtils.checkDuplicate(dbConn, ECompanyDatabase.db, c, errors, "CompanyDBClientCode"))
        {
            return;
        }

        EDatabaseServer dbServer = new EDatabaseServer();

        dbServer.DBServerID = c.DBServerID;
        if (EDatabaseServer.db.select(dbConn, dbServer))
        {
            if (dbServer.DBServerDBType.Equals("MSSQL"))
            {
                System.Data.SqlClient.SqlConnectionStringBuilder saConnStringBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder();
                saConnStringBuilder.DataSource = dbServer.DBServerLocation;
                saConnStringBuilder.UserID     = dbServer.DBServerSAUserID;
                saConnStringBuilder.Password   = dbServer.DBServerSAPassword;

                DatabaseConfig dbConfig = new DatabaseConfig();
                dbConfig.DBType           = WebUtils.DBTypeEmun.MSSQL;
                dbConfig.ConnectionString = saConnStringBuilder.ConnectionString;
                if (dbConfig.TestServerConnectionWithoutDatabase())
                {
                    string DBSchemaName = c.CompanyDBSchemaName.Trim();
                    if (DBSchemaName.Equals(string.Empty))
                    {
                        DBSchemaName = c.CompanyDBClientCode;
                    }
                    System.Data.SqlClient.SqlConnectionStringBuilder connStringBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder();
                    connStringBuilder.DataSource     = dbServer.DBServerLocation;
                    connStringBuilder.InitialCatalog = DBSchemaName;
                    connStringBuilder.UserID         = dbServer.DBServerUserID;
                    connStringBuilder.Password       = dbServer.DBServerPassword;
                    dbConfig.ConnectionString        = connStringBuilder.ConnectionString;
                    if (!dbConfig.TestConnection())
                    {
                        if (chkCreateDB.Checked)
                        {
                            try
                            {
                                HROne.ProductVersion.Database.CreateSchema(saConnStringBuilder.ConnectionString, DBSchemaName, dbServer.DBServerUserID);
                                //c.CompanyDBSchemaName = DBSchemaName;
                                saConnStringBuilder.InitialCatalog = DBSchemaName;
                                HROne.ProductVersion.Database.CreateTableAndData(HROnePath, saConnStringBuilder.ConnectionString);
                                // drop all the connection so that new "normal user" connection to database is accepted
                                System.Data.SqlClient.SqlConnection.ClearAllPools();
                            }
                            catch (Exception ex)
                            {
                                errors.addError(ex.Message);
                                return;
                            }
                        }
                        else
                        {
                            errors.addError("Fail to connect to database");
                            return;
                        }
                    }
                }
                else
                {
                    errors.addError("Fail to connect to server");
                    return;
                }
            }
        }
        if (CurID < 0)
        {
            //            Utils.MarkCreate(Session, c);

            db.insert(dbConn, c);
            CurID = c.CompanyDBID;
            HSBCExchangeProfile_List1.CompanyDBID = CurID;
            //            url = Utils.BuildURL(-1, CurID);
        }
        else
        {
            //            Utils.Mark(Session, c);
        }

        key.SerialNo          = Convert.ToUInt16(c.CompanyDBID);
        c.CompanyDBProductKey = key.GetProductKey();
        db.update(dbConn, c);

        HROne.ProductVersion.Database databaseProcess = new HROne.ProductVersion.Database(new DatabaseConnection(c.getConnectionString(dbConn), DatabaseConnection.DatabaseType.MSSQL), HROnePath);
        databaseProcess.UpdateDatabaseVersion(true);
        errors.addError("Saved");
        loadObject();
        //Response.Redirect("~/CompanyDB_List.aspx");
    }
Esempio n. 4
0
        public void ConfigureServices(IServiceCollection services)
        {
            var db    = new DatabaseConfig();
            var mqtt  = new MqttConfig();
            var cache = new CacheConfig();

            this.m_configuration.GetSection("Database").Bind(db);
            this.m_configuration.GetSection("Mqtt").Bind(mqtt);
            this.m_configuration.GetSection("Cache").Bind(cache);

            var proxyLevel  = this.m_configuration.GetValue <int>("System:ProxyLevel");
            var privatemqtt = mqtt.InternalBroker;

            services.AddDocumentStore(db.MongoDB.ConnectionString, db.MongoDB.DatabaseName, db.MongoDB.MaxConnections);
            services.AddConnectionStrings(db.Networking.ConnectionString, db.SensateIoT.ConnectionString);
            services.AddAuthorizationContext();
            services.AddNetworkingContext();
            services.AddDistributedCaches <PaginationResponse <Sensor> >(cache.Host, cache.Port);
            services.AddCors();

            services.AddInternalMqttService(options => {
                options.Ssl      = privatemqtt.Ssl;
                options.Host     = privatemqtt.Host;
                options.Port     = privatemqtt.Port;
                options.Username = privatemqtt.Username;
                options.Password = privatemqtt.Password;
                options.Id       = Guid.NewGuid().ToString();
            });

            services.Configure <InternalBrokerConfig>(this.m_configuration.GetSection("Mqtt:InternalBroker"));
            services.Configure <RouterConfig>(this.m_configuration.GetSection("Router"));
            services.Configure <BlobOptions>(this.m_configuration.GetSection("Storage"));
            services.Configure <MetricsOptions>(this.m_configuration.GetSection("HttpServer:Metrics"));

            services.AddScoped <ITriggerAdministrationRepository, TriggerAdministrationRepository>();
            services.AddScoped <IMessageRepository, MessageRepository>();
            services.AddScoped <IControlMessageRepository, ControlMessageRepository>();
            services.AddScoped <IMeasurementRepository, MeasurementRepository>();
            services.AddScoped <ISensorRepository, SensorRepository>();
            services.AddScoped <ISensorLinkRepository, SensorLinkRepository>();
            services.AddScoped <IAccountRepository, AccountRepository>();
            services.AddScoped <IApiKeyRepository, ApiKeyRepository>();
            services.AddScoped <ILiveDataHandlerRepository, LiveDataHandlerRepository>();
            services.AddScoped <ISensorService, SensorService>();
            services.AddScoped <ICommandPublisher, CommandPublisher>();
            services.AddScoped <IBlobRepository, BlobRepository>();
            services.AddScoped <IAuditLogRepository, AuditLogRepository>();

            services.AddSingleton <IBlobService, FilesystemBlobService>();
            services.AddSingleton <IRouterClient, RouterClient>();
            services.AddSingleton <IAuthorizationService, AuthorizationService>();
            services.AddSingleton <IMeasurementAuthorizationService, MeasurementAuthorizationService>();
            services.AddSingleton <IMessageAuthorizationService, MessageAuthorizationService>();
            services.AddSingleton <IHashAlgorithm, SHA256Algorithm>();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddHostedService <BatchRoutingService>();
            services.AddHostedService <MetricsService>();

            services.AddSwaggerGen(c => {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title   = "Sensate IoT Network API - Version 1",
                    Version = "v1"
                });

                c.SchemaFilter <ObjectIdSchemaFilter>();
                c.OperationFilter <ObjectIdOperationFilter>();

                c.AddSecurityDefinition("X-ApiKey", new OpenApiSecurityScheme {
                    In          = ParameterLocation.Header,
                    Name        = "X-ApiKey",
                    Type        = SecuritySchemeType.ApiKey,
                    Description = "API key needed to access the endpoints."
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Name      = "X-ApiKey",
                            Type      = SecuritySchemeType.ApiKey,
                            In        = ParameterLocation.Header,
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "X-ApiKey"
                            },
                        },
                        Array.Empty <string>()
                    }
                });
            });

            services.AddReverseProxy(proxyLevel);
            services.AddRouting();
            services.AddControllers().AddNewtonsoftJson();
            services.AddMqttHandlers();
        }
Esempio n. 5
0
 public UserService(IOptions <DatabaseConfig> config)
 {
     databaseConfig = config.Value ?? throw new ArgumentNullException(nameof(config));
 }
 protected override ITableInfo CreateTableInfo(DatabaseConfig dbConfig, TableConfig tableConfig)
 {
     return(new MySqlTableInfoBuilder(dbConfig, tableConfig, _configValidator, _whereConditionValidator, _linkedServerValidator, _columnTypeManager, _primaryKeyManager).Build());
 }
 protected BaseApplicationContext(DbContextOptions options, IOptions <DatabaseConfig> dbOption)
 {
     _dbConfig = dbOption.Value;
 }
Esempio n. 8
0
 /* Unnecessary and unused, so commented it out
  * public  GameRepository()
  * {
  *  DatabaseConfig DBConfig = new DatabaseConfig();
  *  DBConfig.Name = "Data source=./Database/GamesDB.sqlite";
  *  DBConfig.StructureFile = "./Database/DatabaseStructure.sql";
  *  DBService = new DatabaseService(DBConfig);
  * }*/
 public GameRepository(DatabaseConfig DBConfig)
 {
     DBService = new DatabaseService(DBConfig);
 }
Esempio n. 9
0
        public void VerifyProceduresActionWithNoUpdatesNoDriver()
        {
            DatabaseDriver driver = new DatabaseDriver(DatabaseConfig.GetProviderTypeString(), DatabaseConfig.GetConnectionString());

            var result = driver.Execute("setStateAbbrevToSelf", new { StateAbbreviation = "ZZ" }, commandType: CommandType.StoredProcedure);

            Assert.AreEqual(0, result, "Expected 0 state abbreviation to be updated.");
        }
Esempio n. 10
0
        public void VerifyProceduresQueryWithoutResultNoDriver()
        {
            DatabaseDriver driver = new DatabaseDriver(DatabaseConfig.GetProviderTypeString(), DatabaseConfig.GetConnectionString());

            var result = driver.Query("getStateAbbrevMatch", new { StateAbbreviation = "ZZ" }, commandType: CommandType.StoredProcedure);

            Assert.AreEqual(0, result.Count(), "Expected 0 state abbreviation to be returned.");
        }
Esempio n. 11
0
 public Converter(DatabaseConfig P, DatabaseConfig B)
 {
     this.PhoenixDbConfig   = P;
     this.ButterflyDbConfig = B;
 }
Esempio n. 12
0
        public void GetDatabaseProviderTypeStringTest()
        {
            string provider = DatabaseConfig.GetProviderTypeString();

            Assert.AreEqual("SQLSERVER", provider);
        }
Esempio n. 13
0
        public void GetDatabaseConnectionStringTest()
        {
            string connection = DatabaseConfig.GetConnectionString();

            Assert.AreEqual("Data Source=qasqlserver.database.windows.net;Initial Catalog=MagenicAutomation;Persist Security Info=True;User ID=MagenicQA;Password=1magenicMARQ;Connection Timeout=30", connection);
        }
Esempio n. 14
0
 public UrlRepository(DatabaseConfig databaseConfig)
 {
     _databaseConfig = databaseConfig;
 }
Esempio n. 15
0
 public CountyQueries(IOptions <DatabaseConfig> config)
 {
     dbcConfig = config.Value ?? throw new ArgumentNullException(nameof(config));
 }
Esempio n. 16
0
 public PatientRepository(DatabaseConfig databaseConfig)
 {
     _databaseConfig = databaseConfig;
 }
 private async Task <T> ExecuteWithNewConnection <T>(Func <IDbConnection, Task <T> > dataAccessMethod)
 {
     await using var connection = new NpgsqlConnection(DatabaseConfig.GetConnectionString());
     return(await dataAccessMethod(connection));
 }
Esempio n. 18
0
 public MySqlDBAccess(IDBInteraction dbInteraction, DatabaseConfig config, string databaseTypeName)
     : base(dbInteraction, config, databaseTypeName, SQL_MAX_LENGTH)
 {
 }
 /// <summary>
 /// Get the database connection
 /// </summary>
 /// <returns>The database connection</returns>
 protected override IDbConnection GetDataBaseConnection()
 {
     return(DatabaseConfig.GetOpenConnection("SQLITE", $"Data Source={GetDByPath()}"));
 }
Esempio n. 20
0
 protected abstract ITableInfo CreateTableInfo(DatabaseConfig dbConfig, TableConfig tableConfig);
Esempio n. 21
0
 public SQLHelperBase(DatabaseConfig databaseConfig)
 {
     DatabaseConfig = databaseConfig;
 }
Esempio n. 22
0
    public DatabaseConfig GenerateDBType()
    {
        DatabaseConfig config = new DatabaseConfig();

        if (string.IsNullOrEmpty(MSSQLDatabase.Text))
        {
            throw new Exception("Database must be fill in.");
            //return null;
        }

        config.DBType = WebUtils.DBTypeEmun.MSSQL;

        System.Data.SqlClient.SqlConnectionStringBuilder connStringBuilder = new System.Data.SqlClient.SqlConnectionStringBuilder();
        connStringBuilder.DataSource = MSSQLServerLocation.Text;
        connStringBuilder.InitialCatalog = MSSQLDatabase.Text;
        connStringBuilder.UserID = MSSQLUserID.Text;
        connStringBuilder.Password = MSSQLPassword.Text;
        config.ConnectionString = connStringBuilder.ConnectionString;

        if (config.TestConnection())
        {
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connStringBuilder.ConnectionString);
            conn.Open();
            DataTable table = conn.GetSchema("Tables");
            conn.Close();
            DataRow[] rows = table.Select("TABLE_NAME='SystemParameter'");
            if (rows.GetLength(0) == 0)
                if (chkCreateDatabase.Checked)
                    CreateSchema(config.ConnectionString);
                else
                    throw new Exception("Database does not contain table");
            return config;
        }
        else
        {
            if (config.TestServerConnectionWithoutDatabase())
            {
                if (chkCreateDatabase.Checked)
                {
                    try
                    {
                        string saUser = SAUserID.Text;
                        string saPassword = SAPassword.Text;

                        if (saUser.Trim() == string.Empty)
                        {
                            saUser = MSSQLUserID.Text;
                            saPassword = MSSQLPassword.Text;
                        }
                        connStringBuilder.InitialCatalog = string.Empty;
                        connStringBuilder.UserID = saUser;
                        connStringBuilder.Password = saPassword;
                        System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connStringBuilder.ConnectionString);

                        System.Data.SqlClient.SqlCommand command = conn.CreateCommand();
                        command.CommandType = System.Data.CommandType.Text;
                        command.CommandText = "Create Database " + MSSQLDatabase.Text + "\r\n";

                        command.Connection.Open();
                        command.ExecuteNonQuery();

                        if (MSSQLUserID.Text.Trim() != saUser.Trim())
                        {
                            command.CommandText = "USE " + MSSQLDatabase.Text + "\r\n"
                            + "CREATE USER " + MSSQLUserID.Text + " FOR LOGIN " + MSSQLUserID.Text + "\r\n"
                            + "EXEC sp_addrolemember N'db_owner', N'" + MSSQLUserID.Text + "'";

                            command.ExecuteNonQuery();
                        }
                        command.Connection.Close();

                        connStringBuilder.InitialCatalog = MSSQLDatabase.Text;
                        CreateSchema(connStringBuilder.ConnectionString);

                        return config;

                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Error on creating Database:\n" + ex.Message);
                    }
                }
                else
                    throw new Exception("Invalid Database name.");
            }
            else
            {
                throw new Exception("Fail to connect to server.");
            }
        }
        //return null;

    }
Esempio n. 23
0
        public void Backup()
        {
            Log("Backup", "Starting {0} backup to {1}", IsInitialized ? string.Empty : "noninitialized",
                backupDir);

            try
            {
                if (!IsInitialized)
                {
                    ClearDirectory(backupDir);
                }

                // Get log of last checkpoint for last checkpoint
                int newCheckpointLogNumber = storage.Environment.GetLastCheckpointLogNumber();
                // Get list of unused log files
                unusedLogFiles = storage.Environment.GetUnusedLogFiles();
                Log("Backup", "Old log number = {0}, new = {1}", lastCheckpointLogNumber,
                    newCheckpointLogNumber);
                if (unusedLogFiles != null && unusedLogFiles.Count > 0)
                {
                    Log("Backup", "{0} unused log files - from {1} to {2}", unusedLogFiles.Count,
                        unusedLogFiles[0], unusedLogFiles[unusedLogFiles.Count - 1]);
                }


                // get new data files
                List <string> newDataFiles = storage.Environment.GetDataFilesForArchiving();
                if (newDataFiles != null)
                {
                    // skip the ones already copied
                    for (int idx = newDataFiles.Count - 1; idx >= 0; --idx)
                    {
                        if (dataFilesCopied.Contains(newDataFiles[idx]))
                        {
                            newDataFiles.RemoveAt(idx);
                        }
                    }
                    if (newDataFiles.Count > 0)
                    {
                        DatabaseConfig config = new DatabaseConfig
                        {
                            Type      = DatabaseType.Unknown,
                            OpenFlags = DbOpenFlags.ReadOnly,
                            Id        = -1                                                                      // to avoid appending federation index to extension
                        };

                        if (dataCopyBufferSize > 0)
                        {
                            if (copyBuffer == null || copyBuffer.Length < dataCopyBufferSize)
                            {
                                copyBuffer = new byte[dataCopyBufferSize];
                            }
                        }

                        // Copy database files as needed
                        foreach (string dataFile in newDataFiles)
                        {
                            config.FileName = dataFile;
                            string backupDataFile = MakeRelativeToNewFolder(backupDir, dataFile);

                            using (Database db = storage.Environment.OpenDatabase(config))
                            {
                                switch (backupMethod)
                                {
                                case BackupMethod.MpoolFile:
                                    db.BackupFromMpf(backupDataFile, copyBuffer);
                                    break;

                                case BackupMethod.Fstream:
                                    db.BackupFromDisk(backupDataFile, copyBuffer);
                                    break;

                                default:
                                    throw new ArgumentOutOfRangeException(string.Format(
                                                                              "Unhandled backup method {0}", backupMethod));
                                }
                            }

                            // Post data file copy ops
                            dataFilesCopied.Add(dataFile);
                        }
                    }
                }


                // Copy log files as needed
                if (copyLogFiles)
                {
                    List <string> logFiles = storage.Environment.GetAllLogFiles();
                    if (logFiles != null)
                    {
                        if (unusedLogFiles != null)
                        {
                            // unused log files can be moved
                            foreach (string logFile in unusedLogFiles)
                            {
                                if (File.Exists(logFile))
                                {
                                    string backupLogFile = MakeRelativeToNewFolder(backupDir, logFile);
                                    if (File.Exists(backupLogFile))
                                    {
                                        File.Delete(backupLogFile);
                                    }
                                    File.Move(logFile, backupLogFile);
                                    if (!logFilesCopied.Contains(logFile))
                                    {
                                        logFilesCopied.Add(logFile);
                                    }
                                }
                                logFiles.Remove(logFile);
                            }
                        }
                        // remaining log files are in use, so copy them
                        foreach (string logFile in logFiles)
                        {
                            if (!File.Exists(logFile))
                            {
                                continue;
                            }
                            string backupLogFile = MakeRelativeToNewFolder(backupDir, logFile);
                            File.Copy(logFile, backupLogFile, true);
                            if (!logFilesCopied.Contains(logFile))
                            {
                                logFilesCopied.Add(logFile);
                            }
                        }
                    }
                }


                // Set post backup values
                lastCheckpointLogNumber = newCheckpointLogNumber;
                lastUpdateTime          = DateTime.Now;
                if (!isInitialized)
                {
                    firstBackupTime = lastUpdateTime;
                    isInitialized   = true;
                }
                LogCompleted("Backup");
            }
            catch (Exception ex)
            {
                LogError("Backup", ex);
                throw;
            }
        }
Esempio n. 24
0
 public MySqlConnector(DatabaseConfig config)
 {
     this.config = config;
 }
Esempio n. 25
0
 public ProductOptionRepository(DatabaseConfig configuration) : base(configuration)
 {
 }
Esempio n. 26
0
 /// <summary>
 ///  Gets the catalog connection string using the app settings
 /// </summary>
 /// <param name="catalogConfig">The catalog configuration.</param>
 /// <param name="databaseConfig">The database configuration.</param>
 /// <returns></returns>
 private string GetCatalogConnectionString(CatalogConfig catalogConfig, DatabaseConfig databaseConfig)
 {
     return
         ($"Server=tcp:{catalogConfig.CatalogServer},1433;Database={catalogConfig.CatalogDatabase};User ID={databaseConfig.DatabaseUser};Password={databaseConfig.DatabasePassword};Trusted_Connection=False;Encrypt=True;");
 }
Esempio n. 27
0
 public SystemConfig()
 {
     DbConfig = new DatabaseConfig();
 }
Esempio n. 28
0
 public DBInserter(DatabaseConfig databaseConfiguration)
 {
     DatabaseConfiguration = databaseConfiguration;
 }
Esempio n. 29
0
 public ContactRepository(DatabaseConfig databaseConfig)
 {
     this.databaseConfig = databaseConfig;
 }
Esempio n. 30
0
 private static void Initialize(SQLiteConnection connection)
 {
     observableCache = new Dictionary <string, object>();
     cache           = new Dictionary <string, object>();
     cache.Add("MigratedConfigs", DatabaseConfig.Get("MigratedConfigs", false, connection));
     cache.Add("EncodeJobs2", DatabaseConfig.Get("EncodeJobs2", "", connection));
     cache.Add("UpdateInProgress", DatabaseConfig.Get("UpdateInProgress", false, connection));
     cache.Add("UpdateVersion", DatabaseConfig.Get("UpdateVersion", "", connection));
     cache.Add("UpdateInstallerLocation", DatabaseConfig.Get("UpdateInstallerLocation", "", connection));
     cache.Add("UpdateChangelogLocation", DatabaseConfig.Get("UpdateChangelogLocation", "", connection));
     cache.Add("LastOutputFolder", DatabaseConfig.Get("LastOutputFolder", "", connection));
     cache.Add("LastInputFileFolder", DatabaseConfig.Get("LastInputFileFolder", "", connection));
     cache.Add("LastVideoTSFolder", DatabaseConfig.Get("LastVideoTSFolder", "", connection));
     cache.Add("LastSrtFolder", DatabaseConfig.Get("LastSrtFolder", "", connection));
     cache.Add("LastCsvFolder", DatabaseConfig.Get("LastCsvFolder", "", connection));
     cache.Add("LastPresetExportFolder", DatabaseConfig.Get("LastPresetExportFolder", "", connection));
     cache.Add("AutoNameOutputFolder", DatabaseConfig.Get("AutoNameOutputFolder", "", connection));
     cache.Add("AutoNameCustomFormat", DatabaseConfig.Get("AutoNameCustomFormat", false, connection));
     cache.Add("AutoNameCustomFormatString", DatabaseConfig.Get("AutoNameCustomFormatString", "{source}-{title}", connection));
     cache.Add("NativeLanguageCode", DatabaseConfig.Get("NativeLanguageCode", "", connection));
     cache.Add("DubAudio", DatabaseConfig.Get("DubAudio", false, connection));
     cache.Add("LastPresetIndex", DatabaseConfig.Get("LastPresetIndex", -1, connection));
     cache.Add("LastPickerIndex", DatabaseConfig.Get("LastPickerIndex", 0, connection));
     cache.Add("EncodingDialogLastTab", DatabaseConfig.Get("EncodingDialogLastTab", 0, connection));
     cache.Add("OptionsDialogLastTab", DatabaseConfig.Get("OptionsDialogLastTab", 0, connection));
     cache.Add("CollapsedBuiltInFolders", DatabaseConfig.Get("CollapsedBuiltInFolders", "", connection));
     cache.Add("MainWindowPlacement", DatabaseConfig.Get("MainWindowPlacement", "", connection));
     cache.Add("EncodingDialogPlacement", DatabaseConfig.Get("EncodingDialogPlacement", "", connection));
     cache.Add("ChapterMarkersDialogPlacement", DatabaseConfig.Get("ChapterMarkersDialogPlacement", "", connection));
     cache.Add("PreviewWindowPlacement", DatabaseConfig.Get("PreviewWindowPlacement", "", connection));
     cache.Add("QueueTitlesDialogPlacement2", DatabaseConfig.Get("QueueTitlesDialogPlacement2", "", connection));
     cache.Add("AddAutoPauseProcessDialogPlacement", DatabaseConfig.Get("AddAutoPauseProcessDialogPlacement", "", connection));
     cache.Add("OptionsDialogPlacement", DatabaseConfig.Get("OptionsDialogPlacement", "", connection));
     cache.Add("EncodeDetailsWindowPlacement", DatabaseConfig.Get("EncodeDetailsWindowPlacement", "", connection));
     cache.Add("PickerWindowPlacement", DatabaseConfig.Get("PickerWindowPlacement", "", connection));
     cache.Add("LogWindowPlacement", DatabaseConfig.Get("LogWindowPlacement", "", connection));
     cache.Add("EncodingWindowOpen", DatabaseConfig.Get("EncodingWindowOpen", false, connection));
     cache.Add("PreviewWindowOpen", DatabaseConfig.Get("PreviewWindowOpen", false, connection));
     cache.Add("LogWindowOpen", DatabaseConfig.Get("LogWindowOpen", false, connection));
     cache.Add("EncodeDetailsWindowOpen", DatabaseConfig.Get("EncodeDetailsWindowOpen", false, connection));
     cache.Add("PickerWindowOpen", DatabaseConfig.Get("PickerWindowOpen", false, connection));
     cache.Add("VideoExpanded", DatabaseConfig.Get("VideoExpanded", true, connection));
     cache.Add("AudioExpanded", DatabaseConfig.Get("AudioExpanded", true, connection));
     cache.Add("SubtitlesExpanded", DatabaseConfig.Get("SubtitlesExpanded", true, connection));
     cache.Add("UpdatesEnabled", DatabaseConfig.Get("UpdatesEnabled", true, connection));
     cache.Add("UpdatePromptTiming", DatabaseConfig.Get("UpdatePromptTiming", "OnExit", connection));
     cache.Add("UpdatesDisabled32BitOSWarningDisplayed", DatabaseConfig.Get("UpdatesDisabled32BitOSWarningDisplayed", false, connection));
     cache.Add("PreviewSeconds", DatabaseConfig.Get("PreviewSeconds", 10, connection));
     cache.Add("ApplicationVersion", DatabaseConfig.Get("ApplicationVersion", "", connection));
     cache.Add("QueueColumns", DatabaseConfig.Get("QueueColumns", "Source:200|Title:35|Range:106|Destination:200", connection));
     cache.Add("QueueLastColumnWidth", DatabaseConfig.Get("QueueLastColumnWidth", 75.0, connection));
     cache.Add("CompletedColumnWidths", DatabaseConfig.Get("CompletedColumnWidths", "", connection));
     cache.Add("SourcePaneHeightStar", DatabaseConfig.Get("SourcePaneHeightStar", 2.0, connection));
     cache.Add("QueuePaneHeightStar", DatabaseConfig.Get("QueuePaneHeightStar", 1.0, connection));
     cache.Add("PickerListPaneWidth", DatabaseConfig.Get("PickerListPaneWidth", 135.0, connection));
     cache.Add("EncodingListPaneOpen", DatabaseConfig.Get("EncodingListPaneOpen", true, connection));
     cache.Add("EncodingListPaneWidth", DatabaseConfig.Get("EncodingListPaneWidth", 150.0, connection));
     cache.Add("ShowPickerWindowMessage", DatabaseConfig.Get("ShowPickerWindowMessage", true, connection));
     cache.Add("WorkerProcessPriority", DatabaseConfig.Get("WorkerProcessPriority", "BelowNormal", connection));
     cache.Add("LogVerbosity", DatabaseConfig.Get("LogVerbosity", 1, connection));
     cache.Add("CopyLogToOutputFolder", DatabaseConfig.Get("CopyLogToOutputFolder", false, connection));
     cache.Add("AutoPauseProcesses", DatabaseConfig.Get("AutoPauseProcesses", "", connection));
     cache.Add("MaxSimultaneousEncodes", DatabaseConfig.Get("MaxSimultaneousEncodes", 1, connection));
     cache.Add("PreviewCount", DatabaseConfig.Get("PreviewCount", 10, connection));
     cache.Add("PreviewDisplay", DatabaseConfig.Get("PreviewDisplay", "FitToWindow", connection));
     cache.Add("UseCustomPreviewFolder", DatabaseConfig.Get("UseCustomPreviewFolder", false, connection));
     cache.Add("PreviewOutputFolder", DatabaseConfig.Get("PreviewOutputFolder", "", connection));
     cache.Add("QueueTitlesUseTitleOverride", DatabaseConfig.Get("QueueTitlesUseTitleOverride", false, connection));
     cache.Add("QueueTitlesTitleOverride", DatabaseConfig.Get("QueueTitlesTitleOverride", 1, connection));
     cache.Add("ShowAudioTrackNameField", DatabaseConfig.Get("ShowAudioTrackNameField", false, connection));
     cache.Add("SourceHistory", DatabaseConfig.Get("SourceHistory", "", connection));
     cache.Add("MinimizeToTray", DatabaseConfig.Get("MinimizeToTray", false, connection));
     cache.Add("OutputToSourceDirectory", DatabaseConfig.Get("OutputToSourceDirectory", false, connection));
     cache.Add("PreserveFolderStructureInBatch", DatabaseConfig.Get("PreserveFolderStructureInBatch", false, connection));
     cache.Add("WhenFileExists", DatabaseConfig.Get("WhenFileExists", "Prompt", connection));
     cache.Add("WhenFileExistsBatch", DatabaseConfig.Get("WhenFileExistsBatch", "AutoRename", connection));
     cache.Add("UseCustomVideoPlayer", DatabaseConfig.Get("UseCustomVideoPlayer", false, connection));
     cache.Add("CustomVideoPlayer", DatabaseConfig.Get("CustomVideoPlayer", "", connection));
     cache.Add("PlaySoundOnCompletion", DatabaseConfig.Get("PlaySoundOnCompletion", false, connection));
     cache.Add("UseCustomCompletionSound", DatabaseConfig.Get("UseCustomCompletionSound", false, connection));
     cache.Add("CustomCompletionSound", DatabaseConfig.Get("CustomCompletionSound", "", connection));
     cache.Add("LastPlayer", DatabaseConfig.Get("LastPlayer", "vlc", connection));
     cache.Add("QueueTitlesUseDirectoryOverride", DatabaseConfig.Get("QueueTitlesUseDirectoryOverride", false, connection));
     cache.Add("QueueTitlesDirectoryOverride", DatabaseConfig.Get("QueueTitlesDirectoryOverride", "", connection));
     cache.Add("QueueTitlesUseNameOverride", DatabaseConfig.Get("QueueTitlesUseNameOverride", false, connection));
     cache.Add("QueueTitlesNameOverride", DatabaseConfig.Get("QueueTitlesNameOverride", "", connection));
     cache.Add("DxvaDecoding", DatabaseConfig.Get("DxvaDecoding", false, connection));
     cache.Add("EnableLibDvdNav", DatabaseConfig.Get("EnableLibDvdNav", true, connection));
     cache.Add("MinimumTitleLengthSeconds", DatabaseConfig.Get("MinimumTitleLengthSeconds", 10, connection));
     cache.Add("DeleteSourceFilesOnClearingCompleted", DatabaseConfig.Get("DeleteSourceFilesOnClearingCompleted", false, connection));
     cache.Add("PreserveModifyTimeFiles", DatabaseConfig.Get("PreserveModifyTimeFiles", false, connection));
     cache.Add("ResumeEncodingOnRestart", DatabaseConfig.Get("ResumeEncodingOnRestart", false, connection));
     cache.Add("UseWorkerProcess", DatabaseConfig.Get("UseWorkerProcess", true, connection));
     cache.Add("RememberPreviousFiles", DatabaseConfig.Get("RememberPreviousFiles", true, connection));
     cache.Add("VideoFileExtensions", DatabaseConfig.Get("VideoFileExtensions", "avi, mkv, mp4, m4v, mpg, mpeg, mov, wmv", connection));
     cache.Add("PreferredPlayer", DatabaseConfig.Get("PreferredPlayer", "vlc", connection));
     cache.Add("BetaUpdates", DatabaseConfig.Get("BetaUpdates", false, connection));
     cache.Add("InterfaceLanguageCode", DatabaseConfig.Get("InterfaceLanguageCode", "", connection));
     cache.Add("AppTheme", DatabaseConfig.Get("AppTheme", "Auto", connection));
     cache.Add("CpuThrottlingFraction", DatabaseConfig.Get("CpuThrottlingFraction", 1.0, connection));
     cache.Add("UseBuiltInPlayerForPreviews", DatabaseConfig.Get("UseBuiltInPlayerForPreviews", true, connection));
     cache.Add("PreviewVolume", DatabaseConfig.Get("PreviewVolume", 0.5, connection));
     cache.Add("AudioLanguageCode", DatabaseConfig.Get("AudioLanguageCode", "und", connection));
     cache.Add("SubtitleLanguageCode", DatabaseConfig.Get("SubtitleLanguageCode", "und", connection));
     cache.Add("AutoAudio", DatabaseConfig.Get("AutoAudio", "Disabled", connection));
     cache.Add("AutoSubtitle", DatabaseConfig.Get("AutoSubtitle", "Disabled", connection));
     cache.Add("AutoAudioAll", DatabaseConfig.Get("AutoAudioAll", false, connection));
     cache.Add("AutoSubtitleAll", DatabaseConfig.Get("AutoSubtitleAll", false, connection));
     cache.Add("AutoSubtitleOnlyIfDifferent", DatabaseConfig.Get("AutoSubtitleOnlyIfDifferent", true, connection));
     cache.Add("AutoSubtitleBurnIn", DatabaseConfig.Get("AutoSubtitleBurnIn", true, connection));
     cache.Add("AutoSubtitleLanguageDefault", DatabaseConfig.Get("AutoSubtitleLanguageDefault", false, connection));
     cache.Add("AutoSubtitleLanguageBurnIn", DatabaseConfig.Get("AutoSubtitleLanguageBurnIn", false, connection));
     cache.Add("QueueTitlesStartTime", DatabaseConfig.Get("QueueTitlesStartTime", 40, connection));
     cache.Add("QueueTitlesEndTime", DatabaseConfig.Get("QueueTitlesEndTime", 45, connection));
     cache.Add("QueueTitlesUseRange", DatabaseConfig.Get("QueueTitlesUseRange", false, connection));
 }
Esempio n. 31
0
 public DatabaseService(DatabaseConfig config)
 {
     _config = config;
 }
Esempio n. 32
0
        private void EstablishConnections()
        {
            foreach (ConnectionConfig connectionConfig in akConfig.Connections)
            {
                LibNoDaveConfig plcConnConf   = connectionConfig as LibNoDaveConfig;
                TCPIPConfig     tcpipConnConf = connectionConfig as TCPIPConfig;
                DatabaseConfig  dbConnConf    = connectionConfig as DatabaseConfig;


                if (plcConnConf != null)
                {
                    Logging.LogText("Connection: " + connectionConfig.Name + " is starting...", Logging.LogLevel.Information);

                    PLCConnection tmpConn = new PLCConnection(plcConnConf.Configuration);
                    try
                    {
                        tmpConn.Connect();
                        if (!plcConnConf.StayConnected)
                        {
                            tmpConn.Disconnect();
                        }
                    }
                    catch (Exception ex)
                    {
                        Logging.LogText("Connection: " + connectionConfig.Name, ex, Logging.LogLevel.Warning);
                    }

                    ConnectionList.Add(connectionConfig, tmpConn);
                }
                else if (dbConnConf != null)
                {
                    var tmpConn = new DatabaseConnection(dbConnConf);
                    try
                    {
                        tmpConn.Connect();
                    }
                    catch (Exception ex)
                    {
                        Logging.LogText("Connection: " + connectionConfig.Name, ex, Logging.LogLevel.Warning);
                    }
                    ConnectionList.Add(connectionConfig, tmpConn);
                }
                else if (tcpipConnConf != null)
                {
                    //todo: legth of tcp conn
                    //TCPFunctionsAsync tmpConn = new TCPFunctionsAsync(new SynchronizationContext(), tcpipConnConf.IPasIPAddres, tcpipConnConf.Port, !tcpipConnConf.PassiveConnection, 0);

                    //tmpConn.Connect();

                    //ConnectionList.Add(connectionConfig, tmpConn);
                }
            }

            myReEstablishConnectionsThreads = new List <Thread>();
            foreach (ConnectionConfig connectionConfig in akConfig.Connections)
            {
                if (connectionConfig is LibNoDaveConfig)
                {
                    var thrd = new Thread(new ParameterizedThreadStart(ReEstablishConnectionsThreadProc))
                    {
                        Name = "EstablishConnectionsThreadProc"
                    };
                    thrd.Start(connectionConfig as LibNoDaveConfig);
                    this.myReEstablishConnectionsThreads.Add(thrd);
                }
            }
        }
Esempio n. 33
0
		public void Backup()
		{
			Log("Backup", "Starting {0} backup to {1}", IsInitialized ? string.Empty : "noninitialized",
				backupDir);
			
			try
			{
				if (!IsInitialized)
				{
					ClearDirectory(backupDir);
				}

				// Get log of last checkpoint for last checkpoint
				int newCheckpointLogNumber = storage.Environment.GetLastCheckpointLogNumber();
				// Get list of unused log files
				unusedLogFiles = storage.Environment.GetUnusedLogFiles();
				Log("Backup", "Old log number = {0}, new = {1}", lastCheckpointLogNumber,
					newCheckpointLogNumber);
				if (unusedLogFiles != null && unusedLogFiles.Count > 0)
				{
					Log("Backup", "{0} unused log files - from {1} to {2}", unusedLogFiles.Count,
						unusedLogFiles[0], unusedLogFiles[unusedLogFiles.Count - 1]);
				   
				}
				

				// get new data files
				List<string> newDataFiles = storage.Environment.GetDataFilesForArchiving();
				if (newDataFiles != null)
				{
					// skip the ones already copied
					for (int idx = newDataFiles.Count - 1; idx >= 0; --idx)
					{
						if (dataFilesCopied.Contains(newDataFiles[idx]))
						{
							newDataFiles.RemoveAt(idx);
						}
					}
					if (newDataFiles.Count > 0)
					{
						DatabaseConfig config = new DatabaseConfig
												{
													Type = DatabaseType.Unknown,
													OpenFlags = DbOpenFlags.ReadOnly,
													Id = -1 // to avoid appending federation index to extension
												};

						if (dataCopyBufferSize > 0)
						{
							if (copyBuffer == null || copyBuffer.Length < dataCopyBufferSize)
							{
								copyBuffer = new byte[dataCopyBufferSize];
							}
						}

						// Copy database files as needed
						foreach (string dataFile in newDataFiles)
						{
							config.FileName = dataFile;
							string backupDataFile = MakeRelativeToNewFolder(backupDir, dataFile);

							using (Database db = storage.Environment.OpenDatabase(config))
							{
								switch (backupMethod)
								{
									case BackupMethod.MpoolFile:
										db.BackupFromMpf(backupDataFile, copyBuffer);
										break;
									case BackupMethod.Fstream:
										db.BackupFromDisk(backupDataFile, copyBuffer);
										break;
									default:
										throw new ArgumentOutOfRangeException(string.Format(
											"Unhandled backup method {0}", backupMethod));
								}
							}

							// Post data file copy ops
							dataFilesCopied.Add(dataFile);
						}
					}
				}


				// Copy log files as needed
				if (copyLogFiles)
				{
					
					List<string> logFiles = storage.Environment.GetAllLogFiles();
					if (logFiles != null)
					{
						if (unusedLogFiles != null)
						{
							// unused log files can be moved
							foreach (string logFile in unusedLogFiles)
							{
								if (File.Exists(logFile))
								{
									string backupLogFile = MakeRelativeToNewFolder(backupDir, logFile);
									if (File.Exists(backupLogFile)) File.Delete(backupLogFile);
									File.Move(logFile, backupLogFile);
									if (!logFilesCopied.Contains(logFile)) logFilesCopied.Add(logFile);
								}
								logFiles.Remove(logFile);
							}
						}
						// remaining log files are in use, so copy them
						foreach(string logFile in logFiles)
						{
							if (!File.Exists(logFile)) continue;
							string backupLogFile = MakeRelativeToNewFolder(backupDir, logFile);
							File.Copy(logFile, backupLogFile, true);
							if (!logFilesCopied.Contains(logFile)) logFilesCopied.Add(logFile);
						}
					}
				}


				// Set post backup values
				lastCheckpointLogNumber = newCheckpointLogNumber;
				lastUpdateTime = DateTime.Now;
				if (!isInitialized)
				{   
					firstBackupTime = lastUpdateTime;
					isInitialized = true;
				}
				LogCompleted("Backup");                
			}
			catch(Exception ex)
			{
				LogError("Backup", ex);                
				throw;
			}
		}