Skip to content
Igor Tkachev edited this page May 20, 2016 · 1 revision

Home / Data

Configure programmatically

Connection string can be also assigned programmatically. The DbManager.AddConnectionString method can be used for this. You should do it once when your application starts.

OpenConfig2.cs

using System;
using System.Data;

using NUnit.Framework;

using BLToolkit.Data;

namespace HowTo.Data
{
    [TestFixture]
    public class OpenConfig2
    {
        const string sqlConnectionString =
            "Server=.;Database=BLToolkitData;Integrated Security=SSPI";
        const string oleDbConnectionString =
            "Provider=SQLOLEDB;Data Source=.;Integrated Security=SSPI;Initial Catalog=BLToolkitData";

        [Test]
        public void Test1()
        {
            string defaultConfiguration = DbManager.DefaultConfiguration;
            DbManager.DefaultConfiguration = ""; //to reset possible previous changes

            try
            {
                DbManager.AddConnectionString(
                    sqlConnectionString);   // connection string

                using (DbManager db = new DbManager())
                {
                    Assert.AreEqual(ConnectionState.Open, db.Connection.State);
                }
            }
            finally
            {
                DbManager.DefaultConfiguration = defaultConfiguration; // to restore previous settings
            }

        }

        [Test]
        public void Test2()
        {
            DbManager.AddConnectionString(
                "NewConfig",            // configuration string
                sqlConnectionString);   // connection string

            using (DbManager db = new DbManager("NewConfig"))
            {
                Assert.AreEqual(ConnectionState.Open, db.Connection.State);
            }
        }

        [Test]
        public void Test3()
        {
            DbManager.AddConnectionString(
                "OleDb",                // provider name
                "NewConfig",            // configuration string
                oleDbConnectionString); // connection string

            using (DbManager db = new DbManager("OleDb", "NewConfig"))
            {
                Assert.AreEqual(ConnectionState.Open, db.Connection.State);
            }
        }
    }
}
Clone this wiki locally