<?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 &#187; c#</title>
	<atom:link href="http://www.marcdormey.com/index.php/tags/c/feed" rel="self" type="application/rss+xml" />
	<link>http://www.marcdormey.com</link>
	<description>Software Finds, Programming Tutorials and Gadget Reviews</description>
	<lastBuildDate>Tue, 20 Jul 2010 14:52:40 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</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/creating-a-custom-valuetype-and-serialising-with-a-custom-jsonresult</link>
		<comments>http://www.marcdormey.com/index.php/archives/creating-a-custom-valuetype-and-serialising-with-a-custom-jsonresult#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. {&#8220;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. {&#8220;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/creating-a-custom-valuetype-and-serialising-with-a-custom-jsonresult/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC JQuery ScriptManager</title>
		<link>http://www.marcdormey.com/index.php/archives/asp-net-mvc-jquery-scriptmanager</link>
		<comments>http://www.marcdormey.com/index.php/archives/asp-net-mvc-jquery-scriptmanager#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/asp-net-mvc-jquery-scriptmanager/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Yes/No Dropdownlist Extension for ASP.NET MVC</title>
		<link>http://www.marcdormey.com/index.php/archives/yesno-dropdownlist-extension-for-asp-net-mvc</link>
		<comments>http://www.marcdormey.com/index.php/archives/yesno-dropdownlist-extension-for-asp-net-mvc#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/yesno-dropdownlist-extension-for-asp-net-mvc/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Kaboom! &#8211; JQuery MVVM Framework for the web</title>
		<link>http://www.marcdormey.com/index.php/archives/kaboom-jquery-mvvm-framework-for-the-web</link>
		<comments>http://www.marcdormey.com/index.php/archives/kaboom-jquery-mvvm-framework-for-the-web#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/kaboom-jquery-mvvm-framework-for-the-web/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/agile-programming-using-solid-principles</link>
		<comments>http://www.marcdormey.com/index.php/archives/agile-programming-using-solid-principles#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/agile-programming-using-solid-principles/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/behaviour-driven-development-in-nunit-with-storyq</link>
		<comments>http://www.marcdormey.com/index.php/archives/behaviour-driven-development-in-nunit-with-storyq#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/behaviour-driven-development-in-nunit-with-storyq/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Changing the target filename of TransmitFile in asp.net mvc</title>
		<link>http://www.marcdormey.com/index.php/archives/changing-the-target-filename-of-transmitfile-in-asp-net-mvc</link>
		<comments>http://www.marcdormey.com/index.php/archives/changing-the-target-filename-of-transmitfile-in-asp-net-mvc#comments</comments>
		<pubDate>Thu, 17 Sep 2009 12:39:35 +0000</pubDate>
		<dc:creator>Marcel</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[asp.net mvc]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[file download]]></category>
		<category><![CDATA[output response]]></category>
		<category><![CDATA[transmitfile]]></category>

		<guid isPermaLink="false">http://www.marcdormey.com/?p=160</guid>
		<description><![CDATA[Say a file has a physical filename of &#8216;xyz.pdf&#8217;, but when you send it to the user you want it to have a name like &#8216;myxyzbrilliantfilename.pdf&#8217;. How do you change the target filename when transmitting files through the output stream of Response without it popping up a download dialog?
I have searched wide and wild and [...]]]></description>
			<content:encoded><![CDATA[<p>Say a file has a physical filename of &#8216;xyz.pdf&#8217;, but when you send it to the user you want it to have a name like &#8216;myxyzbrilliantfilename.pdf&#8217;. How do you change the target filename when transmitting files through the output stream of Response without it popping up a download dialog?</p>
<p>I have searched wide and wild and the only way you could do this is by modifying the &#8220;ContentDisposition&#8221; like so:</p>
<pre class="brush:csharp">Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
// OR
Response.AddHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");</pre>
<p>The &#8220;attachment&#8221; setting opens a dialog to save the file with the correct name and the &#8220;inline&#8221; setting doesnt open a dialog, but ignores the filename!<br />
This is not the behaviour I am looking for, so I had a quick coffee and came up with the following very simple solution!</p>
<p>My solution came in the form of a new route in my mappings:</p>
<pre class="brush:csharp">
routes.MapRoute(
    "ResourceModulePdf", // Route name
    "ResourceModule/Pdf/{id}.pdf", // URL with parameters
    new
    {
        controller = "ResourceModule",
        action = "Pdf",
        id = "",
        sourceFilename = ""
    } // Parameter defaults
    );
</pre>
<p>and my &#8216;pdf&#8217; action:</p>
<pre class="brush:csharp">
public ActionResult Pdf(string id, string sourceFilename)
{
    // We do not need to do anything with 'id'. It has served it's purpose already
    return new FileResult(sourceFilename, "application/pdf");
}
</pre>
<p>&#8230; and my FileResult</p>
<pre class="brush:csharp">
public class FileResult : ActionResult
{
    public String ContentType { get; set; }
    public byte[] ImageBytes { get; set; }
    public String SourceFilename { get; set; }

    //This is used for times where you have a physical location
    public FileResult(String sourceFilename, String contentType)
    {
        SourceFilename = sourceFilename;
        ContentType = contentType;
    }

    //This is used for when you have the actual image in byte form
    //  which is more important for this post.
    public FileResult(byte[] sourceStream, String contentType)
    {
        ImageBytes = sourceStream;
        ContentType = contentType;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        var response = context.HttpContext.Response;
        response.Clear();
        response.Cache.SetCacheability(HttpCacheability.NoCache);
        response.ContentType = ContentType;

        if (ImageBytes != null)
        {
            var stream = new MemoryStream(ImageBytes);
            stream.WriteTo(response.OutputStream);
            stream.Dispose();
        }
        else
            response.TransmitFile(SourceFilename);
    }
}
</pre>
<p>All we need to do now is construct our hyperlinks like so: </p>
<pre class="brush:xml">

<a href="ResourceModule/Pdf/mynewbrilliantname.pdf?key=actualnameondisk.pdf" target="_blank">Doc</a>
</pre>
<p>By default the &#8220;TransmitFile&#8221; method will take the name of the filename you used in your hyperlink and the result is exactly what we wanted!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.marcdormey.com/index.php/archives/changing-the-target-filename-of-transmitfile-in-asp-net-mvc/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>JQuery function to populate a select box</title>
		<link>http://www.marcdormey.com/index.php/archives/jquery-function-to-populate-a-select-box</link>
		<comments>http://www.marcdormey.com/index.php/archives/jquery-function-to-populate-a-select-box#comments</comments>
		<pubDate>Fri, 04 Sep 2009 11:52:48 +0000</pubDate>
		<dc:creator>Marcel</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[asp.net mvc]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[json]]></category>

		<guid isPermaLink="false">http://www.marcdormey.com/?p=34</guid>
		<description><![CDATA[Something you might be repeating while building a user interface is populating a select box with JSON results. Here is a quick demonstration on a very simple way to do this. Put the &#8216;populateSelect&#8217; method in a global .js file and use it throughout your project as &#8216;$.populateSelect(args&#8230;)&#8217;
ASP.NET MVC Action Method
public ActionResult GetUsers()
{
   [...]]]></description>
			<content:encoded><![CDATA[<p>Something you might be repeating while building a user interface is populating a select box with JSON results. Here is a quick demonstration on a very simple way to do this. Put the &#8216;populateSelect&#8217; method in a global .js file and use it throughout your project as &#8216;$.populateSelect(args&#8230;)&#8217;</p>
<p>ASP.NET MVC Action Method</p>
<pre class="brush:csharp">public ActionResult GetUsers()
{
     var data = Service.QueryUsers()
           .Select(x =&gt; new {value = x.Id, text = x.Name});

      return Json(data);
}</pre>
<p>Usage:</p>
<pre class="brush:js">var url = "&lt;%=Url.Action("GetUsers", "UserController") %&gt;";

$.getJSON(url, function(data, textstatus) {
        $.populateSelect("#someSelectBox", data);
});
</pre>
<p>Global Method:</p>
<pre class="brush:js">
// JQuery Method
jQuery.populateSelect = function(selectId, data) {
    $.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>Removing all Items from a select list is just as simple:</p>
<pre class="brush:js">
$("#mySelectList")
   .find("option")
   .remove();
</pre>
<p>And lastly how to Append or Prepend items to the list:</p>
<pre class="brush:csharp">
// Add options to the end of a select
$("#mySelectList")
    .append("<option value='1'>New Item</option>");

// Add options to the start of a select
$("#mySelectList")
    .prepend("<option value='0'>Select...</option>");
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.marcdormey.com/index.php/archives/jquery-function-to-populate-a-select-box/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JQuery C# String.Format equivalent</title>
		<link>http://www.marcdormey.com/index.php/archives/jquery-c-string-format-equivalent</link>
		<comments>http://www.marcdormey.com/index.php/archives/jquery-c-string-format-equivalent#comments</comments>
		<pubDate>Fri, 04 Sep 2009 11:29:58 +0000</pubDate>
		<dc:creator>Marcel</dc:creator>
				<category><![CDATA[JQuery]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[string]]></category>
		<category><![CDATA[string format]]></category>

		<guid isPermaLink="false">http://www.marcdormey.com/?p=17</guid>
		<description><![CDATA[When I am working with strings in JQuery I sometimes miss the ol&#8217; &#8220;String.Format&#8221; in C#. I decided to create a quick global method that makes life just a little bit easier!
Usage:
$.stringFormat("{0} {1}!", ["Hello", "world"]);
Method:

jQuery.stringFormat = function(format, arguments) {
    var str = format;
    for (i = 0; i &#60; [...]]]></description>
			<content:encoded><![CDATA[<p>When I am working with strings in JQuery I sometimes miss the ol&#8217; &#8220;String.Format&#8221; in C#. I decided to create a quick global method that makes life just a little bit easier!</p>
<p>Usage:</p>
<pre class="brush:js">$.stringFormat("{0} {1}!", ["Hello", "world"]);</pre>
<p>Method:</p>
<pre class="brush:js">
jQuery.stringFormat = function(format, arguments) {
    var str = format;
    for (i = 0; i &lt; arguments.length; i++) {
        str = str.replace('{' + i + '}', arguments[i]);
    }
    return str;
};
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.marcdormey.com/index.php/archives/jquery-c-string-format-equivalent/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
