Quantcast
Channel: patterns & practices – Enterprise Library
Viewing all articles
Browse latest Browse all 1928

New Post: Dynamic connectionstring without web.config

$
0
0

Is the dynamic connection string reused in your application or is it a one off?

If it is reused in the application then you can programmatically configure the Data Access Block at startup using the Fluent API.  If it just a one off why not just "new-up" a SqlDatabase (or a GenericDatabase)?

The latter would look like this:

private DataTable PMHistory(int Id, string connectionString)
        {
            DataTable dt = new DataTable();
            Database db = new SqlDatabase(connectionString);var cmd = db.GetSqlStringCommand("select * from [Log]");var ds = db.ExecuteDataSet(cmd);
            Response.Write("Records: " + ds.Tables[0].Rows.Count);return ds.Tables[0];
        }protectedvoid Page_Load(object sender, EventArgs e)
        {try
            {string connectionString = @"data source=.\SQLEXPRESS;Integrated Security=SSPI;User Instance=false;Database=LoggingDefault";

                PMHistory(1, connectionString);
                PMHistory();
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }

Or you could register the connection at startup (in the global.asax):

publicclass Global : System.Web.HttpApplication
    {void Application_Start(object sender, EventArgs e)
        {var builder = new ConfigurationSourceBuilder();

            builder.ConfigureData()
                   .ForDatabaseNamed("MyDatabase")
                     .ThatIs.ASqlDatabase()
                     .WithConnectionString(@"data source=.\SQLEXPRESS;Integrated Security=SSPI;User Instance=false;Database=LoggingDefault")
                     .AsDefault();var configSource = new DictionaryConfigurationSource();
            builder.UpdateConfigurationWithReplace(configSource);
            EnterpriseLibraryContainer.Current
              = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
        }
    }

Then the data access could could look something like this:

private DataTable PMHistory()
        {
            DataTable dt = new DataTable();
            Database db = DatabaseFactory.CreateDatabase("MyDatabase");var cmd = db.GetSqlStringCommand("select * from [Log]");var ds = db.ExecuteDataSet(cmd);
            Response.Write("Records: " + ds.Tables[0].Rows.Count);return ds.Tables[0];
        }

The method DatabaseFactory.CreateDatabase(string) does not take a connection string but a database name.

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com 


Viewing all articles
Browse latest Browse all 1928

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>