Saturday, March 5, 2011

Customize your .config for each developer.

Recently (VS2010) Microsoft introduced a technique for customising .config files (app.config, web.config) based on a target build / publish. These config transforms are used to update a config file, as it is being built for a particular configuration. I quite like the transform language, it feel straight forward; simple use locators to identify target elements, and then actions to replace elements or attributes as desired.
Over the last couple of months I have been using these transforms at work, but in my situation they are not 'the whole answer'.
I have just introduced WS-Federated security for passive login and delegation (with WIF). As anyone who has done this knowns.. there are A LOT of config settings all of which need to be correct, additionally if your going to set this up so that each developer can work independently, config settings such as Certs / Audience uri's need to be per-developer machine. Initially I was tempted to use config transforms for this problem, but alas transforms are build-config centric; this approach would mean a custom build for each developer [machine]... >10 developers.. no go.

The alternate; MSBuild with some extensions, and a per-developer build file.

1. Used the MSBuild Extension Pack, it has a nice Detokenize task.

2. Create a master config file: web.master.config use this (from now on).
Replace parts of the config with tokens, by default use $(tokenName) format.
I like to have a comment section at the beginning of the config file, that reports on the particular settings.
<!--
Generated from app.master.xml
Using:
UserName = $(UserName)
LocalPath = $(LocalPath)
-->

3. Create a local.targets project file with a BeforeBuild target.
The project defines a default target BeforeBuild which is called as part of the normal visual studio project build.

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="BeforeBuild">
    <!--MSBuild extensions, for the DEtokenize task.-->
    <Import Project="$(MSBuildExtensionsPath)\ExtensionPack\MSBuild.ExtensionPack.tasks"/>

    <Target Name="BeforeBuild">
        <ItemGroup>
            <MasterFile Include="app.master.config" />
            <ConfigFile Include="app.config" />
        </ItemGroup>
        <ItemGroup>
            <Token Include="UserName">
                <Replacement>Developer</Replacement>
            </Token>
            <Token Include="LocalPath">
                <Replacement>D:\Source\Tmp\Sample</Replacement>
            </Token>
        </ItemGroup>
        
        <Copy SourceFiles="@(MasterFile)" DestinationFiles="@(ConfigFile)" OverwriteReadOnlyFiles="true" />
        <MSBuild.ExtensionPack.FileSystem.Detokenise 
            TaskAction="Detokenise" 
            TargetFiles="@(ConfigFile)" ReplacementValues="@(Token)"/>
    </Target>
</Project>

The project itself consist of not much more than a Copy task to copy master.config file(s) over the config files. Followed by a Detokenise task to change the config file.

4. (xml) edit the project to import the per-developer project.
Simply add the following toward the end of the project (after the other import entries).
<Import Project="local.targets" Condition="Exists('local.targets')"/>

5. (Re)Open the project, and next build the developer defined settings will be used.

Quick sample application: http://dl.dropbox.com/u/8153235/SampleMasterConfig.zip

too easy.

Tuesday, January 18, 2011

Code Contracts - a simple idiom

I've been experimenting with .NET 4 Code Contracts for a couple of months.
Contracts themselves are simple enough to understand. The potential to produce stabler code, improve readability, and some help with the pesky 'object null' problem makes them very attractive.
A few blog posts, such as Billy McCafferty, and a series from Derik Whittaker help get up to speed.

My initial work with Contracts started with simple require not null type contracts, and soon escalated to more useful contracts such as 'no nulls in a list', FileInfo.Exists == true. What I found was a simple rule helped to limit what to declare for a contract:

Don't Require more than what a caller can simply (one-line) Ensure.

It is easy for a caller to check an object is not-null before calling a library... but out-of-the-box checking for more complex constraints, such as list contains no-nulls made the code less readable. The idiom above doesn't stop me from using more complex constraints, but it does ensure I provide a simple (one line) way for callers to ensure the constraint.

Tuesday, January 11, 2011

spring.net multiple validators with one action.

I had an interesting problem at work the other day.
I needed to perform a number of validations against an object, and report a single error message.
In this project we're using Spring.net's validation framework.

Out of the box, spring.net validation doesn't provide any easy way to report a single error for multiple validations. But here's a simple trick to work around this:
1. Use a validation group to group all the validations.
2. Don't include an action (message) on the included validations.
3. Set the group's 'Actions' property to a new list of Spring.Validation.Actions.ErrorMessageAction items.

<v:group>
  <v:property name="Actions">
    <list>
      <object type="Spring.Validation.Actions.ErrorMessageAction">
        <constructor-arg index="0" value="error.MyError" />
        <constructor-arg index="1" value="MyErrorParam" />
      </object>
    </list>
  </v:property>

  <v:validator test="Prop1" />
  <v:validator test="Prop2" />
  <v:validator test="Prop3" />
</v:group>

Monday, November 15, 2010

CodeContracts - yum

I just spent the weekend converting a little in-home code over to using the new .Net4 code contracts. My opinion: FANTASTIC.

My initial goal for the weekend, was to create a simple demo, to see whether I'm in the
A) keep unit-tests for contracts. Or
B) don't unit test a contract.
Camp. Opinion on-the-net seams divided over this, so I wanted to make my own mind up by using CodeContracts in a non-trivial piece of software.

What I found: my code was full of potential bugs :( The starting code base wasn't my best work, but I did have a good set of unit tests for it. I was expecting the code-contracts to highlight some weekneses, but it ended up forcing me to think a lot more about the possible problems, so I spent my time fixing what looked like decent code.

To that end I now think
1. Writing verifiable code with CC is a must do.
1.1 it takes a lot more time (script kiddies will hate it), but better time now then bugs later.

2. The current lack of static-checking for Contract.ForAll and Contract.Exists is a problem.
3. Using Contract.Assume is a crappy, currently needed hack.

4. CC tutorials and examples need to focus on Contract.Ensure, not Contract.Requires. To my mind being able to express guarantees on what-my-code does is more important than expressing limits that clients need to obey.

5. Think of CC as like writing tests, docx, and defensive programming all rolled int a couple of code lines.

6. CC forces you to think far more critically. Sometimes, you won't believe it's warnings. Sometimes it'll be because the static checker isn't smart enough, but mostly it'll be the developer isn't looking close enough.

7. CC is NOT just for null checks, if you only Ensure not-null, your missing a lot of the power.

Requires that use more than the input params need to be simple for callers to check.

Sample contract on a duel-construct such as ui ctor + create.
Simple contract on disposable / disposed object.

Saturday, September 25, 2010

OS; Change in the wind

Context:
I have been a (proud) Windows fanboy since Win3.11.
At Uni I studied physics, by the end of my masters, I knew I wanted to be a developer; so I learnt C, and started building a career based on developing software for Windows. Back in the day, Windows was brilliant, it dominated desktops, gave me a single popular platform so I could build skills and get work. Sure there were challenges, but that's software development.

I just received a 'disturbing' email from my dad.
I received the email via gmail (Google). I gave up on Outlook about 3 months ago, too many problems trying to look after .pst files, could never find old emails in outlook.. it all got too hard so I imported everything to GMail.
The email was popped up on my iPad (Apple), using Google mobile-sync.
Yesterday I gave up on windows-live in favor of Blogger (Google), a close call, nearly went Wordpress.

So, the subject of this email:
Bought a Mac.
And the content:
Well I finally got so sick of Vista I bought a Mac. 500gig 21.5" screen.
Vista was the cause of my not being able to access Bigpond (4 weeks of Technical support) by doing something to the usb ports and it also again stopped the disc drive from working so I couldn't install Windows 7
Installed the wireless Broadband onto the Mack and away it went no problem.
This time last year, I knew one person with a Mac; the wife's boss.. he's in the 'creative' music industry, so I forgave him because he has to be 'hip'.

Today: My dad, and 2 of my sister-in-laws' use Mac's.
I don't have a big social circle; so in my little corner of the world, this is a massive change.

This is one of those; things that make you go hmmmm....

P.S Gah, trying to write this blog; IE keeps crashing???... looks like I'm going Crome.

Friday, September 24, 2010

A new day, a change of blog

Ok, firstly; I'm a lurker.
I lurk here, I lurk there... I lol, but rarely contrib.

Ever since getting an iPad a few months ago, my lurking has almost reached a professional level.

In a possibly futile attempt, I'm going to try blogging. If nothing else, I'll have my own little corner of the net to post in.

What you (should) find here:

1. Unstructured ramblings about software development.
2. Bad spelling, bad English bad punctuation.
3. The occasional curse words
4. Posts that are nothing but likes to stuff.
5. Lists... I like lists.

A short list of C# coding issues.

Injecting services into entities It been bugging me for a while now that to use services in a entity can be a bit of pain. It usually starts...