28 Jun 2011

Settings.settings vs web.config file with a web service reference

I have a class library called myClassLibrary that contains a reference to a web service.
The web service URL is stored in a Settings.settings file.
This in turn creates an app.config file.

I use myClassLibrary in a web project, and I ran into the problem that the default URL for the web service that I had specified in Settings.settings needed to be different when my web project was in our test environment. So I wanted to be able to override the Settings.settings value with, say, a value in my web.config.

This is how you do it:

Settings.settings


The URL is defined as a value with Scope set to "Application" and a GenerateDefaultValueInCode property set to "TRUE".
This provides a default value when myClassLibrary is run in a non-web context with no override in the app.config file.

app.config


The URL is set in an applicationSettings block to override the default value when the class library is used in a non-web context.

    <applicationSettings>
        <myClassLibrary.Settings>
            <setting name="myWebServiceUrl" serializeAs="String">
                <value>http://whatever.com/myService</value>
            </setting>
        </myClassLibrary.Settings1>
    </applicationSettings>

web.config


Here is where we do the override for use of the class library in a web context.

Firstly we have to define a configuration block that will match the one in app.config:

  <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup" >
      <section name="myClassLibrary.Settings" type="System.Configuration.ClientSettingsSection" />
    </sectionGroup>    
  </configSections>

Then we just implement that block with our override value.

  <applicationSettings>
    <myClassLibrary.Settings>
      <setting name="myWebServiceUrl" serializeAs="String">
        <value>http://another.com/myAlternativeService</value>
      </setting>
    </myClassLibrary.Settings>
  </applicationSettings>  

22 Jun 2011

.NET Project File - Include External CommonAssemblyInfo file

I wanted to register a common AssemblyInfo.cs file in the Properties folder of my project. This file is actually external to my project, so how to do it?

Add this to your csproj file in the <ItemGroup> section with the Compile elements.

<Compile Include="..\CommonAssemblyInfo.cs">
<Link>Properties\CommonAssemblyInfo.cs</Link>
</Compile>

Then just strip out the [assembly: Whatever()] bits from the original AssemblyInfo.cs file and put them in the CommonAssemblyInfo.cs file.
If I helped you out today, you can buy me a beer below. Cheers!