public void CanUpload2FilesToRootDirUsingProperties() { using (var file1 = new DummyFile(1024 * 1024 * 3)) using (var file2 = new DummyFile(1024 * 1024 * 3)) { var csb = new DbConnectionStringBuilder { ConnectionString = Cs }; Sftp.Host = csb["host"] as string; Sftp.Username = csb["username"] as string; Sftp.Password = csb["password"] as string; Sftp.Hostkey = csb["hostkey"] as string; Sftp.Port = csb.ContainsKey("port") ? csb["port"] as string : string.Empty; Sftp.UploadFiles(file1.FileInfo.DirectoryName, SearchPattern, true); } }
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 void Open() { var sb = new DbConnectionStringBuilder(); sb.ConnectionString = _connectionString; Assert.IsTrue(sb.ContainsKey("Data Source")); var dataSourceObject = sb["Data Source"]; Assert.IsTrue(dataSourceObject is string); var path = (string)dataSourceObject; Database = new Database(path, DatabaseOpenMode.ReadOnly); _state = ConnectionState.Open; }
/// <summary> /// Removes the key value pair from connection string. /// </summary> /// <param name="connectionConfiguration">The connection configuration.</param> /// <param name="key">The key.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException">connectionConfiguration;The expected connection string is not here.</exception> /// <remarks> /// This routine can convert, say, an OLEDB connection string for use with another provider. /// So <c>"Provider=ORAOLEDB.ORACLE;Data Source=MY_SOURCE;User ID=myId;Password=my!#Passw0rd"</c> /// can be converted to <c>Data Source=MY_SOURCE;User ID=myId;Password=my!#Passw0rd"</c> /// with <c>CommonDbmsUtility.RemoveKeyValuePairFromConnectionString(connectionConfiguration, "Provider")</c>. /// </remarks> public static string RemoveKeyValuePairFromConnectionString(string connectionConfiguration, string key) { if (string.IsNullOrEmpty(connectionConfiguration)) { throw new ArgumentNullException("connectionConfiguration", "The expected connection string is not here."); } var builder = new DbConnectionStringBuilder(); builder.ConnectionString = connectionConfiguration; if (builder.ContainsKey(key)) { builder.Remove(key); } return(builder.ConnectionString); }
private void SetConnectionString(string connectionString) { if (string.IsNullOrEmpty(connectionString) || string.IsNullOrEmpty(connectionString.Trim())) { throw new ArgumentNullException("connectionString", ExecutionStringManager.MissingConnectionString); } DbConnectionStringBuilder builder = new DbConnectionStringBuilder { ConnectionString = connectionString }; if (builder.ContainsKey("enlist")) { throw new ArgumentException(ExecutionStringManager.InvalidEnlist); } this.connString = connectionString; this.localProvider = Provider.SqlClient; }
public SannsynConfiguration() { var moduleDisabled = ConfigurationManager.AppSettings["Sannsyn:DisableModule"]; bool.TryParse(moduleDisabled, out _moduleDisabled); // if module is disabled, we won't attempt the connection string if (_moduleDisabled == false) { ConnectionStringSettings connectionString = ConfigurationManager.ConnectionStrings["SannsynConnection"]; if (connectionString == null) { throw new ConfigurationErrorsException("Missing Sannsyn connection string"); } _builder = new DbConnectionStringBuilder(false); _builder.ConnectionString = connectionString.ConnectionString; string url = _builder["Service Url"].ToString(); if (string.IsNullOrEmpty(url)) { throw new ConfigurationErrorsException("Missing service url in Sannsyn connection string"); } if (url.EndsWith("/") == false) { url = url + "/"; } _serviceUrl = new Uri(url); if (_builder.ContainsKey("Configuration")) { _configuration = _builder["Configuration"].ToString(); } var scriptTimeoutString = ConfigurationManager.AppSettings["Sannsyn:ScriptTimeout"]; if (string.IsNullOrEmpty(scriptTimeoutString) == false) { int.TryParse(scriptTimeoutString, out _scriptTimeout); } } var sendDataFlag = ConfigurationManager.AppSettings["Sannsyn:LogSendData"]; bool.TryParse(sendDataFlag, out _logSendData); }
private string ExtractProviderName(string connectionString) { try { var csb = new DbConnectionStringBuilder() { ConnectionString = connectionString }; if (csb.ContainsKey("pbix")) { return("Microsoft.AnalysisServices.AdomdClient"); } } catch (Exception) { return(null); } return(null); }
public override IClient Instantiate(string connectionString) { var connectionStringBuilder = new DbConnectionStringBuilder() { ConnectionString = connectionString }; var endpoint = new Uri((string)connectionStringBuilder[BaseClient.EndpointToken]); var authkey = (string)connectionStringBuilder[BaseClient.AuthKeyToken]; var database = (string)connectionStringBuilder[BaseClient.DatabaseToken]; var graph = (string) ( connectionStringBuilder.ContainsKey(GraphClient.GraphToken) ? connectionStringBuilder[GraphClient.GraphToken] : connectionStringBuilder[BaseClient.CollectionToken] ); return(new GraphClient(endpoint, authkey, database, graph)); }
private static bool IsCompactDatabase(string cxString) { DbConnectionStringBuilder builder = new DbConnectionStringBuilder { ConnectionString = cxString }; if (!builder.ContainsKey("Data Source")) { return(false); } string str = (string)builder["Data Source"]; if (str == null) { return(false); } return(str.EndsWith(".sdf", StringComparison.OrdinalIgnoreCase)); }
private string ExtractProviderName(string connectionString) { try { var csb = new DbConnectionStringBuilder() { ConnectionString = connectionString }; if (csb.ContainsKey("Provider")) { return(csb["Provider"].ToString()); } } catch (Exception) { } return(string.Empty); }
public void CanCreateConnection() { var provider = new MicrOrmConnectionProvider(DbUtility.ConnectionStringName); var connection = provider.CreateConnection(); Assert.NotNull(connection); Assert.AreEqual(ConnectionState.Closed, connection.State); var connectionStringActual = new DbConnectionStringBuilder { ConnectionString = connection.ConnectionString }; foreach (string key in provider.ConnectionString.Keys) { Assert.True(connectionStringActual.ContainsKey(key)); Assert.AreEqual(provider.ConnectionString[key], connectionStringActual[key]); } }
/// <summary> /// Gets DB schema name from connection string, or default from config /// </summary> private static string GetDBSchema(string connectionStringName) { string result; if (!__schemaCache.TryGetValue(connectionStringName, out result)) { lock (__schCacheLock) { if (!__schemaCache.TryGetValue(connectionStringName, out result)) { DbConnectionStringBuilder builder = new DbConnectionStringBuilder(); builder.ConnectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; result = builder.ContainsKey("User ID") ? builder["User ID"] as string : ConfigurationManager.AppSettings["DefaultIntegrationSchema"]; __schemaCache.Add(connectionStringName, result); } } } return(result); }
DbConnection GetConnection(string connStr) { MessageBox.Show(connStr); string providerName = null; var csb = new DbConnectionStringBuilder { ConnectionString = connStr }; if (csb.ContainsKey("provider")) { providerName = csb["provider"].ToString(); } else { var css = ConfigurationManager .ConnectionStrings .Cast <ConnectionStringSettings>() .FirstOrDefault(x => x.ConnectionString == connStr); if (css != null) { providerName = css.ProviderName; } } if (providerName != null) { var providerExists = DbProviderFactories .GetFactoryClasses() .Rows.Cast <DataRow>() .Any(r => r[2].Equals(providerName)); if (providerExists) { var factory = DbProviderFactories.GetFactory(providerName); var dbConnection = factory.CreateConnection(); dbConnection.ConnectionString = connStr; return(dbConnection); } } return(null); }
public static string GetDefaultSchema(Backends backend, DbConnectionStringBuilder connStrBuilder, List <string> schemata) { switch (backend) { case Backends.Access: return(null); case Backends.PostgreSql: return("public"); case Backends.SqlServer: return("dbo"); case Backends.Oracle: if ((connStrBuilder != null) && (connStrBuilder.ContainsKey("USER ID"))) { string userIDstring = DbOracle.GetUserId(connStrBuilder); if ((schemata != null) && (schemata.IndexOf(userIDstring) != -1)) { return(userIDstring); } } return(null); default: if (connStrBuilder != null) { object userID; if ((connStrBuilder.TryGetValue("UID", out userID)) || (connStrBuilder.TryGetValue("User ID", out userID))) { string userIDstring = userID.ToString(); if ((schemata != null) && (schemata.IndexOf(userIDstring) != -1)) { return(userIDstring); } } } return(null); } }
/// <summary>Initializes the store, ensuring that an instance of the server is running and a database is attached.</summary> protected override void InternalInitialize() { _supportsMARS = true; _supportsUpdatableCursor = true; DbConnectionStringBuilder builder = new DbConnectionStringBuilder(); builder.ConnectionString = ConnectionString; if (builder.ContainsKey("Data Source")) { string databaseFileName = (string)builder["Data Source"]; if (!File.Exists(databaseFileName)) { using (SqlCeEngine engine = new SqlCeEngine(ConnectionString)) { engine.CreateDatabase(); } } } }
public static string ExtractSchemaName(this string connectionString, out string schemaName) { const string key = "Queue Schema"; var connectionStringParser = new DbConnectionStringBuilder { ConnectionString = connectionString }; if (connectionStringParser.ContainsKey(key)) { schemaName = (string)connectionStringParser[key]; connectionStringParser.Remove(key); connectionString = connectionStringParser.ConnectionString; } else { schemaName = null; } return(connectionString); }
internal static string GetInitialCatalog(string providerName, string providerConnectionString) { var dbsb = new DbConnectionStringBuilder(); dbsb.ConnectionString = providerConnectionString; var initialCatalog = String.Empty; if (dbsb.ContainsKey(LocalDataUtil.CONNECTION_PROPERTY_ATTACH_DB_FILENAME) && !string.IsNullOrEmpty(dbsb[LocalDataUtil.CONNECTION_PROPERTY_ATTACH_DB_FILENAME] as string)) { //sql client with "AttachDbFileName" parameter in the connection string. object o = null; dbsb.TryGetValue(LocalDataUtil.CONNECTION_PROPERTY_ATTACH_DB_FILENAME, out o); initialCatalog = o as String; if (initialCatalog != null) { initialCatalog = Path.GetFileNameWithoutExtension(initialCatalog); } } else if (LocalDataUtil.IsSqlMobileConnectionString(providerName)) { // sql CE object o = null; dbsb.TryGetValue(LocalDataUtil.CONNECTION_PROPERTY_DATA_SOURCE, out o); initialCatalog = o as String; if (initialCatalog != null) { initialCatalog = Path.GetFileNameWithoutExtension(initialCatalog); } } else { object o = null; dbsb.TryGetValue("Initial Catalog", out o); initialCatalog = o as String; } return(initialCatalog); }
/// <summary> /// Method exposed by the interface IQueryPerformance of engine and implemented due to pubic pressure to support this kind of scenario /// </summary> public void CleanCache() { using (var conn = new AdomdConnection(command.Connection.ConnectionString)) { string xmla = string.Empty; using (var stream = Assembly.GetExecutingAssembly() .GetManifestResourceStream("NBi.Core.Query.CleanCache.xmla")) using (var reader = new StreamReader(stream)) xmla = reader.ReadToEnd(); var csb = new DbConnectionStringBuilder(); csb.ConnectionString = conn.ConnectionString; if (!csb.ContainsKey("Initial Catalog")) { throw new ArgumentException("The token 'Initial Catalog' was not provided in the connection string due to this, it was impossible to clean the cache of the database."); } conn.Open(); using (var cleanCmd = new AdomdCommand(string.Format(xmla, csb["Initial Catalog"]), conn)) cleanCmd.ExecuteNonQuery(); } }
/// <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); }
/// <summary> /// Gets the command timeout (in seconds) from /// the connection string (if the CommandTimeout key is specified). /// </summary> private static int?GetCommandTimeout(DbConnectionStringBuilder csb) { const string key = "CommandTimeout"; int?value = null; if (csb.ContainsKey(key)) { int iValue; if (Int32.TryParse(csb[key].ToString(), out iValue)) { // ignore negative values if (iValue >= 0) { value = iValue; } } csb.Remove(key); } return(value); }
private void SetConnectionString(string connectionString) { if (String.IsNullOrEmpty(connectionString) || String.IsNullOrEmpty(connectionString.Trim())) { throw new ArgumentNullException("connectionString", ExecutionStringManager.MissingConnectionString); } DbConnectionStringBuilder dcsb = new DbConnectionStringBuilder(); dcsb.ConnectionString = connectionString; // Don't allow the client to specify an auto-enlist value since we decide whether to participate in a transaction // (enlist for writing and not for reading). if (dcsb.ContainsKey("enlist")) { throw new ArgumentException(ExecutionStringManager.InvalidEnlist); } this.connString = connectionString; // // We only support sqlclient, sql is the only data store our OOB services talk to. localProvider = Provider.SqlClient; }
private static DbConnectionStringBuilder GetBuilder(string serverNameOrConnectionString) { DbConnectionStringBuilder csb = new DbConnectionStringBuilder(); try { csb.ConnectionString = serverNameOrConnectionString; } catch (ArgumentException ex) { } if (!csb.ContainsKey("Provider")) { csb.Add(ProviderKey, "MSOLAP"); } if (!csb.ContainsAny("Data Source", "DataSource")) { csb.Add(DataSourceKey, serverNameOrConnectionString); } return(csb); }
// <Snippet1> static void Main() { DbConnectionStringBuilder builder = new DbConnectionStringBuilder(); builder.Add("Provider", "Provider=Microsoft.Jet.OLEDB.4.0"); builder.Add("Data Source", "C:\\ThisExcelWorkbook.xls"); builder.Add("Extended Properties", "Excel 8.0;HDR=Yes;IMEX=1"); // Displays the values in the DbConnectionStringBuilder. Console.WriteLine("Contents of the DbConnectionStringBuilder:"); Console.WriteLine(builder.ConnectionString); // Searches for a key. if (builder.ContainsKey("Data Source")) { Console.WriteLine("The collection contains the key \"Data Source\"."); } else { Console.WriteLine("The collection does not contain the key \"Data Source\"."); } Console.ReadLine(); }
/// <summary> /// 获取一个DbContext对象 /// </summary> /// <param name="name">连接名称</param> /// <param name="autoClose">是否自动关闭</param> /// <returns>DbContext对象</returns> public static DbContext GetContext(string name, bool autoClose) { //得到映射后连接名称 name = DbConnectionMappingContext.GetMappedConnectionName(name); DbProviderFactory factory = DbConnectionManager.GetDbProviderFactory(name); DbConnectionStringBuilder csb = factory.CreateConnectionStringBuilder(); csb.ConnectionString = DbConnectionManager.GetConnectionString(name); bool enlist = true; if (csb.ContainsKey("enlist")) { enlist = (bool)csb["enlist"]; } DbContext result = null; if (enlist) { result = new AutoEnlistDbContext(name, autoClose); } else { result = new NotEnlistDbContext(name, autoClose); } result.InitDbContext(name, autoClose); result._autoClose = autoClose; result._commandTimeout = DbConnectionManager.GetCommandTimeout(name); return(result); }
/// <summary> /// Initializes the Queue List with custom settings /// </summary> public void Initialize(string connectionString) { var parser = new DbConnectionStringBuilder { ConnectionString = connectionString }; if (parser.ContainsKey("Data Source")) { _skipFilePath = parser["Data Source"].ToString(); } else { var mediaStorageLocation = PlayOnSettings.GetMediaStorageLocation(); if (mediaStorageLocation == "") { throw new Exception("Unable to find PlayLater's Media Storage Location"); } _skipFilePath = mediaStorageLocation; } if (!Directory.Exists(_skipFilePath)) { throw new Exception(String.Format("Queue List data path does not exists: {0}", _skipFilePath)); } }
private static string ProtectConnectionString(string connectionString) { var builder = new DbConnectionStringBuilder(false) { ConnectionString = connectionString }; var sensitiveKeys = new[] { "Password", "Pwd", }; foreach (var key in sensitiveKeys) { if (builder.ContainsKey(key)) { builder[key] = "******"; } } return(builder.ConnectionString); }
public static IQueueList GetQueueList(string connectionString) { var parser = new DbConnectionStringBuilder { ConnectionString = connectionString }; if (!parser.ContainsKey("Provider")) { throw new Exception("Queue List Provider Type is not specified"); } var providerType = parser["Provider"].ToString().ToUpper(); if (!Classes.ContainsKey(providerType)) { throw new Exception(String.Format("Unregistered Queue List Provider Type: {0}", providerType)); } var type = Classes[providerType]; var instance = (IQueueList)Activator.CreateInstance(type); instance.Initialize(connectionString); return(instance); }
protected static void GetDatabaseInfo(ref Site site, string physicalPath, string remoteComputerName) { try { string virtualSite = "/website"; var map = new WebConfigurationFileMap(); map.VirtualDirectories.Add(virtualSite, new VirtualDirectoryMapping(Environment.ExpandEnvironmentVariables(physicalPath), true)); var configuration = WebConfigurationManager.OpenMappedWebConfiguration(map, virtualSite); if (configuration != null) { ConfigurationSection configSection = configuration.GetSection("connectionStrings"); if (configSection != null) { foreach (ConnectionStringSettings connectionStringSetting in configuration.ConnectionStrings.ConnectionStrings) { string name = connectionStringSetting.Name; string providerName = connectionStringSetting.ProviderName; string dbConnectionString = connectionStringSetting.ConnectionString; if (string.IsNullOrEmpty(dbConnectionString)) { continue; } if (dbConnectionString.Contains("metadata")) { // TODO: check other EF scenarios // this is an entity framework connection string, so we can't migrate it. // We use this to validate later on however // we assume the site has a normal connection string as well site.Add(new Database(providerName, name, dbConnectionString) { ParentSite = site }); continue; } //var builder = new SqlConnectionStringBuilder(dbConnectionString); //if (!string.IsNullOrEmpty(builder.AttachDBFilename) && name == "LocalSqlServer") //{ // we ignore this since it is MOST LIKELY the default values from the machine.config connection string from .NET framework // continue; //} try { var dbConn = new DbConnectionStringBuilder { ConnectionString = dbConnectionString }; // dbConn.ConnectionString = dbConnectionString; if (dbConn.ContainsKey("Provider") && (dbConn["Provider"].ToString() == "SQLOLEDB" || dbConn["Provider"].ToString().Contains("SQLNCLI"))) { dbConn.Remove("Provider"); } var sqlConn = new SqlConnectionStringBuilder(dbConn.ConnectionString); //sqlConn.ConnectionString = dbConnectionString; if (!string.IsNullOrEmpty(sqlConn.AttachDBFilename) && name == "LocalSqlServer") { // we ignore this since it is MOST LIKELY the default values from the machine.config connection string from .NET framework continue; } if (!string.IsNullOrEmpty(remoteComputerName)) { sqlConn.DataSource = SetAppropriateServerName(sqlConn.DataSource, remoteComputerName); } site.Add(new Database(providerName, name, sqlConn.ConnectionString) { ParentSite = site }); } catch (System.ArgumentException e) { MessageBox.Show(e.ToString()); TraceHelper.Tracer.WriteTrace(e.ToString()); } } } } } catch (Exception ex) { site.Errors.Add(ex.Message); TraceHelper.Tracer.WriteTrace(ex.ToString()); } }
static public TypedDataSource GetFromTabularDs(TOMWrapper.ProviderDataSource tabularDataSource) { TypedDataSource ds; bool needsPassword = false; string cs = tabularDataSource.ConnectionString; if (!string.IsNullOrWhiteSpace(tabularDataSource.GetPreviewConnectionString())) { cs = tabularDataSource.GetPreviewConnectionString(); } var csb = new DbConnectionStringBuilder() { ConnectionString = cs }; if (!string.IsNullOrEmpty(tabularDataSource.Password) && tabularDataSource.Password != "********") { csb.Add("password", tabularDataSource.Password); csb.Add("user id", tabularDataSource.Account); } if (csb.ContainsKey("password") && (string)csb["password"] == "********") { if (GlobalPasswords.TryGetValue(tabularDataSource.ConnectionString, out string password)) { csb["password"] = password; } else { needsPassword = true; } } if (csb.ContainsKey("pwd") && (string)csb["pwd"] == "********") { if (GlobalPasswords.TryGetValue(tabularDataSource.ConnectionString, out string password)) { csb["pwd"] = password; } else { needsPassword = true; } } var providerName = !string.IsNullOrWhiteSpace(tabularDataSource.Provider) ? tabularDataSource.Provider : csb.ContainsKey("Provider") ? csb["Provider"].ToString() : ""; var pName = providerName.ToUpper(); if (pName.Contains("MSADSQL") || pName.Contains("OLEDB")) { ds = new OleDbDataSource(); } else if (pName.Contains("SQLNCLI") || pName.Contains("SQLCLIENT")) { ds = new SqlDataSource(); } else if (pName.Contains("ODBC")) { ds = new OdbcDataSource(); } else if (pName.Contains("ORACLE")) { ds = new OracleDataSource(); } else { ds = new OtherDataSource(); } ds.NeedsPassword = needsPassword; if (needsPassword) { ds.MissingPwdConnectionString = tabularDataSource.ConnectionString; } ds.TabularDsName = tabularDataSource.Name; ds.ProviderString = string.Join(";", csb.Keys.OfType <string>().Select(k => k + "=" + csb[k].ToString()).ToArray()); if (!string.IsNullOrEmpty(tabularDataSource.Account)) { ds.Username = tabularDataSource.Account; } else { if (csb.ContainsKey("user id")) { ds.Username = csb["user id"].ToString(); } else if (csb.ContainsKey("uid")) { ds.Username = csb["uid"].ToString(); } else if (csb.ContainsKey("username")) { ds.Username = csb["username"].ToString(); } else if (csb.ContainsKey("account")) { ds.Username = csb["account"].ToString(); } } return(ds); }
protected bool HasApiSetTo(DbConnectionStringBuilder connectionStringBuilder, string api) => connectionStringBuilder.ContainsKey(BaseClient.ApiToken) && ((string)connectionStringBuilder[BaseClient.ApiToken]).ToLowerInvariant() == api.ToLowerInvariant();