<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2enclosuresfull.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:media="http://search.yahoo.com/mrss/" xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0"><channel><title>A Vietnamese developer in Australia</title><link>http://thoai-nguyen.blogspot.com/</link><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/thoainguyen" /><description></description><language>en</language><managingEditor>noreply@blogger.com (vantheshark)</managingEditor><lastBuildDate>Thu, 16 Feb 2012 00:50:27 PST</lastBuildDate><generator>Blogger http://www.blogger.com</generator><openSearch:totalResults xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/">30</openSearch:totalResults><openSearch:startIndex xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/">1</openSearch:startIndex><openSearch:itemsPerPage xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/">25</openSearch:itemsPerPage><feedburner:info uri="thoainguyen" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><itunes:owner><itunes:email>noreply@blogger.com</itunes:email></itunes:owner><itunes:explicit>no</itunes:explicit><itunes:subtitle></itunes:subtitle><item><title>Validation in WCF application with NValidator</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/XDvYlE21nvo/validation-wcf-with-nvalidator.html</link><category>NValidator</category><category>Validation</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Wed, 08 Feb 2012 22:01:04 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-1099066615687569222</guid><description>I have been working on a heavy validation messaging project for 3 months. Basically, my company had built a workflow based system to process incoming WCF messages from other business partners. These WCF messages are supposed to be validated before being queued in a RabbitMQ queue store. And I was responsible for implementing the validation stuff for the application. As mentioned in &lt;a href="http://thoai-nguyen.blogspot.com/2011/11/wcf-validation-with-data-annotation.html" target="_blank"&gt;previous post&lt;/a&gt;, I wanted to have something similar to ASP.NET MVC such as Validattion Provider, Validation Factory and using DataAnnotation for message contracts. But after a first draft implementation I has seen some potential issues:
&lt;br/&gt;
&lt;br/&gt;
1/ It's hard to have a clean contract DLL if using DataAnnotation.
The validation logic for the messaging application is quite complicated. We just perform field validation without touching database at this point. However, the rules are so many and quite complicated. So some basic DataAnnotation attributes cannot fit all requirements. Many custom DataAnnotation attributes have been implemented and I don't want to embedded them in the same assembly with the Contracts. As a result, the contract dll had to reference to 1 or 2 other assemblies which contains the custom DataAnnotation classes. I hate this drawback since the contract we built will be provided to other internal teams, even our business partners.
&lt;br/&gt;
&lt;br/&gt;
2/ It's possible but quite ugly to perform cross field validations
Using DataAnnotation, we can only perform validation rules on the "reader property" of a contract. Believe me, it's not gonna work for public field since the TypeDescriptor .NET class couldn't reflect the fields. To perform validation on crossfields, either we implement an attribute and decorate on the class it self, or implement interface IValidatableObject. I don't like both approaches since the first choice seems to be so complicated and not a straightforward way. The second choice pollutes my POCO classes. So, it's the second drawback to give up DataAnnotation
&lt;br/&gt;
&lt;br/&gt;
3/ Validation rules could be different between different trading partners
Using DataAnnotation, the validation logics are tight to the contract classes so it's almost impossible to changes the rules since the data annotation attributes are decorated on the contract's properties or the class itself.
&lt;br/&gt;
&lt;br/&gt;
4/ And similar to the above reason, validation rules should support versioning. DataAnnotation makes it impossible to deploy new validaton logic without compilation the application eventhough we're hardly need this level of support. 
&lt;br/&gt;
&lt;br/&gt;
Based on above reasons, separating the validation logics to different assembly seems to be a proper decision. I implemented &lt;a href="http://nvalidator.codeplex.com/" target="_blank"&gt;NValidator&lt;/a&gt; and changed my code to using NValidator and it works perfectly. The validation errors are so meanningfull and easy to debug. After applying the library a few days, I got 90 bugs regarding these validations but believe me or not, I fixed all of them just in 1 day.
&lt;br/&gt;
&lt;br/&gt;
&lt;pre class="brush: xml; smart-tabs: true; toolbar: false"&gt;&amp;lt;a:Result&amp;gt;
    &amp;lt;a:MessageCreatedDT&amp;gt;20120105 12170001&amp;lt;/a:MessageCreatedDT&amp;gt;
    &amp;lt;a:MessageReceivedDT&amp;gt;20120127 13250974&amp;lt;/a:MessageReceivedDT&amp;gt;
    &amp;lt;a:MessageSuccess&amp;gt;Fail&amp;lt;/a:MessageSuccess&amp;gt;
    &amp;lt;a:ProcessingErrors&amp;gt;
        &amp;lt;a:ProcessingError&amp;gt;   
            &amp;lt;a:ErrorDataField&amp;gt;CreateProfile.ApplicationNumber&amp;lt;/a:ErrorDataField&amp;gt;
            &amp;lt;a:ErrorDescription&amp;gt;ApplicationNumber is not a valid application number. Received value: "abcdef"&amp;lt;/a:ErrorDescription&amp;gt;
            &amp;lt;a:ErrorUniqueID&amp;gt;2d31f33f-44df-48aa-a682-61e3ca7d5566&amp;lt;/a:ErrorUniqueID&amp;gt;
        &amp;lt;/a:ProcessingError&amp;gt;
        &amp;lt;a:ProcessingError&amp;gt;   
            &amp;lt;a:ErrorDataField&amp;gt;CreateProfile.Entities[0].CompanyName&amp;lt;/a:ErrorDataField&amp;gt;
            &amp;lt;a:ErrorDescription&amp;gt;CompanyName must be null because ‘Entity Type’ = “Person”. Received value: ""&amp;lt;/a:ErrorDescription&amp;gt;
            &amp;lt;a:ErrorUniqueID&amp;gt;854e68c1-7604-412f-991c-20a6fc31b611&amp;lt;/a:ErrorUniqueID&amp;gt;
        &amp;lt;/a:ProcessingError&amp;gt;
        &amp;lt;a:ProcessingError&amp;gt;   
            &amp;lt;a:ErrorDataField&amp;gt;CreateProfile.Entities[1].CompanyName&amp;lt;/a:ErrorDataField&amp;gt;
            &amp;lt;a:ErrorDescription&amp;gt;Mandatory because ‘Entity Type’ = “Company”. Received value: ""&amp;lt;/a:ErrorDescription&amp;gt;
            &amp;lt;a:ErrorUniqueID&amp;gt;cca94d9d-6ea5-4846-8109-091285ae03e4&amp;lt;/a:ErrorUniqueID&amp;gt;
        &amp;lt;/a:ProcessingError&amp;gt;
    &amp;lt;/a:ProcessingErrors&amp;gt;
&amp;lt;/a:Result&amp;gt;
&lt;/pre&gt;

&lt;br/&gt;
Above is a sample message response when validation fails. The 2 last erros are examples of cross field validation. If EntityType = "Person" the CompanyName must be null. CompanyName is mandatory if EntityType = "Company".
&lt;br/&gt;
Reading enough? Here are the steps for using NValidator for validation on WCF service:
&lt;br/&gt;
&lt;ol&gt;
&lt;li&gt;Assume that you have your contract defined in an assembly, add another class library project just for validation rules. Using &lt;a href="http://nuget.org/packages/NValidator" target="_blank"&gt;Nuget to get latest NValidator&lt;/a&gt; and add your validator classes.&lt;/li&gt;
&lt;li&gt;Register your validator classes in the application bootstrapper or anywhere of your app where the code is executed before other stuff.&lt;/li&gt;
&lt;li&gt;Create a validation attribute to decorate on your WCF service. The method is pretty similar to &lt;a href="http://thoai-nguyen.blogspot.com/2011/11/wcf-validation-with-data-annotation.html" target="_blank"&gt;this post&lt;/a&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;br/&gt;

And here is the code. In this demo, I want to print out the value of the validated object so I create a custom Validation result as below. You don't have to do this if you don't want this function. The default ValidationResult and ValidationBuilder work just fine

&lt;br/&gt;
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public class CustomValidationResult : FormattableMessageResult
{
    public CustomValidationResult() : base(new Dictionary&amp;lt;string, object&amp;gt;())
    {
    }

    public CustomValidationResult(ValidationResult originalResult)
        : base(originalResult is FormattableMessageResult
                ? (originalResult as FormattableMessageResult).Params
                : new Dictionary&amp;lt;string, object&amp;gt;())
    {
        CopyValues(originalResult);
    }

    private void CopyValues(ValidationResult originalResult)
    {
        var customValidationResult = originalResult as CustomValidationResult;
        MemberName = originalResult.MemberName;
        Message = originalResult.Message;
        PropertyName = originalResult.PropertyName;

        if (customValidationResult != null &amp;&amp; customValidationResult.ValidatedValueWasSet)
        {
            ValidatedValue = customValidationResult.ValidatedValue;
        }
    }

    public bool ValidatedValueWasSet { get; private set; }

    private object _validatedValue;
    public object ValidatedValue
    {
        get
        {
            return _validatedValue;
        }
        set
        {
            if (!ValidatedValueWasSet)
            {
                _validatedValue = value;
                ValidatedValueWasSet = true;
            }
        }
    }
}
&lt;/pre&gt;
&lt;br/&gt;
I also have to make a customization of ValidationBuilder to make it return my custom ValidationResult:
&lt;br/&gt;
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;/// &amp;lt;summary&amp;gt;
/// This class customizes the behavior of ValidationBuilder and return CustomValidationResult
/// &amp;lt;/summary&amp;gt;
/// &amp;lt;typeparam name="T"&amp;gt;&amp;lt;/typeparam&amp;gt;
/// &amp;lt;typeparam name="TProperty"&amp;gt;The type of the property.&amp;lt;/typeparam&amp;gt;
public class CustomValidationBuilder&amp;lt;T, TProperty&amp;gt; : ValidationBuilder&amp;lt;T, TProperty&amp;gt;
{
    private object _validatedObject;
    public CustomValidationBuilder(Expression&amp;lt;Func&amp;lt;T, TProperty&amp;gt;&amp;gt; expression)
        : base(expression)
    {
    }

    protected override NValidator.ValidationResult FormatValidationResult(NValidator.ValidationResult result, string propertyChain)
    {
        var baseResult = base.FormatValidationResult(result, propertyChain);
        var customResult = new CustomValidationResult(baseResult);
        if (!customResult.ValidatedValueWasSet)
        {
            customResult.ValidatedValue = _validatedObject;
        }
        return customResult;
    }

    protected override object GetObjectToValidate(T value)
    {
        _validatedObject = base.GetObjectToValidate(value);
        return _validatedObject;
    }
}
&lt;/pre&gt;
&lt;br/&gt;
And here is the ParameterValidatorBehavior which invokes validation on every WCF message call:
&lt;br/&gt;
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public class ParameterValidatorBehavior : IParameterInspector
{
    public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)
    {
    }

    public object BeforeCall(string operationName, object[] inputs)
    {
        // validate parameters before call
        var validationResults = new List&amp;lt;ValidationResult&amp;gt;();
        var serviceIntance = OperationContext.Current.InstanceContext.GetServiceInstance();
        if (serviceIntance != null)
        {
            foreach (var input in inputs)
            {
                if (input != null)
                {
                    var validator = ValidatorFactory.Current.GetValidatorFor(input.GetType());
                    if (validator == null)
                    {
                        ColorConsole.WriteLine(ConsoleColor.Yellow, "Validator for {0} not found.", input.GetType().Name);
                        continue;
                    }
                    validationResults.AddRange(validator.GetValidationResult(input));
                }
            }
            if (validationResults.Count &amp;gt; 0)
            {
                throw new FaultException&amp;lt;ValidationFault&amp;gt;(new ValidationFault(validationResults), "Validation error");
            }
        }
        return null;
    }
}
&lt;/pre&gt;
&lt;br/&gt;
As mentioned in the &lt;a href="http://nvalidator.codeplex.com/wikipage?title=ValidatorBuilder&amp;referringTitle=Table%20of%20contents" target="_blank"&gt;NValidator topic&lt;/a&gt;, the above CustomValidationBuilder has to be registered in BootStrapper:
&lt;br/&gt;
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;internal class BootStrapper
{
    public static void Start()
    {
        ValidatorFactory.Config.DefaultValidationBuilderType = typeof (CustomValidationBuilder&amp;lt;,&amp;gt;);

        ValidatorFactory.Current.Register&amp;lt;OrderValidator&amp;gt;(true);
        ValidatorFactory.Current.Register&amp;lt;OrderDetailValidator&amp;gt;(true);
    }
}
&lt;/pre&gt;
&lt;br/&gt;
That cannot be easier. Again, the full source code can be check out here at GitHub.
Cheers.

&lt;script language="javascript" type="text/javascript"&gt;SyntaxHighlighter.config.TypeNames = "CustomValidationResult FormattableMessageResult Dictionary ValidationResult CustomValidationBuilder ValidationBuilder Expression Func ParameterValidatorBehavior IParameterInspector OperationContext ValidatorFactory BootStrapper OrderValidator OrderDetailValidator FaultException ValidationFault";&lt;/script&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-1099066615687569222?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/XDvYlE21nvo" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2012-02-09T17:01:04.312+11:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://thoai-nguyen.blogspot.com/2012/01/validation-wcf-with-nvalidator.html</feedburner:origLink></item><item><title>Is Repository old skool?</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/9FrwWqqPYqo/is-repository-old-skool.html</link><category>Dotnet</category><category>Repository</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Wed, 18 Jan 2012 21:45:40 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-363033812428187836</guid><description>I used to be a fan of Repository pattern, DAO, DAL whatever they're called. I have tried many different approaches for this pattern and normally end up at a DAO object rather than a pure generic Repository. However, I still fooled myself that it was my bad design of Repository pattern and there must be a better design somewhere. More than two years ago, I saw &lt;a href="http://huyrua.wordpress.com/2011/04/13/entity-framework-4-poco-repository-and-specification-pattern-upgraded-to-ef-4-1" target="_blank"&gt;code of my elder colleague&lt;/a&gt; about his design of database abstraction layer. He used Specificication pattern together with the Generic Repository on top of Entity Framework. I talked to myself, what the hell is specification and why on earth would we want to use it when we have LinQ built in in the language. Hmm, I might be wrong at time time and now I know I was properly wrong. Recently, I'm watching &lt;a href="http://ayende.com/blog/153153/northwind-starter-kit-review-refactoring-to-an-actual-read-model" target="_blank"&gt;a interesting argument&lt;/a&gt; among many blog readers on a topic of Oren's blog. Basically, they're arguing about whether we should use Repository Pattern. I'm confused about the trend of community on this topic so I decided to ask my 2 experienced colleagues. Here are their responses:
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;em&gt;
I don’t tend to use them these days ...
&lt;br /&gt;&lt;br /&gt;
A Repository in concept is “an in-memory list” for all intents and purposes ... the problem is they are almost always written as “a generic data access layer”. The main problem is that Repositories should only *ever* be for an Aggregate Root, and therefore handle all data access for all child objects too. Ours are a nasty generic data access layer pretending to be a repository.
&lt;br /&gt;&lt;br /&gt;
Personally I usually favour QueryObjects for querying and CommandObjects for writing
&lt;br /&gt;&lt;br /&gt;
In this case a QueryObject knows how to do one query or projection (which may involve database calls), and returns either DTOs or domain entities
&lt;br /&gt;&lt;br /&gt;
A CommandObject knows how to do one single operation, which may involve multiple database calls), and returns Void
&lt;br /&gt;&lt;br /&gt;
&lt;br /&gt;&lt;br /&gt;
Or as I think Oren advocates later on, I would just let the NH objects into the domain these days – nobody ever replaced a data layer 
&lt;/em&gt;
&lt;br /&gt;
&lt;strong&gt;&lt;a href="http://devlicio.us/blogs/casey/" target="_blank"&gt;Jak Charlton&lt;/a&gt;&lt;/strong&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;em&gt;
I usually, but not always, tend to judge the repository pattern as an anti-pattern and an unnecessary additional layer of abstraction, complexity and maintenance.  It's quite useful if you're going to need to swap out your storage platform at some point, say SQL Server for Oracle or MongoDB, but even then there are often underlying specific implementation differences between platforms that break the abstraction compatibility, so you end up needing to redesign the repository's API contract and break compatibility.  A generic repository that works across several storage platforms must be very generalised, and isn't able to leverage specific features of a particular technology.
&lt;br /&gt;&lt;br /&gt;
This only applies to a generic repository, I see less harm in it when applied more specifically, like EF which provides a good storage abstraction and API over relational databases.
&lt;br /&gt;&lt;br /&gt;
As always, it depends.  I currently tend to design for a service layer that directly uses a mirco-ORM for SQL Server, and other data access libraries specific to their storage type, like the .NET MongoDB driver.
&lt;/em&gt;
&lt;br /&gt;
&lt;strong&gt;&lt;a href="http://chrisfulstow.com" target="_blank"&gt;Chris Fulstow&lt;/a&gt;&lt;/strong&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;

Well, clear enough. These comments plus people's comments on Oren's post tell me that I'm at least 3 years out of date. Repositories are nolonger hot fashion even though I believe there are still more guys like the old me still see the value of Repositories. I had seen enough problems using Repositories as a generic Repository can easily become a DAO at some point otherwise it would lose many features of the ORM technology abstracted behind it. Properly QueryObjects are the one to go for me next time :D.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-363033812428187836?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/9FrwWqqPYqo" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2012-01-19T16:45:40.047+11:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://thoai-nguyen.blogspot.com/2012/01/is-repository-old-skool.html</feedburner:origLink></item><item><title>Introduce NValidator</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/bI_QEXwkb9Y/introduce-nvalidator.html</link><category>NValidator</category><category>Validation</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Tue, 27 Dec 2011 20:29:04 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-5556565059793708374</guid><description>&lt;br/&gt;
I had spent 2 weeks before Christmas to develop a small library to do the validation. It's a lot similar to FluentValidation in syntax. Actually, the implementation and fluent syntax are inspired from this well-known library Fluent Validation. However, I implemented it using Chain of Reponsibility pattern and made it support Dependency Injection for validator classes. Here is a simple example that can help you to start:

&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public class UserValidator : TypeValidator&amp;lt;User&amp;gt;
{
    public UserValidator()
    {
        RuleFor(user =&amp;gt; user.Id)
            .NotEmpty()
            .NotNull();

        RuleFor(user =&amp;gt; user.UserName)
            .NotNull()
            .Length(6, 10)
            .Must(x =&amp;gt; !x.Contains(" ")).WithMessage("@PropertyName cannot contain empty string.");

        RuleFor(user =&amp;gt; user.Password)
            .StopOnFirstError()
            .NotEmpty()
            .Length(6, 20)
            .Must(x =&amp;gt; x.Any(c =&amp;gt; c &amp;gt;= 'a' &amp;&amp; c &amp;lt;= 'z') &amp;&amp;
                       x.Any(c =&amp;gt; c &amp;gt;= '0' &amp;&amp; c &amp;lt;= '9') &amp;&amp;
                       x.Any(c =&amp;gt; c &amp;gt;= 'A' &amp;&amp; c &amp;lt;= 'Z')).WithMessage("@PropertyName must contain both letter and digit.");

        RuleFor(user =&amp;gt; user.Title)
            .In("MR", "MS", "MRS", "DR", "PROF", "REV", "OTHER");

        RuleFor(user =&amp;gt; user.FirstName)
            .NotEmpty().WithMessage("Please specify the first name.");

        RuleFor(user =&amp;gt; user.LastName)
            .NotEmpty().WithMessage("Please specify the last name.");
        
        RuleFor(user =&amp;gt; user.Email)
            .Email();

        RuleFor(user =&amp;gt; user.Address)
            .SetValidator&amp;lt;AddressValidator&amp;gt;()
            .When(x =&amp;gt; x != null);
    }
}
&lt;/pre&gt;

I'm currently using this library for a &lt;strong&gt;heavy server side validation&lt;/strong&gt; project and so far so good. You may ask me why don't I just use FluentValidation instead of reinventing the wheel? My answer is I want to keep myself busy. I have a passionate on Fluent interfaces for a while and this is a good opportunity for me to "do something" :D


Anyway, the source code repository for this project is on &lt;a href="https://github.com/vanthoainguyen/NValidator" target="_blank"&gt;GitHub&lt;/a&gt;. The NuGet package "NValidator" is also available.
Please checkout &lt;a href="http://nvalidator.codeplex.com/documentation" target="_blank"&gt;the document&lt;/a&gt; and &lt;a href="http://nvalidator.codeplex.com/wikipage?title=Table%20of%20contents" target="_blank"&gt;other topics&lt;/a&gt; to get started.

&lt;br /&gt;
Happy New Year.
&lt;br /&gt;
&lt;script language="javascript" type="text/javascript"&gt;SyntaxHighlighter.config.TypeNames = "UserValidator TypeValidator User AddressValidator";&lt;/script&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-5556565059793708374?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/bI_QEXwkb9Y" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-12-28T15:29:04.883+11:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/12/introduce-nvalidator.html</feedburner:origLink></item><item><title>Validation attribute on nested list item</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/Xn0IpFWAgVA/validation-attribute-on-nested-list.html</link><category>Validation</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Mon, 21 Nov 2011 03:38:24 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-7408704896311414004</guid><description>I'm working on some data annotation validation stuff and today I came to a requirement to validate a type nested property which is a list of string. The requirement is quite simple, just make sure every string in the list must be numeric. NumericAttribute is a custom ValidationAttribute to validate a string and to check whether it contains only numeric. Well this is a very basic example and I'm thinking futher, may be I'll need to validate different object type in the list instead of simple string and we might need different validation logic to apply on them. That leads me to this post:
&lt;br /&gt;
Let's say I have an object definition like below:
&lt;br /&gt;
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public class Parent
{
    public List&amp;lt;ChildObject&amp;gt; Children {get;set;}
}&lt;/pre&gt;
&lt;br /&gt;
I want to have a validation attribute to decorate on the Children property and when the validation process happen, that attribute will validate every single ChildObject item in the list.
&lt;br /&gt;
The attribute I want is a derived of ValidationAttribute, take different types of other Validation Attributes as the constructor parameters. And certainly, when override method IsValid, it will loop through the validation attributes set in the constructor to validate all items in the list:
&lt;br /&gt;
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public class ValidateItemUsingAttribute : ValidationAttribute
{
    private readonly Type[] _attributeTypes;

    public ValidateItemUsingAttribute(params Type[] attributes)
    {
        Check.Requires&amp;lt;ArgumentNullException&amp;gt;(attributes != null);
        Check.Requires&amp;lt;ArgumentException&amp;gt;(!attributes.Any(x =&amp;gt; !typeof(ValidationAttribute).IsAssignableFrom(x)));
        _attributeTypes = attributes;
    }

    public override bool IsValid(object value)
    {
        if (value == null || !(value is IEnumerable) || value is string)
        {
            return true;
        }

        var index = 0;
        foreach(var item in value as IEnumerable)
        {
            foreach (var type in _attributeTypes)
            {
                var validator = Activator.CreateInstance(type) as ValidationAttribute;

                var validationResult = validator.GetValidationResult(item, new ValidationContext(item, null, null));
                if (validationResult != null)
                {
                    ErrorMessage = validationResult.ErrorMessage;
                    MemberName = string.Format("{0}[{1}]", MemberName, index);
                    return false;
                }
            }
            index++;
        }
        return true;
    }
}&lt;/pre&gt;
&lt;br /&gt;
Because this attribute uses Activator to create instance of other validation attribute, that require those nested validation attributes to have parameterless constructor. So for example we need to use type of StringLengthAttribute for the constructor, we may implement a derived class of StringLengthAttribute and use the new type for the constructor :D
&lt;br/&gt;
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public class Parent
{
    [ValidateItemUsing(typeof(SomeValidationAttribute), typeof(AnotherValidationAttribute))]
    public List&amp;lt;ChildObject&amp;gt; Children {get;set;}
}&lt;/pre&gt;
&lt;br /&gt;
Anyways, I hope this is a good idea. Cheers.

&lt;script language="javascript" type="text/javascript"&gt;SyntaxHighlighter.config.TypeNames = "Parent ChildObject List Type ValidateItemUsingAttribute ValidationAttribute Check  ArgumentNullException ArgumentException IEnumerable Activator ValidationContext ValidateItemUsing SomeValidationAttribute AnotherValidationAttribute";&lt;/script&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-7408704896311414004?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/Xn0IpFWAgVA" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-11-21T22:38:24.485+11:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/11/validation-attribute-on-nested-list.html</feedburner:origLink></item><item><title>WCF Validation Engine with Data Annotation style like ASP.NET MVC</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/VNgWbz8TQi8/wcf-validation-with-data-annotation.html</link><category>Dotnet</category><category>Validation</category><category>WCF</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Mon, 07 Nov 2011 15:54:52 PST</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-976763883678219684</guid><description>&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;There are many articles about WCF validation. Some are about using WCF with Microsoft Application Block, many others are about using Data Annotation. But there is not any thing like the validation engine of ASP.NET MVC. Honestly, I'm very impressed of MVC Team's work. The code is very SOLID that makes it too easy to extend without changing the implementation. There are still something i don't like in the Framework but overall, I think it's an awesome library. I have been working with ASP.NET MVC for over 2 years and now I'm having a chance to go back to WCF. I realized that WCF is designed a lot as open as MVC, there are so many extensible points in WCF that allows users to  customize the services behavior, validation is one of them. I expected to find some existing code to use for WCF Validation like the one in MVC for me to copy and paste but there is not. I wanted to have a framework that we can switch any validation logic any time, just change the provider. Therefore, I decided to copy some of the implementation from MVC source code and use for this WCF validation demo.
&lt;br/&gt;&lt;br/&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Firstly, I want to say about the way MVC Validation engine work. If you have ever read the MVC source code, you mush have known that in MVC, there is a ModelMetadata provider which will read the view model class and make a ModelMetaData. Then there is one or many ModelValidators which are registered before to create validator objects base the model metadata. Each validator will produce ValidationResults when validate the object. The validation process will happing during model binding and before Action method is executed. If there is an error, the error information will be append to Model State of current Controller context. And finally, in side the action method, we'll check the ModelState.IsValid to decide what to do.
&lt;br/&gt;&lt;br/&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;So I guess the MVC validation engine will not be able to validate nested object. But in MVC application, we still can see the error if nested object has validation error. I'm pretty sure that error is found while model binding process happen. In WCF, we don't have to worry about the model binder thing so one of the problem I have to solve is making the code validate nested object and child objects in an enumerable.
&lt;br/&gt;&lt;br/&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Secondly, the ModelMetadata class and the ModelMetadataProvider classes in MVC aware of ControllerContext object which I don't want to use and there is not any reason to use it in WCF application so the next problem for me is trimming any thing related to ControllerContext.
&lt;br/&gt;&lt;br/&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;And finally, The MVC validation engine itself contains logic for Client validation. Again, these things will add no value for a WCF application. My aim would be copying only the code needed for validation the contract parameters in WCF.
&lt;br/&gt;&lt;br/&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;You may ask me why not using the classes in System.Web.Mvc.dll instead of rewriting/copying them. The answer is we cannot use that dll outside a web environment due to the assembly setting of that library. 
&lt;br/&gt;&lt;br/&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Alright, the way I inject validation logic into WCF method is making a IOperationBehavior as an Attribute to decorate on the action method. It's pretty much the same as other's guide. Here is the implementation:
&lt;br/&gt;&lt;br/&gt;
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;[AttributeUsage(AttributeTargets.Method)]
public sealed class ParameterValidatorAttribute : Attribute, IOperationBehavior
{
    public ParameterValidatorAttribute()
    {
        ThrowErrorOnFirstError = false;
        ThrowErrorAfterValidation = true;
    }

    public bool ThrowErrorOnFirstError { get; set; }
    public bool ThrowErrorAfterValidation { get; set; }

    void IOperationBehavior.Validate(OperationDescription description)
    {
    }

    void IOperationBehavior.AddBindingParameters(OperationDescription description, BindingParameterCollection parameters)
    {
    }

    void IOperationBehavior.ApplyClientBehavior(OperationDescription description, ClientOperation proxy)
    {
    }

    void IOperationBehavior.ApplyDispatchBehavior(OperationDescription description, DispatchOperation dispatch)
    {
        dispatch.ParameterInspectors.Add(new ParameterValidatorBehavior(ThrowErrorOnFirstError, ThrowErrorAfterValidation));
    }
}&lt;/pre&gt;
&lt;br/&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;The ParameterValidatorBehavior implements IParameterInspector, before a service method is called, it will invoke the validation engine to validate every single input parameter. If there is a validation error, the error will be appended to ModelState object. That requires the service implementation must implement the following interface 
&lt;br/&gt;
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public interface IHasModelStateService
{
    ModelState ModelState { get; set; }
}&lt;/pre&gt;
&lt;br/&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Here is the code of the parameter inspector:
&lt;br/&gt;
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public object BeforeCall(string operationName, object[] inputs)
{
    // validate parameters before call
    var serviceIntance = OperationContext.Current.InstanceContext.GetServiceInstance() as IHasModelStateService;
    if (serviceIntance != null)
    {
        if (serviceIntance.ModelState == null)
        {
            serviceIntance.ModelState = new ModelState();
        }
        if (serviceIntance.ModelState.Errors == null)
        {
            serviceIntance.ModelState.Errors = new List&amp;lt;ModelError&amp;gt;();
        }

        IEnumerable&amp;lt;ModelValidationResult&amp;gt; validationResults = new ModelValidationResult[] { };
        foreach (object input in inputs)
        {
            if (input != null)
            {
                ModelMetadata metadata = ModelMetadataProviders.Current.GetMetadataForType(() =&amp;gt; input, input.GetType());

                validationResults = ModelValidator.GetModelValidator(metadata).Validate(null);
                foreach (ModelValidationResult validationResult in validationResults)
                {
                    var temp = validationResult;

                    if (ThrowErrorOnFirstError)
                    {
                        throw new FaultException&amp;lt;ValidationFault&amp;gt;(new ValidationFault(new[] { temp }), "Validation error");
                    }

                    serviceIntance.ModelState.Errors.Add(new ModelError
                    {
                        MemberName = temp.MemberName,
                        Message = temp.Message
                    });
                }
            }
        }
        if (ThrowErrorAfterValidation &amp;&amp; !serviceIntance.ModelState.IsValid)
        {
            throw new FaultException&amp;lt;ValidationFault&amp;gt;(new ValidationFault(validationResults), "Validation error");
        }
    }
    return null;
}&lt;/pre&gt;
&lt;br/&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Summary, to use this library. We need to do following steps:
&lt;ul&gt;
&lt;li&gt;Decorate the service method with &lt;strong&gt;[FaultContract(typeof(ValidationFault))]&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;Decorate the service method implementation or contract with &lt;strong&gt;[ParameterValidator]&lt;/strong&gt;, by default it will throw fault exception if there is validation error&lt;/li&gt;
&lt;li&gt;Make service implementation implement interface &lt;strong&gt;IHasModelStateService&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;If we dont want to throw exception when validation error, we can check the &lt;strong&gt;ModelState.IsValid&lt;/strong&gt; like MVC way and do whatever we want:
&lt;br/&gt;
&lt;br/&gt;
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;if (!ModelState.IsValid)
{
    var error = new StringBuilder();
    foreach (var e in ModelState.Errors)
    {
        error.Append(string.Format("Validation error on {0}:{1}\n", e.MemberName, e.Message));
    }
    throw new FaultException(error.ToString());
}&lt;/pre&gt;
&lt;/ul&gt;
&lt;br/&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;That's it. If we want to use Microsoft Validation Application Block or Fluent Validation, just replace the ModelMetadataProvider and ModelValidatorProvider like what people did with ASP.NET MVC. There is definitely alot of things to improve such as implementing an IgnoreValidationAttribute on a certain complex property of a view model or supporting the validation with validation attribute decorated inside the method contract, etc. I would happy to implement all of them when I have a chance to apply this stuff in my real project. Now it's pretty enough for my birthday night :D
&lt;br/&gt;&lt;br/&gt;
Please refer to full source code here: &lt;a href="https://github.com/vanthoainguyen/Blog/tree/master/WCF.Validation.Demo" target="_blank"&gt;https://github.com/vanthoainguyen/Blog/tree/master/WCF.Validation.Demo&lt;/a&gt;
Cheers.

&lt;script language="javascript" type="text/javascript"&gt;SyntaxHighlighter.config.TypeNames = "ParameterValidatorAttribute Attribute IOperationBehavior AttributeUsage AttributeTargets OperationDescription BindingParameterCollection ClientOperation DispatchOperation ParameterValidatorBehavior IHasModelStateService ModelState OperationContext List ModelError ModelValidationResult IEnumerable ModelMetadata ModelMetadataProviders ModelValidator FaultException ValidationFault StringBuilder";&lt;/script&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-976763883678219684?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/VNgWbz8TQi8" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-11-08T10:54:52.824+11:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/11/wcf-validation-with-data-annotation.html</feedburner:origLink></item><item><title>Autofac, AutoMapper and custom converter with dependency injection</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/iqirxCOLNFI/autofac-automapper-custom-converter-di.html</link><category>AutoMapper</category><category>Autofac</category><category>DependencyInjection</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Fri, 28 Oct 2011 23:40:05 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-6528421199186558600</guid><description>Whenever I work with a library or a technology, one of the question in my mind is how good is it to support dependency injection. I came back to use Autofac in a company's project recently and that question is the one I need to find the answer. Basically, Autofac is a pretty cool library to help converting between domain objects and view models. 

For example:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;Mapper.CreateMap&amp;lt;Order, OrderViewModel&amp;gt;();&lt;/pre&gt;
&lt;br/&gt;
Or even better:
&lt;br/&gt;
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;Mapper.CreateMap&amp;lt;Order, OrderViewModel&amp;gt;()
      .ConvertUsing&amp;lt;OrderConverter&amp;gt;();&lt;/pre&gt;
&lt;br/&gt;
The good thing of Automapper is that it supports very good custom converters following the way above. Most of the cases, the custom converter is just a simple class to map from fields to fields when the structure of the domain object is so complicated. Well, it's good if we can make it simple at first place but life is not that easy. The project I'm working on was created by an offshore team and everyday looking to the code, I just wonder to myself: "WTF is this shit"
&lt;br/&gt;
The domain object is so complicated to map to the View Model by convention. ANd the ViewMOdel itself is complicated as well. It has logic to access WCF service to fetch domain data and map to itself :D. I'm spending my time to move the code to where it should be and using AutoMapper to map things is one of the steps. I hope you will never face anything like this, but in case you would and need a custom converter to access a service, this is the post for you.
&lt;br/&gt;
Now, my need is that the OrderConverter will need to call a service method to fetch some data while mapping objects. I also want the service interface to be the dependency of the converter, it will be the parameter in OrderCOnverter constructor and when we call Mapper.Map, the dependency will be injected by a IOC library, here i use Autofac. Below is the naive implementation of OrderConverter:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public class OrderConverter : ITypeConverter&amp;lt;Order, OrderViewModel&amp;gt;
{
    private readonly IOrderService _orderService;

    public OrderConverter(IOrderService orderService)
    {
        _orderService = orderService;
    }

    public OrderViewModel Convert(ResolutionContext context)
    {
        var order = context.SourceValue as Order;
        if (order == null)
        {
            return null;
        }

        var orderDetails = _orderService.GetOrderDetailsByOrderId(order.Id);
        return new OrderViewModel
        {
            Id = order.Id,
            Details = Mapper.Map&amp;lt;IEnumerable&amp;lt;OrderDetails&amp;gt;, IEnumerable&amp;lt;OrderDetailsViewModel&amp;gt;&amp;gt;(orderDetails).ToList()
        };
    }
}&lt;/pre&gt;
&lt;br /&gt;
I thought Autofac should have supported the way to resolve Converter. I didn't know how to do it until reading through the code. The Mapper static class has a method Initialize and through this, we can pass in custom logic to resolve objects.
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;// AutoMapper initialization
Mapper.Initialize(x =&amp;gt;
{
     x.ConstructServicesUsing(type =&amp;gt; container.Resolve(type));
});&lt;/pre&gt;
&lt;br /&gt;
The tricky thing is we need to call that method before we register mapper classes. The way I register mapper classes is using AutoFac scanning assemblies and make the mapper class implement IStartable.


&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;var builder = new ContainerBuilder();
// startable which include mapper classes
builder.RegisterAssemblyTypes(assemblies)
       .Where(t =&amp;gt; typeof(IStartable).IsAssignableFrom(t))
       .As&amp;lt;IStartable&amp;gt;()
       .SingleInstance();&lt;/pre&gt;
&lt;br /&gt;
These lines suppose to be after the Initialize method. I made the wrong mistake to put them in wrong order so the code couldn't work :D. I use the same way to register all the custom converters:
&lt;br /&gt;
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;// converters
builder.RegisterAssemblyTypes(assemblies)
       .AsClosedTypesOf(typeof(ITypeConverter&amp;lt;, &amp;gt;))
       .AsSelf();&lt;/pre&gt;
&lt;br /&gt;   
       
These lines would be executed in the BootStrapper before the main application run:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;BootStrapper.Run();

var order = new Order {Id = 1};

try
{
    var viewModel = Mapper.Map&amp;lt;Order, OrderViewModel&amp;gt;(order);

    Console.WriteLine(string.Format("\nThere are {0} order details", viewModel.Details.Count));
}
catch (Exception ex)
{
    Console.WriteLine(ex.StackTrace);
}
finally
{
    Console.ReadLine();
}&lt;/pre&gt;
&lt;br /&gt;

That's it. Please check out the full application on github: &lt;a href="https://github.com/vanthoainguyen/Blog/tree/master/TestAutoMapper" target="_blank"&gt;https://github.com/vanthoainguyen/Blog/tree/master/TestAutoMapper&lt;/a&gt;


&lt;script language="javascript" type="text/javascript"&gt;SyntaxHighlighter.config.TypeNames = "Mapper Order OrderViewModel IOrderService OrderService ResolutionContext OrderDetails OrderDetailsViewModel  IStartable ITypeConverter  Console Exception IEnumerable OrderConverter ContainerBuilder BootStrapper";&lt;/script&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-6528421199186558600?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/iqirxCOLNFI" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-10-29T17:40:05.280+11:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/10/autofac-automapper-custom-converter-di.html</feedburner:origLink></item><item><title>Combine logic of MVC FilterAttribute classes</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/IL67YVIvzkU/combine-mvc-filterattribute-logic.html</link><category>FilterAttribute</category><category>MVC</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Thu, 22 Sep 2011 22:10:27 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-532934842561403826</guid><description>&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Hi mates, today I would like to write another blog about the reason why I need an &lt;strong&gt;Autofac IContainer&lt;/strong&gt; as the dependency in some of my classes. In my team, we are developing a website that can allow users create and manage information about organisations. We have frontend pages for normal users to manage their organisations and we also have backend pages for the administrator to do that. So on frontend pages, we created a custom MVC filter attribute to decorate on every action methods that requires a need to check whether current user has the permission to view or edit the organisation. This filter attribute is also used in other places where we need similar authorization logic. On the other hand, we just need built-in Authorize attribute for all the admin pages. That looks like a straightforward solution, right?
&lt;br /&gt;&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;However, life is not that easy. Life is like a dick and sometime it's getting hard for no reason :D. The team decided to use MVC areas for Administrator and Organisations. That means the OrganisationManageController will be shared between those areas. Therefore, the authorization requirement would be: "Either the user is admin or the owner of the orngaisation, let him in". The first thing poped up in my mind was creating another filter attribute, inherit from Authorize filter attribute and copy the logic of my custom filter attribute which willl check the ownership. But not long after that, I realized it was so naive and ugly since the logic will be duplicated in those 2 attributes. Not only that, I was going to violate the cross-concern of the MVC Filter attributes because each of them should care and know about one and only one responsibility.
&lt;br /&gt;&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Then I come up with the idea i'm gonna write in this blog. I decided to create another Filter attribute that implements IAuthorizeFilter. It will be resonpsible for executing all the nested IAuthorizeFilter attributes and let the user pass in if one of the filter was satisfied. The usasge will look like:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;[HttpGet, Either(typeof(AuthorizeAttribute), @"Roles = ""Administrator""", typeof(CheckOwnerAttribute))]
public ActionResult Edit(ObjectId id)
{
	// ..........
}&lt;/pre&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;The &lt;strong&gt;EitherAttribute&lt;/strong&gt; class will have 1 public constructor that accepts an array of objects, begin by the type of an IAuthorizeFilter, followed by it's setter information or parameters for it's constructor or both and so on. So on method OnAuthorization, it will iterate through the child filters and execute method OnAuthorization on this filter. If after executing, the filterContext.Result is modified which means the user is not authorized, i'll reset the result and go for next filter. If it's the last filter which modified the filterContext.Result, i'll just simply return. Here is the implementation:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class EitherAttribute : FilterAttribute, IAuthorizationFilter
{
    // I need a dependency of ContainerFactory here
    public Func&amp;lt;IContainer&amp;gt; ContainerFactory { get; set; }
    
    private readonly object[] _filterConstructDescriptions;

    public EitherAttribute(params object[] filterConstructDescriptions)
    {
        _filterConstructDescriptions = filterConstructDescriptions;
    }

    public void OnAuthorization(AuthorizationContext filterContext)
    {
        List&amp;lt;IAuthorizationFilter&amp;gt; _filters = CreateFilters(_filterConstructDescriptions);
        for (var i = 0; i &amp;lt; _filters.Count(); i++)
        {
            var filter = _filters[i];
            filter.OnAuthorization(filterContext);
            if (filterContext.Result == null)
            {
                return;
            }
            
            // Check next authorize filter
            if (i &amp;lt; _filters.Count() - 1)
            {
                filterContext.Result = null;
            }
        }
    }

    // ..........
}&lt;/pre&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;There is one interesting point to note here is the &lt;strong&gt;EitherAttribute&lt;/strong&gt; has a dependency on &lt;em&gt;Autofac IContainer&lt;/em&gt; because the nested filter will be created by &lt;strong&gt;Activator&lt;/strong&gt; and if it has dependency on some services, we can use IContainer to inject require informations in. That's the reason I wrote about in &lt;a href="/2011/09/register-resolve-autofac-icontainer.html" target="_blank"&gt;previous post&lt;/a&gt;. 

&lt;br /&gt;&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;So with this awesome attribute, I don't have to duplicate the logic across different attributes and now can use it for many different IAuthorizeFilter classes. There is only 1 limitation which is the type it support is IAuthorizeFilter only but I haven't known yet any other cases that need to extend the &lt;strong&gt;EitherAttribute&lt;/strong&gt; to support other filter types.

&lt;br /&gt;&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;So please checkout the &lt;a href="http://innovie.com/blogkuckuvn/blogcontents/2011-09-23/EitherAttribute.zip" target="_blank"&gt;source code&lt;/a&gt; that includes some unit tests.
Cheers



&lt;script language="javascript" type="text/javascript"&gt;SyntaxHighlighter.config.TypeNames = "HttpGet Either AuthorizeAttribute CheckOwnerAttribute ActionResult ObjectId EitherAttribute FilterAttribute IAuthorizationFilter Func IContainer AuthorizationContext List AttributeUsage AttributeTargets ";&lt;/script&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-532934842561403826?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/IL67YVIvzkU" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-09-23T15:10:27.523+10:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><media:content url="http://feedproxy.google.com/~r/thoainguyen/~5/undRwSAN6ZM/EitherAttribute.zip" fileSize="2700" type="application/zip" /><itunes:explicit>no</itunes:explicit><itunes:subtitle>&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Hi mates, today I would like to write another blog about the reason why I need an Autofac IContainer as the dependency in some of my classes. In my team, we are developing a website that can allow users create and manage informatio</itunes:subtitle><itunes:author>noreply@blogger.com (vantheshark)</itunes:author><itunes:summary>&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Hi mates, today I would like to write another blog about the reason why I need an Autofac IContainer as the dependency in some of my classes. In my team, we are developing a website that can allow users create and manage information about organisations. We have frontend pages for normal users to manage their organisations and we also have backend pages for the administrator to do that. So on frontend pages, we created a custom MVC filter attribute to decorate on every action methods that requires a need to check whether current user has the permission to view or edit the organisation. This filter attribute is also used in other places where we need similar authorization logic. On the other hand, we just need built-in Authorize attribute for all the admin pages. That looks like a straightforward solution, right? &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;However, life is not that easy. Life is like a dick and sometime it's getting hard for no reason :D. The team decided to use MVC areas for Administrator and Organisations. That means the OrganisationManageController will be shared between those areas. Therefore, the authorization requirement would be: "Either the user is admin or the owner of the orngaisation, let him in". The first thing poped up in my mind was creating another filter attribute, inherit from Authorize filter attribute and copy the logic of my custom filter attribute which willl check the ownership. But not long after that, I realized it was so naive and ugly since the logic will be duplicated in those 2 attributes. Not only that, I was going to violate the cross-concern of the MVC Filter attributes because each of them should care and know about one and only one responsibility. &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Then I come up with the idea i'm gonna write in this blog. I decided to create another Filter attribute that implements IAuthorizeFilter. It will be resonpsible for executing all the nested IAuthorizeFilter attributes and let the user pass in if one of the filter was satisfied. The usasge will look like: [HttpGet, Either(typeof(AuthorizeAttribute), @"Roles = ""Administrator""", typeof(CheckOwnerAttribute))] public ActionResult Edit(ObjectId id) { // .......... } &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;The EitherAttribute class will have 1 public constructor that accepts an array of objects, begin by the type of an IAuthorizeFilter, followed by it's setter information or parameters for it's constructor or both and so on. So on method OnAuthorization, it will iterate through the child filters and execute method OnAuthorization on this filter. If after executing, the filterContext.Result is modified which means the user is not authorized, i'll reset the result and go for next filter. If it's the last filter which modified the filterContext.Result, i'll just simply return. Here is the implementation: [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)] public class EitherAttribute : FilterAttribute, IAuthorizationFilter { // I need a dependency of ContainerFactory here public Func&amp;lt;IContainer&amp;gt; ContainerFactory { get; set; } private readonly object[] _filterConstructDescriptions; public EitherAttribute(params object[] filterConstructDescriptions) { _filterConstructDescriptions = filterConstructDescriptions; } public void OnAuthorization(AuthorizationContext filterContext) { List&amp;lt;IAuthorizationFilter&amp;gt; _filters = CreateFilters(_filterConstructDescriptions); for (var i = 0; i &amp;lt; _filters.Count(); i++) { var filter = _filters[i]; filter.OnAuthorization(filterContext); if (filterContext.Result == null) { return; } // Check next authorize filter if (i &amp;lt; _filters.Count() - 1) { filterContext.Result = null; } } } // .......... } &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;There is one interesting point to note here is the EitherAttribute has a dependency on Autofac IContainer because the nested filter will be created by Activator and if it has dependency on some services, we can use ICo</itunes:summary><itunes:keywords>FilterAttribute, MVC</itunes:keywords><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/09/combine-mvc-filterattribute-logic.html</feedburner:origLink><enclosure url="http://feedproxy.google.com/~r/thoainguyen/~5/undRwSAN6ZM/EitherAttribute.zip" length="2700" type="application/zip" /><feedburner:origEnclosureLink>http://innovie.com/blogkuckuvn/blogcontents/2011-09-23/EitherAttribute.zip</feedburner:origEnclosureLink></item><item><title>Resolve Autofac IContainer Dependency Injection</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/utQ-0PegJUs/register-resolve-autofac-icontainer.html</link><category>Autofac</category><category>Dotnet</category><category>DependencyInjection</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Fri, 28 Oct 2011 23:54:30 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-1560364712792782909</guid><description>&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Today, i come to a need of using Autofac IContainer somewhere in my code. I know it's a bad practice using IContainer this way but i'm pretty sure sometime we must violate the convention. I'll show you the reason and the case on &lt;a href="/2011/09/combine-mvc-filterattribute-logic.html" target="_blank"&gt;next post&lt;/a&gt;. Now i just say about how to have the IContainer itself resolvable in some of the classes. I guess perhaps that's the intention of the Autofac author not to make the IContainer interface to be the dependency of classes. However, we have the ServiceLocator anyway so it's not that easy to force the developer following best practices.
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Okey, here is the problem. We have the ContainerBuilder to register types, instances, etc and in the end we build the container builder to return the container instance. So If I register the instance of IContainer using the way below, it's not gonna work:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;var builder = new ContainerBuilder();
// Register other dependencies in your app

IContainer container = null;
builder.RegisterInstance(container);

container = builder.Build();&lt;/pre&gt;
&lt;br /&gt;
The reason is we cannot register a null object. So here is the work around:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;var builder = new ContainerBuilder();
// Register other dependencies in your app

IContainer container = null;
Func&amp;lt;IContainer&amp;gt; factory = () =&amp;gt; container;
builder.RegisterInstance(factory);

container = builder.Build();&lt;/pre&gt;
&lt;br /&gt;
And in our code, we will make the factory to be it's dependency:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public class MyClass
{
    public MyClass(Func&amp;lt;IContainer&amp;gt; containerFactory)
    {
    }
}&lt;/pre&gt;
&lt;br /&gt;
Dirty, but works :D

&lt;script language="javascript" type="text/javascript"&gt;SyntaxHighlighter.config.TypeNames = "ContainerBuilder IContainer Func MyClass";&lt;/script&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-1560364712792782909?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/utQ-0PegJUs" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-10-29T17:54:30.890+11:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/09/register-resolve-autofac-icontainer.html</feedburner:origLink></item><item><title>Yet another way programming to the Interface In JavaScript, sort of</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/PeaOjrCPBHA/programming-interface-javascript-nodejs.html</link><category>NodeJs</category><category>JavaScript</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Thu, 25 Aug 2011 15:14:14 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-8589569137957367486</guid><description>&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;i have just blogged about &lt;a href="http://thoai-nguyen.blogspot.com/2011/08/javacript-class-inheritance-oop.html" target="_blank"&gt;inheritance in Javascript&lt;/a&gt;, so next target would be programming to the interface.
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;I had two approaches in mind. The first solution is making an interface as a normal object that contains properties and methods. This object will be static and remain unchanged during the lifetime of the application. The second solution is making the interface using the same way as creating the class in &lt;a href="http://thoai-nguyen.blogspot.com/2011/08/javacript-class-inheritance-oop.html" target="_blank"&gt;previous post&lt;/a&gt;. That means the type of the interface is also a javascript "function". And because i want to use the operator &lt;strong&gt;instanceOf&lt;/strong&gt; in javascript to check whether an object is an instance of a given type so apparently, the first solution will not work. So I have only 1 option and I need to make the interface not to be initialised like a class. Obvisously, you can't create an object with just an interface definition, can you?
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Alright, an interface would have a name and a constract that contains it's members. So I will make an utility which can return a function represents our interface:
&lt;br /&gt;
&lt;pre class="brush: javascript; smart-tabs: true; toolbar: false"&gt;function interface(name, contract){
    var _interface = function() {
        if (this._isImplementing !== true){
            throw 'Cannot initialize interface "' + name + '"';
        }    
        
        if (name === '' || typeof name !== 'string'){
            throw 'Must provide interface name';
        }
        
        if (contract == null || typeof contract !== 'object') {
            throw 'Must provide a contract as an object';
        }
        
        this._name = name;            
        this._contract = contract;    
    };        
    return _interface;
}&lt;/pre&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;I'm using a flag &lt;srong&gt;_isImplementing&lt;/strong&gt; to avoid creating instances using above function. Now I need a method similar to method "Inherit" in &lt;a href="http://thoai-nguyen.blogspot.com/2011/08/javacript-class-inheritance-oop.html" target="_blank"&gt;previous post&lt;/a&gt; but instead of inheriting from a class, it would implement the interface and make the class has all members of the interface's contract:
&lt;br /&gt;
&lt;pre class="brush: javascript; smart-tabs: true; highlight: [14]; toolbar: false"&gt;Object.defineProperty(Object.prototype, "Implement", {
    enumerable: false,
    value: function(anInterface) {        
        if (typeof (anInterface) != 'function') {
            throw 'Can implement and interface only';
        }
        if (typeof (this) != 'function') {
            throw 'Can call method on a function/class only';
        }        
        anInterface.prototype._isImplementing = true;
        this.prototype = new anInterface();
        anInterface.prototype._isImplementing = false;
        
        this.prototype.extend(this.prototype._contract);
        this.prototype._contract = null;
    }
});&lt;/pre&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;On line 14, I used method &lt;strong&gt;extend&lt;/strong&gt; which just simply copies all members from the contract to "this". So the class will have all members of the contract. You can find the implementation for that method in the file I attach at the end of this post. Finally, with all those stuff ready, i can introduce the demo below:
&lt;br /&gt;
&lt;pre class="brush: javascript; smart-tabs: true; toolbar: false"&gt;var IPet = interface('IPet', {
    Name: '', 
    Species: '', 
    GetDescription : function() {
        console.log('function.GetDescription: ' + this.Name + ' is a ' + this.Species);
    }
});
// define a class constructor
var Cat = function(name) {
    this.Name = name;
    this.Species = 'Cat';
}
// make that class implement an interface
Cat.Implement(IPet);

// create another class inherit from the above class
var Tiger = inheritFrom(Cat);


var cat = new Cat('Garfield');
if (cat instanceof IPet) {
    console.log('cat is an instance of IPet');           // Output: cat is an instance of Ipet
}
cat.GetDescription();                                    // Output: function.GetDescription: Garfield is a Cat

var tiger = new Tiger('Tony');
tiger.Species = 'Tiger';
if (tiger instanceof Cat){
    console.log('tiger is an instance of Cat');          // Output: tiger is an instance of Cat
}
if (tiger instanceof IPet){
    console.log('tiger is also an instance of IPet');    // Output: tiger is also an instance of IPet
}
tiger.GetDescription();                                  // Output: function.GetDescription: Tony is a Tiger
 
var tryToInitializeAnInterface = new IPet();             // ERROR: Can not initialize interface "IPet"&lt;/pre&gt;

&lt;br /&gt;
Well, &lt;strong&gt;the interface should not contain implementation&lt;/strong&gt;. In fact, I should throw "Not implemented exception" in the contract when i create the interface, and implement that in one of the top class that implements this interface. Honestly, in my real code I would be happy to do like that, but I still keep this mistake for the demo :D

Again, comments are welcome!!!
&lt;br /&gt;
&lt;a href="http://innovie.com/blogkuckuvn/blogcontents/2011-08-25/Demo-Interface-Javascript.zip" target="_blank"&gt;Source code&lt;/a&gt;
&lt;br /&gt;&lt;br /&gt;
Cheers&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-8589569137957367486?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/PeaOjrCPBHA" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-08-26T08:14:14.043+10:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">1</thr:total><media:content url="http://feedproxy.google.com/~r/thoainguyen/~5/4wGPUWKDiIw/Demo-Interface-Javascript.zip" fileSize="690" type="application/zip" /><itunes:explicit>no</itunes:explicit><itunes:subtitle>&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;i have just blogged about inheritance in Javascript, so next target would be programming to the interface. &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;I had two approaches in mind. The first solution is making an interface as a normal object that cont</itunes:subtitle><itunes:author>noreply@blogger.com (vantheshark)</itunes:author><itunes:summary>&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;i have just blogged about inheritance in Javascript, so next target would be programming to the interface. &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;I had two approaches in mind. The first solution is making an interface as a normal object that contains properties and methods. This object will be static and remain unchanged during the lifetime of the application. The second solution is making the interface using the same way as creating the class in previous post. That means the type of the interface is also a javascript "function". And because i want to use the operator instanceOf in javascript to check whether an object is an instance of a given type so apparently, the first solution will not work. So I have only 1 option and I need to make the interface not to be initialised like a class. Obvisously, you can't create an object with just an interface definition, can you? &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Alright, an interface would have a name and a constract that contains it's members. So I will make an utility which can return a function represents our interface: function interface(name, contract){ var _interface = function() { if (this._isImplementing !== true){ throw 'Cannot initialize interface "' + name + '"'; } if (name === '' || typeof name !== 'string'){ throw 'Must provide interface name'; } if (contract == null || typeof contract !== 'object') { throw 'Must provide a contract as an object'; } this._name = name; this._contract = contract; }; return _interface; } &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;I'm using a flag _isImplementing to avoid creating instances using above function. Now I need a method similar to method "Inherit" in previous post but instead of inheriting from a class, it would implement the interface and make the class has all members of the interface's contract: Object.defineProperty(Object.prototype, "Implement", { enumerable: false, value: function(anInterface) { if (typeof (anInterface) != 'function') { throw 'Can implement and interface only'; } if (typeof (this) != 'function') { throw 'Can call method on a function/class only'; } anInterface.prototype._isImplementing = true; this.prototype = new anInterface(); anInterface.prototype._isImplementing = false; this.prototype.extend(this.prototype._contract); this.prototype._contract = null; } }); &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;On line 14, I used method extend which just simply copies all members from the contract to "this". So the class will have all members of the contract. You can find the implementation for that method in the file I attach at the end of this post. Finally, with all those stuff ready, i can introduce the demo below: var IPet = interface('IPet', { Name: '', Species: '', GetDescription : function() { console.log('function.GetDescription: ' + this.Name + ' is a ' + this.Species); } }); // define a class constructor var Cat = function(name) { this.Name = name; this.Species = 'Cat'; } // make that class implement an interface Cat.Implement(IPet); // create another class inherit from the above class var Tiger = inheritFrom(Cat); var cat = new Cat('Garfield'); if (cat instanceof IPet) { console.log('cat is an instance of IPet'); // Output: cat is an instance of Ipet } cat.GetDescription(); // Output: function.GetDescription: Garfield is a Cat var tiger = new Tiger('Tony'); tiger.Species = 'Tiger'; if (tiger instanceof Cat){ console.log('tiger is an instance of Cat'); // Output: tiger is an instance of Cat } if (tiger instanceof IPet){ console.log('tiger is also an instance of IPet'); // Output: tiger is also an instance of IPet } tiger.GetDescription(); // Output: function.GetDescription: Tony is a Tiger var tryToInitializeAnInterface = new IPet(); // ERROR: Can not initialize interface "IPet" Well, the interface should not contain implementation. In fact, I should throw "Not implemented exception" in the contract when i create the interface, and implement that in one of the top class that implements this interface. Honestly, in my real code I would be happy t</itunes:summary><itunes:keywords>NodeJs, JavaScript</itunes:keywords><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/08/programming-interface-javascript-nodejs.html</feedburner:origLink><enclosure url="http://feedproxy.google.com/~r/thoainguyen/~5/4wGPUWKDiIw/Demo-Interface-Javascript.zip" length="690" type="application/zip" /><feedburner:origEnclosureLink>http://innovie.com/blogkuckuvn/blogcontents/2011-08-25/Demo-Interface-Javascript.zip</feedburner:origEnclosureLink></item><item><title>Yet another way for Javacript class inheritance, sort of</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/z9v4-bliEkA/javacript-class-inheritance-oop.html</link><category>NodeJs</category><category>JavaScript</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Wed, 24 Aug 2011 18:35:33 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-2974369723491149556</guid><description>&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Recently, I'm so interested in Node.js and i'm planning to do something cool with that new stuff. I have .NET background so i would expect I can write Javascript in OOP style or at least I want to create classes with inheritance support. Again, as usual, I did some googling :D. That leads me to following blog:
&lt;br /&gt;
&lt;a href="http://ejohn.org/blog/simple-javascript-inheritance/" target="_blank"&gt;http://ejohn.org/blog/simple-javascript-inheritance/&lt;/a&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;That is an elegant solution and it works. However, there is a drawback: you can only inherit from object not from type which i want to do. I mean if you want to create a class Pet and another class named Cat inherit from Pet, using this approach, you have to create an object name Pet and extend that pet object to make another Cat object.
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;I try to find other solution and find out some magic of using Javascript prototype which leads to my solution. First, we all know that everything in Javascript is object. Second we can create a function and it would be a constructor for any desire class.
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;For example, we can create a class Pet like below:
&lt;br /&gt;
&lt;pre class="brush: javascript; smart-tabs: true; toolbar: false"&gt;var Pet = function(name, species){
    this.Name = name;
    this.Species = species;        
};

// Define abstract method
Pet.prototype.Shout = function() {
    throw "Not implemented exception"; // Like .NET huh?
};

// and then we can create an object of type Pet:
var pet = new Pet('Scoobydoo', 'Dog');
&lt;/pre&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Alright, what we want to do is some how creating a function Dog that can create dogs inherit from Pet, dogs should also have Name and Species property.
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;I notice that in javascript, we can define methods, properties for "any object" at runtime using &lt;strong style='text-decoration:underline'&gt;Object.defineProperty&lt;/strong&gt; method. This ability is like extension methods in .NET but it's cooler since we can define the extensions at runtime.
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Okey, go back, with this idea in mine, i would implement the "inherit" method like below:
&lt;br /&gt;
&lt;pre class="brush: javascript; smart-tabs: true; toolbar: false"&gt;Object.defineProperty(Object.prototype, "Inherit", {
    enumerable: false,
    value: function(from) {
        if (typeof (from) != 'function') {
            throw 'Can inherit from a class function only';
        }
        if (typeof (this) != 'function') {
            throw 'Can call method on a class function only';
        }
        this.prototype = new from();        
        this.prototype._base = from.prototype;
    }
});&lt;/pre&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;So I can create the Dog class function like:
&lt;br /&gt;
&lt;pre class="brush: javascript; smart-tabs: true; toolbar: false"&gt;var Dog = function(name) {
    Dog.prototype = new Pet(name, 'Dog');
};

// Override the abstract method
Dog.prototype.Shout = function(){
    console.log('Woof!!!');
};&lt;/pre&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;If you notice, you can see that inside the "Inherit" method, i define a property name _base. That means the new type that inherits from provided type can access the base implementation:
&lt;br /&gt;
&lt;pre class="brush: javascript; smart-tabs: true; toolbar: false"&gt;Dog.prototype.Bark = function() {
    this._base.Shout();
};&lt;/pre&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Run this code will throw the "Not implemented exception" because of the Pet base method. We can redefine the Bark method to call the override Shout method:
&lt;br /&gt;
&lt;pre class="brush: javascript; smart-tabs: true; toolbar: false"&gt;Dog.prototype.Bark = function() {
    this.Shout();
};&lt;/pre&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;In summary, to be able to call method "Inherit" you need to defined base type, then define a derived type with a constructor and finally call this method. I would make another utility that can be reused to completly inherit from a given type include it's default constructor:
&lt;br /&gt;
// Call this method to completely inherit from a type include the base constructor
&lt;pre class="brush: javascript; smart-tabs: true; toolbar: false"&gt;function inheritFrom(type) {
    if (typeof (type) != 'function') {
        throw 'type must be a function';
    }
    
    // constructor with more than 3 params is not a good practice
    // in that case, param3 should be an object that contains the rest params
    var theClass = function(param1, param2, param3){
        type.call(this, param1, param2, param3);
    };    
    
    theClass.Inherit(type);
    return theClass;
}&lt;/pre&gt;
&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;There is 1 interesting point about this method is that it returns a &lt;strong&gt;function definition&lt;/strong&gt; which is an object in Javascript. So the overall demo would look like:
&lt;br /&gt;
&lt;pre class="brush: javascript; smart-tabs: true; highlight: [12, 21, 31]; toolbar: false"&gt;// PET: base class with a constructor require 2 params
var Pet = function(name, species){
    this.Name = name;
    this.Species = species;    
};
// Define abstract method
Pet.prototype.Shout = function() {
    throw "Not implemented exception"; // Like .NET huh?
};

// DOG: directly inherit from Pet, include constructor
var Dog = inheritFrom(Pet);
Dog.prototype.Shout = function(){
    console.log('Woof!!!');
};
Dog.prototype.Bark = function() {
    this.Shout();
};

// FISH: define another constructor which call base constructor inside, then inherit from the base type
var Fish = function(name) {
    Pet.call(this, name, 'Fish');
};
Fish.Inherit(Pet);
Fish.prototype.Shout = function(){
    console.log('!!!!!!!!!!!!!!!!!');
};


// CAT: directly inherit from Pet, include constructor
var Cat = inheritFrom(Pet);


var pet1 = new Dog('Scoobydoo', 'Dog');     // call inherit constructor
var pet2 = new Fish('Nemo');                // call custom constructor without specify species
var pet3 = new Cat('Garfield', 'Cat');      // call inherit constructor

pet1.Shout();              // Output 'Woof!!!'
pet1.Bark();               // Output 'Woof!!!'
console.log(pet1.Name);    // Output 'Scoobydoo'
console.log(pet1.Species); // Output 'Dog'


pet2.Shout();              // Output '!!!!!!!!!!!!!!!!!'
pet2.Bark();               // ERROR: Object has no method 'Bark'
console.log(pet2.Name);    // Output 'Nemo'
console.log(pet2.Species); // Output 'Fish'


pet3.Shout();              // ERROR: Not implemented exception
console.log(pet3.Name);    // Output 'Garfield'
console.log(pet3.Species); // Output 'Cat'
&lt;/pre&gt;
&lt;br /&gt;
Cheers, comments are welcome!!!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-2974369723491149556?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/z9v4-bliEkA" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-08-25T11:35:33.500+10:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/08/javacript-class-inheritance-oop.html</feedburner:origLink></item><item><title>MVC Donut hole caching for Razor View</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/XnCUG8B4xpU/mvc-donut-hole-caching-for-razor-view.html</link><category>ViewEngine</category><category>MVC</category><category>Razor</category><category>Caching</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Wed, 24 Aug 2011 18:59:55 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-861182512209462952</guid><description>&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;I was interested with Donut caching for a while and today I have a need for the Donut hole caching or partial view caching. As many of us, I tried to find whether some smart guys had solved this problem. And it seems like Mr.Haacked had mentioned this in &lt;a href="http://haacked.com/archive/2009/05/12/donut-hole-caching.aspx" target="_blank"&gt;his post&lt;/a&gt;. However, that solution is for ASP.NET view engine. I have no choice and have to solve it myself. Hopefully MVC team will support this feature in next versions of MVC framework. Hmmm indeed, it could be supported in version 4: See &lt;a href="http://aspnet.codeplex.com/wikipage?title=ASP.NET%20MVC%204%20RoadMap" target="_blank"&gt;road map&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;
&lt;img src="http://medicare.healthinsurance.org/img/donut-hole.jpg" /&gt;&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;My idea is if a view engine renders the view's content to a stream or text writer, we can intercept that process, cache the output string to somewhere together with the view's id or what ever that can identify the view. Then next time the view is rendered, we can determine whether or not to get the content from cache or let the view engine continue it's job. So i dig into the MVC source code and find this:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public class RazorView : BuildManagerCompiledView
{
    protected override void RenderView(ViewContext viewContext, TextWriter writer, object instance)
    {
        //.............
    }
}&lt;/pre&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;That's exactly what i need, isn't it? We probably can create a derived class from RazorView and override above method, get the content that the text writer receive and write it directly to the writer if the view is cached. So, i need a custom text writer that could return to me what it receive :D
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public class TrackableTextWriter : TextWriter
{
    private readonly TextWriter _writer;
    private StringBuilder _mem;
    public TrackableTextWriter(TextWriter writer)
    {
        _writer = writer;
        _mem = new StringBuilder();
    }
    public override Encoding Encoding
    {
        get { return _writer.Encoding; }
    }
    public override void Write(string value)
    {
        _writer.Write(value);
        _mem.Append(value);
    }
    public string GetWrittenString()
    {
        return _mem.ToString();
    }
    protected override void Dispose(bool disposing)
    {
        if (!disposing)
        {
            _writer.Dispose();           
        }
        base.Dispose(disposing);
        _mem = null;
    }
}&lt;/pre&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Alright, now it's time to create a derived of RazorView:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public class CachableRazorView : RazorView
{
	private const string ViewCachePrefix = "ViewCache__";
    protected override void RenderView(ViewContext viewContext, TextWriter writer, object instance)
	{
		var appCache = viewContext.HttpContext.Cache;
		var cacheKey = ViewCachePrefix + ViewPath;
		// Check if there was a Cache config that had been fully added to the cache
		var cacheConfiguration = appCache[cacheKey] as CacheConfiguration;
		if (cacheConfiguration != null &amp;amp;&amp;amp; cacheConfiguration.Data != null)
		{
			writer.Write(cacheConfiguration.Data);
			return;
		}
		var trackableTextWriter = new TrackableTextWriter(writer);
		base.RenderView(viewContext, trackableTextWriter, instance);
		
		// Cache config has just been added when the view is rendered the first time thanks to the HtmlHelper
		cacheConfiguration = appCache[cacheKey] as CacheConfiguration;
		if (cacheConfiguration != null)
		{
			var writtenString = trackableTextWriter.GetWrittenString();
			cacheConfiguration.Data = writtenString;
			appCache.Remove(cacheConfiguration.Id);
			appCache.Add(cacheConfiguration.Id,
						cacheConfiguration,
						null,
						Cache.NoAbsoluteExpiration,
						TimeSpan.FromSeconds(cacheConfiguration.Duration),
						CacheItemPriority.Default,
						null);
		}
	}
}&lt;/pre&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Then there's of course a place we can return this custom view instead of RazorView. That's definitely the RazorViewEngine. So next step is creating our custom razor view engine:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public class CachableRazorViewEngine : RazorViewEngine
{
	protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
	{
		return new CachableRazorView(controllerContext, partialPath, null, false, FileExtensions, ViewPageActivator);
	}

	protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
	{
		return new CachableRazorView(controllerContext, viewPath, masterPath, true, FileExtensions, ViewPageActivator);
	}
}&lt;/pre&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;As usual, we need to make the web application use this view engine by modifying the globals.asax
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;protected void Application_Start()
{
	AreaRegistration.RegisterAllAreas();

	RegisterGlobalFilters(GlobalFilters.Filters);

	ViewEngines.Engines.Clear();
	ViewEngines.Engines.Add(new CachableRazorViewEngine());

	RegisterRoutes(RouteTable.Routes);
}&lt;/pre&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Using this approach, the traditional OutputCache will not have value. So the idea pops in my head is making a HtmlHelper extension and calling it in the view, something like this:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;@{
	Html.OutputCache(new CacheConfiguration { Duration = 10 });
}&lt;/pre&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;So here is the implementation:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public static class CacheHtmlHelperExtensions
{
	public const string ViewCachePrefix = "ViewCache__";
	public static void OutputCache(this HtmlHelper helper, CacheConfiguration cacheConfiguration)
	{
		var view = helper.ViewContext.View as BuildManagerCompiledView;
		if (view != null)
		{
			cacheConfiguration.Id = ViewCachePrefix + view.ViewPath;
			helper.ViewContext.HttpContext.Cache.Add(cacheConfiguration.Id,
													cacheConfiguration,
                                                    null,
                                                    Cache.NoAbsoluteExpiration,
                                                    TimeSpan.FromSeconds(cacheConfiguration.Duration),
                                                    CacheItemPriority.Default,
                                                    null);
		}
	}
}&lt;/pre&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Okey, it's time to test this implementation. I put the Html.OutputCache method in the Index page of default MVC application like above. So the view will be cached in 10 seconds. If the view is not accessed in next 10 seconds, the cache engine will remove the content from the cache. However, within 10 seconds, if the view is accessed again, the cache will remain for next 10 seconds and so on. Pretty cool, huh? I need to run the performance test on this page to see the actual result. There is a very cool tool in Linux named "curl-loader" but I didn't know any for Windows. After a while searching, I found apache benchmark very similar and usefull :D. I use "ab" tool to test the web app when enable and disable the cache. The result is very interesting. Eventhough the Index page is quite simple with only text, no database access but when I enable the cache, the web server can serve 1107 requests per second when I run 10000 requests to server at concurency level at 100 compare to only 531 requests per second when I disable the cache, 2 times faster:
&lt;br /&gt;&lt;br /&gt;
&lt;a href="http://innovie.com/blogkuckuvn/blogcontents/2011-08-20/Result.png" target="_blank"&gt;&lt;img src="http://innovie.com/blogkuckuvn/blogcontents/2011-08-20/Result.png" style="width:560px" alt="benchmark result" /&gt;&lt;/a&gt;
&lt;br /&gt;&lt;br /&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Summary, there is a outstanding issue using this approach, the builtin output cache of ASP.NET can not be utilised. It also ignores the value of ViewModel, that's mean this implementation has not supported caching by different view model. But I think we can do it if we really need that feature. Just find a way to distinguish the different between view model values, it could be a hash code or something :D.
&lt;br /&gt;&lt;br /&gt;
Source code: &lt;a href="http://innovie.com/blogkuckuvn/blogcontents/2011-08-20/Razor.DonutHoleCaching.zip" target="_blank"&gt;Razor.DonutHoleCaching.zip&lt;/a&gt;
&lt;br /&gt;&lt;br /&gt;
Cheers
&lt;script language="javascript" type="text/javascript"&gt;SyntaxHighlighter.config.TypeNames = "RazorView BuildManagerCompiledView ViewContext TextWriter TrackableTextWriter StringBuilder Encoding CachableRazorView CacheConfiguration Cache TimeSpan CacheItemPriority CachableRazorViewEngine RazorViewEngine IView ControllerContext GlobalFilters ViewEngines RouteTable CacheHtmlHelperExtensions HtmlHelper";&lt;/script&gt;
&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-861182512209462952?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/XnCUG8B4xpU" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-08-25T11:59:55.395+10:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">2</thr:total><media:content url="http://feedproxy.google.com/~r/thoainguyen/~5/C0Or6lWJnOU/Razor.DonutHoleCaching.zip" fileSize="2090220" type="application/zip" /><itunes:explicit>no</itunes:explicit><itunes:subtitle>&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;I was interested with Donut caching for a while and today I have a need for the Donut hole caching or partial view caching. As many of us, I tried to find whether some smart guys had solved this problem. And it seems like Mr.Haacke</itunes:subtitle><itunes:author>noreply@blogger.com (vantheshark)</itunes:author><itunes:summary>&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;I was interested with Donut caching for a while and today I have a need for the Donut hole caching or partial view caching. As many of us, I tried to find whether some smart guys had solved this problem. And it seems like Mr.Haacked had mentioned this in his post. However, that solution is for ASP.NET view engine. I have no choice and have to solve it myself. Hopefully MVC team will support this feature in next versions of MVC framework. Hmmm indeed, it could be supported in version 4: See road map. &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;My idea is if a view engine renders the view's content to a stream or text writer, we can intercept that process, cache the output string to somewhere together with the view's id or what ever that can identify the view. Then next time the view is rendered, we can determine whether or not to get the content from cache or let the view engine continue it's job. So i dig into the MVC source code and find this: public class RazorView : BuildManagerCompiledView { protected override void RenderView(ViewContext viewContext, TextWriter writer, object instance) { //............. } } &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;That's exactly what i need, isn't it? We probably can create a derived class from RazorView and override above method, get the content that the text writer receive and write it directly to the writer if the view is cached. So, i need a custom text writer that could return to me what it receive :D public class TrackableTextWriter : TextWriter { private readonly TextWriter _writer; private StringBuilder _mem; public TrackableTextWriter(TextWriter writer) { _writer = writer; _mem = new StringBuilder(); } public override Encoding Encoding { get { return _writer.Encoding; } } public override void Write(string value) { _writer.Write(value); _mem.Append(value); } public string GetWrittenString() { return _mem.ToString(); } protected override void Dispose(bool disposing) { if (!disposing) { _writer.Dispose(); } base.Dispose(disposing); _mem = null; } } &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Alright, now it's time to create a derived of RazorView: public class CachableRazorView : RazorView { private const string ViewCachePrefix = "ViewCache__"; protected override void RenderView(ViewContext viewContext, TextWriter writer, object instance) { var appCache = viewContext.HttpContext.Cache; var cacheKey = ViewCachePrefix + ViewPath; // Check if there was a Cache config that had been fully added to the cache var cacheConfiguration = appCache[cacheKey] as CacheConfiguration; if (cacheConfiguration != null &amp;amp;&amp;amp; cacheConfiguration.Data != null) { writer.Write(cacheConfiguration.Data); return; } var trackableTextWriter = new TrackableTextWriter(writer); base.RenderView(viewContext, trackableTextWriter, instance); // Cache config has just been added when the view is rendered the first time thanks to the HtmlHelper cacheConfiguration = appCache[cacheKey] as CacheConfiguration; if (cacheConfiguration != null) { var writtenString = trackableTextWriter.GetWrittenString(); cacheConfiguration.Data = writtenString; appCache.Remove(cacheConfiguration.Id); appCache.Add(cacheConfiguration.Id, cacheConfiguration, null, Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(cacheConfiguration.Duration), CacheItemPriority.Default, null); } } } &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Then there's of course a place we can return this custom view instead of RazorView. That's definitely the RazorViewEngine. So next step is creating our custom razor view engine: public class CachableRazorViewEngine : RazorViewEngine { protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath) { return new CachableRazorView(controllerContext, partialPath, null, false, FileExtensions, ViewPageActivator); } protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) { return new CachableRazorView(controllerContext, viewPath, masterPath, true, FileExtensions, ViewPageActivator); } } &amp;nbsp;&amp;nb</itunes:summary><itunes:keywords>ViewEngine, MVC, Razor, Caching</itunes:keywords><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/08/mvc-donut-hole-caching-for-razor-view.html</feedburner:origLink><enclosure url="http://feedproxy.google.com/~r/thoainguyen/~5/C0Or6lWJnOU/Razor.DonutHoleCaching.zip" length="2090220" type="application/zip" /><feedburner:origEnclosureLink>http://innovie.com/blogkuckuvn/blogcontents/2011-08-20/Razor.DonutHoleCaching.zip</feedburner:origEnclosureLink></item><item><title>Unit Test DisplayFormat attribute HtmlHelper</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/lxjxeE-NLwA/unit-test-displayformat-attribute.html</link><category>UnitTest</category><category>Mock</category><category>MVC</category><category>Moq</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Thu, 28 Jul 2011 17:32:25 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-4070822746776045913</guid><description>&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Previously, I wrote about &lt;a href="http://thoai-nguyen.blogspot.com/2011/04/test-mock-mvc-view-engine.html" target="_blank"&gt;how to mock a ViewEngine&lt;/a&gt; for one of my unit tests. Today, I came across a question on &lt;a href="http://stackoverflow.com/questions/6778681/displayformat-unit-testing-with-htmlhelper" target="_blank"&gt;StackOverflow&lt;/a&gt; asking about how to unit test the out put of DataAnnotation attribute DisplayFormat. I'm very interested in Unit Test so I decide to find the answer, another reason is to increase my reputation on StackOverflow :D. Honestly, I don't exactly know the reason why to test the output because for me, we don't need to test code that was not written by us. Anyways, this is a interesting question for me.

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Let's say we have a ViewModel using DisplayFormat like below:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public class UserViewModel
{        
    [DisplayFormat(DataFormatString = "{0:dd/MM/yy}")]
    public DateTime Birthday { get; set; }
}&lt;/pre&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;And here is the basic unit test to verify the output
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;[Test]
public void Test_output_display_format_for_Birthday_property()
{
    // Arrange
    var _model = new UserViewModel {Birthday = DateTime.Parse("28/07/11") };
    var helper = MvcTestControllerBuilder.GetHtmlHelper&amp;lt;UserViewModel&amp;gt;();
    helper.ViewData.Model = _model;
    
    // Action
    var result = helper.DisplayFor(x =&amp;gt; x.Birthday);
    
    // Assert
    Assert.That(result.ToHtmlString(), Is.EqualTo("28/07/11"));
}&lt;/pre&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Apparently, this test failed like the description in the StackOverflow question. I decided to debug the MVC source code and found 2 reasons:

+ First, the MVC framework will find the ActionCacheItem using method GetActionCache:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;internal static Dictionary&amp;lt;string, ActionCacheItem&amp;gt; GetActionCache(HtmlHelper html)
{
    HttpContextBase httpContext = html.ViewContext.HttpContext;
    if (!httpContext.Items.Contains(cacheItemId))
    {
        Dictionary&amp;lt;string, ActionCacheItem&amp;gt; dictionary = new Dictionary&amp;lt;string, ActionCacheItem&amp;gt;();
        httpContext.Items[cacheItemId] = dictionary;
        return dictionary;
    }
    return (Dictionary&amp;lt;string, ActionCacheItem&amp;gt;) httpContext.Items[cacheItemId];
}&lt;/pre&gt;
It'll try to find the cache item in httpContext.Items but the Items is null. So the first thing we need to mock the value for httpContext.Items:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;var helper = MvcTestControllerBuilder.GetHtmlHelper&amp;lt;UserViewModel&amp;gt;();
helper.ViewContext.HttpContext.Setup(x =&amp;gt; x.Items).Returns(new Dictionary&amp;lt;string, object&amp;gt;());&lt;/pre&gt;
+ Secondly, the MVC framework will try to find the display template for "DateTime" and "String". Obviously we don't have those stuff in the Unit test environment. The code is located in TemplateHelpers.cs:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false;highlight: [19]"&gt;internal static string ExecuteTemplate(HtmlHelper html, ViewDataDictionary viewData, string templateName, DataBoundControlMode mode, GetViewNamesDelegate getViewNames, GetDefaultActionsDelegate getDefaultActions)
{
    Dictionary&amp;lt;string, ActionCacheItem&amp;gt; actionCache = GetActionCache(html);
    Dictionary&amp;lt;string, Func&amp;lt;HtmlHelper, string&amp;gt;&amp;gt; dictionary2 = getDefaultActions(mode);
    string str = modeViewPaths[mode];
    foreach (string str2 in getViewNames(viewData.ModelMetadata, new string[] { templateName, viewData.ModelMetadata.TemplateHint, viewData.ModelMetadata.DataTypeName }))
    {
        ActionCacheItem item;
        Func&amp;lt;HtmlHelper, string&amp;gt; func;
        string key = str + "/" + str2;
        if (actionCache.TryGetValue(key, out item))
        {
            if (item != null)
            {
                return item.Execute(html, viewData);
            }
            continue;
        }
        ViewEngineResult result = ViewEngines.Engines.FindPartialView(html.ViewContext, key);
        if (result.View != null)
        {
            ActionCacheViewItem item2 = new ActionCacheViewItem {
                ViewName = key
            };
            actionCache[key] = item2;
            using (StringWriter writer = new StringWriter(CultureInfo.InvariantCulture))
            {
                result.View.Render(new ViewContext(html.ViewContext, result.View, viewData, html.ViewContext.TempData, writer), writer);
                return writer.ToString();
            }
        }
        if (dictionary2.TryGetValue(str2, out func))
        {
            ActionCacheCodeItem item3 = new ActionCacheCodeItem {
                Action = func
            };
            actionCache[key] = item3;
            return func(MakeHtmlHelper(html, viewData));
        }
        actionCache[key] = null;
    }
    throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, MvcResources.TemplateHelpers_NoTemplate, new object[] { viewData.ModelMetadata.RealModelType.FullName }));
}&lt;/pre&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;So the main thing we need to do is somehow mock the result at line "19" to make the view engine return a ViewEngineResult that has View property equals to null. I make a helper method similar to this post to do this:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public static ViewEngineResult SetupNullViewFor(string viewName)
{
    Mock&amp;lt;IViewEngine&amp;gt; mockedViewEngine = GetCurrentMockViewEngine() ?? new Mock&amp;lt;IViewEngine&amp;gt;();
    var viewEngineResult = new ViewEngineResult(new List&amp;lt;string&amp;gt;());

    mockedViewEngine.Setup(x =&amp;gt; x.FindPartialView(It.IsAny&amp;lt;ControllerContext&amp;gt;(), viewName, It.IsAny&amp;lt;bool&amp;gt;()))
                    .Returns(viewEngineResult);
    mockedViewEngine.Setup(x =&amp;gt; x.FindView(It.IsAny&amp;lt;ControllerContext&amp;gt;(), viewName, It.IsAny&amp;lt;string&amp;gt;(), It.IsAny&amp;lt;bool&amp;gt;()))
                    .Returns(viewEngineResult);

    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(mockedViewEngine.Object);
    return viewEngineResult;
}

private static Mock&amp;lt;IViewEngine&amp;gt; GetCurrentMockViewEngine()
{
    foreach(var v in ViewEngines.Engines)
    {
        try
        {
            return Mock.Get&amp;lt;IViewEngine&amp;gt;(v);
        }
        catch (Exception)
        {
        }
    }
    return null;
}&lt;/pre&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;With all of these stuff, the final unit test would look like:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;[Test]
public void Test_output_display_format_for_Birthday_property()
{
    // Arrange    
    MvcTestFixtureHelper.SetupNullViewFor("DisplayTemplates/DateTime");
    MvcTestFixtureHelper.SetupNullViewFor("DisplayTemplates/String");
    
    var _model = new UserViewModel {Birthday = DateTime.Parse("28/07/11")};
    var helper = MvcTestControllerBuilder.GetHtmlHelper&amp;lt;UserViewModel&amp;gt;();
    helper.ViewContext.HttpContext.Setup(x =&amp;gt; x.Items).Returns(new Dictionary&amp;lt;string, object&amp;gt;());
    helper.ViewData.Model = _model;
    
    // Action
    var result = helper.DisplayFor(x =&amp;gt; x.Birthday);
    
    // Assert
    Assert.That(result.ToHtmlString(), Is.EqualTo("28/07/11"));
}&lt;/pre&gt;

You can refer to my similar posts about &lt;a href="" target="_blank"&gt;MvcTestControllerBuilder&lt;/a&gt; (this class has some methods to mock HtmlHelper) and &lt;a href="http://thoai-nguyen.blogspot.com/2011/04/test-mock-mvc-view-engine.html" target="_blank"&gt;How to mock the ViewEngine&lt;/a&gt;. In those posts, I used NSubstitue but now I changed to use Moq, they're quite similar :D.
Cheers.
&lt;script language="javascript" type="text/javascript"&gt;SyntaxHighlighter.config.TypeNames = "DisplayFormat UserViewModel MvcTestControllerBuilder Assert Is Dictionary ActionCacheItem HtmlHelper ViewDataDictionary DataBoundControlMode GetViewNamesDelegate GetDefaultActionsDelegate Func ViewEngineResult StringWriter CultureInfo ActionCacheCodeItem InvalidOperationException ControllerContext It List MvcResources IViewEngine Mock MvcTestFixtureHelper HttpContextBase Test ViewEngines  ActionCacheViewItem ViewContext";&lt;/script&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-4070822746776045913?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/lxjxeE-NLwA" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-07-29T10:32:25.744+10:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">3</thr:total><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/07/unit-test-displayformat-attribute.html</feedburner:origLink></item><item><title>Save some lines for your Razor view</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/vcXapdFGibg/save-some-lines-for-your-razor-view.html</link><category>MVC</category><category>Dotnet</category><category>Razor</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Mon, 18 Jul 2011 23:39:15 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-8483054515242373689</guid><description>We all know that we should not put logic in the MVC view. If we have to do something base on a complex condition, we should better make a HtmlHelper method for that logic. In an attempt to remove some simple if/else statement on the view by using some extention method.

Let's say we have something like below in the view:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;@if (!Request.IsAuthenticated)
{
    Html.RenderPartial("LoginBox");
}&lt;/pre&gt;
I attempt to make it look like:
&lt;pre class="brush: csharp;gutter: false; toolbar: false;smart-tabs: true;"&gt;&amp;nbsp;
@{ Html.Do(x =&amp;gt; x.RenderPartial("LoginBox"))
       .When(!Request.IsAuthenticated); }
&amp;nbsp;&lt;br/&gt;
&lt;/pre&gt;
So we can save 2 lines of code or event 3 lines if we write the code in 1 line:
&lt;pre class="brush: csharp;gutter: false; toolbar: false;smart-tabs: true;"&gt;&amp;nbsp;
@{ Html.Do(x =&amp;gt; x.RenderPartial("LoginBox")).When(!Request.IsAuthenticated); }
&amp;nbsp;&lt;br/&gt;
&lt;/pre&gt;
I know it is very hard to remove all condition logic from the view unless you create HtmlHelper methods for all the condition logic on your view. But it could lead to so many methods. I think we should not create helper method if we don't use the method 2 places. So the method I suggest could help :D. I think it improves the readablity for your view code especially both the designers and developers are working on the same file.
So here is the code:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public interface IAction&amp;lt;T&amp;gt;
{
    T Object { get;}
    Action&amp;lt;T&amp;gt; Action { get; }
    void When(Expression&amp;lt;Func&amp;lt;T, bool&amp;gt;&amp;gt; when);
    void When(bool when);
}&lt;/pre&gt;
I will make 2 implementation of the above interface. The first one is OneConditionAction and the other is PostConditionAction. So I can combine multi conditions like:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;@{ Html.When(!Request.IsAuthenticated)
       .And(....)
       .And(....)
       .Do(x =&amp;gt; x.RenderPartial("LoginBox")); }&lt;/pre&gt;       
Below is the implementation:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public class OneConditionAction&amp;lt;T&amp;gt; : IAction&amp;lt;T&amp;gt;
{
    public T Object { get; private set; }

    public Action&amp;lt;T&amp;gt; Action { get; private set; }

    public virtual void When(Expression&amp;lt;Func&amp;lt;T, bool&amp;gt;&amp;gt; when)
    {
        if (when.Compile()(Object))
        {
            Action(Object);
        }
    }

    public void When(bool when)
    {
        if (when)
        {
            Action(Object);
        }
    }

    public OneConditionAction(Action&amp;lt;T&amp;gt; action, T helper)
    {
        Action = action;
        Object = helper;
    }
}       

public class PostConditionsAction&amp;lt;T&amp;gt; : OneConditionAction&amp;lt;T&amp;gt;
{
    public PostConditionsAction(IAction&amp;lt;T&amp;gt; conditionalAction)
        : base(conditionalAction.Action, conditionalAction.Object)
    {
        Condition = x =&amp;gt; true;
    }

    public Expression&amp;lt;Func&amp;lt;T, bool&amp;gt;&amp;gt; Condition { get; set; }

    public override void When(Expression&amp;lt;Func&amp;lt;T, bool&amp;gt;&amp;gt; when)
    {
        var newCondition = this.And(when);
        Condition = newCondition.Condition;
    }
}&lt;/pre&gt;
We'll need the extension methods:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;namespace System.Web.Mvc
{
    public static class ActionExtensions
    {
        public static IAction&amp;lt;T&amp;gt; Do&amp;lt;T&amp;gt;(this T obj, Action&amp;lt;T&amp;gt; action) where T : class
        {
            return new OneConditionAction&amp;lt;T&amp;gt;(action, obj);
        }

        public static IAction&amp;lt;T&amp;gt; Do&amp;lt;T&amp;gt;(this T obj, Action action) where T : class
        {
            return new OneConditionAction&amp;lt;T&amp;gt;(a =&amp;gt; action(), obj);
        }
    }
    
    public static class PostConditionsActionExtensions
    {
        public static PostConditionsAction&amp;lt;T&amp;gt; When&amp;lt;T&amp;gt;(this T obj, bool condition)
        {
            var newAction = new PostConditionsAction&amp;lt;T&amp;gt;(new OneConditionAction&amp;lt;T&amp;gt;(x =&amp;gt; { }, obj));
            newAction = newAction.And(condition);
            return newAction;
        }

        public static PostConditionsAction&amp;lt;T&amp;gt; When&amp;lt;T&amp;gt;(this T obj, Expression&amp;lt;Func&amp;lt;T, bool&amp;gt;&amp;gt; condition)
        {
            var newAction = new PostConditionsAction&amp;lt;T&amp;gt;(new OneConditionAction&amp;lt;T&amp;gt;(x =&amp;gt; { }, obj));
            newAction = newAction.And(condition);
            return newAction;
        }

        public static PostConditionsAction&amp;lt;T&amp;gt; And&amp;lt;T&amp;gt;(this PostConditionsAction&amp;lt;T&amp;gt; postConditions, Expression&amp;lt;Func&amp;lt;T, bool&amp;gt;&amp;gt; andCondition)
        {
            var x = Expression.Parameter(typeof(T));
            postConditions.Condition = Expression.Lambda&amp;lt;Func&amp;lt;T, bool&amp;gt;&amp;gt;(Expression.And(Expression.Invoke(postConditions.Condition, x), Expression.Invoke(andCondition, x)), x);
            return postConditions;
        }

        public static PostConditionsAction&amp;lt;T&amp;gt; And&amp;lt;T&amp;gt;(this PostConditionsAction&amp;lt;T&amp;gt; postConditions, bool andCondition)
        {
            return postConditions.And(x =&amp;gt; andCondition);
        }

        public static PostConditionsAction&amp;lt;T&amp;gt; Or&amp;lt;T&amp;gt;(this PostConditionsAction&amp;lt;T&amp;gt; postConditions, Expression&amp;lt;Func&amp;lt;T, bool&amp;gt;&amp;gt; orCondition)
        {
            var x = Expression.Parameter(typeof(T));
            postConditions.Condition = Expression.Lambda&amp;lt;Func&amp;lt;T, bool&amp;gt;&amp;gt;(Expression.Or(Expression.Invoke(postConditions.Condition, x), Expression.Invoke(orCondition, x)), x);
            return postConditions;
        }

        public static PostConditionsAction&amp;lt;T&amp;gt; Or&amp;lt;T&amp;gt;(this PostConditionsAction&amp;lt;T&amp;gt; postConditions, bool orCondition)
        {
            return postConditions.Or(x =&amp;gt; orCondition);
        }

        public static void Do&amp;lt;T&amp;gt;(this PostConditionsAction&amp;lt;T&amp;gt; postConditions, Action&amp;lt;T&amp;gt; action) where T : class
        {
            postConditions.Object.Do(action).When(postConditions.Condition);
        }

        public static void Do&amp;lt;T&amp;gt;(this PostConditionsAction&amp;lt;T&amp;gt; postConditions, Action action) where T : class
        {
            postConditions.Object.Do(action).When(postConditions.Condition);
        }
    }
}&lt;/pre&gt;

Because they are generic classes, so we can use this syntax for any object, not only HtmlHelper :D

Cheers
&lt;script language="javascript" type="text/javascript"&gt;SyntaxHighlighter.config.TypeNames = "IAction OneConditionAction PostConditionsAction Action Expression Func ActionExtensions PostConditionsActionExtensions";&lt;/script&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-8483054515242373689?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/vcXapdFGibg" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-07-19T16:39:15.821+10:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">1</thr:total><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/07/save-some-lines-for-your-razor-view.html</feedburner:origLink></item><item><title>How to mock UrlHelper?</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/Rr45Gre0bSY/how-to-mock-urlhelper.html</link><category>UnitTest</category><category>Mock</category><category>MVC</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Mon, 18 Jul 2011 22:24:07 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-1677130015141637779</guid><description>Sometime, you need to write unit test for an action method that needs a &lt;strong&gt;UrlHelper&lt;/strong&gt;. But I'm sure you will never can mock that stuff since it's a concrete class and it's methods are not virtual. Let's say we have following action method and want to test it:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;[Authorize]
public ActionResult LogOnAs(Guid userId, string returnUrl)
{
    // Logic to login user by Id ...
    
    if (Url.IsLocalUrl(returnUrl))
    {
        return Redirect(returnUrl);
    }

    return RedirectToAction("Index", "User");
}&lt;/pre&gt;
    I did some research, experimented with some results and find that extracting the UrlHelper methods to an interface then make a wrapper class to implement that interface is the best way. We need to define a new property to the BaseController like below.
&lt;pre class="brush: csharp;gutter: false; toolbar: false;smart-tabs: true;"&gt;&amp;nbsp;
public new IUrlHelper Url {get; set;}
&amp;nbsp;&lt;br/&gt;
&lt;/pre&gt;
    Then in the unit test project, after initializing the controller, you can mock the interface easily. You probably need only some methods from the UrlHelper so I would recommend you extract only those required methods to IUrlHelper. For example:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public interface IUrlHelper
{
    string Action(string actionName, string controllerName);

    string Action(string actionName, string controllerName, object routeValues);

    string Action(string actionName, string controllerName, RouteValueDictionary routeValues);
    
    bool IsLocalUrl(string url);
}&lt;/pre&gt;
    Finally, we can create an adaptor class like below to delegate all method calls to the real UrlHelper object:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public class UrlHelperAdaptor : UrlHelper, IUrlHelper
{
    internal UrlHelperAdaptor(RequestContext requestContext)
        : base(requestContext)
    {
    }

    internal UrlHelperAdaptor(RequestContext requestContext, RouteCollection routeCollection)
        : base(requestContext, routeCollection)
    {
    }

    public UrlHelperAdaptor(UrlHelper helper) 
        : base(helper.RequestContext, helper.RouteCollection)
    {
    }
}&lt;/pre&gt;
    Apparently, we need to initialize the new Url property in the BaseController to make the real code work normally:    
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
    base.Initialize(requestContext);
    Url = new UrlHelperAdaptor(base.Url);
}&lt;/pre&gt;
    Now, the controller method is fully testable.
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;[Test]
public void LogonAs_should_return_RedirectToRouteResult()
{
    // Arrange
    var controller = new AccountController();
    /* Create a mock of IUrlHelper */
    controller.Url = Moq.Mock.Of&amp;lt;IUrlHelper&amp;gt;(x =&amp;gt; x.IsLocalUrl(It.IsAny&amp;lt;string&amp;gt;()) == false);     

    // Action
    var result = controller.LogOnAs(Guid.NewGuid(), "any-return-url") as RedirectToRouteResult;

    // Assert
    result.Should().Not.Be.Null();
}&lt;/pre&gt;

   Using this approach can help you test any class that depends on IUrlHelper such as custom UrlHelper classes.

Cheers
&lt;script language="javascript" type="text/javascript"&gt;SyntaxHighlighter.config.TypeNames = "Authorize ActionResult Guid Mock Test RedirectToRouteResult UrlHelperAdaptor IUrlHelper UrlHelper RouteValueDictionary It AccountController RequestContext RouteCollection";&lt;/script&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-1677130015141637779?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/Rr45Gre0bSY" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-07-19T15:24:07.596+10:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/07/how-to-mock-urlhelper.html</feedburner:origLink></item><item><title>Never give a chance to make something wrong</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/-X2uB7KXWIs/never-give-chance-to-make-something.html</link><category>Dotnet</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Wed, 06 Jul 2011 00:19:05 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-148584366884565699</guid><description>Recectly, I've penetrated the truth that if you don't want others do something (bad), never ever give them a chance to do that. It's true in both my real life and in programming. Since my blog is just about software programming, I would like to write about some funny mistakes that people often make. Well, I did make some of them in the past :D

&lt;h4&gt;1/ You may forget about the ability of the constructor.&lt;/h4&gt;
Let's look at following code:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public class UserViewModel
{    
    // These properties must not be null
    public string FirstName { get; set;}
    public string LastName { get; set;}
    public string Email { get; set;}    
}&lt;/pre&gt;
We can see from the comment in the class above, the author want 3 propreties must have value. It oould be his intention but someone else may need a instance of this class, so he instantiates a UserViewModel object without setting the values for any of those 3 properties. And that could cause problems at runtime since it's not what the author of UserViewModel want. So instead of doing this, we can make the language ensuring that requirement for us:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;using System.Diagnostics.Contracts;
public class UserViewModel
{    
    public UserViewModel(string firstName, string lastName, string email)
    {
        Contract.Assert(!string.IsNullOrEmpty(firstName), "firstName must have value");
        Contract.Assert(!string.IsNullOrEmpty(lastName) , "lastName must have value");
        Contract.Assert(!string.IsNullOrEmpty(email)    , "email must have value");
    
        FirstName = firstName;
        LastName = lastName;
        Email = email;
    }
    
    // These properties must not be null
    public string FirstName { get; private set;}
    public string LastName { get; private set;}
    public string Email { get; private set;}    
}&lt;/pre&gt;
&lt;h4&gt;2/ You won't need a private field for a public property.&lt;/h4&gt;
My team is applying BDD and using PageObject pattern. A guy in a team created a class that have a something like:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;private RegistrationStatus _registrationStatus;

public RegistrationStatus Status
{
    get { return _registrationStatus; }
}&lt;/pre&gt;
What an unnecessary 4 lines of code. You know what, just a few weeks later, the solution is full of these mistakes because alot of people are writing BDD tests and they like copy &amp; paste.
So, just change it to 1 line of code version:
&lt;pre class="brush: csharp;gutter: false; toolbar: false;smart-tabs: true;"&gt;&amp;nbsp;
public RegistrationStatus Status {get; private set;}
&amp;nbsp;&lt;br/&gt;
&lt;/pre&gt;
Well, if you don't want to see these stuff in the code, don't make any thing like this because we're all doing the "COPY &amp; PASTE" job.

&lt;h4&gt;3/ If you have not finished something, use NotImplementedException&lt;/h4&gt;
Apparently working in a team, someone could create a service interface with some methods then the other could use the service for presentation layer.
Here is an example:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public interface IUserService
{
    User Get(Guid id);
    int Count();
}

public UserService : IUserService
{
    public User Get(Guid id)
    {
        return null;
    }
    
    public int Count()
    {
        return -1;
    }
}&lt;/pre&gt;
Everything is fine when compile but why return something like those when they're useless value. Well, if we need an implementation of IUserService, why not create a Mock or a fake object then everyone knows it's a fake and it will never been used in the production. However, it could be acceptable if we are creating a NullObject, but I mostly throw NotImplementedException instead of doing nothing for a void method or return meaningless value for functions.

&lt;h4&gt;4/ it's not really a singleton&lt;/h4&gt;
Everyone knows about singleton. It supposes to be the easiest most simple design pattern. Let's see this code:
&lt;pre class="brush: csharp; smart-tabs: true; toolbar: false"&gt;public class Helper
{
    private static Helper _instance;
    public static Helper Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new Helper();
            }
            return _instance;            
        }
    }
}&lt;/pre&gt;
Okey, it's just a very simple implementation. But the idea is that it allows only 1 instance of Helper in the system and whenever you want that instance, you must access it from Helper.Instance. Cool but it's not really singleton. Anyone can create an object of Helper easily because by default, the constructor is public so make it private if you don't want people use it.

&lt;h4&gt;5/ We should follow Dependency Inversion Principle&lt;/h4&gt;
This principle is the one that affects my way of thinking. If you read about the Onion architecture, you'll see that architecture is not complicated. It just applies the DIP and make a flashy name. If we apply DIP strickly, we'll never put implementation and interface together in a class library. Instead, put them in separated project. Classes depend on the interface will never know about the concreate implementation of that interface and they will be connected by some sort of IOC library. However, doing that way can make you create alot of projects in one solution. Honestly I have never done anything like this but, but I think Onion architecture is something to consider when you design new application. I prefer isolating the business implementation from the technology we use so any changes of technology will make a little affect to our code. 


&lt;script language="javascript" type="text/javascript"&gt;SyntaxHighlighter.config.TypeNames = "UserViewModel RegistrationStatus Helper IUserService UserService Contract";&lt;/script&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-148584366884565699?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/-X2uB7KXWIs" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-07-06T17:19:05.849+10:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/07/never-give-chance-to-make-something.html</feedburner:origLink></item><item><title>Basic Unit Of Work Implementation</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/HyvXCYC7yW4/basic-unit-of-work-implementation.html</link><category>UnitOfWork</category><category>EntityFramework</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Tue, 31 May 2011 23:52:00 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-301756017978042286</guid><description>&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;I bet you must have heard about Unit Of Work. If you have not, you can find the discription here : &lt;a href="http://martinfowler.com/eaaCatalog/unitOfWork.html" target="_blank"&gt;http://martinfowler.com/eaaCatalog/unitOfWork.html&lt;/a&gt;.

&lt;quote&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;You can change the database with each change to your object model, but this can lead to lots of very small database calls, which ends up being very slow. Furthermore it requires you to have a transaction open for the whole interaction, which is impractical if you have a business transaction that spans multiple requests. The situation is even worse if you need to keep track of the objects you've read so you can avoid inconsistent reads.
&lt;/quote&gt;

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Nowadays, DDD is one of the most famous design methodologies in the developer community. Even though &lt;a href="http://thinkddd.com/assets/2/Domain_Driven_Design_-_Step_by_Step.pdf" target="_blank"&gt;95% of all software applications fall into the “not so good for using DDD” categories&lt;/a&gt;, some practices and ideas of DDD can be used in many .NET projects, especially Repository and Domain Service. I have seen many implementations of Repository pattern and UnitOfWork, but i am not so happy with any because of the following reason. We tend to use some kinds of ORM like NHibernate or EF as the technology behind Repository implementation. These frameworks mostly have the Unit Of Work built in, so I think the Domain Service layer should not call IUnitOfWork.CommitChange() when it needs to persist something to the repository. In some complex services, we call a service method which may execute different service methods; and because a service method (that requires changing the database) should call IUnitOfWork.CommitChanges. Therefore, as a result, IUnitOfWork.CommitChanges will be called many times in 1 business transaction. 

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Another example could be the controller which can use several domain services to execute an action method. Let's say a website user wants to register at your website. When he submits the registration form, the RegisterController will call the UserService to create a user to the repository and another service create a WelcomeEmail in the Email repository. That means there are 2 records are got involed in this transaction (assume that you use SQL as the data source). And a proper UnitOfWork implementation should be called only 1 time to finish the saving task. However, it's easy to see the implementation like this:
&lt;pre class="brush: csharp; toolbar: false"&gt;[HttpPost]
public ActionResult Register(RegisterUserViewModel viewModel)
{
    if (!ModelState.IsValid)
    {
        return View(viewModel)
    }
    
    UserService.Create(user);
    EmailService.Create(welcomeEmail);
    
    return RedirectToAction("Index", "Home");
}&lt;/pre&gt;
In the user service implementation :
&lt;pre class="brush: csharp; toolbar: false"&gt;public void Create(User contact)
{    
    _userRepository.Add(contact);
    _unitOfWork.CommitChange();
}&lt;/pre&gt;
And in the email service implementation :
&lt;pre class="brush: csharp; toolbar: false"&gt;public void Create(Email email)
{    
    _emailRepository.Add(email);
    _unitOfWork.CommitChange();
}&lt;/pre&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;It's not difficult to see that the UnitOfWork will call method &lt;strong&gt;CommitChange()&lt;/strong&gt; two times. If you use EF behind the Repository implementation, I'm sure the code above will make your breakpoint stop at method &lt;strong&gt;ObjectContext.SaveChanges()&lt;/strong&gt; 2 times. For me it’s not &lt;em&gt;“Unit Of Work”&lt;/em&gt; if we do like that. It would be nice if we could have a way to call the CommitChange() only when we actually need, it could be the end of every http request. Therefore, the domain services should never call CommitChange() on your UnitOfWork. 

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Base on this idea which is a bit similar to "Open Session In View" pattern, I created a basic implementation of UnitOfWork below:
&lt;pre class="brush: csharp; toolbar: false"&gt;public interface IUnitOfWork
{
    void CommitChange();
    bool IsDirty { get; set; }
}&lt;/pre&gt;
The domain service will use a &lt;strong&gt;UnitOfWorkScope&lt;/strong&gt; to ensure the change will be committed in the end or immediately based on the &lt;strong&gt;UnitOfWorkScopeOption&lt;/strong&gt;:
&lt;pre class="brush: csharp; toolbar: false"&gt;public enum UnitOfWorkScopeOption
{
    Shared,
    CommitImmediately
}

public class UnitOfWorkScope : Disposable
{
    private readonly UnitOfWorkScopeOption _option;
    private readonly IUnitOfWork _unitOfWork;

    public UnitOfWorkScope() : this(UnitOfWorkScopeOption.Shared)
    {
    }

    public UnitOfWorkScope(UnitOfWorkScopeOption option)
    {
        _option = option;
        _unitOfWork = ObjectFactory.GetInstance&amp;lt;IUnitOfWork&amp;gt;(); // I'm using StructureMap
    }

    protected override void DisposeCore()
    {
        switch(_option)
        {
            case UnitOfWorkScopeOption.CommitImmediately:
                {
                    _unitOfWork.CommitChange();
                    _unitOfWork.IsDirty = false;
                    break;
                }
            default:
                _unitOfWork.IsDirty = true;
                break;
        }
    }
}&lt;/pre&gt;
I will change the service methods like below:
&lt;pre class="brush: csharp; toolbar: false"&gt;public void Create(User contact)
{    
    using (new UnitOfWorkScope())
    {
        _userRepository.Add(contact);    
    }
}

public void Create(Email email)
{    
    using (new UnitOfWorkScope())
    {
        _emailRepository.Add(email);
    }
}&lt;/pre&gt;
The default constructor of UnitOfWorkScope would set the scope option to Shared. That means it would do nothing but mark the UnitOfWork.IsDirty to true. In the end,
we can base on that value to determine whether we should call commit change. I put this logic in the base controller, so after the ActionExecuted, the UnitOfWork will be invoked to do the saving job.
&lt;pre class="brush: csharp; toolbar: false"&gt;protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
    base.OnActionExecuted(filterContext);

    if (filterContext.Exception == null || filterContext.ExceptionHandled)
    {
        var unitOfWork = ObjectFactory.GetInstance&amp;lt;IUnitOfWork&amp;gt;();
        if (unitOfWork != null &amp;&amp; unitOfWork.IsDirty)
        {
            unitOfWork.CommitChange();
        }
    }    
}&lt;/pre&gt;
I made a test project and looks like it run at least 2 times faster than the the original way when I use &lt;strong&gt;UnitOfWorkScope&lt;/strong&gt;.
There is a very cool implementation of UnitOfWork at &lt;a href="https://github.com/riteshrao/ncommon" target="_blank"&gt;NCommon&lt;/a&gt;. You should check it out.
Finally, &lt;a href="http://innovie.com/blogkuckuvn/blogcontents/2011-06-01/UnitOfWork.rar" target="_blank"&gt;here is the test project.&lt;/a&gt;
Cheers
&lt;script language="javascript" type="text/javascript"&gt;SyntaxHighlighter.config.TypeNames = "HttpPost ActionResult RegisterUserViewModel ModelState User Email IUnitOfWork UnitOfWorkScope Disposable UnitOfWorkScopeOption ObjectFactory ActionExecutedContext";&lt;/script&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-301756017978042286?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/HyvXCYC7yW4" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-06-01T16:52:00.377+10:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">5</thr:total><media:content url="http://feedproxy.google.com/~r/thoainguyen/~5/GlqkdHEMZkw/Domain_Driven_Design_-_Step_by_Step.pdf" fileSize="911240" type="application/pdf" /><itunes:explicit>no</itunes:explicit><itunes:subtitle>&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;I bet you must have heard about Unit Of Work. If you have not, you can find the discription here : http://martinfowler.com/eaaCatalog/unitOfWork.html. &amp;nbsp;&amp;nbsp;&amp;nbsp;You can change the database with each change to your object mo</itunes:subtitle><itunes:author>noreply@blogger.com (vantheshark)</itunes:author><itunes:summary>&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;I bet you must have heard about Unit Of Work. If you have not, you can find the discription here : http://martinfowler.com/eaaCatalog/unitOfWork.html. &amp;nbsp;&amp;nbsp;&amp;nbsp;You can change the database with each change to your object model, but this can lead to lots of very small database calls, which ends up being very slow. Furthermore it requires you to have a transaction open for the whole interaction, which is impractical if you have a business transaction that spans multiple requests. The situation is even worse if you need to keep track of the objects you've read so you can avoid inconsistent reads. &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Nowadays, DDD is one of the most famous design methodologies in the developer community. Even though 95% of all software applications fall into the “not so good for using DDD” categories, some practices and ideas of DDD can be used in many .NET projects, especially Repository and Domain Service. I have seen many implementations of Repository pattern and UnitOfWork, but i am not so happy with any because of the following reason. We tend to use some kinds of ORM like NHibernate or EF as the technology behind Repository implementation. These frameworks mostly have the Unit Of Work built in, so I think the Domain Service layer should not call IUnitOfWork.CommitChange() when it needs to persist something to the repository. In some complex services, we call a service method which may execute different service methods; and because a service method (that requires changing the database) should call IUnitOfWork.CommitChanges. Therefore, as a result, IUnitOfWork.CommitChanges will be called many times in 1 business transaction. &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Another example could be the controller which can use several domain services to execute an action method. Let's say a website user wants to register at your website. When he submits the registration form, the RegisterController will call the UserService to create a user to the repository and another service create a WelcomeEmail in the Email repository. That means there are 2 records are got involed in this transaction (assume that you use SQL as the data source). And a proper UnitOfWork implementation should be called only 1 time to finish the saving task. However, it's easy to see the implementation like this: [HttpPost] public ActionResult Register(RegisterUserViewModel viewModel) { if (!ModelState.IsValid) { return View(viewModel) } UserService.Create(user); EmailService.Create(welcomeEmail); return RedirectToAction("Index", "Home"); } In the user service implementation : public void Create(User contact) { _userRepository.Add(contact); _unitOfWork.CommitChange(); } And in the email service implementation : public void Create(Email email) { _emailRepository.Add(email); _unitOfWork.CommitChange(); } &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;It's not difficult to see that the UnitOfWork will call method CommitChange() two times. If you use EF behind the Repository implementation, I'm sure the code above will make your breakpoint stop at method ObjectContext.SaveChanges() 2 times. For me it’s not “Unit Of Work” if we do like that. It would be nice if we could have a way to call the CommitChange() only when we actually need, it could be the end of every http request. Therefore, the domain services should never call CommitChange() on your UnitOfWork. &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Base on this idea which is a bit similar to "Open Session In View" pattern, I created a basic implementation of UnitOfWork below: public interface IUnitOfWork { void CommitChange(); bool IsDirty { get; set; } } The domain service will use a UnitOfWorkScope to ensure the change will be committed in the end or immediately based on the UnitOfWorkScopeOption: public enum UnitOfWorkScopeOption { Shared, CommitImmediately } public class UnitOfWorkScope : Disposable { private readonly UnitOfWorkScopeOption _option; private readonly IUnitOfWork _unitOfWork; public UnitOfWorkScope() : this(UnitOfWorkScop</itunes:summary><itunes:keywords>UnitOfWork, EntityFramework</itunes:keywords><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/06/basic-unit-of-work-implementation.html</feedburner:origLink><enclosure url="http://feedproxy.google.com/~r/thoainguyen/~5/GlqkdHEMZkw/Domain_Driven_Design_-_Step_by_Step.pdf" length="911240" type="application/pdf" /><feedburner:origEnclosureLink>http://thinkddd.com/assets/2/Domain_Driven_Design_-_Step_by_Step.pdf</feedburner:origEnclosureLink></item><item><title>Some issues with BDD Specflow &amp; WatIn</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/9jIDJY4LfOY/bdd-specflow-watin.html</link><category>UnitTest</category><category>BDD</category><category>WatIn</category><category>Specflow</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Mon, 30 May 2011 16:28:43 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-901212885869687077</guid><description>&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Last few weeks, our team is doing alot of experiments on BDD. We read several books trying to find out the proper way to apply BDD in .NET project using &lt;a href="http://www.specflow.org/" target="_blank"&gt;Specflow&lt;/a&gt; and &lt;a href="http://watin.org/" target="_blank"&gt;WatIn&lt;/a&gt;. There are some good articles out there indeed but for me, they're quite basic. These articles do the good works to help me start the first steps but after walking several steps, some issues comes up:
&lt;em&gt;
- What is the good way to initialize some test data before a scenario? 
- What is the good way to write feature files?
- When would we run these UI tests?
- What is the good way to implement step definitions that faciliate reusable and easy maintenance?
- What to do if the feature requires some interaction to external sources?&lt;/em&gt;

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Honestly, we've not had the best answers in 3 weeks. Some other issues would come up in the future and we might have better answers for what we want. However, I'm quite happy with following solutions:
&lt;h4&gt;1/ What is the good way to initialize some test data before a scenario?&lt;/h4&gt;
This question came up when we met some feature that requite existing data. Let's look at following scenario:
&lt;pre class="brush: specflow;gutter: false;  toolbar: false"&gt;Scenario: Log-In
Given I enter a previously registered email address / password combination
When I click log-in
Then the site will authenticate me and remember me for the remainder of my session&lt;/pre&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;In order to execute this test, it assumes that we have a registered user in the system. I tried to google a lot to find the answer for this question. Fortunately, I found it while reading the &lt;a href="http://cuke4ninja.com" target="_blank"&gt;cuke4ninja&lt;/a&gt; document. Basicaly, there are 3 methods to do this:

- Direct access to the database
- Call to the business layer API
- Creating records using the UI

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Our team had a big argument about it for 2 weeks. The reason is we devided developers into Presentation and Service teams. These 2 teams will work parallel together, one to build the services include backend code like repositories, services, etc; one to implement the web and UI test that utilises the service made by the other team. The thing is presentation team will not know and should not know anything about what the other team would do. For example, the presentation team should not know anything about database schema. We should have agrement on the a service the presentation team needs. So the presentation team will mock the service to be able to run the web while the required service is being implemented by the other team. And thus, the presentation team could call this service to make some initialisation for the test. Personally, I don't like this idea because of following reasons:

- Ultimately, the UI tests will talk to the database, not the mocked service because we want the end to end task, so writing some codes that access to the database to clean up/ initalise is not a big deal.

- For me, The UI test code should only be methods that are called to interact with user interface rather than depending on some Service API

- The UI test would be run multiple times against the real database, we definitely need some way to clean up the records made be previous test run. It could be difficult to delete a record since it could require cascade delete. If I still keen to use this way, I have to modify the service and add method &lt;strong&gt;Delete&lt;/strong&gt; for some related services. And I think it is not a best practice because we should not change the code design just for the test run. 

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Therefore, a small script to empty tables, re-insert data to tables is quite good for me. This script will be made by the service team and they need to ensure that the script is up to date to make the whole test pass. The presentation team should use UI to create records they need for the test. Everything will be much simpler if the developer can get involve in implementing everything from service code to presentation code.
&lt;h4&gt;2/ What is the good way to write feature files?&lt;/h4&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;The solution above leads to this question. For some complex scenarios that require complex exisiting data, writing UI code for it is not a proper way. Even though the script to initialise data could do this perfectly, but let me say again, the presentation team will not know what the service team would do include that scripts. So if i don't want to call the service api to do the job, I must spend effort to write the UI code for initialisation stuff.

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;So, why don't we re-write the scenario in a way that reduces the need for data initialisation. Let's say we have this scenario:
&lt;pre class="brush: specflow;gutter: false;  toolbar: false"&gt;Given I am a new user
And I am on the Registration page
When I enter the following basic details
 | Forename | Surname | Email                | Password |
 | Van      | Nguyen  | van.nguyen@email.com | 123456   |
And I submit the form
Then the site will save my details
And show a message saying 'Registration successful'&lt;/pre&gt;
Should we write:
&lt;pre class="brush: specflow;gutter: false;  toolbar: false"&gt;Given I am a new user
And I am on the Registration page
When I enter the my basic details with an email that's never been used
And I submit the form
Then the site will save my details
And show a message saying 'Registration successful'&lt;/pre&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Then we could implement the "Never been used" by using an email that contains a GUID or DateTime.Now.Ticks. So that test won't need any database clean up or initialisation. It's easier to create something that is unique rather than making sure something that does not exist in the system. Positive way is always better than negative way, isn't it :D. In the sample solution, I utilised the @tag feature of Specflow, so any scenarios with the tag &lt;strong&gt;@requireCleanDb&lt;/strong&gt; would have the step hook to clean and initialise the database to the original state.
&lt;h4&gt;3/ When would we run these UI tests?&lt;/h4&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;I must say that I'm a bad developer. I hate to fix bugs, expecially bugs that caused by others. In our project, I implemented a feature and later on, any bugs on that feature were assigned to me. That was fine but the thing is when fixing these bugs I found that the root reason was some changes in javascript or some guys just removed the property of a View Model without fixing the View. Unit test does the very good work that can make sure any checkin will not break the existing code, but it cannot prevents bug caused by a small change in javascript. UI automation test could do this, but it has a problem with running time so It could not be executed for every checkin. Then my pain will still be there as my team agrees to run the tests every day at night. And in the morning, developers will receive the test run report. However, every developer could run the tests before checkin to make sure he would not ruin something.
&lt;h4&gt;4/ What is the good way to implement step definitions that facilitate reusable and easy maintenance?&lt;/h4&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;This is my most interesting question. I couldn't resist the temptation to use WatIn classes to implement the test when I read the &lt;a href="http://watin.org" target="_blank"&gt;how to&lt;/a&gt; document. But when I read the other book &lt;a href="http://cuke4ninja.com" target="_blank"&gt;cuke4ninja&lt;/a&gt; and I watched this mvcConf: &lt;a href="http://channel9.msdn.com/Series/mvcConf/mvcConf-2-Brandom-Satrom-BDD-in-ASPNET-MVC-using-SpecFlow-WatiN-and-WatiN-Test-Helpers" target="_blank"&gt;BDD in ASP.NET MVC using SpecFlow, WatiN and WatiN Test Helpers&lt;/a&gt;, I knew I need some kind of abstraction. I need wrappers for WatIn classes. I implemented some "technical" classes like Page, Form and "Workflow" classes for the flow of the UI tests. I decided to split these things into separated class libraries, most of the classes were internal except the "workflow" classes which will be used in the step definition implementation. So in the end, my integration test project just know about workflow classes without knowing anything about Page, Form or WatIn. Actually, at first, I let the UI test methods utilise Page, Form objects along with WorkFlow classes but then I thought it would be better to make Page and Form internal. So instead of doing like this:
&lt;pre class="brush: csharp; toolbar: false"&gt;[Then(@"the site will authenticate me and remember me for the remainder of my session")]
public void ThenTheSiteWillAuthenticateMeAndRememberMeForTheRemainderOfMySession()
{
      Assert.IsTrue(Page.Current.ContainsText("Log Off"));
      Assert.IsTrue(Page.Current.Url == "/Home/Index" || Page.Current.Url == "/");
}&lt;/pre&gt;
I prefer doing like this:
&lt;pre class="brush: csharp; toolbar: false"&gt;[Then(@"the site will authenticate me and remember me for the remainder of my session")]
public void ThenTheSiteWillAuthenticateMeAndRememberMeForTheRemainderOfMySession()
{
      Assert.IsTrue(LoggedInUser.Current.IsLoggin());
      Assert.IsTrue(LoggedInUser.Current.IsAtHomePage());
}&lt;/pre&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;It makes the test method easy to read and certainly, the method is reusable. Please checkout the example project in the end of this post for more detail. Please note that I implement it based on my perspective and I don't say It the best way. So please correct me.
&lt;h4&gt;5/ What to do if the feature requires some interaction to external sources?&lt;/h4&gt;
Or should we test if the feature requires interation to external resources?
Let's say we have following scenarios:
&lt;pre class="brush: specflow;gutter: false;  toolbar: false"&gt;Scenario: Forgot Password - Password Retrieval
Given I enter an email address that was previously registered with the site
When I click 'send email'
Then I receive a message telling 'An email was sent to you to reset your password!'
And I receive an email containing a link to reset my password&lt;/pre&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;If we want to write the test for this, we might need a mail box such as Gmail. We'll simulate user interaction on the mail box to click on the forget password link, etc. So what happens if the Gmail change their UI which could make our test fail. Personally, I still like to test this scenario as a normal user instead of creating some kind of mocks to have the reset link. Because I think the "end to end test" is testing the appliation just like the normal user use it. And these kind of scenarios would just be a few so It will not be a big deal. Okey, what's if they are alot? Well, I think abstraction of the external interaction activities could be an option. Talking to external resources is the common thing of a software. We use ORM to talk to database, they could change the library anytime, so what we do? We update the library. We call to 3rd API like Facebook API, Twitter API, Credit card processing service, etc. They could change their API anytime, so what we do? We make the wrapper to these API then we could switch to better service anytime. That's it. So I believe abstraction would be a good solution for these kinds of thing. However, it's still a debate in my team whether it could add much value to write UI test for these kinds of scenario. Perhaps the time will find the answer for this question.

&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Hmmm, so far so good. Please checkout the demo project. It contains my basic idea above. Again, I don't say It's the best way of using WatIn or implementation of BDD. There must be other issues because these features are very basic. Everything here is based on my personal perspective and I'm very gratefull if any readers of this post would give me your idea to make it better, or just tell me I was wrong at some points.

Thanks for reading.

Code: &lt;a href="http://innovie.com/blogkuckuvn/blogcontents/2011-05-30/BDD.Test.rar"&gt;Download&lt;/a&gt;


&lt;script language="javascript" type="text/javascript"&gt;SyntaxHighlighter.config.TypeNames = "Then Page LoggedInUser";&lt;/script&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-901212885869687077?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/9jIDJY4LfOY" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-05-31T09:28:43.966+10:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/05/bdd-specflow-watin.html</feedburner:origLink></item><item><title>Defining Custom Functions in Entity Framework</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/OG9W3jT8NTQ/custom-function-entity-framework.html</link><category>EntityFramework</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Mon, 30 May 2011 16:12:25 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-6972566129910062654</guid><description>Well, I's been 1 month since my last post. Today, I'm gonna write something about the well-known not supported issue of Entity Framework.

   I intended to write a LinQ to Entity query that would require a comparison and conversion between uniqueidentifier and string value in SQL database. The query looks like this:
&lt;pre class="brush: csharp; toolbar: false"&gt;var items = from x in XRepository.GetAll()
            join y in YRepository.GetAll() on x.UniqueId.ToString() equals y.StringValue into xy
            from z in xy.DefaultIfEmpty()
            select x;&lt;/pre&gt;

   I wrote the unit test and the test run through the code without any problem. But when I run the application against the real SQL database, there would be a following exception:

&lt;em&gt;
&lt;strong style="color:red"&gt;System.NotSupportedException&lt;/strong&gt;: LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.
&lt;/em&gt;

   After a while googling, I realized that there are not any built-in support to achive what I want. However, in EF4, there is a class named: &lt;strong&gt;SqlFunctions.StringConvert&lt;/strong&gt; that can convert from double to string. Moreover, it can be used in LinQ to Entity queries. That class led me to the &lt;strong&gt;EdmFunctionAttribute&lt;/strong&gt; and then I decided to create something similar to convert from uniqueidentifier to nvarchar for my need.

   I definitely need a custom SQL Function for conversion:

&lt;pre class="brush: sql; toolbar: false"&gt;CREATE FUNCTION [dbo].[GuidToString]
(
    @guid as uniqueidentifier
)
RETURNS varchar(50)
AS
BEGIN
    return CONVERT(varchar(50), @guid)
END");&lt;/pre&gt;

   What I do next is to modify the EDMX file and add a small xml code:
&lt;pre class="brush: sql; toolbar: false"&gt;&amp;lt;Function Name="GuidToString" 
          Aggregate="false" 
          BuiltIn="false" 
          NiladicFunction="false" 
          IsComposable="true" 
          ParameterTypeSemantics="AllowImplicitConversion" 
          Schema="dbo" ReturnType="varchar"&amp;gt;
    &amp;lt;Parameter Name="guid" Type="uniqueidentifier" Mode="In" /&amp;gt;
&amp;lt;/Function&amp;gt;&lt;/pre&gt;

   I just find  &lt;strong&gt;&amp;lt;/Schema&amp;gt;&amp;lt;/edmx:StorageModels&amp;gt;&lt;/strong&gt; and add the xml code before it. Because the function would return something, so the &lt;strong&gt;IsComposable&lt;/strong&gt; must be set to true and we must provide the &lt;strong&gt;ReturnType&lt;/strong&gt; value for the function.

   After that, I create a static class like below. It can be put anywhere in your solution.         

&lt;pre class="brush: csharp; toolbar: false"&gt;[EdmFunction("My.Namespace.Store", "GuidToString")]
public static string GuidToString(Guid guid)
{
    // This code will never been run against real SQL database
    // This will help any test requires this method pass
    return guid.ToString().ToUpper();
}&lt;/pre&gt;

   The namespace I provide to &lt;strong&gt;EdmFunctionAttribute&lt;/strong&gt; is really important. It must match the namespace in the &lt;strong&gt;EDMX file&lt;/strong&gt;. You can easily find the namespace as an attribute of the xml node "Schema" when viewing the EDMX file using any XML editor.

   Finally, I can change the code to use the method like below:
&lt;pre class="brush: csharp; toolbar: false"&gt;var items = from x in XRepository.GetAll()
            join y in YRepository.GetAll() on GuidToString(x.UniqueId) equals y.StringValue into xy
            from z in xy.DefaultIfEmpty()
            select x;&lt;/pre&gt;


Cheers

&lt;script language="javascript" type="text/javascript"&gt;SyntaxHighlighter.config.TypeNames = "EdmFunction Guid from on equals into select join";&lt;/script&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-6972566129910062654?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/OG9W3jT8NTQ" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-05-31T09:12:25.206+10:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/05/custom-function-entity-framework.html</feedburner:origLink></item><item><title>MVC RouteConstraint is the culprite</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/ALCcV0E6Lyo/mvc-routeconstraint-is-culprite.html</link><category>MVC</category><category>RouteConstraint</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Thu, 21 Apr 2011 18:59:15 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-3240147639224641725</guid><description>Today, several of our live product sites got a serious issue. The page that renders a list of businesses took over 1 minutes to render. We couldn't find out the problem in serveral hours. After a while keep investigating, we found that the call of below method took about 6 seconds to run:

&lt;pre class="brush: csharp;gutter: false; toolbar: false]"&gt;&amp;nbsp;&lt;br/&gt;UrlHelper.Action("action", "controller", RouteValueCollection)
&amp;nbsp;&lt;br/&gt;
&lt;/pre&gt;

That means on a page that contains 10 links to the business detail would take about 1 minutes to render. It was really strange because this method is the built-in method of ASP.NET MVC so we didn't think it's our database issus. Another reason helped us beleave in our assumtion was that we tried to debug the service to get the list of businesses from database and saw that it was fast although we have over 1 mil of records in database, just the rendering step was so slow.

I kept trying and stepped into MVC source code. It led me to this method which took 6 seconds to run: 

&lt;pre class="brush: csharp;gutter: false; toolbar: false]"&gt;&amp;nbsp;&lt;br/&gt;RouteCollection.GetVirtualPath(RequestContext, RouteValueDictionary)
&amp;nbsp;&lt;br/&gt;&lt;/pre&gt;

RouteCollection is a class in namespace &lt;b&gt;System.Web.Routing&lt;/b&gt; and it was very strange because I couldn't continue to step into this method to debug. But anyways, it gave me another hint, there could be something wrong with our Routing table. So I opened the route registration code in our project and realized that we were using a RouteConstraint for the business route:

&lt;pre class="brush: csharp; toolbar: false]"&gt;routes.MapRoute(
  "Business",
  "Business/{slug}",
  new { controller = "Business", action = "Detail" },
  new { slug = new BusinessSlugConstraint()}
);&lt;/pre&gt;


That means whenever it renders the link like &lt;em&gt;"/Business/business-slug"&lt;/em&gt; it will check whether the slug "business-slug" exists. We have over 1 mil of businesses in database so it could took a lot of time for this check. For now, what we can do to make a quick fix is rendering the detail links manually without using UrlHelper. It could save us some time and we'll address this issue later. Anyway, from now on, we should be careful when using the &lt;strong&gt;RouteConstraint&lt;/strong&gt; cos it would never jump into it's code when we press F11 unless we put a break point in the &lt;strong&gt;RouteConstraint&lt;/strong&gt; implementation.

Cheers


&lt;script language="javascript" type="text/javascript"&gt;SyntaxHighlighter.config.TypeNames = "BusinessSlugConstraint UrlHelper RouteCollection RequestContext RouteValueDictionary";&lt;/script&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-3240147639224641725?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/ALCcV0E6Lyo" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-04-22T11:59:15.427+10:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/04/mvc-routeconstraint-is-culprite.html</feedburner:origLink></item><item><title>Optional Parameter Is Ugly</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/RTzyR4osXtY/optional-parameter-is-ugly.html</link><category>Dotnet</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Tue, 19 Apr 2011 05:49:40 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-7032784337225247943</guid><description>&lt;strong&gt;Optional Parameter&lt;/strong&gt; has been introduced since C# 4.0. It's a nice feature indeed. Let's say we wanted to create a Html Helper method that can generate a Html markup of a link by providing the inner Html, controller and action name. The method would look like:

&lt;strong&gt;HtmlLink(string innerHtml, string action, stirng controller)&lt;/strong&gt;

Definetily, there would be a requirement to provide a routeValue object to make the link in some cases like we want to have a link to edit a blog post, we would need something like:

&lt;strong&gt;HtmlLink("Edit post", "Edit", "Blog", new {id = 1000})&lt;/strong&gt;

Before C# 4.0, we had to create another overload for the above method. But with optional parameter we can easily archive this by adding the routeValue param as optional:

&lt;strong&gt;HtmlLink(string innerHtml, string action, string controller, object routeValue = null)&lt;/strong&gt;

Cool, but the requirement would have a small change. We wanted to provide a css class name for the link so we had to change the method again:

&lt;strong&gt;HtmlLink(string innerHtml, string action, string controller, object routeValue = null, object htmlAttribute = null)&lt;/strong&gt;

Hmmm, It's becoming more complicated but still okey because "everything is working fine" and "there is nothing wrong with it". Believe me, there are 2 common sentences that I hear everyday. Some days later, a guy in our team felt like it's time to make the method more handy by providing another optional parameter for area name. He wanted to make the change quickly without affecting the existing codes that have been using this method. So the method would be modified again:

&lt;strong&gt;HtmlLink(string innerHtml, string action, string controller, string area = null, object routeValue = null, object htmlAttribute = null)&lt;/strong&gt;

Now, It's really a problem. The method had too many optional parameters. So when you want to use default area as null and provide route value object and htmlAttribute, then you have to use named arguments when call this method:

&lt;strong&gt;HtmlLink("Edit post", "Edit", "Blog", routeValue: new {id = 1000}, htmlAttribute: new {@class = "edit-post"})&lt;/strong&gt;

Given that we would use this powerful method to generate the links for some menu items. And there was a new requirement like if current page comes from the "menu item A" then this menu item should have css class "active". A guy who implemented that change could make this method even more "powerful" by adding another optional parameter:

&lt;strong&gt;HtmlLink(string innerHtml, string action, string controller, string area = null, object routeValue = null, object htmlAttribute = null, bool isActive = false)&lt;/strong&gt;

It's not difficult to realize that this method's signature is so complicated due to the  amount of parameters. It was cool at the first time but rapidly becomes ugly when being added more parameters. You would easily meet this kind of sittuation when you were in a team of many developers because there must be a time people want to have something done as quick as possible without thinking about clean code. I think optional parameter is good as soon as we use it in the reasonable way. For me, one optional parameter in a method is enough and 3 parameters should be the maximum of parameters in any methods. If we need more parameters, it's time to think about a DTO class.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-7032784337225247943?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/RTzyR4osXtY" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-04-19T22:49:40.696+10:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/04/optional-parameter-is-ugly.html</feedburner:origLink></item><item><title>How to mock the MVC View Engine</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/_ol_qq05dY8/test-mock-mvc-view-engine.html</link><category>UnitTest</category><category>Mock</category><category>MVC</category><category>NSubstitute</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Tue, 19 Apr 2011 06:08:24 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-405615622132300564</guid><description>Let's say we've created an HtmlHelper extension method to render a partial view without a need to provide a partial view name based on the type or template hint of a view model.
The helper would look like:

&lt;pre class="brush: csharp"&gt;public static void DisplayModel(this HtmlHelper htmlHelper, object model)
{
    var type = model.GetType();
    var modelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, type);
    if (string.IsNullOrEmpty(modelMetadata.TemplateHint))
    {
        htmlHelper.RenderPartial("DisplayTemplates/" + modelMetadata.ModelType.Name, model);
    }
    else
    {
        htmlHelper.RenderPartial("DisplayTemplates/" + modelMetadata.TemplateHint, model);
    }
}&lt;/pre&gt;

This method is quite simple. It employs the built-in extension method of HtmlHelper: RenderPartial(). If you read the MVC source code, you will find that this method requires the ViewEngines to find the provided viewName and return a viewEngineResult. Then the viewEngineResult will be used to render the View content to Html. So it's quite complicated to test something that requires a ViewEngine behind the scene.

I fell into this sittuation when i tried to test my extension methods (I attempt to raise the coverage for our team unit tests, started by writing unit tests for all the shits I made before.). After digging into the MVC source code, I think I need to replace the default view engines in ViewEngine.Engines collection by a mocked ViewEngine. Here is the implementation:

&lt;pre class="brush: csharp"&gt;public static ViewEngineResult SetupViewContent(string viewName, string viewHtmlContent)
{
    var mockedViewEngine = Substitute.For&amp;lt;IViewEngine&amp;gt;();
    var resultView = Substitute.For&amp;lt;IView&amp;gt;();
    resultView.When(x =&amp;gt; x.Render(Arg.Any&amp;lt;ViewContext&amp;gt;(), Arg.Any&amp;lt;TextWriter&amp;gt;())).Do(c =&amp;gt;
    {
        var textWriter = c.Arg&amp;lt;TextWriter&amp;gt;();
        textWriter.Write(viewHtmlContent);
    });
    var viewEngineResult = new ViewEngineResult(resultView, mockedViewEngine);

    mockedViewEngine.FindPartialView(Arg.Any&amp;lt;ControllerContext&amp;gt;(), viewName,  Arg.Any&amp;lt;bool&amp;gt;()).Returns(viewEngineResult);
    mockedViewEngine.FindView(Arg.Any&amp;lt;ControllerContext&amp;gt;(), viewName, Arg.Any&amp;lt;string&amp;gt;(), Arg.Any&amp;lt;bool&amp;gt;()).Returns(viewEngineResult);

    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(mockedViewEngine);
    return viewEngineResult;
}&lt;/pre&gt;

As i said in my previous posts, I'm using &lt;a href="http://thoai-nguyen.blogspot.com/search/label/NSubstitute"&gt;NSubstitute&lt;/a&gt; as my primary mock framework due to it's simplicity and easy to use. To setup all the things for my test, I'll create a mock for the &lt;em&gt;IView&lt;/em&gt; which will be used to initialize the &lt;em&gt;ViewEngineResult&lt;/em&gt;. And the ViewEngineResult will be the output for our mocked &lt;em&gt;IViewEngine&lt;/em&gt; when it's method &lt;em&gt;FindView&lt;/em&gt; or &lt;em&gt;FindPartialView&lt;/em&gt; is executed. The most interesting point to do these stuff is that the default viewEngine collection in MVC3 has 2 item which are Aspx view engine and razor view engine. Therefore, to make our mocked view engine to be able to work, we need to clear these 2 default view engines and insert our mocked view engine. That's it.

Here is one of the tests:

&lt;pre class="brush: csharp"&gt;[TestMethod]
public void Can_use_a_model_type_as_partial_view_name_and_display_model_with_provided_view_model()
{
    // Arrange
    var builder = MvcTestControllerBuilder.GetDefaultBuilder();
    var htmlHelper = builder.GetHtmlHelper();
    htmlHelper.ViewContext.Writer = Substitute.For&amp;lt;StringWriter&amp;gt;();
    MvcTestFixtureHelper.SetupViewContent("DisplayTemplates/ProfileViewModel", "ProfileViewModel Content");

    // Action
    htmlHelper.DisplayModel(new ProfileViewModel());

    // Assert
    htmlHelper.ViewContext.Writer.Received().Write("ProfileViewModel Content");
}&lt;/pre&gt;

Please refer to &lt;a href="http://thoai-nguyen.blogspot.com/2011/02/mvc-test-controller-builder-and.html"&gt;this post&lt;/a&gt; about &lt;a href="http://thoai-nguyen.blogspot.com/2011/02/mvc-test-controller-builder-and.html"&gt;MvcTestControllerBuilder&lt;/a&gt;.
Cheers.


&lt;script language="javascript" type="text/javascript"&gt;SyntaxHighlighter.config.TypeNames = "EventController MvcTestControllerBuilder Substitute ViewEngines StringWriter MvcTestFixtureHelper ProfileViewModel ViewEngineResult IView IViewEngine Arg TextWriter ViewContext ControllerContext ModelMetadataProviders";&lt;/script&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-405615622132300564?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/_ol_qq05dY8" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-04-19T23:08:24.624+10:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/04/test-mock-mvc-view-engine.html</feedburner:origLink></item><item><title>What is the best unit test naming convention?</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/XymZxss1g70/unit-test-naming-convention.html</link><category>UnitTest</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Fri, 08 Apr 2011 18:20:23 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-8822324757876991858</guid><description>I'm not good at namming actually because I'm not an English native speaker.
So I tried many best practices about naming the test methods and I met a few interesting strategies:

- &lt;a href="http://blog.stevensanderson.com/2009/08/24/writing-great-unit-tests-best-and-worst-practises/"&gt;[Subject_Scenario_Result]&lt;/a&gt; 

or 

- &lt;a href="http://osherove.com/blog/2005/4/3/naming-standards-for-unit-tests.html"&gt;[MethodName_StateUnderTest_ExpectedBehavior]&lt;/a&gt;

And i found a very interesting way at:

http://stevesmithblog.com/blog/unit-test-naming-convention/

For me I think those methods both have pros and cons. For the first one, in some complicated scenarios, my method name would look like:

&lt;strong&gt;Edit_IfIdIsEmpty_ShouldCreateOrganisationAndReturnRedirectToRouteResult&lt;/strong&gt;

Sometime, when I want to write the expected behavior before the senario, I would write the name like:

&lt;strong&gt;Edit_ShouldCreateOrganisationAndReturnRedirectToRouteResult_IfIdIsEmpty&lt;/strong&gt;

And time goes by, I have a lot of different styles of names and believe me, some of the names are very funny.

I like ideas of the second method. When you run all your tests in the solution, the test result list will look beautiful and meanningful. But like the first method, in some complicated scenarioes, the name would be long and personally, I think it's hard to read and I'm not happy with the way he names the test class and test methods. Why don't we combine these methods and use this way:

- Class name : &lt;em&gt;ClassNameTests&lt;/em&gt;
- Method name: &lt;em&gt;Any_sentence_or_phrase_that_can_describe_the_intention_of_unit_test&lt;/em&gt;

For example:

&lt;strong&gt;BusinessServiceTests&lt;/strong&gt;
- Search_business_by_keyword_and_location_should_return_result_with_full_information

&lt;strong&gt;UploadControllerTests&lt;/strong&gt;
- Should_throw_security_exception_if_file_type_is_not_supported

I think using this way, we have the freedom of naming but still can provide the full intention of the unit test and the method name is very easy to read. 


Have a better idea? Please share it :D.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-8822324757876991858?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/XymZxss1g70" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-04-09T11:20:23.999+10:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/04/unit-test-naming-convention.html</feedburner:origLink></item><item><title>Turn on Compile-time View Checking for ASP.NET MVC Projects for DEBUG only</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/lx44pFcY9Hs/compile-time-view-checking-mvc-debug.html</link><category>MVC</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Fri, 08 Apr 2011 18:15:28 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-1160560354552020756</guid><description>I wrote a post about &lt;a href="/2011/03/compile-time-view-checking-mvc.html" target="_blank"&gt;"Turn on Compile-time View Checking for ASP.NET MVC Projects"&lt;/a&gt;
Today, we got a annoying problem with it. Our team have a gate checkin in TFS. Basically, it will build the solution when someone checks in code and if it builds successfully as well as all tests pass, the checkin will be approved. Some dude in our team did some code mergings and then checked in with so many errors on View files so we got serveral complains from the testers when they tested those pages. I expected my changes in the project configuration would not effect these builds on TFS because the MvcBuildViews would only be ignored on DEBUG configuration. And I also made an assumtion that the GateCheckin build on TFS didn't use DEBUG configuration but it did indeed. Actually, the GateCheckin was setup long time ago by someone and it was not set to choose a build configuration. So if you look in the top of the project file, you will see that if there is no configuration setup, the DEBUG will be default:

&lt;pre class="brush: xml"&gt;&amp;lt;Configuration Condition=" '$(Configuration)' == '' "&amp;gt;Debug&amp;lt;/Configuration&amp;gt;
&amp;lt;Platform Condition=" '$(Platform)' == '' "&amp;gt;AnyCPU&amp;lt;/Platform&amp;gt;&lt;/pre&gt;

We raised this issue to the IT guy, just asked him to set the default build configuration for the GateCheckin because we don't have enough permission to change that. But there are not any responses... for some reasons :D. So I decided to cheat the build server myself.

I change the line in the project configuration to something like:

&lt;pre class="brush: xml"&gt;&amp;lt;MvcBuildViews Condition=" '$(MvcBuildViews)' == '' Or '$(Configuration)' != 'Debug' "&amp;gt;true&amp;lt;/MvcBuildViews&amp;gt;&lt;/pre&gt;


The MSBUILD can get the property value from &lt;em&gt;Environment Variables&lt;/em&gt;. That's how i cheat the build. The build server will never have &lt;strong&gt;MvcBuildViews&lt;/strong&gt; in it's Environment Variables so it will have MvcBuildViews set to "true" always. In developer machines, we setup a system variable MvcBuildViews and set to false.

&lt;img src="http://img219.imageshack.us/img219/9798/uservariable.png" /&gt;

This step will help skipping the view compilation while debugging, switch to Release or something else to compile the views when you want. Please note that it's neccessary to logoff then login or just restart the PC to make the environment variable take effect.

Cheers&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-1160560354552020756?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/lx44pFcY9Hs" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-04-09T11:15:28.473+10:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/04/compile-time-view-checking-mvc-debug.html</feedburner:origLink></item><item><title>Write unit test for a method depends on RoleProvider</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/2CbqMO-DdkY/unit-test-mock-roleprovider-nsubstitute.html</link><category>UnitTest</category><category>Mock</category><category>NSubstitute</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Sat, 19 Mar 2011 20:14:04 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-3945932482610527448</guid><description>Let's say I have a class like this:

&lt;pre class="brush: csharp; highlight: [12]"&gt;public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        return string.IsNullOrEmpty(Roles) 
            ? base.AuthorizeCore(httpContext) 
            : IsUserInRole(Roles);
    }

    public static bool IsUserInRole(string roles)
    {
        return roles.Split(',', ';').Any(x =&amp;gt; System.Web.Security.Roles.IsUserInRole(x.Trim()));
    }
}&lt;/pre&gt;

This class is a very simple class that depends on a &lt;strong&gt;RoleProvider&lt;/strong&gt; to check whether current user is in one of demanded roles. 

The question is what I'm suppose to test this class? 
Hmmm, the &lt;strong&gt;System.Web.Security.Roles&lt;/strong&gt; class has a Providers collection of RoleProvider but it's readonly as well as the property Provider which should be default provider. It looks like there is only one way to put my mock/fake role provider is placing it into configuration file of the Test project.

Currently, I'm interested in using NSubstitue as the mocking framework, but I think the following TestRoleProvider can be easily changed to use other mock library like RhinoMock or Moq. Here is my very simple TestRoleProvider that can be configed in the App.config and later on arrange our "Expectation" on it:

&lt;pre class="brush: csharp;"&gt;public class TestRoleProvider : RoleProvider
{
    private readonly RoleProvider _roleProvider;
    public TestRoleProvider(RoleProvider provider)
    {
        _roleProvider = provider;
    }

    public TestRoleProvider()
    {
        _roleProvider = Substitute.For&amp;lt;RoleProvider&amp;gt;();
    }

    public override void AddUsersToRoles(string[] usernames, string[] roleNames)
    {
        RoleProvider.AddUsersToRoles(usernames, roleNames);
    }

    public override string ApplicationName
    {
        get { return RoleProvider.ApplicationName; }
        set { RoleProvider.ApplicationName = value; }
    }

    public RoleProvider RoleProvider
    {
        get { return _roleProvider; }
    }

    public override void CreateRole(string roleName)
    {
        RoleProvider.CreateRole(roleName);
    }

    public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
    {
        return RoleProvider.DeleteRole(roleName, throwOnPopulatedRole);
    }

    public override string[] FindUsersInRole(string roleName, string usernameToMatch)
    {
        return RoleProvider.FindUsersInRole(roleName, usernameToMatch);
    }

    public override string[] GetAllRoles()
    {
        return RoleProvider.GetAllRoles();
    }

    public override string[] GetRolesForUser(string username)
    {
        return RoleProvider.GetRolesForUser(username);
    }

    public override string[] GetUsersInRole(string roleName)
    {
        return RoleProvider.GetUsersInRole(roleName);
    }

    public override bool IsUserInRole(string username, string roleName)
    {
        return _roleProvider.IsUserInRole(username, roleName);
    }

    public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
    {
        RoleProvider.RemoveUsersFromRoles(usernames, roleNames);
    }

    public override bool RoleExists(string roleName)
    {
        return RoleProvider.RoleExists(roleName);
    }
}&lt;/pre&gt;

And here is the configuration in App.config to make the test project use this TestRoleProvider as default RoleProvider:
&lt;pre class="brush: xml; highlight: [6]"&gt;&amp;lt;?xml version="1.0" encoding="utf-8" ?&amp;gt;
&amp;lt;configuration&amp;gt;
  &amp;lt;system.web&amp;gt;
    &amp;lt;roleManager enabled="true" defaultProvider="TestRoleProvider"&amp;gt;
      &amp;lt;providers&amp;gt;
        &amp;lt;add name="TestRoleProvider" type="MyCompany.MyProject.Tests.TestRoleProvider, MyCompany.MyProject.Tests"/&amp;gt;
        &amp;lt;!-- 
            Note: Change the namespace, assembly name to the assembly you put TestRoleProvider.
        --&amp;gt;
      &amp;lt;/providers&amp;gt;
    &amp;lt;/roleManager&amp;gt;
  &amp;lt;/system.web&amp;gt;
&amp;lt;/configuration&amp;gt;&lt;/pre&gt;
Now, I will write a simple unit test for method CustomAuthorizeAttribute.IsUserInRole(roles):

&lt;pre class="brush: csharp; highlight: [10]"&gt;[TestMethod]
public void Can_Check_User_Roles_Using_Role_Provider()
{
    // Arrange
    var testRoleProvider = Roles.Provider as TestRoleProvider;
    if (testRoleProvider == null)
    {
        throw new Exception("TestRoleProvider must be configed in app.config as default provider for your unit tests");
    }
    testRoleProvider.RoleProvider.IsUserInRole(Arg.Any&amp;lt;string&amp;gt;(), Arg.Any&amp;lt;string&amp;gt;()).Returns(true);
            
    // Action
    var result = CustomAuthorizeAttribute.UserInRole("Admin, Mod");

    // Assert
    Assert.AreEqual(true, result);
}&lt;/pre&gt;
And here the result after running above unit test:

&lt;img class="fancybox" src="http://pblycq.blu.livefilestore.com/y1p9IuxaWzfh2Oy0GjLIBZQ23mouSJssuMB1d_JymgnK-1TYiargnO2zg8bOdEDUGpdPn393cfLkLB6lGMeSksBLvEqXvVuEZhH/TestFailed.png" alt="TestFailed" /&gt;


Look like something's wrong. I swear I had setup the provider correctly in App.config. The Test ran failed and that means "testRoleProvider" is not null because I did not receive any exception. Maybe there are some secrets inside the implementation of &lt;strong&gt;System.Web.Security.Roles&lt;/strong&gt;. Fine, I will find out what they are. It's time to use the power of Reflector but let's download it first. Hmm, newest version is 7 and it has not been free anymore. Ok, I will use previous free version, let's show some googling skill.

Hehe, I found some old web addresses that allow me to download Reflector 5.x. Arggg, It forced me to upgrade to 7.0, I chose not to upgrade and It deleted the reflector executable file.
All I need is to see the code inside Roles, so free 14 days trial is enough for me :(.

And here is the secret:

&lt;pre class="brush: csharp; highlight: [19,26]"&gt;public static bool IsUserInRole(string username, string roleName)
{
    bool flag3;
    if (HostingEnvironment.IsHosted &amp;&amp; EtwTrace.IsTraceEnabled(4, 8))
    {
        EtwTrace.Trace(EtwTraceType.ETW_TYPE_ROLE_BEGIN, HttpContext.Current.WorkerRequest);
    }
    EnsureEnabled();
    bool flag = false;
    bool flag2 = false;
    try
    {
        SecUtility.CheckParameter(ref roleName, true, true, true, 0, "roleName");
        SecUtility.CheckParameter(ref username, true, false, true, 0, "username");
        if (username.Length &amp;lt; 1)
        {
            return false;
        }
        IPrincipal currentUser = GetCurrentUser();
        if (((currentUser != null) &amp;&amp; (currentUser is RolePrincipal)) &amp;&amp; ((((RolePrincipal) currentUser).ProviderName == Provider.Name) &amp;&amp; StringUtil.EqualsIgnoreCase(username, currentUser.Identity.Name)))
        {
            flag = currentUser.IsInRole(roleName);
        }
        else
        {
            flag = Provider.IsUserInRole(username, roleName);
        }
        flag3 = flag;
    }
    finally
    {
        if (HostingEnvironment.IsHosted &amp;&amp; EtwTrace.IsTraceEnabled(4, 8))
        {
            if (EtwTrace.IsTraceEnabled(5, 8))
            {
                string str = SR.Resources.GetString(flag ? "Etw_Success" : "Etw_Failure", CultureInfo.InstalledUICulture);
                EtwTrace.Trace(EtwTraceType.ETW_TYPE_ROLE_IS_USER_IN_ROLE, HttpContext.Current.WorkerRequest, flag2 ? "RolePrincipal" : Provider.GetType().FullName, username, roleName, str);
            }
            EtwTrace.Trace(EtwTraceType.ETW_TYPE_ROLE_END, HttpContext.Current.WorkerRequest, flag2 ? "RolePrincipal" : Provider.GetType().FullName, username);
        }
    }
    return flag3;
}&lt;/pre&gt;
And this is the way it gets current user:

&lt;pre class="brush: csharp; highlight: [11]"&gt;private static IPrincipal GetCurrentUser()
{
    if (HostingEnvironment.IsHosted)
    {
        HttpContext current = HttpContext.Current;
        if (current != null)
        {
            return current.User;
        }
    }
    return Thread.CurrentPrincipal;
}&lt;/pre&gt;

Okey, i have enough information to let the test use my roleprovider. It's quite complicated to modify &lt;em&gt;HostingEnvironment.IsHosted&lt;/em&gt; as well as &lt;em&gt;HttpContext.Current&lt;/em&gt;. Indeed, I can create a mock httpContext and set the mock object to &lt;em&gt;HttpContext.Current&lt;/em&gt; but I think changing &lt;em&gt;CurrentPrincipal&lt;/em&gt; of current Thread is more simple. So, I decided to change my unit test arrangement:

&lt;pre class="brush: csharp;"&gt;[TestMethod]
public void Can_Check_User_Roles_Using_Role_Provider()
{
    // Arrange
    var identity = Substitute.For&amp;lt;IIdentity&amp;gt;();
    identity.IsAuthenticated.Returns(true);
    identity.Name.Returns("AnyUsername");

    var principal = Substitute.For&amp;lt;IPrincipal&amp;gt;();
    principal.Identity.Returns(identity);
    Thread.CurrentPrincipal = principal;

    var testRoleProvider = Roles.Provider as TestRoleProvider;
    if (testRoleProvider == null)
    {
        throw new Exception("TestRoleProvider must be configed in app.config as default provider for your unit tests");
    }
    testRoleProvider.RoleProvider.IsUserInRole(Arg.Any&amp;lt;string&amp;gt;(), Arg.Any&amp;lt;string&amp;gt;()).Returns(true);

    
    // Action
    var result = CustomAuthorizeAttribute.IsUserInRole("Admin, Mod");


    // Assert
    Assert.AreEqual(true, result);
}&lt;/pre&gt;
Hoho, finally It passed. Reflector is so useful, isn't it? 

I think we can do the same way if we want to test any implementations that need &lt;strong&gt;MembershipProvider&lt;/strong&gt; or &lt;strong&gt;ProfileProvider&lt;/strong&gt;. I would move the Principal Arrangement into a public static method of TestRoleProvider to make it reusable. And because I changed the Thread.CurrentPrincipal during the test, so it could be nice if we make a test initialize and test cleanup to backup/restore current principle.But I let you to do those stuff if you're interested in :D

Cheers.
&lt;script language="javascript" type="text/javascript"&gt;SyntaxHighlighter.config.TypeNames = "AuthorizeAttribute CustomAuthorizeAttribute HttpContextBase TestMethod TestRoleProvider RoleProvider Exception Arg Assert HostingEnvironment EtwTrace SecUtility RolePrincipal StringUtil IPrincipal HttpContext Thread Substitute";&lt;/script&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-3945932482610527448?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/2CbqMO-DdkY" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-03-20T14:14:04.727+11:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">0</thr:total><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/03/unit-test-mock-roleprovider-nsubstitute.html</feedburner:origLink></item><item><title>Turn on Compile-time View Checking for ASP.NET MVC Projects</title><link>http://feedproxy.google.com/~r/thoainguyen/~3/7izcw-P4tzs/compile-time-view-checking-mvc.html</link><category>UnitTest</category><category>MVC</category><author>noreply@blogger.com (vantheshark)</author><pubDate>Wed, 16 Mar 2011 03:36:36 PDT</pubDate><guid isPermaLink="false">tag:blogger.com,1999:blog-6734369634474697600.post-69336151277670569</guid><description>You can make the web project perform compile time checking of the markup in the views by modifying the .csproj file and turning on the "&lt;span style="font-weight:bold;"&gt;MvcBuildViews&lt;/span&gt;" property.

The advantage of this is that you will know at compile time any problem with a view,  not at run time when someone accesses that page. So please follow the below blog to do that:

http://blogs.msdn.com/b/jimlamb/archive/2010/04/20/turn-on-compile-time-view-checking-for-asp-net-mvc-projects-in-tfs-build-2010.aspx

However, doing in this will make the compilation is extremely slower. It made me crazy every time I want to debug a unit test because it build the solution include the views and It could take 1 minutes before starting the test debug.

To overcome that, I turn off &lt;span style="font-weight:bold;"&gt;MvcBuildViews &lt;/span&gt;for Debug compilation of the solution. To do this, open the web .csproj file by any text editor, find 

&lt;em&gt;&amp;lt;PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "&amp;gt;&lt;/em&gt;

then add &lt;em&gt;&amp;lt;MvcBuildViews&amp;gt;false&amp;lt;/MvcBuildViews&amp;gt;&lt;/em&gt; under it. It will simply overwrite the default setting which was set to true for DEBUG configuration.


&lt;pre class="brush: xml; highlight: [2]"&gt;&amp;lt;PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "&amp;gt;
    &amp;lt;MvcBuildViews&amp;gt;false&amp;lt;/MvcBuildViews&amp;gt;
    &amp;lt;DebugSymbols&amp;gt;true&amp;lt;/DebugSymbols&amp;gt;
    &amp;lt;DebugType&amp;gt;full&amp;lt;/DebugType&amp;gt;
    &amp;lt;Optimize&amp;gt;false&amp;lt;/Optimize&amp;gt;
    &amp;lt;OutputPath&amp;gt;bin\&amp;lt;/OutputPath&amp;gt;
    &amp;lt;DefineConstants&amp;gt;DEBUG;TRACE&amp;lt;/DefineConstants&amp;gt;
    &amp;lt;ErrorReport&amp;gt;prompt&amp;lt;/ErrorReport&amp;gt;
    &amp;lt;WarningLevel&amp;gt;4&amp;lt;/WarningLevel&amp;gt;
&amp;lt;/PropertyGroup&amp;gt;&lt;/pre&gt;


Cheers&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/6734369634474697600-69336151277670569?l=thoai-nguyen.blogspot.com' alt='' /&gt;&lt;/div&gt;&lt;img src="http://feeds.feedburner.com/~r/thoainguyen/~4/7izcw-P4tzs" height="1" width="1"/&gt;</description><app:edited xmlns:app="http://www.w3.org/2007/app">2011-03-16T21:36:36.472+11:00</app:edited><thr:total xmlns:thr="http://purl.org/syndication/thread/1.0">3</thr:total><feedburner:origLink>http://thoai-nguyen.blogspot.com/2011/03/compile-time-view-checking-mvc.html</feedburner:origLink></item><media:rating>nonadult</media:rating></channel></rss>

