c# webconfig database

I have database string in webconfig, and I have different .cs class in app_code file.
I would like to find a way to get the name from the webconfig
and it can be use for all of the .cs there. The goal is if one day I need to change the database connection name, ip address and etc. I can just change in webconfig file.

You guys know any professional way to do that? Thanks
Webboy2008Asked:
Who is Participating?
 
santhimurthydCommented:
Kaufmed
I'm not trying to deny the approach, it's just to get control more on the settings. I agree as the user who controls the project should have the knowledge on the infrastructure of the applciation.

Webboy
Take a look into the link for best practises of declaring and usign the connection string
http://peterkellner.net/2008/02/23/webconfigbestpractice/
0
 
santhimurthydCommented:
You can use the configurationmanager

Use the below namespace
using System.Configuration;

Read from web.config
SQLConnection con = new SQLConnection(ConfigurationManager.ConnectionStrings["name"]);

more info

http://msdn.microsoft.com/en-us/library/ms178411.aspx
0
 
Webboy2008Author Commented:
That does not resolve the problem. and this is what we have now.
just thinking you have 100 .cs file that have
connString =rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"];

As a developer, you still have to change 'NorthwindConnectionString' in all 100 .cs file.
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

 
käµfm³d 👽Commented:
Small correction to santhimurthyd's example:

SQLConnection con = new SQLConnection(ConfigurationManager.ConnectionStrings["name"]ConnectionString);

Also, make sure to add a reference to System.Configuration.dll.
0
 
käµfm³d 👽Commented:
As a developer, you still have to change 'NorthwindConnectionString' in all 100 .cs file.
Declare a global constant that holds the name:

public const string CONN_STRING_NAME = "NorthwindConnectionString";

Open in new window


...then you 100 places would have:

connString =rootWebConfig.ConnectionStrings.ConnectionStrings[CONN_STRING_NAME].ConnectionString;

Open in new window


Now you only have one place to change.
0
 
Webboy2008Author Commented:
SQLConnection con = new SQLConnection(ConfigurationManager.ConnectionStrings["name"]ConnectionString);

kaufmed: thank, but i still have to change "name" for all 100 .cs in your example
0
 
käµfm³d 👽Commented:
P.S.

The above example is rather contrived. It does not demonstrate global-ness for 100 files. To achieve that, you would put that into a common class that all 100 files could access.
0
 
Webboy2008Author Commented:
i don't think so. it got to have a better solution. Thanks anyway. I may wait for more comment later.
0
 
käµfm³d 👽Commented:
i don't think so. it got to have a better solution.
Better than what? Changing it one place? It seems to me that you want it to be automatically detected by the configuration system. You can achieve this somewhat, but you would need to add some error checking. How would you guarantee that someone editing your config file didn't put in more than one connection string (which is possible, and valid)?

There is going to be some degree of expectation on the part of what your config file contains.
0
 
santhimurthydCommented:
You can do the same in more userfriendly and no need to change in codebehind

In the Web.Config file
Add an appsettings, which will carry the connection string needs to be used

Sample will be like

 
<configuration>
  <appSettings>
    <add key ="ConnectionKey" value="ApplicationServices"/>
  </appSettings>
  <connectionStrings>
    <add name="ApplicationServices"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

Open in new window


In you AppCode, declare an constant sring to get the connection string as like
public static const string ConnectionStirng = ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings["ConnectionKey"]].ConnectionString;

You can use the smae in you application as like
 using(SqlConnection conn = new SqlConnection(<<ClassNamewhereVariableDeclare>>.ConnectionStirng))
            {

            }

so, if you wan to change the connectionstring key, Just update at "AppSettings"  ConnectionKey value.
0
 
käµfm³d 👽Commented:
Also, you don't have to use name to index the ConnectionStrings property. You can use indexes also. You could instead do something like:

connString =rootWebConfig.ConnectionStrings.ConnectionStrings[0].ConnectionString;

Open in new window


...but again, this would depend on how many connection strings you had in your config file, and what order they were in. For example, in your web.config you could have:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
	<add connectionString="Data Source=prodServer;Initial Catalog=myDataBase;Integrated Security=SSPI;" name="PROD" />
	<add connectionString="Data Source=testServer;Initial Catalog=myDataBase;Integrated Security=SSPI;" name="TEST" />
  </connectionStrings>
</configuration>

Open in new window


...and using an index of "0" would return the "PROD" connection string; however if you swapped the lines:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
	<add connectionString="Data Source=testServer;Initial Catalog=myDataBase;Integrated Security=SSPI;" name="TEST" />
	<add connectionString="Data Source=prodServer;Initial Catalog=myDataBase;Integrated Security=SSPI;" name="PROD" />
  </connectionStrings>
</configuration>

Open in new window


...then an index of "0" returns "TEST".
0
 
Webboy2008Author Commented:
kaufmed: I will have two connection one dev/prod
can you show me coding experience in .cs
0
 
santhimurthydCommented:
Working based on Index in the connection string is not an Good practise as their be chance of getting wrong connection, if any other person in the team / support team may try to change the index postion. I had an bad experience with this Index based approach and thus why we went on Appsettings with what's the connection string need to use.

If you wish to go with Idex then the below code change to my code snippet

<configuration>
  <connectionStrings>
    <add name="Production"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=aspnetdb.mdf;User Instance=true"
         providerName="System.Data.SqlClient" />
        <add name="Development"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=aspnetdb.mdf;User Instance=true"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

In you AppCode, declare an constant sring to get the connection string as like
public static const string ConnectionStirng = ConfigurationManager.ConnectionStrings[0].ConnectionString;

You can use the smae in you application as like
 using(SqlConnection conn = new SqlConnection(<<ClassNamewhereVariableDeclare>>.ConnectionStirng))
            {

            }

You can even go with the appsettings mode

<configuration>
<appSettings>
    <add key ="ConnectionKey" value="ApplicationServices"/>
  </appSettings>
    <connectionStrings>
    <add name="Production"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=aspnetdb.mdf;User Instance=true"
         providerName="System.Data.SqlClient" />
        <add name="Development"
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=aspnetdb.mdf;User Instance=true"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

In you AppCode, declare an constant sring to get the connection string as like
public static const string ConnectionStirng = ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings["ConnectionKey"]].ConnectionString;

You can use the smae in you application as like
 using(SqlConnection conn = new SqlConnection(<<ClassNamewhereVariableDeclare>>.ConnectionStirng))
            {

            }

you can change the value of connection Key at the Appsetting.

check with this way also,
Give the same name to teh connection string for PROD and DEV, and comment out the not in use section

DEV
<configuration>
    <connectionStrings>
    <!--<add name="Appconnection"
         connectionString="data source=.\PROD;Integrated Security=SSPI;AttachDBFilename=aspnetdb.mdf;User Instance=true"
         providerName="System.Data.SqlClient" />-->
        <add name="Appconnection"
         connectionString="data source=.\DEV;Integrated Security=SSPI;AttachDBFilename=aspnetdb.mdf;User Instance=true"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

PROD
<configuration>
    <connectionStrings>
    <add name="Appconnection"
         connectionString="data source=.\PROD;Integrated Security=SSPI;AttachDBFilename=aspnetdb.mdf;User Instance=true"
         providerName="System.Data.SqlClient" />
        <!--<add name="Appconnection"
         connectionString="data source=.\DEV;Integrated Security=SSPI;AttachDBFilename=aspnetdb.mdf;User Instance=true"
         providerName="System.Data.SqlClient" />-->
  </connectionStrings>

In you AppCode, declare an constant sring to get the connection string as like
public static const string ConnectionStirng = ConfigurationManager.ConnectionStrings["Appconnection"].ConnectionString;

You can use the smae in you application as like
 using(SqlConnection conn = new SqlConnection(<<ClassNamewhereVariableDeclare>>.ConnectionStirng))
            {

            }
0
 
käµfm³d 👽Commented:
@santhimurthyd
...as their be chance of getting wrong connection, if any other person in the team / support team may try to change the index postion...
While I don't particular prefer the index route myself, the same could be said of the AppSettings approach. At the end of the day, there needs to be an expectation between the application's logic and the users who have access to modify the behavior of the application by way of the config file.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.