Where to store application global settings? - c#

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.

Related

How to persist / save program information

I wrote a reminder program that runs automatically on startup. I want to know if there is a way, other than SQL-Server, to store event, date and time data. I do not want to use SQL-Server for this work, because I think SQL-Server is very big for this simple task. I think that I can use a file to store data in it. What do you think about this?
Some common ways to store information:
As a file. You have many options where you can store the file. For instance, user directory, and program directory. Further explanation here and here. I prefer using a serializer (xml or json).
As a registry entry. You store your information as key-value pairs.
In a light-weight database:
RavenDB: its document-oriented, and stores data in json format
SQLite: relational; I recommend this SQLite Admin for managing purpose
Registry entries are more safe regarding user actions. On the other hand, files can be easily deleted.
You always have the option, to encrypt your information.
As a side note, you can also use PostSharp to declare variables to be stored in your registry. The code becomes something like this:
[RegistryBacking]
private bool _boolean;
I can provide code later if you need it... when I'm home again.
For the part where to persist
From this document (Managing User Data Deployment Guide, download):
Windows uses the Local and LocalLow folders for application data
that does not roam with the user. Usually this data is either machine
specific or too large to roam.
Windows uses the Roaming folder for application specific data, such
as custom dictionaries, which are machine independent and should roam
with the user profile.
So, I suggest using AppData\Roaming and persisting to a file since I consider a 'reminder app' to be user specific. And domain users for example would consider that valuable (syncing to server).
Local and LocalLow (the latter is used for low integrity mode, for applications with reduced privileges) would be more appropriate for some machine/installation specific data which can be calculated on-the-fly.
Registry seems great for some low amount of keys, but doesn't seem to be the best option for such use.
There is another option - IsolatedStorage, which should be used when mentioned options are not applicable, like when using ClickOnce deployments.
For the part how to persist your data to a file ... well, pick your favorite. You could use SQLite database which comes really lightweigt if you want more control and power or just use XML serialization to a file if you consider using SQLite an overkill. Or any of other viable options.
XML. .NET has classes that makes handling xml files easy. If you're saving structured data then XML might be your best bet.
I have for very similar reasons tried some easy to deploy databases and yet use the knowledge i have.
VistaDB 3.x and 4 are my first choice because they are very much SQL Server compaible and allows me to switch to sql server anytime i like. This supports EF too!!!
Next is db4o by Versant which is very very handy. I use it mostly for quick prototyping but i have deployed to several small solutions and perfect for your kind of application.
I hope that helps!

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.

Web App Configuration Settings - Best Practices

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.

What's the preferred method for storing user settings in a .NET windows application?

Pardon my ignorance, but I've never really developed Windows applications. How do you store user settings? Is an embedded database the preferred method?
I think you are looking for user settings:
The .NET Framework 2.0 allows you to
create and access values that are
persisted between application
execution sessions. These values are
called settings. Settings can
represent user preferences, or
valuable information the application
needs to use. For example, you might
create a series of settings that store
user preferences for the color scheme
of an application. Or you might store
the connection string that specifies a
database that your application uses.
Settings allow you to both persist
information that is critical to the
application outside of the code, and
to create profiles that store the
preferences of individual users.
It depends on what kind of settings. There are a variety of methods from embedded databases (like SQLite) to XML files, to the Registry.
If the settings are very few, the registry often makes sense.
If the settings are more complicated, and need to be hand edited, you can use XML files or JSON.
If the settings are complex and do not need hand editing, an embedded database like SQLite, .NetBtree, or BerkelyDB .NET are good choices.
Use Blane's Pegasus Library (http://pegasus.codeplex.com/).
You could use his XmlSerializationHelper class which makes it a snap to turn objects into XML and vice versa.
Or you could use Isolated Storage (I would provide a link to MSDN if I wasn't a new user and restricted to one hyperlink per post). If you use IsolatedStorage, consider using Blane's IsolatedStorageHashtable class.
It all depends on what size of an application you are building. If you are on something simple, let's say, "family shopping list", you can store the settings in a good old plain text file.
If you are building something bigger, for example a "classmate notifier" you can use an XML file, or some kind of other resource.
For any bigger application you should use some kind of relational database, for storing user data.

Categories