Web App Configuration Settings - Best Practices - c#

I was recently involved with patching a web app project and noticed the previous developer used database table for configuration settings instead of web.config (app.settings).
Which should I use? web.config or database table? Which is best?

Things should go into the web.config in the following situations:
They're things that must be available to make the database available (db connection string!)
They're things that, if they should change, you want the application pool to refresh, or that are insanely unlikely to change.
They're things that need to be available when the database is unavailable for any reason (such as a list of email addresses and an smtp server to send error messages to, or locations where log files belong)
Things should go into the database in the following situations:
Both your DB and your web layer use that configuration.
You need the ability to change the configuration on the fly, without forcing an application pool refresh.
That said - if you're going to put your config in the database you probably want to cache it in some way in the web layer so you're not hitting the db unnecessarily. I suggest the Cache class for this.
In addition to all of the above, you will also need to consider your company's policy for working with your servers. If its very, very hard for you to work with the db, it might make more sense to put things in the web.config and vice versa.

One advantage for using a database for the settings is that things can be changed on the fly without disrupting the production website.
Changes to the web.config file will cause the worker processes on IIS to recycle and the app to be re-started. If you are using InProcess sessions, those will be lost. This could potentially disrupt your website users.

We use a combination of both web.config settings and database level settings.
For each setting we ask the following question: "Is this setting specific to the machine that the application is running in?" If it is, then it goes in the web.config. If not, then we ask an additional question: "If this setting is changed, should the app be forced to reboot?" If yes, web.config. More often than not a reboot is not acceptable for our service level agreements.
Most of our applications are multi-tenant and/or run in a web farm. Simple things like a local file system path, logging level, or database connection strings go in the web.config. The reason is that these deal with resources specific to that machine.
Pretty much everything else is going to impact program execution and must be accessible to both the app and data layers. Also, they tend to be needed by other applications (assuming multiple applications hit the same database).

It it makes sense why the prev. dev used the DB for setting, go with it. You must have a web.config, I think an ASP.NET can't work without it. Project configuration setting should go into web.config (declarations of custom controls, additional assemblies etc...), but user settings or anything specific about the business logic may be better off in the database.

A contentious issue between developers and DBAs at my company.
In my opinion you should always use configuration files for application level, read-only settings. If the settings are user specific or editable at runtime you may or may not want to reconsider the approach.
I have seen situations where settings are stored in the database that are used internally within stored procedures. I can see some justification for this, but it’s not critical since the value can be passed to the procedures via a parameter.

One consideration may be that once the web application is deployed, the developer no longer had access to the web.config files in the production environment.
If he's occasionally needing to view settings to provide any form of support, putting settings in a database where he can get read-only access to a configuration table may make tons of sense.

One use case that argues for a database is load-balanced applications, like web farms. There may be some settings that are relevant to a single machine distinct from the other machines in the farm, that need to go in the web.config, but there will probably be a whole slew of settings that are supposed to be identical across the farm. The farm is supposed to look like a single application from the outside, and can benefit if it can be configured like a single machine. That means some sort of shared repository, like a database.

Related

for securing a database that is meant to be accessed by several clients, is using a web service as a proxy an overkill?

we're going to have a database, and a client application that is going to be installed on several machines in a local network, and they must be able to access the DB.
Some of them must be able to edit and modify the DB, and some of them are going to just read them. each of these two groups are separated to several groups too, based on who must be able to access to which table/field.
To create this application, we were gave an advice to deploy a web service to role as a proxy between clients and the DB, in order to secure the DB.
But we're not transferring any sensitive data (such as credit card numbers or...) and we're only afraid of not an unauthorized person be able to modify the DB.
Isn't just using the integrated security option in the app.config sufficient?
Do we really need to hide and secure the connection string?
It could be overkill, but it might not be. Deciding to go to a Service-Oriented Architecture could be based on several factors, among which:
How long are you expecting to maintain this application?
How many client deployments are you expecting?
Do you expect your database to change often?
What are your SLA requirements?
Do you expect the database to eventually be used for other applications?
etc...
The long and short of it is, if you want to be able to change things in the middle tier or database, and you don't want to have to upgrade every client when you do so, adding a Service layer might be the way to go. You also have the advantage of providing a rich API for other client developers (internal or external) while controlling business rules and security in one, centralized location.
SOA definitely adds to the complexity of the project, but in many cases, it can save you a lot of headaches in the future.
For further reading, look at http://en.wikipedia.org/wiki/Service-oriented_architecture, http://www.soapatterns.org/, or Google.
Sounds way overboard to me. If the application is only going to be used internally, and Windows authentication is an option, certainly use it. Building a web service is only going to slow down development and add an unnecessary layer of complexity. The read/write users could be members of a Windows group that has read/write access to the database, and the read-only users could be members of a Windows group that only has read access to the database. Then, if the user is able to gain direct access to the database (without using your front-end) they would only be able to either read or read/write based on their Windows rights.

Use different connection string based on the application url in .net

I have a asp.net web project named FinanceTracker (which is under use for an year).
And the data is stored in Finance_Tracker_db.
(this is a intranet web site to track the financial data for an organization, accessed from
http://OrgTracker)
Now I have a requirement to have the same application for IT department.
everything is same on the data for both should be segregated.
So I created an empty copy of database name IT_Tracker_db.(on same database server)
And used the old code with modified connection string in web.config
(accessed from http://OrgTracker/IT/ deployed on same IIS server)
But as to have less maintenance to apply the same code to both deployed version, I am planning to use the same code with different connection strings.
Now I wish to have something like.
http://OrgTracker/ - This should show two links
http://OrgTracker/fincance/
http://OrgTracker/IT/
And based on user selected URL the proper connection string should be used from web.config
Like all pages will remain same like.
http://OrgTracker/fincance/Status.aspx, http://OrgTracker/fincance/Inbox.aspx, etc.
http://OrgTracker/IT/Status.aspx, http://OrgTracker/IT/Inbox.aspx, etc.
Can have more than one config
ASP.NET Configuration File Hierarchy and Inheritance
I suggest not doing this. First, it is complicated and out of build-in ASP.NET functionality.
Second, in some time in future your users can demand different things: one department would want newer version immediately, while the other one would want to have stable old version until they can test everything.
P.S. But if I were you, I'd start thinking about adding additional column called "Department" in all relevant tables so I could unite databases in future. This goes against my second point :), but it would make everything more manageable and architecturally sound, especially if more departments would want to use your application.

Where to store application global settings?

I have some global settings
For example some below are
ShortLeaveAllowedInOneDay = 2
LeaveAllowedInMonth = 3
I have following options to store these global settings
1-Store in Database table
2-Store in Webconfig file
3-Store in class as const filed
4-In XML file
Could you please suggest me which one is better approach and why
I am using Asp.net MVC3
with sqlserver 2005
It depends on your requirements, each one of these options has it own advantages and disadvantages. It tried to list a few:
1. Store in Database table
Advantages:
Relatively easy to read settings.
Possible to write/update settings.
Access is to the database is fast.
Updates to database values are immediately available.
DB is can be shared across multiple instances in clustered environment.
Disadvantages:
More infrastructure required than the rest of the options (i.e. tables, db access etc).
If done incorrectly DB IO can become an issue. (Can be solved with caching strategies)
2. Store in web.config file
Advantages:
Simple to add and access settings.
Disadvantages:
Changes to the web.config may result in the application pool to restart.
Settings are generally not encrypted.
In a clustered environment the file has to be kept in sync with other instances.
Generally have to deal with strings data types and possible invalid user input when settings are set.
3. Store in class as const field
Advantages:
Very simple to work with.
Can work with static types.
Good first step towards refactoring settings into one of the other options.
Disadvantages:
Requires rebuild for settings to change.
4. In XML file
Advantages:
Convenient for storing complex settings such a hierarchies.
Custom XML config settings can be embedded inside the web.config. (Popular option see log4net as one such example)
Updates to the config files can be made without restarting the application pool.
An XSD can enforce the validity of the settings in the file (both structure and data types)
Disadvantages:
It is XML. Not really human readable, formats like YAML improves on that.
Implementation required to parse XML for reading and writing settings.
If you need them to be configured by a user of your software I would not do option 3. If they are settings that you define as a programmer and do not expect them to be changed when your application is in production you could do that.
I would say that option 4 and 2 are basically the same, conceptually, and it is personal preference which to choose. Personally I like to define a custom configuration section and then have just that section defined in it's own .config file (this shows how to do that) so that you don't have a really massive web.config that the user has to navigate.
I would choose option 1 if I had a scenario where I had multiple components that all need access to the same configuration. If all you are building is a single web application, it does not feel necessary to me to do that but if, for example, you have a web application and some other client application and both require access to the database then storing the configuration there is a good choice.
Add an AppSettings session in the web config file, that can be accessed from the code directly like :
System.Configuration.ConfigurationManager.AppSettings["ShortLeaveAllowedInOneDay "];
EDIT :
and the Confir file would look like :
<appSettings>
<add key="ShortLeaveAllowedInOneDay " value="2" />
</appSettings>
No approach is inherently better than the others.
The best approach depends entirely on what your requirements are for things like security, scalability, flexibility, read-only vs. writeable, config complexity, and so on.
Storing global variables in the web.config file is a very common task.
Storing values in your web.config file is extremely useful when a database might be overkill and when you don't need a separate external file.
Reading the .xml file several times for each page lifecycle would be VERY bad for performance.
I would definitely go for web.config.
You can store the variable in Web.config file.
I will be more practical. Two basic cases.
Values/parameters that changes ones and are critical to start/run/initialize the program
Values are change offend, or they are different for every user.
You store the initial variables on web.config, and all the other on database. If you do not have database, then what ever is available, like XML file.

Simple Advice where to save setting

Im programming C# WinForm application which have big SQL Server Database.
I need to make setting.
I dont know how to save application setting. Which is better just add my solution .setting file or save in database Table?
I hate to say it, but it depends on whether the setting is intended to span all clients to the database, vs whether different nodes/applications would require different values. Having the values in the database can make it easier to centrally configure the system via the system itself (an admin page), without needing to re-deploy or reconfigure any nodes.
Disconnected clients can also work either way, as long as they capture the settings locally when connected (being able to connect at least once is not unreasonable).
Of course, even per-node settings can be in the db if you add suitable dimensions to the table. The one setting that is a pain, of course, being the connection details...
use application configuration file to save your app wise settings.
Depend of your needs, when use app.settings (tutorial http://msdn.microsoft.com/en-us/library/ms143432.aspx ) file it will be stored with application itself, when you strore them in database is more accessible.
You edit: (have) (sure you don't have, sorry for my poor english ....) you can to store configuration in the app.config file. Here's a post about using configurations files.
Informations will be accessible by the Configuration manager (Msdn link) Class.

What's the right approach to storing application configuration parameters in an ASP.NET Application?

We have lot of application parameters for each module in a C# .NET 4 ASP website.
parameter examples: timeouts, formulae constants, thread limits per module, $ charges per usage etc.
What is best out of following approaches we know:
Use DB config table
Use an xml. load that xml into local cache on start (and on xml change)
simple constants.cs file with public const int XYZ = 123; type of key-value pairs.
web.config (though i think its mostly for deployment type of config)
Any other way ?
Help on pros and cons and std. approach followed would be helpful.
I like #1, storing the values in the database, for several reasons:
This works on a web farm. You don't have to synchronize versions of web.config on multiple servers.
Making changes does not require recompiling and redeploying the application. Changes can be immediate.
It is relatively easy to create a maintenance web page for authorized users to update the values without bugging production support.
The values can be determined at any time from outside the application by anybody given access to the database (or to a maintenance page displaying the values). Nobody has to read through the source code or look at web.config files.
The web application does not have to be restarted for the change to take effect.
Edit: Additional comments about the other proposed methods:
If the app is going to be on a web farm, all three non-database choices will require deployment to all servers. This is not a trivial matter if a lot of web servers are involved, if the deployment procedure is complicated, or if corporate policy severely limits who (and when) changes can be deployed to production servers.
Even when there is no web farm, in a corporate production environment, it can be excruciatingly slow to deploy a change.
Regarding constants, I have found that they tend to get sprinkled all over the application code. Finding them can be a real challenge. Of course, if you have the discipline to centralize the configuration constants, you won't have this problem.
There is one other approach not on your list, which is using resource files (.resx). While this is generally used for localization, I have seen it used for configuration values, and especially for storing the text of standard messages. While you don't have to recompile your application to alter a .resx file, changing it will cause the application to restart.
In summary, then, my reasons for preferring the database approach are the speed and ease of deployment, avoiding recompilations and app restarts, centralizing the data outside the application, and making the data accessible to business users.
You seem to mix different level of setting together:
Timeout is best suited to be part of a web.config file, while
$ charges per usage is more related to a per-user setting and should be located in a database along with the user.
Should you decide to use a web.config file, I suggest the following to keep your web.config file clear of application settings.
Create a file that will store your settings. I usually create a file named as the application, like nerddinner.config. Remember that the config extension is used for security reason.
Add your setting in the file:
<appSettings>
<add key="Test" value="Hello world"/>
</appSettings>
In your web.config file, create the <appSetting>, but redirect it to the other file:
<configuration>
...
<appSettings configSource="nerddinner.config" />
...
</configuration>
In order of preference:
Web.config - The main benefit of using web.config is that the application pool is automatically recycled when the file changes. Also, you have the well-known System.Configuration API for accessing the data. You shouldn't have to muck around with a separate XML file and monitor it for changes when ASP.NET already has support for configuration files.
Constants file - This has the same app pool recycling benefits as the web.config, but it's more likely that you could accidentally introduce new bugs when deploying new assemblies than editing .config files. If you work in a shop where untrustworthy non-programmers are in charge of the config files, having something compiled in does reduce the chance of entering bad data.
Database config table - Fetching configuration data from a database is more complicated than retrieving it from a config file. Plus, you have to be careful about data locks and other DB goodness. However, if you need to edit settings at runtime without triggering app pool recycling (unlikely), this is your best bet.
XML file - It's easier to use web.config, but this allows you to deploy a file independent of the web.config so it is less-likely to contain potentially-hazardous side-effects.
Well, option 4 (web.config) is safer than option 2 (xml). A .config can't be downloaded so easily.
For the rest it depends a little, there is no 'right' way but i would use a web.config unless there is a really good reason not to. Web.config is not just for 'deployment related' stuff.
1.- Use DB config table when you want to change parameters without having to restart your application. Prefer its usage.
2.- Use xml file. If your application is XML oriented.
3.- Simple constants file. This should not have parameters, constants are not parameters.
4.- web.config. Use appSettings items for storing simple values that does not change continuously (DBConnectionTimeout, DBCommandTimeout, PageSize etc..), use customized sectionGroup for more complex parameters.
Here is a simple configuration table definition:
CREATE TABLE ctr_group_parameters (
option varchar(50) NOT NULL,
id_group int NOT NULL,
description varchar(100) NOT NULL,
value varchar(200) NOT NULL,
PRIMARY KEY CLUSTERED (option, id_group) )
If these are settings that wouldn't be updated often, I like using web.config. If they are updated a bit more often, I'd think about using a database table.
I'd use the web.config for stuff you know never changes except when it changes along with application logic. For stuff that may need to change independently of code (like $ charges) you may want to use a database.

Categories