How web.config is validated - asp.net

All,This question may be ignored everyday by us asp.net developer like air. If you think it is dumb, Please don't laugh. Thanks,
We knew the web.config is hosted in every Asp.Net web application. And It's syntax is restricted by the xml and DotNetConfig.xsd. The schema will describe what can be allowed in the web.config.
But When we look in a specified web.config.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
....
</configuration>
We didn't see any place to show this xml is based on the DotNetConfig.xsd.I mean any xml need to be validated should be documented which schema it is from
So that It can be validated in the runtime. Is that right ?
How does the validation works ? Could someone please tell me something about it .
Thanks.

web.config is not strictly validated against the XSD file at runtime. The XSD file is used by Visual Studio as an assistance to developers to avoid typos and other errors in known parts of the configuration file, however because .NET configuration is entirely extensible there is little point in performing XSD-based validation at runtime.
Some validation is performed by System.Configuration classes in the class library when they load configuration data, however per-element validation (in this sense) is the responsibility of the consuming configuration classes rather than the web.config loader/parser itself.

Related

Purpose of Runtime section in Web.config

When closely observing Web.config, all the possible child elements of <configuration> are also present inside configuration/runtime.
I have never encountered a need to specify values in configuration/runtime section. Have you come across this situation?
What is the purpose of specifying values in runtime section ?
The purpose of <configuration><Runtime> settings as described in msdn here
is
"Runtime settings specify how the common language runtime handles
garbage collection and the version of an assembly to use in
configuration files."
These are CLR settings that you can configure for your application. The possible settings directly under <configuration> is the not the same as <configuration><Runtime>. You can refer to the <configuration> schema here
To add to above reply i did face real time situation to use
"runtime" element for configuring Assembly binding.
I was using Ninject which was referring to System.Web.MVC 3.0.0.0 while i was having System.Web.MVC with version 5.0.0.0
This was causing IOFileNotFound exception
By Adding "runtime" binding i could redirect any binding for System.Web.MVC to 5.0.0.0 verison.

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>

Automatic schema generation from code

For configuring my ASP.Net Application I'm using Custom Configuration Sections in my web.config. But I would like to get IntelliSense support for my own-build configuration sections. I figured that it is possible to create a XSD Schema Definition and include that in the web.config. But is there a less painful way of getting that schema?
With Configuration Section Designer I found a tool offering a GUI for creating my configuration section and generating the schema. But I like coding and I don't want to learn how to deal with another GUI.
So, is there a possibility of automatically generating the schema for my code?
I have used this tool to generate generic schema from xml; See if it helps in your case.

How does one create Channels at runtime using BlazeDS?

So as you may or may not know, BlazeDS (open source version of LiveCycle Data Services) is a nice way to get your server-side Java and client-side Flex application to play together. Unfortunately, it does have several pitfalls that need to be corrected. I'll try to explain one of them here.
All of BlazeDS's configuration is written via XML files in the flex/ folder of your webapp. The default names are separated for clarity, such as services-config.xml, remoting-config.xml, messaging-config.xml, etc. In these configuration files (particularly services-config.xml), Channels are defined; these setup URIs and objects used to capture and send information between the server and the client. In these config files, it is quite common to use a syntax like so:
<channel-definition id="my-secure-amf" class="mx.messaging.channels.SecureAMFChannel">
<endpoint url="https://{server.name}:{server.port}/{context.root}/messagebroker/amfsecure" class="flex.messaging.endpoints.SecureAMFEndpoint"/>
<properties>
<add-no-cache-headers>false</add-no-cache-headers>
</properties>
</channel-definition>
Unfortunately, what they don't tell you is that some of these key-in replacements (ie: {context.root}) are not replaced dynamically upon execution but upon compilation of the WAR file you intend to distribute. Obviously not a good idea when switching domains.
So, instead I seek to dynamically define these channels. According to the documentation, that's all good and fine, but it only works if the channel already exists when the webapp is launched. I feel like that sort of defeats the point.
So my question is, how do you truly create channels dynamically so that both the client and the server recognize their existence?
Read this blog post; I believe it is what you're after.
I believe these xml config files have no direct relation to the server at all. They are used to tell the SWF how to find the server.
During Compile time of your Flex App; the services-config information is, in essence, hard coded into the SWF.

Alternatives to using web.config to store settings (for complex solutions)

In our web applications, we seperate our Data Access Layers out into their own projects.
This creates some problems related to settings.
Because the DAL will eventually need to be consumed from perhaps more than one application, web.config does not seem like a good place to keep the connection strings and some of the other DAL-related settings.
To solve this, on some of our recent projects we introduced a third project just for settings. We put the setting in a system of .Setting files... With a simple wrapper, the ability to have different settings for various enviroments (Dev, QA, Staging, Production, etc) was easy to achieve.
The only problem there is that the settings project (including the .Settings class) compiles into an assembly, so you can't change it without doing a build/deployment, and some of our customers want to be able to configure their projects without Visual Studio.
So, is there a best practice for this? I have that sense that I'm reinventing the wheel.
Some solutions such as storing settings in a fixed directory on the server in, say, our own XML format occurred to us. But again, I would rather avoid having to re-create encryption for sensitive values and so on. And I would rather keep the solution self-contained if possible.
EDIT: The original question did not contain the really penetrating reason that we can't (I think) use web.config ... That puts a few (very good) answers out of context, my bad.
System.Configuration.ConfigurationManager.ConnectionStrings and System.Configuration.ConfigurationManager.AppSettings
Contain settings from the executing application so in your DAL you can get the settings stored in your web.config file.
For your system you can create a custom configuration section that will sit in your web.config file or your DAL's consumer*.config file In these config files you can specify that they load from a separate config file of your design and location.
Referencing external config files from Web.Config
How to: Create Custom Configuration Sections Using ConfigurationSection
Alternativly you can manualy load your DAL configuration data from any file using ConfigurationManager.OpenExeConfiguration
You can add the equivalent to a web.config file called app.config that compiles into a file named for the dll or exe project of your code behind. This is completely changeable without having to recompile. You can use the standard settings for connection strings and various app settings that can be defined in a key/value pair - or with a little more work you can define your own custom config settings class and section. You can even reference settings in your app config - so you could have 3 settings stored in your app (DEV, QA, PROD) and then only reference the one you want at runtime in your app.config file. Here is an example of one that was created for a webs service setting.
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="{Project}.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
<section name="microsoft.web.services3" type="Microsoft.Web.Services3.Configuration.WebServicesConfiguration, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</configSections>
<applicationSettings>
<{Project}.Properties.Settings>
<setting name="{SettingName}" serializeAs="String">
<value>{SettingValue}</value>
</setting>
</{Project}.Properties.Settings>
</applicationSettings>
<microsoft.web.services3>
<security>
<securityTokenManager>
<add type="Microsoft.Web.Services3.Security.Tokens.UsernameTokenManager, Microsoft.Web.Services3, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" namespace="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" localName="UsernameToken" />
</securityTokenManager>
</security>
</microsoft.web.services3>
</configuration>
It sounds like you do not understand how web.config/app.config work, if I'm reading you correctly. Let's say you have a structure like the following:
DAL Project
References:
Some core libraries
Miscellaneous references
Classes:
DatabaseHelper
ObjectClass1
ObjectClass2
etc...
Web Project
References:
Some core libraries
DAL Project
Miscellaneous references
Pages:
Default.aspx
SomePage1.aspx
etc...
Web.config
In your DatabaseHelper class, you might reference the connection string like so:
string connString = ConfigurationManager
.ConnectionStrings["myConnString"]
.ConnectionString;
When this happens at runtime, your DatabaseHelper class will be running under the same app domain as your web page, and thus, any calls to ConfigurationManager will load the request from the web.config file provided by the web project.
Therefore, you only need the one config file in your web/console/winforms/etc... project, and do not need to worry about having one at design time in each of your class library projects.
If you actually run your DAL as a service or a separate console application or something, then and only then would you need to give the DAL project it's own app.config / web.config file.
Split it up. Use the fixed-XML storage file solution for the database connection, encrypted with .NET's built-in encryptor functions (do not roll your own). Then, using the resultant database connection, look up your 'settings table' in the database. This way you can modify your settings without a redeploy. If your customers need to be able to change the database connection string without visual studio, just write a small Windows Forms app that is capable of generating the encrypted connection string and saving the fixed-XML storage file, and, if necessary, also can connect to DB (via that same file) and modify the Settings table as the user needs.
A completely different approach would be to use SQLite and store all your application settings in there. You can password protect the database in question, if that is of importance to the application, and you can create some simple property/value tables to store the data.
Using the SQLite ADO adapter would only require 1 additional DLL into the projects to access the settings and the SQLite DB itself would be accessible to those folks that don't want to use Visual Studio. There is even a plugin for Firefox to interact with SQLite databases.
You could store the settings in any old Xml file and use the XmlSerializer to take your class and convert it to < - > from Xml. In another answer I wrote some code that did just that. The linked answer serializes a list of simple objects, but it also works to serialize one large configuration object.
Because the XmlSerializer serializes to/from public properties, if you don't want to allow values to change, you might need make the class itself immutable (popsicle style) or have a read-only facade that sits in front of the deserialized one.
It's a handy trick. You can set it up via ConfigurationManager.AppSettings[] with it's own config section and external file references, or you can alternatively just hardcode a specifc xml filename per configuration class.
Take a look of Config.Net - the easiest configuration framework for .NET developers.
A comprehensive easy to use and powerful .NET configuration library, fully covered with unit tests and tested in the wild on thousands of servers and applications.
You could have a Interface that mapped you settings that is used on your DAL. Then on the App you could just use IoC to feed the settings to the DAL.
If you're using a DI framework (like Unity) you can specify constructor arguments. So, hypothetically, your DAL provider could have a constructor that takes its connection string.
I know you can't enforce constructors in interfaces, but that's something we have to deal with. I know the framework has a few places where there are unspoken dependencies on constructor signatures...
Have a look at DslConfig. It seems this solves what you are looking for.

Resources