public void Setup() { _databaseName = GetType().Name; _databaseConfigModel = HeartOfGoldController.CreateDatabaseConfig("localhost", _databaseName, "postgres", "postgres"); _hogController = new HeartOfGoldController { RuntimeDir = HogHelper.RuntimeDir, ConfigDir = HogHelper.ConfigDirParam, ExecutionTimeout = 60 }; _targetModel = typeof(TestModelContext).FullName; Console.WriteLine("Starting HeartOfGold"); var started = _hogController.StartApplication(); Assert.IsTrue(started, "Can't start HeartOfGold."); Assert.IsFalse(_hogController.Process.HasExited, "HeartOfGold has exited unexpectedly."); _hogController.CreateClients(); var result = _hogController.WaitForService("Maintenance", ServerModuleState.Running, 10); Assert.IsTrue(result, "Service 'Maintenance' did not reach state 'Running'"); if (_hogController.CheckDatabase(_databaseConfigModel, _targetModel).Result == TestConnectionResult.Success) { result = _hogController.DeleteDatabase(_databaseConfigModel, _targetModel); Assert.IsTrue(result, "Can't delete database '{0}' in Setup.", _databaseName); } }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) { return(null); } var para = (string)parameter; try { dcm = JsonConvert.DeserializeObject <DatabaseConfigModel>((string)value); switch (para.ToLower()) { case "table": return(SystemSettings.DbTables.First(t => t.Name == this.GetValue <string>(dcm, para))); case "column": return(SystemSettings.Columns.First(t => t.Name == this.GetValue <string>(dcm, para))); default: return(null); } } catch { return(null); } }
/// <summary> /// DBインスタンス取得 /// </summary> /// <returns>IDatabasインスタンス</returns> public static IDatabase Create(DatabaseConfigModel config) { IDatabase result = null; var targetDB = config.Target.ToLower(); if (!config.ConnectionStrings.ContainsKey(targetDB)) { throw new Exception($"{targetDB}の接続文字列が定義されていません。"); } var connectionString = config.ConnectionStrings[targetDB]; // DB種類で作成するインスタンスを変える switch (targetDB) { case nameof(DatabaseTypes.sqlite): result = new SQLiteDB(connectionString); break; case nameof(DatabaseTypes.postgres): result = new PostgreSQLDB(connectionString); break; case nameof(DatabaseTypes.sqlserver): result = new SQLServerDB(connectionString); break; default: result = new SQLiteDB(connectionString); break; } return(result); }
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { var data = (ComboBoxItemModel)value; if (dcm is null) { dcm = new DatabaseConfigModel(); } this.SetValue(dcm, (string)parameter, data?.Name); return(JsonConvert.SerializeObject(dcm)); }
public KRNetworkingConfig(bool p_isInstantiation) { if (p_isInstantiation) { DatabaseConfigModel = new DatabaseConfigModel(); PatientMapModel = new PatientMapModel(DatabaseHelper.LocalConnStr); ReportSaveModel = new ReportSaveModel(); DataCallBackModel = new DataCallBackModel(); HttpConfigModel = new HttpConfigModel(); WcfConfigModel = new WcfConfigModel(); } }
/// <summary> /// Deletes the database as defined in the database configuration. /// </summary> /// <param name="databaseConfigModel">The database configuration with the delete information.</param> /// <param name="targetModel">The model name.</param> /// <returns><c>true</c> if the database has been deleted successfully, <c>false</c> if not</returns> public bool DeleteDatabase(DatabaseConfigModel databaseConfigModel, string targetModel) { var result = WaitForServiceCall(() => _databaseClient.EraseDatabase(targetModel, databaseConfigModel)); // result is "" when it was successful. if (result.Success) { return(true); } Console.WriteLine("Database deletion failed with error message: {0}", result.ErrorMessage); return(false); }
/// <summary> /// Backups the database and stores the backup to the ".\Backups\" folder. /// </summary> public InvocationResponse DumpDatabase(DatabaseConfigModel databaseConfigModel, string targetModel) { var result = WaitForServiceCall(() => _databaseClient.DumpDatabase(targetModel, databaseConfigModel)); // result is "" when it was successful. if (result.Success) { return(result); } Console.WriteLine("Database dump failed with error message: {0}", result.ErrorMessage); return(null); }
/// <summary> /// Creates the database configuration. /// </summary> /// <param name="server">The database server address.</param> /// <param name="database">The database name.</param> /// <param name="user">The user name.</param> /// <param name="password">The user password.</param> /// <param name="schema">The schema name.</param> /// <param name="port">The database server port.</param> /// <returns>Created database configuration.</returns> public static DatabaseConfigModel CreateDatabaseConfig(string server, string database, string user, string password, string schema, int port = 5432) { // Initialize the database config var databaseConfigModel = new DatabaseConfigModel { Server = server, Database = database, User = user, Password = password, Port = port }; return(databaseConfigModel); }
/// <summary> /// Executes a database setup /// </summary> public bool ExecuteSetup(DatabaseConfigModel databaseConfigModel, string targetModel, SetupModel setupModel) { var result = WaitForServiceCall(() => _databaseClient.ExecuteSetup(targetModel, new ExecuteSetupRequest { Config = databaseConfigModel, Setup = setupModel })); if (result.Success) { return(true); } Console.WriteLine("Setup execution failed with error message: {0}", result); return(false); }
/// <summary> /// Restores the database. /// </summary> public bool RestoreDatabase(DatabaseConfigModel databaseConfigModel, string targetModel, string databaseFile) { var result = WaitForServiceCall(() => _databaseClient.RestoreDatabase(targetModel, new RestoreDatabaseRequest { BackupFileName = databaseFile, Config = databaseConfigModel })); // result is "" when it was successful. if (result.Success) { return(true); } Console.WriteLine("Database restore failed with error message: {0}", result); return(false); }
/// <summary> /// Save and activates the database configuration. /// The services may restart cause of the changed database configuration! /// </summary> /// <param name="databaseConfigModel">The database configuration to save and activate.</param> /// <param name="targetModel">The model name.</param> public void ActivateDatabase(DatabaseConfigModel databaseConfigModel, string targetModel) { try { // activate the new database. this will reincarnate the services on the heart of gold WaitForServiceCall(() => _databaseClient.SetDatabaseConfig(targetModel, databaseConfigModel)); } catch { // Sometimes there comes an exception because the service has stopped on the HoG } finally { Thread.Sleep(1000); } }
public override void Execute(object parameter) { DatabaseConfigModel dbConfig = NetworkingViewModel.DatabaseConfigModel; bool isSuccess = false; try { DatabaseEnum databaseEnum = DataBaseSoft.TransDatabaseSoft(dbConfig.DatabaseSoft, dbConfig.IsAdvancedSetting); isSuccess = DatabaseHelper.TestConnection(databaseEnum, dbConfig.ConnectionString); } catch (Exception ex) { MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error); return; } if (isSuccess) { MessageBox.Show("连接测试成功!"); } }
/// <summary> /// DBインスタンス取得 /// </summary> /// <returns>IDatabasインスタンス</returns> public static IDatabase Create(DatabaseConfigModel config) { IDatabase result = null; // DB種類で作成するインスタンスを変える switch (config.Type.ToLower()) { case "sqlite": result = new SQLiteDB(config.connectionString); break; case "postgres": result = new PostgreSQLDB(config.connectionString); break; default: result = new SQLiteDB(config.connectionString); break; } return(result); }
public override void Execute(object parameter) { PatientMapModel pmm = NetworkingViewModel.PatientMapModel; try { DatabaseConfigModel dataConfig = NetworkingViewModel.DatabaseConfigModel; string sql = pmm.GetTestPatientInfoSql(dataConfig.DatabaseSoft); DatabaseEnum databaseEnum = DataBaseSoft.TransDatabaseSoft(dataConfig.DatabaseSoft, dataConfig.IsAdvancedSetting); IDatabaseHelper dbHelper = DatabaseHelper.Open(databaseEnum, dataConfig.ConnectionString); DataTable table = dbHelper.ExecuteQuery(sql); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } MessageBox.Show("目标表与字段测试成功!"); }
protected override void ConfigClient() { try { base.ConfigClient(); if (Config == null) { ClientHelper.TraceException("DBClient.ConfigClient", "未能成功加载数据库联网方式联网配置文件", "_config为Null"); } _dbConfig = Config.DatabaseConfigModel; if (_dbConfig == null) { ClientHelper.TraceException("DBClient.ConfigClient", "未能成功加载数据库联网方式联网配置文件", "DatabaseConfigModel为Null"); } _connStr = _dbConfig.ConnectionString; DatabaseEnum databaseEnum = DataBaseSoft.TransDatabaseSoft(_dbConfig.DatabaseSoft, _dbConfig.IsAdvancedSetting); _dbHelper = DatabaseHelper.Open(databaseEnum, _connStr); } catch (KRException ex) { throw new Exception("加载联网配置失败"); } }
public InvocationResponse CreateDatabase(string targetModel, DatabaseConfigModel config) { return(PostAsJson <InvocationResponse>($"models/{targetModel}/create", config)); }
public override void Execute(object parameter) { DatabaseConfigModel dbConfig = NetworkingViewModel.DatabaseConfigModel; DataCallBackModel dcModel = NetworkingViewModel.DataCallBackModel; DatabaseEnum databaseEnum = DataBaseSoft.TransDatabaseSoft(dbConfig.DatabaseSoft, dbConfig.IsAdvancedSetting); IDatabaseHelper db = DatabaseHelper.Open(databaseEnum, dbConfig.ConnectionString); ; string tableName = string.Empty; if (dcModel.CallbackType == "表") { tableName = dcModel.TargetTableName; } else if (dcModel.CallbackType == "存储过程") { tableName = dcModel.TargetProcName; } if (string.IsNullOrEmpty(tableName)) { return; } string sql = string.Empty; if (dbConfig.DatabaseSoft == DatabaseSoft.SQLServer) { sql = string.Format( "SELECT A.NAME,B.NAME AS TYPE,A.LENGTH,A.ISNULLABLE FROM SYSCOLUMNS A,SYSTYPES B,SYSOBJECTS D WHERE A.XTYPE=B.XUSERTYPE AND A.ID=D.ID AND A.ID =OBJECT_ID('{0}')", tableName); } else if (dbConfig.DatabaseSoft == DatabaseSoft.Oracle) { if (dcModel.CallbackType == "表") { sql = string.Format( "SELECT A.COLUMN_NAME AS NAME,A.DATA_TYPE AS TYPE,A.DATA_LENGTH AS LENGTH,A.NULLABLE AS ISNULLABLE FROM USER_TAB_COLS A WHERE UPPER(A.TABLE_NAME) = '{0}'", tableName.ToUpper()); } else { sql = string.Format( "SELECT A.ARGUMENT_NAME AS NAME,A.DATA_TYPE AS TYPE,NVL(A.DATA_LENGTH,0) AS LENGTH, 0 AS ISNULLABLE FROM USER_ARGUMENTS A WHERE UPPER(A.OBJECT_NAME)='{0}' ORDER BY SEQUENCE", tableName.ToUpper()); } } else if (dbConfig.DatabaseSoft == DatabaseSoft.PostgreSQL) { sql = string.Format( "select a.column_name as Name, a.udt_name as TYPE,a.character_maximum_length as LENGTH, a.is_nullable as ISNULLABLE from information_schema.columns a where table_schema='public' and table_name='{0}'", tableName); } else { if (dcModel.CallbackType == "表") { sql = string.Format( "SELECT A.COLUMN_NAME AS NAME, A.DATA_TYPE TYPE,A.COLUMN_TYPE AS LENGTH,A.IS_NULLABLE AS ISNULLABLE FROM INFORMATION_SCHEMA.COLUMNS A WHERE A.TABLE_SCHEMA = '{0}' AND A.TABLE_NAME = '{1}'", dbConfig.Database, tableName); } else { sql = string.Format( "SELECT DB, TYPE, SPECIFIC_NAME, PARAM_LIST, RETURNS FROM MYSQL.PROC A WHERE UPPER(A.SPECIFIC_NAME) = '{0}'", tableName.ToUpper()); } } DataTable table = db.ExecuteQuery(sql); dcModel.CallbackTabelMap.Clear(); if (!(dbConfig.DatabaseSoft == DatabaseSoft.MySql && dcModel.CallbackType == "存储过程")) { var regex = new Regex(@"^\d*$"); foreach (DataRow row in table.AsEnumerable()) { string name = row["NAME"].ToString(); if (string.IsNullOrEmpty(name)) { continue; } int size = -1; string length = row["LENGTH"].ToString(); Match match = regex.Match(length); if (match.Success && !string.IsNullOrEmpty(match.Value)) { size = Convert.ToInt32(match.Value); } var tfmm = new TableFieldMapModel(); tfmm.LocalField = row["NAME"].ToString(); tfmm.Type = row["TYPE"].ToString(); tfmm.TargetField = ""; tfmm.Size = size; dcModel.CallbackTabelMap.Add(tfmm); } } else { DataRow dataRow = table.AsEnumerable().FirstOrDefault(); if (dataRow != null) { var parambytes = dataRow["PARAM_LIST"] as byte[]; var ue = new ASCIIEncoding(); string paramList = ue.GetString(parambytes); if (!string.IsNullOrEmpty(paramList)) { string[] paraml = paramList.Split(new string[1] { "," }, StringSplitOptions.RemoveEmptyEntries); foreach (string param in paraml) { string value = param.Trim(); if (value.StartsWith("OUT")) { continue; } string[] values = value.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries); string name = string.Empty; string type = string.Empty; if (value.StartsWith("IN")) { name = values[1]; type = values[2]; } else { name = values[0]; type = values[1]; } var tfmm = new TableFieldMapModel(); tfmm.LocalField = name; tfmm.Type = type; tfmm.TargetField = ""; tfmm.Size = 0; dcModel.CallbackTabelMap.Add(tfmm); } } } } //NetworkingViewModel.TargetFieldList = list; }
/// <summary> /// Checks if the database already exists. /// </summary> /// <param name="databaseConfigModel">The database configuration to check.</param> /// <param name="targetModel">The model name.</param> /// <returns><c>true</c> if the database exists, <c>false</c> if it do not exist or the connection was not possible.</returns> public TestConnectionResponse CheckDatabase(DatabaseConfigModel databaseConfigModel, string targetModel) { // Check if database already exists return(WaitForServiceCall(() => _databaseClient.TestDatabaseConfig(targetModel, databaseConfigModel))); }
public Task SetAllConfigsAsync(DatabaseConfigModel config) { return(PostAsJsonAsync("configs", config)); }
public Task <InvocationResponse> EraseDatabaseAsync(string targetModel, DatabaseConfigModel config) { return(DeleteAsJsonAsync <InvocationResponse>($"model/{targetModel}", config)); }
public override void Execute(object parameter) { try { DatabaseConfigModel dbConfig = NetworkingViewModel.DatabaseConfigModel; DatabaseEnum databaseEnum = DataBaseSoft.TransDatabaseSoft(dbConfig.DatabaseSoft, dbConfig.IsAdvancedSetting); IDatabaseHelper db = DatabaseHelper.Open(databaseEnum, dbConfig.ConnectionString); ; string sql = null; if (dbConfig.DatabaseSoft == DatabaseSoft.SQLServer) { sql = "select name from sys.databases"; } else if (dbConfig.DatabaseSoft == DatabaseSoft.MySql) { sql = " SHOW DATABASES "; } else if (dbConfig.DatabaseSoft == DatabaseSoft.PostgreSQL) { sql = "SELECT datname FROM pg_database"; } if (sql == null) { return; } DataTable table = db.ExecuteQuery(sql); if (table == null) { return; } var list = new ObservableCollection <string>(); EnumerableRowCollection <string> en = null; if (table.Columns.Contains("datname")) { en = table.AsEnumerable().Select(r => r["datname"].ToString()); } else if (table.Columns.Contains("name")) { en = table.AsEnumerable().Select(r => r["name"].ToString()); } else { en = table.AsEnumerable().Select(r => r["Database"].ToString()); } foreach (string str in en) { if (string.IsNullOrEmpty(str)) { continue; } list.Add(str); } NetworkingViewModel.DatabaseList = list; } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public Task <InvocationResponse> CreateDatabaseAsync(string targetModel, DatabaseConfigModel config) { return(PostAsJsonAsync <InvocationResponse>($"model/{targetModel}/create", config)); }
public InvocationResponse EraseDatabase(string targetModel, DatabaseConfigModel config) { return(DeleteAsJson <InvocationResponse>($"model/{targetModel}", config)); }
public Task <TestConnectionResponse> TestDatabaseConfigAsync(string targetModel, DatabaseConfigModel config) { return(PostAsJsonAsync <TestConnectionResponse>($"model/{targetModel}/config/test", config)); }
public Task <DatabaseUpdateSummary> MigrateDatabaseModelAsync(string targetModel, string migrationName, DatabaseConfigModel config) { throw new System.NotImplementedException(); }
public void SetDatabaseConfig(string targetModel, DatabaseConfigModel config) { PostAsJson($"model/{targetModel}/config", config); }
public TestConnectionResponse TestDatabaseConfig(string targetModel, DatabaseConfigModel config) { return(PostAsJson <TestConnectionResponse>($"models/{targetModel}/config/test", config)); }
public InvocationResponse DumpDatabase(string targetModel, DatabaseConfigModel config) { throw new System.NotImplementedException(); }
public Task SetDatabaseConfigAsync(string targetModel, DatabaseConfigModel config) { return(PostAsJsonAsync($"model/{targetModel}/config", config)); }
public Task <InvocationResponse> RollbackDatabaseAsync(string targetModel, DatabaseConfigModel config) { throw new System.NotImplementedException(); }