• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Configuration.ConnectionStringSettings类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Configuration.ConnectionStringSettings的典型用法代码示例。如果您正苦于以下问题:C# ConnectionStringSettings类的具体用法?C# ConnectionStringSettings怎么用?C# ConnectionStringSettings使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



ConnectionStringSettings类属于System.Configuration命名空间,在下文中一共展示了ConnectionStringSettings类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: DeleteDatabase

		public static void DeleteDatabase(ConnectionStringSettings connectionString)
		{
			var builder = new SqlConnectionStringBuilder(connectionString.ConnectionString);
			string databaseName = builder.InitialCatalog;
			builder.InitialCatalog = string.Empty;

			using (var conn = new SqlConnection(builder.ConnectionString))
			{
				conn.Open();
				using (var command = conn.CreateCommand())
				{
					command.CommandText = string.Format(
						@"IF EXISTS(select * from sys.databases where name='{0}')
						BEGIN
							DECLARE @DatabaseName nvarchar(50)
							SET @DatabaseName = N'{0}'
							DECLARE @Sql varchar(max)
							SELECT @Sql = COALESCE(@Sql,'') + 'Kill ' + Convert(varchar, SPId) + ';'
								FROM MASTER..SysProcesses
								WHERE DBId = DB_ID(@DatabaseName) AND SPId <> @@SPId
							EXEC(@Sql)
							DROP DATABASE [{0}]
						END",
						databaseName);

					command.ExecuteNonQuery();
				}
			}
		}
开发者ID:behaug,项目名称:webapi.nhibernate-odata,代码行数:29,代码来源:NHibernateHelper.cs


示例2: Assemble

        /// <summary>
        /// Builds an instance of the concrete subtype of <see cref="T:Microsoft.Practices.EnterpriseLibrary.Data.Database"/> 
        /// the receiver knows how to build, based on the provided connection string and any configuration information 
        /// that might be contained by the <paramref name="configurationSource"/>.
        /// </summary>
        /// <param name="name">The name for the new database instance.</param>
        /// <param name="connectionStringSettings">The connection string for the new database instance.</param>
        /// <param name="configurationSource">The source for any additional configuration information.</param>
        /// <returns>
        /// The new database instance.
        /// </returns>
        public Database Assemble(string name, ConnectionStringSettings connectionStringSettings,
                                 IConfigurationSource configurationSource) {
            if(IsDebugEnabled)
                log.Debug("EnterpriseLibrary용 OracleProvider 인스턴스를 빌드합니다... name=[{0}]", name);

            var settings = OracleConnectionSettings.GetSettings(configurationSource);

            if(settings != null) {
                var data = settings.OracleConnectionsData.Get(name);

                if(data != null) {
                    var packages = new IOraclePackage[data.Packages.Count];
                    var num = 0;

                    foreach(var package in data.Packages) {
                        packages[num++] = package;
                    }
                    return new OracleDatabase(connectionStringSettings.ConnectionString);
                }
            }

            if(IsDebugEnabled)
                log.Debug("OracleDatabase를 생성합니다. connectionString=[{0}]", connectionStringSettings.ConnectionString);

            return new OracleDatabase(connectionStringSettings.ConnectionString);
        }
开发者ID:debop,项目名称:NFramework,代码行数:37,代码来源:OracleDatabaseAssembler.cs


示例3: SqlBulkInsertOperation

 /// <summary>
 /// Initializes a new instance of the <see cref="SqlBulkInsertOperation"/> class.
 /// </summary>
 /// <param name="connectionStringSettings">Connection string settings to use.</param>
 /// <param name="targetTable">The target table.</param>
 /// <param name="timeout">The timeout.</param>
 protected SqlBulkInsertOperation(ConnectionStringSettings connectionStringSettings, string targetTable, int timeout)
     : base(connectionStringSettings)
 {
     Guard.Against(string.IsNullOrEmpty(targetTable), "TargetTable was not set, but it is mandatory");
     this.targetTable = targetTable;
     this.timeout = timeout;
 }
开发者ID:hoffmanc,项目名称:rhino-etl,代码行数:13,代码来源:SqlBulkInsertOperation.cs


示例4: GetNewOnMatch

        internal static SqlCeProvider GetNewOnMatch(ConnectionStringSettings connectionConfig)
        {
            if (ProviderNames.Contains(connectionConfig.ProviderName))
                return new SqlCeProvider(connectionConfig.Name, connectionConfig.ConnectionString, connectionConfig.ProviderName);

            return null;
        }
开发者ID:bazer,项目名称:Modl,代码行数:7,代码来源:SqlCeProvider.cs


示例5: BuildConnectionString

        protected virtual string BuildConnectionString(Guid streamId, ConnectionStringSettings setting)
        {
            if (this.shards == 0)
                return setting.ConnectionString;

            return setting.ConnectionString.FormatWith(this.ComputeHashKey(streamId));
        }
开发者ID:stgwilli,项目名称:EventStore,代码行数:7,代码来源:ConfigurationConnectionFactory.cs


示例6: DynamicModel

        public DynamicModel(ConnectionStringSettings settings, DbProviderFactory factory)
        {
            Errors = new List<string>();

            _dbProviderFactory = factory;
            _connectionString = settings.ConnectionString;
        }
开发者ID:GodLesZ,项目名称:ZeusEngine,代码行数:7,代码来源:DynamicModel.cs


示例7: GetConnectionStringsSection

 static ConnectionStringsSection GetConnectionStringsSection()
 {
     ConnectionStringsSection section = new ConnectionStringsSection();
     ConnectionStringSettings connectionStringSettings = new ConnectionStringSettings(instanceName, connectionString, providerName);
     section.ConnectionStrings.Add(connectionStringSettings);
     return section;
 }
开发者ID:HondaBey,项目名称:EnterpriseLibrary6,代码行数:7,代码来源:SqlCeDatabaseFixture.cs


示例8: Create

 public IDataProvider Create(ConnectionStringSettings settings, Transaction transactionMode)
 {
     var provider = ResolveDataProvider(settings.ProviderName);
     provider.DbConnection = CreateConnection(settings.ProviderName, settings);
     provider.TransactionMode = transactionMode;
     return provider;
 }
开发者ID:jonasgiehl,项目名称:Thunderstruck,代码行数:7,代码来源:ProviderFactory.cs


示例9: Main

        static void Main(string[] args)
        {
            // Code that runs on application startup
            ConnectionStringSettings cs = new ConnectionStringSettings("dbconnstring", HP.Rfg.lib.utility.getParameter("dbconnstring"), "System.Data.SqlClient");
            string poolSize = HP.Rfg.lib.utility.getParameter("dbpoolsize");
            int poolSizeInt = 5;
            int.TryParse(poolSize, out poolSizeInt);
            string pathToTempDir = utility.getParameter("path_to_temp");
            
            HP.Rfg.Control.RFGActivator.StartApplication(cs, HP.Rfg.lib.utility.getParameter("smtp"), poolSizeInt, pathToTempDir);

            MessageCallback_Console msg = new MessageCallback_Console();

            try
            {
                BatchJobs.Process(pathToTempDir, msg);

                System.Environment.Exit(0);
            }
            catch (Exception ex)
            {
                msg.AppendLine(ex.Message + "\n" + ex.StackTrace + "\n");
                System.Environment.Exit(-1);
            }
            finally
            {
                HP.Rfg.Control.RFGActivator.StopApplication();
            }
            //}
        }
开发者ID:amalapannuru,项目名称:RFC,代码行数:30,代码来源:Program.cs


示例10: CreateConnectionStringsConfig

        ///<summary> 
        ///创建ConnectionString(如果存在,先删除再创建) 
        ///</summary> 
        ///<param name="config">Configuration实例</param>
        ///<param name="newName">连接字符串名称</param> 
        ///<param name="newConString">连接字符串内容</param> 
        ///<param name="newProviderName">数据提供程序名称</param>         
        public static Boolean CreateConnectionStringsConfig(Configuration config, string newName, string newConString, string newProviderName)
        {
            if (config == null && string.IsNullOrEmpty(newName) && string.IsNullOrEmpty(newConString) && string.IsNullOrEmpty(newProviderName))
            {
                return false;
            }

            bool isModified = false;
            //记录该连接串是否已经存在
            //如果要更改的连接串已经存在
            if (config.ConnectionStrings.ConnectionStrings[newName] != null)
            { isModified = true; }

            //新建一个连接字符串实例
            ConnectionStringSettings mySettings = new ConnectionStringSettings(newName, newConString, newProviderName);

            // 如果连接串已存在,首先删除它
            if (isModified)
            {
                config.ConnectionStrings.ConnectionStrings.Remove(newName);
            }
            // 将新的连接串添加到配置文件中.
            config.ConnectionStrings.ConnectionStrings.Add(mySettings);
            // 保存对配置文件所作的更改
            config.Save(ConfigurationSaveMode.Modified);

            return true;
        }
开发者ID:riveryong,项目名称:shopsoft,代码行数:35,代码来源:ConfigFileUtil.cs


示例11: Initialize

    public override void Initialize(string name, NameValueCollection config)
    {
      // Initialize values from web.config.
      if (config == null) throw new ArgumentNullException("config");
      if (name == null || name.Length == 0) name = "VauctionSessionStateStore";
      if (String.IsNullOrEmpty(config["description"]))
      {
        config.Remove("description");
        config.Add("description", "Vauction Session State Store provider");
      }
      // Initialize the abstract base class.
      base.Initialize(name, config);
      // Initialize the ApplicationName property.

      // Get <sessionState> configuration element.
      System.Configuration.Configuration cfg = WebConfigurationManager.OpenWebConfiguration(ApplicationName);
      pConfig = (SessionStateSection)cfg.GetSection("system.web/sessionState");

      // Initialize connection string.
      pConnectionStringSettings = ConfigurationManager.ConnectionStrings[config["connectionStringName"]];

      if (pConnectionStringSettings == null || pConnectionStringSettings.ConnectionString.Trim() == "")
        throw new ProviderException("Connection string cannot be blank.");
      connectionString = pConnectionStringSettings.ConnectionString;

      // Initialize WriteExceptionsToEventLog
      pWriteExceptionsToEventLog = false;
      if (config["writeExceptionsToEventLog"] != null)
      {
        if (config["writeExceptionsToEventLog"].ToUpper() == "TRUE")
          pWriteExceptionsToEventLog = true;
      }
      pApplicationName = (config["application"] != null) ? config["application"] : System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
      eventSource = (!String.IsNullOrEmpty(config["eventLogSource"])) ? config["eventLogSource"] : "VauctionSessionStateStore";
    }
开发者ID:clpereira2001,项目名称:Lelands-Master,代码行数:35,代码来源:VauctionSessionStateStore.cs


示例12: Parse

 private ConnectionStringSettings Parse(ConnectionStringSettings connectionStringSettings)
 {
     var result = connectionStringSettings.ConnectionString;
     result = ExpandEnvironmentVariables(result);
     connectionStringSettings.ConnectionString = result;
     return connectionStringSettings;
 }
开发者ID:ReactiveServices,项目名称:ReactiveServices.MessageBus,代码行数:7,代码来源:ConnectionStrings.cs


示例13: IndexOf

    public int IndexOf (ConnectionStringSettings settings)
    {
      Contract.Requires (settings != null);
      Contract.Ensures (Contract.Result<int>() >= -1);

      return default(int);
    }
开发者ID:asvishnyakov,项目名称:CodeContracts,代码行数:7,代码来源:System.Configuration.ConnectionStringSettingsCollection.cs


示例14: InitDb

        private static IDbConnectionProvider InitDb(DirectoryInfo baseDirectory)
        {
            if (baseDirectory == null)
            {
                var appdomainDirectory = AppDomain.CurrentDomain.BaseDirectory;
                baseDirectory = new DirectoryInfo(Path.Combine(appdomainDirectory, "platibus", "subscriptions"));
            }
            var dbPath = Path.Combine(baseDirectory.FullName, "subscriptions.db");
            var connectionStringSettings = new ConnectionStringSettings
            {
                Name = dbPath,
                ConnectionString = "Data Source=" + dbPath + "; Version=3",
                ProviderName = "System.Data.SQLite"
            };

            var connectionProvider = new SingletonConnectionProvider(connectionStringSettings);
            var connection = connectionProvider.GetConnection();
            try
            {
                using (var command = connection.CreateCommand())
                {
                    command.CommandType = CommandType.Text;
                    command.CommandText = new SQLiteDialect().CreateSubscriptionTrackingServiceObjectsCommand;
                    command.ExecuteNonQuery();
                }
            }
            finally
            {
                connectionProvider.ReleaseConnection(connection);
            }
            return connectionProvider;
        }
开发者ID:tdbrian,项目名称:Platibus,代码行数:32,代码来源:SQLiteSubscriptionTrackingService.cs


示例15: GetDefaultConnectionStringSettings

 private static ConnectionStringSettings GetDefaultConnectionStringSettings()
 {
     var connStrSettingsList = ConfigurationManager.ConnectionStrings;
     ConnectionStringSettings defaultConnStrSettings = null;
     for (int i = 0; i < connStrSettingsList.Count; ++i)
     {
         var connStrSettings = connStrSettingsList[i];
         if ("default".Equals(connStrSettings.Name, StringComparison.OrdinalIgnoreCase))
         {
             if (defaultConnStrSettings != null)
             {
                 throw new ConfigurationErrorsException("Multiple connection string settings with name \"default\"");
             }
             defaultConnStrSettings = connStrSettingsList[i];
             if (string.IsNullOrEmpty(defaultConnStrSettings.ConnectionString))
             {
                 throw new ConfigurationErrorsException("A connection string setting with name \"default\" has empty or null ConnectionString");
             }
         }
     }
     if (defaultConnStrSettings == null)
     {
         throw new ConfigurationErrorsException("No connection string settings with name \"default\"");
     }
     return defaultConnStrSettings;
 }
开发者ID:Zeemlap,项目名称:abruzzesemolisano.it,代码行数:26,代码来源:BusinessBase.cs


示例16: LoadConfigurations

 public void LoadConfigurations()
 {
     appSettings = new NameValueCollection();
     connSettings = new ConnectionStringSettingsCollection();
     var areaDir = new DirectoryInfo(HttpContext.Current.Server.MapPath("~/Modules"));
     if(areaDir.Exists)
     {
         foreach(var dir in areaDir.GetDirectories())
         {
             var file = dir.GetFiles("web.config").FirstOrDefault();
             if(file != null)
             {
                 var config = WebConfigurationManager.OpenWebConfiguration(string.Format("/Modules/{0}/web.config", dir.Name));
                 var settings = config.AppSettings.Settings;
                 foreach(var key in settings.AllKeys)
                 {
                     appSettings.Add(string.Format("{0}.{1}", dir.Name, key), settings[key] == null ? "" :  settings[key].ToString());
                 }
                 var conns = config.ConnectionStrings.ConnectionStrings;
                 foreach(ConnectionStringSettings conn in conns)
                 {
                     ConnectionStringSettings c = new ConnectionStringSettings(conn.Name, conn.ConnectionString, conn.ProviderName);
                     connSettings.Add(c);
                 }
             }
         }
     }
 }
开发者ID:cairabbit,项目名称:daf,代码行数:28,代码来源:ModuleConfigurationProvider.cs


示例17: CreateTemplate

 private static AdoTemplate CreateTemplate(ConnectionStringSettings connectionStringSettings)
 {
     var dbProvider = DbProviderFactory.GetDbProvider(connectionStringSettings.ProviderName);
     dbProvider.ConnectionString = connectionStringSettings.ConnectionString;
     return new AdoTemplate(dbProvider)
            {DataReaderWrapperType = typeof (NullMappingDataReader), CommandTimeout = 120};
 }
开发者ID:ETK,项目名称:SqlMonitor,代码行数:7,代码来源:QueryRunner.cs


示例18: AuthMutableStructureSearchManager

 /// <summary>
 /// Initializes a new instance of the <see cref="AuthMutableStructureSearchManager"/> class.
 /// </summary>
 /// <param name="mutableRetrievalManagerFactory">
 /// The mutable retrieval manager factory.
 /// </param>
 /// <param name="crossReferenceManager">
 /// The cross reference manager.
 /// </param>
 /// <param name="connectionStringSettings">
 /// The connection string settings.
 /// </param>
 public AuthMutableStructureSearchManager(
     IAuthAdvancedMutableRetrievalManagerFactory mutableRetrievalManagerFactory, 
     IAuthCrossRetrievalManagerFactory crossReferenceManager, 
     ConnectionStringSettings connectionStringSettings)
     : base(mutableRetrievalManagerFactory, crossReferenceManager, connectionStringSettings)
 {
 }
开发者ID:SDMXISTATFRAMEWORK,项目名称:ISTAT_ENHANCED_SDMXRI_WS,代码行数:19,代码来源:AuthMutableStructureSearchManager.cs


示例19: Main

        static void Main(string[] args)
        {
            // Объект ConnectionStringSettings представляет собой отдельную строку подключения в разделе строк подключения 
            // конфигурационного файла
            ConnectionStringSettings setting = new ConnectionStringSettings()
            {
                Name = "MyConnectionString2",     //имя строки подключения в конфигурационном файле
                ConnectionString = @"Data Source=(localdb)\v11.0;AttachDbFilename=D:\KIN\DB\People.mdf;Integrated Security=True"
            };

            Configuration config;  // Объект Config представляет конфигурационный файл
            config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            Console.WriteLine(config.FilePath);
            // Объект ConfigurationManager предоставляет доступ к файлам конфигурации
            config.ConnectionStrings.ConnectionStrings.Add(setting);
            config.Save();  // СОХРАНЕНИЕ СТРОКИ ПОДКЛЮЧЕНИЯ В ФАЙЛЕ

            Console.WriteLine("Строка подключения записана в конфигурационный файл.");

            // Получение строки подключения.
            Console.WriteLine("Строка подключения MyConnectionString2");
            Console.WriteLine(ConfigurationManager.ConnectionStrings["MyConnectionString2"].ConnectionString);
            Console.WriteLine("Строка подключения DefaultConnection");
            Console.WriteLine(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);


            Console.ReadKey();

        }
开发者ID:Saroko-dnd,项目名称:My_DZ,代码行数:29,代码来源:Program.cs


示例20: CreateConnectionString

        public void CreateConnectionString(ServerConfiguration serverConfiguration)
        {
            Configuration config = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
            ConnectionStringSettings connectionstringsets = new ConnectionStringSettings();
            connectionstringsets.Name = "filth1connection";

            // create connection string
            if (serverConfiguration.Live)
            {
                connectionstringsets.ConnectionString = "Data Source=" + serverConfiguration.ServerName + ";Initial Catalog=" + serverConfiguration.Catalog + ";Integrated Security=false;User ID=" + serverConfiguration.Username + ";Password=" + serverConfiguration.Password + ";multipleactiveresultsets=True;App=EntityFramework;"; //Encrypt=yes
                try
                {
                    using (var connection = new SqlConnection(connectionstringsets.ConnectionString))
                    {
                        connection.Open();
                        // most hostings doesn't allow this
                        // var command = connection.CreateCommand();
                        // command.CommandText = "CREATE DATABASE " + database;
                        // command.ExecuteNonQuery();
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
            else
                connectionstringsets.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDBFilename=|DataDirectory|filthdb_" + new Random().Next() + ".mdf" + ";User Instance=true;Integrated Security=true;multipleactiveresultsets=True;App=EntityFramework";

            connectionstringsets.ProviderName = "System.Data.SqlClient";

            config.ConnectionStrings.ConnectionStrings.Add(connectionstringsets);

            config.Save();
        }
开发者ID:nenadg,项目名称:filth,代码行数:35,代码来源:FilthConfiguration.cs



注:本文中的System.Configuration.ConnectionStringSettings类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Configuration.ConnectionStringsSection类代码示例发布时间:2022-05-26
下一篇:
C# Configuration.ConfigurationSection类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap