Friday, November 25, 2011

IOC for objects loaded from orm

I like the idea of coding a Rich domain model, and then applying services to the model. Recently I was trying to get just a little closer to a rich domain, by resolving domain object dependencies during their creation via the ORM. I did find nhibernate supports this style, but alas I am currently constrained to use EF4.1 - code first.

The EF4.1 doco is.... Well there isn't any as best I can tell. For EF4 code first I've relied on blog entries, and perusing the API in object browser. In my quest for rich domain, I found no extension point in EF where I could manage entity proxy creation (pre or post load). I tried finding an override in the db context, no luck. I had some hopes there would be extensibility in te object tracker.. Nup :(.

So in the end I opted to wrap the EF model inside an IOC context aware class (spring.net), that way I coud at least get a post orm load IOC approach.
I've used a simple convention; when the ORM loads an entity, the entity full class name is used as a key in the IOC container. If it's found, the IOC is called, to resolve dependancies on the orm created object.

This approach is all I currently have, with ef4.1.
It works fine, for very simple situations, but since I've intercepted out side of the orm, I only get a shot at resolving dependencies on a top-level entity, not on any child objects that the ORMloads, which kind of makes the whole approach invalid, since I want my ORM to load a more complex entity model than just a set of top-level entities .

Wednesday, November 16, 2011

Add implied interface to a class.

Often... Well often enough, I need to use a .net framework class to implement a method. I almost always find that I want to use an interface on my class, so I can unit test it, and that the framework class provides no interface. This leads to me needing to define a interface, and implement it with a quick decorator around the framework class. Recently I was doing this with the Ping class when I decided to invest a little time looking for a better answer.

My first attempt was to use spring.net mix-ins, or introductions in AOP terms. That kinda worked, but since mixing require a class with the interface implementation, I still needed to write the decorator... not a whole lot better.

After more googling, turns out what I wanted is called duck-typing (who knew). And as with other problems, once you get the term, the googling is easy. I found a few different libraries that could help, I settled on impromptu.

It did take me a while to work out a good way of integrating with spring.net, i've used spring.net a fair bit, but haven't done a lot of extension work to date. Finally I settled on a custom factory object, it requires the target objec rand target interface, using that, it produces a ready to go decorator.
/emote "<-- nods and files away a new tool for the toolbox"

A quick sample class:

Thursday, November 10, 2011

Multiple submit buttons with MVC 3.

I recently needed to create a MVC (MVC3) view with multiple submit buttons.
A quick look around with Google and I found a couple of approaches, but I thought to myself, there must be a cleaner way.

Up till now I've been using the simple approach of creating a controller action where the method takes an extra parameter to describe which action to take like:

Controller:
public class MyController
{
public ViewResult Index() { return View();}

public ViewResult DoSomething(string action, string someData)
{
if(action == "Action1") {}
else if(action == "Action2") {}
else {/*unknown action.*/ }
}
}

xhtml:
<form action="My/DoSomething>
<input name="someData"/>

<input type='submit' name='action' value='Action1' />
<input type='submit' name='action' value='Action2' />
</form>

What I wanted was to be able to define my Controller to have multiple Actions, one for each submit action on a Form, like this:

public class MyController
{
public ViewResult Index() {return View();}

public ViewResult Action1(string someData) {return View();}
public ViewResult Action2(string someData) {return View();}
}

But alas, with MVC I couldn't construct a Route that would do this; MVC routing always uses the Forms action attribute to decide which Controller method to call.

In the end the answer wasn't that hard. I just created a smarter IRouteHander, and applied it to the MVC default route.
The HTML for the form looks almost the same, though I remove the Action from the Form's action attribute, since the route handler will look after that.
xhtml:
<form action="My>
<input name="someData"/>

<input type='submit' name='action' value='Action1' />
<input type='submit' name='action' value='Action2' />
</form>


Now the methods on my controller don't need 'special' arguments, and the world is a better place :D
Here is the custom RouteHandler:

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>

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...