Remove() 공개 메소드

public Remove ( string keyword ) : bool
keyword string
리턴 bool
예제 #1
0
        /// <summary>
        /// Replaces any existing 'enlist' parameter in the connection string
        /// with a value indicating that manual enlist is necessary.
        /// </summary>
        /// <remarks>
        /// ODP.NET supports 3 values for 'enlist'; 'true', 'false' and 'dynamic'.
        ///  'dynamic' effectively works the same as 'false' in System.Data.OracleClient.
        /// </remarks>
        protected override void ReplaceEnlistInConnectionString(DbConnectionStringBuilder dbConnectionStringBuilder)
        {
            if (dbConnectionStringBuilder.ContainsKey("enlist"))
                dbConnectionStringBuilder.Remove("enlist");

            dbConnectionStringBuilder.Add("enlist", "dynamic");
        }
예제 #2
0
        /// <summary>
        /// Extracts the provider from the connection string or uses the default.
        /// </summary>
        /// <param name="csb">The DbConnectionStringBuilder object to use.</param>
        /// <returns>the string type of the provider.</returns>
        private static string GetProvider(DbConnectionStringBuilder csb)
        {
            string provider = "System.Data.SqlClient"; // default factory provider

            if (csb.ContainsKey("provider"))
            {
                provider = csb["provider"].ToString();
                csb.Remove("provider");
            }

            return provider;
        }
        public override void ResetValue(object component)
        {
            DbConnectionStringBuilder builder = component as DbConnectionStringBuilder;

            if (builder != null)
            {
                builder.Remove(this.DisplayName);
                if (this.RefreshOnChange)
                {
                    builder.ClearPropertyDescriptors();
                }
            }
        }
예제 #4
0
        public override void ResetValue(object component)
        {
            DbConnectionStringBuilder builder = (component as DbConnectionStringBuilder);

            if (null != builder)
            {
                builder.Remove(DisplayName);

                if (RefreshOnChange)
                {
                    builder.ClearPropertyDescriptors();
                }
            }
        }
        public string GetConncetionString()
        {

            if(connectionStringBuilder == null)
            {
                var umbracoVersion = new Version(GlobalSettings.CurrentVersion);

                var umbracoConnectionString = umbracoVersion.Major > 4
                ? ConfigurationManager.ConnectionStrings["umbracoWorkflow"].ConnectionString
                : ConfigurationManager.AppSettings["umbracoWorkflow"];

                connectionStringBuilder = new DbConnectionStringBuilder { ConnectionString = umbracoConnectionString };

                connectionStringBuilder.Remove("datalayer");
            }

            return connectionStringBuilder.ConnectionString;

        }
        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;
        }
예제 #7
0
        /// <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;
        }
        // Awesome SQL CE 4 speed improvement by Erik Ejskov Jensen - SQL CE 4 MVP
        // It's not an issue with SQL CE 4 that we never close the connection
        public static SqlCeConnection Open(string connectionString)
        {
            var connectionStringBuilder = new DbConnectionStringBuilder();
            try
            {
                connectionStringBuilder.ConnectionString = connectionString;
            }
            catch (Exception ex)
            {
                throw new ArgumentException("Bad connection string.", "connectionString", ex);
            }
            connectionStringBuilder.Remove("datalayer");

            // SQL CE 4 performs better when there's always a connection open in the background
            EnsureOpenBackgroundConnection(connectionStringBuilder.ConnectionString);

            SqlCeConnection conn = new SqlCeConnection(connectionStringBuilder.ConnectionString);
            conn.Open();

            return conn;

        }
예제 #9
0
        /// <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();
        }
예제 #10
0
        /// <summary>
        /// Initialize the Connection Parameters using the Connection String Settings
        /// </summary>
        /// <param name="settings"></param>
        public void ReadConnectionParameters(ConnectionStringSettings settings)
        {
            var connectionString = new DbConnectionStringBuilder { ConnectionString = settings.ConnectionString };

            if (connectionString.ContainsKey("Database"))
            {
                DatabaseName = (string)connectionString["Database"];
            }

            if (connectionString.ContainsKey("DriverClass"))
            {
                Connection_DriverClass = (string)connectionString["DriverClass"];
                connectionString.Remove("DriverClass");
            }
            else
                throw new ConnectionElementNotFoundException("DriverClass");

            if (connectionString.ContainsKey("Dialect"))
            {
                Dialect = (string)connectionString["Dialect"];
                connectionString.Remove("Dialect");
            }
            else
                throw new ConnectionElementNotFoundException("Dialect");

            if (connectionString.ContainsKey("proxyfactory.factory_class"))
            {
                ProxyFactoryClass = (string)connectionString["proxyfactory.factory_class"];
                connectionString.Remove("proxyfactory.factory_class");
            }

            if (connectionString.ContainsKey("TablePrefix"))
            {
                TablePrefix = (string)connectionString["TablePrefix"];
                connectionString.Remove("TablePrefix");
            }

            if (connectionString.ContainsKey("show_sql"))
            {
                ShowSql = (string)connectionString["NHibernateInterceptor"] == "true";
                connectionString.Remove("show_sql");
            }
            if (connectionString.ContainsKey("NHibernateInterceptor"))
            {
                Interceptor = (string)connectionString["NHibernateInterceptor"];
                connectionString.Remove("NHibernateInterceptor");
            }

            if (connectionString.ContainsKey("CreatedOn"))
            {
                FieldCreatedOn = (string)connectionString["CreatedOn"];
                connectionString.Remove("CreatedOn");
            }

            if (connectionString.ContainsKey("UpdatedOn"))
            {
                FieldUpdatedOn = (string)connectionString["UpdatedOn"];
                connectionString.Remove("UpdatedOn");
            }

            if (connectionString.ContainsKey("CreatedBy"))
            {
                FieldCreatedBy = (string)connectionString["CreatedBy"];
                connectionString.Remove("CreatedBy");
            }

            if (connectionString.ContainsKey("UpdatedBy"))
            {
                FieldUpdatedBy = (string)connectionString["UpdatedBy"];
                connectionString.Remove("UpdatedBy");
            }

            Connection_ConnectionString = connectionString.ConnectionString;
        }
예제 #11
0
        /// <summary>
        /// Creates a SQL helper for the specified connection string.
        /// </summary>
        /// <param name="connectionString">The connection string containing the SQL helper type.</param>
        /// <returns>A new SQL helper.</returns>
        /// <remarks>This method will change to allow the addition of external SQL helpers.</remarks>
        public static ISqlHelper CreateSqlHelper(string connectionString)
        {
            /* check arguments */
            if (String.IsNullOrEmpty(connectionString))
                throw new ArgumentNullException("connectionString");

            /* try to parse connection string */
            DbConnectionStringBuilder connectionStringBuilder = new DbConnectionStringBuilder();
            try
            {
                connectionStringBuilder.ConnectionString = connectionString;
            }
            catch (Exception ex)
            {
                throw new ArgumentException("Bad connection string.", "connectionString", ex);
            }

            // get the data layer type and parse it
            string datalayerType = String.Empty;
            if (connectionStringBuilder.ContainsKey(ConnectionStringDataLayerIdentifier))
            {
                datalayerType = connectionStringBuilder[ConnectionStringDataLayerIdentifier].ToString();
                connectionStringBuilder.Remove(ConnectionStringDataLayerIdentifier);
            }
            
            string[] datalayerTypeParts = datalayerType.Split(",".ToCharArray());
            string helperTypeName = datalayerTypeParts[0].Trim();
            string helperAssemblyName = datalayerTypeParts.Length < 2 ? String.Empty
                                                                      : datalayerTypeParts[1].Trim();
            if (datalayerTypeParts.Length > 2 || (helperTypeName.Length == 0 && helperAssemblyName.Length > 0))
                throw new ArgumentException("Illegal format of data layer property. Should be 'DataLayer = Full_Type_Name [, Assembly_Name]'.", "connectionString");

            /* create the helper */

            // find the right assembly
            Assembly helperAssembly = Assembly.GetExecutingAssembly();
            if (datalayerTypeParts.Length == 2)
            {
                try
                {
                    helperAssembly = Assembly.Load(helperAssemblyName);
                }
                catch (Exception exception)
                {
                    throw new UmbracoException(String.Format("Could not load assembly {0}.", helperAssemblyName), exception);
                }
            }

            // find the right type
            Type helperType;
            if (helperTypeName == String.Empty)
                helperTypeName = DefaultDataHelperName;
            if (!helperTypeName.Contains("."))
                helperTypeName = String.Format(DefaultDataHelperFormat, helperTypeName);
            try
            {
                helperType = helperAssembly.GetType(helperTypeName, true, true);
            }
            catch (Exception exception)
            {
                throw new UmbracoException(String.Format("Could not load type {0} ({1}).", helperTypeName, helperAssembly.FullName), exception);
            }

            // find the right constructor
            ConstructorInfo constructor = helperType.GetConstructor(new Type[] { typeof(string) });
            if (constructor == null)
                throw new UmbracoException(String.Format("Could not find constructor that takes a connection string as parameter. ({0}, {1}).", helperTypeName, helperAssembly.FullName));

            // finally, return the helper
            try
            {
                return constructor.Invoke(new object[] { connectionStringBuilder.ConnectionString }) as ISqlHelper;
            }
            catch (Exception exception)
            {
                throw new UmbracoException(String.Format("Could not execute constructor of type {0} ({1}).", helperTypeName, helperAssembly.FullName), exception);
            }
        }
예제 #12
0
        private static void SetDataHelperNamesLegacyConnectionString(DbConnectionStringBuilder connectionStringBuilder)
        {
            // get the data layer type and parse it
            var datalayerType = String.Empty;
            if (connectionStringBuilder.ContainsKey(ConnectionStringDataLayerIdentifier))
            {
                datalayerType = connectionStringBuilder[ConnectionStringDataLayerIdentifier].ToString();
                connectionStringBuilder.Remove(ConnectionStringDataLayerIdentifier);
            }

            _connectionString = connectionStringBuilder.ConnectionString;

            var datalayerTypeParts = datalayerType.Split(",".ToCharArray());

            _dataHelperTypeName = datalayerTypeParts[0].Trim();
            _dataHelperAssemblyName = datalayerTypeParts.Length < 2
                                          ? string.Empty
                                          : datalayerTypeParts[1].Trim();

            if (datalayerTypeParts.Length > 2 || (_dataHelperTypeName.Length == 0 && _dataHelperAssemblyName.Length > 0))
                throw new ArgumentException("Illegal format of data layer property. Should be 'DataLayer = Full_Type_Name [, Assembly_Name]'.", "connectionString");
        }
예제 #13
0
        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;
        }
예제 #14
0
		[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();
				}
			}
		}
예제 #15
0
 public string Patch(string connectionString) {
     var builder = new DbConnectionStringBuilder { ConnectionString = connectionString };
     string instanceName = GetSqlServerInstanceName();
     builder["Data Source"] = instanceName;
     if(!instanceName.ToUpper().Contains(".\\SQLEXPRESS")) {
         builder.Remove("User Instance");
     }
     return builder.ConnectionString;
 }
        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());
            }
        }
		public void Remove ()
		{
			Assert.IsFalse (builder.Remove ("Dsn"), "#A1");
			Assert.IsFalse (builder.Remove ("Driver"), "#A2");
			builder.Add ("DriverID", "790");
			builder ["DefaultDir"] = "C:\\";
			Assert.IsTrue (builder.Remove ("DriverID"), "#B1");
			Assert.IsFalse (builder.ContainsKey ("DriverID"), "#B2");
			Assert.IsFalse (builder.Remove ("DriverID"), "#B3");
			Assert.IsFalse (builder.ContainsKey ("DriverID"), "#B4");
			Assert.IsTrue (builder.Remove ("defaulTdIr"), "#B5");
			Assert.IsFalse (builder.ContainsKey ("DefaultDir"), "#B6");
			Assert.IsFalse (builder.Remove ("defaulTdIr"), "#B7");
			Assert.IsFalse (builder.Remove ("userid"), "#B8");
			Assert.IsFalse (builder.Remove (string.Empty), "#B9");
			Assert.IsFalse (builder.Remove ("\r"), "#B10");
			Assert.IsFalse (builder.Remove ("a;"), "#B11");
			builder ["Dsn"] = "myDsn";
			Assert.IsTrue (builder.Remove ("Dsn"), "#C1");
			Assert.IsFalse (builder.ContainsKey ("Dsn"), "#C2");
			Assert.IsFalse (builder.Remove ("Dsn"), "#C3");
			builder ["Driver"] = "SQL Server";
			Assert.IsTrue (builder.Remove ("Driver"), "#D1");
			Assert.IsFalse (builder.ContainsKey ("Driver"), "#D2");
			Assert.IsFalse (builder.Remove ("Driver"), "#D3");

			builder = new DbConnectionStringBuilder (false);
			Assert.IsFalse (builder.Remove ("Dsn"), "#A1");
			Assert.IsFalse (builder.Remove ("Driver"), "#A2");
			builder.Add ("DriverID", "790");
			builder ["DefaultDir"] = "C:\\";
			Assert.IsTrue (builder.Remove ("DriverID"), "#B1");
			Assert.IsFalse (builder.ContainsKey ("DriverID"), "#B2");
			Assert.IsFalse (builder.Remove ("DriverID"), "#B3");
			Assert.IsFalse (builder.ContainsKey ("DriverID"), "#B4");
			Assert.IsTrue (builder.Remove ("defaulTdIr"), "#B5");
			Assert.IsFalse (builder.ContainsKey ("DefaultDir"), "#B6");
			Assert.IsFalse (builder.Remove ("defaulTdIr"), "#B7");
			Assert.IsFalse (builder.Remove ("userid"), "#B8");
			Assert.IsFalse (builder.Remove (string.Empty), "#B9");
			Assert.IsFalse (builder.Remove ("\r"), "#B10");
			Assert.IsFalse (builder.Remove ("a;"), "#B11");
			builder ["Dsn"] = "myDsn";
			Assert.IsTrue (builder.Remove ("Dsn"), "#C1");
			Assert.IsFalse (builder.ContainsKey ("Dsn"), "#C2");
			Assert.IsFalse (builder.Remove ("Dsn"), "#C3");
			builder ["Driver"] = "SQL Server";
			Assert.IsTrue (builder.Remove ("Driver"), "#D1");
			Assert.IsFalse (builder.ContainsKey ("Driver"), "#D2");
			Assert.IsFalse (builder.Remove ("Driver"), "#D3");

			builder = new DbConnectionStringBuilder (true);
			Assert.IsFalse (builder.Remove ("Dsn"), "#A1");
			Assert.IsFalse (builder.Remove ("Driver"), "#A2");
			builder.Add ("DriverID", "790");
			builder ["DefaultDir"] = "C:\\";
			Assert.IsTrue (builder.Remove ("DriverID"), "#B1");
			Assert.IsFalse (builder.ContainsKey ("DriverID"), "#B2");
			Assert.IsFalse (builder.Remove ("DriverID"), "#B3");
			Assert.IsFalse (builder.ContainsKey ("DriverID"), "#B4");
			Assert.IsTrue (builder.Remove ("defaulTdIr"), "#B5");
			Assert.IsFalse (builder.ContainsKey ("DefaultDir"), "#B6");
			Assert.IsFalse (builder.Remove ("defaulTdIr"), "#B7");
			Assert.IsFalse (builder.Remove ("userid"), "#B8");
			Assert.IsFalse (builder.Remove (string.Empty), "#B9");
			Assert.IsFalse (builder.Remove ("\r"), "#B10");
			Assert.IsFalse (builder.Remove ("a;"), "#B11");
			builder ["Dsn"] = "myDsn";
			Assert.IsTrue (builder.Remove ("Dsn"), "#C1");
			Assert.IsFalse (builder.ContainsKey ("Dsn"), "#C2");
			Assert.IsFalse (builder.Remove ("Dsn"), "#C3");
			builder ["Driver"] = "SQL Server";
			Assert.IsTrue (builder.Remove ("Driver"), "#D1");
			Assert.IsFalse (builder.ContainsKey ("Driver"), "#D2");
			Assert.IsFalse (builder.Remove ("Driver"), "#D3");
		}
        private void SyncSelectedObjects(TreeNode selectedNode, bool nodeChecked)
        {
            if ((selectedNode == this.siteTree.TopNode) ||
                 (null == this.siteTree.Tag))
            {
                return;
            }

            SelectedObjects selectedObjs = (SelectedObjects)this.siteTree.Tag;
            Type objectType = selectedNode.Tag.GetType();

            //
            // Add or remove selected items from the selected objects list.
            //
            if (nodeChecked) {
                if(typeof(string) == objectType && selectedNode.Tag == "AddDB")
                {
                    AddDbConnectionDialog dbDialog = new AddDbConnectionDialog();
                    if(dbDialog.ShowDialog() == DialogResult.OK)
                    {
                        string dbConnectionString = dbDialog.textBoxDbConnectionString.Text.Trim();
                        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;
                            Site site = (Site)selectedNode.Parent.Tag;
                            Database db = new Database("", sqlConn.InitialCatalog, sqlConn.ConnectionString) { ParentSite = site };
                            site.Add(db);
                            selectedNode.Tag = db;
                            objectType = typeof(Database);
                        }
                        catch (System.ArgumentException ex)
                        {
                            string message = "Invalid connection string.\r\n\r\nValid connection string should be like\r\n 'Data Source=<servername>; Initial Catalog=<intialCatalog>; Trusted_Connection=<Yes|No>'";
                            MessageBox.Show(message);
                            selectedNode.Tag = "AddDB";
                            selectedNode.Checked = false;
                            TraceHelper.Tracer.WriteTrace(message);
                            return;
                        }
                    }
                    else
                    {
                        selectedNode.Tag = "AddDB";
                        selectedNode.Checked = false;
                        return;
                    }

                }
                //
                // If this is a child node, and it's been checked, make sure its
                // parent nodes are checked.
                //
                TreeNode nodeParent = selectedNode.Parent;
                while (null != nodeParent) {
                    if (!nodeParent.Checked) {
                        nodeParent.Checked = true;
                    }
                    nodeParent = nodeParent.Parent;
                }

                if (typeof(Site) == objectType) {
                    if (!selectedObjs.SelectedSites.Contains((Site)selectedNode.Tag)) {
                        selectedObjs.SelectedSites.Add((Site)selectedNode.Tag);
                    }
                    // It's actually not possible to check (enable) anything
                    // in the tree without at least one site being checked.
                    this.StartButton.Enabled = true;
                }
                else if (typeof(Database) == objectType)
                {
                    if (!selectedObjs.SelectedDatabases.Contains((Database)selectedNode.Tag))
                    {
                        selectedObjs.SelectedDatabases.Add((Database)selectedNode.Tag);
                    }
                }
                else if (typeof(IISServer) == objectType)
                {
                    if (!selectedObjs.SelectedServers.Contains((IISServer)selectedNode.Tag))
                    {
                        selectedObjs.SelectedServers.Add((IISServer)selectedNode.Tag);
                    }
                }
            }
            else
            {
                if (typeof(Site) == objectType)
                {
                    if (selectedObjs.SelectedSites.Contains((Site)selectedNode.Tag))
                    {
                        selectedObjs.SelectedSites.Remove((Site)selectedNode.Tag);
                    }
                }
                else if (typeof(Database) == objectType)
                {
                    if (selectedObjs.SelectedDatabases.Contains((Database)selectedNode.Tag))
                    {
                        selectedObjs.SelectedDatabases.Remove((Database)selectedNode.Tag);
                    }
                }
                else if (typeof(IISServer) == objectType)
                {
                    if (!selectedObjs.SelectedServers.Contains((IISServer)selectedNode.Tag))
                    {
                        selectedObjs.SelectedServers.Remove((IISServer)selectedNode.Tag);
                    }
                }
                this.StartButton.Enabled = (0 != selectedObjs.SelectedSites.Count());
            }
        }
예제 #19
0
        public void Remove()
        {
            Assert.False(_builder.Remove("Dsn"));
            Assert.False(_builder.Remove("Driver"));
            _builder.Add("DriverID", "790");
            _builder["DefaultDir"] = "C:\\";
            Assert.True(_builder.Remove("DriverID"));
            Assert.False(_builder.ContainsKey("DriverID"));
            Assert.False(_builder.Remove("DriverID"));
            Assert.False(_builder.ContainsKey("DriverID"));
            Assert.True(_builder.Remove("defaulTdIr"));
            Assert.False(_builder.ContainsKey("DefaultDir"));
            Assert.False(_builder.Remove("defaulTdIr"));
            Assert.False(_builder.Remove("userid"));
            Assert.False(_builder.Remove(string.Empty));
            Assert.False(_builder.Remove("\r"));
            Assert.False(_builder.Remove("a;"));
            _builder["Dsn"] = "myDsn";
            Assert.True(_builder.Remove("Dsn"));
            Assert.False(_builder.ContainsKey("Dsn"));
            Assert.False(_builder.Remove("Dsn"));
            _builder["Driver"] = "SQL Server";
            Assert.True(_builder.Remove("Driver"));
            Assert.False(_builder.ContainsKey("Driver"));
            Assert.False(_builder.Remove("Driver"));

            _builder = new DbConnectionStringBuilder(false);
            Assert.False(_builder.Remove("Dsn"));
            Assert.False(_builder.Remove("Driver"));
            _builder.Add("DriverID", "790");
            _builder["DefaultDir"] = "C:\\";
            Assert.True(_builder.Remove("DriverID"));
            Assert.False(_builder.ContainsKey("DriverID"));
            Assert.False(_builder.Remove("DriverID"));
            Assert.False(_builder.ContainsKey("DriverID"));
            Assert.True(_builder.Remove("defaulTdIr"));
            Assert.False(_builder.ContainsKey("DefaultDir"));
            Assert.False(_builder.Remove("defaulTdIr"));
            Assert.False(_builder.Remove("userid"));
            Assert.False(_builder.Remove(string.Empty));
            Assert.False(_builder.Remove("\r"));
            Assert.False(_builder.Remove("a;"));
            _builder["Dsn"] = "myDsn";
            Assert.True(_builder.Remove("Dsn"));
            Assert.False(_builder.ContainsKey("Dsn"));
            Assert.False(_builder.Remove("Dsn"));
            _builder["Driver"] = "SQL Server";
            Assert.True(_builder.Remove("Driver"));
            Assert.False(_builder.ContainsKey("Driver"));
            Assert.False(_builder.Remove("Driver"));

            _builder = new DbConnectionStringBuilder(true);
            Assert.False(_builder.Remove("Dsn"));
            Assert.False(_builder.Remove("Driver"));
            _builder.Add("DriverID", "790");
            _builder["DefaultDir"] = "C:\\";
            Assert.True(_builder.Remove("DriverID"));
            Assert.False(_builder.ContainsKey("DriverID"));
            Assert.False(_builder.Remove("DriverID"));
            Assert.False(_builder.ContainsKey("DriverID"));
            Assert.True(_builder.Remove("defaulTdIr"));
            Assert.False(_builder.ContainsKey("DefaultDir"));
            Assert.False(_builder.Remove("defaulTdIr"));
            Assert.False(_builder.Remove("userid"));
            Assert.False(_builder.Remove(string.Empty));
            Assert.False(_builder.Remove("\r"));
            Assert.False(_builder.Remove("a;"));
            _builder["Dsn"] = "myDsn";
            Assert.True(_builder.Remove("Dsn"));
            Assert.False(_builder.ContainsKey("Dsn"));
            Assert.False(_builder.Remove("Dsn"));
            _builder["Driver"] = "SQL Server";
            Assert.True(_builder.Remove("Driver"));
            Assert.False(_builder.ContainsKey("Driver"));
            Assert.False(_builder.Remove("Driver"));
        }
예제 #20
0
 private static string FormatCustomCxString(string s)
 {
     try
     {
         DbConnectionStringBuilder builder = new DbConnectionStringBuilder {
             ConnectionString = s
         };
         if (builder.ContainsKey("password"))
         {
             builder.Remove("password");
         }
         if (builder.ContainsKey("pwd"))
         {
             builder.Remove("pwd");
         }
         string[] toRemove = new string[] { "true", "false", "enabled" };
         s = string.Join(";", (from v in builder.Values.OfType<string>()
             where !toRemove.Contains<string>(v.ToLowerInvariant()) && (v.Length > 2)
             select v).ToArray<string>());
     }
     catch
     {
     }
     if (s.Length > 0x55)
     {
         s = s.Substring(0, 80) + "...";
     }
     return s;
 }
예제 #21
0
        /// <summary>
        /// Replaces any existing 'enlist' parameter in the connection String
        /// with a value indicating that manual enlist is necessary.
        /// </summary>
        protected virtual void ReplaceEnlistInConnectionString(DbConnectionStringBuilder dbConnectionStringBuilder)
        {
            if (dbConnectionStringBuilder.ContainsKey("enlist"))
                dbConnectionStringBuilder.Remove("enlist");

            dbConnectionStringBuilder.Add("enlist", false);
        }
예제 #22
0
파일: DbFactory.cs 프로젝트: Rgl88/Yarn
        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;
        }