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.
Related
Folks,
I have an ASP.NET project which is pretty n-tier, by namespace, but I need to separate into three projects: Data Layer, Middle Tier and Front End.
I am doing this because...
A) It seems the right thing to do, and
B) I am having all sorts of problems running unit tests for ASP.NET hosted assemblies.
Anyway, my question is, where do you keep your config info?
Right now, for example, my middle tier classes (which uses Linq to SQL) automatically pull their connection string information from the web.config when instantiating a new data context.
If my data layer is in another project can/should it be using the web.config for configuration info?
If so, how will a unit test, (typically in a separate assembly) provide soch configuration info?
Thank you for your time!
We keep them in a global "Settings" file which happens to be XML. This file contains all the GLOBAL settings, one of which is a connection string pointing to the appropriate server as well as username and password. Then, when my applications consume it, they put the specific catalog (database) they need in the connection string.
We have a version of the file for each operating environment (prod, dev, staging, etc). Then, with two settings -- file path (with a token representing the environment) and the environment -- I can pick up the correct settings files.
This also has the nice benefit of a 30 second failover. Simple change the server name in the settings file and restart the applications (web) and you have failed over (of course you have to restore your data if necessary).
Then when the application starts, we write the correct connection string to the web.config file (if it is different). With this, we can change a website from DEV to PROD by changing one appSettings value.
As long as there isn't too much, it's convenient to have it in the web.config. Of course, your DAL should have absolutely no clue that it comes from there.
A good option is for your data layer to be given its config information when it is called upon to do something, and it will be called upon to do something when a web call comes in. Go ahead and put the information in your web.config. In my current project, I have a static dictionary of connection strings in my data layer, which I fill out like so in a routine called from my global.asax:
CAPPData.ConnectionStrings(DatabaseName.Foo) =
ConfigurationManager.ConnectionStrings("FooConnStr").ConnectionString()
CAPPData.ConnectionStrings(DatabaseName.Bar) =
ConfigurationManager.ConnectionStrings("BarConnStr").ConnectionString()
etc.
"Injecting" it like this can be good for automated testing purposes, depending on how/if you test your DAL. For me, it's just because I didn't want to make a separate configuration file.
For testing purposes don't instantiate DataContext with default ctor. Pass connection string info to constructor.
I prefer to use IoC frameworks to inject connection to data context then inject context to other classes.
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.
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.
I'm writing a desktop app which needs a simple persistence layer - I found out about SubSonic and it's capability to work with SQLite. However I need to keep the database file in user's AppData folder and don't know how to put such value into app.config - I don't want to use absolute paths.
Can app.config somehow access enviroment variables or reference application data folder?
For subsonic v2.x I would ignore the app.config connection string and just set it at runtime before working with the database. The provider name stays the same of course.
string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), #"MyApplication\Northwind.db3");
DataService.Providers["Northwind"].DefaultConnectionString =
String.Format(#"Data Source={0};Version=3;New=False;Connection Timeout=3", dbPath);
There's no way to specify the AppData folder in the app.config for a connections string.
But what you could do is write the value to the config file either during install or when the application is first run.
The "framework way" of finding appdata is to use Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
This will find the correct appdata path regardless of platform.
There are several ways if you are using ASP.NET , in either language
Server.MapPath("~") will return the root of the application as a full path name then you can just add "/app_data" to it to get you're full path.
Alternatively inspect the HttpContext.Current.Request and HttpContext.Current.Application
there are numerous ( and much better then the one I just mentioned ) properties that will provide you with the same folder - being the root of the application as s full path.
Note that these should all work even if you have the application as a virtual folder and a regular folder with an application configures in IIS on that folder
However this is only possible at runtime , so it can't really be mentioned in the app.config. you could try using relaltive paths from where the app.config is resident IE "../App_Data" or "/App_data" but I'm not sure of you're exact requirements.
Good luck
How can one specify the connection string in a config file of a class library and later modify this when used in a ASP.NET Web Application?
The Class library is a data access layer that has a Dataset connecting to a database based on a connection string specified in a config file (Settings.settings/app.config).
This class library is used in a web application where user inputs data and is written to the database using the DAL classes & methods exposed in the class library.
Now, I want to migrate this application from development environment to testing environment and later to production. The problem I'm facing is that after migrating to testing, the app in testing still connects to development database. I've changed the connection string mentioned in <class library>.dll.config file but this seems to have no impact.
Can someone explain the right way to achieve this? Thanks in advance for any help. Cheers.
With the .config files the name has to match the main executing assembly. For example I had a situation like yours, I needed a class library to have its settings in a .dll.config file. While it was able to reference it the actual application would not be able to read the config file because it was expecting .exe.config. Renaming the .dll.config to .exe.config fixed the problem.
In your case migrating your connection strings from .dll.config to web.config should fix your problem!
Good luck!
Joshua is partly right ... For posterity I would like to add a bit more to this answer as I have delt with the same problems on several occasions. First, one must consider their architecture. There are several issues you can run into with .config files in ASP.NET based on deployments.
Considering the architectural ramifications:
Single tier (one server):
A simple web application may be able to leverage a reference to the sites Web.config file and resolve your issues. This would be a fine solution for a single tier application. In the case of a windows application leveraged as a .exe file, the App.config will work too.
Multi-tier (more than one server):
Here is where things became a bit hairy for me the first time I was working with .config files across boundries. Remember the hierarchy of the config structure and keep this in mind (MSDN Article on .Config structure) - there is a machine.config at the root in the appropriate ASP.NET folder. These reside at each physical server. These are overridden by the site Web.config (or App.config) which are in turn overridden by subfolder .config files. If you have more than one .config file you may want to use one of the methods to pass the file path for the specific .config you want to use. More importantly, these files each may have connection information. ASP.NET's machine.config holds some for the framework ... so you should at least be senstive to the fact this is an "inheritance" chain. Second, any changes to the Web.config file once deployed will tell the application to restart. This will result in loss of state (bad if you have active users on the site). The way around this is to keep a separate .config file (e.g. connections.config) and put a reference to that file in the Web.config. This will allow you to change the connection information (e.g. password) without having to restart the application. Here is a link to more info: MSDN: Working with Configuration Files. This article lays out all the details you need to be aware of in a normal server / IIS deployed application. Keep in mind that the .config files are mainly intended for applications, not libraries. If you have several tiers, chances are you are using some communicaiton / messaging layer (e.g. WCF). This will have / allow its own Web.config. You can keep connection strings there (and encrypt them if needed), but better yet, put them in a second file referenced by the Web.config for manageability. One final point, if you are ever going to consider the cloud, .config files are wrapped for application deployments which in effect removes all of the benefits they offer in terms of "not having restart or redeploy". Azure deployments will want to consider this article to save themselves from nightmares of maintenance: Bill Lodin blog - Configuration files in Azul / Cloud. One other point on this article – great example on how to programmatically select configuration depending on deployment! Be sure to check that out if you want to add flexibility to deploy in or out of the cloud .
I hope these points saves all of you time and headaches. I know I lost a couple days of programming time dealing with these issues ... and it was hard to find all the reasons in one place why may app was not "implementing" its connection object. Hopefully this will save you all from the same fate I had.