<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>XHalent Coding...</title>
	<atom:link href="http://xhalent.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://xhalent.wordpress.com</link>
	<description>Exploring the Microsoft Development Stack</description>
	<lastBuildDate>Tue, 10 Jan 2012 12:00:23 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='xhalent.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>XHalent Coding...</title>
		<link>http://xhalent.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://xhalent.wordpress.com/osd.xml" title="XHalent Coding..." />
	<atom:link rel='hub' href='http://xhalent.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Master Details with Dialog in ASP.Net MVC and Unobstrusive Ajax</title>
		<link>http://xhalent.wordpress.com/2011/05/25/master-details-with-dialog-in-asp-net-mvc-and-unobstrusive-ajax/</link>
		<comments>http://xhalent.wordpress.com/2011/05/25/master-details-with-dialog-in-asp-net-mvc-and-unobstrusive-ajax/#comments</comments>
		<pubDate>Wed, 25 May 2011 13:19:25 +0000</pubDate>
		<dc:creator>xhalent</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Ajax]]></category>
		<category><![CDATA[ASP.Net MVC]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[aspnet.mvc]]></category>
		<category><![CDATA[unobstrusive ajax]]></category>

		<guid isPermaLink="false">http://xhalent.wordpress.com/?p=287</guid>
		<description><![CDATA[Today&#8217;s post explains a user interface that is not uncommon. The user interface consists of a list of items, and if the user clicks a link in the row of data for an item, a dialog window appears so the &#8230; <a href="http://xhalent.wordpress.com/2011/05/25/master-details-with-dialog-in-asp-net-mvc-and-unobstrusive-ajax/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=xhalent.wordpress.com&amp;blog=17892286&amp;post=287&amp;subd=xhalent&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Today&#8217;s post explains a user interface that is not uncommon. The user interface consists of a list of items, and if the user clicks a link in the row of data for an item, a dialog window appears so the user can edit the details of the item. When the user saves their changes, the table updates itself to reflect the new changes. </p>
<p>I&#8217;m going to cover an approach you can use with ASP.Net MVC to enable this, and explain the aspects required for the Controller and Views that make it all hang together. I&#8217;m not going into detail about where the data comes from or what the data is. The idea here is to concentrate on the pattern &#8211; you can work out what the data for the list and details screens, respectively, is.</p>
<h3>Controller</h3>
<p>We&#8217;ll set up the controller first. The controller requires at least four methods: </p>
<h4>Index method</h4>
<p>This handles the initial interaction of the user with the screen. It&#8217;s job is to retrieve the data from whatever is the data source to display and display the &#8220;Index&#8221; View.</p>
<pre><pre class="brush: csharp;">
public ActionResult Index(){
  MyListModel model = new MyListModel{
    Data= myDataStore.GetDataAsList()             
  };

  return View(model);
}
</pre></pre>
<h4>The Record &#8211; Get &#8211; Method</h4>
<p>This action returns a partial view via Ajax of the record to be edited. I will cover in a moment what is done on the client, but this method builds the edit View Model for the entity by first retrieving it from the data store. Note the use of the null able parameter to indicate if a new record should be created.</p>
<p>Also of interest is the use of the OutputCache action filter to ensure that the Ajax GET request is not cached on the client.</p>
<pre><pre class="brush: csharp;">
[OutputCache(NoStore = true, VaryByParam = &quot;None&quot;, Duration = 0)]
public PartialViewResult MyEntity(int? id){
  DetailViewModel model = new DetailViewModel ();

  if (id.HasValue){
    model.EntityDetail = myDataStore.GetData(id.Value);
  }
  else{
    model.EntityDetail = new MyEntityDetail();
  }
  
  return PartialView(&quot;Detail&quot;, model);
}
</pre>
</pre>
<h4>The Record &#8211; Post- Method</h4>
<p>This method does the update based on a POSTed model. Note how it the method has same name as the previous method, but is decorated with a <code>[HttpPost]</code> attribute and takes a populated entity model as a parameter. If the ModelState is valid, then it is prudent to clear the model state so that posted values are not re-displayed when rendering the view. Instead, the model is refreshed from the data store.</p>
<pre><pre class="brush: csharp;">
[HttpPost]
public PartialViewResult MyEntity(DetailViewMode model){
  if(ModelState.IsValid){
     ModelState.Clear();   
     model.EntityDetail = myDataStore.UpdateMyEntity(model.EntityDetail);
     ViewBag.Message = &quot;Details Successfully Updated&quot;;  
  }

  return PartialView(&quot;Detail&quot;, model);
}

</pre>
</pre>
<h4>The partial list refresh</h4>
<p>Once the record has been updated, the list of records needs to refresh itself. To do this, it need to make an Ajax call to the server to return a <code>PartialView</code> of just the table contents. That&#8217;s what this method does. Note again the use of the <code>[OutputCache]</code> filter to prevent Ajax request caching.</p>
<pre><pre class="brush: csharp;">
[OutputCache(NoStore = true, VaryByParam = &quot;None&quot;, Duration = 0)]
public PartialViewResult EntityList(){
  MyListModel model = new MyListModel{
    Data= myDataStore.GetDataAsList()             
  };
  return PartialView(&quot;List&quot;, model);
}
</pre>
</pre>
<h3>Views</h3>
<p>Okay, so that&#8217;s the controller covered, now lets consider the views. I&#8217;m going to use 3 views:</p>
<ol>
<li><b>Index</b> &#8211; the initial view when the user goes to the list.</li>
<li><b>Detail</b> &#8211; the details view of the entity, used for creates and edits.</li>
<li><b>List</b> &#8211; the partical view of the table of entitites.</li>
</ol>
<h4>The Index View</h4>
<p>This is very simple. It simply renders the partial list view and all the client side script that makes it all work. Aside from the comments in the script, the keys points are the hidden div for the placements of the Ajax retrieved content.</p>
<pre><pre class="brush: xml;">
@model MyListModel
@{
    ViewBag.Title = &quot;List of Entities&quot;;
    Layout = &quot;~/Views/Shared/_MainLayout.cshtml&quot;;
    //render the partial view
    Html.RenderPartial(&quot;List&quot;, Model);
}

&lt;!-- container for ajax loaded dialog content --&gt;
&lt;div id=&quot;ajax-content&quot; style=&quot;display:none&quot;&gt;

&lt;/div&gt;


&lt;script type=&quot;text/javascript&quot;&gt;
//&lt;![CDATA[
    //this function gets called when the ajax request to GET a entity detail has completed.
    //The GET request ends with the returned HTML being placed in the div with id='ajax-content'
    //A modal dialog is created. The title for the dialog is extracted from the contained fieldset legend.
    //On close, the dialog is destroyed and the content of the ajax-content div are removed
    //On Save the contained form is submitted
    function loadEntity(xhr, status) {
        $('#ajax-content').dialog({
            modal: true,
            width:600,
            title: $('#ajax-content legend').text(),
            buttons: {
                &quot;Save&quot;: function () {
                    //submit the form
                    $('#ajax-content form').submit();
                },
                &quot;Close&quot;: function () {
                    //remove the content, destroy the dialog
                    $(this).dialog('destroy').html('');
                }
            }
        });
    }

    //this function gets called when the contained form has been submitted via ajax
    //this results in the content INSIDE the ajax-content being replaced, however ajax-content, which is wrapped in
    //a dialog, is not replaced and so remain visible.
    //The title of the dialog is refreshed based on the contained legend.
    //The last thing this function does is makes the table 'entity-list' reload itself from the appropriate Url which points to the &quot;EntityList&quot; action on the controller
    function entityDetailsUpdated(responseText, status, xhr) {
        $('#ajax-content').dialog(&quot;option&quot;, &quot;title&quot;, $('#ajax-content legend').text());          
        $('#entity-list').load( '@Url.Action(&quot;EntityList&quot;)');
    }
//]]&gt;
&lt;/script&gt;


</pre>
</pre>
<h4>The List View</h4>
<p>This is simply a table that shows whatever properties of the entity you want, but with one of the properties being rendered as an <code>Ajax.ActionLink</code>. This little Microsoft extension simply leverages the jQuery Ajax stack in an unobtrusive way. You can see that I have used the <code>AjaxOptions</code> class to define that callback  function to call when the Ajax call is complete and the element to put the returned content in, both of which are defined in the Index View.
<p>Note the use of the additional link in the footer of the table to create a new record. In this case, no id is passed to the controller.</p>
<pre><pre class="brush: xml;">
@model MyListModel
@{
    AjaxOptions options = new AjaxOptions
    { 
        //&quot;loadEntity&quot; is a javascript method defined on the Index View
        OnComplete = &quot;loadEntity&quot;,
        //&quot;ajax-content&quot; is a div defined on the Index View
        UpdateTargetId = &quot;ajax-content&quot;
    };
}

&lt;!-- Important to give this an Id so that it can be told to reload itself when the 
the entity is updated --&gt;
&lt;table id=&quot;entity-list&quot;&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th&gt;
        Name
      &lt;/th&gt;
          .........            
    &lt;/tr&gt;
  &lt;/thead&gt;
&lt;tbody&gt;
@foreach (var entity in Model) {           
    &lt;tr&gt;
       &lt;td&gt;
            @Ajax.ActionLink(entity.Name, &quot;MyEntity&quot;, new { id = entity.EntityID }, options)
       &lt;/td&gt;
        ......
     &lt;/tr&gt;
 }
  &lt;/tbody&gt;
&lt;tfoot&gt;
  &lt;tr&gt;
    &lt;td colspan=&quot;4&quot;&gt;
        @Ajax.ActionLink(&quot;New Entity&quot;, &quot;MyEntity&quot;, options)
    &lt;/td&gt;
  &lt;/tr&gt;
&lt;/tfoot&gt;
&lt;/table&gt;


</pre>
</pre>
<h4>The Details View</h4>
<p>This is the edit form, and it will display in a modal dialog all going well. The key points are</p>
<ul>
<li>
The use of an id for the form, so that it can be submitted when the Save button is clicked.</p>
<li>
<li>
 the use of the <code>Ajax.BeginForm</code> to apply unobtrusive Ajax enabling of the form and the corresponding <code>AjaxOptions</code>,
</li>
<li>
the use of a hidden legend in the fieldset, the text of which you might recall is extracted when and used as the dialog title,
</li>
<li>
the setting of unobtrusive validations using script, because Ajax loaded content does not have this happen automagically
</li>
</ul>
<pre><pre class="brush: xml;">
@model DetailViewModel
@{
  AjaxOptions options = new AjaxOptions{
    //always post
    HttpMethod = &quot;post&quot;,
    //replace the existing content in the &quot;ajax-content&quot; element
    InsertionMode = InsertionMode.Replace,
    //defined in the Index view
    UpdateTargetId = &quot;ajax-content&quot;,
    //the callback, defined in the Index view
    OnSuccess = &quot;entityDetailsUpdated&quot;        
  };    
}

@using (Ajax.BeginForm(&quot;MyEntity&quot;, null, options, new { id = &quot;entitydetails&quot; }))
{
  &lt;fieldset&gt;
    &lt;legend style=&quot;display:none&quot;&gt;Entity Details - @Model.Name&lt;/legend&gt;
    @if (ViewBag.Message != null){ 
       &lt;span class=&quot;update-message&quot;&gt;@ViewBag.Message&lt;/span&gt;
    }      
    @Html.ValidationSummary(true)
    &lt;ol class=&quot;formFields&quot;&gt;
      &lt;li&gt;
         @Html.EditorFor(m =&gt; m.EntityDetail.Name)
      &lt;/li&gt;
      .......
    &lt;/ol&gt;
    @Html.HiddenFor(m =&gt; m.EntityDetail.EntityID)
  &lt;/fieldset&gt;  
    
  &lt;script type=&quot;text/javascript&quot;&gt;
    $(function () {
       $.validator.unobtrusive.parse('#entitydetails');            
     });
  &lt;/script&gt;
}

</pre>
</pre>
<h3>Conclusion</h3>
<p>This post has demonstrated how to achieve the user interface pattern for master-Details views with dialogs using ASP.Net MVC, jQuery and unobtrusive Ajax. The same effects can be created using explicit script of course, but the unobtrusive Ajax extensions are a time saver and make your views more succinct.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://xhalent.wordpress.com/2011/05/25/master-details-with-dialog-in-asp-net-mvc-and-unobstrusive-ajax/"><br />
<img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://xhalent.wordpress.com/2011/05/25/master-details-with-dialog-in-asp-net-mvc-and-unobstrusive-ajax/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/xhalent.wordpress.com/287/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/xhalent.wordpress.com/287/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/xhalent.wordpress.com/287/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/xhalent.wordpress.com/287/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/xhalent.wordpress.com/287/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/xhalent.wordpress.com/287/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/xhalent.wordpress.com/287/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/xhalent.wordpress.com/287/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/xhalent.wordpress.com/287/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/xhalent.wordpress.com/287/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/xhalent.wordpress.com/287/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/xhalent.wordpress.com/287/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/xhalent.wordpress.com/287/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/xhalent.wordpress.com/287/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=xhalent.wordpress.com&amp;blog=17892286&amp;post=287&amp;subd=xhalent&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://xhalent.wordpress.com/2011/05/25/master-details-with-dialog-in-asp-net-mvc-and-unobstrusive-ajax/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/59d165db24237b353d07fab21cc0897e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">xhalent</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://xhalent.wordpress.com/2011/05/25/master-details-with-dialog-in-asp-net-mvc-and-unobstrusive-ajax/" medium="image">
			<media:title type="html">kick it on DotNetKicks.com</media:title>
		</media:content>
	</item>
		<item>
		<title>Accessing Embedded Resources from Razor Views in ASP.Net MVC</title>
		<link>http://xhalent.wordpress.com/2011/05/14/accessing-embedded-resources-from-razor-views-in-asp-net-mvc/</link>
		<comments>http://xhalent.wordpress.com/2011/05/14/accessing-embedded-resources-from-razor-views-in-asp-net-mvc/#comments</comments>
		<pubDate>Sat, 14 May 2011 09:41:44 +0000</pubDate>
		<dc:creator>xhalent</dc:creator>
				<category><![CDATA[Razor]]></category>
		<category><![CDATA[aspnet.mvc]]></category>
		<category><![CDATA[Embedded Resources]]></category>

		<guid isPermaLink="false">http://xhalent.wordpress.com/?p=284</guid>
		<description><![CDATA[In razor, there is no access to the ClientScriptManager so there is no readily available method of using that class&#8217;s useful GetWebResourceUrl method to retrieve embedded resources. There are few techniques for synthesizing the functionality, revolving around the reflection of &#8230; <a href="http://xhalent.wordpress.com/2011/05/14/accessing-embedded-resources-from-razor-views-in-asp-net-mvc/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=xhalent.wordpress.com&amp;blog=17892286&amp;post=284&amp;subd=xhalent&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In razor, there is no access to the <code>ClientScriptManager</code> so there is no readily available method of using that class&#8217;s useful <code>GetWebResourceUrl</code> method to retrieve embedded resources. There are few techniques for synthesizing the functionality, revolving around the reflection of the <code>AssemblyResourceLoader</code> class which is all fine and well unless the application trust level prohibits reflection of non-public members. A simpler and pragmatic method is to have a partial view of the old <b>ascx</b> variety, and have it access the ClientScript manager of it&#8217;s Page property as below:</p>
<pre><pre class="brush: xml;">
&lt;%@ Control Language=&quot;C#&quot; Inherits=&quot;System.Web.Mvc.ViewUserControl&lt;dynamic&gt;&quot; %&gt;
&lt;script 
     src=&quot;&lt;%=Page.ClientScript.GetWebResourceUrl(typeof(Page), &quot;WebForms.js&quot;)%&gt;&quot; 
     type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
</pre></pre>
<p>Note I&#8217;m referencing WebForms.js because I&#8217;m momentarily insane. I wouldn&#8217;t recommend it in practice !! <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> . To include this web resource in a razor layout page is the same as for any partial view:</p>
<pre><pre class="brush: xml;">

&lt;head&gt;
    &lt;title&gt;@ViewBag.Title&lt;/title&gt;
    &lt;link href=&quot;@Url.Content(&quot;~/Content/Site.css&quot;)&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
    &lt;script 
        src=&quot;@Url.Content(&quot;~/Scripts/jquery-1.5.1.min.js&quot;)&quot; 
        type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;!-- render using as ascx control to access the client script manager --&gt;
    @{Html.RenderPartial(&quot;WebResources&quot;);}
&lt;/head&gt;

</pre></pre>
<p>And that&#8217;s all there is to it. Using this technique enable to continue using embedded resources from within your razor views.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/xhalent.wordpress.com/284/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/xhalent.wordpress.com/284/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/xhalent.wordpress.com/284/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/xhalent.wordpress.com/284/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/xhalent.wordpress.com/284/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/xhalent.wordpress.com/284/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/xhalent.wordpress.com/284/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/xhalent.wordpress.com/284/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/xhalent.wordpress.com/284/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/xhalent.wordpress.com/284/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/xhalent.wordpress.com/284/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/xhalent.wordpress.com/284/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/xhalent.wordpress.com/284/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/xhalent.wordpress.com/284/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=xhalent.wordpress.com&amp;blog=17892286&amp;post=284&amp;subd=xhalent&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://xhalent.wordpress.com/2011/05/14/accessing-embedded-resources-from-razor-views-in-asp-net-mvc/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/59d165db24237b353d07fab21cc0897e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">xhalent</media:title>
		</media:content>
	</item>
		<item>
		<title>Localization of Dates in ASP.Net MVC</title>
		<link>http://xhalent.wordpress.com/2011/05/14/localization-of-dates-in-asp-net-mvc/</link>
		<comments>http://xhalent.wordpress.com/2011/05/14/localization-of-dates-in-asp-net-mvc/#comments</comments>
		<pubDate>Sat, 14 May 2011 07:07:17 +0000</pubDate>
		<dc:creator>xhalent</dc:creator>
				<category><![CDATA[ASP.Net MVC]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Razor]]></category>
		<category><![CDATA[aspnet.mvc]]></category>
		<category><![CDATA[datepicker]]></category>
		<category><![CDATA[globalization]]></category>
		<category><![CDATA[localization]]></category>

		<guid isPermaLink="false">http://xhalent.wordpress.com/?p=277</guid>
		<description><![CDATA[Introduction It is a somewhat inconvenient truth that users of your web site are everywhere but they don&#8217;t all talk the same language or even do simple things like read dates in the same way. ASP.Net prov ides rich support &#8230; <a href="http://xhalent.wordpress.com/2011/05/14/localization-of-dates-in-asp-net-mvc/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=xhalent.wordpress.com&amp;blog=17892286&amp;post=277&amp;subd=xhalent&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>
It is a somewhat inconvenient truth that users of your web site are everywhere but they don&#8217;t all talk the same language or even do simple things like read dates in the same way. ASP.Net prov ides rich support for globalization. This post covers the localization of dates, the different treatment ASP.Net applies to dates received in a QueryString to those in posted fields and provides some techniques to mitigate any issues caused by this different treatment.</p>
<h3>ASP.Net treats Dates in URL&#8217;s different to POST fields</h3>
<p>This came as a surprise to me. When ASP.MVC binds values from POSTed fields, it applies the current culture, but when it binds values from the URL (querystring) is uses the Invariant Culture.</p>
<p>This can result in unpleasant effects, particularly if like me (programming in Australia) want dates in the format day-month-year, and not the invariant month-day-year.</p>
<p>Say you had a form with a input field for dates. If the user entered ‘14/5/2011’ and the form was submitted via GET instead of POST, MVC would complain that this was not a valid date. If you submit the form via POST, MVC would bind the date correctly.</p>
<p>I wrote to Phil Haack about this:</p>
<p><i>Hi Phil,I noticed this one today. I&#8217;m in Australia (en-AU), so it common to use dates of the form dd/mm/yyyy.When these fields are POSTed, the values are as expected, because the ValueProviderResult is being constructed with the CurrentCulture out of the Mvc.FormCollection.But when the string is submitted via GET, the NameValueProvider is creating a ValueProviderResult with the Invariant culture, which is different to the current culture, and it doesn&#8217;t believe that 29/4/2011 is a valid date (29 April 2011). Most upsetting !</i></p>
<p>He replied thus</p>
<p><i>Yeah. We made a conscious choice that values pulled from the URL would be culture invariant. The reason is that URLs must be uniform. So if I send you the URL, it shouldn’t change its meaning whether the person clicking it is in AU or in US.</i></p>
<p>I can&#8217;t say I&#8217;m convinced as to his reasoning. It kind of assumes that URL&#8217;s are static and only accessed by &#8216;clicking&#8217;. But a form submitted via GET is a totally different interaction to a mere click. This logic more or less requires unless the server current culture somewhat reflects the invariant culture (ie you&#8217;re in the US) you should POST your forms. Consider the following simple page:</p>
<pre><pre class="brush: xml;">
@model TestDates.Models.HomeModel
&lt;html&gt;
&lt;head&gt;
    
    &lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;@Url.Content(&quot; content ~ site.css?)?&gt;
    &lt;script src=&quot;@Url.Content(&quot;~/Scripts/jquery-1.5.1.min.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;


@using (Html.BeginForm(&quot;Index&quot;, &quot;Home&quot;, FormMethod.Get))
{ 
    @Html.ValidationSummary(true)
    @Html.LabelFor(m =&amp;gt; m.SubmissionDate);    
    @Html.TextBoxFor(m =&amp;gt; m.SubmissionDate, new { type = &quot;date&quot; })
    @Html.ValidationMessageFor(m =&amp;gt; m.SubmissionDate);
    
    &lt;input value=&quot;submit&quot; type=&quot;submit&quot;&gt;
}


</pre></pre>
<p>Assuming that using a cultre with a date format dd/MM/yyyy, if you fire up this page and enter a date of say &#8217;14/5/2010&#8242;, you will get an error from the server:&#8221;The value &#8217;14/5/2010&#8242; is not valid for SubmissionDate&#8221;. Not ideal!! This is a bit of a restriction but there is a workaround. You need to hook into the form submit event, get the URL the form was going to send, including it&#8217;s serialized field information and manually find and replace date fields with their equivalent invariant values. Then manually submit the form and cancel the default event. This is done using the script below:</p>
<pre><pre class="brush: jscript;">
&lt;script type=&quot;text/javascript&quot;&gt;
    $('form').submit(function (e) {
        //serialize the form
        var data = $(this).serialize();
	//find the url that the form was going to submit itself to
        var url = $(this).attr('action');

	//now replace every instance of a date with the equivalent ISO-8601 value
        data = data.replace(/(\d{1,2})%2F(\d{1,2})%2F(\d{4})/g, &quot;$3%2F$2%2F$1&quot;);

	//append the url and change the window location
        if (url.match(/\?/)) {
            window.location.href = url + '&amp;amp;' + data;
        } else {
            window.location.href = url + '?' + data;
        }

	//prevent the default action
        e.preventDefault();
    });
&lt;/script&gt;

</pre></pre>
<p>If you run this and submit, then the date will be parsed correctly. However a problem exists &#8211; when the date is displayed to the user, it is in the format posted to the server, so although the user typed dd/MM/yyyy, MVC saw yyyy/MM/dd in the query string and this is the format returned to the user. To get around this, you need to ensure that the users local or preferred culture is automatically set from the user&#8217;s browser by setting the following web.config element:</p>
<pre><pre class="brush: xml;">
 &lt;system.web&gt;
    &lt;globalization responseEncoding=&quot;UTF-8&quot; 
                       requestEncoding=&quot;UTF-8&quot; 
                       culture=&quot;auto&quot; 
                       uiCulture =&quot;auto&quot; /&gt;
	.....
 &lt;/system.web&gt;
</pre></pre>
<p>This will result in output to the browser of, for example, dd/MM/yyyy for en-AU, MM/dd/yyyy for en-US and YYYY/MM/dd for ja-JP.</p>
<p>The problem still remains in that I want the date to come back to the browser in an invariant manner, so I&#8217;m going to modify my submit script to take into the current culture and always submit the date in yyyy/mm/dd format &#8211; ISO-8601 format. But because the relative positions of date, months and years can change between cultures, I need to work out the positions before applying the respective replacement regex. To do this, I create a test date and format it to a string in the current UI Culture and test what the first element is. That tells me whether the date or month or year comes first. I can then render the appropriate regex accordingly.So instead of:</p>
<pre><pre class="brush: csharp;">

data = data.replace(/(\d{1,2})%2F(\d{1,2})%2F(\d{4})/g, &quot;$3%2F$2%2F$1&quot;);

</pre></pre>
<p>I need to use some Razor C# when rendering the script block as follows:</p>
<pre><pre class="brush: csharp;">

....//following on previous script
@{        
  //create a known date 
  string testDate = new DateTime(2000, 10, 30).ToString(&quot;d&quot;);

  //replace the known values for years, months and days 
  //with the replacement regex expressions
  string dateRegex = testDate.Replace(&quot;2000&quot;, @&quot;(\d{4})&quot;)
     .Replace(&quot;10&quot;, @&quot;(\d{1,2})&quot;).Replace(&quot;30&quot;, @&quot;(\d{1,2})&quot;).Replace(&quot;/&quot;, &quot;%2F&quot;);

  //see if the produced date starts with the date component
  if(testDate.StartsWith(&quot;30&quot;)){
    @:data = data.replace(/@dateRegex/g, &quot;$3%2F$2%2F$1&quot;);                           
  }
  //see if it starts with the month component
  else if(testDate.StartsWith(&quot;10&quot;)){
    @:data = data.replace(/@dateRegex/g, &quot;$3%2F$1%2F$2&quot;);
  }  
  //it starts with the year component so no work to be done
}

....//continuing on with the script

</pre></pre>
<p>Obviously you can extend the logic to test for date culture formats such as yyyy/dd/MM or dd/yyyy/MM (if such cultures exist) but I hope you get the point.</p>
<h3>Localization and jQuery datepicker</h3>
<p>It is worth noting how to switch the jquery datepicker localization. It&#8217;s simply a matter of dynamically setting the localization js as follows:</p>
<pre><pre class="brush: xml;">
&lt;head&gt;
    &lt;title&gt;@ViewBag.Title&lt;/title&gt;
    &lt;link href=&quot;@Url.Content(&quot;~/Content/Site.css&quot;)&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
    &lt;link href=&quot;../../Content/themes/base/jquery.ui.all.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt;
    &lt;script src=&quot;@Url.Content(&quot;~/Scripts/jquery-1.5.1.min.js&quot;)&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;../../Scripts/jquery-ui-1.8.11-min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    
    &lt;!-- set the localization file based on the current culture --&gt;
    &lt;script src=&quot;../../Scripts/jquery.ui.datepicker-@(UICulture).js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
</pre></pre>
<h3>Conclusion</h3>
<p>This post has demonstrated the vagaries of localizing dates using ASP.Net MVC, and presented a few methods to provide a consistent date experience to the user, regardless of their culture.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/xhalent.wordpress.com/277/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/xhalent.wordpress.com/277/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/xhalent.wordpress.com/277/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/xhalent.wordpress.com/277/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/xhalent.wordpress.com/277/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/xhalent.wordpress.com/277/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/xhalent.wordpress.com/277/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/xhalent.wordpress.com/277/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/xhalent.wordpress.com/277/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/xhalent.wordpress.com/277/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/xhalent.wordpress.com/277/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/xhalent.wordpress.com/277/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/xhalent.wordpress.com/277/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/xhalent.wordpress.com/277/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=xhalent.wordpress.com&amp;blog=17892286&amp;post=277&amp;subd=xhalent&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://xhalent.wordpress.com/2011/05/14/localization-of-dates-in-asp-net-mvc/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/59d165db24237b353d07fab21cc0897e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">xhalent</media:title>
		</media:content>
	</item>
		<item>
		<title>Custom Unobstrusive Jquery Validation in ASP.Net MVC 3 using DataAnnotationsModelValidatorProvider</title>
		<link>http://xhalent.wordpress.com/2011/05/12/custom-unobstrusive-jquery-validation-in-asp-net-mvc-3-using-dataannotationsmodelvalidatorprovider/</link>
		<comments>http://xhalent.wordpress.com/2011/05/12/custom-unobstrusive-jquery-validation-in-asp-net-mvc-3-using-dataannotationsmodelvalidatorprovider/#comments</comments>
		<pubDate>Thu, 12 May 2011 13:50:38 +0000</pubDate>
		<dc:creator>xhalent</dc:creator>
				<category><![CDATA[ASP.Net MVC]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[unobtrusive validation]]></category>

		<guid isPermaLink="false">http://xhalent.wordpress.com/?p=262</guid>
		<description><![CDATA[Introduction In a previous post I covered the use of Custom Unobrusive Validation in ASP.Net MVC using the IClientValidatable. The use of this interface may not always be possible, for example if the validation attribute is defined in an assembly &#8230; <a href="http://xhalent.wordpress.com/2011/05/12/custom-unobstrusive-jquery-validation-in-asp-net-mvc-3-using-dataannotationsmodelvalidatorprovider/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=xhalent.wordpress.com&amp;blog=17892286&amp;post=262&amp;subd=xhalent&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>In a previous <a href="http://xhalent.wordpress.com/2011/01/27/custom-unobstrusive-jquery-validation-in-asp-net-mvc-3/">post</a> I covered the use of Custom Unobrusive Validation in ASP.Net MVC using the <code>IClientValidatable</code>. The use of this interface may not always be possible, for example if the validation attribute is defined in an assembly that cannot reference the MVC assembly, or such a reference makes no sense. Under these circumstances, there is another approach to take and that is to use adapters to help the MVC assign the client side validation to apply for a given validation attribute.</p>
<h3>Server side code</h3>
<p>I&#8217;ll use the same example as last time, that is a check sum validator for Australian Business and Company Numbers, but in this case I will not be implementing <code>IClientValidatable</code>.</p>
<pre><pre class="brush: csharp;">
public abstract class CheckSumNumberAttribute : ValidationAttribute{                       

  private string checkSumType;

  protected CheckSumNumberAttribute(string checkSumType){
    this.checkSumType = checkSumType;
  }

  public string CheckSumType{
    get {return checkSumType;}
  }
}
</pre>
</pre>
<p>The implementations of two concrete classes <code>AustralianBusinessNumberAttribute</code> and <code>AustralianCompanyNumberAttribute</code>  remain the same.</p>
<pre><pre class="brush: csharp;">
public class AustralianBusinessNumberAttribute : CheckSumNumberAttribute{
  private static int[] ABN_WEIGHT = { 10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19 };
  private static Regex ABNRegex = new Regex(&quot;\\d{11}&quot;);

  public AustralianBusinessNumberAttribute() : base(&quot;abn&quot;) { }

  public override bool IsValid(object val){
    string ABN = val as string;
    bool valid = false;
    if (ABN != null){
      ABN = ABN.Replace(&quot; &quot;, &quot;&quot;).Trim();
    }

    if (string.IsNullOrEmpty(ABN)){
      return true;
    }

    if (!ABNRegex.IsMatch(ABN)){
      return false;
    }

    int sum = 0;
    try{
      for (int i = 0; i &lt; ABN_WEIGHT.Length; i++){
        // Subtract 1 from the first left digit before multiplying against the weight
        if (i == 0){
          sum = (Convert.ToInt32(ABN.Substring(i, 1)) - 1) * ABN_WEIGHT[i];
        }else{
          sum += Convert.ToInt32(ABN.Substring(i, 1)) * ABN_WEIGHT[i];
        }
      }
      valid = (sum % 89 == 0);
    }
    catch{
      valid = false;
    }
    return valid;
  }
}


public class AustralianCompanyNumberAttribute : CheckSumNumberAttribute{
  private static int[] ACN_WEIGHT = { 8, 7, 6, 5, 4, 3, 2, 1 };
  private static Regex ACNRegex = new Regex(&quot;\\d{9}&quot;);

  public AustralianCompanyNumberAttribute(): base(&quot;acn&quot;){}

  public override bool IsValid(object val){
    string ACN = val as string;
    bool valid = false;

    if (ACN != null){
      ACN = ACN.Replace(&quot; &quot;, &quot;&quot;).Trim();
    }

    if (string.IsNullOrEmpty(ACN)){
      return true;
    }

    if (!ACNRegex.IsMatch(ACN)){
      return false;
    }

    int remainder = 0;
    int sum = 0;
    int calculatedCheckDigit = 0;

    try{
      // Sum the multiplication of all the digits and weights
      for (int i = 0; i &lt; ACN_WEIGHT.Length; i++){
        sum += Convert.ToInt32(ACN.Substring(i, 1)) * ACN_WEIGHT[i];
      }

      // Divide by 10 to obtain remainder
      remainder = sum % 10;

      // Complement the remainder to 10
      calculatedCheckDigit = (10 - remainder == 10) ? 0 : (10 - remainder);

      // Compare the calculated check digit with the actual check digit
      valid = (calculatedCheckDigit == Convert.ToInt32(ACN.Substring(8, 1)));
    }
    catch{
      valid = false;
    }
    return valid;
  }
}
</pre>
</pre>
<p>Without the <code>IClientValidatble</code> interface, we need to create a &#8220;buddy&#8221; class of type <code> DataAnnotationsModelValidator&lt;TValidationAttribute&gt;</code> that MVC will use to create the <code>data-val</code> information for a given validator.</p>
<pre><pre class="brush: csharp;">
public class CheckSumValidator : 
  DataAnnotationsModelValidator&lt;CheckSumNumberAttribute&gt;{
  private string errorMessage;
  private string checkSumType;

  public RelatedDatesValidator(
      ModelMetadata metadata, ControllerContext context, CheckSumNumberAttribute attribute)
    : base(metadata, context, attribute){
     this.errorMessage = attribute.FormatErrorMessage(metadata.DisplayName);
     this.checkSumType = &quot;checksum&quot;;
  }

  public override IEnumerable&lt;ModelClientValidationRule&gt; GetClientValidationRules(){
    var rule = new ModelClientValidationRule{
      ErrorMessage = this.errorMessage,
      ValidationType = this.validationType
    };

    rule.ValidationParameters.Add(&quot;checksumtype&quot;, checkSumType);
    yield return rule;
  }
}
</pre></pre>
<p>Having defined the adapter class, it is neccesary to register the adapter with the <code>DataAnnotationsModelValidatorProvider</code> for the validation attribute. Global.asax is a good place to do this.</p>
<pre>
<pre class="brush: csharp;">
protected void Application_Start(){
    .....
  DataAnnotationsModelValidatorProvider
     .RegisterAdapter(
         typeof(CheckSumNumberAttribute&gt;), 
         typeof(CheckSumValidator));
    .....
}
</pre></pre>
<h3>Client side code</h3>
<p>The javascript required for the client side validation also remains the same as per the previous post, but here is it again for completeness.</p>
<pre><pre class="brush: jscript;">
var Xhalent = Xhalent || {};

Xhalent.validateABN = function (value) {

  value = value.replace(/[ ]+/g, '');

  if (!value.match(/\d{11}/)) {
    return false;
  }

  var weighting = [10, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19];

  var tally = (parseInt(value.charAt(0)) - 1) * weighting[0];

  for (var i = 1; i &lt; value.length; i++) {
    tally += (parseInt(value.charAt(i)) * weighting[i]);
  }

  return (tally % 89) == 0;
};

Xhalent.validateACN = function (value) {
  value = value.replace(/[ ]+/g, '');

  if (!value.match(/\d{9}/)) {
    return false;
  }

  var weighting = [8, 7, 6, 5, 4, 3, 2, 1];
  var tally = 0;
  for (var i = 0; i &lt; weighting.length; i++) {
    tally += (parseInt(value.charAt(i)) * weighting[i]);
  }

  var check = 10 - (tally % 10);
  check = check == 10 ? 0 : check;

  return check == parseInt(value.charAt(i));
};

//get reference to global jquery validator object and addMethod named 'xhalent_checksum'
$.validator.addMethod(&quot;xhalent_checksum&quot;, function (value, element, checksumtype) {
  if (value == null || value.length == 0) {
    return true;
  }

  if(checksumtype == 'abn') {
    return Xhalent.validateABN(value);
  }else if (checksumtype == 'acn') {
    return Xhalent.validateACN(value);
  }
});

//register the method with the unobtrusive validator library
$.validator.unobtrusive.adapters.addSingleVal('checksum', 'checksumtype', 'xhalent_checksum');

</pre></pre>
<p>Of course, my caveats about placing this script after the dependant javascript libraries have been loaded still apply.</p>
<h3>Conclusion</h3>
<p>This post have demonstrated how to use Custom Unobstrusive Jquery Validation in ASP.Net MVC 3 using DataAnnotationsModelValidatorProvider instead of IClientValidatable. This is a suitable solution where it is not possible to decorate an attribute the the IClientValidatable interface or it is inappropriate to reference the MVC library from the assembly the validation attribute is defined in.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/xhalent.wordpress.com/262/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/xhalent.wordpress.com/262/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/xhalent.wordpress.com/262/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/xhalent.wordpress.com/262/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/xhalent.wordpress.com/262/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/xhalent.wordpress.com/262/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/xhalent.wordpress.com/262/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/xhalent.wordpress.com/262/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/xhalent.wordpress.com/262/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/xhalent.wordpress.com/262/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/xhalent.wordpress.com/262/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/xhalent.wordpress.com/262/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/xhalent.wordpress.com/262/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/xhalent.wordpress.com/262/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=xhalent.wordpress.com&amp;blog=17892286&amp;post=262&amp;subd=xhalent&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://xhalent.wordpress.com/2011/05/12/custom-unobstrusive-jquery-validation-in-asp-net-mvc-3-using-dataannotationsmodelvalidatorprovider/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/59d165db24237b353d07fab21cc0897e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">xhalent</media:title>
		</media:content>
	</item>
		<item>
		<title>Javascript Closures</title>
		<link>http://xhalent.wordpress.com/2011/05/12/javascript-closures/</link>
		<comments>http://xhalent.wordpress.com/2011/05/12/javascript-closures/#comments</comments>
		<pubDate>Thu, 12 May 2011 13:07:36 +0000</pubDate>
		<dc:creator>xhalent</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[closures]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://xhalent.wordpress.com/?p=256</guid>
		<description><![CDATA[Introduction Following on from my previous article on javascript object creation and objects, arrays and associative arrays, I am now going to cover the concept of call-scope and closures in JavaScript. Understanding scopes In common with most languages, JavaScript has &#8230; <a href="http://xhalent.wordpress.com/2011/05/12/javascript-closures/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=xhalent.wordpress.com&amp;blog=17892286&amp;post=256&amp;subd=xhalent&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h3>Introduction</h3>
<p>Following on from my previous article on <a href="http://xhalent.wordpress.com/2011/02/16/javascript-object-instantiation-and-prototypes/">javascript object creation</a> and <a href="http://xhalent.wordpress.com/2011/01/21/javascript-arrays-objects-and-associative-arrays/">objects, arrays and associative arrays</a>, I am now going to cover the concept of call-scope and closures in JavaScript.</p>
<h3>Understanding scopes</h3>
<p>In common with most languages, JavaScript has the concept of scope. Scope defines what objects are visible to a body of code at runtime. In JavaScript script the variables in scope are those in scope at the time the function was created or assigned. Variables defined in the global scope are visible to all code so long as the variable or object has been declared prior to the code in question:</p>
<pre><pre class="brush: jscript;"> 
var x = 1;

function sumFunc(y)
{   
    alert(x+y);
}

sumFunc(3);

//the value of x is visible within the function sunFunc().
</pre>
</pre>
<p>JavaScript code is run in the context of a call object, which contains references to all accessible variables. Each new function or frame results in a new call object being chained onto the previous (parent) one, with the properties of the parent scope being available in the child scope. Additionally, any variables declared within the new function, and any parameters, will be properties on the child scope. If a child scope defines variables or arguments that have the same name as a property of the parent scope, they will hide the parent scope<br />
s instance.</p>
<p>
Examining what is going on above, when <code>sumFunc</code> is called, the global scope contains x. The child scope has inherited the property &#8216;x&#8217; and added a new property &#8216;y&#8217; which was in the parameters. When the function ends, there will be no more references to the child scope and it will be disposed of by the garbage collection. The value &#8216;y&#8217; will not be available to any code. Consider if we change the code slightly:
</p>
<pre><pre class="brush: jscript;"> 
var x = 1;

function sumFunc(y)
{   
    return function(){alert(x+y);};
}

var f1 = sumFunc(3);
var f2 = sumFunc(4);

f1();
f2();

</pre>
</pre>
<p>
If you run this code, you will get 4 and 5 displayed, respectively. What is happening is that each invocation of <code>sumFunc</code> results in a new instance of the nested function being created in the current scope, with their unique value of the parameter &#8216;y&#8217;. Exiting the function has not led to the scope being destroyed because the nested function in it&#8217;s construction attains a reference to the current scope.
</p>
<p>
Where closures are interesting is that although JavaScript does not have the concept of private variables, the use of closures can synthesize private members successfully. Consider the following script. I want to create a function that returns the next number whenever it is called.</p>
<p>I create a function that defines a local variable <code>iNext</code> and return from the function a nested function that refers back to <code>iNext</code>. Any function I create in this child scope will always be able to reference the value of <code>iNext</code>. Now when <code>uniqueID</code> is called, the function can reference the variable <code>iNext</code> because it was in scope when the function was created (it doesn&#8217;t matter if it is in scope when the function is called).
</p>
<pre><pre class="brush: jscript;"> 
var uniqueID = (function(){
    var iNext = 0;   
    return function(){return iNext++;};
})();

alert(uniqueID());
alert(uniqueID());
alert(uniqueID());
alert(uniqueID());

</pre>
</pre>
<p>
The really interesting point is that <code>iNext</code> is not programmatically accessible in code. This technique can be extended to synthesize private functions. In the following script the function <code>getSquare</code> is not accessible through code once the self-executing function has run.
</p>
<pre><pre class="brush: jscript;"> 
var uniqueID = (function(){
    var iNext = 0;   
    var iPower = 0;
    function getSquare(){
        return Math.pow(iNext,iPower);
    }
    
    return function(){return getSquare(iNext+=2, iPower++);};
})();

alert(uniqueID());
alert(uniqueID());
alert(uniqueID());
alert(uniqueID());


</pre>
</pre>
<p>
The closure of a function is evaluated when the function is assigned to a variable. Consider the following code. When the prototype method <code>area</code> is assigned to the newly created object, &#8216;this&#8217; is in scope and is the object being constructed. When the function is copied into a global variable, the value of &#8216;this&#8217; is evaluated again and this time it is the global window object, which does not have a value for width or height.
</p>
<pre><pre class="brush: jscript;"> 
function Rect(width,height){
  this.width = width;
  this.height = height;
};

Rect.prototype = {
  area:function(){
      return this.width * this.height;     
   }
};

//create a new rect object
var rect= new Rect(10,5);

//this will output 50
alert(rect.area());

var copyOfArea = rect.area;

//this will alert NaN
alert(copyOfArea());

</pre>
</pre>
<p>
If we were to add two global variables width and height to the global window object, then <code>copyOfArea</code> would be the product of those two numbers.</p>
<p>It can be seen now why it is necessary to prefix all calls to properties and function for an object with the &#8216;this&#8217; keyword. At the time of construction, &#8216;this&#8217; is the object being constructed and all the properties relate to that instance only. That is how properties and function make up a javscript object &#8211; through the shared call context when the object is constructed.
</p>
<p>Be aware it is <b>important</b> to remember that when coding event handlers that the value &#8216;this&#8217; is not taken for granted. Consider the following script.</p>
<pre><pre class="brush: jscript;"> 
function MyObj(){
  this.SpecialName = &quot;myobj&quot;;
 
    jQuery('#someButton').click(function(){        
        alert(this.SpecialName);
    });
};

var r = new MyObj();
</pre>
</pre>
<p>If a button with Id &#8220;someButton&#8221; was clicked, the value of <code>this.SpecialName</code> would be undefined. That is because the value of &#8220;this&#8221; is different to the value of &#8220;this&#8221; when the object was created.</p>
<p>The correct approach for referencing an object from within a delegated function is take a local reference to &#8220;this&#8221; and have the function use it instead as below:</p>
<pre><pre class="brush: jscript;"> 
function MyObj(){
  this.SpecialName = &quot;myobj&quot;;
   var _this = this;
    jQuery('#someButton').click(function(){        
        alert(_this.SpecialName);
    });
};

var r = new MyObj();
</pre>
</pre>
<h3>Conclusion</h3>
<p>This post has covered the basics of closures in JavaScript. It was shown that functions are a combination of both the their code and the context or scope in which they are called. Interesting closures can be created by returning nested functions from functions containing local variables or methods, and in doing do private members can be synthesized. It is important to keep in mind how scopes can result in the value of &#8220;this&#8221; being overwritten in event handlers, and a safe approach under these circumstances is refer to a local reference of the &#8220;this&#8221; object prior to declaring the event handler.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/xhalent.wordpress.com/256/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/xhalent.wordpress.com/256/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/xhalent.wordpress.com/256/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/xhalent.wordpress.com/256/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/xhalent.wordpress.com/256/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/xhalent.wordpress.com/256/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/xhalent.wordpress.com/256/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/xhalent.wordpress.com/256/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/xhalent.wordpress.com/256/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/xhalent.wordpress.com/256/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/xhalent.wordpress.com/256/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/xhalent.wordpress.com/256/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/xhalent.wordpress.com/256/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/xhalent.wordpress.com/256/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=xhalent.wordpress.com&amp;blog=17892286&amp;post=256&amp;subd=xhalent&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://xhalent.wordpress.com/2011/05/12/javascript-closures/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/59d165db24237b353d07fab21cc0897e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">xhalent</media:title>
		</media:content>
	</item>
		<item>
		<title>A few ideas to improve NHibernate performance</title>
		<link>http://xhalent.wordpress.com/2011/03/24/a-few-ideas-to-improve-nhibernate-performance/</link>
		<comments>http://xhalent.wordpress.com/2011/03/24/a-few-ideas-to-improve-nhibernate-performance/#comments</comments>
		<pubDate>Thu, 24 Mar 2011 12:52:29 +0000</pubDate>
		<dc:creator>xhalent</dc:creator>
				<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[nhibernate]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://xhalent.wordpress.com/?p=250</guid>
		<description><![CDATA[I’m currently working a project with a major focus on insert – throughput and I’d thought I mention a few things I’ve done to improve that throughout that are departures from your typical CRUD .Net application. Don’t use identities. They &#8230; <a href="http://xhalent.wordpress.com/2011/03/24/a-few-ideas-to-improve-nhibernate-performance/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=xhalent.wordpress.com&amp;blog=17892286&amp;post=250&amp;subd=xhalent&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I’m currently working a project with a major focus on insert – throughput and I’d thought I mention a few things I’ve done to improve that throughout that are departures from your typical CRUD .Net application.</p>
<ul>
<li>Don’t use identities. </li>
<ul>
<li>They require an additional read immediately after inserting</li>
<li>They defeat insert batching</li>
</ul>
<li>Use Guid.Comb instead</li>
<ul>
<li>Creates Guids with just enough order to enable SqlServer to index effectively</li>
<li>Generated by NHibernate without a round trip to the server.</li>
<li>Enables deferment on inserts</li>
<li>Enables insert batching</li>
</ul>
<li>Lock only aggregate roots and not every entity</li>
<ul>
<li>Control entity access through repositories for each aggregate root entity.</li>
</ul>
<li>Use pessimistic locking instead of optimistic locking (with timestamps/versions)</li>
<ul>
<li>Using a timestamp results in an additional read after each insert or update</li>
<li>Defeats batching</li>
</ul>
<li>Use a table per hierarchy instead of a table per subclass (which is the default)</li>
<ul>
<li>A joined-subclass table strategy requires two inserts, one to the primary table and then the a second to the joined table.</li>
<li>Can’t be batched</li>
</ul>
<li>Look hard at inheritance hierarchies. Batching only works for entities of the same type, so subclass entities cannot be batched with their base types. I whittled down a few classes and opted for null-properties (exposed as components) rather than subclass – you shouldn’t be building a hierarchy based on data anyway, but behaviour.</li>
<li>Use second level caching for reference objects. I had a few entities were really almost static in nature but need to be referenced by each inserted record. I used the HashtableCache (not really a enterprise cache) to hold these entities. I am not concerned about the cache growing out of control and growing stale, and the application is not clustered so my choice I think stands up. By caching these entities I save a lot of reads from the database.</li>
</ul>
<p>In general what I have attempted to do is to minimise the calls the database. NHibernate batching is brilliant at this, enabling any number of commands to be issued in a single ADO batch, but it works only under certain conditions.</p>
<p>There were a few other ideas put to me by the local DBA which I haven;t implemented but would consider:</p>
<ul>
<li>Drop foreign key constraints as the constraints are handled at the application layer</li>
<li>Don’t have a primary key on the inserting tables, rather simply have indexed columns. This would enable SqlServer to heap insert rather than B-tree inserts, which if the primary key is sequential might become problematic as the B-tree would need to rebalance.</li>
</ul>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://xhalent.wordpress.com/2011/03/24/a-few-ideas-to-improve-nhibernate-performance/"><br />
<img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://xhalent.wordpress.com/2011/03/24/a-few-ideas-to-improve-nhibernate-performance/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/xhalent.wordpress.com/250/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/xhalent.wordpress.com/250/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/xhalent.wordpress.com/250/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/xhalent.wordpress.com/250/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/xhalent.wordpress.com/250/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/xhalent.wordpress.com/250/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/xhalent.wordpress.com/250/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/xhalent.wordpress.com/250/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/xhalent.wordpress.com/250/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/xhalent.wordpress.com/250/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/xhalent.wordpress.com/250/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/xhalent.wordpress.com/250/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/xhalent.wordpress.com/250/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/xhalent.wordpress.com/250/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=xhalent.wordpress.com&amp;blog=17892286&amp;post=250&amp;subd=xhalent&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://xhalent.wordpress.com/2011/03/24/a-few-ideas-to-improve-nhibernate-performance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/59d165db24237b353d07fab21cc0897e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">xhalent</media:title>
		</media:content>

		<media:content url="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://xhalent.wordpress.com/2011/03/24/a-few-ideas-to-improve-nhibernate-performance/" medium="image">
			<media:title type="html">kick it on DotNetKicks.com</media:title>
		</media:content>
	</item>
		<item>
		<title>Using CodeContracts Reference Assemblies in Client Applications</title>
		<link>http://xhalent.wordpress.com/2011/03/24/using-codecontracts-reference-assemblies-in-client-applications/</link>
		<comments>http://xhalent.wordpress.com/2011/03/24/using-codecontracts-reference-assemblies-in-client-applications/#comments</comments>
		<pubDate>Thu, 24 Mar 2011 12:23:36 +0000</pubDate>
		<dc:creator>xhalent</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[CodeContracts]]></category>

		<guid isPermaLink="false">http://xhalent.wordpress.com/?p=245</guid>
		<description><![CDATA[It is useful when designing interfaces to be able to define the design-contracts for those interfaces, however because interfaces cannot contain code, CodeContracts cannot be written for them directly. Instead, contracts are defined through the of “buddy” contract abstract classes &#8230; <a href="http://xhalent.wordpress.com/2011/03/24/using-codecontracts-reference-assemblies-in-client-applications/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=xhalent.wordpress.com&amp;blog=17892286&amp;post=245&amp;subd=xhalent&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>It is useful when designing interfaces to be able to define the design-contracts for those interfaces, however because interfaces cannot contain code, CodeContracts cannot be written for them directly. Instead, contracts are defined through the of “buddy” contract abstract classes that are not really classes at all, but just place holders for the contracts in the interfaces.</p>
<p>Consider the simple interface below:</p>
<pre>
<pre class="brush: csharp;">
[ContractClass(typeof(MyServiceContracts))]
public interface IMyService{
   string Echo(string str);
}
</pre>
</pre>
<p>To define a simple not null contract, we create a class as follows:</p>
<pre>
<pre class="brush: csharp;">
[ContractClassFor(typeof(IMyService))]
public abstract class MyServiceContracts : IMyService{
  public string Echo(string str){
    Contract.Requires&lt;ArgumentNullException&gt;(str != null);
    return null;
  } 
}
</pre>
</pre>
<p>You can see that the buddy class implements the interface it is the buddy for. Because this buddy class is never intended to be referenced, the actual implementation is not important other than the contracts it defines.</p>
<p>To build the reference assembly, make sure you set the Contract Reference Assembly option to &#8220;Build&#8221; in the project settings, on the Code Contracts tab.</p>
<h3>Using the Reference Assembly</h3>
<p>There was surprisingly little information on how to actually use a reference assembly to enforce constraints on interfaces, so I created a test harness as follows:</p>
<pre>
<pre class="brush: csharp;">
class Program{
  public class MyServiceImpl:IMyService{
    public string Echo(string str){
      throw new NotImplementedException();
    }
  }

  static void Main(string[] args){
    IMyService service = new MyServiceImpl();

    Console.WriteLine(service.Echo(null));
  }
}
</pre>
</pre>
<p>If the contracts worked and enforced at the interface level, then I should get a null argument exception thrown, else if they don&#8217;t work I would get the &#8220;NotImplementedException&#8221;.</p>
<p>I copied the built interfaces assembly to a separate, new folder location on my machine, leaving the CodeContracts assembly alone for now. I then added a reference to the interface assembly from my client code. When I ran the test, I did not get the contract exception. I then checked the code contracts settings for the project to make sure I was enabling full runtime checking. I then noticed that the Assembly Mode was set to &#8220;Custom Parameter Validation&#8221; so I changed it to &#8220;Standard Contract Requires&#8221;, ran the test and still got no contract exception.</p>
<p>I then copied the CodeContracts reference assembly from the first project to the location of the interface assembly and re-ran the test. Still no code contract exception. This was really beginning to bug me.</p>
<p>A burst of inspiration hit me and I re-built the client application (instead of merely re-running it) and well hello, I got the contract exception I was longing for.</p>
<p>I also experimented with locating the contracts reference assembly in the folder called CodeContracts in the same place as the interface assembly, and it works as well.<br />
<h3>Conclusion</h3>
<p>This post has covered how to use contracts reference assemblies in client applications. It is necessary to either co-locate the reference assembly where the real assembly is placed, or in a folder &#8220;CodeContracts&#8221; in that location. It is also necessary to turn on CodeContract runtime checking and use &#8220;Standard Contract Requires&#8221;, and a rebuild is required to pick up CodeContract assemblies.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/xhalent.wordpress.com/245/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/xhalent.wordpress.com/245/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/xhalent.wordpress.com/245/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/xhalent.wordpress.com/245/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/xhalent.wordpress.com/245/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/xhalent.wordpress.com/245/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/xhalent.wordpress.com/245/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/xhalent.wordpress.com/245/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/xhalent.wordpress.com/245/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/xhalent.wordpress.com/245/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/xhalent.wordpress.com/245/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/xhalent.wordpress.com/245/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/xhalent.wordpress.com/245/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/xhalent.wordpress.com/245/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=xhalent.wordpress.com&amp;blog=17892286&amp;post=245&amp;subd=xhalent&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://xhalent.wordpress.com/2011/03/24/using-codecontracts-reference-assemblies-in-client-applications/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/59d165db24237b353d07fab21cc0897e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">xhalent</media:title>
		</media:content>
	</item>
		<item>
		<title>EntityFramework&#8211;What&#8217;s in it for Microsoft?</title>
		<link>http://xhalent.wordpress.com/2011/03/21/entityframeworkwhats-in-it-for-microsoft/</link>
		<comments>http://xhalent.wordpress.com/2011/03/21/entityframeworkwhats-in-it-for-microsoft/#comments</comments>
		<pubDate>Mon, 21 Mar 2011 11:09:27 +0000</pubDate>
		<dc:creator>xhalent</dc:creator>
				<category><![CDATA[Entity Framework]]></category>

		<guid isPermaLink="false">https://xhalent.wordpress.com/2011/03/21/entityframeworkwhats-in-it-for-microsoft/</guid>
		<description><![CDATA[I can’t understand why Microsoft persists with the EntityFramework development. Don’t get me wrong, the project isn’t necessarily terminally flawed or anything, but what is their corporate motivation? Can they go their shareholders and demonstrably show that development of the &#8230; <a href="http://xhalent.wordpress.com/2011/03/21/entityframeworkwhats-in-it-for-microsoft/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=xhalent.wordpress.com&amp;blog=17892286&amp;post=243&amp;subd=xhalent&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I can’t understand why Microsoft persists with the EntityFramework development. Don’t get me wrong, the project isn’t necessarily terminally flawed or anything, but what is their corporate motivation?</p>
<p>Can they go their shareholders and demonstrably show that development of the EntityFramework will increase the companies bottom line?</p>
<p>I don’t think so.</p>
<p>The decision on what data access strategy to use does not drive the choice of server platform or development language. Generally enterprise organisations will have an overall strategy or theme to their suite of applications, with an intention to reduce the technology footprint to maximise the opportunities for re-use both in terms of components and physical resources, including developers.</p>
<p>It is very unlikely, IMHO, that a project in a predominantly unix/java environment would suggest creating a Win2008 stack so that their project can use EntityFramework 4.1. </p>
<p>If you programming web sites hosted in a windows enterprise environment, then you’re going to use .Net (especially if you reading this). You’re not using .Net because of the EntityFramework. If the EntityFramework did not exist then you would still use .Net and host in windows servers. In fact, only a year ago when EntityFramework really, really, was the pits that was exactly what we all did.</p>
<p>Can you seriously imagine in the pre-EntityFramework a developer saying, “hey guys, lets do this in java and hibernate, because, you know, .Net data access is just too hard….”. But that seems like the business problem Microsoft is trying to solve, and I for one just can’t see it.</p>
<p>So, that brings me back to the thrust of my discussion. Microsoft are not going to sell any more licenced products because of the EntityFramework. That means they will not make a cent from it.</p>
<p>How big is the EntityFramework team? I’m not sure, but whatever millions of dollars a year Microsoft is spending on the development I doubt they will ever see a red cent in return.</p>
<p>Microsoft is not a charity. If there aren’t making a dollar from a business activity, how loyal are they going to be to it?</p>
<p>But it’s worse than that. Microsoft haven’t developed a great product, and by freezing development on Linq-2-Sql they’ve burnt social capital. They’ve lumbered themselves with a product that they’ve asked enterprises to trust but knowing that it doesn’t scale up to the needs of enterprises. </p>
<p>There’s a marketing blitz to manage. Books to write, blogs and tweets and whatever people do on Facebook. A new fleet MVP’s spruiking the latest and greatest and demonstrating, once again, how EntityFramework works if you’re designing the worlds simplest blog or dinner invite management program.</p>
<p>So, projects will take on EntityFramework. They might have been directed to by their bosses, or perhaps they themselves feel cosier in the warm embracing bosom of the Microsoft mother ship. They&#8217;ll send of queries to the “support” line at Microsoft wondering about specific features to be told that those features are not supported, and may never be supported, and if we did support them then it would be a scheduled release sometime in the first quarter of the next millennium. You are not going to get a special build, just for you. Are you certainly are not going to be able to compile your own version.</p>
<p>And when it all goes horribly wrong, when entities and contexts and states are sprinkled from the the browser to the database and all the tiers in between (oh, yes – whose ever seen a demo on n-tier implementations of the EntityFramework, and aren’t self tracking POCO objects a contradiction?) and it performs like a dog then the blame will laid at Microsoft’s feet. </p>
<p>I think there is every likelihood that Microsoft will stop development of EntityFramework. Just. Like. That. Wouldn’t that be a pain. Projects already coupled to EF would have a just get by. Perversely, Microsoft are not likely to loose any revenue from this decision.</p>
<p>Consider NHibernate as an alternative. It hasn’t got a profit motive – it is driven by the passion of those core developers and the community that picks up builds and provides feedback. No corporate backer demanding profits and revenue streams, source code free to download and wade through. By any comparison NHibernate is more feature rich than EntityFramework (a direct result of it’s maturity and pedigree). The main complaint with NHibernate is the lack of coherent documentation on all the knobs, levers and other points of extensibility that can be made use of.</p>
<p>I think EntityFramework is a case of corporate “Not Written Here Syndrome”, where software is written in the firm but predominantly mistaken belief that you can write something better than that other, mature product, because you’re a genius and you’re starting from scratch. We’ve all done it. But hopefully at some point we mature out of it.</p>
<p>I want to reflect on the fact that Microsoft supports jQuery, to the benefit of both – it certainly adds keyboard-cred to the ASP.Net MVC platform. In my opinion, Microsoft would have done everyone a favour by getting behind the NHibernate project while enhancing Linq-2-Sql for the small data access tasks. </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/xhalent.wordpress.com/243/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/xhalent.wordpress.com/243/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/xhalent.wordpress.com/243/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/xhalent.wordpress.com/243/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/xhalent.wordpress.com/243/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/xhalent.wordpress.com/243/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/xhalent.wordpress.com/243/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/xhalent.wordpress.com/243/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/xhalent.wordpress.com/243/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/xhalent.wordpress.com/243/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/xhalent.wordpress.com/243/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/xhalent.wordpress.com/243/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/xhalent.wordpress.com/243/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/xhalent.wordpress.com/243/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=xhalent.wordpress.com&amp;blog=17892286&amp;post=243&amp;subd=xhalent&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://xhalent.wordpress.com/2011/03/21/entityframeworkwhats-in-it-for-microsoft/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/59d165db24237b353d07fab21cc0897e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">xhalent</media:title>
		</media:content>
	</item>
		<item>
		<title>Javascript Object Instantiation and Prototypes</title>
		<link>http://xhalent.wordpress.com/2011/02/16/javascript-object-instantiation-and-prototypes/</link>
		<comments>http://xhalent.wordpress.com/2011/02/16/javascript-object-instantiation-and-prototypes/#comments</comments>
		<pubDate>Wed, 16 Feb 2011 11:42:38 +0000</pubDate>
		<dc:creator>xhalent</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[fundamentals]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://xhalent.wordpress.com/?p=233</guid>
		<description><![CDATA[This is part of series on javascript mechanics I&#8217;m writing &#8211; mainly for my own benefit but also to help those shy server developers out there venture into the mysterious land of the &#8216;client side&#8217;. In my last post I &#8230; <a href="http://xhalent.wordpress.com/2011/02/16/javascript-object-instantiation-and-prototypes/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=xhalent.wordpress.com&amp;blog=17892286&amp;post=233&amp;subd=xhalent&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>
This is part of series on javascript mechanics I&#8217;m writing &#8211; mainly for my own benefit but also to help those shy server developers out there venture into the mysterious land of the &#8216;client side&#8217;. In my last post I covered the basics of what is a javascript object, and in my next post I am going to cover javascript closures but today I&#8217;m going to cover object construction and initialisation.
</p>
<p>Following on from my <a href="http://xhalent.wordpress.com/2011/01/21/javascript-arrays-objects-and-associative-arrays/">previous post</a>, I now want to explain javascript objects in some greater detail. In my previous post I had some script that created an object as follows:</p>
<pre><pre class="brush: jscript;"> 
var rect = new Object();

rect.width = 10;
rect.height = 30;

rect.area = function () {
    return this.width * this.height;
};

</pre>
</pre>
<p>This script is invoking the Object type’s instance factory method that returns a new Object instance. This is equivalent defining a function called Object() and calling in the context of a newly created object as follows:</p>
<pre><pre class="brush: jscript;"> 
function Object(){
  return this;
}

var rect = {};

Object.apply(rect);

.....
</pre>
</pre>
<h3>So what is really going on here?</h3>
<p>What the <code>new</code> keyword does is instantiates an empty object (<code>{}</code>) and calls the specified constructor function in the context of the newly created object. Once you understand this, you are well on your way to becoming a javascript legend!</p>
<p>So you can see that every javascript starts the same &#8211; as an empty object <code>{}</code>, it is what method gets called in conjunction with <code>new</code> keyword that defines the properties of the resultant object. To demonstrate what I mean, consider the following script: </p>
<pre><pre class="brush: jscript;"> 

var objectCount = 1; 

Object = function(){ 
  this.id = objectCount++; 
}; 

var obj = new Object(); 
//this will have a value of 1
alert(obj.id); 

var otherobj = {}; 
//this object did not get run though the object factory, so this will be undefined
alert(otherobj.id); 

</pre>
</pre>
<p>If you run this, <code>obj.id</code> will have some integer value. However <code>otherobj.id</code> is undefined, becuase it&#8217;s instance has not been run though the object factory. If I now do this..</p>
<pre>
<pre class="brush: jscript;"> 
var objectCount = 1; 

Object = function(){ this.id = objectCount++; }; 

var otherobj = {}; 
//apply the factory method in the context of the new object 

Object.apply(otherobj); 

//the object now has the property set and equal to 2 
alert(otherobj.id); 
</pre>
</pre>
<p>otherobj.id now has a integer value.</p>
<p>So to reiterate, in javascript all object are created equal. What the new operator does is to apply a factory method to the newly instantiated object.</p>
<p>Now we understand what a object fatcory is, we can start to create them so we get uniformly created objects. First we&#8217;ll create a Factory method for a mythical but possibly useful <code>Rect</code> class as follows:</p>
<pre>
<pre class="brush: jscript;"> 

function Rect(width,height){
  this.width = width;
  this.height = height;
  this.area = function () {
    return this.width * this.height;
  };
}

var rect= new Rect(10,5);

alert(rect.area());

var rect2 = new Rect(5,1);

alert(rect2.area());

alert(rect2.area == rect.area);

</pre>
</pre>
<p>Here you&#8217;ll note the use of parameters in the constructor. Again, what the <code>new</code> keyword results in is the construction of an empty object {}, which is then set as the &#8220;this&#8221; context for the factory method that is called with the two parameters. If you run this script, you&#8217;ll see that the for each instance of <code>Rect</code> created, they both have a method <code>area</code> defined, <strong>but they each have their own version</strong>.</p>
<p>This may initially seem bizarre, but it should be remembered that functions in javascript are objects that can be assigned to properties at runtime, much like delegates in C#.</p>
<p>This is probably sub-optimal, so javascript has the concept of a prototype. The prototype of a constructor function is a special property of the function that is used in the object construction pipeline to initialise objects prior to their constructor being run. Each property of the prototype object is shallow copied to the new object (from my <a href="http://xhalent.wordpress.com/2011/01/21/javascript-arrays-objects-and-associative-arrays/">previous post</a>, you&#8217;ll recall javascript objects are more or less associative arrays whose properties can be altered freely at runtime).</p>
<p>The psudeo-code for object construction then becomes</p>
<ol>
<li>Create an empty object {}</li>
<li>Copy all the properties of the prototype object of the constructor function to the newly created object</li>
<li>Pass the object to the constructor function to perform any initialisation</li>
</ol>
<p>Revisiting the script from above
<pre>
<pre class="brush: jscript;"> 

function Rect(width,height){
  this.width = width;
  this.height = height;;
};

/* Add to the prototype */
Rect.prototype.area  = function () {
   return this.width * this.height;
};

var rect= new Rect(10,5);

alert(rect.area());

var rect2 = new Rect(5,1);

alert(rect2.area());

alert(rect2.area == rect.area);

</pre>
</pre>
<p>When this code is run, it will be seen that both rects have the function srea and they are in fact the same function-object. This makes sense becuase when the prototype is applied, the copies of the function are by reference.</p>
<p>Note that the prototype of an constructor function can be altered at any point. If we re-assign the <code>area</code> of our <code>rect</code>, then new instances of <code>rect</code> will have a different <code>area</code> method to the first few instances. Changing the prototype does not affect instances of created objects.</p>
<p>Being objects, the popular way to define a prototype is to use object-notation. The provides for a succinct collation of each function to be assigned to the new object. The following sample demonstrates:</p>
<pre>
<pre class="brush: jscript;"> 

function Rect(width,height){
  this.width = width;
  this.height = height;;
};

/* Add to the prototype */
Rect.prototype = {
  area:function(){
       return this.width * this.height;
   },
   diagonal:function(){
       return Math.sqrt( Math.pow(this.width,2) + Math.pow(this.height,2) );
   }
};


var rect= new Rect(10,5);

alert(rect3.diagonal());

</pre>
</pre>
<p>One thing to keep in mind when creating prototype objects is the need to reference object properties using the keyword <code>this</code>. This is to deal with closures, which will the topic of my next javascript in-depth topic.</p>
<h3>Conclusion</h3>
<p>In this post I have the fundamentals of objects and their instantiation in Javascript.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/xhalent.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/xhalent.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/xhalent.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/xhalent.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/xhalent.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/xhalent.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/xhalent.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/xhalent.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/xhalent.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/xhalent.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/xhalent.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/xhalent.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/xhalent.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/xhalent.wordpress.com/233/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=xhalent.wordpress.com&amp;blog=17892286&amp;post=233&amp;subd=xhalent&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://xhalent.wordpress.com/2011/02/16/javascript-object-instantiation-and-prototypes/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/59d165db24237b353d07fab21cc0897e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">xhalent</media:title>
		</media:content>
	</item>
		<item>
		<title>Copying Jquery Validation from one element to another</title>
		<link>http://xhalent.wordpress.com/2011/02/08/copying-jquery-validation-from-one-element-to-another/</link>
		<comments>http://xhalent.wordpress.com/2011/02/08/copying-jquery-validation-from-one-element-to-another/#comments</comments>
		<pubDate>Tue, 08 Feb 2011 11:09:30 +0000</pubDate>
		<dc:creator>xhalent</dc:creator>
				<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://xhalent.wordpress.com/?p=229</guid>
		<description><![CDATA[A simple note to self about copying jquery validations on one element to another. 1. First get the validation rules pertaining to the element you want to copy from using the validation jquery extensions var rules = $(&#8216;#elementtocopy&#8217;).rules(); 2. The &#8230; <a href="http://xhalent.wordpress.com/2011/02/08/copying-jquery-validation-from-one-element-to-another/">Continue reading <span class="meta-nav">&#8594;</span></a><img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=xhalent.wordpress.com&amp;blog=17892286&amp;post=229&amp;subd=xhalent&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>A simple note to self about copying jquery validations on one element to another.</p>
<p>1. First get the validation rules pertaining to the element you want to copy from using the validation jquery extensions</p>
<p>var rules = $(&#8216;#elementtocopy&#8217;).rules();</p>
<p>2. The get the messages that match those rules &#8211; these are in the settings object for the element. Note how element name is used, and not element id.</p>
<p>rules['messages'] = $(&#8216;form&#8217;).data(&#8216;validator&#8217;).settings["your element name, NOT id"];</p>
<p>3. Simply invoke the validation jquery extension on the selector that you wish to apply the rules to</p>
<p>$(&#8216;#newelementid&#8217;).rules(&#8220;add&#8221;, args);</p>
<p>Simple eh <img src='http://s1.wp.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/xhalent.wordpress.com/229/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/xhalent.wordpress.com/229/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/xhalent.wordpress.com/229/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/xhalent.wordpress.com/229/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/xhalent.wordpress.com/229/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/xhalent.wordpress.com/229/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/xhalent.wordpress.com/229/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/xhalent.wordpress.com/229/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/xhalent.wordpress.com/229/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/xhalent.wordpress.com/229/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/xhalent.wordpress.com/229/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/xhalent.wordpress.com/229/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/xhalent.wordpress.com/229/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/xhalent.wordpress.com/229/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=xhalent.wordpress.com&amp;blog=17892286&amp;post=229&amp;subd=xhalent&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://xhalent.wordpress.com/2011/02/08/copying-jquery-validation-from-one-element-to-another/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/59d165db24237b353d07fab21cc0897e?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">xhalent</media:title>
		</media:content>
	</item>
	</channel>
</rss>
