Showing posts with label Configuration. Show all posts
Showing posts with label Configuration. Show all posts

Thursday, March 31, 2016

xUnit.net: Extensions Config v3.3.0

I recently made several updates to the xunit.extensions.config library, which allows you to configure theory data from your app.config file. Here are the links to the source and the NuGet package:

New Features

  • Named Parameter Support

You no longer need to configure your data by parameter index. You can now name your data for each parameter, making the configuration much easier to read and understand.

  • AppSettings Support

You can now use the standard AppSettings section of the App.config to configure your data. If no settings are found, then the framework will fallback to trying to use the standard config section.

  • Default Namespace Option

You can now provide a default namespace for your tests. This reduced the amount of redundant text in your config file, and makes test names much more concise and easy to read.

  • Extensible Data Provider

Don't want to use the existing data providers? Would you rather use a database? Now you can! Just add an AppSettings key for "TestData.ServiceFactory" that provides the fully qualified name of a static method that returns an IConfigTestDataService, and the framework will try to use that to load configuration data.

Sunday, October 25, 2015

Override Configuration via Command Line

In my previous blog posts I have talked about creating complex config objects from your app.config file, as well as how to have cascading configuration settings from multiple files. Now I want to build on that concept by taking in configuration from command line in a generic fashion that will override your other cascading settings.

Configuration Object

public class TestConfig
{
    public string Hello { get; set; }
    public string Goodnight { get; set; }
}

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="TestConfig.Hello" value="World" />
    <add key="TestConfig.Goodnight" value="Moon" />
  </appSettings>
</configuration>

Saturday, July 25, 2015

Cascading AppSettings from Multiple Config Files

In my previous blog post I talked about creating complex configuration objects from AppSettings. I really like this practice, but it can cause your config files to grow pretty large. One solution is to break your app.config into multiple files using the SectionInformation.ConfigSource property.

This also has the added side effect of allowing you to include defaults and overrides by having those settings cascade. I have created an extension method to combine a series of NameValueCollections, such as an AppSettings section. You can also grab this code from the GitHub project.

Combine Extension

public static NameValueCollection Combine(
    this NameValueCollection collection, 
    params NameValueCollection[] collections)
{
    var result = new NameValueCollection { collection };
 
    foreach (var subCollection in collections)
        foreach (var key in subCollection.AllKeys)
        {
            if (result.AllKeys.Contains(key))
                continue;
 
            var value = subCollection[key];
            result.Add(key, value);
        }
 
    return result;
}

Sunday, July 19, 2015

Create Config Objects from AppSettings

Providing configuration settings is a vital task that all applications need. Unfortunately dealing with ConfigurationSections and IConfigurationSectionHandlers can be annoying.

That is why I created a simple little extension method to create complex objects from your app settings. The extension works with a NameValueCollection, and can create primitive types, complex objects, collections, dictionaries, and even recursive properties.

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="TestConfig.Int" value="1" />
    <add key="TestConfig.String" value="Hello" />
    <add key="TestConfig.DateTime" value="1/2/2015" />
    <add key="TestConfig.TimeSpan" value="00:01:00" />
    <add key="TestConfig.Enum" value="Moon" />
    <add key="TestConfig.NullableIntA" value="2" />
    <add key="TestConfig.NullableIntB" value="" />
  </appSettings>
</configuration>

Test

[Fact]
public void CreateSimpleObject()
{
    var result = ConfigurationManager.AppSettings.CreateObject<TestConfig>();
 
    Assert.NotNull(result);
    Assert.Equal(1, result.Int);
    Assert.Equal(42, result.IntWithDefault);
    Assert.Equal("Hello", result.String);
    Assert.Equal(new DateTime(2015, 1, 2), result.DateTime);
    Assert.Equal(TimeSpan.FromMinutes(1), result.TimeSpan);
    Assert.Equal(TestEnum.Moon, result.Enum);
    Assert.Equal(2, result.NullableIntA);
    Assert.Null(result.NullableIntB);
}

Enjoy,
Tom

Thursday, May 14, 2015

Split your App.config into Multiple Files

What do you do when any file in your project becomes too big? You break it apart into multiple files!

Did you know that you can split your .NET configuration files into multiple files as well? Here is how...

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="customSection" 
    type="ConfigSectionDemo.CustomConfigurationSection, ConfigSectionDemo" />
  </configSections>
  <appSettings configSource="AppSettings.config" />
  <customSection configSource="CustomSection.config" />
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
</configuration>

AppSettings.config

<appSettings>
  <add key="Hello" value="World"/>
</appSettings>

CustomSection.config

<customSection goodnight="Moon">
</customSection>

Monday, May 26, 2014

Three Things that all Applications SHOULD Have

This is the second in a three part series:

  1. Three Things that all Applications MUST Have
  2. Three Things that all Applications SHOULD Have
  3. Three Things that all Applications SHOULD WANT to Have

These three things are all generally agreed upon as being best practice, and few people will argue against their value. Unfortunately not all teams take the time to set them up. Again, I can not emphasize how much time these services will save you time in the long run, the earlier you set them up the more value they will return to you!

1. Dynamic Configuration

What the hell is "dynamic" configuration? It's configuration that is simply not not static or hard coded. Do not use constant strings or compiler symbols to configure your application! Start by using configuration files and build transforms. If your system is very distributed, consider using remote or discovered configuration.

2. Continuous Integration

How do you know that the code in your source control is in a functional state? If not, who broke the build? Continuous integration is the practice of consistently pulling and building the projects in source control in an automated fashion. Typically these builds will also execute any tests associated with the project and provide reports for each build. This is crucial rapid development, and is a necessary first step on the road to continuous deployment.

3. Automated Deployment

Before we can get to continuous deployment we have to start with automated deployment. This is simply the act of having a service that deploys your applications to an environment without the need for any significant human interaction; i.e. you can deploy with the click of a button! Automated deployment is extremely useful because it drastically speeds up deployments, prevents human error, and restricts access to different environments (such as production). Please, do not under estimate the value that a deployment system can provide!

Continue reading part 3: Three Things that all Applications SHOULD WANT to Have

Enjoy,
Tom

Saturday, January 18, 2014

Sharing Generic Configuration Across Projects

When you work with a team of developers on a large application across multiple projects, everyone is going to need access to unique configuration settings. Often this will give rise to each project having it's own separate configuration services, or worse everyone will just call the static ConfiguationManager directly.

How do you share a single configuration object across projects?

The answer is simple: extension methods! Just create a generic configuration service in your core library, and then have all of your other projects call it via extension methods. This ensures that you only have one testable, injectable, and extensible source for configuration. Additionally it keeps all of your configuration both discoverable and abstracted to their consuming project.

public interface IConfigService
{
    T Get<T>(string key);
    T Get<T>(string key, T defaultValue);
}
 
public static class ConfigServiceExtensions
{
    private const string NotificationsKey = "AreNotificationsEnabled";
    private const bool NotificationsDefault = true;
 
    public static bool AreNotificationsEnabled(this IConfigService config)
    {
        return config.Get(NotificationsKey, NotificationsDefault);
    }
}

Remember, every project can have it's own set of ConfigService extension methods. :)

Monday, October 22, 2012

How to Unlock a Configuration Section from IIS Manager

HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.

This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".

If you have ever experienced this problem then you probably have also experienced the fun of digging through your system configuration files to find where to unlock the related authentication sections. This is, to say the least, not fun.

Did you know that you can unlock configuration sections from IIS Manager?

  1. Launch IIS Manager.
  2. Select your Connection's home page.
  3. Open the Configuration Editor under Management.
  4. Navigate to the section that you need to unlock.
  5. Look to the right Action pane and click unlock!

Shout it

Enjoy,
Tom

Thursday, November 3, 2011

Configuring MVC Routes in Web.config

ASP.NET MVC is even more configurable than you think!

Routes are registered in the Application Start of an MVC application, but there is no reason that they have to be hard coded in the Global.asax. By simply reading routes out of the Web.config you provide a way to control routing without having to redeploy code, allowing you to enable or disable website functionality on the fly.

I can't take credit for this idea, my implementation is an enhancement of Fredrik Normén's MvcRouteHandler that adds a few things that were missing:

  • Optional Parameters
  • Typed Constraints
  • Data Tokens
  • An MVC3 Library

Download MvcRouteConfig.zip for the project and a sample application.

Example Global.asax

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
    var routeConfigManager = new RouteManager();
    routeConfigManager.RegisterRoutes(routes);
}

Example Web.config

<configuration>
  <configSections>
    <section name="routeTable" type="MvcRouteConfig.RouteSection" />
  </configSections>
  <routeTable>
    <routes>
      <add name="Default" url="{controller}/{action}/{id}">
        <defaults controller="Home" action="Index" id="Optional" />
        <constraints>
          <add name="custom"
              type="MvcApplication.CustomConstraint, MvcApplication">
            <params value="Hello world!" />
          </add>
        </constraints>
      </add>
    </routes>
  </routeTable>

Thanks Fredrik!

~Tom

Update 2/16/2013 - I have added this source to GitHub and created a NuGet Package.

Shout it

Real Time Web Analytics