public TryGetValue ( string keyword, object &value ) : bool | ||
keyword | string | |
value | object | |
리턴 | bool |
/// <summary> /// This function returns login and password of user for a passed NpgsqlConnection /// </summary> /// <param name="connection">the current opened DbConnection</param> /// <param name="login">returned login corresponding to the NpgsqlConnection passed</param> /// <param name="password">returned password corresponding to the NpgsqlConnection passed</param> /// <returns>true if succeed, false otherwise (connection null or not opened)</returns> public static bool GetConnectionInformationsFrom( IDbConnection connection, out string login, out string password) { login = string.Empty; password = string.Empty; if ((connection != null) && (connection.State == System.Data.ConnectionState.Open)) { DbConnectionStringBuilder builder = new DbConnectionStringBuilder(); builder.ConnectionString = connection.ConnectionString; if (builder != null) { object value = null; bool result = builder.TryGetValue("User Id", out value); if (result) { login = value.ToString(); } result &= builder.TryGetValue("Password", out value); if (result) { password = value.ToString(); } builder.Clear(); return result; } } return false; }
public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config) { string connectionStringName = config.Properties["ConnectionStringName"]; if (string.IsNullOrEmpty(connectionStringName)) { this.Log.Info("Starting RavenDB Storage Provider InMemory"); return this.InMemoryMode(); } var settings = ConfigurationManager.ConnectionStrings[connectionStringName]; var connectionStringBuilder = new DbConnectionStringBuilder { ConnectionString = settings.ConnectionString }; object url; if (connectionStringBuilder.TryGetValue("Url", out url)) { this.Log.Info("Starting RavenDB Storage Provider attached to server {0}", url); return this.ServerMode(connectionStringName); } object dataDir; if (connectionStringBuilder.TryGetValue("DataDir", out dataDir)) { this.Log.Info("Starting RavenDB Storage Provider embedded in directory {0}", dataDir); return this.LocalMode(connectionStringName); } return TaskDone.Done; }
public string GetDataBaseName(System.Data.Common.DbConnectionStringBuilder builder) { object database = ""; builder.TryGetValue("database", out database); if (database == null || string.IsNullOrEmpty(database.ToString())) { builder.TryGetValue("initial catalog", out database); } if (database == null || string.IsNullOrEmpty(database.ToString())) { builder.TryGetValue("data source", out database); if (database != null) { if (database.ToString().Contains("/")) { return(database.ToString().Split('/')[1]); } } } if (database == null || string.IsNullOrEmpty(database.ToString())) { throw new Exception(ProviderName + " must have database;" + builder.ConnectionString); } return(database.ToString().FirstLetterToUpper()); }
internal static string GetDatabaseName(System.Data.Common.DbConnectionStringBuilder connectionStringBuilder) { object objDbName; string dbName = null; if (connectionStringBuilder.TryGetValue("USER ID", out objDbName)) { dbName = objDbName.ToString(); } else if (connectionStringBuilder.TryGetValue("UID", out objDbName)) { dbName = objDbName.ToString(); } return(dbName.ToUpper()); }
public string GetDataBaseName(System.Data.Common.DbConnectionStringBuilder builder) { object database = ""; builder.TryGetValue("database", out database); if (database == null || string.IsNullOrEmpty(database.ToString())) { builder.TryGetValue("initial catalog", out database); } if (database == null || string.IsNullOrEmpty(database.ToString())) { throw new Exception(ProviderName + " must have database;" + builder.ConnectionString); } return(database.ToString()); }
/// <summary> /// Gets the provider information stored on the connection string /// </summary> /// <param name="connection">The connection object to get the connection string from</param> /// <returns>An string providing the provider information</returns> public static String GetConnectionProvider(DbConnection connection) { object result = String.Empty; DbConnectionStringBuilder builder = new DbConnectionStringBuilder(); builder.ConnectionString = connection.ConnectionString; builder.TryGetValue("Provider", out result); return result == null ? string.Empty : (string)result; }
public override object GetValue(object component) { object obj2; DbConnectionStringBuilder builder = component as DbConnectionStringBuilder; if ((builder != null) && builder.TryGetValue(this.DisplayName, out obj2)) { return(obj2); } return(null); }
public string GetDataBaseName(System.Data.Common.DbConnectionStringBuilder builder) { object database = ""; builder.TryGetValue("Data Source", out database); if (database == null || string.IsNullOrEmpty(database.ToString())) { throw new Exception(ProviderName + " Data Source error!"); } database = Path.GetFileName(database.ToString()).Replace(".db", ""); return(database.ToString()); }
//TODO: Custom config section? //TODO: Combine constructors public DomainCredential(string connectionString) { //TODO: Custom parser? var builder = new DbConnectionStringBuilder(); builder.ConnectionString = connectionString; object[] value = new object[6]; builder.TryGetValue("NetBIOS", out value[0]); builder.TryGetValue("Domain", out value[1]); builder.TryGetValue("Container", out value[2]); builder.TryGetValue("Username", out value[3]); builder.TryGetValue("Password", out value[4]); builder.TryGetValue("SecureConnection", out value[5]); if (String.IsNullOrWhiteSpace(value[0] as string)) throw new ArgumentNullException("netbios"); if (String.IsNullOrWhiteSpace(value[1] as string)) throw new ArgumentNullException("domain"); if (String.IsNullOrWhiteSpace(value[2] as string)) throw new ArgumentNullException("container"); NetBIOS = value[0] as string; Domain = value[1] as string; Container = value[2] as string; Username = value[3] as string; Password = value[4] as string; SecureConnection = bool.Parse(value[5] as string ?? "False"); }
/// <summary> /// Parses semicolon-delimited parameter string, /// which has same format as connection strings, /// and extracts a value for given key. /// Returns defaultValue if key was not found. /// </summary> /// <param name="delimiteParamString"></param> /// <param name="paramKey"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static string GetParameterValue(string delimiteParamString, string paramKey, string defaultValue = null) { DbConnectionStringBuilder paramStringParse = new DbConnectionStringBuilder { ConnectionString = delimiteParamString }; object val; if(!paramStringParse.TryGetValue(paramKey, out val)) return defaultValue; return val.ToStringEx(); }
public LogServerConnection([NotNull] string connStringOrName) { if (connStringOrName == null) throw new ArgumentNullException("connStringOrName"); var connString = connStringOrName; try { connString = ConfigurationManager.ConnectionStrings[connStringOrName].ConnectionString; } // ReSharper disable EmptyGeneralCatchClause catch { } // ReSharper restore EmptyGeneralCatchClause var csb = new DbConnectionStringBuilder(); try { csb.ConnectionString = connString; } catch (ArgumentException ex) { throw new FormatException(string.Format("The connection string '{0}' is not formatted correctly. " + "Example connection string: " + "url=http://logserver.company.com:123;username=johndoe;password=secret", connString), ex); } object value; if (csb.TryGetValue("url", out value)) Url = (string)value; else throw new FormatException("A url was not specified in the connection string."); if (csb.TryGetValue("username", out value)) Username = (string)value; if (csb.TryGetValue("password", out value)) Password = (string)value; }
public override object GetValue(object component) { DbConnectionStringBuilder builder = (component as DbConnectionStringBuilder); if (null != builder) { object value; if (builder.TryGetValue(DisplayName, out value)) { return(value); } } return(null); }
private static string GetProviderName(string connectionString) { var builder = new DbConnectionStringBuilder(); builder.ConnectionString = connectionString; object providerObject; if (!builder.TryGetValue("provider", out providerObject)) { return (string)providerObject; } // TODO - look at deducing provider from related config throw new ConnectionProviderException(connectionString); }
internal static string GetLocalDbFilePath(string providerInvariantName, string providerConnectionString) { var filePathKey = GetFilePathKey(providerInvariantName, providerConnectionString); if (string.IsNullOrEmpty(filePathKey)) { return null; } var providerConnectionStringBuilder = new DbConnectionStringBuilder(); providerConnectionStringBuilder.ConnectionString = providerConnectionString; object filePathObject; providerConnectionStringBuilder.TryGetValue(filePathKey, out filePathObject); var filePath = filePathObject as string; if (string.IsNullOrEmpty(filePath)) { return null; } return filePath; }
internal static bool IsSqlLocalConnectionString(string providerInvariantName, string providerConnectionString) { if (null == providerInvariantName || null == providerConnectionString) { return false; } if (0 == string.CompareOrdinal(providerInvariantName, PROVIDER_NAME_SQLCLIENT)) { var providerConnectionStringBuilder = new DbConnectionStringBuilder(); providerConnectionStringBuilder.ConnectionString = providerConnectionString; object ignoreResult; if (providerConnectionStringBuilder.TryGetValue(CONNECTION_PROPERTY_ATTACH_DB_FILENAME, out ignoreResult)) { return true; } } return false; }
private void ParseEndpoints(DbConnectionStringBuilder builder) { object val; builder.TryGetValue("Source", out val); if (val == null) throw new CqlException("no \"Source\" param specified in connection string"); string source = val as string; if (source.Contains(":")) { var parts = source.Split(':'); ushort port; if (!ushort.TryParse(parts[1], out port)) throw new CqlException("cannot parse Source param: port number is not parsable"); Host = parts[0]; Port = port; } else { Host = source; Port = DEFAULT_CASSANDRA_PORT; } }
private void ParseDefaultKeyspace(DbConnectionStringBuilder builder) { object val; if (builder.TryGetValue("Keyspace", out val)) { DefaultKeyspace = EnsureKeyspaceNameIsValid(val as string); } else if (builder.TryGetValue("Database", out val)) { DefaultKeyspace = EnsureKeyspaceNameIsValid(val as string); } }
/// <summary> /// Gets the value of the specified item in the connection string. /// </summary> /// <param name="connectionStringBuilder">The connection string.</param> /// <param name="keyword">Name of the item.</param> /// <returns>The value of the item, or an empty string if not found.</returns> protected string GetConnectionStringValue(DbConnectionStringBuilder connectionStringBuilder, string keyword) { object value = null; connectionStringBuilder.TryGetValue(keyword, out value); return (string)value ?? String.Empty; }
private string ConvertConnectionStringToNewPath( string providerInvariantName, string filePathKey, string oldConnectionString, string newFilePath, bool useDataDirectoryMacro) { if (string.IsNullOrEmpty(filePathKey)) { Debug.Fail("requires non-null, non-empty filePathKey"); return oldConnectionString; } if (LocalDataUtil.IsSqlMobileConnectionString(providerInvariantName)) { // DbConnectionString does not support SQL Mobile return GenerateNewSqlMobileConnectionString(oldConnectionString, newFilePath, useDataDirectoryMacro); } var dbConnectionStringBuilder = new DbConnectionStringBuilder(); dbConnectionStringBuilder.ConnectionString = oldConnectionString; object filePathObject; dbConnectionStringBuilder.TryGetValue(filePathKey, out filePathObject); var filePath = filePathObject as string; if (string.IsNullOrEmpty(filePath)) { Debug.Fail("could not find filePath for filePathKey=" + filePathKey); return oldConnectionString; } // replace old path with new one dbConnectionStringBuilder.Remove(filePathKey); if (useDataDirectoryMacro) { dbConnectionStringBuilder.Add(filePathKey, DataDirectoryMacro + Path.DirectorySeparatorChar + Path.GetFileName(newFilePath)); } else { dbConnectionStringBuilder.Add(filePathKey, newFilePath); } return dbConnectionStringBuilder.ConnectionString; }
private static void GetConnectionStringParam(string connectionString,string paramName,out object paramValue) { var connectionStringBuilder = new DbConnectionStringBuilder {ConnectionString = connectionString}; connectionStringBuilder.TryGetValue(paramName, out paramValue); }
internal static bool IsAccessConnectionString(string providerInvariantName, string providerConnectionString) { if (null == providerInvariantName || null == providerConnectionString) { return false; } if (0 == string.CompareOrdinal(providerInvariantName, PROVIDER_NAME_OLEDB)) { // This is an OleDb connection string, verify if it is using the Jet provider. var providerConnectionStringBuilder = new DbConnectionStringBuilder(); providerConnectionStringBuilder.ConnectionString = providerConnectionString; object oleDbProviderObject; providerConnectionStringBuilder.TryGetValue(CONNECTION_PROPERTY_PROVIDER, out oleDbProviderObject); var oleDbProvider = oleDbProviderObject as string; Debug.Assert(oleDbProvider != null, "Expected the provider connection string to contain a 'provider' property."); if (!string.IsNullOrEmpty(oleDbProvider)) { if (oleDbProvider.StartsWith(PROVIDER_NAME_JET, StringComparison.OrdinalIgnoreCase) || oleDbProvider.StartsWith(PROVIDER_NAME_ACE, StringComparison.OrdinalIgnoreCase)) { // This is a Jet or Ace connection string. return true; } } } return false; }
public void TryGetValueTest() { object value = null; _builder["DriverID"] = "790"; _builder.Add("Server", "C:\\"); Assert.True(_builder.TryGetValue("DriverID", out value)); Assert.Equal("790", value); Assert.True(_builder.TryGetValue("SERVER", out value)); Assert.Equal("C:\\", value); Assert.False(_builder.TryGetValue(string.Empty, out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("a;", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("\r", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue(" ", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("doesnotexist", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("Driver", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("Dsn", out value)); Assert.Null(value); _builder = new DbConnectionStringBuilder(false); _builder["DriverID"] = "790"; _builder.Add("Server", "C:\\"); Assert.True(_builder.TryGetValue("DriverID", out value)); Assert.Equal("790", value); Assert.True(_builder.TryGetValue("SERVER", out value)); Assert.Equal("C:\\", value); Assert.False(_builder.TryGetValue(string.Empty, out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("a;", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("\r", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue(" ", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("doesnotexist", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("Driver", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("Dsn", out value)); Assert.Null(value); _builder = new DbConnectionStringBuilder(true); _builder["DriverID"] = "790"; _builder.Add("Server", "C:\\"); Assert.True(_builder.TryGetValue("DriverID", out value)); Assert.Equal("790", value); Assert.True(_builder.TryGetValue("SERVER", out value)); Assert.Equal("C:\\", value); Assert.False(_builder.TryGetValue(string.Empty, out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("a;", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("\r", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue(" ", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("doesnotexist", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("Driver", out value)); Assert.Null(value); Assert.False(_builder.TryGetValue("Dsn", out value)); Assert.Null(value); }
public static ConnectionProvider Register(string serverName, string connectionString) { DbConnectionStringBuilder conn = new DbConnectionStringBuilder(); conn.ConnectionString = connectionString.ToLower(); string providerName = "sqldb"; object value; if (conn.TryGetValue("provider", out value)) { if (value is string) providerName = (string)value; } ConnectionProvider pvd = null; switch (providerName) { case "xmlfile": pvd = new XmlDbConnectionProvider(serverName, connectionString); break; case "riadb": //Remote Invoke Agent pvd = new RiaDbConnectionProvider(serverName, connectionString); break; case "Microsoft.ACE.OLEDB.12.0": //Excel 2010 case "Microsoft.Jet.OLEDB.4.0": //Excel 2007 or Access case "MySqlProv": //MySql case "MSDAORA": //Oracle case "sqloledb": pvd = new OleDbConnectionProvider(serverName, connectionString); break; case "sqldb": //Sql Server pvd = new SqlDbConnectionProvider(serverName, connectionString); break; } if (pvd != null) Register(pvd); else throw new Exception($"invlaid connection string {connectionString}"); return pvd; }
private static object ReadProp( DbConnectionStringBuilder cnn, params string[] aliases ) { if (aliases.Length == 0) { return null; } foreach (string alias in aliases) { object val; if (cnn.TryGetValue(alias, out val)) { return val; } } return null; }
internal static string InjectEFAttributesIntoConnectionString(string sourceConnectionString, string providerInvariantName) { // if the provider connection string's provider property is "System.Data.SqlClient" then add the // MARS attribute (value is true if SQL Server version >= 9, false otherwise). Also add the App // attribute (with fixed value EntityFramework) - which is useful for statistics on server. if (!string.Equals(providerInvariantName, SqlClientProviderName, StringComparison.Ordinal)) { return sourceConnectionString; } var configFileConnectionBuilder = new DbConnectionStringBuilder(); try { configFileConnectionBuilder.ConnectionString = sourceConnectionString; } catch (ArgumentException) { return sourceConnectionString; } // add MARS property if it does not already exist object marsValue; if (!configFileConnectionBuilder.TryGetValue(XmlAttrNameMultipleActiveResultSets, out marsValue)) { configFileConnectionBuilder[XmlAttrNameMultipleActiveResultSets] = true.ToString(); } // add App attribute if neither App nor Application Name property is already set if (!configFileConnectionBuilder.ContainsKey(ProviderConnectionStringPropertyNameApp) && !configFileConnectionBuilder.ContainsKey(ProviderConnectionStringPropertyNameApplicationName)) { // note: fixed value so no localization; configFileConnectionBuilder[ProviderConnectionStringPropertyNameApp] = "EntityFramework"; } return configFileConnectionBuilder.ConnectionString; }
/// <summary> /// Extracts the <see cref="String"/> value of the specified keyword from the specified <see cref="DbConnectionStringBuilder"/>. /// </summary> /// <param name="value">The <see cref="DbConnectionStringBuilder"/> to extract the value from.</param> /// <param name="keyword">The keyword to extract the value of.</param> /// <returns> /// The <see cref="String"/> value of the keyword specified by <paramref name="keyword"/> present in <paramref name="value"/>, if any; otherwise <see langword="null"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="value"/> is <see langword="null"/>. /// </exception> private static string ExtractStringValueFromConnectionString(this DbConnectionStringBuilder value, string keyword) { if (value == null) { throw new ArgumentNullException("value"); } // N.B. Keywords are used here rather than the strongly-typed derived classes // of DbConnectionStringBuilder. This is so that custom derived classes can be // used and also so that both of the following entity connection string builders // can be used without using reflection and hard-coded type names: // 1) System.Data.EntityClient.EntityClientConnectionStringBuilder (System.Data.Entity.dll) // 2) System.Data.Entity.Core.EntityClient.EntityClientConnectionStringBuilder (EntityFramework.dll) // First assume it's an SQL connection string object resultAsObject; string result = null; if (value.TryGetValue(keyword, out resultAsObject)) { result = resultAsObject as string; } if (!string.IsNullOrEmpty(result)) { return result; } object providerConnectionStringAsObject; string providerConnectionString = null; // If it wasn't SQL, see if it's an entity connection string // by trying to extract the provider connection string if (value.TryGetValue(ProviderConnectionStringKeywordName, out providerConnectionStringAsObject)) { // It wasn't an entity connection string, nothing further to try providerConnectionString = providerConnectionStringAsObject as string; } if (!string.IsNullOrEmpty(providerConnectionString)) { // Build a connection string from the provider connection string DbConnectionStringBuilder builder = new DbConnectionStringBuilder() { ConnectionString = providerConnectionString, }; object resultFromProviderAsObject; // Try and extract the initial catalog from the provider's connection string if (builder.TryGetValue(keyword, out resultFromProviderAsObject)) { result = resultFromProviderAsObject as string; } } // Derived types of DbConnectionStringBuilder may return the empty string instead of null // if they key is missing/not set, so in those cases explicitly return null instead. if (string.IsNullOrEmpty(result)) { return null; } return result; }
/// <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(); }
string GetDatabaseName() { var connectionStringBuilder = new DbConnectionStringBuilder { ConnectionString = this.ConnectionString }; object objDbName; string dbName = null; if (DbProviderName == DbProviderNames.Oracle || DbProviderName == DbProviderNames.Oracle_ODP) { if (connectionStringBuilder.TryGetValue("USER ID", out objDbName)) dbName = objDbName.ToString(); else if (connectionStringBuilder.TryGetValue("UID", out objDbName)) dbName = objDbName.ToString(); } else { if (connectionStringBuilder.TryGetValue("Initial Catalog", out objDbName)) dbName = objDbName.ToString(); else if (connectionStringBuilder.TryGetValue("Database", out objDbName)) dbName = objDbName.ToString(); else if (connectionStringBuilder.TryGetValue("AttachDBFileName", out objDbName)) dbName = objDbName.ToString(); else if (connectionStringBuilder.TryGetValue("Data Source", out objDbName)) dbName = objDbName.ToString(); var dataDirectory = AppDomain.CurrentDomain.GetData("DataDirectory") as string; if (dbName == null) return null; if (dbName.Contains(@"|DataDirectory|\")) { if (dataDirectory == null) dataDirectory = CheckDataDirectory(dataDirectory); dbName = dbName.Replace(@"|DataDirectory|\", dataDirectory + @"\"); } else if (dbName.Contains(@"|DataDirectory|")) { if (dataDirectory == null) dataDirectory = CheckDataDirectory(dataDirectory); dbName = dbName.Replace(@"|DataDirectory|", dataDirectory + @"\"); } } return dbName; }
public void TryGetValueTest () { object value = null; builder ["DriverID"] = "790"; builder.Add ("Server", "C:\\"); Assert.IsTrue (builder.TryGetValue ("DriverID", out value), "#A1"); Assert.AreEqual ("790", value, "#A2"); Assert.IsTrue (builder.TryGetValue ("SERVER", out value), "#B1"); Assert.AreEqual ("C:\\", value, "#B2"); Assert.IsFalse (builder.TryGetValue (string.Empty, out value), "#C1"); Assert.IsNull (value, "#C2"); Assert.IsFalse (builder.TryGetValue ("a;", out value), "#D1"); Assert.IsNull (value, "#D2"); Assert.IsFalse (builder.TryGetValue ("\r", out value), "#E1"); Assert.IsNull (value, "#E2"); Assert.IsFalse (builder.TryGetValue (" ", out value), "#F1"); Assert.IsNull (value, "#F2"); Assert.IsFalse (builder.TryGetValue ("doesnotexist", out value), "#G1"); Assert.IsNull (value, "#G2"); Assert.IsFalse (builder.TryGetValue ("Driver", out value), "#H1"); Assert.IsNull (value, "#H2"); Assert.IsFalse (builder.TryGetValue ("Dsn", out value), "#I1"); Assert.IsNull (value, "#I2"); builder = new DbConnectionStringBuilder (false); builder ["DriverID"] = "790"; builder.Add ("Server", "C:\\"); Assert.IsTrue (builder.TryGetValue ("DriverID", out value), "#A1"); Assert.AreEqual ("790", value, "#A2"); Assert.IsTrue (builder.TryGetValue ("SERVER", out value), "#B1"); Assert.AreEqual ("C:\\", value, "#B2"); Assert.IsFalse (builder.TryGetValue (string.Empty, out value), "#C1"); Assert.IsNull (value, "#C2"); Assert.IsFalse (builder.TryGetValue ("a;", out value), "#D1"); Assert.IsNull (value, "#D2"); Assert.IsFalse (builder.TryGetValue ("\r", out value), "#E1"); Assert.IsNull (value, "#E2"); Assert.IsFalse (builder.TryGetValue (" ", out value), "#F1"); Assert.IsNull (value, "#F2"); Assert.IsFalse (builder.TryGetValue ("doesnotexist", out value), "#G1"); Assert.IsNull (value, "#G2"); Assert.IsFalse (builder.TryGetValue ("Driver", out value), "#H1"); Assert.IsNull (value, "#H2"); Assert.IsFalse (builder.TryGetValue ("Dsn", out value), "#I1"); Assert.IsNull (value, "#I2"); builder = new DbConnectionStringBuilder (true); builder ["DriverID"] = "790"; builder.Add ("Server", "C:\\"); Assert.IsTrue (builder.TryGetValue ("DriverID", out value), "#A1"); Assert.AreEqual ("790", value, "#A2"); Assert.IsTrue (builder.TryGetValue ("SERVER", out value), "#B1"); Assert.AreEqual ("C:\\", value, "#B2"); Assert.IsFalse (builder.TryGetValue (string.Empty, out value), "#C1"); Assert.IsNull (value, "#C2"); Assert.IsFalse (builder.TryGetValue ("a;", out value), "#D1"); Assert.IsNull (value, "#D2"); Assert.IsFalse (builder.TryGetValue ("\r", out value), "#E1"); Assert.IsNull (value, "#E2"); Assert.IsFalse (builder.TryGetValue (" ", out value), "#F1"); Assert.IsNull (value, "#F2"); Assert.IsFalse (builder.TryGetValue ("doesnotexist", out value), "#G1"); Assert.IsNull (value, "#G2"); Assert.IsFalse (builder.TryGetValue ("Driver", out value), "#H1"); Assert.IsNull (value, "#H2"); Assert.IsFalse (builder.TryGetValue ("Dsn", out value), "#I1"); Assert.IsNull (value, "#I2"); }
public static string GetProviderInvariantNameByConnectionString(string connectionString) { if (connectionString == null) return null; var builder = new DbConnectionStringBuilder { ConnectionString = connectionString }; object providerValue; if (builder.TryGetValue("provider", out providerValue)) { return providerValue.ToString(); } var persistSecurityInfo = false; object persistSecurityInfoValue; if (builder.TryGetValue("persist security info", out persistSecurityInfoValue)) { persistSecurityInfo = Convert.ToBoolean(persistSecurityInfoValue); } var lostPassword = !persistSecurityInfo && !builder.ContainsKey("pwd") && !builder.ContainsKey("password"); if (!lostPassword) { for (var i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++) { var config = ConfigurationManager.ConnectionStrings[i]; if (string.Equals(config.ConnectionString, connectionString, StringComparison.OrdinalIgnoreCase)) { return config.ProviderName; } } } else { object uid; if (builder.TryGetValue("uid", out uid)) { builder.Remove("uid"); builder["user id"] = uid; } for (var i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++) { var config = ConfigurationManager.ConnectionStrings[i]; var otherBuilder = new DbConnectionStringBuilder { ConnectionString = config.ConnectionString }; otherBuilder.Remove("pwd"); otherBuilder.Remove("password"); object otherUid; if (otherBuilder.TryGetValue("uid", out otherUid)) { otherBuilder.Remove("uid"); otherBuilder["user id"] = otherUid; } if (otherBuilder.Count != builder.Count) continue; var equivalenCount = builder.Cast<KeyValuePair<string, object>>().Select(p => { object value; return otherBuilder.TryGetValue(p.Key, out value) && string.Equals(Convert.ToString(value), Convert.ToString(p.Value), StringComparison.OrdinalIgnoreCase) ? 1 : 0; }).Sum(); if (equivalenCount == builder.Count) { return config.ProviderName; } } } return null; }
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] // File.Exists method call. void IProvider.CreateDatabase() { this.CheckDispose(); this.CheckInitialized(); // Don't need to call CheckNotDeleted() here since we allow CreateDatabase after DeleteDatabase // Don't need to call InitializeProviderMode() here since we don't need to know the provider to do this. string catalog = null; string filename = null; DbConnectionStringBuilder builder = new DbConnectionStringBuilder(); builder.ConnectionString = _conManager.Connection.ConnectionString; if(_conManager.Connection.State == ConnectionState.Closed) { if(_mode == SqlServerProviderMode.SqlCE) { if(!File.Exists(_dbName)) { Type engineType = _conManager.Connection.GetType().Module.GetType("System.Data.SqlServerCe.SqlCeEngine"); object engine = Activator.CreateInstance(engineType, new object[] { builder.ToString() }); try { engineType.InvokeMember("CreateDatabase", BindingFlags.Instance | BindingFlags.Public | BindingFlags.InvokeMethod, null, engine, new object[] { }, CultureInfo.InvariantCulture); } catch(TargetInvocationException tie) { throw tie.InnerException; } finally { IDisposable disp = engine as IDisposable; if(disp != null) { disp.Dispose(); } } } else { throw Error.CreateDatabaseFailedBecauseSqlCEDatabaseAlreadyExists(_dbName); } } else { // get connection string w/o reference to new catalog object val; if(builder.TryGetValue("Initial Catalog", out val)) { catalog = val.ToString(); builder.Remove("Initial Catalog"); } if(builder.TryGetValue("Database", out val)) { catalog = val.ToString(); builder.Remove("Database"); } if(builder.TryGetValue("AttachDBFileName", out val)) { filename = val.ToString(); builder.Remove("AttachDBFileName"); } } _conManager.Connection.ConnectionString = builder.ToString(); } else { if(_mode == SqlServerProviderMode.SqlCE) { if(File.Exists(_dbName)) { throw Error.CreateDatabaseFailedBecauseSqlCEDatabaseAlreadyExists(_dbName); } } object val; if(builder.TryGetValue("Initial Catalog", out val)) { catalog = val.ToString(); } if(builder.TryGetValue("Database", out val)) { catalog = val.ToString(); } if(builder.TryGetValue("AttachDBFileName", out val)) { filename = val.ToString(); } } if(String.IsNullOrEmpty(catalog)) { if(!String.IsNullOrEmpty(filename)) { catalog = Path.GetFullPath(filename); } else if(!String.IsNullOrEmpty(_dbName)) { catalog = _dbName; } else { throw Error.CouldNotDetermineCatalogName(); } } _conManager.UseConnection(this); _conManager.AutoClose = false; try { if(_services.Model.GetTables().FirstOrDefault() == null) { // we have no tables to create throw Error.CreateDatabaseFailedBecauseOfContextWithNoTables(_services.Model.DatabaseName); } _deleted = false; // create database if(_mode == SqlServerProviderMode.SqlCE) { // create tables foreach(MetaTable table in _services.Model.GetTables()) { string command = SqlBuilder.GetCreateTableCommand(table); if(!String.IsNullOrEmpty(command)) { this.ExecuteCommand(command); } } // create all foreign keys after all tables are defined foreach(MetaTable table in _services.Model.GetTables()) { foreach(string command in SqlBuilder.GetCreateForeignKeyCommands(table)) { if(!String.IsNullOrEmpty(command)) { this.ExecuteCommand(command); } } } } else { string createdb = SqlBuilder.GetCreateDatabaseCommand(catalog, filename, Path.ChangeExtension(filename, ".ldf")); this.ExecuteCommand(createdb); _conManager.Connection.ChangeDatabase(catalog); // create the schemas that our tables will need // cannot be batched together with the rest of the CREATE TABLES if(_mode == SqlServerProviderMode.Sql2005 || _mode == SqlServerProviderMode.Sql2008) { HashSet<string> schemaCommands = new HashSet<string>(); foreach(MetaTable table in _services.Model.GetTables()) { string schemaCommand = SqlBuilder.GetCreateSchemaForTableCommand(table); if(!string.IsNullOrEmpty(schemaCommand)) { schemaCommands.Add(schemaCommand); } } foreach(string schemaCommand in schemaCommands) { this.ExecuteCommand(schemaCommand); } } StringBuilder sb = new StringBuilder(); // create tables foreach(MetaTable table in _services.Model.GetTables()) { string createTable = SqlBuilder.GetCreateTableCommand(table); if(!string.IsNullOrEmpty(createTable)) { sb.AppendLine(createTable); } } // create all foreign keys after all tables are defined foreach(MetaTable table in _services.Model.GetTables()) { foreach(string createFK in SqlBuilder.GetCreateForeignKeyCommands(table)) { if(!string.IsNullOrEmpty(createFK)) { sb.AppendLine(createFK); } } } if(sb.Length > 0) { // must be on when creating indexes on computed columns sb.Insert(0, "SET ARITHABORT ON" + Environment.NewLine); this.ExecuteCommand(sb.ToString()); } } } finally { _conManager.ReleaseConnection(this); if(_conManager.Connection is SqlConnection) { SqlConnection.ClearAllPools(); } } }
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; }
static TokenProviderFactory CreateTokenProviderFactory(DbConnectionStringBuilder builder) { object provider; if (!builder.TryGetValue("provider", out provider)) { throw new ArgumentException("'Provider' was not supplied.", "builder"); } string providerString = (string)provider; if (string.Equals(providerString, "SharedSecret", StringComparison.OrdinalIgnoreCase)) { return new SharedSecretTokenProviderFactory(builder); } throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, "Unrecognized provider. {0}", providerString), "builder"); }