private static string CensorConnectionString(string connectionString) { var builder = new DbConnectionStringBuilder { ConnectionString = connectionString }; var keysToMask = new[] { "password", "pwd", "user id", "uid" }; foreach (var key in keysToMask) { if (builder.ContainsKey(key)) { builder[key] = "*****"; } } return(builder.ToString()); }
public DataTable ToDataTable() { #region OleDbプロバイダを利用してテキストファイル(CSV)に接続する. DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb"); using (DbConnection conn = factory.CreateConnection()) { #region テキストファイルに接続する為の接続文字列を構築. // // 基本的にExcelに接続する場合とほぼ同じ要領となる。 // Extended Properties内のISAMドライバがExcel 12.0からtextになる。 // また、フォーマット方式を指定する必要がある。 // // Data Sourceに指定するのは、該当ファイルが存在するディレクトリを指定する。 // 尚、該当ファイルの構造については別途schema.iniファイルを同じディレクトリに // 用意する必要がある。 // DbConnectionStringBuilder builder = factory.CreateConnectionStringBuilder(); builder["Provider"] = "Microsoft.ACE.OLEDB.12.0"; builder["Data Source"] = System.IO.Path.GetDirectoryName(FilePath); // // UTF8 builder["Extended Properties"] = String.Format("text;CharacterSet=65001;HDR={0};FMT=Delimited", HasHeaderRecord ? "YES" : "NO"); #endregion conn.ConnectionString = builder.ToString(); conn.Open(); // // SELECT. // FROM句の中に読み込む対象のファイル名を指定する。 // データが取得される際にschema.iniファイルが参照され、列定義が行われる。 // using (DbCommand command = conn.CreateCommand()) { command.CommandText = String.Format("SELECT * FROM [{0}]", System.IO.Path.GetFileName(FilePath)); var table = new DataTable(); using (DbDataReader reader = command.ExecuteReader()) { table.Load(reader); } return(table); } } #endregion }
/// <summary> /// Required MetaStack database in sql server /// </summary> public ORMDBTest() { _services = Program.GetServices(); _logger = _services .GetRequiredService <ILoggerProvider>() .CreateLogger("ORMDBTest"); var mdbTest = new MetaStack.Test.Data.MdbContextTest(); _cn = mdbTest.connectionString; DbConnectionStringBuilder sb = new DbConnectionStringBuilder { ConnectionString = _cn }; sb["Initial Catalog"] = "MetaStack"; _cn = sb.ToString(); }
private void initialize(string path, bool hasHeaders, bool hasMixedData) { string fullPath = Path.GetFullPath(path); string extension = Path.GetExtension(path); if (!File.Exists(fullPath)) { throw new FileNotFoundException(String.Format("File could not be found: {0}", fullPath), fullPath); } string tempFileName = Path.GetTempFileName(); File.Copy(fullPath, tempFileName, true); // Reader Settings HasHeaders = hasHeaders; HasMixedData = hasMixedData; switch (extension) { case ".xls": Version = "Excel 8.0"; break; // Excel 95-2003 case ".xlsx": Version = "Excel 12.0"; break; // Excel 2007+ default: throw new ArgumentException("File type could not be determined by file extension.", "path"); } if (IntPtr.Size == 4 && extension == ".xls") { Provider = "Microsoft.Jet.OLEDB.4.0"; // for x86/95-2003 } else { Provider = "Microsoft.ACE.OLEDB.12.0"; // for x64/95-2007+ } var strBuilder = new DbConnectionStringBuilder(); strBuilder.Add("Provider", Provider); strBuilder.Add("Data Source", tempFileName); strBuilder.Add("Extended Properties", Version + ";" + "HDR=" + (HasHeaders ? "Yes" : "No") + ';' + "Imex=" + (HasMixedData ? "2" : "0") + ';'); strConnection = strBuilder.ToString(); }
public string GetConnectionString() { var csb = new DbConnectionStringBuilder(); switch (AuthType) { default: csb["AuthType"] = "AD"; break; case AuthenticationProviderType.OnlineFederation: csb["AuthType"] = "Office365"; break; case AuthenticationProviderType.Federation: csb["AuthType"] = "IFD"; break; } csb["Url"] = WebApplicationUrl; if (!string.IsNullOrEmpty(UserDomain)) { csb["Domain"] = UserDomain; } csb["Username"] = UserName; csb["Password"] = "******"; if (!string.IsNullOrEmpty(HomeRealmUrl)) { csb["HomeRealmUri"] = HomeRealmUrl; } if (UseMfa) { csb["AuthType"] = "OAuth"; csb["ClientId"] = AzureAdAppId.ToString("B"); csb["LoginPrompt"] = "Auto"; csb["RedirectUri"] = ReplyUrl; csb["TokenCacheStorePath"] = Path.Combine(Path.GetTempPath(), ConnectionId.Value.ToString("B"), "oauth-cache.txt"); } return(csb.ToString()); }
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string)) { // Mask password if present: if (value != null && TryGetPassword(value.ToString(), out string key, out string password)) { var csb = new DbConnectionStringBuilder(); csb.ConnectionString = value.ToString(); csb[key] = "********"; return(csb.ToString()); } return(value); } else { return(base.ConvertTo(context, culture, value, destinationType)); } }
private string ReplaceDatabaseNameOnConnectionString(string newDbName, string connectionString, string connectionStringDatabaseKey) { Dictionary <string, string> connectionStringParts = this.GetConnectionStringParts(connectionString); if (!connectionStringParts.TryGetValue(connectionStringDatabaseKey, out _)) { throw new KeyNotFoundException($"The connection string database key of {connectionStringDatabaseKey} does not exist in the connection string."); } connectionStringParts[connectionStringDatabaseKey] = newDbName; var connectionStringBuilder = new DbConnectionStringBuilder(); foreach (KeyValuePair <string, string> element in connectionStringParts) { connectionStringBuilder[element.Key] = element.Value; } return(connectionStringBuilder.ToString()); }
/// <summary> /// First time database initialization. /// </summary> /// <param name="database">The database.</param> /// <param name="databaseRaw">Raw bytes of database file.</param> /// <param name="init">Initialization callback.</param> /// <returns>Path to the database file.</returns> public static string FirstTimeInit(this Database database, byte[] databaseRaw, Action <Database> init = null) { if (database == null) { throw new ArgumentNullException(nameof(database)); } if (databaseRaw == null) { throw new ArgumentNullException(nameof(databaseRaw)); } var conStr = new DbConnectionStringBuilder { ConnectionString = database.ConnectionString }; var dbFile = (string)conStr.Cast <KeyValuePair <string, object> >().ToDictionary(StringComparer.InvariantCultureIgnoreCase).TryGetValue("Data Source"); if (dbFile == null) { return(null); } dbFile = dbFile.ToFullPathIfNeed(); conStr["Data Source"] = dbFile; database.ConnectionString = conStr.ToString(); dbFile.CreateDirIfNotExists(); if (!File.Exists(dbFile)) { databaseRaw.Save(dbFile); UpdateDatabaseWalMode(database); init?.Invoke(database); } return(dbFile); }
/// <summary> /// 根据配置数据库配置名称生成Database对象 /// </summary> /// <returns></returns> public static Database CreateDatabase() { Database db = null; //if (string.IsNullOrEmpty(dbConfigName)) //{ // db = DatabaseFactory.CreateDatabase(); //} //else //{ // db = DatabaseFactory.CreateDatabase(dbConfigName); //} DbConnectionStringBuilder sb = db.DbProviderFactory.CreateConnectionStringBuilder(); sb.ConnectionString = GetConnectionString(); GenericDatabase newDb = new GenericDatabase(sb.ToString(), db.DbProviderFactory); db = newDb; return(db); }
private void Prepare() { var database = Storage as Database; if (database == null || !(database.Provider is SQLiteDatabaseProvider)) { return; } var conStr = new DbConnectionStringBuilder { ConnectionString = database.ConnectionString }; var file = (string)conStr["Data Source"]; file = file.Replace("%Documents%", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)); file.CreateDirIfNotExists(); var isNew = false; if (!File.Exists(file)) { Resources.StockSharp.Save(file); isNew = true; } conStr["Data Source"] = file; database.ConnectionString = conStr.ToString(); if (isNew) { UpdateDatabaseVersion(); UpdateDatabaseWalMode(); } else { TryUpdateDatabaseVersion(); } }
/// <summary> /// 根据配置数据库配置名称生成Database对象 /// </summary> /// <returns></returns> protected override Database CreateDatabase() { Database db = null; if (string.IsNullOrEmpty(dbConfigName)) { db = DatabaseFactory.CreateDatabase(); } else { db = DatabaseFactory.CreateDatabase(dbConfigName); } DbConnectionStringBuilder sb = db.DbProviderFactory.CreateConnectionStringBuilder(); sb.ConnectionString = GetConnectionString(dbConfigName); GenericDatabase newDb = new GenericDatabase(sb.ToString(), db.DbProviderFactory); db = newDb; return(db); }
/// <summary> /// Creates an ADO connection and enlists it in the specified transaction. /// </summary> /// <param name="transaction"></param> /// <returns></returns> public DbConnection CreateEnlistedConnection(Transaction transaction) { DbConnectionStringBuilder dbConnectionStringBuilder = dbProviderFactory.CreateConnectionStringBuilder(); dbConnectionStringBuilder.ConnectionString = connectionStringSettings.ConnectionString; // make sure the connection isn't enlisted by default if (dbConnectionStringBuilder.ContainsKey("enlist")) { dbConnectionStringBuilder.Remove("enlist"); } AddEnlistToConnectionString(dbConnectionStringBuilder); DbConnection dbConnection = dbProviderFactory.CreateConnection(); // enlist the connection in the specified transaction dbConnection.ConnectionString = dbConnectionStringBuilder.ToString(); dbConnection.Open(); dbConnection.EnlistTransaction(transaction); return(dbConnection); }
private void Connect() { if (this._conn != null && this._conn.State == ConnectionState.Open) { return; } if (this._conn != null) { this.Release(); } _factory = DbProviderFactories.GetFactory("System.Data.OleDb"); this._conn = _factory.CreateConnection(); DbConnectionStringBuilder builder = _factory.CreateConnectionStringBuilder(); builder["Provider"] = "Microsoft.ACE.OLEDB.12.0"; //builder["Provider"] = "Microsoft.Jet.OLEDB.4.0;"; builder["Data Source"] = this._dataSource; builder["Extended Properties"] = "Excel 12.0;HDR=YES;"; this._conn.ConnectionString = builder.ToString(); this._conn.Open(); }
private static string ParseConnectionString(string connectionString, ref string providerName) { if (string.IsNullOrEmpty(connectionString)) { return(connectionString); } var builder = new DbConnectionStringBuilder { ConnectionString = connectionString }; // Replace data directory placeholder const string attachDbFileNameKey = "AttachDbFileName"; const string dataDirectoryPlaceholder = "|DataDirectory|"; if (builder.TryGetValue(attachDbFileNameKey, out var attachDbFileNameValue) && attachDbFileNameValue is string attachDbFileName && attachDbFileName.Contains(dataDirectoryPlaceholder)) { var dataDirectory = AppDomain.CurrentDomain.GetData("DataDirectory")?.ToString(); if (!string.IsNullOrEmpty(dataDirectory)) { builder[attachDbFileNameKey] = attachDbFileName.Replace(dataDirectoryPlaceholder, dataDirectory); // Mutate the existing connection string (note: the builder also lowercases the properties) connectionString = builder.ToString(); } } // Also parse provider name now we already have a builder if (string.IsNullOrEmpty(providerName)) { providerName = ParseProviderName(builder); } return(connectionString); }
private static void Main() { string connectionString = "Server=main-database-1.postgres.database.azure.com;" + "Database=r51;" + "Port=5432;" + "User Id=database_admin@main-database-1;" + "Password=osj29209gf1-bkhE;" + "Ssl Mode=Require;"; var conStrBuilder = new DbConnectionStringBuilder { { "Server", "main-database-1.postgres.database.azure.com" }, { "Database", "main-database-1" }, { "Port", 5432 }, { "User Id", "database_admin@main-database-1" }, { "Password", "osj29209gf1-bkhE" }, { "Ssl Mode", "Require" } }; Console.WriteLine(connectionString); Console.WriteLine(conStrBuilder.ToString()); // DbContextOptionsBuilder<ApplicationDbContext> builder = new DbContextOptionsBuilder<ApplicationDbContext>(); // builder.UseNpgsql(connectionString); // ApplicationDbContext dbContext = new ApplicationDbContext(builder.Options); // dbContext.Accounts.Add(new Account() // { // Username = "******", // ServiceId = "asofjbna'sbnj", // RegistrationDateTime = DateTime.Now // }); // dbContext.SaveChanges(); // int count = dbContext.Accounts.Count(); // Console.WriteLine(count); // // Console.WriteLine("end"); }
/// <summary> /// /// </summary> /// <param name="factory"></param> /// <param name="configuration"></param> /// <returns></returns> private static string GetConnectionString(DbProviderFactory factory, DatabaseConfigurationInfo configuration) { string result = null; DbConnectionStringBuilder connectionStringBuilder = factory.CreateConnectionStringBuilder(); if (connectionStringBuilder != null) { switch (configuration.Provider) { case DatabaseTypeCode.SqlServer: connectionStringBuilder.Add("Data Source", configuration.Server); connectionStringBuilder.Add("Initial Catalog", configuration.Database); connectionStringBuilder.Add("User ID", configuration.UserName); connectionStringBuilder.Add("Password", configuration.Password); break; case DatabaseTypeCode.Oracle: connectionStringBuilder.Add("Data Source", configuration.Server); connectionStringBuilder.Add("User ID", configuration.UserName); connectionStringBuilder.Add("Password", configuration.Password); break; case DatabaseTypeCode.MySql: connectionStringBuilder.Add("Server", configuration.Server); connectionStringBuilder.Add("Database", configuration.Database); connectionStringBuilder.Add("User ID", configuration.UserName); connectionStringBuilder.Add("Password", configuration.Password); break; } result = connectionStringBuilder.ToString(); } return(result); }
public ConnectInfo(string connectionString) { if (_csCache.TryGetValue(connectionString, out ConnectInfo connectInfo)) { ConnectionString = connectInfo.ConnectionString; ProviderName = connectInfo.ProviderName; DbName = connectInfo.DbName; } else { DbConnectionStringBuilder sb = new DbConnectionStringBuilder { ConnectionString = connectionString }; if (!sb.ContainsKey(ProviderNameField)) { ProviderName = ProviderNameDefault; ConnectionString = connectionString; } else { ProviderName = (string)sb[ProviderNameField]; sb.Remove(ProviderNameField); ConnectionString = sb.ToString(); } if (sb.ContainsKey(DbNameField)) { DbName = (string)sb[DbNameField]; } if (!_csCache.ContainsKey(connectionString)) { _csCache.TryAdd(connectionString, this); } } SchemaSupport = true; }
/// <summary> /// Strips out the database instance name from a connectionString. /// </summary> /// <param name="connectionString">The connection string.</param> /// <param name="dbName">Name of the db.</param> /// <returns>The newly created connection string.</returns> private static string _StripDbName(string connectionString, string providerName, out string dbName, out string dbFile) { var builder = new DbConnectionStringBuilder { ConnectionString = connectionString }; string dbname = null, dbfile = null; object tmp; // SQLServer.. minimal option.. if (builder.TryGetValue("Initial Catalog", out tmp)) { dbname = tmp.ToString(); builder.Remove("Initial Catalog"); } // SQLServer default option.. if (builder.TryGetValue("Database", out tmp)) { dbname = tmp.ToString(); builder.Remove("Database"); } // SQLite! (XXX: MsSql has 'Data Source' as a means to specify Server address) if ((providerName == SQLiteProvider || providerName == SqlCe) && builder.TryGetValue("Data Source", out tmp)) { dbname = tmp.ToString(); builder.Remove("Data Source"); } // SQLServer (auto attach alternate) if (builder.TryGetValue("AttachDBFileName", out tmp)) { dbfile = tmp.ToString(); // Replace |DataDirectory| in connection string. dbfile = dbfile.Replace("|DataDirectory|", AppDomain.CurrentDomain.GetData("DataDirectory") as string); builder.Remove("AttachDBFileName"); } // Oracle SID if (providerName == OracleDataProvider && builder.TryGetValue("Data Source", out tmp)) { string connStr = tmp.ToString().Replace(" ", "").Replace("\r", "").Replace("\n", ""); Match match = Regex.Match(connStr, @"SERVICE_NAME=([^\)]+)"); if (match.Success) { dbname = match.Groups[1].Value; } // Try EZ-Connect method.. if (string.IsNullOrEmpty(dbname)) { match = Regex.Match(connStr, ".*/([^$]*)$"); if (match.Success) { dbname = match.Groups[1].Value; } } } // If no database is specified at connStr, throw error.. if (string.IsNullOrEmpty(dbname) && string.IsNullOrEmpty(dbfile)) { throw new ArgumentException("ConnectionString should specify a database name or file"); } // If not catalog nor database name passed, try to obtain it from db file path. if (string.IsNullOrEmpty(dbname)) { dbname = dbfile; } // Save return values.. dbName = dbname; dbFile = dbfile; return(builder.ToString()); }
private void BuildSitesList() { try { List <QMSite> newSites = new List <QMSite>(); string basepaths = ""; string sNTUserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; RegistryKey rk = Registry.LocalMachine.OpenSubKey(const_subKey); if (rk != null) { string[] m_sBasePathSubkeys = rk.GetSubKeyNames(); rk.Close(); foreach (string sBasePath in m_sBasePathSubkeys) { string basePath = sBasePath.Trim(); try { if (!string.IsNullOrEmpty(basePath)) { rk = Registry.LocalMachine.OpenSubKey(const_subKey + basePath); if (rk != null) { QMSite site = null; if (rk.GetValue("QMActive", "no").ToString().ToLower() == "yes") { site = new QMSite(); site.basePath = basePath; var dbConnectionStringBuilder = new DbConnectionStringBuilder { ConnectionString = rk.GetValue("ConnectionString", string.Empty).ToString().Trim() }; dbConnectionStringBuilder.Remove("Provider"); site.connection = dbConnectionStringBuilder.ToString(); site.pid = rk.GetValue("PID", string.Empty).ToString().Trim(); site.cn = rk.GetValue("CN", string.Empty).ToString().Trim(); int nDefaultTraceChannels = 0; Int32.TryParse(rk.GetValue("Trace", 0).ToString(), out nDefaultTraceChannels); site.ActiveTraceChannels = nDefaultTraceChannels.ToString(); } rk.Close(); if (site != null) { using (var m_oConnection = new SqlConnection()) { m_oConnection.ConnectionString = site.connection + ";Application Name=PfEQueueManager"; m_oConnection.Open(); using (SqlCommand cmd = new SqlCommand("SELECT WRES_ID,RES_NAME,WRES_TRACE FROM EPG_RESOURCES WHERE WRES_CAN_LOGIN = 1 AND WRES_USE_NT_LOGON = 1 AND WRES_NT_ACCOUNT=@WRES_NT_ACCOUNT", m_oConnection)) { cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@WRES_NT_ACCOUNT", sNTUserName.ToLower()); using (SqlDataReader reader = cmd.ExecuteReader()) { if (reader != null) { if (reader.Read()) { site.WRES_ID = reader["WRES_ID"].ToString(); site.userName = reader["RES_NAME"].ToString(); site.NTAccount = sNTUserName.ToLower(); site.SessionInfo = Guid.NewGuid().ToString().ToUpper(); } } } } } newSites.Add(site); if (!string.IsNullOrEmpty(basepaths)) { basepaths += ","; } basepaths += basePath.Trim(); } } } } catch (Exception ex) { ExceptionHandler("BuildSitesList for basepath '" + basePath + "'", ex); } } } lock (sitesLock) { m_sites = newSites; m_basepaths = basepaths; } } catch (Exception ex) { ExceptionHandler("BuildSitesList", ex); } }
void DetectSqlServer(Object state) { var item = (String)state; try { var dal = DAL.Create(item); if (dal.DbType != DatabaseType.SqlServer) { return; } var sw = Stopwatch.StartNew(); DataTable dt = null; // 列出所有数据库 //Boolean old = DAL.ShowSQL; //DAL.ShowSQL = false; //try //{ if (dal.Db.CreateMetaData().MetaDataCollections.Contains("Databases")) { dt = dal.Db.CreateSession().GetSchema(null, "Databases", null); } //} //finally { DAL.ShowSQL = old; } if (dt == null) { return; } var dbprovider = dal.DbType.ToString(); var builder = new DbConnectionStringBuilder { ConnectionString = dal.ConnStr }; // 统计库名 var n = 0; var names = new List <String>(); var sysdbnames = new String[] { "master", "tempdb", "model", "msdb" }; foreach (DataRow dr in dt.Rows) { var dbname = dr[0].ToString(); if (Array.IndexOf(sysdbnames, dbname) >= 0) { continue; } var connName = String.Format("{0}_{1}", item, dbname); builder["Database"] = dbname; DAL.AddConnStr(connName, builder.ToString(), null, dbprovider); n++; try { var ver = dal.Db.ServerVersion; names.Add(connName); } catch { if (DAL.ConnStrs.ContainsKey(connName)) { DAL.ConnStrs.Remove(connName); } } } sw.Stop(); XTrace.WriteLine("发现远程数据库{0}个,耗时:{1}!", n, sw.Elapsed); if (names != null && names.Count > 0) { var list = new List <String>(); foreach (var elm in DAL.ConnStrs) { if (!String.IsNullOrEmpty(elm.Value)) { list.Add(elm.Key); } } list.AddRange(names); this.Invoke(SetDatabaseList, list); } } catch { //if (item == localName) DAL.ConnStrs.Remove(localName); } }
void AutoDetectDatabase() { var list = new List <String>(); // 加上本机MSSQL String localName = "local_MSSQL"; String localstr = "Data Source=.;Initial Catalog=master;Integrated Security=True;"; if (!ContainConnStr(localstr)) { DAL.AddConnStr(localName, localstr, null, "mssql"); } var sw = new Stopwatch(); sw.Start(); #region 检测本地Access和SQLite var n = 0; String[] ss = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.*", SearchOption.TopDirectoryOnly); foreach (String item in ss) { String ext = Path.GetExtension(item); if (String.Equals(ext, ".exe", StringComparison.OrdinalIgnoreCase)) { continue; } if (String.Equals(ext, ".dll", StringComparison.OrdinalIgnoreCase)) { continue; } if (String.Equals(ext, ".zip", StringComparison.OrdinalIgnoreCase)) { continue; } if (String.Equals(ext, ".rar", StringComparison.OrdinalIgnoreCase)) { continue; } if (String.Equals(ext, ".txt", StringComparison.OrdinalIgnoreCase)) { continue; } if (String.Equals(ext, ".config", StringComparison.OrdinalIgnoreCase)) { continue; } try { if (DetectFileDb(item)) { n++; } } catch (Exception ex) { XTrace.WriteException(ex); } } #endregion sw.Stop(); XTrace.WriteLine("自动检测文件{0}个,发现数据库{1}个,耗时:{2}!", ss.Length, n, sw.Elapsed); foreach (var item in DAL.ConnStrs) { if (!String.IsNullOrEmpty(item.Value.ConnectionString)) { list.Add(item.Key); } } // 远程数据库耗时太长,这里先列出来 this.Invoke(new Action <List <String> >(SetDatabaseList), list); //!!! 必须另外实例化一个列表,否则作为数据源绑定时,会因为是同一个对象而被跳过 list = new List <String>(list); sw.Reset(); sw.Start(); #region 探测连接中的其它库 var sysdbnames = new String[] { "master", "tempdb", "model", "msdb" }; n = 0; var names = new List <String>(); foreach (var item in list) { try { var dal = DAL.Create(item); if (dal.DbType != DatabaseType.SqlServer) { continue; } DataTable dt = null; String dbprovider = null; // 列出所有数据库 Boolean old = DAL.ShowSQL; DAL.ShowSQL = false; try { if (dal.Db.CreateMetaData().MetaDataCollections.Contains("Databases")) { dt = dal.Db.CreateSession().GetSchema("Databases", null); dbprovider = dal.DbType.ToString(); } } finally { DAL.ShowSQL = old; } if (dt == null) { continue; } var builder = new DbConnectionStringBuilder(); builder.ConnectionString = dal.ConnStr; // 统计库名 foreach (DataRow dr in dt.Rows) { String dbname = dr[0].ToString(); if (Array.IndexOf(sysdbnames, dbname) >= 0) { continue; } String connName = String.Format("{0}_{1}", item, dbname); builder["Database"] = dbname; DAL.AddConnStr(connName, builder.ToString(), null, dbprovider); n++; try { String ver = dal.Db.ServerVersion; names.Add(connName); } catch { if (DAL.ConnStrs.ContainsKey(connName)) { DAL.ConnStrs.Remove(connName); } } } } catch { if (item == localName) { DAL.ConnStrs.Remove(localName); } } } #endregion sw.Stop(); XTrace.WriteLine("发现远程数据库{0}个,耗时:{1}!", n, sw.Elapsed); if (DAL.ConnStrs.ContainsKey(localName)) { DAL.ConnStrs.Remove(localName); } if (list.Contains(localName)) { list.Remove(localName); } if (names != null && names.Count > 0) { list.AddRange(names); this.Invoke(new Action <List <String> >(SetDatabaseList), list); } }
public void Save() { string dataSource = DataSource; string sheetName = SheetName; Action <DataTable, object> edit = EditTable; DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb"); using (DbConnection conn = factory.CreateConnection()) { #region // // Excel用の接続文字列を構築. // // Providerは、Microsoft.ACE.OLEDB.12.0を使用する事。 // (JETドライバを利用するとxlsxを読み込む事が出来ない。) // // Extended Propertiesには、ISAMのバージョン(Excel 12.0)とHDRを指定する。 // (2003までのxlsの場合はExcel 8.0でISAMバージョンを指定する。) // HDRは先頭行をヘッダ情報としてみなすか否かを指定する。 // 先頭行をヘッダ情報としてみなす場合はYESを、そうでない場合はNOを設定。 // // HDR=NOと指定した場合、カラム名はシステム側で自動的に割り振られる。 // (F1, F2, F3.....となる) // #endregion DbConnectionStringBuilder builder = factory.CreateConnectionStringBuilder(); builder["Provider"] = "Microsoft.ACE.OLEDB.12.0"; builder["Data Source"] = dataSource; builder["Extended Properties"] = "Excel 12.0;HDR=YES"; conn.ConnectionString = builder.ToString(); conn.Open(); #region // // SELECT. // // 通常のSQLのように発行できる。その際シート指定は // [Sheet1$]のように行う。範囲を指定することも出来る。[Sheet1$A1:C7] // ------------------------------------------------------------------- // INSERT // // こちらも普通のSQLと同じように発行できる。 // 尚、トランザクションは設定できるが効果は無い。 // (ロールバックを行ってもデータは戻らない。) // // また、INSERT,UPDATEはエクセルを開いた状態でも // 行う事ができる。 // // データの削除は行う事ができない。(制限) // #endregion using (DbCommand command = factory.CreateCommand()) { var tableName = sheetName; var selectQueryString = String.Format("SELECT * FROM [{0}$]", sheetName); command.CommandText = selectQueryString; command.Connection = conn; // Create the DbDataAdapter. DbDataAdapter adapter = factory.CreateDataAdapter(); adapter.SelectCommand = command; // Create the DbCommandBuilder. DbCommandBuilder cmdBuilder = factory.CreateCommandBuilder(); cmdBuilder.DataAdapter = adapter; if (!String.IsNullOrEmpty(InsertSql)) { var insertCommand = factory.CreateCommand(); insertCommand.CommandText = InsertSql; adapter.InsertCommand = insertCommand; foreach (var item in InsertCommandParameters) { adapter.InsertCommand.Parameters.Add(item); } } var data = new DataSet(); adapter.Fill(data, tableName); Console.WriteLine(data.Tables[tableName].Rows.Count); edit?.Invoke(data.Tables[tableName], Arg); //データベース更新 var updatedRowCount = adapter.Update(data, tableName); //データ更新終了をDataTableに伝える data.AcceptChanges(); Console.WriteLine("更新された行数: " + updatedRowCount); } } }
static void DetectMySql(String item, Action callback) { try { var dal = DAL.Create(item); if (dal.DbType != DatabaseType.MySql) { return; } var sw = Stopwatch.StartNew(); // 列出所有数据库 DataTable dt = null; if (dal.Db.CreateMetaData().MetaDataCollections.Contains("Databases")) { dt = dal.Db.CreateSession().GetSchema(null, "Databases", null); } if (dt == null) { return; } var dbprovider = dal.DbType.ToString(); var builder = new DbConnectionStringBuilder { ConnectionString = dal.ConnStr }; // 统计库名 var n = 0; var names = new List <String>(); var sysdbnames = new String[] { "mysql" }; foreach (DataRow dr in dt.Rows) { var dbname = dr["database_name"].ToString(); if (Array.IndexOf(sysdbnames, dbname) >= 0) { continue; } var connName = String.Format("{0}_{1}", item, dbname); builder["Database"] = dbname; DAL.AddConnStr(connName, builder.ToString(), null, dbprovider); n++; try { var ver = dal.Db.ServerVersion; names.Add(connName); } catch { if (DAL.ConnStrs.ContainsKey(connName)) { DAL.ConnStrs.Remove(connName); } } } sw.Stop(); XTrace.WriteLine("发现远程数据库{0}个,耗时:{1}!", n, sw.Elapsed); if (names != null && names.Count > 0) { //var list = new List<String>(); //foreach (var elm in DAL.ConnStrs) //{ // if (!String.IsNullOrEmpty(elm.Value)) list.Add(elm.Key); //} //list.AddRange(names); //this.Invoke(SetDatabaseList, list); callback(); } } catch { //if (item == localName) DAL.ConnStrs.Remove(localName); } }
public async Task InitializeAsync() { var images = await Client.Images.ListImagesAsync(new ImagesListParameters { Filters = new Dictionary <string, IDictionary <string, bool> > { { "reference", new Dictionary <string, bool> { { SqlServerImageName, true } } } } }); if (images.Count == 0) { await Client.Images.CreateImageAsync( new ImagesCreateParameters { FromImage = ImageName, Tag = Tag }, null, new Progress <JSONMessage>(message => { Console.WriteLine(!string.IsNullOrEmpty(message.ErrorMessage) ? message.ErrorMessage : $"{message.ID} {message.Status} {message.ProgressMessage}"); })); } var sqlServerHostPort = ThreadLocalRandom.Current.Next(9000, 10000); // create the container await Client.Containers.CreateContainerAsync(new CreateContainerParameters { Image = SqlServerImageName, Name = SqlContainerName, Tty = true, ExposedPorts = new Dictionary <string, EmptyStruct> { { "1433/tcp", new EmptyStruct() } }, HostConfig = new HostConfig { PortBindings = new Dictionary <string, IList <PortBinding> > { { "1433/tcp", new List <PortBinding> { new PortBinding { HostPort = $"{sqlServerHostPort}" } } } } }, Env = new[] { "ACCEPT_EULA=Y", "SA_PASSWORD=l0lTh1sIsOpenSource" } }); // start the container await Client.Containers.StartContainerAsync(SqlContainerName, new ContainerStartParameters()); // Provide a 30 second startup delay await Task.Delay(TimeSpan.FromSeconds(30)); var connectionString = new DbConnectionStringBuilder { ConnectionString = "data source=.;database=akka_persistence_tests;user id=sa;password=l0lTh1sIsOpenSource" }; connectionString["Data Source"] = $"localhost,{sqlServerHostPort}"; ConnectionString = connectionString.ToString(); }
void IProvider.CreateDatabase() { var SqlBuilder = new SqlBuilder(SqlIdentifier); object obj3; CheckDispose(); CheckInitialized(); string databaseName = null; string str2 = null; var builder = new DbConnectionStringBuilder(); builder.ConnectionString = conManager.Connection.ConnectionString; if (conManager.Connection.State != ConnectionState.Closed) { object obj4; if ((Mode == ProviderMode.SqlCE) && File.Exists(this.dbName)) { throw Error.CreateDatabaseFailedBecauseSqlCEDatabaseAlreadyExists(this.dbName); } if (builder.TryGetValue("Initial Catalog", out obj4)) { databaseName = obj4.ToString(); } if (builder.TryGetValue("Database", out obj4)) { databaseName = obj4.ToString(); } if (builder.TryGetValue("AttachDBFileName", out obj4)) { str2 = obj4.ToString(); } goto Label_01D2; } if (Mode == ProviderMode.SqlCE) { if (!File.Exists(this.dbName)) { Type type = conManager.Connection.GetType().Module.GetType("System.Data.SqlServerCe.SqlCeEngine"); object target = Activator.CreateInstance(type, new object[] { builder.ToString() }); try { type.InvokeMember("CreateDatabase", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, target, new object[0], CultureInfo.InvariantCulture); goto Label_0153; } catch (TargetInvocationException exception) { throw exception.InnerException; } finally { IDisposable disposable = target as IDisposable; if (disposable != null) { disposable.Dispose(); } } } throw Error.CreateDatabaseFailedBecauseSqlCEDatabaseAlreadyExists(this.dbName); } if (builder.TryGetValue("Initial Catalog", out obj3)) { databaseName = obj3.ToString(); builder.Remove("Initial Catalog"); } if (builder.TryGetValue("Database", out obj3)) { databaseName = obj3.ToString(); builder.Remove("Database"); } if (builder.TryGetValue("AttachDBFileName", out obj3)) { str2 = obj3.ToString(); builder.Remove("AttachDBFileName"); } Label_0153: conManager.Connection.ConnectionString = builder.ToString(); Label_01D2: if (string.IsNullOrEmpty(databaseName)) { if (string.IsNullOrEmpty(str2)) { if (string.IsNullOrEmpty(this.dbName)) { throw Error.CouldNotDetermineCatalogName(); } databaseName = this.dbName; } else { databaseName = Path.GetFullPath(str2); } } conManager.UseConnection(this); conManager.AutoClose = false; try { if (services.Model.GetTables().FirstOrDefault() == null) { throw Error.CreateDatabaseFailedBecauseOfContextWithNoTables(services.Model.DatabaseName); } deleted = false; if (Mode == ProviderMode.SqlCE) { foreach (MetaTable table in services.Model.GetTables()) { string createTableCommand = SqlBuilder.GetCreateTableCommand(table); if (!string.IsNullOrEmpty(createTableCommand)) { ExecuteCommand(createTableCommand); } } foreach (MetaTable table2 in services.Model.GetTables()) { foreach (string str4 in SqlBuilder.GetCreateForeignKeyCommands(table2)) { if (!string.IsNullOrEmpty(str4)) { ExecuteCommand(str4); } } } } else { string command = SqlBuilder.GetCreateDatabaseCommand(databaseName, str2, Path.ChangeExtension(str2, ".ldf")); ExecuteCommand(command); conManager.Connection.ChangeDatabase(databaseName); if (Mode == ProviderMode.Sql2005) { var set = new HashSet <string>(); foreach (MetaTable table3 in services.Model.GetTables()) { string createSchemaForTableCommand = SqlBuilder.GetCreateSchemaForTableCommand(table3); if (!string.IsNullOrEmpty(createSchemaForTableCommand)) { set.Add(createSchemaForTableCommand); } } foreach (string str7 in set) { ExecuteCommand(str7); } } var builder2 = new StringBuilder(); foreach (MetaTable table4 in services.Model.GetTables()) { string str8 = SqlBuilder.GetCreateTableCommand(table4); if (!string.IsNullOrEmpty(str8)) { builder2.AppendLine(str8); } } foreach (MetaTable table5 in services.Model.GetTables()) { foreach (string str9 in SqlBuilder.GetCreateForeignKeyCommands(table5)) { if (!string.IsNullOrEmpty(str9)) { builder2.AppendLine(str9); } } } if (builder2.Length > 0) { builder2.Insert(0, "SET ARITHABORT ON" + Environment.NewLine); ExecuteCommand(builder2.ToString()); } } } finally { conManager.ReleaseConnection(this); if (conManager.Connection is SqlConnection) { SqlConnection.ClearAllPools(); } } }
protected DatabaseProvider(DbConnectionStringBuilder connectionStringBuilder) : this(connectionStringBuilder.ToString()) { }
private void InitializeDataSource() { _storageRegistry = new StorageRegistry(); ConfigManager.RegisterService(_storageRegistry); _entityRegistry = (HydraEntityRegistry)ConfigManager.GetService <IEntityRegistry>(); _entityRegistry.TasksSettings.Recycle = false; ((SecurityList)_entityRegistry.Securities).BulkLoad = true; var database = (Database)_entityRegistry.Storage; if (database != null) { var conStr = new DbConnectionStringBuilder { ConnectionString = database.ConnectionString }; _dbFile = (string)conStr.Cast <KeyValuePair <string, object> >().ToDictionary(StringComparer.InvariantCultureIgnoreCase).TryGetValue("Data Source"); if (_dbFile != null) { _dbFile = _dbFile.Replace("%Documents%", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)); conStr["Data Source"] = _dbFile; database.ConnectionString = conStr.ToString(); _dbFile.CreateDirIfNotExists(); if (!File.Exists(_dbFile)) { Properties.Resources.StockSharp.Save(_dbFile); _entityRegistry.Version = HydraEntityRegistry.LatestVersion; UpdateDatabaseWalMode(); } } } CheckDatabase(); ConfigManager.RegisterService <IExchangeInfoProvider>(new ExchangeInfoProvider(_entityRegistry)); var allSec = _entityRegistry.Securities.GetAllSecurity(); if (allSec != null) { return; } _entityRegistry.Securities.Add(new Security { Id = Core.Extensions.AllSecurityId, Code = "ALL", //Class = task.GetDisplayName(), Name = LocalizedStrings.Str2835, Board = ExchangeBoard.Associated, ExtensionInfo = new Dictionary <object, object>(), }); _entityRegistry.Securities.DelayAction.WaitFlush(); }
private void zUpdateConnectionString() { this.ConnectionString = m_ConnectionStringBuilder.ToString(); txtConnectionStringPreview.Text = this.ConnectionString; }
private static void Main(string[] args) { #region MySql Server Login string server; string port; string database; string user; string password = ""; Dictionary <string, string> parameters = args.Select(a => a.Split('=')).ToDictionary(a => a[0], a => a.Length == 2 ? a[1] : null); if (parameters.Keys.Contains("debug")) { Debug = parameters["debug"] == "true" ? true : false; } if (parameters.Keys.Contains("google")) { _withGoogle = parameters["google"] == "false" ? false : true; } if (parameters.Keys.Contains("server")) // assuming you'd type them all in { server = parameters["server"]; port = parameters["port"]; database = parameters["database"]; user = parameters["user"]; password = parameters["password"]; } else { Console.WriteLine("/----- MySQL Database Login -----\\"); Console.Write("| Server: "); server = Console.ReadLine(); Console.Write("| Port: "); port = Console.ReadLine(); Console.Write("| Database: "); database = Console.ReadLine(); Console.Write("| User ID: "); user = Console.ReadLine(); Console.Write("| Password:"******"\b \b"); } } else if (i.KeyChar != '\u0000') // KeyChar == '\u0000' if the key pressed does not correspond to a printable character, e.g. F1, Pause-Break, etc { password += i.KeyChar; Console.Write("*"); } } Console.WriteLine("\n\\--------------------------------/\n\n"); } try { DbConnectionStringBuilder builder = new DbConnectionStringBuilder(); builder.Add("server", server); builder.Add("port", port); builder.Add("database", database); builder.Add("user", user); builder.Add("password", password); builder.Add("persistsecurityinfo", "True"); builder.Add("sslmode", "None"); dbWalrusContext.SetConnectionString(builder.ToString()); } catch (Exception e) { Console.WriteLine($"Failed with exception:\n{e.Message}"); Console.WriteLine("This was most likely a failure to log into the database, so check your connection!"); Console.Read(); return; } #endregion MySql Server Login new Program().MainAsync().GetAwaiter().GetResult(); }