peschuster

Technology, .NET and Web

  • Info

ASP.NET

How to configure ConnectionStrings in web.config per developer/user

December 9, 2012 by peter

One thing Martin Fowler states in his article about Evolutionary Database Design is that every developer needs to have its own database instance.

For .NET Windows client projects you can simply change the ConnectionStrings configuration in the App.config file inside the bin directory. But for web/ASP.NET projects this is not possible, because the root directory for debugging the project is the project directory itself (being under source control). I.e. you would have to checkout the web.config file from source control and edit it. This itself is not such a problem, but you always have to watch out to not check the changed web.config file into source control.

The Solution

A solution to make this work is to split the web.config configuration into multiple files and extend the build process by editing the project file of the web project to create a configuration file which is not in source control and therefore can be customized per developer.

1. Split the configuration

Replace the connectionStrings configuration in your web.config file with the following line:

  <connectionStrings configSource="connectionStrings.config" />

2. Create a default configuration

Create a new configuration file “connectionStrings.default.config” with your configured ConnectionStrings (example):

<?xml version="1.0" encoding="utf-8"?>
<connectionStrings>
    <add 
      name="MyDbConnection" 
      connectionString="Data Source=(local)\SQLEXPRESS;Initial Catalog=MyAppDb;User ID=myapp;Password=123pw" />
</connectionStrings>

3. Extend the build process

Edit the project file and include a new target “BeforeBuild” (at the bottom of the file, but inside the “project” node):

<Target Name="BeforeBuild">
  <Copy 
      Condition="!Exists('connectionStrings.config')" 
      SourceFiles="connectionStrings.default.config" 
      DestinationFiles="connectionStrings.config" />
</Target>

This extends the build process with a new step which checks whether the file “connectionStrings.config” exists and (if not) copies the file “connectionStrings.default.config” to “connectionStrings.config“. When you want to change a ConnectionString in your local development environment you can simply edit the file “connectionStrings.config” and adjust it to your environment.

4. Add a transformation for publishing

For publishing/deploying your project you can create a web.config transformation which “inlines” the ConnectionStrings again:

<?xml version="1.0" encoding="utf-8"?>

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <connectionStrings xdt:Transform="Replace">
    <add 
      name="MyDbConnection" 
      connectionString="Data Source=(local)\SQLEXPRESS;Initial Catalog=MyAppDb;User ID=myapp;Password=123pw" />
  </connectionStrings>
</configuration>

Summary

Summing it up, the solution consists of the following parts

  • An outsourced ConnectionString configuration not under source control.
  • A default ConnectionString configuration under source control.
  • A build step ensuring a ConnectionString configuration exists at the expected path.
  • (Optional) A web.config transformation for cleaning everything up on publishing/deploying the project.
Posted in: .NET, ASP.NET Tagged: .NET, ASP.NET, Build, Configuration

Reporting Exceptions from ELMAH to Graphite and StatsD

October 25, 2012 by peter

On one project we use Graphite and StatsD to monitor some webserver and performance parameters of the site and ELMAH to catch all unhandled exceptions. Wouldn’t it be cool to also see the occurrence of exceptions captured by ELMAH in our Graphite graphs?

For this purpose I extended my library of Graphite “tools” by a Graphite.Elmah project.

ELMAH is designed to support only on backend for logging errors. This is usually configured to be some kind of database backend to store exception details for later access. Therefore Graphite.Elmah hooks into ELMAH using a custom error filter, to report exceptions to Graphite or StatsD.

You can configure ELMAH in your project to use this error filter with the following configuration snipped:

<errorFilter>
  <test
      xmlns:my="http://schemas.microsoft.com/clr/nsassem/Graphite/Graphite.Elmah">
    <my:log />
  </test>
</errorFilter>

Graphite.Elmah itself needs to be configured with the following settings:

<graphite.elmah
    key="elmah_errors"
    type="counter"
    target="statsd" />

You can set a metric key, a metric type and a target for the metrics (either “statsd” or “graphite”). The complete configuration for your web.config file is also included in the respective readme for reference: Graphite.Elmah web.config

Graphite.Elmah was build upon the Graphite base library. Therefore some configuration for the Graphite backend(s) is required as well:

<configSections>
  <section name="graphite" type="Graphite.Configuration.GraphiteConfiguration, Graphite" />
</configSections>
<graphite xmlns="http://github.com/peschuster/Graphite/Configuration">
  <!--<graphite address="127.0.0.1" port="2003" transport="Tcp" />-->
  <statsd address="127.0.0.1" port="8125" prefixKey="test" />
</graphite>

When using the NuGet package Graphite.Elmah all required settings are added to your project automatically during installation:

Install-Package Graphite.Elmah
Posted in: .NET, ASP.NET, Monitoring Tagged: ELMAH, Graphite, StatsD

New line bug in ASP.NET MVC Textarea helper

November 6, 2011 by peter

To render a textarea for a model property in ASP.NET MVC you usually perform a call to @Html.TextAreaFor(…):

@Html.TextAreaFor(m => m.MyProperty)

Recently I encountered the strange behavior that it always adds a new line at the beginning of the textarea. How comes?

Analysis

Note: if you just look for a workaround for this bug scroll down to “Conclusion and solution”.

Internally the TextAreaFor(…) method uses the TextAreaExtensions class in System.Web.Mvc.Html. The code responsible for generating the html output looks roughly like the following:

private static MvcHtmlString TextAreaHelper(HtmlHelper htmlHelper, ModelMetadata modelMetadata, string name, IDictionary<string, object> rowsAndColumns, IDictionary<string, object> htmlAttributes)
{
    // Some initialization here...

    TagBuilder tagBuilder = new TagBuilder("textarea");

    // Some more logic...
 
    tagBuilder.SetInnerText(Environment.NewLine + attemptedValue);
    return tagBuilder.ToMvcHtmlString(TagRenderMode.Normal);
}

So, the intended output of TextAreaFor is:

<textarea>
This is the content...</textarea>

This should be fine and not add an extra new line at the beginning, right? Well, the actual html output looks like this:

<textarea>&#13;&#10;This is the content...</textarea>

There seems to be some more magic in place. And by risking a deeper look at TagBuilder.SetInnerText(…) we discover that it does a call to HttpUtility.HtmlEncode(…):

public void SetInnerText(string innerText)
{
    this.InnerHtml = HttpUtility.HtmlEncode(innerText);
}

Now the pieces come together and one important fact surfaces: the bug only appears when the popular AntiXssEncoder is used as HttpEncoder. The AntiXSS encoder encodes output in views in a safer way by using a white list approach for allowed characters. Till now you had to manually include the AntiXSSEncoder in your ASP.NET MVC project, but up from the next version (ASP.NET 4.5) it is already included and can be activated via web.config.

Conclusion and solution

In contrast to the default HttpEncoder the AntiXssEncoder also encodes new line characters to “&#13;&#10;”, but for the browser this is not the same like just a new line in the html markup. In ASP.NET MVC4 Developer Preview (and most likely also in the soon coming stable version) this is fixed, but till then the probably easiest workaround is to create your own helper for rendering textarea markup in views:

public static MvcHtmlString FixedTextAreaFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
    return new MvcHtmlString(htmlHelper.TextAreaFor(expression)
        .ToHtmlString()
        .Replace(">&#13;&#10;", ">" + Environment.NewLine));
}

(On demand you can just create fixed versions of TextAreaFor(…) for the other overloaded methods like in the example above.)

Posted in: .NET, ASP.NET Tagged: .NET, AntiXssEncoder, ASP.NET, MVC

Syndication

  • RSS 2.0

Recent Posts

  • Ubiquiti EdgeRouter™ X SFP – Teardown
  • Force HttpWebRequest to IPv4
  • Blackmagic Design ATEM GPI and Tally Interface Teardown
  • WinForms ListView DoubleClick Event for Empty Lists
  • Planning Center Online – Custom Plan Reports in Landscape Orientation

Tags

.NET AntiXssEncoder ASP.NET Build c# Configuration crawler Debugging EF ELMAH Expression tree Graphite Interop IssuerNameRegistry iTunes Linq ListView MVC pco pdf Security SecurityKey SecurityToken simulatebe sql server StatsD STS teardown TYPO3 UAC UI UserSettings Visual Studio WIF WIF in depth WinForms WndProc
profile for Peter at Stack Overflow, Q&A for professional and enthusiast programmers Peter Schuster

Copyright © 2025 peschuster.

Alpha WordPress Theme by themehall.com