How to Reference ConnectionString in ASP.NET? - asp.net

I have a web project and a separate project for a class which contains a constant and I am thinking of adding a connection string. What is the best way for storing this?
Thanks

Add a section to your web.config file called ConnectionStrings, as a child of the <configuration> element. An example might look like:
<connectionStrings>
<add name="MyConnectionString"
connectionString="Server=myserver;Database=mydatabase;Uid=username;Pwd=password;"/>
</connectionStrings>
In your code, use the ConfigurationManager to access your connection strings. For example,
string connStr = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString();

Add it to settings file. In Visual Studio, go to My Project -> Settings and add it there as (Connection String). You can access it this way: C# - properties.settings.default...; VB - My.Settings...

I would advise against storing your connection string in a hard-coded constant. There are many problems with that, not the least of which you aren't actually able to "configure" your connection string for different environments. Having it hard coded makes it very difficult to test your code in one environment against a different database than your production environment, without having to recompile your code. There are also security concerns in regards to hard-coding configuration, particularly connection strings.
I recommend reading the following article...it should give you a good base about storing connection strings in the standard .NET way:
Connection Strings and Configuration Files (ADO.NET)

Put it in the settings file for the project. The settings file is merged into the .config file - and you get a class automatically built for you with accessors for the stuff in the settings file.

Related

asp.net production / development environments

Most of my previous web applications have built using the pyramid (python) framework. With pyramid, it is possible to run the application in either development or production mode. This is achieved by providing the location of a production.ini or a development.ini settings file as one of the start up arguments to the application.
This file contains settings relating to logging levels, error reporting and database connections. The equivalent of these files in the .net world would appear to be web.config files. I assume i can create different execution environments, by simply creating a new web.config, renaming it to something appropriate, and restarting the application.
My question is, how can i get my app to target the correct *.config file (hypothetically call them production.config and development.config)?
You may want to look at MSDeploy. I use this for similar situations and it's helped me establish a single parameters file (of what is to be replaced, regardless of if it's XML, a filepath, text file, etc.) and multiple set parameter files [you can read about declareParam and setParam here.
Without knowing too much of your structure you are basically going to do something to the effect of this.
msdeploy -verb:sync -source:contentPath=c:\pathtosite\root -dest:package=c:\package.zip -declareParamFile=c:\packageparameters.xml"
Create an associated parameters file for each environment such as
development.xml
staging.xml
production.xml
(Here is a good explanation of parameter file setup)
then for your deploy you would have something (depending on the providers you want to use)
msdeploy -verb:sync -source:package=c:\package.zip -dest:contentPath=c:\inetpub\production -setParamFile=c:\<environment>.xml
The # of providers is pretty extensive. Content Path is just an easy example, but you can pull directly from IIS, to IIS, etc. Pretty robust.
There's no way that I know of to specify a different web.config file. Since .NET 4.0, however, you can use something called web.config transforms, which modify your base web.config on build. You can have a Web.Debug.Config and Web.Release.Config, which get applied depending on which build configuration you're using. Keep in mind these aren't normal web.config files, but rather transform files that modify the base web.config.
For more info and a walkthrough of the basic idea involved, see here on MSDN. The basic example given of a web.config transform file is this, which modifies a connection string to use a different connection string for the release build:
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings>
<add name="MyDB" connectionString="ReleaseSQLServer"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
</configuration>

Web.Configs across different development environments (and SVN)

So we have a build process that handles different development web.configs across different environments. We use the ConfigSource attribute and have Team City pick the appropriate file.
That's great, but what do I do when the developers have slightly different environments?
CI, can't help, because everyones getting it straight out of SVN (i.e. CI obviously doesn't build to each developers local machine).
I'll use the ConnectionStrings config section as an example:
<connectionStrings configSource=".\Config\ConnectionStrings.config">
</connectionStrings>
And we have:
configs\ConnectionStrings.config (the generic one)
But I might need to use:
configs\ConnectionStrings.dev1.config
configs\ConnectionStrings.dev2.config
configs\ConnectionStrings.dev3.config
depending on which developer is using the code at the moment.
Any ideas?
Have you tried looking into web.config transformations? They might be able to provide the functionality that you seek while still keeping everything in version control or needing any code changes. Plus it will work for more things than just connection strings, but also directories, etc.
One technique we've used in the past (I recall Ayende mentioning it on a web cast) is that each connection string is named with the developers machine name e.g.
<connectionStrings>
<add name="BobsPC" connectionString=""/>
<add name="JonsPC" connectionString=""/>
</connectionStrings>
When in debug we then look for a connection string name of the "current" machine name.
This saves having multiple connection string files. Instead we have one file with multiple connection strings.
We have a separate connection file just like you mentioned with the current machine name in it.
In the build event for the projects that need a connection string we've added a pre built event that deletes the connection.config file from the current project and in the post build event we copy connections.machine.config to connections.config in the current project folder.
In our web.config we have a so .NET will look in a separate file for the connection string information.
Web.config transformations can only be used when you actually deploy a project. The 'default' web.config will always be used on your local development machine so this is not an option for development environments.
You can extend this mechanism also to app settings and other config files by placing the machine specif ones in the solution folder and just copying them on build.

Connection String in a .Net Windows Program

I'm working on my first Windows .Net application (as opposed to a .net web app, which I've done a lot of), and I have a question about database connection strings - is there an equivalent to the section in web.config?
I want to be able to have the program run against our test database (which will required a different connection string. What is the "canonical" way to define connection string objects in a Windows .Net application?
Thanks
Rather than write this all down again, here's a good article on this subject:
Storing and Retrieving Connection Strings
Add an "application configuration" file to your project. It will add a file called "app.config" Put your connection in there.
When the app is compiled it will change the name of the config file to match your executable. For example: MyApp.config.
I'm not sure what you mean by "canonical" way to define connection string objects. Name them whatever you want. Sometimes we use the name of the database, sometimes just the name of the project.
With regards to having multiple config files, we use Config Transforms. Which name them app.config, app.debug.config, app.release.config, etc. and use configuration manager to define which one to use based on where it's being deployed.
Non ASP.Net apps simply use app.config instead of web.config. See here.
Connection strings can be stored as key/value pairs in the
connectionStrings section of the configuration element of an
application configuration file.

Difference between Setting.settings and web.config?

This might sound a bit dumb.
I always had this impression that web.config should store all settings which could be subject to change post-build and setting.settings should have the one which may change pre-build.
but I have seen projects which had like connection string in setting.settings. Connection Strings should always been in web.config, shouldn't it?
I am interested in a design perspective answer.
Just a bit of background:
My current scenario is that I am developing a web application with all the three tiers abstracted in three separate visual studio projects thus every tier has its own .settings and .config file.
Web.config is mostly meant for configuration, and it also stores the default values of your settings.
Settings.settings is just a convenience file for Visual Studio to provide a UI for editing your settings.
The .config comes in two different flavors: App.config for Windows applications, which will be named YourApplication.exe.config, and the Web.config for web applications. They share the same schema, syntax, and options.
You may notice that if you add a setting to Settings.settings, it gets added to the .config as well.
The .config must be deployed with apps, but Settings.settings doesn't need to.
Setting.settings is a class, it is not used to store the connection string as such, it is used to expose a specific connection string from web/app.config as a property on a class. VS does also tend to hard code a default value if the particular connnection string cannot be found.

Configuration madness, I have an app.Config but my object looks to web.Config

if you have a class library project that acts as ur DAL and it has an App.Config file with connectionstrings, how can I force it to use that config file? It keep getting values from the web.config in my Web Application project.
The DAL project uses LinqToSql. When I instansiate a DataContext object in my Web Application, from the referenced DAL Class Library project, can I make it use it's app.Config connectionstrings? It seems to ignore this file and tries to pick up connectionstrings from the web.Config connectionstrings node. There are no connectionstrings present there.
Any help is appreciated. A colleague mentioned making the app.Config in the DAL and embedded resource. Does that sounds like a good idea?
Thanks,
~ck in San Diego
Web applications always use web.config. Desktop applications always use app.config.
how can I force it to use that config file? It keep getting values from the web.config in my Web Application project.
You can't. If you use the System.Configuration classes, they will always pull from the active application's .config file (app.config for executables, web.config for asp.net websites).
Workarounds include using file i/o for reading your settings out (as opposed to the System.Configuration namespace) or putting your DAL configuration information in the appropriate .config file (the more common choice).
I'm not sure, but take a look at that:
using System.Configuration;
ExeConfigurationFileMap Map = new ExeConfigurationFileMap();
Map.ExeConfigFilename = FileName;
Configuration Conf = ConfigurationManager.OpenMappedExeConfiguration(Map, ConfigurationUserLevel.None);
AppSettingsSection section = (AppSettingsSection)Conf.GetSection("???");
Here's how I think of a *.config file. Say you have a method in your DAL:
DoSomething(connectString, SqlDialect, businessObject)
Since connectString and SqlDialect don't change with every call to this method, it would be nice to be able to remove those parameters and get those through some other means.
Well, *.config files are there for that reason--they are not only environment-specific, they are also app-specific. It's so your Web app can say, "Hey everybody, connectString = "..." and SqlDialect = "...", for every method call, until I say otherwise."
Let's say you want one app to log into SQL with one set of credentials, and another app to use another set of credentials (with different perms if necessary) so that the DBA can keep track of which app is doing what (if he/she so chooses). Well, *.config files make this happen.
That's why the app that you're running is the one that provides the *.config file. So just cut all the contents from your DAL's app.config file and paste it into your Web.config file, then delete App.config. You should be good-to-go after that.

Resources