<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Marc Dormey</title>
	<atom:link href="http://www.marcdormey.com/index.php/feed" rel="self" type="application/rss+xml" />
	<link>http://www.marcdormey.com</link>
	<description>Bespoke Software Solutions in C#.Net, ASP.Net MVC, JQuery, MEF and more</description>
	<lastBuildDate>Thu, 25 Feb 2010 23:21:13 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Creating a custom ValueType and Serialising with a custom JsonResult</title>
		<link>http://www.marcdormey.com/index.php/archives/300</link>
		<comments>http://www.marcdormey.com/index.php/archives/300#comments</comments>
		<pubDate>Thu, 25 Feb 2010 23:21:13 +0000</pubDate>
		<dc:creator>Marcel</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[IPhone]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[asp.net mvc]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[custom valuetype]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[struct]]></category>
		<category><![CDATA[system.valuetype]]></category>
		<category><![CDATA[valuetype]]></category>

		<guid isPermaLink="false">http://www.marcdormey.com/?p=300</guid>
		<description><![CDATA[When trying to serialise your model into Json you would notice the ugly way that the Microsoft JavaScriptserializer outputs dates. ie. {&#8221;d&#8221;:&#8221;\/Date(1240718400000)\/&#8221;} 
This might not be a problem when you are using JQuery or Javascript, but what if your consumer is, say, an IPhone or another device? Wouldn&#8217;t you rather stick to a platform independent [...]]]></description>
			<content:encoded><![CDATA[<p>When trying to serialise your model into Json you would notice the ugly way that the Microsoft JavaScriptserializer outputs dates. ie. {&#8221;d&#8221;:&#8221;\/Date(1240718400000)\/&#8221;} </p>
<p>This might not be a problem when you are using JQuery or Javascript, but what if your consumer is, say, an IPhone or another device? Wouldn&#8217;t you rather stick to a platform independent and recognised format?</p>
<p>The steps below might be a bit too drastic for your implementations, but follow them and you might also learn how to create your own ValueType and CustomJsonSerialiser all in one go!</p>
<p>This is what we want to accomplish. We only needed to give one converter to our CustomConverterJsonResult, but you could make this a list or even a configuration/ioc injection.</p>
<pre class="brush:csharp"> public ActionResult Index(int? id)
 {
      return new CustomConverterJsonResult (new UnixDateTimeConverter(), _repository.GetPerson(id));
 }</pre>
<p>Below is our custom ValueType. This allows you to do the following:</p>
<pre class="brush:csharp">
UnixDateTime uDateTime = DateTime.Now;
//OR
DateTime dateTime = uDateTime;
//OR > < => and even casting between them
</pre>
<pre class="brush:csharp">public struct UnixDateTime : IComparable
{
    private static DateTime _baseDateTime = new DateTime(1970, 1, 1, 0, 0, 0);
    private readonly long _epochSeconds;

    public UnixDateTime(DateTime dateTime)
    {
       _epochSeconds = ConvertToUnixEpochSeconds(dateTime) ?? 0;
    }

    public UnixDateTime(long epochSeconds)
    {
       _epochSeconds = epochSeconds;
    }

    public override bool Equals(object obj)
    {
       if (!obj.GetType().IsAssignableFrom(typeof(UnixDateTime)))
          return false;
       return ((UnixDateTime)obj)._epochSeconds.Equals(_epochSeconds);
    }

    public bool Equals(UnixDateTime other)
    {
       return other._epochSeconds.Equals(_epochSeconds);
    }

    public override int GetHashCode()
    {
       return _epochSeconds.GetHashCode();
    }

    public int CompareTo(object obj)
    {
       return _epochSeconds.CompareTo(((UnixDateTime) obj)._epochSeconds);
    }

    public override string ToString()
    {
       return _epochSeconds.ToString();
    }

    public static bool operator &gt;(UnixDateTime source, UnixDateTime target)
    {
       return source._epochSeconds &gt; target._epochSeconds;
    }

    public static bool operator &lt;(UnixDateTime source, UnixDateTime target)
    {
       return source._epochSeconds &lt; target._epochSeconds;
    }

    public static bool operator ==(UnixDateTime source, UnixDateTime target)
    {
       return source._epochSeconds == target._epochSeconds;
    }

    public static bool operator !=(UnixDateTime source, UnixDateTime target)
    {
       return source._epochSeconds != target._epochSeconds;
    }

    public static implicit operator UnixDateTime(DateTime dateTime)
    {
       return new UnixDateTime(dateTime);
    }

    public static implicit operator UnixDateTime(long value)
    {
       return new UnixDateTime(value);
    }

    public DateTime? ToDateTime()
    {
       return ConvertFromUnixEpochSeconds(_epochSeconds);
    }

    private static long? ConvertToUnixEpochSeconds(DateTime? date)
    {
       if (!date.HasValue)
          return null;

       return (long)((DateTime)date - _baseDateTime).TotalSeconds;
    }

    private static DateTime? ConvertFromUnixEpochSeconds(long? seconds)
    {
       if (!seconds.HasValue)
          return null;

       return _baseDateTime.AddSeconds(seconds.Value);
    }
}</pre>
<p>We then need a CustomConverterJsonResult. The reason for this is to inject the converters needed (no support for this in the normal JsonResult).</p>
<pre class="brush:csharp">public class CustomConverterJsonResult : JsonResult
{
    private readonly JavaScriptConverter _customConverter;

    public CustomConverterJsonResult(JavaScriptConverter customConverter, object data)
    {
       _customConverter = customConverter;
       Data = data;
    }

    public override void ExecuteResult(ControllerContext context)
    {
       if (context == null)
          throw new ArgumentNullException("context");

       HttpResponseBase response = context.HttpContext.Response;

       response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json";

       if (ContentEncoding != null)
          response.ContentEncoding = ContentEncoding;

       if (Data != null)
       {
          JavaScriptSerializer serializer = CreateJsonSerializer();
          response.Write(serializer.Serialize(Data));
       }
    }

    private JavaScriptSerializer CreateJsonSerializer()
    {
       var serializer = new JavaScriptSerializer();
       serializer.RegisterConverters(new []{_customConverter});
       return serializer;
    }
}</pre>
<p>And finally&#8230; the JavascriptConverter.</p>
<pre class="brush:csharp">   public class UnixDateTimeConverter : JavaScriptConverter
   {
       public override object Deserialize(IDictionary&lt;string, object&gt; dictionary, Type type,    JavaScriptSerializer serializer)
       {
          if(dictionary != null)
          {
             var stringValue = string.Empty + dictionary["UnixEpochSeconds"];
             if(string.IsNullOrEmpty(stringValue))
                return null;

             return new UnixDateTime(long.Parse(stringValue));
          }

          return null;
       }

       public override IDictionary&lt;string, object&gt; Serialize(object obj, JavaScriptSerializer serializer)
       {
          var result = new Dictionary&lt;string, object&gt; { { "UnixEpochSeconds", obj.ToString() } };
          return result;
       }

       public override IEnumerable&lt;Type&gt; SupportedTypes
       {
          get { return new ReadOnlyCollection&lt;Type&gt;(new List&lt;Type&gt;(new[] {     typeof(UnixDateTime), typeof(UnixDateTime?) })); }
       }
}</pre>
<p>This creates the following output:</p>
<pre class="brush:csharp">
{"Person":[{"Name":"John Doe","LastUpdated":[{"UnixEpochSeconds":"187653000"}]]}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.marcdormey.com/index.php/archives/300/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>NBouncer, my Context Aware Validation Framework</title>
		<link>http://www.marcdormey.com/index.php/archives/281</link>
		<comments>http://www.marcdormey.com/index.php/archives/281#comments</comments>
		<pubDate>Thu, 12 Nov 2009 12:12:24 +0000</pubDate>
		<dc:creator>Marcel</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Misc]]></category>
		<category><![CDATA[asp.net mvc]]></category>
		<category><![CDATA[aspnet]]></category>
		<category><![CDATA[context aware]]></category>
		<category><![CDATA[validation]]></category>

		<guid isPermaLink="false">http://www.marcdormey.com/?p=281</guid>
		<description><![CDATA[For most people out there using the current Validation Frameworks (DataAnnotations, Nhibernate Validation) are more than enough. But for some, like me, I need mine to be &#8220;Context Aware&#8221;.
What do I mean with &#8220;Context Aware&#8221;? Well lets say, for instance, that you are phoning your bank for an insurance policy. The first thing they need [...]]]></description>
			<content:encoded><![CDATA[<p>For most people out there using the current Validation Frameworks (DataAnnotations, Nhibernate Validation) are more than enough. But for some, like me, I need mine to be &#8220;Context Aware&#8221;.</p>
<p>What do I mean with &#8220;Context Aware&#8221;? Well lets say, for instance, that you are phoning your bank for an insurance policy. The first thing they need is to obtain just enough info to get you in their database so that they can take the application further. Once they have you, then they forward the application where underwriting, risk calculation etc can take place. So the application goes through quite a few states. We could say it has a preliminary, draft, final etc&#8230; state at each given moment. The validation and business rules might be completely different depending on what state the agreement is in.</p>
<p>Three more requirements had to be satisfied before I started to plan a prototype.</p>
<p>1. Needs to be VERY simple to use<br />
2. Needs to stay out of my POCO objects (no attributes!)<br />
3. Validation rules are just a subset of business rules. I want to be able to use the validation framework for complex business rules and simple validation and treat them as one layer.</p>
<p>After a few days <a href="http://nbouncer.codeplex.com/" target="_blank">NBouncer</a> was born. This is just a prototype and more feedback is needed to justify investing more time into. I know there are &#8220;Context Aware&#8221; rule frameworks out there, but I need mine to be VERY SIMPLE.</p>
<p>Enough rambling, lets see some code!</p>
<p>Lets say we have a Person object, an Agreement object and a Hobby object: (note how clean these are, this is how they will stay!)</p>
<pre class="brush:csharp">public class Person
{
	public string Name { get; set; }
	public int Age { get; set; }
	public IList&lt;Hobby&gt; Hobbies = new List&lt;Hobby&gt;();
}

public class Agreement
{
	public AgreementState State { get; set; }
}

public class Hobby
{
	public string Name { get; set; }
}</pre>
<p>The first example is to send a Warning message if the execution action is &#8220;Validate&#8221;, but to send an Error if the user is trying to &#8220;Persist&#8221; the person. The only thing we need to do is create a PersonRules class and set an attribute specifying it&#8217;s a &#8220;RuleProvider&#8221; for the &#8220;Person&#8221; class&#8230;</p>
<pre class="brush:csharp">[RuleProviderFor(typeof (Person))]
public class PersonRules : RuleProvider&lt;Person&gt;
{
	public PersonRules(RuleContext context)
		: base(context)
	{
	}

	protected override void RegisterRules()
	{
		CreateNameValidationRules();
	}

	private void CreateNameValidationRules()
	{
		switch (Context.ExecutionAction)
		{
			case ExecutionAction.Validate:
				RegisterRule(x =&gt; string.IsNullOrEmpty(x.Name),
							 CreateWarning(ErrorMessages.NameRequired, "Name"));
				break;
			case ExecutionAction.Persist:
				RegisterRule(x =&gt; string.IsNullOrEmpty(x.Name),
							 CreateError(ErrorMessages.NameRequired, "Name"));
				break;
		}
	}
}</pre>
<p>A more complicated example is when we have custom &#8220;Actions&#8221; and the rules are dependent of other classes&#8230;</p>
<pre class="brush:csharp">[RuleProviderFor(typeof (Person))]
public class PersonRules : RuleProvider&lt;Person&gt;
{
	public PersonRules(RuleContext context)
		: base(context)
	{
	}

	protected override void RegisterRules()
	{
		var data = Context.ResolveData&lt;Agreement&gt;();
		CreateNameValidationRules();
		CreateAgeValidationRules(data);
		CreateHobbyValidationRules(data);
	}

	private void CreateHobbyValidationRules(Agreement agreement)
	{
            if (Context.CustomAction == CustomActions.UnexpectedExit)
	        {
		      RegisterRule(x =&gt; x.Hobbies.Count == 0,
                       CreateError(ErrorMessages.HobbiesCannotBeEmpty, "Hobby"));
            }
            else
            {
                switch (Context.ExecutionAction)
                {
                    case ExecutionAction.Persist:
                        if (agreement.State == AgreementState.Draft)
                        {
                            RegisterRule(x =&gt; x.Hobbies.Count == 0,
                                         CreateWarning(ErrorMessages.HobbiesCannotBeEmpty, "Hobby"));
                        }
                        else if(agreement.State == AgreementState.Final)
                        {
                            RegisterRule(x =&gt; x.Hobbies.Count == 0,
                                         CreateError(ErrorMessages.HobbiesCannotBeEmpty, "Hobby"));
                        }
                        break;
                    case ExecutionAction.Release:
                        RegisterRule(x =&gt; x.Hobbies.Count == 0,
                                     CreateError(ErrorMessages.HobbiesCannotBeEmpty, "Hobby"));
                        break;
                }
            }
        }

        private void CreateAgeValidationRules(Agreement agreement)
        {
            switch (Context.ExecutionAction)
            {
                case ExecutionAction.Persist:
                    if (agreement.State == AgreementState.Draft)
                    {
                        RegisterRule(x =&gt; x.Age &lt; 18,
                               CreateWarning(ErrorMessages.AgeCannotBeLessThan18, "Age"));
                    }
                    else if(agreement.State == AgreementState.Final)
                    {
                        RegisterRule(x =&gt; x.Age &lt; 18,
                               CreateError(ErrorMessages.AgeCannotBeLessThan18, "Age"));
                    }
                break;
                case ExecuteAction.Validate:
                        RegisterRule(x =&gt; x.Age &lt; 18,
                               CreateWarning(ErrorMessages.AgeCannotBeLessThan18, "Age"));
                break;
            }
        }
    }</pre>
<p>The only thing left to do is to see how we validate&#8230;</p>
<pre class="brush:csharp">public ActionResult EditPerson(Person person)
{
    var agreement = new Agreement {State = AgreementState.Draft};
    var ruleContext = new RuleContext(ExecutionAction.Persist);
    ruleContext.RegisterData(agreement);

    var rules = person.GetRuleProvider(ruleContext);
    if(rules.Validate())
    {
       rules.ValidationResult.ForEach(x =&gt; ModelState.AddModelError(x.Message, x.TargetProperty);
       return View(person);
    }
    Service.CreateAgreement(person, agreement);
    return View(person);
}</pre>
<p>As I said before, this is just a prototype and feedback would be appreciated!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.marcdormey.com/index.php/archives/281/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Writing Facebook Apps with ASP.NET MVC, Silverlight, LINQ2Facebook and BDD</title>
		<link>http://www.marcdormey.com/index.php/archives/269</link>
		<comments>http://www.marcdormey.com/index.php/archives/269#comments</comments>
		<pubDate>Tue, 10 Nov 2009 11:19:19 +0000</pubDate>
		<dc:creator>Marcel</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Misc]]></category>
		<category><![CDATA[asp.net mvc]]></category>
		<category><![CDATA[bdd]]></category>
		<category><![CDATA[facebook]]></category>
		<category><![CDATA[linq2facebook]]></category>
		<category><![CDATA[silverlight]]></category>
		<category><![CDATA[storyq]]></category>

		<guid isPermaLink="false">http://www.marcdormey.com/?p=269</guid>
		<description><![CDATA[This weekend I looked into creating facebook applications from a .NET perspective. It turns out a quick search presents loads of support starting with the Facebook Developer Toolkit (Update: Just heard version 3 was released yesterday which gives silverlight and mvc support, wow what a coincidence?) and LINQ2Facebook (Fql).
I decided to do some research and [...]]]></description>
			<content:encoded><![CDATA[<p>This weekend I looked into creating facebook applications from a .NET perspective. It turns out a quick search presents loads of support starting with the <a href="http://wiki.developers.facebook.com/index.php/C" target="_blank">Facebook Developer Toolkit</a> (Update: Just heard version 3 was released yesterday which gives silverlight and mvc support, wow what a coincidence?) and <a href="http://www.codeproject.com/KB/aspnet/LinqToFqlAddon.aspx" target="_blank">LINQ2Facebook</a> (Fql).</p>
<p>I decided to do some research and ended up created a Facebook application framework using ASP.NET MVC, Silverlight, LINQ2Facebook. I also used <a href="http://www.codeplex.com/storyq" target="_blank">StoryQ</a> to POC their BDD framework and give the community a chance to see its power.</p>
<p>I have created a codeplex project with the source code here:</p>
<p><a href="http://facebookmvcbdd.codeplex.com/" target="_blank">Facebook MVC BDD Silverlight Framework</a></p>
<p>Source code sample:</p>
<pre class="brush:csharp">
public ActionResult Index()
{
	if (_service.TryAuthenticating())
	{
		user user = _service.GetCurrentUser();
		var silverlightViewModel = new SilverlightViewModel
									   {
										   ApplicatonName = "TestApp",
										   Width = "400",
										   Height = "400"
									   };

		silverlightViewModel.Params.Add("Name", user.name);
		silverlightViewModel.Params.Add("Picture", user.pic_big);

		return View(silverlightViewModel);
	}
	throw new AuthenticationException("Not allowed!");
}
</pre>
<pre class="brush:csharp">
[Test]
public void IndexActionShouldReturnViewModelWithCurrentLoggedInUser()
{
    var story = new Story("Index action should return a new silverlight view model");

    story.AsA("facebook application home page")
        .IWant("to receive a new silverlight view model")
        .SoThat("I can send it to the silverlight applicatioin")
        .WithScenario("Get silverlight view model")
        .Given(() => Steps.TheUserIsLoggedInWithUsername("Joe Blogs"))
        .When(() => Steps.TheUserEntersTheHomePage())
        .Then(() => Steps.EnsureTheCurrentLoggedInUserDetailsIsReceivedInTheViewModel());

    story.Assert();
}
</pre>
<p>producing output:</p>
<p>Story: Index action should return a new silverlight view model</p>
<p>  As a facebook application home page<br />
  I want to receive a new silverlight view model<br />
  So that I can send it to the silverlight applicatioin</p>
<p>  Scenario 1: Get silverlight view model<br />
    Given The user is logged in with username (Joe Blogs)                          Passed<br />
    When The user enters the home page                                             Passed<br />
    Then Ensure the current logged in user details is received in the view model   Passed</p>
]]></content:encoded>
			<wfw:commentRss>http://www.marcdormey.com/index.php/archives/269/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC JQuery ScriptManager</title>
		<link>http://www.marcdormey.com/index.php/archives/250</link>
		<comments>http://www.marcdormey.com/index.php/archives/250#comments</comments>
		<pubDate>Fri, 23 Oct 2009 11:19:54 +0000</pubDate>
		<dc:creator>Marcel</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Misc]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[asp.net mvc]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[scriptmanager]]></category>

		<guid isPermaLink="false">http://www.marcdormey.com/?p=250</guid>
		<description><![CDATA[As I was developing a CMS system for a client, we had a very unique scenario (well maybe not that unique) where we had custom &#8220;parts&#8221; which you could add to a page. The &#8220;parts&#8221; were highly customisable, thus you could have 3 instances of the same &#8220;part&#8221; on one page. The html and javascript [...]]]></description>
			<content:encoded><![CDATA[<p>As I was developing a CMS system for a client, we had a very unique scenario (well maybe not that unique) where we had custom &#8220;parts&#8221; which you could add to a page. The &#8220;parts&#8221; were highly customisable, thus you could have 3 instances of the same &#8220;part&#8221; on one page. The html and javascript rendered by the part would conflict with each other, because they had the same id&#8217;s and registered events.</p>
<p>I needed something similar to the old ASP.NET Script manager and the way that old ASP.NET used the &#8220;clientId&#8221; instead of the &#8220;htmlId&#8221; when dealing with html objects. The &#8220;clientId&#8221; was a generated unique key that prevented duplicated user controls conflicting with one another.</p>
<p>I found quite a few implementations of ScriptManager (<a href="http://pietschsoft.com/post/2009/08/13/Simple-ScriptManager-for-ASPNET-MVC.aspx">http://pietschsoft.com/post/2009/08/13/Simple-ScriptManager-for-ASPNET-MVC.aspx</a>, <a href="http://aspmvccombine.codeplex.com/">http://aspmvccombine.codeplex.com/</a>) for MVC, but none of them were solving my unique &#8220;htmlId&#8221; problem. If you are looking for a ScriptManager for MVC, then the two solutions I provided would be more than enough. If, however, you are in a similar situation as I am with the html controls, please read on&#8230;</p>
<p>I decided to combine knowledge obtained from the two ScriptManager implementations, and create my own light-weight solution addressing both problems.<br />
Because I wanted the usage of this to be very simple, I created a fluent interface which I can use in all my parts&#8230;</p>
<p>This is what the end result looks like:</p>
<pre class="brush:csharp">&lt;% Html.ScriptManager()
     .CreateClientScript(GetUniqueId())
       .AddParam("SelectId", GetUniqueId("selectList"))
       .AddParam("SourceUrl", Url.Action("Index", "Person"))
       .Ready(() =&gt; {%&gt;
            $.getJSON(params.SourceUrl, function(result) {
                $.populate_combobox(result, params.SelectId);
            });
      &lt;%});%&gt;

&lt;% Html.ScriptManager().AddStaticMethod("populate_combobox", () =&gt;{ %&gt;
    jQuery.populate_combobox = function(data, selectId) {
        $.each(data, function() {
            var option = new Option(this.text, this.value);
            var dropdownList = $(selectId)[0];
            if ($.browser.msie) {
                dropdownList.add(option);
            } else {
                dropdownList.add(option, null);
            }
        });
    }
&lt;%});%&gt;

&lt;div id="&lt;%=GetUniqueId() %&gt;_part"&gt;
 &lt;select id="&lt;%=GetUniqueId("selectList") %&gt;"&gt;&lt;/select&gt;
&lt;/div&gt;</pre>
<p>My &#8220;GetUniqueId()&#8221; function returns a combination of the PartId, PageId, but you can replace this with anything you fancy.<br />
The javascript that gets generated by this is:</p>
<pre class="brush:js">var ContentPart_AboutPage_82 = {
        Init: function(params) {
            $.getJSON(params.SourceUrl, function(result) {
                $.populate_combobox(result, params.SelectId);
            });
        }
}
var ContentPart_AboutPage_83 = {
        Init: function(params) {
            $.getJSON(params.SourceUrl, function(result) {
                $.populate_combobox(result, params.SelectId);
            });
       }
}
var ContentPart_AboutPage_84 = {
        Init: function(params) {
            $.getJSON(params.SourceUrl, function(result) {
                $.populate_combobox(result, params.SelectId);
            });
       }
}
$(document).ready(function() {
    ContentPart_AboutPage_82.Init({
       SelectId:'ContentPart_AboutPage_82_selectList',
       SourceUrl:'/Person'
    });
    ContentPart_AboutPage_83.Init({
       SelectId:'ContentPart_AboutPage_83_selectList',
       SourceUrl:'/Person'
    });
    ContentPart_AboutPage_84.Init({
       SelectId:'ContentPart_AboutPage_84_selectList',
       SourceUrl:'/Person'
    });
});

    jQuery.populate_combobox = function(data, selectId) {
        $.each(data, function() {
        var option = new Option(this.text, this.value);
        var dropdownList = $(selectId)[0];
        if ($.browser.msie) {
            dropdownList.add(option);
        } else {
            dropdownList.add(option, null);
        }
      });
    }</pre>
<p>Update: I have gone even further and added the concept of &#8220;SharedVariables&#8221; to the ScriptManager where the &#8220;SourceUrl&#8221; above and even the Json request is fired only once!</p>
<p>Here is my ScriptManager Class:</p>
<pre class="brush:csharp">public class ScriptManager
{
    private readonly HtmlHelper _helper;

    public IDictionary&lt;string, ClientScript&gt; ClientScripts
    {
       get
       {
          if (_helper.ViewContext.HttpContext.Items["ClientScripts"] == null)
          _helper.ViewContext.HttpContext.Items["ClientScripts"] = new Dictionary&lt;string, ClientScript&gt;();

          return (IDictionary&lt;string, ClientScript&gt;)_helper.ViewContext.HttpContext.Items["ClientScripts"];
       }
    }

    public IDictionary&lt;string, Action&gt; Methods
    {
      get
      {
         if (_helper.ViewContext.HttpContext.Items["ScriptMethods"] == null)
         _helper.ViewContext.HttpContext.Items["ScriptMethods"] = new Dictionary&lt;string, Action&gt;();

         return (IDictionary&lt;string, Action&gt;) _helper.ViewContext.HttpContext.Items["ScriptMethods"];
      }
    }

   public ScriptManager(HtmlHelper helper)
   {
       _helper = helper;
   }

   public ClientScript CreateClientScript(string key)
   {
      if(!ClientScripts.ContainsKey(key))
       ClientScripts.Add(key, new ClientScript());

      return ClientScripts[key];
   }

   public ScriptManager AddStaticMethod(string key, Action javascript)
   {
     if(!Methods.ContainsKey(key))
       Methods.Add(key, javascript);

     return this;
   }

   public void Render()
   {
     TextWriter writer = _helper.ViewContext.HttpContext.Response.Output;
     writer.WriteLine("&lt;script type=\"text/javascript\"&gt;");

     foreach (var clientScript in ClientScripts.Keys)
     {
       writer.WriteLine("var " + clientScript + " = {");
       writer.WriteLine("        Init: function(params) {");
       ClientScripts[clientScript].Value();
       writer.WriteLine("        }");
       writer.WriteLine("}");
     }

     writer.WriteLine("$(document).ready(function() {");
     foreach(var clientScript in ClientScripts.Keys)
     {
       var client = ClientScripts[clientScript];
       writer.WriteLine("    " + clientScript + ".Init({");
       foreach (var param in client.Params)
         writer.WriteLine("       {0}:'{1}'{2}", param.Key, param.Value, IsLast(client.Params, param.Key) ? string.Empty : ",");
         writer.WriteLine("    });");
       }
     writer.WriteLine("});");
     foreach(var method in Methods.Values)
       method();
     writer.WriteLine("&lt;/script&gt;");
   }

   private static bool IsLast(IDictionary&lt;string, string&gt; parameters, string key)
   {
     var keys = parameters.Keys.ToList();
     return keys.Count &gt; 0 &amp;&amp; keys[keys.Count-1] == key;
   }
}</pre>
<p>Here is the ClientScript class:</p>
<pre class="brush:csharp">public class ClientScript
{
   private readonly IDictionary&lt;string, string&gt; _parameters = new Dictionary&lt;string, string&gt;();
   private Action _script;

   public IDictionary&lt;string, string&gt; Params
   {
     get { return _parameters; }
   }

   public ClientScript AddParam(string key, string value)
   {
     Params.Add(key, value);
     return this;
   }

   public ClientScript Ready(Action script)
   {
     _script = script;
     return this;
   }

   public Action Value
   {
     get
     {
       return _script;
     }
   }
}</pre>
<p>Here is my extension method:</p>
<pre class="brush:csharp">public static ScriptManager ScriptManager(this HtmlHelper helper)
{
    return new ScriptManager(helper);
}</pre>
<p>And then you only need to add this at the end of your master page:</p>
<pre class="brush:csharp">&lt;% Html.ScriptManager().Render(); %&gt;</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.marcdormey.com/index.php/archives/250/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>jLinq &#8211; LINQ for JSON</title>
		<link>http://www.marcdormey.com/index.php/archives/229</link>
		<comments>http://www.marcdormey.com/index.php/archives/229#comments</comments>
		<pubDate>Mon, 19 Oct 2009 10:44:55 +0000</pubDate>
		<dc:creator>Marcel</dc:creator>
				<category><![CDATA[CSS/Html]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Misc]]></category>
		<category><![CDATA[jlinq]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[linq]]></category>
		<category><![CDATA[linq2sql]]></category>

		<guid isPermaLink="false">http://www.marcdormey.com/?p=229</guid>
		<description><![CDATA[

Sometimes I stumble accross something and immediately think &#8220;where has this been all my life?&#8221;. Finding jLinq is one of those moments.
I love Language Integrated Query (LINQ) and have used it for the last couple of years. With LINQ2NHibernate, LINQ2Lucene, LINQ2Amazon and even LINQ2Twitter emerging, it is very clear that LINQ is here to stay.
Enter [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.marcdormey.com/wp-content/uploads/2009/10/jLinq.png" alt="jLinq" title="jLinq" style="float:right; margin-left:5px; margin-bottom: 5px;" /></p>
<div style="margin-top: -5px;">
Sometimes I stumble accross something and immediately think &#8220;where has this been all my life?&#8221;. Finding jLinq is one of those moments.<br />
I love Language Integrated Query (LINQ) and have used it for the last couple of years. With <a href="http://www.hookedonlinq.com/LINQToNHibernate.ashx">LINQ2NHibernate</a>, <a href="http://www.codeplex.com/linqtolucene">LINQ2Lucene</a>, <a href="http://weblogs.asp.net/fmarguerie/archive/2006/06/26/Introducing-Linq-to-Amazon.aspx">LINQ2Amazon</a> and even <a href="http://linqtotwitter.codeplex.com/">LINQ2Twitter</a> emerging, it is very clear that LINQ is here to stay.</p>
<p>Enter <a href="http://www.hugoware.net/Projects/jLinq">jLinq from Hugoware</a>&#8230;
</div>
<pre class="brush:csharp">
$.getJSON("/Person/All", function(data) {
  var results = jLinq.from(data.users)
      .startsWith("first", "a")
      .orEndsWith("y")
      .orderBy("admin", "age")
      .select();
});
</pre>
<p>You can view the basics of jLinq from this <a href="http://www.hugoware.net/Projects/jLinq/Screencast1">screencast</a>.<br />
We used jLinq to solve a very complex join operation on our JSON object and found it to be a very simple task&#8230;</p>
<pre class="brush:csharp">
  var results = jLinq.from(data.users)
    .join(data.locations, "location", "locationId", "id")
    .equals("location.state", "texas")
    .orderBy("location.city")
    .select(function(r) {
    return {
       fullname:r.first + " " + r.last,
       city:r.location.city,
       state:r.location.state
    };
});
</pre>
<p>jLinq is also very extensible and creating your own extension methods couldnt be easier&#8230;</p>
<pre class="brush:csharp">
  jLinq.extend({
    name:"startsWithLetterP",
    type:"query",
    count:0,
    method:function(q) {
        return q.helper.match(q.value, /^p/);
    }}); 

//use the new method
var results = jLinq.from(data.users)
    .startsWithLetterP("first")
    .select();
</pre>
<p>So why wait another minute, head off to experiment <a href="http://www.hugoware.net/Projects/jLinq">here </a> right now!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.marcdormey.com/index.php/archives/229/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Yes/No Dropdownlist Extension for ASP.NET MVC</title>
		<link>http://www.marcdormey.com/index.php/archives/222</link>
		<comments>http://www.marcdormey.com/index.php/archives/222#comments</comments>
		<pubDate>Wed, 14 Oct 2009 09:51:21 +0000</pubDate>
		<dc:creator>Marcel</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CSS/Html]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[asp.net mvc]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[html]]></category>

		<guid isPermaLink="false">http://www.marcdormey.com/?p=222</guid>
		<description><![CDATA[I am not a big fan of using checkboxes for a simple yes/no question on a form. I use checkboxes only for selecting multiple items to perform an action on, or when I am using a checkboxlist. The reason for this is because I believe a yes/no question has three possible states, not only two. [...]]]></description>
			<content:encoded><![CDATA[<p>I am not a big fan of using checkboxes for a simple yes/no question on a form. I use checkboxes only for selecting multiple items to perform an action on, or when I am using a checkboxlist. The reason for this is because I believe a yes/no question has three possible states, not only two. </p>
<p>If you are asking a user &#8220;Do you agree with our terms?&#8221;, the general consensus is to assume that not clicking the box is &#8220;forgetting&#8221; to make a selection and warning me that &#8220;You have forgotten to tick our terms and conditions&#8221;. In this situation the case may be so, but what if I did not agree? What if the question was &#8220;Do you want to opt out of us sending you loads and loads of spam?&#8221; and simply not spotting this question.</p>
<p>I believe that if you did not make a selection it is a valid state. Thus a yes/no question, in my opinion, has the following states; &#8220;yes&#8221;, &#8220;no&#8221; and &#8220;did not choose&#8221;.<br />
Once again, I don&#8217;t simply rant, I also offer a solution&#8230; a very simple extension method which I love using for all my yes/no questions instead of checkboxes. In this case I made the &#8220;not selected&#8221; state 0.</p>
<p></p>
<pre class="brush:csharp">
public static string YesNoDropDownList(this HtmlHelper helper, string id, string selectedValue)
        {

            var list = new SelectList(new[]
                              {
                                  new {text = "Select", value = "0"},
                                  new {text = "No", value = "1"},
                                  new {text = "Yes", value = "2"}
                              }, "value", "text", selectedValue);

            return helper.DropDownList(id, list);
        }
</pre>
<p>PS: It also looks a bit neater and more uniform.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.marcdormey.com/index.php/archives/222/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Update Form Fields with JSON result in ASP.NET MVC</title>
		<link>http://www.marcdormey.com/index.php/archives/217</link>
		<comments>http://www.marcdormey.com/index.php/archives/217#comments</comments>
		<pubDate>Mon, 05 Oct 2009 10:28:21 +0000</pubDate>
		<dc:creator>Marcel</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[asp.net mvc]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[properties]]></category>

		<guid isPermaLink="false">http://www.marcdormey.com/?p=217</guid>
		<description><![CDATA[Wouldn&#8217;t it be nifty to receive a JSON result object from AJAX and it automagically updates your form fields? Those who said &#8220;No&#8221; leave now!
I had to find a way to iterate through my JSON properties and, if I named the fields the same as the JSON properties, update them all in one go.
Lets use [...]]]></description>
			<content:encoded><![CDATA[<p>Wouldn&#8217;t it be nifty to receive a JSON result object from AJAX and it automagically updates your form fields? Those who said &#8220;No&#8221; leave now!<br />
I had to find a way to iterate through my JSON properties and, if I named the fields the same as the JSON properties, update them all in one go.</p>
<p>Lets use a simple &#8220;Person&#8221; model and have a look at the ASP.NET MVC action:</p>
<pre class="brush:csharp">
public ActionResult GetPerson(int id)
{
    var person = Context.GetPerson(id);
    return Json(new
                    {
                        success = true,
                        model = new
                                    {
                                        person.Id,
                                        person.Name,
                                        person.Surname,
                                        person.Age,

                                    }
                    });
}
</pre>
<p>As you can see this returns a DTO (data transfer object) as JSON result and is ready to be consumed via AJAX&#8230;</p>
<pre class="brush:js">
$.getJSON("/Person/1", function(data) {
    if (data.success) {
        $.updateForm(data.model);
    } else {
        alert("An error occurred");
    }
});
</pre>
<p>All we then need is the magical &#8220;$.updateForm&#8221; method that contains all the voodoo:</p>
<pre class="brush:js">
jQuery.updateForm = function(model) {
   // we iterate through all the properties
   for (var property in model) {
        // evaluate the expression to get the value
        var propertyValue = eval("model." + property);
        // and update the field
        $("#" + property).val(propertyValue);
    }
};
</pre>
<p>Currenty this will work fine for textboxes and textareas as this was all the functionality I needed for now. If anyone extends this for &#8220;select&#8221;, &#8220;checkbox&#8221;, &#8220;radiobutton&#8221; etc&#8230; please share with us so I can update this post.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.marcdormey.com/index.php/archives/217/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Kaboom! &#8211; JQuery MVVM Framework for the web</title>
		<link>http://www.marcdormey.com/index.php/archives/199</link>
		<comments>http://www.marcdormey.com/index.php/archives/199#comments</comments>
		<pubDate>Wed, 30 Sep 2009 12:41:20 +0000</pubDate>
		<dc:creator>Marcel</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[asp.net mvc]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[mvvm]]></category>

		<guid isPermaLink="false">http://www.marcdormey.com/?p=199</guid>
		<description><![CDATA[&#8220;Kaboom!&#8221; is one of those things you stumble upon and intrigues you from the start. It probably needs more work (not to mention documentation), but certainly gives you a peak at what I believe could be the next big thing in the ASP.NET MVC world. Having just finished a CMS system where I used a [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-full wp-image-205" title="Screenshot" src="http://www.marcdormey.com/wp-content/uploads/2009/09/Screenshot1.png" alt="Screenshot" width="211" height="396" />&#8220;Kaboom!&#8221; is one of those things you stumble upon and intrigues you from the start. It probably needs more work (not to mention documentation), but certainly gives you a peak at what I believe could be the next big thing in the ASP.NET MVC world. Having just finished a CMS system where I used a very rich JQuery client, I found this a very probable next step. Already using &#8220;jquery.forms&#8221; to submit all my forms via ajax POST and using &#8220;$.getJSON&#8221; for all my GET actions, my views started to get pretty lean. I thought, what if I had a JQuery ViewModel that would handle my UI commands and handle all my communication with my controller? A quick search lead me to &#8220;Kaboom!&#8221;.</p>
<p>The first thing I worried about was testability. &#8220;QUnit&#8221; (<a href="http://docs.jquery.com/QUnit">http://docs.jquery.com/QUnit</a>) seems to be a very powerful testing framework that would probably give me more coverage than what I had before! UnitTesting &#8211; Check <img src='http://www.marcdormey.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>So lets look at one of the samples in the codeplex download, specifically the Asp.Net MVC sample&#8230;</p>
<p>We start with a &#8220;Person&#8221; Model:</p>
<pre class="brush:csharp">public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}</pre>
<p>And a &#8220;PersonController&#8221; class which has a Search action:</p>
<pre class="brush:csharp">public class PersonsController : Controller
{
    public JsonResult Search(string searchString)
    {
        List persons = new List();
        persons.Add(new Person { FirstName = "Kozin", LastName = "Osot" });
        persons.Add(new Person { FirstName = "Setesyci", LastName = "Rynaugh" });
        persons.Add(new Person { FirstName = "Atheck", LastName = "Garash" });

        return Json(persons
            .Where(p =&gt; p.FirstName.ToLower().Contains(searchString.ToLower()) ||
                p.LastName.ToLower().Contains(searchString.ToLower())).ToList());
    }
}</pre>
<p>Then we create a &#8220;SearchViewModel&#8221; js file and put this in our &#8220;ViewModels&#8221; folder like so:</p>
<pre class="brush:js">var SearchViewModel = {
    Initialize: function(args, callback) {
        Kaboom.register("Search", SearchViewModel.Search);
        SearchViewModel.SearchResults = new Array();
        callback();
    },

    Ready: function() {
        SearchViewModel.Search();
    },

    SearchString: '',
    SearchResults: null,
    Search: function() {
        $.getJSON('/Person/Search',// You can set this as a hidden field on your View with 'Url.Action(..' and simply do $('#searchSource').val()
            { searchString: SearchViewModel.SearchString },
            SearchViewModel.PopulateSearchResults);
    },

    PopulateSearchResults: function(data) {
        SearchViewModel.SearchResults = data;
        Kaboom.notify(SearchViewModel, "SearchResults");
    }
}</pre>
<p>And our &#8220;Search&#8221; view would hook up to our view model like so&#8230;</p>
<pre class="brush:xml">&lt;head runat="server"&gt;
    &lt;title&gt;Search&lt;/title&gt;
    &lt;% string version = DateTime.Now.Ticks.ToString(); %&gt;
    &lt;script type="text/javascript" src="../../ViewModels/Persons/SearchViewModel.js?id=&lt;%= version %&gt;"&gt;&lt;/script&gt;
    &lt;script type="text/javascript" src="Scripts/jquery-1.3.2.js?id=&lt;%= DateTime.Now.Ticks.ToString() %&gt;"&gt;&lt;/script&gt;
    &lt;script type="text/javascript" src="Scripts/json2.js?id=&lt;%= DateTime.Now.Ticks.ToString() %&gt;"&gt;&lt;/script&gt;
    &lt;script type="text/javascript" src="Scripts/kaboom.js?id=&lt;%= DateTime.Now.Ticks.ToString() %&gt;"&gt;&lt;/script&gt;

&lt;/head&gt;
&lt;body&gt;
    Quick start shows how to communicate with an aspMVC controller.....&lt;br /&gt;
    &lt;input type="hidden" id="viewmodel" viewmodel="SearchViewModel" debug="0" /&gt;
    &lt;div id="Debug"&gt;&lt;/div&gt;
    Search:&lt;br /&gt;
    &lt;input type="text" bindto="SearchString" mode="TwoWay" /&gt;&lt;br /&gt;
    &lt;input type="button" value="Search" command="Search" /&gt;
    &lt;br /&gt;
    &lt;table bindto="SearchResults"&gt;
        &lt;thead&gt;
            &lt;tr&gt;
                &lt;th&gt;First Name&lt;/th&gt;
                &lt;th&gt;Last Name&lt;/th&gt;
                &lt;th&gt;Options&lt;/th&gt;
            &lt;/tr&gt;
        &lt;/thead&gt;
        &lt;tbody&gt;
            &lt;tr&gt;
                &lt;td&gt;$FirstName&lt;/td&gt;
                &lt;td&gt;$LastName&lt;/td&gt;
                &lt;td&gt;&lt;a href="#" onclick="alert('$FirstName')"&gt;Delete&lt;/a&gt;&lt;/td&gt;
            &lt;/tr&gt;
        &lt;/tbody&gt;
    &lt;/table&gt;
&lt;/body&gt;</pre>
<p>You can bind all your view actions to commands.</p>
<pre class="brush:xml">
&lt;input type=&quot;button&quot; command=&quot;Save&quot; value=&quot;Bound to Save command via jQuery(element).click()&quot; /&gt;&lt;br /&gt;&lt;br /&gt;
&lt;input type=&quot;button&quot; command=&quot;Save&quot; trigger=&quot;dblclick&quot; value=&quot;Bound to Save command via jQuery(element).dblclick()&quot; /&gt;&lt;br /&gt;&lt;br /&gt;
&lt;input type=&quot;button&quot; command=&quot;Save&quot; trigger=&quot;blur&quot; value=&quot;Bound to Save command via jQuery(element).blur()&quot; /&gt;&lt;br /&gt;&lt;br /&gt;
&lt;input type=&quot;button&quot; command=&quot;Save&quot; trigger=&quot;customaction&quot; value=&quot;Bound to Save command via jQuery(element).customaction()&quot; /&gt;&lt;br /&gt;&lt;br /&gt;</pre>
<p>&#8230; and it has support for other controls and more complex bindings.</p>
<pre class="brush:xml">
&lt;select bindto=&quot;Person.Salutation&quot;
         datatextfield=&quot;Name&quot;
         datavaluefield=&quot;Id&quot;
         datasourceid=&quot;Salutations&quot;
         onbind=&quot;ProgrammaticallyBindIt&quot; &gt;
   &lt;option value=&quot;0&quot;&gt;[select]&lt;/option&gt;
&lt;/select&gt;</pre>
<p>There are loads of other examples, including binding to Tables, Divs, Spans, Checkboxes etc. You can download the framework <a href="http://kaboom.codeplex.com/">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.marcdormey.com/index.php/archives/199/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Agile Programming using SOLID Principles</title>
		<link>http://www.marcdormey.com/index.php/archives/182</link>
		<comments>http://www.marcdormey.com/index.php/archives/182#comments</comments>
		<pubDate>Thu, 24 Sep 2009 09:01:14 +0000</pubDate>
		<dc:creator>Marcel</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[agile]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[dependency injection]]></category>
		<category><![CDATA[inversion of control]]></category>
		<category><![CDATA[open close principle]]></category>
		<category><![CDATA[principles]]></category>
		<category><![CDATA[solid]]></category>

		<guid isPermaLink="false">http://www.marcdormey.com/?p=182</guid>
		<description><![CDATA[If you use Agile as project management methodology then you must have heard of the &#8216;SOLID&#8217; principles. Agile and SOLID goes hand in hand.
Uncle Bob has a great article on SOLID and explains each principle in detail with examples.
A summary of the principles below:

S &#8211; Single Responsibility Pattern
A class should have one, and only one, [...]]]></description>
			<content:encoded><![CDATA[<p>If you use Agile as project management methodology then you must have heard of the &#8216;SOLID&#8217; principles. Agile and SOLID goes hand in hand.<br />
Uncle Bob has a great article on SOLID and explains each principle in detail with examples.</p>
<p>A summary of the principles below:</p>
<ul>
<li><b>S &#8211; Single Responsibility Pattern</b><br />
A class should have one, and only one, reason to change</li>
<li><b>O &#8211; Open/Close Principle</b><br />
Classes should be closed for modification, but open for extension</li>
<li><b>L &#8211; Liskov Substitution Principle</b><br />
Derived classes must be substitutable for their base classes.</li>
<li><b>I &#8211; Interface Segregation Principle</b><br />
Clients should not be forced to depend upon interfaces that they do not use.</li>
<li><b>D &#8211; Dependency Inversion Principle</b><br />
Depend on abstractions, not concretions</li>
</ul>
<p><a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod" target="_blank">You can read the full article here</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.marcdormey.com/index.php/archives/182/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Behaviour Driven Development in NUnit with StoryQ</title>
		<link>http://www.marcdormey.com/index.php/archives/178</link>
		<comments>http://www.marcdormey.com/index.php/archives/178#comments</comments>
		<pubDate>Tue, 22 Sep 2009 11:38:41 +0000</pubDate>
		<dc:creator>Marcel</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[bdd]]></category>
		<category><![CDATA[behaviour driven development]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[mspec]]></category>
		<category><![CDATA[nbehave]]></category>
		<category><![CDATA[resharper]]></category>
		<category><![CDATA[specifications]]></category>
		<category><![CDATA[storyq]]></category>
		<category><![CDATA[tdd]]></category>

		<guid isPermaLink="false">http://www.marcdormey.com/?p=178</guid>
		<description><![CDATA[A few months ago I started with BDD (Behaviour Driven Development). The first thing I noticed with most frameworks (MSpec, NBehave) is that you either need a new test runner tool (Galio) or need quite a bit of tweaking to implement the respective framework with Test-Driven.NET or Resharper&#8217;s test runner (Galio has a Resharper plugin). [...]]]></description>
			<content:encoded><![CDATA[<p>A few months ago I started with BDD (Behaviour Driven Development). The first thing I noticed with most frameworks (MSpec, NBehave) is that you either need a new test runner tool (<a href="http://www.gallio.org/" target="_blank">Galio</a>) or need quite a bit of tweaking to implement the respective framework with <a href="http://www.testdriven.net/" target="_blank">Test-Driven.NET</a> or <a href="http://www.jetbrains.com/resharper/" target="_blank">Resharper</a>&#8217;s test runner (Galio has a Resharper plugin). </p>
<p>This isn&#8217;t a problem in most cases, but what if you need to run these tests on Team-City or Cruise-Control? Now the complexity of the tweaking starts to become quite a different ball game!</p>
<p>Luckily there is an open-source tool called <a href="http://www.codeplex.com/storyq" target="_blank">StoryQ</a> which runs on NUnit and doesnt require any tweaking. The developer can run this with his usual test-runner tool and best of all, nothing has to change on the Buildserver.</p>
<p>Besides requiring no tweaking, StoryQ is a pretty competitive BDD tool altogether and provides loads of nifty features.</p>
<p>The idea is that &#8220;Tests&#8221; should be viewed as &#8220;Specs&#8221;, because this removes much of the confusion of TDD especially for beginners.<br />
Your typical Unit test (or Spec) would look like this:</p>
<pre class="brush:csharp">
using NUnit.Framework;
using StoryQ.Framework;

  namespace StoryQ.Tests.Documentation
  {
    [TestFixture]
    public class SimpleDocumentationSpec
    {

        [Test]
        public void WritingSpecificationsToBegin()
        {
            Story story = new Story("writing executable specifications");

            story.AsA("business person")
                .IWant("to write executable specifications")
                .SoThat("a developer can implement them")

                .WithScenario("Writing specifications")
                    .Given("That i have written everything in text")
                    .When("the test is run")
                    .Then("the test result should be pending")

                .WithScenario("Writing specifications again")
                    .Given("That i have written everything in text")
                        .And("still have no asserts")
                        .And("and have another condition")
                    .When("the test is run")
                        .And("I am happy")
                    .Then("the test result should be pending")
                       .And("here's just some more and's");

            story.Assert();
        }

    }
  }
</pre>
<p>This would present an NUnit output result of:</p>
<pre class="brush:xml">
SimpleDocumentationSpec.WritingSpecificationsToBegin : IgnoredPending
Story: writing executable specifications

  As a business person
  I want to write executable specifications
  So that a developer can implement them

  Scenario 1: Writing specifications
    Given That i have written everything in text  *Pending
    When the test is run                          *Pending
    Then the test result should be pending        *Pending

  Scenario 2: Writing specifications again
    Given That i have written everything in text  *Pending
      And still have no asserts                   *Pending
      And and have another condition              *Pending
    When the test is run                          *Pending
      And I am happy                              *Pending
    Then the test result should be pending        *Pending
      And here's just some more and's             *Pending
</pre>
<p>You can then start adding functionality with the given scenarios like so:</p>
<pre class="brush:csharp">
using NUnit.Framework;
using StoryQ.Framework;

namespace StoryQ.Tests.Documentation
{
    [TestFixture]
    public class UsingNarrativesSpec
    {

        [Test]
        public void WritingExecutablePassingSpecificationsWithNarratives()
        {
            Story story = new Story("writing executable specifications");

            story.AsA("business person")
                .IWant("to write executable specifications")
                .SoThat("a developer can implement them")

                .WithScenario("Writing specifications again")
                    .Given(Narrative.Text("I have a narrative"))
                    .When(() => TheTestIs_("run"))
                    .Then(Narrative.Exec("this will now pass", passMe));

            story.Assert();
        }

        static void passMe()
        {
            Assert.IsTrue(true);
        }

        static void TheTestIs_(string s)
        {
            Assert.AreEqual(s, "run");
        }

    }
}
</pre>
<p>Which will give you the output of:</p>
<pre class="brush:csharp">
UsingActionsSpec.WritingExecutableSpecificationsAsActions : PassedStory: writing executable specifications

  As a business person
  I want to write executable specifications
  So that a developer can implement them

  Scenario 1: Writing specifications
    Given That i have written everything in text  *Pending
    When the test is run                          *Pending
    Then the test result should be pending        *Pending

  Scenario 2: Writing specifications again
    Given That everything isnt                     Passed
    When The test is run                           Passed
    Then the test result should be pending        *Pending
</pre>
<p>There are many more options and different ways to implement the scenarios on the <a href="http://www.codeplex.com/storyq" target="_blank">StoryQ home page</a>.<br />
Another great feature about StoryQ is to convert your english written stories into C# tests. Yes, you read that right! It will even write the code for you! By using convention that can be tought to your &#8220;Product Owners&#8221;, you can literally copy and paste their requirements to a tool which will present the generated c# test.</p>
<p><img alt="" src="http://i3.codeplex.com/Project/Download/FileDownload.aspx?ProjectName=storyq&#038;DownloadId=39599" title="StoryQ Converter" class="aligncenter" width="600" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.marcdormey.com/index.php/archives/178/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
