<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.encosia.com/~d/styles/itemcontent.css"?><rss 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:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Encosia</title>
	
	<link>http://encosia.com</link>
	<description>ASP.NET and AJAX code, ideas, and examples.</description>
	<lastBuildDate>Mon, 29 Jun 2009 14:15:55 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" /><meta xmlns="http://pipes.yahoo.com" name="pipes" content="noprocess" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.encosia.com/Encosia" type="application/rss+xml" /><feedburner:emailServiceId>Encosia</feedburner:emailServiceId><feedburner:feedburnerHostname>http://feedburner.google.com</feedburner:feedburnerHostname><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><item>
		<title>Never worry about ASP.NET AJAX’s .d again</title>
		<link>http://feeds.encosia.com/~r/Encosia/~3/CjlWNiqx02E/</link>
		<comments>http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/#comments</comments>
		<pubDate>Mon, 29 Jun 2009 05:00:48 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=883</guid>
		<description><![CDATA[When I recently received this message from a frustrated reader:
After hours and hours of slamming my head into the desk it turns out it was the darn &#34;d&#34; in the response. My home computer is on .NET 2.0 and my work computer is on 3.5. Jimminie Christmas!
I realized that the “.d” introduced in ASP.NET AJAX [...]<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/">Never worry about ASP.NET AJAX&#8217;s .d again</a></p>
]]></description>
			<content:encoded><![CDATA[<p>When I recently received this message from a frustrated reader:</p>
<blockquote><p>After hours and hours of slamming my head into the desk it turns out it was the darn &quot;d&quot; in the response. My home computer is on .NET 2.0 and my work computer is on 3.5. <strong>Jimminie Christmas</strong>!</p></blockquote>
<p>I realized that the “.d” introduced in ASP.NET AJAX 3.5’s JSON responses is still all too common a stumbling block when <a target="_blank" href="http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/">calling ASP.NET AJAX services through a library such as jQuery</a>. In fact, with jQuery’s popularity among ASP.NET developers on the rise, this appears to have <strong>become an even more frequent problem</strong>.</p>
<p>Since a lot of people are having trouble with it, I want to share one method you can use to completely isolate your code from the problem. If you bake this into an $.ajax() code snippet or otherwise use it as a template for calling ASP.NET AJAX services in jQuery, you should never have to think or worry about the “.d” again.</p>
<p>In this post, I will show you <strong>how to detect the “.d”</strong> and how you can <strong>completely isolate your $.ajax success handler from it</strong>.</p>
<h3>“.d” what?</h3>
<p>If you aren’t familiar with the “.d” I’m referring to, it is simply a security feature that Microsoft added in ASP.NET 3.5’s version of ASP.NET AJAX. By encapsulating the JSON response within a parent object, the framework helps protect against <a href="http://haacked.com/archive/2009/06/25/json-hijacking.aspx" target="_blank">a particularly nasty XSS vulnerability</a>.</p>
<p>Before ASP.NET 3.5, “ScriptServices” and page methods returned their data at the top level of the JSON response, like this:</p>
<p><img title="2.0 JSON Response" border="0" alt="2.0 JSON Response in Firebug" src="http://encosia.com/blog/wp-content/uploads/2009/02/20-json-response.png" width="490" height="146" /></p>
<p>In ASP.NET 3.5 and later, the same server-side code returns this:</p>
<p><img title="3.5 JSON Response" border="0" alt="3.5 JSON Response in Firebug" src="http://encosia.com/blog/wp-content/uploads/2009/02/35-json-response.png" width="490" height="146" /></p>
<p>For more information about the change and <em>why</em> the change is a good one, be sure to see my earlier post: <a href="http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/" target="_blank">A breaking change between versions of ASP.NET AJAX</a>.</p>
<p>However, what my previous post lacks is a solution for mitigating the inconsistency entirely. Using different client-side code against 2.0 and 3.5 based services is workable, but far from ideal. <strong>Wouldn’t it be nicer to not have to worry about it?</strong></p>
<h3>Determining whether or not the “.d” is there</h3>
<p>In order to isolate ourselves from the “.d”, we first need a reliable way to test for its presence. Though JavaScript provides several methods for determining this, I suggest hasOwnProperty, <a href="http://encosia.com/2009/02/16/review-the-best-javascript-book-i%E2%80%99ve-read/" rel="nofollow" target="_blank">as recommended by Douglas Crockford</a>.</p>
<p>By using hasOwnProperty, your code is protected against <a href="http://encosia.com/2008/09/28/avoid-this-tricky-conflict-between-aspnet-ajax-and-jquery/" target="_blank">unexpected changes to an object’s prototype chain</a>. Though it is an unlikely problem to encounter, it’s always best to code defensively in JavaScript. The browser is a hostile environment!</p>
<p>Using hasOwnProperty to test for “.d”, you might end up with something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
  type<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;POST&quot;</span><span style="color: #339933;">,</span>
  url<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;WebService.asmx/MethodName&quot;</span><span style="color: #339933;">,</span>
  data<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;{}&quot;</span><span style="color: #339933;">,</span>
  contentType<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;application/json; charset=utf-8&quot;</span><span style="color: #339933;">,</span>
  dataType<span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;json&quot;</span><span style="color: #339933;">,</span>
  success<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>msg<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>msg.<span style="color: #660066;">hasOwnProperty</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;d&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
      <span style="color: #006600; font-style: italic;">// Leave the .d behind and pass the rest of </span>
      <span style="color: #006600; font-style: italic;">//  the JSON object forward.</span>
      DoSomething<span style="color: #009900;">&#40;</span>msg.<span style="color: #660066;">d</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">else</span>
      <span style="color: #006600; font-style: italic;">// No .d; no transformation necessary.</span>
      DoSomething<span style="color: #009900;">&#40;</span>msg<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">function</span> DoSomething<span style="color: #009900;">&#40;</span>msg<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #006600; font-style: italic;">// Do something with the response data here.</span>
  <span style="color: #006600; font-style: italic;">//  Expect it to consistently have no .d.</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This code <em>will</em> perform identically against any version of ASP.NET AJAX.</p>
<p>Unfortunately, this might still get in your way. You may not always want to use the response in a call to another function, and you’ll have to remember the conditional every time you write a success handler.</p>
<h3>Don’t make me think</h3>
<p>I prefer a solution that doesn’t touch the success handler at all. Then, you’re free to integrate the “.d” handling into a generic $.ajax code snippet in Visual Studio and/or easily copy-paste it between files without modification.</p>
<p>Luckily, jQuery provides a mechanism that allows us to do just that: <strong>dataFilter</strong>.</p>
<p>The dataFilter parameter to $.ajax allows you to arbitrarily transform a response <em>just before</em> the success handler fires. Specifically tailored to this sort of situation, it passes response data into a callback function, captures the return value of that callback, and then passes the modified data into your success handler.</p>
<p>Hence, you can forever stop worrying about that pesky “.d” like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
  type<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;POST&quot;</span><span style="color: #339933;">,</span>
  url<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;WebService.asmx/MethodName&quot;</span><span style="color: #339933;">,</span>
  data<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;{}&quot;</span><span style="color: #339933;">,</span>
  contentType<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;application/json; charset=utf-8&quot;</span><span style="color: #339933;">,</span>
  dataFilter<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// This boils the response string down </span>
    <span style="color: #006600; font-style: italic;">//  into a proper JavaScirpt Object().</span>
    <span style="color: #003366; font-weight: bold;">var</span> msg <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">eval</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'('</span> <span style="color: #339933;">+</span> data <span style="color: #339933;">+</span> <span style="color: #3366CC;">')'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #006600; font-style: italic;">// If the response has a &quot;.d&quot; top-level property,</span>
    <span style="color: #006600; font-style: italic;">//  return what's below that instead.</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>msg.<span style="color: #660066;">hasOwnProperty</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'d'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
      <span style="color: #000066; font-weight: bold;">return</span> msg.<span style="color: #660066;">d</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">else</span>
      <span style="color: #000066; font-weight: bold;">return</span> msg<span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
  success<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>msg<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// This will now output the same thing </span>
    <span style="color: #006600; font-style: italic;">//  across any current version of .NET.</span>
    console.<span style="color: #660066;">log</span><span style="color: #009900;">&#40;</span>msg.<span style="color: #660066;">foo</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Now, regardless which of these JSON forms the server returns:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// ASP.NET 2.0 with the ASP.NET AJAX Extensions installed.</span>
<span style="color: #009900;">&#123;</span><span style="color: #3366CC;">'foo'</span><span style="color: #339933;">:</span><span style="color: #3366CC;">'bar'</span><span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// ASP.NET 3.5 and 4.0.</span>
<span style="color: #009900;">&#123;</span><span style="color: #3366CC;">'d'</span><span style="color: #339933;">:</span><span style="color: #009900;">&#123;</span><span style="color: #3366CC;">'foo'</span><span style="color: #339933;">:</span><span style="color: #3366CC;">'bar'</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span></pre></div></div>

<p>Your success handler will simply receive this consistent JSON object every time:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#123;</span><span style="color: #3366CC;">'foo'</span><span style="color: #339933;">:</span><span style="color: #3366CC;">'bar'</span><span style="color: #009900;">&#125;</span></pre></div></div>

<h3>dataType: none of your business</h3>
<p>It&#8217;s important to note the removal of the dataType parameter in the $.ajax() code above. This is required in order to prevent a double-eval of service responses containing only a single string.</p>
<p>Internally, jQuery uses a combination of the dataType parameter and the implicit type the response. If the dataType is &quot;json&quot; and typeof(response) is “string”, then jQuery uses eval() to deserialize the response.</p>
<p>In the example above, manually deserializing the response in dataFilter results in it being of type Object, jQuery leaves it alone, and our dataFilter’d object makes its way back to the success callback either way.</p>
<p>However, if the dataType is set to “json” and the “.d” sanitized response happens to be of JavaScript type “string”, jQuery will assume that it is a JSON response from the server and still needs to be deserialized. That will throw an error at best.</p>
<p>The solution is to simply drop the dataType parameter from the $.ajax() call. It is only needed for purposes of instructing jQuery how to deserialize the response, and we’re handling that ourselves now.</p>
<p>Thanks to Brett <a href="#comment-35702">for pointing this out</a>.</p>
<h3>Wait, isn’t eval() supposed to be evil?</h3>
<p>If the eval() usage gives you pause, don’t worry. For now (as of jQuery 1.3.2), this is the same mechanism that jQuery uses to deserialize JSON too. Though eval() <em>is</em> potentially evil, <strong>it is still a necessary evil in many browsers</strong>.</p>
<p>In my next post, I’ll show you how to modify this to leverage a native browser implementation of JSON.parse instead of eval(), available in some newer browsers.</p>
<p>So, if you aren’t already, make sure to stay tuned by subscribing to either <a href="http://feeds.encosia.com/Encosia" rel="nofollow" target="_blank">my RSS feed</a>, <a href="http://www.feedburner.com/fb/a/emailverifySubmit?feedId=654672&amp;loc=en_US" rel="nofollow" target="_blank">email updates</a>, or <a href="http://twitter.com/encosia" rel="nofollow" target="_blank">Twitter stream</a>.</p>
<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/">Never worry about ASP.NET AJAX&#8217;s .d again</a></p>
<div class="feedflare">
<a href="http://feeds.encosia.com/~ff/Encosia?a=CjlWNiqx02E:g3bSo8JWwZ4:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Encosia?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=CjlWNiqx02E:g3bSo8JWwZ4:aWKiLpGymzw"><img src="http://feeds.feedburner.com/~ff/Encosia?d=aWKiLpGymzw" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=CjlWNiqx02E:g3bSo8JWwZ4:30RXbuXOgYA"><img src="http://feeds.feedburner.com/~ff/Encosia?d=30RXbuXOgYA" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=CjlWNiqx02E:g3bSo8JWwZ4:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/Encosia?i=CjlWNiqx02E:g3bSo8JWwZ4:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=CjlWNiqx02E:g3bSo8JWwZ4:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/Encosia?i=CjlWNiqx02E:g3bSo8JWwZ4:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Encosia/~4/CjlWNiqx02E" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		<feedburner:origLink>http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/</feedburner:origLink></item>
		<item>
		<title>Hear me talk about jQuery on the Polymorphic Podcast</title>
		<link>http://feeds.encosia.com/~r/Encosia/~3/-bOZ6DkXXtE/</link>
		<comments>http://encosia.com/2009/06/20/hear-me-talk-about-jquery-on-the-polymorphic-podcast/#comments</comments>
		<pubDate>Sat, 20 Jun 2009 17:12:28 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://encosia.com/2009/06/20/hear-me-talk-about-jquery-on-the-polymorphic-podcast/</guid>
		<description><![CDATA[As a longtime listener myself, I was eager when Craig asked me to come on the Polymorphic Podcast to talk about jQuery. I’ve always enjoyed how he doesn’t shy away from talking about HTML and JavaScript, which is still too uncommon in the .NET world.
With that in mind, I knew we’d be able to have [...]<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/06/20/hear-me-talk-about-jquery-on-the-polymorphic-podcast/">Hear me talk about jQuery on the Polymorphic Podcast</a></p>
]]></description>
			<content:encoded><![CDATA[<p>As a longtime listener myself, I was eager when Craig asked me to come on the Polymorphic Podcast to talk about jQuery. I’ve always enjoyed how he doesn’t shy away from talking about HTML and JavaScript, which is still too uncommon in the .NET world.</p>
<p>With that in mind, I knew we’d be able to have a great conversation about jQuery and the concerns that ASP.NET developers run into when using it. I really enjoyed recording the show, and think it turned out pretty well. I hope you’ll enjoy it too:</p>
<p><a href="http://polymorphicpodcast.com/shows/jquery/" target="_blank">Polymorphic Podcast: jQuery Secrets with Dave Ward</a></p>
<p> If you haven’t yet, I highly recommend <a href="http://polymorphicpodcast.com/podcast/feed/" target="_blank">subscribing to Craig’s podcast</a>. There are some real gems in his <a href="http://polymorphicpodcast.com/shows/" target="_blank">previous shows</a> too, so check those out as well.</p>
<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/06/20/hear-me-talk-about-jquery-on-the-polymorphic-podcast/">Hear me talk about jQuery on the Polymorphic Podcast</a></p>
<div class="feedflare">
<a href="http://feeds.encosia.com/~ff/Encosia?a=-bOZ6DkXXtE:QPgVoGZEjTc:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Encosia?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=-bOZ6DkXXtE:QPgVoGZEjTc:aWKiLpGymzw"><img src="http://feeds.feedburner.com/~ff/Encosia?d=aWKiLpGymzw" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=-bOZ6DkXXtE:QPgVoGZEjTc:30RXbuXOgYA"><img src="http://feeds.feedburner.com/~ff/Encosia?d=30RXbuXOgYA" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=-bOZ6DkXXtE:QPgVoGZEjTc:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/Encosia?i=-bOZ6DkXXtE:QPgVoGZEjTc:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=-bOZ6DkXXtE:QPgVoGZEjTc:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/Encosia?i=-bOZ6DkXXtE:QPgVoGZEjTc:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Encosia/~4/-bOZ6DkXXtE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/06/20/hear-me-talk-about-jquery-on-the-polymorphic-podcast/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://encosia.com/2009/06/20/hear-me-talk-about-jquery-on-the-polymorphic-podcast/</feedburner:origLink></item>
		<item>
		<title>11 keystrokes that made my jQuery selector run 10x faster</title>
		<link>http://feeds.encosia.com/~r/Encosia/~3/j3O6VrqWWWM/</link>
		<comments>http://encosia.com/2009/06/09/11-keystrokes-that-made-my-jquery-selector-run-10x-faster/#comments</comments>
		<pubDate>Tue, 09 Jun 2009 18:45:31 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=877</guid>
		<description><![CDATA[As an ASP.NET developer working on the client-side, one problem you’ll encounter is how to reference the HTML elements that ASP.NET web controls generate. All too often, you find yourself wasting time trying to reference TextBox1, when the element is actually rendered as ctl00_panel1_wizard1_TextBox1.
Much has been written about this, including a post of my own, [...]<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/06/09/11-keystrokes-that-made-my-jquery-selector-run-10x-faster/">11 keystrokes that made my jQuery selector run 10x faster</a></p>
]]></description>
			<content:encoded><![CDATA[<p>As an ASP.NET developer working on the client-side, one problem you’ll encounter is how to reference the HTML elements that ASP.NET web controls generate. All too often, you find yourself wasting time trying to reference TextBox1, when the element is actually rendered as ctl00_panel1_wizard1_TextBox1.</p>
<p>Much has been written about this, <a href="http://encosia.com/2007/08/08/robust-aspnet-control-referencing-in-javascript/">including a post of my own</a>, so I won’t go into detail about many of the workarounds. Instead, I want to take a closer look at the performance drawbacks of one popular solution: <a href="http://docs.jquery.com/Selectors/attributeEndsWith#attributevalue" target="_blank">the [attribute$=value] selector</a>.</p>
<p>By specifying <strong>id</strong> as the <strong>attribute</strong> in this selector, you can avoid ASP.NET’s ClientID issues completely. No matter what the framework prefixes your rendered elements with, they still “end with” the ID you specify at design time. This makes the “ends with” selector a convenient alternative to injecting a control’s ClientID property via angle-brackets.</p>
<p>However, are we<strong> trading performance for this convenience</strong>? If so, <strong>how much</strong>?</p>
<p>When <a href="http://weblogs.asp.net/craigshoemaker/" target="_blank">Craig Shoemaker</a> asked that question while interviewing me for an upcoming episode of <a href="http://polymorphicpodcast.com/" target="_blank">Polymorphic Podcast</a>, I realized I didn’t know the answer as clearly as I’d like. So, I decided to do a bit of benchmarking.</p>
<p>In this post, I’ll share <strong>the results of that benchmarking</strong>, and show you one way to <strong>significantly improve the performance</strong> of this convenient selector.</p>
<h3>The test scenario</h3>
<p>One difficulty when analyzing selector performance is that <strong>they all perform well on small test pages</strong>. Most performance issues aren’t readily apparent until a page grows in complexity and contains many elements. This can easily leave you overly confident in techniques that survive a simple proof of concept, but don’t scale well to practical usage.</p>
<p>Rather than construct a complex demonstration page from scratch to test against, I decided to use an existing page. With over 160 comments at the time of writing (and testing), <a href="http://encosia.com/downloads/highslide-js-net/">the Highslide JS .NET project page</a> is an ideal candidate. Its 1,000+ DOM elements are well suited to expose poorly performing selectors.</p>
<p>Enclosing each comment on the page, there’s a div like this one:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;div id=&quot;div-comment-35496&quot; class=&quot;comment&quot;&gt;
  &lt;!-- Comment content here --&gt;
&lt;/div&gt;</pre></div></div>

<p>If you imagine that the “div-“ prefix is “ctl00_”, these IDs are a great substitute for the ClientIDs that ASP.NET controls render within naming containers.</p>
<p>So for purposes of testing, I attempted to select the element <strong>div-comment-35496</strong> on that page, assuming that I knew its ID of <strong>comment-35496</strong> at design time and that the “div-“ prefix was added at run time. This is identical to the process of selecting the div rendered by an ASP.NET Panel control within a Content Page, for example.</p>
<h3>Test methodology</h3>
<p>To benchmark each selector, I used the following JavaScript:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> iterations <span style="color: #339933;">=</span> <span style="color: #CC0000;">100</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> totalTime <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Repeat the test the specified number of iterations.</span>
<span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> iterations<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #006600; font-style: italic;">// Record the starting time, in UTC milliseconds.</span>
  <span style="color: #003366; font-weight: bold;">var</span> start <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #006600; font-style: italic;">// Execute the selector. The result does not need</span>
  <span style="color: #006600; font-style: italic;">//  to be used or assigned to determine how long </span>
  <span style="color: #006600; font-style: italic;">//  the selector itself takes to run.</span>
  $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'[id$=comment-35496]'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #006600; font-style: italic;">// Record the ending time, in UTC milliseconds.</span>
  <span style="color: #003366; font-weight: bold;">var</span> end <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #006600; font-style: italic;">// Determine how many milliseconds elapsed and</span>
  <span style="color: #006600; font-style: italic;">//  increment the test's totalTime counter.</span>
  totalTime <span style="color: #339933;">+=</span> <span style="color: #009900;">&#40;</span>end <span style="color: #339933;">-</span> start<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Report the average time taken by one iteration.</span>
<span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span>totalTime <span style="color: #339933;">/</span> iterations<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This simply executes the selector 100 times, recording how many milliseconds each run takes, and then determines the average.</p>
<p>I had originally recorded and displayed an array of each individual time, but found there was very little variation and stopped tracking each execution. The average is good enough for these purposes.</p>
<p>For each selector, I ran the test five times and then averaged the results, resulting in an average across 500 separate executions in semi-isolated batches. Then, I repeated the process for each major browser.</p>
<p>CERN probably won’t be flying me out to work on the LHC with this level of rigor, but it’s accurate enough for measuring the relative performance change between different selectors.</p>
<h3>The baseline</h3>
<p>jQuery’s <a href="http://docs.jquery.com/Selectors/id#id" target="_blank">#id selector</a> leverages browsers’ native <a href="http://msdn.microsoft.com/en-us/library/ms536437%28VS.85%29.aspx" rel="nofollow" target="_blank">getElementById</a> routine. Though slower than calling getElementById directly, this is a very fast way to reference our div as a jQuery object:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#div-comment-35496'</span><span style="color: #009900;">&#41;</span></pre></div></div>

<p>As you may expect, this browser assisted selector is fastest. In fact, <strong>every major browser consistently performed this in less than one millisecond</strong> in my testing. Most in less than <em>a third of a millisecond</em>.</p>
<p>To safely use this selector in ASP.NET, we have to manually inject the a control’s ClientID property. Otherwise, any naming container added, removed, or renamed would break our client-side code.</p>
<p>You’ve probably seen that accomplished like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#&lt;%= comment-35496.ClientID %&gt;'</span><span style="color: #009900;">&#41;</span></pre></div></div>

<p>It looks messy and requires a bit more effort, but it’s <strong>fast</strong>.</p>
<p>ASP.NET 4.0’s <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode%28VS.100%29.aspx" rel="nofollow" target="_blank">ClientIDMode property</a> promises to eliminate this inconvenience in the long-term, but we’re stuck with it for now. For that matter, with many projects still using ASP.NET 1.x and 2.0, slow to adopt the latest version, we may be stuck with the problem for quite some time to come.</p>
<h3>Convenience</h3>
<p>To avoid the messy work of manually injecting ASP.NET’s rendered ClientIDs, you may have seen the suggestion that this is an easier way:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'[id$=comment-35496]'</span><span style="color: #009900;">&#41;</span></pre></div></div>

<p>Indeed, this will successfully select the element that we’re after. Since its ID is div-comment-35496, searching for an element whose ID “ends with” comment-35496 works as desired.</p>
<p>Eliminating the angle-brackets is aesthetically pleasing and it’s less up-front work, but what about performance?</p>
<p>jQuery’s selector engine implements “ends with” by performing this test on every element in question, where value is the attribute you’ve specified and check is the string that you’re searching for:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">value.<span style="color: #660066;">substr</span><span style="color: #009900;">&#40;</span>value.<span style="color: #660066;">length</span> <span style="color: #339933;">-</span> check.<span style="color: #660066;">length</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">===</span> check</pre></div></div>

<p>That’s not so bad if you’re only doing it once, but doing it <strong>for every element on the page</strong> is a different story. Remember our test page has <em>thousands</em> of elements.</p>
<p>What’s worse, jQuery has no way to know that only one element should match the pattern. So, it must continue iterating through to the end of the page, even after locating the single element that we’re actually interested in.</p>
<p>How bad is it? Over the course of several hundred executions on the test page, I obtained these average speeds for a single $= selector execution in each browser:</p>
<p><img src="http://encosia.com/blog/wp-content/uploads/2009/06/ends-with-comparison.png" width="492" height="199" /></p>
<p>The Chrome numbers are unsurprising, given its speedy <a href="http://code.google.com/p/v8/" target="_blank">V8 JavaScript engine</a>. IE8 and Firefox 3.5 perform admirably too. These newer browsers all executed the selector very <strong>nearly as quickly as document.getElementById</strong>.</p>
<p>However, IE7 and Firefox 3.0 are <strong>substantially slower</strong> when executing the “ends with” selector. Remembering the non-trivial difference that Firebug made in <a href="http://weblogs.asp.net/yuanjian/archive/2009/03/22/json-performance-comparison-of-eval-new-function-and-json.aspx" target="_blank">this interesting post about JSON parsing speeds</a>, I also tested with and without Firebug enabled in Firefox 3.0 (which turned out to be a significant factor here too).</p>
<p>Even though we’re only talking about milliseconds, the penalty in older browsers is too large to ignore — especially when the vast majority of users are still on IE6, IE7, or Firefox 3.0, not the new generation of faster browsers.</p>
<h3>Convenience optimized</h3>
<p>Remembering that the #id selector is quick because it leverages the native speed of getElementById, we can help jQuery execute the $= selector more efficiently.</p>
<p>If we modify the selector to descend from an HTML tag before performing the “ends with” search, jQuery can use <a href="http://msdn.microsoft.com/en-us/library/ms536439%28VS.85%29.aspx" rel="nofollow" target="_blank">getElementsByTagName</a> to pre-filter the set of elements to search within. Since getElementsByTagName is a native browser routine, it is much faster than jQuery’s interpreted selector engine.</p>
<p>For example, since we know the element we’re after is a div, we could optimize the previous $= selector like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'div[id$=comment-35457]'</span><span style="color: #009900;">&#41;</span></pre></div></div>

<p>The benefit is substantial:</p>
<p><img src="http://encosia.com/blog/wp-content/uploads/2009/06/ends-with-descending-from-div-comparison.png" width="492" height="199" /></p>
<p>The optimized selector runs more than twice as quickly in IE7 and Firefox 3.0!</p>
<p>Along the same lines, <a href="http://sizzlejs.com/" rel="nofollow" target="_blank">jQuery’s Sizzle engine</a> is able to select CSS classes faster than it can perform substring searches within arbitrary attributes. So, the selector can be further optimized by descending from both an HTML tag <em>and</em> a CSS class.</p>
<p>Since the particular div we’re testing against has a CSS class of <em>comment</em>, let’s try this selector:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'div.comment[id$=comment-35457]'</span><span style="color: #009900;">&#41;</span></pre></div></div>

<p>The results?</p>
<p><img src="http://encosia.com/blog/wp-content/uploads/2009/06/ends-with-descending-from-css-comparison.png" width="492" height="199" /></p>
<p>IE7 doesn’t improve much, but Firefox 3.0 shows another excellent increase in its performance. The reason that Firefox shines here is that <a href="http://ejohn.org/blog/getelementsbyclassname-in-firefox-3/" target="_blank">it implements a native getElementsByClassName routine</a> that IE7 doesn’t (though IE8 does).</p>
<p>While slower than the getElementById powered #id selector, <strong>these optimizations have given us a 3-10x speed increase</strong> while referencing exactly the same element as the original $= selector. That’s a pretty good return on the investment of typing a measly eleven characters (div.comment) in front of the selector!</p>
<h3>A mountain out of a molehill?</h3>
<p>This post may seem like a lot of effort to spend on a seemingly tiny performance differential. In fact, I almost considered leaving this one on the shelf, because it’s often difficult to sell the importance of milliseconds.</p>
<p>But, you know what? <strong>Milliseconds count! </strong>A performance difference of a few dozen milliseconds is a perceptible delay. A few hundred will alienate your users.</p>
<p>Research has consistently shown a strong correlation between fast sites and <a href="http://www.bizjournals.com/atlanta/stories/2008/12/15/daily6.html" rel="nofollow" target="_blank">higher conversion rates</a>, <a href="http://glinden.blogspot.com/2006/11/marissa-mayer-at-web-20.html" target="_blank">more user actions per visit</a>, and <a href="http://web.archive.org/web/20040913083444/http://developer.netscape.com/viewsource/bickford_wait.htm" rel="nofollow" target="_blank">user satisfaction</a>. Compounded across the thousands or millions of times a particular function in your application will be used, it is absolutely worthwhile to invest a few minutes in order to save a few milliseconds.</p>
<h3>Conclusion</h3>
<p>I hope you’ve found this information useful. Without hard data, it’s difficult to decide which optimizations are premature and which are worthwhile. Especially since your page is likely to grow more complex over time, I think the data clearly shows that selectors which don’t directly target an ID should <em>always</em> descend from an HTML tag when possible.</p>
<p>Perhaps the most important takeaway is that you must keep in mind how easy it is to write one succinct line of jQuery code that results in a non-trivial loop. The real danger lies in putting a selector like $= within a loop yourself, unaware that what appears to be a simple loop is actually a relatively sluggish nested loop.</p>
<p>The other lesson here is that if speed is crucial, you should inject ClientIDs and use the #id selector (as in the baseline shown above). Even the most optimized “ends with” selector in this post still runs at least one order of magnitude slower than the direct #id selector.</p>
<p>Instead of simply posting that div.class[id$=id] is faster than [id$=id], I wanted to explain the sequence of events that led me to that determination. Armed with knowledge of how I optimized the “ends with” selector, I hope that you have a few new optimization tricks up your sleeve now.</p>
<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/06/09/11-keystrokes-that-made-my-jquery-selector-run-10x-faster/">11 keystrokes that made my jQuery selector run 10x faster</a></p>
<div class="feedflare">
<a href="http://feeds.encosia.com/~ff/Encosia?a=j3O6VrqWWWM:wq3fSyo4fzs:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Encosia?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=j3O6VrqWWWM:wq3fSyo4fzs:aWKiLpGymzw"><img src="http://feeds.feedburner.com/~ff/Encosia?d=aWKiLpGymzw" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=j3O6VrqWWWM:wq3fSyo4fzs:30RXbuXOgYA"><img src="http://feeds.feedburner.com/~ff/Encosia?d=30RXbuXOgYA" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=j3O6VrqWWWM:wq3fSyo4fzs:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/Encosia?i=j3O6VrqWWWM:wq3fSyo4fzs:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=j3O6VrqWWWM:wq3fSyo4fzs:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/Encosia?i=j3O6VrqWWWM:wq3fSyo4fzs:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Encosia/~4/j3O6VrqWWWM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/06/09/11-keystrokes-that-made-my-jquery-selector-run-10x-faster/feed/</wfw:commentRss>
		<slash:comments>32</slash:comments>
		<feedburner:origLink>http://encosia.com/2009/06/09/11-keystrokes-that-made-my-jquery-selector-run-10x-faster/</feedburner:origLink></item>
		<item>
		<title>Highslide JS .NET v4.1.4</title>
		<link>http://feeds.encosia.com/~r/Encosia/~3/cSdpBAZ5IEo/</link>
		<comments>http://encosia.com/2009/06/03/highslide-js-net-v414/#comments</comments>
		<pubDate>Wed, 03 Jun 2009 20:18:48 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Highslide]]></category>
		<category><![CDATA[UI]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=870</guid>
		<description><![CDATA[A new version of Highslide JS .NET is available today. Nothing major has changed in the .NET control, but the newer Highslide JS version includes several bug fixes, compatibility improvements, and performance benefits.
To eliminate one common source of confusion, I’ve decided to begin versioning Highslide JS .NET based on the version of Highslide JS embedded [...]<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/06/03/highslide-js-net-v414/">Highslide JS .NET v4.1.4</a></p>
]]></description>
			<content:encoded><![CDATA[<p>A new version of Highslide JS .NET is available today. Nothing major has changed in the .NET control, but the newer Highslide JS version includes several bug fixes, compatibility improvements, and performance benefits.</p>
<p>To eliminate one common source of confusion, I’ve decided to begin versioning Highslide JS .NET based on the version of Highslide JS embedded within the the control. For example, since this release is v4.1.4, it contains v4.1.4 of Highslide.</p>
<p>Changes in v4.1.4 include:</p>
<ul>
<li>Updated embedded Highslide JS script version to 4.1.4. You can see what has changed in that on <a href="http://highslide.com/changelog.php" target="_blank">the Highslide.com changelog page</a>. </li>
<li>Added <strong>ControlBarPosition</strong> property to the HighslideManager, which allows you to position the enlargement’s control bar in any corner of the image. </li>
<li>Added several properties (<strong>ControlBarPreviousTitle</strong>,<strong> ControlBarNextTitle</strong>,<strong> ControlBarMoveTitle</strong>, and <strong>ControlBarCloseTitle</strong>) to control title attributes of links rendered in the control bar. Useful for localization. </li>
</ul>
<p>As always, the free download is available on <a href="http://encosia.com/downloads/highslide-js-net/">the Highslide JS .NET project page</a>.</p>
<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/06/03/highslide-js-net-v414/">Highslide JS .NET v4.1.4</a></p>
<div class="feedflare">
<a href="http://feeds.encosia.com/~ff/Encosia?a=cSdpBAZ5IEo:2BARL4R4I0c:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Encosia?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=cSdpBAZ5IEo:2BARL4R4I0c:aWKiLpGymzw"><img src="http://feeds.feedburner.com/~ff/Encosia?d=aWKiLpGymzw" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=cSdpBAZ5IEo:2BARL4R4I0c:30RXbuXOgYA"><img src="http://feeds.feedburner.com/~ff/Encosia?d=30RXbuXOgYA" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=cSdpBAZ5IEo:2BARL4R4I0c:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/Encosia?i=cSdpBAZ5IEo:2BARL4R4I0c:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=cSdpBAZ5IEo:2BARL4R4I0c:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/Encosia?i=cSdpBAZ5IEo:2BARL4R4I0c:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Encosia/~4/cSdpBAZ5IEo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/06/03/highslide-js-net-v414/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://encosia.com/2009/06/03/highslide-js-net-v414/</feedburner:origLink></item>
		<item>
		<title>Automatically minify and combine JavaScript in Visual Studio</title>
		<link>http://feeds.encosia.com/~r/Encosia/~3/Tf7mDx6wdRA/</link>
		<comments>http://encosia.com/2009/05/20/automatically-minify-and-combine-javascript-in-visual-studio/#comments</comments>
		<pubDate>Wed, 20 May 2009 17:42:14 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Performance]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=868</guid>
		<description><![CDATA[As you begin developing more complex client-side functionality, managing the size and shape of your JavaScript includes becomes a key concern. It’s all too easy to accidentally end up with hundreds of kilobytes of JavaScript spread across many separate HTTP requests, significantly slowing down your initial page loads.
To combat this, it’s important to combine and [...]<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/05/20/automatically-minify-and-combine-javascript-in-visual-studio/">Automatically minify and combine JavaScript in Visual Studio</a></p>
]]></description>
			<content:encoded><![CDATA[<p>As you begin developing more complex client-side functionality, managing the size and shape of your JavaScript includes becomes a key concern. It’s all too easy to accidentally end up with hundreds of kilobytes of JavaScript spread across many separate HTTP requests, significantly slowing down your initial page loads.</p>
<p>To combat this, <strong>it’s important to combine and compress your JavaScript</strong>. While there are useful standalone tools and HttpHandler based solutions to the problem already, none of them work quite how I prefer. Instead, I’m going to show you my dead-simple method for automatically compressing and combining script includes.</p>
<p>To accomplish that in this post, we will <strong>select a compression utility</strong>,<strong> learn how to use it</strong> at the command line, <strong>explore a useful automation feature</strong> in Visual Studio, and apply that to keep scripts combined and compressed with no ongoing effort.</p>
<h3>Selecting a JavaScript compression tool</h3>
<p>The first thing we’ll need is a utility to compress our JavaScript. There are many utilities available, ranging from <strong>YUI Compressor</strong> to Dean Edwards’ <strong>Packer</strong>, each with its own strengths and weaknesses.</p>
<p><a href="http://developer.yahoo.com/yui/compressor/" target="_blank">YUI Compressor</a> is powerful, but requires a Java runtime be available during the build process. <a href="http://dean.edwards.name/packer/" target="_blank">Packer</a> is popular for its Base62 encoding mode, however that form of compression carries <a href="http://ejohn.org/blog/library-loading-speed/" target="_blank">a non-trivial performance tax on the client-side</a>.</p>
<p>In terms of simplicity, it’s hard to beat <a href="http://www.crockford.com/javascript/jsmin.html" target="_blank">Douglas Crockford’s JSMin</a>. It requires no command line options, no runtimes or frameworks, and accepts input directly from standard input (which will be useful for us later).</p>
<p>One common concern about JSMin is that it outputs less compact code than YUI Compressor and Packer on their most aggressive settings. However, this is a bit of a red herring. When gzipped, the result of all three boil down to almost exactly the same size across the wire. Since you should <a href="http://www.julienlecomte.net/blog/2007/08/13/" target="_blank">always serve your JavaScript with gzip compression at the HTTP level</a>, this initial “disadvantage” is moot.</p>
<h3>Using JSMin from the command line</h3>
<p>Using JSMin is very straightforward. For example, say we have the following, well-commented JavaScript and want to minify it:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// how many times shall we loop? </span>
<span style="color: #003366; font-weight: bold;">var</span> foo <span style="color: #339933;">=</span> <span style="color: #CC0000;">10</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// what message should we use? </span>
<span style="color: #003366; font-weight: bold;">var</span> bar <span style="color: #339933;">=</span> <span style="color: #3366CC;">'Encosia'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// annoy our user with O(foo) alerts! </span>
<span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i <span style="color: #339933;">=</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">;</span> i <span style="color: #339933;">&lt;</span> foo<span style="color: #339933;">;</span> i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> 
  <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span>bar<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Assuming that JavaScript is in a file called AlertLoop.js, this command line usage of JSMin will minify it and output it to the console:</p>

<div class="wp_syntax"><div class="code"><pre class="dos" style="font-family:monospace;">jsmin &lt; AlertLoop.js</pre></div></div>

<p><img title="jsmin-stdin" border="0" alt="jsmin-stdin" src="http://encosia.com/blog/wp-content/uploads/2009/05/jsmin-stdin.png" width="492" height="123" /></p>
<p>What this does is run jsmin and feed the contents of AlertLoop.js into standard input. It’s the same as if you had run jsmin and then typed all that JavaScript on the command line.</p>
<p>Similarly, this usage does the trick if you want to redirect that output to a file:</p>

<div class="wp_syntax"><div class="code"><pre class="dos" style="font-family:monospace;">jsmin &lt; AlertLoop.js &gt; AlertLoop.min.js</pre></div></div>

<p><img title="jsmin-to-file" border="0" alt="jsmin-to-file" src="http://encosia.com/blog/wp-content/uploads/2009/05/jsmin-to-file.png" width="492" height="154" /> </p>
<p>The minified output is less than half the size of the original. Not bad!</p>
<p><em>Note: If you’re wondering about the upper ASCII characters preceding the minified script, they’re nothing to be concerned about. Because I had created AlertLoop.js in Visual Studio, it was saved as UTF-8 by default and those characters are the UTF BOM (thanks to Oleg, Sugendran, and Bart <a href="http://encosia.com/2009/05/20/automatically-minify-and-combine-javascript-in-visual-studio/#comment-35349">for clarification</a>).</em></p>
<h3>Set up project directories</h3>
<p><img style="float: right; border: 1px solid #000; margin-left: 10px;" title="project-layout" border="0" alt="project-layout" align="right" src="http://encosia.com/blog/wp-content/uploads/2009/05/project-layout.png" width="231" height="275" />Before we get to the next steps, we need to define a structure for our project. The one shown to the right works for simple projects.</p>
<p>Within the website project, the important takeaway is that the JavaScript files to be compressed are all in the same directory and named with a <strong>*.debug.js</strong> pattern.</p>
<p>Outside of the website, notice the “tools” directory which contains a copy of JSMin. I think we can all agree that executables should not be included within a website project if possible. <strong>That would just be begging for trouble</strong>.</p>
<p>However, I do suggest including an external tools directory and JSMin executable in your project’s source control. You never want to create a scenario where someone can’t perform a checkout and then a successful build immediately afterward.</p>
<h3>Automation: Visual Studio earns its keep</h3>
<p>To automate script compression as part of the build process, I suggest using a <strong>build event</strong>. There are perfectly legitimate alternatives, but I prefer having a tangible file sitting on disk and having that compression process automated. So, “building” the minified JavaScript include(s) as part of the build process makes the most sense to me.</p>
<p>Build events may sound complicated, but they aren’t at all. Build events are simply <a href="http://msdn.microsoft.com/en-us/library/ke5z92ks(VS.80).aspx" target="_blank">a mechanism for executing command line code before and/or after your project is compiled</a>.</p>
<p>For our purposes, a post-build event is perfect. Additionally, we can specify that it should only run the build event if the project builds successfully. That way we avoid wasting unnecessary time on minifying the JavaScript when there are build errors.</p>
<h3>Setting up a build event in Visual Studio</h3>
<p>To add build events, right-click on your project and choose <strong>properties</strong>. In the properties page that opens, click on the “Build Events” tab to the left. You’ll be presented with something similar to this:</p>
<p><img title="project-properties" border="0" alt="project-properties" src="http://encosia.com/blog/wp-content/uploads/2009/05/project-properties.png" width="492" height="412" /></p>
<p><em>Note: If you’re using Visual Basic, there will be no build events tab in the project properties. Instead, look for a build events button on the “Build” tab, which allows access the same functionality.</em></p>
<p>You can type commands directly in the post-build field if you want, but clicking the “Edit Post-build” button provides a better editing interface:</p>
<p><img title="post-build-events" border="0" alt="post-build-events" src="http://encosia.com/blog/wp-content/uploads/2009/05/post-build-events.png" width="492" height="272" /></p>
<p>The interface’s macro list is especially useful. In particular, the <strong>ProjectDir</strong> macro will be handy for what we’re doing. $(ProjectDir) placed anywhere in a build event will be replaced with the actual project path, <strong>including a trailing backslash</strong>.</p>
<p>For example, we can use it to execute JSMin.exe in the hierarchy described above:</p>

<div class="wp_syntax"><div class="code"><pre class="dos" style="font-family:monospace;">$<span style="color: #66cc66;">&#40;</span>ProjectDir<span style="color: #66cc66;">&#41;</span>..\tools\jsmin.exe</pre></div></div>

<p>Or, reference that same project’s js directory:</p>

<div class="wp_syntax"><div class="code"><pre class="dos" style="font-family:monospace;">$<span style="color: #66cc66;">&#40;</span>ProjectDir<span style="color: #66cc66;">&#41;</span>js\</pre></div></div>

<h3>Putting it all together: Minify a single file</h3>
<p>Now that we’ve covered how to use JSMin at the command line and how to execute command line scripts as part of Visual Studio builds, putting it all together is easy.</p>
<p>For example, to minify default.debug.js, this post-build event will do the trick:</p>

<div class="wp_syntax"><div class="code"><pre class="dos" style="font-family:monospace;">&quot;$<span style="color: #66cc66;">&#40;</span>ProjectDir<span style="color: #66cc66;">&#41;</span>..\tools\jsmin&quot; &lt; 
&quot;$<span style="color: #66cc66;">&#40;</span>ProjectDir<span style="color: #66cc66;">&#41;</span>js\default.debug.js&quot; &gt; 
&quot;$<span style="color: #66cc66;">&#40;</span>ProjectDir<span style="color: #66cc66;">&#41;</span>js\default.min.js&quot;</pre></div></div>

<p><em>(The line breaks are for readability here. The command in your actual build event must not contain them, or it will be interpreted as separate commands and fail.)</em></p>
<p>The quotes are important, in case $(ProjectDir) happens to include directories with spaces in their names. Since you never know where this project may eventually be built at, it’s best to always use the quotes.</p>
<h3>*Really* putting it together: Combine files</h3>
<p>I did promise more than just compression in the post’s title. <a href="http://developer.yahoo.com/performance/rules.html" target="_blank">Combining scripts is just as important as compression</a>, if not more so. Since JSMin takes its input from stdin, it’s easy to roll scripts together for minification into a single result:</p>

<div class="wp_syntax"><div class="code"><pre class="dos" style="font-family:monospace;">type &quot;$<span style="color: #66cc66;">&#40;</span>ProjectDir<span style="color: #66cc66;">&#41;</span>js\*.debug.js&quot; | 
&quot;$<span style="color: #66cc66;">&#40;</span>ProjectDir<span style="color: #66cc66;">&#41;</span>..\tools\jsmin&quot; &gt; 
&quot;$<span style="color: #66cc66;">&#40;</span>ProjectDir<span style="color: #66cc66;">&#41;</span>js\script-bundle.min.js&quot;</pre></div></div>

<p>This build event would combine all of our *.debug.js scripts, minify the combined script bundle, and then output it in a new file named script-bundle.min.js.</p>
<p>This is great if you want to combine your most commonly used jQuery plugins into a single payload, for example. A reduction in HTTP requests usually provides a nice improvement in performance. This is especially true when you’re dealing with JavaScript, because the browser blocks while script references load.</p>
<h3>Dealing with dependencies</h3>
<p>Cross-dependencies between scripts is one issue that requires extra consideration when combining. Just the same as ordering script includes incorrectly, bundling scripts together in the wrong order may cause them to fail.</p>
<p>One relatively easy way to handle this is to give your scripts prefixes to force the correct order. For example, the source sample below includes this set of JavaScript files:</p>

<div class="wp_syntax"><div class="code"><pre class="dos" style="font-family:monospace;">default.debug.js
jQuery-1.3.2.debug.js
jQuery-jtemplates.debug.js</pre></div></div>

<p>Combining these and referencing the result will fail, because default.debug.js is sorted ahead both jQuery and the plugin by default. Since default.debug.js depends on both of those, this is a big problem. To fix this, rename the files with prefixes:</p>

<div class="wp_syntax"><div class="code"><pre class="dos" style="font-family:monospace;">01-jQuery.debug.js
05-jQuery-jtemplates.debug.js
<span style="color: #cc66cc;">10</span>-default.debug.js</pre></div></div>

<p>Now it will work perfectly.</p>
<p>Any system of alphanumeric prefixes will work, but be sure to pad numbers with leading zeroes if you use a numeric system. Otherwise, the default sort ordering may catch you off guard (e.g. 2-file.js sorts ahead of 11-file.js through 19-file.js).</p>
<h3>To debug, or not to debug</h3>
<p>Now that we have the minification process under control, one final issue to address is <strong>how to keep this from complicating our development workflow</strong>.</p>
<p>While editing these scripts, we certainly don’t want to be forced to recompile every time we make a change to the JavaScript. After all, one of the nice things about JavaScript is that it <em>doesn’t</em> require precompilation. Even worse, using a JavaScript debugger against minified files is a nightmare I wouldn’t recommend to anyone. </p>
<p>The easiest way I know of to ensure that the correct scripts are emitted for both scenarios is to <a href="http://www.west-wind.com/Weblog/posts/10228.aspx" target="_blank">check the IsDebuggingEnabled property of the HttpContext</a>:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;head&gt;
&lt;% if (HttpContext.Current.IsDebuggingEnabled) { %&gt;
  &lt;script type=&quot;text/javascript&quot; src=&quot;js/01-jquery-1.3.2.debug.js&quot;&gt;&lt;/script&gt;
  &lt;script type=&quot;text/javascript&quot; src=&quot;js/05-jquery-jtemplates.debug.js&quot;&gt;&lt;/script&gt;
  &lt;script type=&quot;text/javascript&quot; src=&quot;js/10-default.debug.js&quot;&gt;&lt;/script&gt;
&lt;% } else { %&gt;
  &lt;script type=&quot;text/javascript&quot; src=&quot;js/js-bundle.min.js&quot;&gt;&lt;/script&gt;
&lt;% } %&gt;
&lt;/head&gt;</pre></div></div>

<p>When the web.config’s compilation mode is set to debug, the *.debug.js versions of the files are referenced, and the auto-minified bundle otherwise. Now we have the best of both worlds.</p>
<h3>Conclusion</h3>
<p>I hope you’ll find that this technique is a good compromise between the tedium of using manual minification tools and the overwrought complexity of setting up some of the more “<a href="http://en.wikipedia.org/wiki/Enterprise_software" rel="nofollow" target="_blank">enterprisey</a>” automation solutions.</p>
<p>One not-so-obvious benefit that I’ve noticed stems from minification’s automatic comment stripping. Without worry about your comments burdening the size of the client-side payload or being distributed across the Internet, you’re more likely to comment your JavaScript well. Dealing with a dynamic language, sans-compiler, I find that <strong>comments are often crucial to maintainability</strong>.</p>
<p>This is one of those problems with quite a few perfectly legitimate solutions. What do you think of this solution? How do you normally handle this?</p>
<h3>Get the source</h3>
<p>For demonstration, I took my <a href="http://encosia.com/2008/06/26/use-jquery-and-aspnet-ajax-to-build-a-client-side-repeater/" target="_blank">jQuery client-side repeater example</a> and applied this technique. Having several JavaScript includes (one that’s full of comments), it’s a perfect candidate for combining and compression.</p>
<p>One particular thing to notice in this example is the use of numeric prefixes to order the JavaScript includes, as mentioned earlier. This naming scheme is <strong>crucial when dealing with interdependent scripts</strong>. If the scripts are combined in the wrong order, your functionality will break just the same as if you had used script reference tags in the wrong order.</p>
<p><a href="http://encosia.com/source/jsmin-build.zip"><img title="jsmin-build.zip" border="0" alt="Download Source: jsmin-build.zip" src="http://encosia.com/blog/wp-content/uploads/2009/05/download-bar-jsmin-build.png" width="492" height="46" /></a></p>
<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/05/20/automatically-minify-and-combine-javascript-in-visual-studio/">Automatically minify and combine JavaScript in Visual Studio</a></p>
<div class="feedflare">
<a href="http://feeds.encosia.com/~ff/Encosia?a=Tf7mDx6wdRA:BnUpfPY3-DM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Encosia?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=Tf7mDx6wdRA:BnUpfPY3-DM:aWKiLpGymzw"><img src="http://feeds.feedburner.com/~ff/Encosia?d=aWKiLpGymzw" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=Tf7mDx6wdRA:BnUpfPY3-DM:30RXbuXOgYA"><img src="http://feeds.feedburner.com/~ff/Encosia?d=30RXbuXOgYA" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=Tf7mDx6wdRA:BnUpfPY3-DM:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/Encosia?i=Tf7mDx6wdRA:BnUpfPY3-DM:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=Tf7mDx6wdRA:BnUpfPY3-DM:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/Encosia?i=Tf7mDx6wdRA:BnUpfPY3-DM:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Encosia/~4/Tf7mDx6wdRA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/05/20/automatically-minify-and-combine-javascript-in-visual-studio/feed/</wfw:commentRss>
		<slash:comments>36</slash:comments>
		<feedburner:origLink>http://encosia.com/2009/05/20/automatically-minify-and-combine-javascript-in-visual-studio/</feedburner:origLink></item>
		<item>
		<title>What ASP.NET developers should know about jQuery</title>
		<link>http://feeds.encosia.com/~r/Encosia/~3/HCPctGlUVM0/</link>
		<comments>http://encosia.com/2009/05/13/what-aspnet-developers-should-know-about-jquery/#comments</comments>
		<pubDate>Wed, 13 May 2009 17:10:41 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=855</guid>
		<description><![CDATA[As much as I enjoyed attending MIX09 this year, it wasn’t a difficult decision when Karsten asked me to write an article for the MIX Online site.
Reading this here, there’s a good chance the article is targeted below the amount of jQuery expertise you already have. However, it’s been brought to my attention that some [...]<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/05/13/what-aspnet-developers-should-know-about-jquery/">What ASP.NET developers should know about jQuery</a></p>
]]></description>
			<content:encoded><![CDATA[<p>As much as I enjoyed attending <a href="http://live.visitmix.com/" target="_blank">MIX09</a> this year, it wasn’t a difficult decision when <a href="http://visitmix.com/About/karstenj" target="_blank">Karsten</a> asked me to write an article for the MIX Online site.</p>
<p>Reading this here, there’s a good chance the article is targeted below the amount of jQuery expertise you already have. However, it’s been brought to my attention that some readers have found it useful for sending to their more JavaScript-phobic coworkers.</p>
<p>So, I decided that it’s worth mentioning here after all:</p>
<blockquote><p>It’s hard to believe that <strong>JavaScript is already well over a decade old</strong>. Often relegated to marginal tasks in its early years, JavaScript has grown to become a pillar of modern web development. With the current popularity of DHTML and AJAX, it can be difficult to find a site that <strong>doesn’t</strong> use JavaScript anymore. One of the driving forces behind JavaScript’s newfound popularity is a proliferation of JavaScript frameworks, such as <strong>jQuery</strong>.</p>
<p>&#160;</p>
<p>Why?</p></blockquote>
<p><a class="more-link" href="http://visitmix.com/Opinions/What-ASPNET-Developers-Should-Know-About-jQuery" target="_blank">Click here to continue reading this article on the MIX Online site &raquo;</a></p>
<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/05/13/what-aspnet-developers-should-know-about-jquery/">What ASP.NET developers should know about jQuery</a></p>
<div class="feedflare">
<a href="http://feeds.encosia.com/~ff/Encosia?a=HCPctGlUVM0:8bYm9JkZSiw:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Encosia?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=HCPctGlUVM0:8bYm9JkZSiw:aWKiLpGymzw"><img src="http://feeds.feedburner.com/~ff/Encosia?d=aWKiLpGymzw" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=HCPctGlUVM0:8bYm9JkZSiw:30RXbuXOgYA"><img src="http://feeds.feedburner.com/~ff/Encosia?d=30RXbuXOgYA" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=HCPctGlUVM0:8bYm9JkZSiw:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/Encosia?i=HCPctGlUVM0:8bYm9JkZSiw:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=HCPctGlUVM0:8bYm9JkZSiw:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/Encosia?i=HCPctGlUVM0:8bYm9JkZSiw:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Encosia/~4/HCPctGlUVM0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/05/13/what-aspnet-developers-should-know-about-jquery/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://encosia.com/2009/05/13/what-aspnet-developers-should-know-about-jquery/</feedburner:origLink></item>
		<item>
		<title>How I handle JSON dates returned by ASP.NET AJAX</title>
		<link>http://feeds.encosia.com/~r/Encosia/~3/Okgn0H5ch5w/</link>
		<comments>http://encosia.com/2009/04/27/how-i-handle-json-dates-returned-by-aspnet-ajax/#comments</comments>
		<pubDate>Mon, 27 Apr 2009 15:22:44 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=853</guid>
		<description><![CDATA[
The problem of how to handle dates in JSON is one of the more troublesome issues that may arise when directly calling ASP.NET AJAX web services and page methods.
Unlike every other data type in the language, JavaScript offers no declarative method for expressing a Date. Consequently, embedding them within JSON requires a bit of fancy [...]<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/04/27/how-i-handle-json-dates-returned-by-aspnet-ajax/">How I handle JSON dates returned by ASP.NET AJAX</a></p>
]]></description>
			<content:encoded><![CDATA[<p><img style="border: 1px solid #000;" title="image" border="0" alt="A calendar" src="http://encosia.com/blog/wp-content/uploads/2009/04/calendar-blocks.jpg" width="490" height="215" /></p>
<p>The problem of how to handle dates in JSON is one of the more troublesome issues that may arise when <em>directly</em> calling ASP.NET AJAX web services and page methods.</p>
<p>Unlike every other data type in the language, <strong>JavaScript offers no declarative method for expressing a Date</strong>. Consequently, embedding them within JSON requires a bit of fancy footwork. Since the question of how I handle this problem is something asked often in emails and in comments on other posts here, I want to address the topic with its own post.</p>
<p>To that end, I will attempt to explain <strong>what exactly the problem is</strong> with dates in JSON, <strong>how ASP.NET AJAX solves it</strong>, and <strong>my alternative solution</strong> that I believe is easier and works just as well in most cases.</p>
<h3>What’s the problem?</h3>
<p>The fundamental problem is that JavaScript does not provide a way to declaratively express <a href="http://www.w3schools.com/jS/js_obj_date.asp" rel="nofollow" target="_blank">Date objects</a>. You may previously have seen this <a href="http://www.nikhilk.net/DateSyntaxForJSON.aspx" target="_blank">described as (the lack of) <strong>a Date literal</strong></a>.</p>
<p>What are literals? To illustrate, these are literals for several other data types:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// String</span>
<span style="color: #3366CC;">'foo'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Number</span>
<span style="color: #CC0000;">3.14</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Boolean</span>
<span style="color: #003366; font-weight: bold;">true</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Array</span>
<span style="color: #009900;">&#91;</span>1<span style="color: #339933;">,</span> 2<span style="color: #339933;">,</span> 3<span style="color: #339933;">,</span> 5<span style="color: #339933;">,</span> 7<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Object</span>
<span style="color: #009900;">&#123;</span> pi<span style="color: #339933;">:</span> 3.14<span style="color: #339933;">,</span> phi<span style="color: #339933;">:</span> 1.62 <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Unfortunately, when it comes to dates, the lack of a literal means that the only way to create one is by explicitly initializing a Date object:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Correct.</span>
<span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'4/26/09'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Correct (the month is 0 indexed, hence the 3).</span>
<span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span>2009<span style="color: #339933;">,</span> 3<span style="color: #339933;">,</span> 26<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Incorrect. This is a string, not a Date.</span>
<span style="color: #3366CC;">'4/26/09'</span><span style="color: #339933;">;</span></pre></div></div>

<p>While this limitation is fine when writing client-side JavaScript code, it leaves us without a good way to transmit dates within JSON objects.</p>
<h3>How ASP.NET AJAX handles it</h3>
<p>While the lack of a date literal is a problem, it’s certainly not without solution.</p>
<p>In fact, ASP.NET AJAX <strong>already handles this</strong> if you’re using MicrosoftAjax.js to call your services. You may not have even noticed as server-side DateTime values are transparently converted into JavaScript Date objects on the client-side.</p>
<p>For example, consider this web service:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span><span style="color: #000000;">System.<span style="color: #0000FF;">Web</span></span>.<span style="color: #0000FF;">Script</span>.<span style="color: #0000FF;">Services</span>.<span style="color: #0000FF;">ScriptService</span><span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> DateService <span style="color: #008000;">:</span> <span style="color: #000000;">System.<span style="color: #0000FF;">Web</span>.<span style="color: #0000FF;">Services</span></span>.<span style="color: #0000FF;">WebService</span>
<span style="color: #000000;">&#123;</span>
  <span style="color: #000000;">&#91;</span>WebMethod<span style="color: #000000;">&#93;</span>
  <span style="color: #0600FF;">public</span> DateTime GetDate<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
  <span style="color: #000000;">&#123;</span>
    <span style="color: #0600FF;">return</span> <span style="color: #008000;">new</span> DateTime<span style="color: #000000;">&#40;</span>2009, 4, 26<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>If you <a href="http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/" target="_blank">consume that web service with jQuery</a> (or any method that circumvents the ScriptManager), you’ll find that ASP.NET AJAX serializes the DateTime as an escaped JavaScript Date initializer:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#123;</span><span style="color: #3366CC;">&quot;d&quot;</span><span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;<span style="color: #000099; font-weight: bold;">\/</span>Date(1240718400000)<span style="color: #000099; font-weight: bold;">\/</span>&quot;</span><span style="color: #009900;">&#125;</span></pre></div></div>

<p><em>Note: If you&#8217;re unsure about why the &#8220;d&#8221; is there, be sure to see <a href="http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/">my recent post about this security feature which was added in ASP.NET 3.5</a>.</em></p>
<p>On the client-side, MicrosoftAjax.js uses a regular expression to isolate any Date constructors and then eval() to initialize Date objects. The end result is that proper JavaScript Date objects are instantiated for every DateTime value returned.</p>
<p>However, if you’re <em>not</em> using MicrosoftAjax.js (i.e. the ScriptManager) to call your services, you’ve got a bit of a mess to decode. You can <a href="http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx" target="_blank">use regex machinations to work around the problem</a>, but is that really necessary?</p>
<h3>How I handle it</h3>
<p>Consider <em>why</em> you want to send a DateTime to the client-side to begin with. Most often, you’re <strong>displaying a string representation of it</strong> and have no need for the proper JavaScript Date object.</p>
<p>What’s more, if you end up with a JavaScript Date object, you’ll probably use additional code or a JavaScript library to <strong>display it in a user-friendly format</strong>.</p>
<p>As much as I appreciate a clever workaround, I’d much rather avoid the problem completely. Rather than jump through all of these hoops to instantiate a JavaScript Date object on the client-side and then format it, <strong>I suggest simply returning a formatted string</strong>.</p>
<p>For example, we might modify the previous example like so:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#91;</span>System.<span style="color: #660066;">Web</span>.<span style="color: #660066;">Script</span>.<span style="color: #660066;">Services</span>.<span style="color: #660066;">ScriptService</span><span style="color: #009900;">&#93;</span>
<span style="color: #003366; font-weight: bold;">public</span> <span style="color: #003366; font-weight: bold;">class</span> DateService <span style="color: #339933;">:</span> System.<span style="color: #660066;">Web</span>.<span style="color: #660066;">Services</span>.<span style="color: #660066;">WebService</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #009900;">&#91;</span>WebMethod<span style="color: #009900;">&#93;</span>
  <span style="color: #003366; font-weight: bold;">public</span> string GetDate<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">new</span> DateTime<span style="color: #009900;">&#40;</span>2009<span style="color: #339933;">,</span> 4<span style="color: #339933;">,</span> 26<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ToLongDateString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Now, calling the service will return this JSON:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#123;</span><span style="color: #3366CC;">&quot;d&quot;</span><span style="color: #339933;">:</span><span style="color: #3366CC;">&quot;Sunday, April 26, 2009&quot;</span><span style="color: #009900;">&#125;</span></pre></div></div>

<p>No more regular expressions. No more JavaScript Date objects. No more worrying about formatting the data on the client-side.</p>
<p>Even better, no functionality is lost. If we need to instantiate Dates, we still can.</p>
<h3>Still want Dates?</h3>
<p>Even if you <em>do</em> end up needing JavaScript Date objects, <strong>DateTime strings are sufficient for instantiating them</strong>. JavaScript’s Date constructor is very flexible:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// ASP.NET AJAX form</span>
<span style="color: #003366; font-weight: bold;">var</span> foo <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span>1240718400000<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// DateTime.ToLongDateString() form</span>
<span style="color: #003366; font-weight: bold;">var</span> bar <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Sunday, April 26, 2009'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// DateTime.ToShortDateString() form</span>
<span style="color: #003366; font-weight: bold;">var</span> baz <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'4/26/2009'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// true!</span>
foo <span style="color: #339933;">===</span> bar <span style="color: #339933;">===</span> baz<span style="color: #339933;">;</span></pre></div></div>

<p>By delaying string-to-Date conversions until truly necessary, we save effort on the server- and client-side. Not only that, but we have the option of retaining both the formatted string <em>and</em> the JavaScript Date to use as desired.</p>
<p>The best of both worlds.</p>
<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/04/27/how-i-handle-json-dates-returned-by-aspnet-ajax/">How I handle JSON dates returned by ASP.NET AJAX</a></p>
<div class="feedflare">
<a href="http://feeds.encosia.com/~ff/Encosia?a=Okgn0H5ch5w:-1AdCwXRcdM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Encosia?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=Okgn0H5ch5w:-1AdCwXRcdM:aWKiLpGymzw"><img src="http://feeds.feedburner.com/~ff/Encosia?d=aWKiLpGymzw" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=Okgn0H5ch5w:-1AdCwXRcdM:30RXbuXOgYA"><img src="http://feeds.feedburner.com/~ff/Encosia?d=30RXbuXOgYA" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=Okgn0H5ch5w:-1AdCwXRcdM:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/Encosia?i=Okgn0H5ch5w:-1AdCwXRcdM:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=Okgn0H5ch5w:-1AdCwXRcdM:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/Encosia?i=Okgn0H5ch5w:-1AdCwXRcdM:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Encosia/~4/Okgn0H5ch5w" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/04/27/how-i-handle-json-dates-returned-by-aspnet-ajax/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
		<feedburner:origLink>http://encosia.com/2009/04/27/how-i-handle-json-dates-returned-by-aspnet-ajax/</feedburner:origLink></item>
		<item>
		<title>Using complex types to make calling services less… complex</title>
		<link>http://feeds.encosia.com/~r/Encosia/~3/DsL3MYQPhVw/</link>
		<comments>http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/#comments</comments>
		<pubDate>Tue, 07 Apr 2009 08:33:22 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=849</guid>
		<description><![CDATA[A detailed examination of how jQuery can call ASP.NET AJAX web services (or page methods) with complex types as parameters, to simplify the process of serializing and sending several fields of data at a time.<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/">Using complex types to make calling services less&#8230; complex</a></p>
]]></description>
			<content:encoded><![CDATA[<p>So far, my examples of using jQuery to interact with ASP.NET AJAX services have avoided <strong>passing complex data to the server</strong> during the request. This has been intentional, because I didn’t want to over-complicate the examples.</p>
<p>For primarily read-only scenarios, like <a href="http://encosia.com/2008/06/26/use-jquery-and-aspnet-ajax-to-build-a-client-side-repeater/">the RSS reader examples</a>, passing just a few simple values to the service is often all you need. However, this scalar approach quickly becomes untenable when making real-world service calls.</p>
<p>In this post, I’m going to show you how <strong>passing complex types </strong><strong>to the server</strong> helps alleviate complexity, how <strong>json2.js and a data transfer object (DTO) facilitates this</strong>, and how to <strong>use jQuery to very easily build the DTO</strong>.</p>
<h3>Setting the stage</h3>
<p>Let’s say that we want to improve the performance of a data entry application used to add <strong>Person</strong> records to a database. The original version was developed quickly using an UpdatePanel, <a href="http://encosia.com/2007/07/11/why-aspnet-ajax-updatepanels-are-dangerous/">but performs poorly</a>. Not wanting the Person-data-entry-department to spend more time waiting than they do typing, we must find a way to improve the application’s performance.</p>
<p>Having done some research, we might decide that replacing the UpdatePanel with <a href="http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/">jQuery and a web service would be a great way to speed things up</a>.</p>
<h3>A foundation and a facade</h3>
<p>The properties of the existing <strong>Person</strong> class could be as simple as this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Person
<span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> FirstName <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
  <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> LastName <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
  <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Address <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
  <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> City <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
  <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> State <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
  <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> Zip <span style="color: #000000;">&#123;</span> get<span style="color: #008000;">;</span> set<span style="color: #008000;">;</span> <span style="color: #000000;">&#125;</span>
&nbsp;
  <span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> Add<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
  <span style="color: #000000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">// Magic happens here.</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>The original entry form probably used TextBox controls, but that will no longer be necessary. Regular HTML input elements carry less overhead and ensure that we don’t have to worry about <a href="http://encosia.com/2007/08/08/robust-aspnet-control-referencing-in-javascript/">ClientID issues</a>:</p>

<div class="wp_syntax"><div class="code"><pre class="asp" style="font-family:monospace;"><span style="color: #006600; font-weight: bold;">&lt;</span>label <span style="color: #990099; font-weight: bold;">for</span><span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;FirstName&quot;</span><span style="color: #006600; font-weight: bold;">&gt;</span>First Name<span style="color: #006600; font-weight: bold;">:&lt;/</span>label<span style="color: #006600; font-weight: bold;">&gt;</span>
<span style="color: #006600; font-weight: bold;">&lt;</span>input type<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;text&quot;</span> id<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;FirstName&quot;</span> <span style="color: #006600; font-weight: bold;">/&gt;</span>
&nbsp;
<span style="color: #006600; font-weight: bold;">&lt;</span>label <span style="color: #990099; font-weight: bold;">for</span><span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;LastName&quot;</span><span style="color: #006600; font-weight: bold;">&gt;</span>Last Name<span style="color: #006600; font-weight: bold;">:&lt;/</span>label<span style="color: #006600; font-weight: bold;">&gt;</span>
<span style="color: #006600; font-weight: bold;">&lt;</span>input type<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;text&quot;</span> id<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;LastName&quot;</span> <span style="color: #006600; font-weight: bold;">/&gt;</span>
&nbsp;
<span style="color: #006600; font-weight: bold;">&lt;</span>label <span style="color: #990099; font-weight: bold;">for</span><span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;Address&quot;</span><span style="color: #006600; font-weight: bold;">&gt;</span>Address<span style="color: #006600; font-weight: bold;">:&lt;/</span>label<span style="color: #006600; font-weight: bold;">&gt;</span>
<span style="color: #006600; font-weight: bold;">&lt;</span>input type<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;text&quot;</span> id<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;Address&quot;</span> <span style="color: #006600; font-weight: bold;">/&gt;</span>
&nbsp;
<span style="color: #006600; font-weight: bold;">&lt;</span>label <span style="color: #990099; font-weight: bold;">for</span><span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;City&quot;</span><span style="color: #006600; font-weight: bold;">&gt;</span>City<span style="color: #006600; font-weight: bold;">:&lt;/</span>label<span style="color: #006600; font-weight: bold;">&gt;</span>
<span style="color: #006600; font-weight: bold;">&lt;</span>input type<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;text&quot;</span> id<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;City&quot;</span> <span style="color: #006600; font-weight: bold;">/&gt;</span>
&nbsp;
<span style="color: #006600; font-weight: bold;">&lt;</span>label <span style="color: #990099; font-weight: bold;">for</span><span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;State&quot;</span><span style="color: #006600; font-weight: bold;">&gt;</span>State<span style="color: #006600; font-weight: bold;">:&lt;/</span>label<span style="color: #006600; font-weight: bold;">&gt;</span>
<span style="color: #006600; font-weight: bold;">&lt;</span>input type<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;text&quot;</span> id<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;State&quot;</span> <span style="color: #006600; font-weight: bold;">/&gt;</span>
&nbsp;
<span style="color: #006600; font-weight: bold;">&lt;</span>label <span style="color: #990099; font-weight: bold;">for</span><span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;Zip&quot;</span><span style="color: #006600; font-weight: bold;">&gt;</span>Zip<span style="color: #006600; font-weight: bold;">:&lt;/</span>label<span style="color: #006600; font-weight: bold;">&gt;</span>
<span style="color: #006600; font-weight: bold;">&lt;</span>input type<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;text&quot;</span> id<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;Zip&quot;</span> <span style="color: #006600; font-weight: bold;">/&gt;</span>
&nbsp;
<span style="color: #006600; font-weight: bold;">&lt;</span>input type<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;button&quot;</span> id<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;Save&quot;</span> value<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;Save&quot;</span> <span style="color: #006600; font-weight: bold;">/&gt;</span></pre></div></div>

<p>Note that the input elements have IDs matching the corresponding Person property. This will help us implement an improvement to our client-side code later on.</p>
<h3>One way <em>not</em> to do it</h3>
<p>Now that we’ve had a look at the front and back ends, it’s time to connect them together with a web service. One unfortunate anti-pattern that often emerges in this situation is a service method with too many parameters:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>WebMethod<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> AddPerson<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">string</span> FirstName, <span style="color: #FF0000;">string</span> LastName, 
                      <span style="color: #FF0000;">string</span> Address, <span style="color: #FF0000;">string</span> City,
                      <span style="color: #FF0000;">string</span> State, <span style="color: #FF0000;">string</span> Zip<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
  Person newPerson <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Person<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
  newPerson.<span style="color: #0000FF;">FirstName</span> <span style="color: #008000;">=</span> FirstName<span style="color: #008000;">;</span>
  newPerson.<span style="color: #0000FF;">LastName</span> <span style="color: #008000;">=</span> LastName<span style="color: #008000;">;</span>
  newPerson.<span style="color: #0000FF;">Address</span> <span style="color: #008000;">=</span> Address<span style="color: #008000;">;</span>
  newPerson.<span style="color: #0000FF;">City</span> <span style="color: #008000;">=</span> City<span style="color: #008000;">;</span>
  newPerson.<span style="color: #0000FF;">State</span> <span style="color: #008000;">=</span> State<span style="color: #008000;">;</span>
  newPerson.<span style="color: #0000FF;">Zip</span> <span style="color: #008000;">=</span> Zip<span style="color: #008000;">;</span>
&nbsp;
  newPerson.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Not only do we have to manually keep that method’s parameter list in sync with the Person class, but we also have to maintain the pointless object initialization code.</p>
<p>Calling the service on the client-side is just as messy too:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
  type<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;POST&quot;</span><span style="color: #339933;">,</span>
  contentType<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;application/json; charset=utf-8&quot;</span><span style="color: #339933;">,</span>
  url<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;PersonService.asmx/AddPerson&quot;</span><span style="color: #339933;">,</span>
  data<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;{'FirstName':'&quot;</span> <span style="color: #339933;">+</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#FirstName&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;', &quot;</span>
       <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;'LastName':'&quot;</span> <span style="color: #339933;">+</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#LastName&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;',&quot;</span>
       <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;'Address':'&quot;</span> <span style="color: #339933;">+</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#Address&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;',&quot;</span>
       <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;'City':'&quot;</span> <span style="color: #339933;">+</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#City&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;',&quot;</span>
       <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;'State':'&quot;</span> <span style="color: #339933;">+</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#State&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;',&quot;</span>
       <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;'Zip':'&quot;</span> <span style="color: #339933;">+</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#Zip&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;'}&quot;</span><span style="color: #339933;">,</span>
  dataType<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;json&quot;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>As <em>ugly</em> as it is, that <strong>will</strong> work and be much faster than anything we could possibly implement in an UpdatePanel. <strong>It would also be a nightmare to maintain</strong>.</p>
<p>Let’s continue improving this until it’s something we can be proud of.</p>
<h3>Things can only get better</h3>
<p>A good first improvement is to refactor the web service to get rid of the parameter list and redundant object initialization.</p>
<p>Most examples (including my own) never go beyond passing a string, integer, or maybe an array, but that only scratches the surface of what’s possible. An underutilized feature of ASP.NET AJAX “ScriptService” methods is that <strong>they can accept complex types as parameters</strong> and parse those parameters from JSON.</p>
<p>Leveraging this, we can dramatically simplify the web service:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>WebMethod<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">void</span> AddPerson<span style="color: #000000;">&#40;</span>Person NewPerson<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
  NewPerson.<span style="color: #0000FF;">Add</span><span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Unfortunately, calling this method on the client-side is just as messy as ever:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
  type<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;POST&quot;</span><span style="color: #339933;">,</span>
  contentType<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;application/json; charset=utf-8&quot;</span><span style="color: #339933;">,</span>
  url<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;PersonService.asmx/AddPerson&quot;</span><span style="color: #339933;">,</span>
  data<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;{'NewPerson': {'FirstName':'&quot;</span> <span style="color: #339933;">+</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#FirstName&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;',&quot;</span>
                     <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;'LastName':'&quot;</span> <span style="color: #339933;">+</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#LastName&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;',&quot;</span>
                     <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;'Address':'&quot;</span> <span style="color: #339933;">+</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#Address&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;',&quot;</span>
                     <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;'City':'&quot;</span> <span style="color: #339933;">+</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#City&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;',&quot;</span>
                     <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;'State':'&quot;</span> <span style="color: #339933;">+</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#State&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;',&quot;</span>
                     <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;'Zip':'&quot;</span> <span style="color: #339933;">+</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#Zip&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;'}}&quot;</span><span style="color: #339933;">,</span>
  dataType<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;json&quot;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>That’s about the same as before. However, instead of sending a flat group of input field values, now we’re sending a JSON object corresponding to the Person class.</p>
<p>In other words, that declarative JSON data string is equivalent to this JavaScript:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> NewPerson <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Object<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
NewPerson.<span style="color: #660066;">FirstName</span> <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#FirstName&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
NewPerson.<span style="color: #660066;">LastName</span> <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#LastName&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
NewPerson.<span style="color: #660066;">Address</span> <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#Address&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
NewPerson.<span style="color: #660066;">City</span> <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#City&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
NewPerson.<span style="color: #660066;">State</span> <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#State&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
NewPerson.<span style="color: #660066;">Zip</span> <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#Zip&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>ASP.NET AJAX seamlessly translates the JSON string into a new instance of our Person class and passes that object into the service method. It works exactly as you’d expect, which is almost too good to be true!</p>
<h3>Cleaning up the client-side</h3>
<p>The best way to improve the client-side situation is to abandon our manual JSON serialization in the $.ajax() call. It works well enough for a couple parameters, but has devolved into <a href="http://en.wikipedia.org/wiki/Big_ball_of_mud" rel="nofollow" target="_blank">a ball of mud</a> as the parameter count increased.</p>
<p>Douglas Crockford’s <a href="http://www.json.org/js.html" target="_blank">json2.js</a> contains a <strong>stringify</strong> function which is exactly what we need. Stringify() accepts a JSON object and returns the same type of string that we’re manually concatenating together right now.</p>
<p>Using json2.js, our previous client-side code can be refactored to this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Initialize the object, before adding data to it.</span>
<span style="color: #003366; font-weight: bold;">var</span> NewPerson <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Object<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
NewPerson.<span style="color: #660066;">FirstName</span> <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#FirstName&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
NewPerson.<span style="color: #660066;">LastName</span> <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#LastName&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
NewPerson.<span style="color: #660066;">Address</span> <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#Address&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
NewPerson.<span style="color: #660066;">City</span> <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#City&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
NewPerson.<span style="color: #660066;">State</span> <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#State&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
NewPerson.<span style="color: #660066;">Zip</span> <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#Zip&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
$.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
  type<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;POST&quot;</span><span style="color: #339933;">,</span>
  contentType<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;application/json; charset=utf-8&quot;</span><span style="color: #339933;">,</span>
  url<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;PersonService.asmx/AddPerson&quot;</span><span style="color: #339933;">,</span>
  data<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;{'NewPerson':&quot;</span> <span style="color: #339933;">+</span> JSON.<span style="color: #660066;">stringify</span><span style="color: #009900;">&#40;</span>NewPerson<span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;}&quot;</span><span style="color: #339933;">,</span>
  dataType<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;json&quot;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>It’s still a fair amount of code, but <strong>it’s much cleaner</strong>. If you dropped this in my lap and asked me to maintain it, we wouldn’t have a problem.</p>
<h3>Using a data transfer object</h3>
<p>Adding json2.js and its stringify functionality made our code significantly more readable, but <strong>we can do better</strong>. There’s still a bit of manual JSON string building in the $.ajax() call, which would be nice to avoid.</p>
<p>Since we already have JSON.stringify() at our disposal, we can build and stringify a JSON object to represent the entire request&#8217;s data instead of just the form data:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Initialize the object, before adding data to it.</span>
<span style="color: #006600; font-style: italic;">//  { } is declarative shorthand for new Object().</span>
<span style="color: #003366; font-weight: bold;">var</span> NewPerson <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
NewPerson.<span style="color: #660066;">FirstName</span> <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#FirstName&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
NewPerson.<span style="color: #660066;">LastName</span> <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#LastName&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
NewPerson.<span style="color: #660066;">Address</span> <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#Address&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
NewPerson.<span style="color: #660066;">City</span> <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#City&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
NewPerson.<span style="color: #660066;">State</span> <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#State&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
NewPerson.<span style="color: #660066;">Zip</span> <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#Zip&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Create a data transfer object (DTO) with the proper structure.</span>
<span style="color: #003366; font-weight: bold;">var</span> DTO <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span> <span style="color: #3366CC;">'NewPerson'</span> <span style="color: #339933;">:</span> NewPerson <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
$.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
  type<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;POST&quot;</span><span style="color: #339933;">,</span>
  contentType<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;application/json; charset=utf-8&quot;</span><span style="color: #339933;">,</span>
  url<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;PersonService.asmx/AddPerson&quot;</span><span style="color: #339933;">,</span>
  data<span style="color: #339933;">:</span> JSON.<span style="color: #660066;">stringify</span><span style="color: #009900;">&#40;</span>DTO<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
  dataType<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;json&quot;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>By creating a data transfer object (often referred to as a DTO), we’ve <strong>completely eliminated all manual JSON string building</strong>.</p>
<p>Even though it’s a small change, it feels quite a bit cleaner doesn’t it?</p>
<h3>Bonus: jQuery makes everything better</h3>
<p>Using the DTO makes sending the form data clean, but we’re still stuck with <strong>the unnecessary chore of maintaining the NewPerson initialization block</strong>. jQuery is perfectly suited to solving this problem:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Initialize the object, before adding data to it.</span>
<span style="color: #006600; font-style: italic;">//  { } is declarative shorthand for new Object().</span>
<span style="color: #003366; font-weight: bold;">var</span> NewPerson <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Iterate over all the text fields and build an</span>
<span style="color: #006600; font-style: italic;">//  object with their values as named properties.</span>
$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">':text'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">each</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #006600; font-style: italic;">// Ex: NewPerson['FirstName'] = $('#FirstName').val();</span>
  NewPerson<span style="color: #009900;">&#91;</span><span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">id</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">this</span>.<span style="color: #660066;">value</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Create a data transfer object (DTO) with the proper structure.</span>
<span style="color: #003366; font-weight: bold;">var</span> DTO <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span> <span style="color: #3366CC;">'NewPerson'</span> <span style="color: #339933;">:</span> NewPerson <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
$.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
  type<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;POST&quot;</span><span style="color: #339933;">,</span>
  contentType<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;application/json; charset=utf-8&quot;</span><span style="color: #339933;">,</span>
  url<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;PersonService.asmx/AddPerson&quot;</span><span style="color: #339933;">,</span>
  data<span style="color: #339933;">:</span> JSON.<span style="color: #660066;">stringify</span><span style="color: #009900;">&#40;</span>DTO<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
  dataType<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;json&quot;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Using <a href="http://docs.jquery.com/Core/each" target="_blank">jQuery.each()</a> to iterate over the fields and build our client-side object is a nice improvement. Even in this simple example, it cuts down on the amount of JavaScript we have to write and maintain. In real-world scenarios where your objects have dozens of properties, this will save you a lot of time (and typos).</p>
<p>More important than saving a few keystrokes, <strong>we’ve got one less place to worry about updating if the Person class changes in the future</strong>. We can modify the Person class, update the entry form accordingly, and this will continue working.</p>
<h3>Conclusion</h3>
<p>We have <em>solidly</em> accomplished the goal of refactoring this until it’s something we can be proud of. There’s always room for improvement, but this will serve as a great start for writing robust, maintainable client-side service calls.</p>
<p><strong>Death by a thousand dependencies</strong>: When I first started experimenting with this <em>stringified DTO pattern</em>, I was reluctant to take on the json2.js dependency. However, it’s tiny when minified, has no dependencies of its own, and is ideal for rolling into another combined script. Its dependable functionality is well worth a few kilobytes.</p>
<p>A great thing about committing to the JSON.stringify usage is that <a href="http://blog.mozilla.com/webdev/2009/02/12/native-json-in-firefox-31/" target="_blank">web browsers are beginning to natively support it</a>. So, at some point in the future, you’ll actually be able to drop the json2.js dependency and this method will still work (faster).</p>
<p><strong>DTOs</strong>: If your server-side situation is more complex than this example (and it probably is), don’t be afraid to use a throw-away DTO class as the service method parameter.</p>
<p>For example, our Person class could also have been a PersonDTO class, specifically intended to take these form submissions and merge them into a more complicated domain.</p>
<h3>Source</h3>
<p><a href="http://encosia.com/source/jQuery-DTO.zip"><img src="http://encosia.com/blog/wp-content/uploads/2009/04/jquery-dto-download-bar.png" alt="jQuery DTO source download" title="jQuery DTO source download" width="492" height="46" /></a></p>
<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/">Using complex types to make calling services less&#8230; complex</a></p>
<div class="feedflare">
<a href="http://feeds.encosia.com/~ff/Encosia?a=DsL3MYQPhVw:fFM8ti4iP2o:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Encosia?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=DsL3MYQPhVw:fFM8ti4iP2o:aWKiLpGymzw"><img src="http://feeds.feedburner.com/~ff/Encosia?d=aWKiLpGymzw" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=DsL3MYQPhVw:fFM8ti4iP2o:30RXbuXOgYA"><img src="http://feeds.feedburner.com/~ff/Encosia?d=30RXbuXOgYA" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=DsL3MYQPhVw:fFM8ti4iP2o:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/Encosia?i=DsL3MYQPhVw:fFM8ti4iP2o:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=DsL3MYQPhVw:fFM8ti4iP2o:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/Encosia?i=DsL3MYQPhVw:fFM8ti4iP2o:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Encosia/~4/DsL3MYQPhVw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/feed/</wfw:commentRss>
		<slash:comments>41</slash:comments>
		<feedburner:origLink>http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/</feedburner:origLink></item>
		<item>
		<title>PostBack Ritalin v1.0</title>
		<link>http://feeds.encosia.com/~r/Encosia/~3/kU6wyBBsmQw/</link>
		<comments>http://encosia.com/2009/04/06/postback-ritalin-v1-0/#comments</comments>
		<pubDate>Mon, 06 Apr 2009 06:46:29 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[PostBack Ritalin]]></category>
		<category><![CDATA[UI]]></category>

		<guid isPermaLink="false">http://encosia.com/2009/04/06/postback-ritalin-v10/</guid>
		<description><![CDATA[Thanks to all of your excellent feedback during the months since the last release of PostBack Ritalin, an improved version is ready for release today. With the addition of “disable all elements”, I believe the control is now feature complete, worthy of a version 1.0 release.
Notable changes in v1.0 include:

Added disable all elements functionality to [...]<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/04/06/postback-ritalin-v1-0/">PostBack Ritalin v1.0</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Thanks to all of your excellent feedback during the months since the last release of <a href="http://encosia.com/downloads/postback-ritalin/" target="_blank">PostBack Ritalin</a>, an improved version is ready for release today. With the addition of “disable all elements”, I believe <strong>the control is now feature complete, worthy of a version 1.0 release</strong>.</p>
<p>Notable changes in v1.0 include:</p>
<ul>
<li>Added <a href="http://encosia.com/2008/03/04/why-my-aspnet-ajax-forms-are-never-submitted-twice/" target="_blank">disable all elements functionality</a> to MonitoredUpdatePanels.</li>
<li>Fixed a bug in the WaitImage preloading functionality, that prevented the MonitoredUpdatePanels’ WaitImages from being preloaded.</li>
<li>Added both debug and release versions of the JavaScript resource. Your site’s compilation mode will determine which script version is embedded.</li>
<li>Fixed a problem handling postbacks raised by Button controls that have their UseSubmitBehavior property set to false.</li>
<li>Improved ClientID handling in naming containers.</li>
</ul>
<p>As always, you can visit <a href="http://encosia.com/downloads/postback-ritalin/" target="_blank">the PostBack Ritalin project page</a> to download the latest version, see usage examples, and find documentation.</p>
<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/04/06/postback-ritalin-v1-0/">PostBack Ritalin v1.0</a></p>
<div class="feedflare">
<a href="http://feeds.encosia.com/~ff/Encosia?a=kU6wyBBsmQw:ybtHTZ0qTMs:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Encosia?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=kU6wyBBsmQw:ybtHTZ0qTMs:aWKiLpGymzw"><img src="http://feeds.feedburner.com/~ff/Encosia?d=aWKiLpGymzw" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=kU6wyBBsmQw:ybtHTZ0qTMs:30RXbuXOgYA"><img src="http://feeds.feedburner.com/~ff/Encosia?d=30RXbuXOgYA" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=kU6wyBBsmQw:ybtHTZ0qTMs:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/Encosia?i=kU6wyBBsmQw:ybtHTZ0qTMs:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=kU6wyBBsmQw:ybtHTZ0qTMs:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/Encosia?i=kU6wyBBsmQw:ybtHTZ0qTMs:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Encosia/~4/kU6wyBBsmQw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/04/06/postback-ritalin-v1-0/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://encosia.com/2009/04/06/postback-ritalin-v1-0/</feedburner:origLink></item>
		<item>
		<title>$(document).ready() and pageLoad() are not the same!</title>
		<link>http://feeds.encosia.com/~r/Encosia/~3/hhnUZkucYmo/</link>
		<comments>http://encosia.com/2009/03/25/document-ready-and-pageload-are-not-the-same/#comments</comments>
		<pubDate>Wed, 25 Mar 2009 10:00:36 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=842</guid>
		<description><![CDATA[Recently, I’ve attended several presentations in which ASP.NET AJAX’s pageLoad() shortcut is demonstrated as interchangeable with jQuery’s $(document).ready() event. The suggestion that both methods are equivalent actually appears to be true in simple demos, but is not the case and is certain to lead to later confusion.
While they seem similar on the surface, $(document).ready() and [...]<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/03/25/document-ready-and-pageload-are-not-the-same/">$(document).ready() and pageLoad() are not the same!</a></p>
]]></description>
			<content:encoded><![CDATA[<p>Recently, I’ve attended several presentations in which ASP.NET AJAX’s pageLoad() shortcut is demonstrated as interchangeable with jQuery’s $(document).ready() event. The suggestion that both methods are equivalent actually appears to be true in simple demos, but is <strong>not the case</strong> and is <strong>certain to lead to later confusion</strong>.</p>
<p>While they seem similar on the surface, $(document).ready() and pageLoad() <strong>are very different behind the scenes</strong>. Determining the earliest point that it’s safe to modify the DOM requires a bit of black magic, and the two libraries approach that in their own unique ways. Additionally, <strong>pageLoad() is overloaded with some extra functionality which may surprise you</strong>.</p>
<p>In this post, I’ll clarify the major differences between jQuery and ASP.NET AJAX’s initialization functions, what implications those difference have in practice, and show you a third alternative when working with ASP.NET AJAX.</p>
<h3>Under the hood: $(document).ready()</h3>
<p>As you would expect from John Resig, jQuery’s method for determining when the DOM is ready uses an assortment of optimizations.</p>
<p>For example, if a browser supports the <strong>DOMContentLoaded</strong> event (as many non-IE browsers do), then it will fire on that event. However, IE can’t safely fire until the document’s <strong>readyState</strong> reaches “complete”, which is typically later.</p>
<p>If none of those optimizations are available, <strong>window.onload</strong> will trigger the event.</p>
<h3>Under the hood: pageLoad()</h3>
<p>Instead of targeting browser-specific optimizations, the ASP.NET AJAX pageLoad() shortcut function is called as a result of a more uniform process.</p>
<p>That process is queued up the same way on all browsers, via a call to setTimeout with a timeout of 0 milliseconds. This trick leverages JavaScript’s single-threaded execution model to (theoretically) push the init event back until just after the DOM has finished loading.</p>
<p>Counter-intuitively, this isn’t the only point at which pageLoad() is called. <strong>It is also called after every partial postback</strong>. It basically functions as a combination of <a href="http://msdn.microsoft.com/en-us/library/bb397532.aspx" rel="nofollow">Application.Init</a> <em>and</em> <a href="http://msdn.microsoft.com/en-us/library/bb383810.aspx" rel="nofollow">PageRequestManager.EndRequest</a>.</p>
<h3>Danger: UpdatePanels ahead</h3>
<p>Since pageLoad() is called after <strong>every</strong> UpdatePanel refresh, the complications that arise can be initially difficult to grasp. For example, you’ll often see code like this:</p>

<div class="wp_syntax"><div class="code"><pre class="asp" style="font-family:monospace;"><span style="color: #006600; font-weight: bold;">&lt;</span>script type<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;text/javascript&quot;</span><span style="color: #006600; font-weight: bold;">&gt;</span> 
  <span style="color: #0000ff; font-weight: bold;">function</span> pageLoad<span style="color: #006600; font-weight:bold;">&#40;</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #006600; font-weight:bold;">&#123;</span> 
    <span style="color: #ff6600;">// Initialization code here, meant to run once. </span>
  <span style="color: #006600; font-weight:bold;">&#125;</span> 
<span style="color: #006600; font-weight: bold;">&lt;/</span>script<span style="color: #006600; font-weight: bold;">&gt;</span>
&nbsp;
<span style="color: #006600; font-weight: bold;">&lt;</span>asp<span style="color: #006600; font-weight: bold;">:</span>ScriptManager runat<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;server&quot;</span> <span style="color: #006600; font-weight: bold;">/&gt;</span>
&nbsp;
<span style="color: #006600; font-weight: bold;">&lt;</span>asp<span style="color: #006600; font-weight: bold;">:</span>UpdatePanel runat<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;server&quot;</span><span style="color: #006600; font-weight: bold;">&gt;</span> 
  <span style="color: #006600; font-weight: bold;">&lt;</span>ContentTemplate<span style="color: #006600; font-weight: bold;">&gt;</span> 
    <span style="color: #006600; font-weight: bold;">&lt;</span>asp<span style="color: #006600; font-weight: bold;">:</span>Button runat<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;server&quot;</span> ID<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;Button1&quot;</span> <span style="color: #006600; font-weight: bold;">/&gt;</span> 
    <span style="color: #006600; font-weight: bold;">&lt;</span>asp<span style="color: #006600; font-weight: bold;">:</span>Literal runat<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;server&quot;</span> ID<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;TextBox1&quot;</span> <span style="color: #006600; font-weight: bold;">/&gt;</span> 
  <span style="color: #006600; font-weight: bold;">&lt;/</span>ContentTemplate<span style="color: #006600; font-weight: bold;">&gt;</span> 
<span style="color: #006600; font-weight: bold;">&lt;/</span>asp<span style="color: #006600; font-weight: bold;">:</span>UpdatePanel<span style="color: #006600; font-weight: bold;">&gt;</span></pre></div></div>

<p>That initialization code will execute on the initial load, and things will seem okay at first. However, <strong>pageLoad() will then continue to be called each time Button1 is triggered</strong>, resulting in the initialization code running more often than intended.</p>
<p>This problem is similar to the classic ASP.NET mistake of forgetting to test for IsPostBack during the server-side Page_Load event. Depending on the nature of your initialization code, you may not even notice that there’s a problem, but <em>it’s bound to catch up with you eventually</em>.</p>
<p><strong>In the case of initialization code that should run once, $(document).ready() is the ideal solution</strong>. It will do exactly what you need and nothing more.</p>
<h3>Sometimes, pageLoad() is exactly what you want</h3>
<p>While $(document).ready() is ideal for one-time initialization routines, it leaves you hanging if you have code that needs to be re-run after every partial postback. The <a href="http://docs.jquery.com/Events/live" rel="nofollow">LiveQuery functionality</a> added in jQuery v1.3+ helps with this, but only works for a limited set of functionality.</p>
<p>For example, what if we wanted to add a jQueryUI datepicker to the TextBox in the previous example? Adding it in $(document).ready() would work great, <strong>until</strong> a partial postback occurred. Then, the UpdatePanel’s new TextBox element would no longer have the datepicker wired up to it. <a href="http://encosia.com/2007/08/01/simplify-aspnet-ajax-client-side-page-initialization/">This is exactly where pageLoad() shines</a>:</p>

<div class="wp_syntax"><div class="code"><pre class="asp" style="font-family:monospace;"><span style="color: #006600; font-weight: bold;">&lt;</span>script type<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;text/javascript&quot;</span><span style="color: #006600; font-weight: bold;">&gt;</span>
  <span style="color: #0000ff; font-weight: bold;">function</span> pageLoad<span style="color: #006600; font-weight:bold;">&#40;</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #006600; font-weight:bold;">&#123;</span>
    $<span style="color: #006600; font-weight:bold;">&#40;</span><span style="color: #008000;">'#TextBox1').unbind();</span>
    $<span style="color: #006600; font-weight:bold;">&#40;</span><span style="color: #008000;">'#TextBox1').datepicker(); </span>
  <span style="color: #006600; font-weight:bold;">&#125;</span>
<span style="color: #006600; font-weight: bold;">&lt;/</span>script<span style="color: #006600; font-weight: bold;">&gt;</span>
&nbsp;
<span style="color: #006600; font-weight: bold;">&lt;</span>asp<span style="color: #006600; font-weight: bold;">:</span>ScriptManager runat<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;server&quot;</span> <span style="color: #006600; font-weight: bold;">/&gt;</span>
&nbsp;
<span style="color: #006600; font-weight: bold;">&lt;</span>asp<span style="color: #006600; font-weight: bold;">:</span>UpdatePanel runat<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;server&quot;</span><span style="color: #006600; font-weight: bold;">&gt;</span>
  <span style="color: #006600; font-weight: bold;">&lt;</span>ContentTemplate<span style="color: #006600; font-weight: bold;">&gt;</span>
    <span style="color: #006600; font-weight: bold;">&lt;</span>asp<span style="color: #006600; font-weight: bold;">:</span>Button runat<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;server&quot;</span> ID<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;Button1&quot;</span> <span style="color: #006600; font-weight: bold;">/&gt;</span>
    <span style="color: #006600; font-weight: bold;">&lt;</span>asp<span style="color: #006600; font-weight: bold;">:</span>TextBox runat<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;server&quot;</span> ID<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;TextBox1&quot;</span> <span style="color: #006600; font-weight: bold;">/&gt;</span>
  <span style="color: #006600; font-weight: bold;">&lt;/</span>ContentTemplate<span style="color: #006600; font-weight: bold;">&gt;</span>
<span style="color: #006600; font-weight: bold;">&lt;/</span>asp<span style="color: #006600; font-weight: bold;">:</span>UpdatePanel<span style="color: #006600; font-weight: bold;">&gt;</span></pre></div></div>

<p>By attaching in pageLoad(), our TextBox will now have the datepicker attached to it on initial page load, <strong>and have it re-attached after every partial postback</strong>.</p>
<p>The call to unbind() is optional in this case, but a good precaution on more complex pages. Else, you run the risk of stacking multiple events on elements that were <em>not</em> refreshed as part of the partial postback.</p>
<h3>An ASP.NET AJAX alternative to $(document).ready()</h3>
<p>The previous sections should make it easier to decide between jQuery and ASP.NET AJAX’s events, but they assume you’re using both frameworks. What if you’re only using ASP.NET AJAX and want functionality similar to $(document).ready()?</p>
<p>Luckily, <strong>ASP.NET AJAX does provide a corresponding event</strong>. The <a href="http://msdn.microsoft.com/en-us/library/bb397532.aspx" rel="nofollow">Application.Init</a> event fires only one time per page load, and is perfect for onetime initialization tasks. It’s not available through a shortcut function and requires slightly more caution, but serves its purpose:</p>

<div class="wp_syntax"><div class="code"><pre class="asp" style="font-family:monospace;"><span style="color: #006600; font-weight: bold;">&lt;</span>asp<span style="color: #006600; font-weight: bold;">:</span>ScriptManager runat<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;server&quot;</span> <span style="color: #006600; font-weight: bold;">/&gt;</span> 
&nbsp;
<span style="color: #006600; font-weight: bold;">&lt;</span>script type<span style="color: #006600; font-weight: bold;">=</span><span style="color: #cc0000;">&quot;text/javascript&quot;</span><span style="color: #006600; font-weight: bold;">&gt;</span> 
  Sys.<span style="color: #990099; font-weight: bold;">Application</span>.<span style="color: #9900cc;">add_init</span><span style="color: #006600; font-weight:bold;">&#40;</span><span style="color: #0000ff; font-weight: bold;">function</span><span style="color: #006600; font-weight:bold;">&#40;</span><span style="color: #006600; font-weight:bold;">&#41;</span> <span style="color: #006600; font-weight:bold;">&#123;</span> 
    <span style="color: #ff6600;">// Initialization code here, meant to run once.</span>
  <span style="color: #006600; font-weight:bold;">&#125;</span><span style="color: #006600; font-weight:bold;">&#41;</span><span style="color: #006600; font-weight: bold;">;</span> 
<span style="color: #006600; font-weight: bold;">&lt;/</span>script<span style="color: #006600; font-weight: bold;">&gt;</span></pre></div></div>

<p>Note that the call to Application.add_init is placed <strong>after</strong> the ScriptManager. This is necessary because the ScriptManager injects its reference to <em>MicrosoftAjax.js</em> in that location. <a href="http://encosia.com/2007/08/16/updated-your-webconfig-but-sys-is-still-undefined/" target="_blank">Attempting to reference the Sys object before that point will result in a “sys is undefined” JavaScript error</a>.</p>
<p><strong>If you think that limitation is a bit messy, you are not alone</strong>. I’m not a big fan of littering my presentation code with any more inline JavaScript than is necessary. To avoid this clutter, you may alternatively include your Application.Init code in an external file, included via a ScriptReference (see the previous link for an example).</p>
<h3>Summary (tl;dr)</h3>
<p><strong>$(document).ready()</strong></p>
<ul>
<li>Ideal for onetime initialization.</li>
<li>Optimization black magic; may run slightly earlier than pageLoad().</li>
<li>Does <strong>not</strong> re-attach functionality to elements affected by partial postbacks.</li>
</ul>
<p><strong>pageLoad()</strong></p>
<ul>
<li>Unsuitable for onetime initialization if used with UpdatePanels.</li>
<li>Slightly less optimized in some browsers, but consistent.</li>
<li>Perfect for re-attaching functionality to elements within UpdatePanels.</li>
</ul>
<p><strong>Application.Init</strong></p>
<ul>
<li>Useful for onetime initialization if only ASP.NET AJAX is available.</li>
<li>More work required to wire the event up.</li>
<li>Exposes you to the “sys is undefined” error if you aren’t careful.</li>
</ul>
<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/03/25/document-ready-and-pageload-are-not-the-same/">$(document).ready() and pageLoad() are not the same!</a></p>
<div class="feedflare">
<a href="http://feeds.encosia.com/~ff/Encosia?a=hhnUZkucYmo:mA7NWLsLJ5Y:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Encosia?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=hhnUZkucYmo:mA7NWLsLJ5Y:aWKiLpGymzw"><img src="http://feeds.feedburner.com/~ff/Encosia?d=aWKiLpGymzw" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=hhnUZkucYmo:mA7NWLsLJ5Y:30RXbuXOgYA"><img src="http://feeds.feedburner.com/~ff/Encosia?d=30RXbuXOgYA" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=hhnUZkucYmo:mA7NWLsLJ5Y:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/Encosia?i=hhnUZkucYmo:mA7NWLsLJ5Y:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=hhnUZkucYmo:mA7NWLsLJ5Y:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/Encosia?i=hhnUZkucYmo:mA7NWLsLJ5Y:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Encosia/~4/hhnUZkucYmo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/03/25/document-ready-and-pageload-are-not-the-same/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
		<feedburner:origLink>http://encosia.com/2009/03/25/document-ready-and-pageload-are-not-the-same/</feedburner:origLink></item>
		<item>
		<title>Use jQuery to catch and display ASP.NET AJAX service errors</title>
		<link>http://feeds.encosia.com/~r/Encosia/~3/NlO0ZPXAIVI/</link>
		<comments>http://encosia.com/2009/03/04/use-jquery-to-catch-and-display-aspnet-ajax-service-errors/#comments</comments>
		<pubDate>Wed, 04 Mar 2009 06:51:06 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[UI]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=832</guid>
		<description><![CDATA[An example of how to detect errors that occur when requesting ASP.NET AJAX web services and page methods with jQuery, how to handle them, and how to more attractively present errors to the user.<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/03/04/use-jquery-to-catch-and-display-aspnet-ajax-service-errors/">Use jQuery to catch and display ASP.NET AJAX service errors</a></p>
]]></description>
			<content:encoded><![CDATA[<p><img style="border: 1px solid #000;" title="Screaming at jQuery" alt="Another user fed up with your lack of error handling!" src="http://encosia.com/blog/wp-content/uploads/2009/03/screaming-at-jquery.jpg" width="490" height="198" /></p>
<p>If you don’t properly handle the inevitable errors in your web applications, you can expect your users to eventually react about like this guy. Since they typically squelch any server-side errors, <strong>AJAX service calls are especially problematic</strong>. In fact, they rarely even throw a client-side error when they fail.</p>
<p>Even when a client-side error is thrown, <strong>most users won’t notice</strong> it and the ones who do notice won’t know what the error means or what to do next. In fact, I’ve found that even many <em>developers</em> don’t notice client-side scripting errors that occur <strong>while they’re debugging their own applications</strong>!</p>
<p>To help you remedy this problem in your own applications, I want to show you one way that I handle AJAX service call errors with jQuery. To do this, we will <strong>build an error-prone web service</strong>, <strong>make an AJAX request to it</strong> via jQuery, <strong>handle the resulting server-side errors</strong> gracefully, and use a jQuery plugin to attractively <strong>present those errors</strong>.</p>
<h3>Building an erroneous method</h3>
<p>To experiment with error handling, the first thing we’ll need is an error. We could use throw() to raise a synthetic error, but let’s build a page method that&#8217;s apt to throw a couple of real errors:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>WebMethod<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #0600FF;">static</span> <span style="color: #FF0000;">int</span> DivideByZero<span style="color: #000000;">&#40;</span><span style="color: #FF0000;">int</span> Dividend<span style="color: #000000;">&#41;</span>
<span style="color: #000000;">&#123;</span>
  <span style="color: #008080; font-style: italic;">// To fool the compiler into not saving us from ourselves.</span>
  <span style="color: #FF0000;">int</span> zero <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">;</span>
&nbsp;
  <span style="color: #0600FF;">return</span> <span style="color: #000000;">&#40;</span>Dividend <span style="color: #008000;">/</span> zero<span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>If this method is called with a parameter that cannot be parsed as an integer, it will throw a type conversion error. If we do correctly call it with a string that can be converted to an integer, we’ll get a division by zero exception.</p>
<h3>Using jQuery to call the page method</h3>
<p>To interface with the page method, we’ll need an input field to supply the dividend and a button to trigger a call to the page method. Something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;Division by Zero Utility v1.0&lt;/title&gt;
  &lt;script type=&quot;text/javascript&quot; src=&quot;jquery-1.3.2.min.js&quot;&gt;&lt;/script&gt;
  &lt;script type=&quot;text/javascript&quot; src=&quot;default.js&quot;&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;
  &lt;input type=&quot;text&quot; id=&quot;Dividend&quot; /&gt;
  &lt;input type=&quot;button&quot; id=&quot;Divide&quot; value=&quot;Divide by 0&quot; /&gt;
&lt;/body&gt;
&lt;/html&gt;</pre></div></div>

<p><a href="http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/">Using jQuery to call an ASP.NET AJAX page method</a> is easy once you understand <a href="http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/">the required syntax and a few quirks</a>. In <em>default.js</em>, we can use jQuery’s click() to wire our DivideByZero method up to the input button’s click event:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">/// &lt;reference path=&quot;~/jquery-1.3.2-vsdoc.js /&gt;</span>
<span style="color: #006600; font-style: italic;">// When the page loads...</span>
$<span style="color: #009900;">&#40;</span>document<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ready</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #006600; font-style: italic;">// ...attach an onclick handler to the Divide button.</span>
  $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#Divide&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">click</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// Trigger a request to the page method.</span>
    $.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
      type<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;POST&quot;</span><span style="color: #339933;">,</span>
      contentType<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;application/json; charset=utf-8&quot;</span><span style="color: #339933;">,</span>
      dataType<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;json&quot;</span><span style="color: #339933;">,</span>
      url<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Default.aspx/DivideByZero&quot;</span><span style="color: #339933;">,</span>
      <span style="color: #006600; font-style: italic;">// Supply the Dividend value from our input field.</span>
      data<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;{ 'Dividend': '&quot;</span> <span style="color: #339933;">+</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#Dividend&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;' }&quot;</span><span style="color: #339933;">,</span>
      <span style="color: #006600; font-style: italic;">// Error!</span>
      error<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>xhr<span style="color: #339933;">,</span> <span style="color: #000066;">status</span><span style="color: #339933;">,</span> error<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #006600; font-style: italic;">// Display a generic error for now.</span>
        <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;AJAX Error!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Notice the <strong>error</strong> callback function. This function will be raised in the event of any error <em>or timeout</em> when calling the service. For now, we’ll just display an alert() with a static error message.</p>
<p>If you were to run this example now, typing anything in the input field and hitting the “Divide by 0” button will result in the error handler being called. That’s better than nothing, but wouldn&#8217;t it be more useful to display specific information about the exception that occurred?</p>
<h3>Inspecting the server&#8217;s response in Firebug</h3>
<p>To improve the detail of our message, we need to dissect the error returned by the server and find where the specific detail lies. To accomplish this most effectively, I recommend using the <a href="http://getfirebug.com">Firebug addon to Firefox</a>.</p>
<p><a href="http://encosia.com/2007/03/06/debug-and-explore-aspnet-ajax-with-firebug/">Using Firebug to set a breakpoint</a> on the error handler, we’re able to inspect the request’s state at that point and quickly drill down to the information we’re after:</p>
<p><img style="border: 1px solid #000;" title="Debugging with a breakpoint" border="0" alt="Inspecting the error's state, using a breakpoint in Firebug" src="http://encosia.com/blog/wp-content/uploads/2009/03/error-breakpoint.png" width="490" height="147" /></p>
<p>While the <strong>status</strong> of “error” may seem unhelpful, it is a useful bit of information in some cases. In a more sophisticated error handling scenario, it would allow us to distinguish between a server-side error and a timeout.</p>
<p>However, the undefined <strong>error</strong> parameter certainly <em>is not</em> helpful.</p>
<p>To find the detail that we need, we’ll have to explore a bit further. Our request’s XMLHttpRequest instance should contain what we’re looking for. Clicking on the green <strong>XMLHttpRequest</strong> text will shift the Firebug window to inspect that specific object in detail:</p>
<p><img style="border: 1px solid #000;" title="XMLHttpRequest error inspection" alt="Inspecting the XMLHttpRequest object in Firebug" src="http://encosia.com/blog/wp-content/uploads/2009/03/xhr-error-inspection.png" width="490" height="157" /></p>
<p>Now we’re getting there: The XMLHttpRequest’s <strong>responseText</strong> property contains a JSON object with all the detail that the server returned.</p>
<p>As you can see in the Firebug screenshot, the <strong>Message</strong> variable contains a more familiar .NET error. In this case, indicating that the empty string I submitted was unsuitable for conversion to the Int32 parameter that <strong>DivideByZero</strong> expects.</p>
<h3>Making effective use of the error data</h3>
<p>As a string, this JSON object isn’t quite what we need. The last thing we should do is try to parse the error message ourselves. While technically possible, it would be messy and prone to breakage, or require using an extra library such as <em>json2.js</em>.</p>
<p>One of the nice things about JSON is that it is a native JavaScript construct. Thus, JavaScript’s <a href="http://www.json.org/js.html">eval() will evaluate a <strong>JSON string</strong> and return an actual <strong>JSON object</strong></a>.</p>
<p>To take advantage of that, we can modify the error handler like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">error<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>xhr<span style="color: #339933;">,</span> <span style="color: #000066;">status</span><span style="color: #339933;">,</span> error<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #006600; font-style: italic;">// Boil the ASP.NET AJAX error down to JSON.</span>
  <span style="color: #003366; font-weight: bold;">var</span> err <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">eval</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;(&quot;</span> <span style="color: #339933;">+</span> xhr.<span style="color: #660066;">responseText</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;)&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #006600; font-style: italic;">// Display the specific error raised by the server (e.g. not a</span>
  <span style="color: #006600; font-style: italic;">//   valid value for Int32, or attempted to divide by zero).</span>
  <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span>err.<span style="color: #660066;">Message</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Now, the properties of the error that we got a glimpse of in Firebug are available via the same dot-notation that you’d expect from any object. In particular, the errors returned by ASP.NET AJAX provide three variables in their JSON response: <strong>ExceptionType</strong>, <strong>Message</strong>, and <strong>StackTrace</strong>.</p>
<p><em>Note: I would normally recommend against using eval() to evaluate a JSON string. However, it is relatively safe in this case since these messages come directly from the .NET framework and do not contain any user-injected content.</em></p>
<h3>Presenting the error message with jQuery</h3>
<p>I’ve written about Mike Alsup’s <a href="http://malsup.com/jquery/block/">BlockUI plugin</a> before, showing you how to use it to display <a href="http://encosia.com/2008/10/04/using-jquery-to-enhance-aspnet-ajax-progress-indication/">modal progress indication</a> and <a href="http://encosia.com/2008/10/11/using-jquery-to-display-a-modal-updatepanel-confirmation/">confirmation windows</a>. An often overlooked feature of the plugin is the ability to display basic “growl” style notifications.</p>
<p>See the demo at the bottom of <a href="http://malsup.com/jquery/block/#demos" rel="nofollow">this page</a> for an example of that.</p>
<p>After adding a script reference to blockUI.js, displaying the error “growl” couldn’t be easier:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">error<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>xhr<span style="color: #339933;">,</span> <span style="color: #000066;">status</span><span style="color: #339933;">,</span> error<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #003366; font-weight: bold;">var</span> err <span style="color: #339933;">=</span> <span style="color: #000066; font-weight: bold;">eval</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;(&quot;</span> <span style="color: #339933;">+</span> xhr.<span style="color: #660066;">responseText</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;)&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #006600; font-style: italic;">// Display the error &quot;growl&quot;, with a title of &quot;Error&quot;,</span>
  <span style="color: #006600; font-style: italic;">//  the error message as content, and a 20s display time.</span>
  $.<span style="color: #660066;">growlUI</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Error'</span><span style="color: #339933;">,</span> err.<span style="color: #660066;">Message</span><span style="color: #339933;">,</span> 20000<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
success<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #006600; font-style: italic;">// On the outside chance that our method manages to succeed, </span>
  <span style="color: #006600; font-style: italic;">//  clear any lingering error &quot;growls&quot;.</span>
  $.<span style="color: #660066;">unblockUI</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Since it’s important that the user notice the error message, we can specify a much longer than default <strong>timeout</strong> for the “growl”. Twenty seconds in the example above.</p>
<p>The <strong>success</strong> handler is added to make sure any leftover error is cleared after a successful request completes. This avoids any confusion that would be caused by an error message remaining even after a successful request completes.</p>
<p>Because $.growlUI() is just a shortcut for a complex BlockUI usage, $.unblockUI() works on “growl” messages just as if they were $.blockUI() modals.</p>
<p><em>Note: As with the rest of BlockUI, these “growl” messages can be customized via CSS. For this simple demo, I’m happy with the default styling, but you can easily change it to match your application.</em></p>
<h3>Conclusion</h3>
<p>You should never assume your service calls are 100% reliable. This seems obvious, but I’ve encountered mountains of <strong>production code without error handling</strong>.</p>
<p>As you’ve hopefully seen in this post, it is <strong>trivially easy</strong> to add great looking error handling to your jQuery service calls. After all is said and done, you’re only looking at about <strong>3-5 extra lines of code</strong>. This substantial improvement in usability is well worth the minimal effort.</p>
<p>We focused on an example of using a page method here, but keep in mind that this technique can be implemented to work with <em>both</em> <strong>page methods</strong> and <strong>web service</strong> calls.</p>
<h3>Source</h3>
<p><a href="http://encosia.com/source/jquery-error-handling.zip"><img src="http://encosia.com/blog/wp-content/uploads/2009/03/jquery-error-handling-download-bar.png" width="490" height="46" alt="Download source: jquery-error-handling.zip" title="Source code Download" /></a></p>
<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/03/04/use-jquery-to-catch-and-display-aspnet-ajax-service-errors/">Use jQuery to catch and display ASP.NET AJAX service errors</a></p>
<div class="feedflare">
<a href="http://feeds.encosia.com/~ff/Encosia?a=NlO0ZPXAIVI:VtSQrAbyFg0:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/Encosia?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=NlO0ZPXAIVI:VtSQrAbyFg0:aWKiLpGymzw"><img src="http://feeds.feedburner.com/~ff/Encosia?d=aWKiLpGymzw" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=NlO0ZPXAIVI:VtSQrAbyFg0:30RXbuXOgYA"><img src="http://feeds.feedburner.com/~ff/Encosia?d=30RXbuXOgYA" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=NlO0ZPXAIVI:VtSQrAbyFg0:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/Encosia?i=NlO0ZPXAIVI:VtSQrAbyFg0:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.encosia.com/~ff/Encosia?a=NlO0ZPXAIVI:VtSQrAbyFg0:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/Encosia?i=NlO0ZPXAIVI:VtSQrAbyFg0:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Encosia/~4/NlO0ZPXAIVI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/03/04/use-jquery-to-catch-and-display-aspnet-ajax-service-errors/feed/</wfw:commentRss>
		<slash:comments>26</slash:comments>
		<feedburner:origLink>http://encosia.com/2009/03/04/use-jquery-to-catch-and-display-aspnet-ajax-service-errors/</feedburner:origLink></item>
		<item>
		<title>Review: The best JavaScript book I’ve read</title>
		<link>http://feeds.encosia.com/~r/Encosia/~3/evklxgFCXEI/</link>
		<comments>http://encosia.com/2009/02/16/review-the-best-javascript-book-i%e2%80%99ve-read/#comments</comments>
		<pubDate>Mon, 16 Feb 2009 22:44:44 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Reading]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=823</guid>
		<description><![CDATA[ Having used JavaScript for over a decade, I’ve read many books covering the language. Some focused primarily on syntax. Others recounted and solved specific real-world problems.
Learning a language as a set of tasks is one way to get up to speed quickly, but it’s not a very good way to thoroughly learn a language’s [...]<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/02/16/review-the-best-javascript-book-i%e2%80%99ve-read/">Review: The best JavaScript book I’ve read</a></p>
]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.amazon.com/gp/product/0596517742?ie=UTF8&amp;tag=encosia-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0596517742" rel="nofollow" rel="nofollow"><img style="margin-top: 5px; margin-right: 10px; float: left;" src="http://encosia.com/blog/wp-content/uploads/2009/02/javascript-the-good-parts-cover.png" width="200" height="262" /></a> Having used JavaScript for over a decade, I’ve read many books covering the language. Some focused primarily on syntax. Others recounted and solved specific real-world problems.</p>
<p>Learning a language as a set of tasks is one way to get up to speed quickly, but it’s not a very good way to thoroughly learn a language’s nuances and idioms.</p>
<p>While those sorts of books certainly have their place, it’s disappointingly rare to find a book which presents JavaScript as the first-class programming language that it truly is.</p>
<p>After reading no more than the first page of this book&#8217;s preface, I knew that I had finally found the antidote to those trite examples of compound interest calculators and the tedious minutiae of books that spend pages on alert()&#8217;s syntax. No, this book is different than the rest&#8230;</p>
<h3 style="clear: both; margin-top: 10px;">Learning from a master</h3>
<p>When it comes to deep mastery of JavaScript, <strong>there are few who can consider themselves Douglas Crockford’s peer</strong>. In fact, as the first to introduce <a href="http://json.org">JSON</a>, you could even say that much of what I write about here is made possible by Crockford. As if that wasn’t enough, Crockford also wrote the handy <a href="http://www.jslint.com/">JSLint</a> tool, went on to become a JavaScript architect at Yahoo and serves on the ECMAScript committee.</p>
<p>I don’t mean to oversell the man. My point is simply that if there’s a single source that you can trust to accelerate your <a href="http://sethgodin.typepad.com/seths_blog/2008/12/10000-hours.html">10,000 hours</a> toward JavaScript mastery, Crockford is as likely that source as anyone.</p>
<h3>Right to the point</h3>
<p>One of my favorite aspects of the book is that it is very succinct. The entire book weighs in at less than 150 pages, which is rare when it comes to a technical book. Especially rare for one aimed at an intermediate to advanced audience.</p>
<p>The book’s brevity allows it to be both more affordable, and also more convenient to keep handy and use as a reference. In fact, <strong>I usually find myself cracking open the book instead of searching Google</strong>, when I need to clarify a JavaScript issue.</p>
<p>However, such densely packed knowledge isn’t without its drawbacks. You will need to take your time and probably read some sections of the book more than once. Think of it as the <a title="Link to Code Complete on Amazon" href="http://www.amazon.com/gp/product/0735619670?ie=UTF8&amp;tag=encosia-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0735619670" rel="nofollow">Code Complete</a> of JavaScript books. Crockford himself puts it well in this “warning” on the first page of the book:</p>
<blockquote><p>This is not a book for dummies. This book is small, but it is dense. There is a lot of material packed into it. Don’t be discouraged if it takes multiple readings to get it. Your efforts will be rewarded.</p></blockquote>
<h3>The bad parts too</h3>
<p>Not much time is devoted to the negative aspects of JavaScript, but the book does briefly warn us about some of the worst parts of the language. For example, do you know why these aren’t the same?</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// This returns undefined</span>
<span style="color: #000066; font-weight: bold;">return</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #000066;">status</span><span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">true</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// This returns { status: true }</span>
<span style="color: #000066; font-weight: bold;">return</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #000066;">status</span><span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">true</span> 
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></div></div>

<p>How about the difference between these?</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Valid</span>
<span style="color: #003366; font-weight: bold;">var</span> foo <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span> box<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">true</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Syntax error</span>
<span style="color: #003366; font-weight: bold;">var</span> bar <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span> <span style="color: #000066; font-weight: bold;">case</span><span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">true</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Those are just a couple of the “bad parts” described in the book. Having been caught in a few of JavaScript&#8217;s hidden quagmires over the years myself, let me tell you that <strong>knowing the location of these landmines will save you many hours</strong>.</p>
<h3>Hear it from the man himself</h3>
<p>If you have a few minutes (okay, more like forty), Crockford gave a great talk at Yahoo to complement the book.</p>
<p>Even if you aren’t interested in reading the book, I highly recommend watching the talk if you work with JavaScript at all. It’s fascinating to hear how he got started with JavaScript and his take on the ins and outs of the language:</p>
<p><noscript>Your browser or RSS reader won&#8217;t be able to render this embedded video. <a href="http://encosia.com/2009/02/16/review-the-best-javascript-book-i%e2%80%99ve-read/">Click here to visit the post on Encosia.com</a> if you&#8217;d like to watch the embedded video.</noscript></p>
<div><object width="492" height="322"><param name="movie" value="http://d.yimg.com/static.video.yahoo.com/yep/YV_YEP.swf?ver=2.2.34" /><param name="allowFullScreen" value="true" /><param name="AllowScriptAccess" VALUE="always" /><param name="bgcolor" value="#000000" /><param name="flashVars" value="id=2974197&#038;vid=630959&#038;lang=en-us&#038;intl=us&#038;thumbUrl=http%3A//l.yimg.com/a/i/us/sch/cn/v/v1/w826/630959_100_70.jpeg%3Fx%3D158%26y%3D111%26sig%3DMUc0gpdIoywY3Yi7Bqgn1g--&#038;embed=1" /><embed src="http://d.yimg.com/static.video.yahoo.com/yep/YV_YEP.swf?ver=2.2.34" type="application/x-shockwave-flash" width="492" height="322" allowFullScreen="true" AllowScriptAccess="always" bgcolor="#000000" flashVars="id=2974197&#038;vid=630959&#038;lang=en-us&#038;intl=us&#038;thumbUrl=http%3A//l.yimg.com/a/i/us/sch/cn/v/v1/w826/630959_100_70.jpeg%3Fx%3D158%26y%3D111%26sig%3DMUc0gpdIoywY3Yi7Bqgn1g--&#038;embed=1" ></embed></object></div>
<p></p>
<h3>Not necessarily for everyone</h3>
<p>As great as this book is, <em>it’s not for everyone</em>.</p>
<p>If you’re looking for quick tutorials, you won’t find them here. A Google search is going to get you to the finish line a lot quicker if that’s all you care about.</p>
<p>If you want to learn JavaScript from a blank slate, I would suggest pairing the Crockford book with another that’s geared more toward beginners. <a title="Link to JavaScript: The Missing Manual on Amazon" href="http://www.amazon.com/gp/product/0596515898?ie=UTF8&amp;tag=encosia-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0596515898" rel="nofollow">JavaScript: The Missing Manual</a> would make an excellent companion to this book, for instance. You could technically learn JavaScript from scratch using only the Crockford book, but it would be an uphill battle.</p>
<p>However, if you want to learn how to take JavaScript to its limits, use its advanced features effectively, and gain a deeper understanding of this oft-misunderstood pillar of the Internet as we know it: <a title="Link to JavaScript: The Good Parts on Amazon" href="http://www.amazon.com/gp/product/0596517742?ie=UTF8&amp;tag=encosia-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0596517742" rel="nofollow">JavaScript: The Good Parts</a><strong> is a must-read</strong>!</p>
<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/02/16/review-the-best-javascript-book-i%e2%80%99ve-read/">Review: The best JavaScript book I’ve read</a></p>
<div class="feedflare">
<a href="http://feeds.encosia.com/~f/Encosia?a=pExBjBPv"><img src="http://feeds.feedburner.com/~f/Encosia?d=41" border="0"></img></a> <a href="http://feeds.encosia.com/~f/Encosia?a=dsXwPukJ"><img src="http://feeds.feedburner.com/~f/Encosia?d=1763" border="0"></img></a> <a href="http://feeds.encosia.com/~f/Encosia?a=jhzVgxlg"><img src="http://feeds.feedburner.com/~f/Encosia?d=1747" border="0"></img></a> <a href="http://feeds.encosia.com/~f/Encosia?a=qHyNFEbU"><img src="http://feeds.feedburner.com/~f/Encosia?i=qHyNFEbU" border="0"></img></a> <a href="http://feeds.encosia.com/~f/Encosia?a=taeIwCW4"><img src="http://feeds.feedburner.com/~f/Encosia?i=taeIwCW4" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Encosia/~4/evklxgFCXEI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/02/16/review-the-best-javascript-book-i%e2%80%99ve-read/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		<feedburner:origLink>http://encosia.com/2009/02/16/review-the-best-javascript-book-i%e2%80%99ve-read/</feedburner:origLink></item>
		<item>
		<title>A breaking change between versions of ASP.NET AJAX</title>
		<link>http://feeds.encosia.com/~r/Encosia/~3/XvmvKPkyJYA/</link>
		<comments>http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/#comments</comments>
		<pubDate>Tue, 10 Feb 2009 08:28:08 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=817</guid>
		<description><![CDATA[An examination and explanation of one undocumented change between ASP.NET 2.0 and 3.5's System.Web.Extensions that will break code making direct calls to JSON serialized ASMX services.<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/">A breaking change between versions of ASP.NET AJAX</a></p>
]]></description>
			<content:encoded><![CDATA[<p>When working directly with JSON serialized ASMX services, be it <a href="http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/">via jQuery</a>, pure XmlHttpRequest calls, or anything else other than the ScriptManager, one question inevitably arises. That question is of the inexplicable <strong>.d</strong> attribute that appeared in ASP.NET 3.5.</p>
<p>What is it? Why is it there?</p>
<p>In this post, I’ll use both a 2.0 and a 3.5 example ASMX web service to <strong>illustrate exactly what’s going on</strong>. I’ll also show you <strong>why it’s a good change</strong>.</p>
<h3>An example</h3>
<p>Following a concrete example always helps to better clarify these things. For that purpose, let’s assume that we want to call a web service and retrieve an instance of the following <strong>Person</strong> class:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> Person
<span style="color: #000000;">&#123;</span>
  <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> FirstName<span style="color: #008000;">;</span>
  <span style="color: #0600FF;">public</span> <span style="color: #FF0000;">string</span> LastName<span style="color: #008000;">;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>The ASMX web service to return an instance of that class could be simple as this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #000000;">&#91;</span>ScriptService<span style="color: #000000;">&#93;</span>
<span style="color: #0600FF;">public</span> <span style="color: #FF0000;">class</span> PersonService <span style="color: #008000;">:</span> WebService
<span style="color: #000000;">&#123;</span>
  <span style="color: #000000;">&#91;</span>WebMethod<span style="color: #000000;">&#93;</span>
  <span style="color: #0600FF;">public</span> Person GetPerson<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span>
  <span style="color: #000000;">&#123;</span>
    Person p <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Person<span style="color: #000000;">&#40;</span><span style="color: #000000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    p.<span style="color: #0000FF;">FirstName</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Dave&quot;</span><span style="color: #008000;">;</span>
    p.<span style="color: #0000FF;">LastName</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;Ward&quot;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF;">return</span> p<span style="color: #008000;">;</span>
  <span style="color: #000000;">&#125;</span>
<span style="color: #000000;">&#125;</span></pre></div></div>

<p>Because our WebService class is decorated with the [ScriptService] attribute, the ASP.NET AJAX Extensions (System.Web.Extensions) <a href="http://encosia.com/2008/06/05/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/">will automatically serialize the return value as JSON if properly requested</a>.</p>
<p><strong>Note:</strong> A common anti-pattern that I’ve seen in practice is using a return type of string and returning a manually JSON serialized object. Don’t. It’s unnecessary and results in doubled effort on both the server and in the browser.</p>
<p>Let the framework handle this task unless you have a good reason not to use the built-in functionality. It works just fine in most scenarios.</p>
<h3>Calling the service and inspecting its result</h3>
<p><a href="http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/">Using jQuery to consume an ASMX web service</a> is simple, but does require <a href="http://weblogs.asp.net/scottgu/archive/2007/04/04/json-hijacking-and-how-asp-net-ajax-1-0-mitigates-these-attacks.aspx">jumping through a few hoops</a>. We can use this jQuery to consume the Person service we just created:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$.<span style="color: #660066;">ajax</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>
  type<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;POST&quot;</span><span style="color: #339933;">,</span>
  contentType<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;application/json; charset=utf-8&quot;</span><span style="color: #339933;">,</span>
  url<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;PersonService.asmx/GetPerson&quot;</span><span style="color: #339933;">,</span>
  data<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;{}&quot;</span><span style="color: #339933;">,</span>
  dataType<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;json&quot;</span><span style="color: #339933;">,</span>
  success<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>msg<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// Do interesting things here.</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Making that call against an ASP.NET 2.0 site with the ASP.NET AJAX Extensions 1.0 installed, this JSON object would be the return value:</p>
<p><img style="border: 1px solid black;" title="2.0 JSON Response" border="0" alt="2.0 JSON Response in Firebug" src="http://encosia.com/blog/wp-content/uploads/2009/02/20-json-response.png" width="490" height="146" /></p>
<p>I find that it often helps to visualize the JSON in a more human readable format. This is the same JSON object as seen in the Firebug screenshot above:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#123;</span><span style="color: #3366CC;">&quot;__type&quot;</span>    <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Person&quot;</span><span style="color: #339933;">,</span>
 <span style="color: #3366CC;">&quot;FirstName&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Dave&quot;</span><span style="color: #339933;">,</span>
 <span style="color: #3366CC;">&quot;LastName&quot;</span>  <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Ward&quot;</span><span style="color: #009900;">&#125;</span></pre></div></div>

<p>Within the <strong>success</strong> callback shown above, you may access properties of the Person exactly as you would expect. For example, <strong>msg.FirstName</strong> will evaluate to “Dave”.</p>
<h3>Waiter, there’s a .d in my msg soup!</h3>
<p>Eventually, you’ll <em>finally</em> convince management to let you upgrade the site to ASP.NET 3.5. After all, you can use an object initializer to cut the size of the web service in half!</p>
<p>However, your <strong>msg.FirstName statement now results in the dreaded <em>undefined</em></strong>.</p>
<p>What happened? Let’s inspect the ASP.NET 3.5 response in Firebug:</p>
<p><img style="border: 1px solid black;" title="3.5 JSON Response" border="0" alt="3.5 JSON Response in Firebug" src="http://encosia.com/blog/wp-content/uploads/2009/02/35-json-response.png" width="490" height="146" /></p>
<p>The entire Person object is wrapped within a new “<strong>d</strong>” object now. Alternatively we might visualize it this way:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#123;</span><span style="color: #3366CC;">&quot;d&quot;</span><span style="color: #339933;">:</span><span style="color: #009900;">&#123;</span><span style="color: #3366CC;">&quot;__type&quot;</span>    <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Person&quot;</span><span style="color: #339933;">,</span>
      <span style="color: #3366CC;">&quot;FirstName&quot;</span> <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Dave&quot;</span><span style="color: #339933;">,</span>
      <span style="color: #3366CC;">&quot;LastName&quot;</span>  <span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;Ward&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#125;</span></pre></div></div>

<p>As you’ve probably figured out by now, the solution is to reference the property as <strong>msg.d.FirstName</strong> now. In our example, this will again resolve correctly as “Dave”.</p>
<p>This is the case with <strong>all</strong> ASMX services JSON serialized through the ASP.NET AJAX Extensions in ASP.NET 3.5. Even if you’re only returning a scalar return value, such as a string, int, or boolean, the result will always be enclosed within the “d”.</p>
<h3>Why did it change?</h3>
<p>While I wish this unexpected change had been more clearly announced, it’s a good one. Here’s how <a href="http://weblogs.asp.net/infinitiesloop/">Dave Reed</a> explained it to me:</p>
<blockquote><p>{&quot;d&quot;: 1 }</p>
<p>  &#160;</p>
<p>  Is not a valid JavaScript statement, where as this:</p>
<p>  &#160;</p>
<p>  [1]</p>
<p>  &#160;</p>
<p>  Is.</p>
<p>  &#160;</p>
<p>So the wrapping of the &quot;d&quot; parameter prevents direct execution of the string as script. No Object or Array constructor worries.</p></blockquote>
<p>[] is JavaScript’s array literal notation, allowing you to instantiate an array without explicitly calling a constructor. To expand on Dave’s explanation, simply consider this code:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#91;</span><span style="color: #3366CC;">&quot;Dave&quot;</span><span style="color: #339933;">,</span> <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Do Evil&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;Ward&quot;</span><span style="color: #009900;">&#93;</span></pre></div></div>

<p>That literal array declaration <strong>will execute the alert</strong> in most browsers. Danger!</p>
<p><strong>Update</strong>:  For an even better description of why the .d is important, from Dave Reed himself, be sure to see <a href="#comment-34045">his comment below</a>.</p>
<h3>Conclusion</h3>
<p>I hope this post has helped clarify any confusion caused by the “d” in ASP.NET 3.5’s JSON serialized ASMX services, and made you aware of why it’s worth the hassle. <a href="http://xss-proxy.sourceforge.net/Advanced_XSS_Control.txt" rel="nofollow">As sophisticated as XSS exploits have become in recent years</a>, unexpected script execution has the potential for devastating consequences. <strong>That extra “d” is well worth the short-term hassle</strong>.</p>
<p>Microsoft often catches flak over security related issues, but rarely gets credit when they do things right. I, for one, think the ASP.NET team deserves credit for remaining vigilant and often preempting these exploits for us.</p>
<p><strong>Thanks, guys.</strong></p>
<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/">A breaking change between versions of ASP.NET AJAX</a></p>
<div class="feedflare">
<a href="http://feeds.encosia.com/~f/Encosia?a=IX7vDQuL"><img src="http://feeds.feedburner.com/~f/Encosia?d=41" border="0"></img></a> <a href="http://feeds.encosia.com/~f/Encosia?a=rfW8hnDE"><img src="http://feeds.feedburner.com/~f/Encosia?d=1763" border="0"></img></a> <a href="http://feeds.encosia.com/~f/Encosia?a=tUmhv9pL"><img src="http://feeds.feedburner.com/~f/Encosia?d=1747" border="0"></img></a> <a href="http://feeds.encosia.com/~f/Encosia?a=1O8e6eth"><img src="http://feeds.feedburner.com/~f/Encosia?i=1O8e6eth" border="0"></img></a> <a href="http://feeds.encosia.com/~f/Encosia?a=hki4OdKu"><img src="http://feeds.feedburner.com/~f/Encosia?i=hki4OdKu" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Encosia/~4/XvmvKPkyJYA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/feed/</wfw:commentRss>
		<slash:comments>31</slash:comments>
		<feedburner:origLink>http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/</feedburner:origLink></item>
		<item>
		<title>Design the new Encosia logo. Win $350.</title>
		<link>http://feeds.encosia.com/~r/Encosia/~3/uJM4xuTflqw/</link>
		<comments>http://encosia.com/2009/01/28/design-the-new-encosia-logo-win-350/#comments</comments>
		<pubDate>Wed, 28 Jan 2009 15:54:39 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://encosia.com/2009/01/28/design-the-new-encosia-logo-win-350/</guid>
		<description><![CDATA[The time for this is long past due. The current logo does not make the sort of first impression that it needs to. It’s a good reminder that we should usually stick to our core competencies (i.e. I shouldn’t pretend to be a graphic designer).
I know at least a handful of you are design focused. [...]<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/01/28/design-the-new-encosia-logo-win-350/">Design the new Encosia logo. Win $350.</a></p>
]]></description>
			<content:encoded><![CDATA[<p>The time for this is long past due. The current logo does not make the sort of first impression that it needs to. It’s a good reminder that we should usually stick to our core competencies (i.e. I shouldn’t pretend to be a graphic designer).</p>
<p>I know at least a handful of you are design focused. So, if you want to take a shot at the contest, head on over to <a href="http://logotournament.com/contests/Encosia" target="_blank" rel="nofollow">the contest page</a> at Logo Tournament and show me what you’ve got.</p>
<p><strong>Update</strong>:  The contest is over.  I want to thank everyone who participated, especially the winner: <a href="http://logotournament.com/contests/Encosia/by/anica.soleva" rel="nofollow">Anica Soleva</a>.</p>
<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/01/28/design-the-new-encosia-logo-win-350/">Design the new Encosia logo. Win $350.</a></p>
<div class="feedflare">
<a href="http://feeds.encosia.com/~f/Encosia?a=Cfmgtvor"><img src="http://feeds.feedburner.com/~f/Encosia?d=41" border="0"></img></a> <a href="http://feeds.encosia.com/~f/Encosia?a=glQrsRv6"><img src="http://feeds.feedburner.com/~f/Encosia?d=1763" border="0"></img></a> <a href="http://feeds.encosia.com/~f/Encosia?a=vhgwnih4"><img src="http://feeds.feedburner.com/~f/Encosia?d=1747" border="0"></img></a> <a href="http://feeds.encosia.com/~f/Encosia?a=VBxxqJ8Q"><img src="http://feeds.feedburner.com/~f/Encosia?i=VBxxqJ8Q" border="0"></img></a> <a href="http://feeds.encosia.com/~f/Encosia?a=32Abzvsa"><img src="http://feeds.feedburner.com/~f/Encosia?i=32Abzvsa" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Encosia/~4/uJM4xuTflqw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/01/28/design-the-new-encosia-logo-win-350/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		<feedburner:origLink>http://encosia.com/2009/01/28/design-the-new-encosia-logo-win-350/</feedburner:origLink></item>
		<item>
		<title>How to rotate JavaScript ads during ASP.NET AJAX requests</title>
		<link>http://feeds.encosia.com/~r/Encosia/~3/2Hh4l7NoDqU/</link>
		<comments>http://encosia.com/2009/01/04/how-to-rotate-javascript-ads-during-aspnet-ajax-requests/#comments</comments>
		<pubDate>Sun, 04 Jan 2009 22:36:25 +0000</pubDate>
		<dc:creator>Dave Ward</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[UI]]></category>

		<guid isPermaLink="false">http://encosia.com/?p=750</guid>
		<description><![CDATA[An examination of why it's difficult to work with JavaScript based advertising during ASP.NET AJAX partial postbacks, and my suggested solution to solving that problem.  Deferred loading of the ad content is also covered, using the same technique.<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/01/04/how-to-rotate-javascript-ads-during-aspnet-ajax-requests/">How to rotate JavaScript ads during ASP.NET AJAX requests</a></p>
]]></description>
			<content:encoded><![CDATA[<p>A common question that I find myself fielding lately is how to handle the problem of <strong>rotating JavaScript based advertisements</strong>. As AJAX becomes ubiquitous on ad supported sites, we must take care that decreasing page views don’t also mean proportionally decreasing revenues.</p>
<p>Many find their way to ScriptManager.RegisterStartupScript, use that to re-inject the script during a partial postback, and expect that doing so will refresh the ad. Unfortunately, that doesn’t work when dealing with JavaScript based ads such as Google’s AdSense.</p>
<p>In this post, I’m going to show you <strong>why RegisterStartupScript does not solve the problem</strong>, <strong>the alternative that I suggest</strong>, and how to use that method to also <strong>defer loading of advertisements</strong> until after your content.</p>
<h3>How JavaScript ads are displayed</h3>
<p>After being spoiled by high level libraries like ASP.NET AJAX and jQuery, it’s easy to forget how tedious it is to write cross-browser DOM manipulation code. If you do manage to write something from scratch that works well, you’ll usually find that it ends up being quite large.</p>
<p>For this reason, advertising units embedded via JavaScript includes usually use a series of <a target="_blank" href="http://msdn.microsoft.com/en-us/library/ms536782%28printer%29.aspx" rel="nofollow">document.write</a> statements to output raw HTML.</p>
<p>For example, I added the <a target="_blank" href="http://lakequincy.com/default.aspx">Lake Quincy</a> ad in my sidebar with this JavaScript:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;script type=&quot;text/javascript&quot;&gt;
  lqm_channel = 1;
  lqm_publisher = 199;
  lqm_zone = 1;
  lqm_format = 7;
&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;http://a.lakequincy.com/s.js&quot;&gt;
&lt;/script&gt;</pre></div></div>

<p>Depending on which advertisement is returned from Lake Quincy’s server, s.js will use document.write to eventually render something like:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;a target=&quot;_top&quot; href=&quot;http://a.lakequincy.com/c.ashx?...&quot;&gt;
  &lt;img border=&quot;0&quot; src=&quot;http://a.lakequincy.com/img/foo.png&quot;/&gt;
&lt;/a&gt;</pre></div></div>

<p>This HTML renders in the same location that the &lt;script&gt; element is placed.</p>
<p>Google AdSense, Amazon Widgets, and just about every other advertising service that I&#8217;ve encountered all use this document.write method.</p>
<h3>Why doesn’t RegisterStartupScript work?</h3>
<p>There are two reasons why this document.write method makes rotation difficult when using ASP.NET AJAX’s server-side JavaScript methods.</p>
<p>First, the ScriptManager’s RegisterStartupScript method <strong>does not allow control over positioning</strong> the JavaScript it emits. Since these JavaScript based ads literally dump HTML code right where they are located, being unable to target them is a big problem.</p>
<p>You <em>can</em> attempt to circumvent this with absolute CSS positioning, but it adds a lot of unnecessary complexity to what should otherwise be simple.</p>
<p>Second, most <strong>browsers ignore document.write statements after the initial page layout has completed</strong>. Even if you found a way to get the script asynchronously injected at the precise location you desire, it would do absolutely nothing in most browsers.</p>
<p>Between these two problems, it becomes apparent that we need to find something altogether different.</p>
<h3>So, what does work?</h3>
<p>The answer to this dilemma is simple: <strong>the iframe</strong>.</p>
<p>One very useful property of the iframe is that <strong>its contents are created within the scope of a completely new DOM</strong>. For our purposes, the benefit of this is that it provides a way to execute document.write statements at any time after the initial page rendering.</p>
<p>Additionally, iframes are as easily positioned as a &lt;div&gt; <strong>and</strong> the separate DOM protects against unruly ad content breaking out of its intended location.</p>
<h3>Encapsulating the ad within an iframe</h3>
<p>To move the ad into an iframe, first we need to move the script blocks to an external HTML file. I called this one <em>LQ-336&#215;280.html</em>. This naming scheme helps me keep track of which file corresponds to each advertiser and unit size:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;html&gt;
&lt;head&gt;
  &lt;meta name=&quot;ROBOTS&quot; content=&quot;NOINDEX, NOFOLLOW&quot; /&gt;
  &lt;title&gt;LQ-336x280&lt;/title&gt;
&lt;/head&gt;
&lt;body style=&quot;margin: 0; padding: 0;&quot;&gt;
  &lt;script type=&quot;text/javascript&quot;&gt;
    lqm_channel = 1;
    lqm_publisher = 199;
    lqm_zone = 1;
    lqm_format = 7;
  &lt;/script&gt;
  &lt;script type=&quot;text/javascript&quot; src=&quot;http://a.lakequincy.com/s.js&quot;&gt;
  &lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</pre></div></div>

<p>The one thing in that HTML you might not be familiar with is the meta tag. That particular tag instructs search engine spiders to completely ignore the file. It’s my understanding that it’s important to include this to avoid running afoul of Google’s policies, in the same vein as using nofollow on paid links.</p>
<p>Finally, we just have to replace the inline script blocks with an iframe referencing the HTML include file we just created:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;iframe id=&quot;AdFrame&quot; width=&quot;336&quot; height=&quot;280&quot; src=&quot;LQ-336x280.html&quot;
        frameborder=&quot;0&quot; scrolling=&quot;no&quot;&gt;&lt;/iframe&gt;</pre></div></div>

<p>The ad is now encapsulated within the iframe, with its own DOM.</p>
<h3>Using that iframe to rotate the ad content</h3>
<p>Now that we’ve got the document.write code into an iframe, cycling the ad content is as simple as reloading the iframe. This can be accomplished by re-setting its <strong>src</strong> attribute:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Get a reference to the iframe.</span>
<span style="color: #003366; font-weight: bold;">var</span> adFrame <span style="color: #339933;">=</span> document.<span style="color: #660066;">getElementById</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'AdFrame'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Force it to refresh, by setting its location to</span>
<span style="color: #006600; font-style: italic;">//  whatever it currently is.</span>
adFrame.<span style="color: #660066;">src</span> <span style="color: #339933;">=</span> adFrame.<span style="color: #660066;">src</span><span style="color: #339933;">;</span></pre></div></div>

<p>This code allows us to rotate the advertisement at any arbitrary time, independent of the main page’s loading and rendering.</p>
<h3>Using this during ASP.NET AJAX partial postbacks</h3>
<p>Having figured out a fundamental method for accomplishing the rotation, now we can get back to the original question of how to rotate ads during an UpdatePanel’s async postback.</p>
<p>For example, let’s say that we want to rotate ads during every partial postback. After all, that’s how often they would’ve changed had there been no UpdatePanel.</p>
<p>The easiest way is to handle the PageRequestManager’s EndRequest event:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Add an initialization handler to run once</span>
<span style="color: #006600; font-style: italic;">//  per page load.</span>
Sys.<span style="color: #660066;">Application</span>.<span style="color: #660066;">add_init</span><span style="color: #009900;">&#40;</span>AppInit<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">function</span> AppInit<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #006600; font-style: italic;">// Get a reference to the PageRequestManager.</span>
  <span style="color: #003366; font-weight: bold;">var</span> prm <span style="color: #339933;">=</span> Sys.<span style="color: #660066;">WebForms</span>.<span style="color: #660066;">PageRequestManager</span>.<span style="color: #660066;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
&nbsp;
  <span style="color: #006600; font-style: italic;">// Add an end request handler to rotate the ad.</span>
  <span style="color: #006600; font-style: italic;">//  after every partial postback.</span>
  prm.<span style="color: #660066;">add_endRequest</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    $get<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'AdFrame'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">src</span> <span style="color: #339933;">=</span> $get<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'AdFrame'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">src</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Optionally, you could perform the rotation at BeginRequest instead. I’ve found that ads receive a slight boost in their CTR when rotated before the request completes, instead of after. It depends on what behavior you want to optimize, engagement or CTR.</p>
<h3>Bonus: Deferred loading</h3>
<p>Because inline script elements block rendering until they’ve finished downloading and executing, a few slow ad servers may have a tremendous impact on your site’s overall performance.</p>
<p>Now that we’ve gained the ability to render our advertisement anytime we want to, another handy use for this is to <strong>defer loading of the ad</strong>.</p>
<p>To implement deferred loading, we need to first revise the iframe element in our main page to omit the src attribute:</p>

<div class="wp_syntax"><div class="code"><pre class="html" style="font-family:monospace;">&lt;iframe id=&quot;AdFrame&quot; width=&quot;336&quot; height=&quot;280&quot;
        frameborder=&quot;0&quot; scrolling=&quot;no&quot;&gt;&lt;/iframe&gt;</pre></div></div>

<p>Then, dynamically set the attribute later in the page load. For example, you could set it inside the Application.Init handler that we created earlier, revising it to:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">Sys.<span style="color: #660066;">Application</span>.<span style="color: #660066;">add_init</span><span style="color: #009900;">&#40;</span>AppInit<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">function</span> AppInit<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
  <span style="color: #006600; font-style: italic;">// This initiates the ad's deferred load, late in the</span>
  <span style="color: #006600; font-style: italic;">//  page's overall loading cycle.</span>
  $get<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'AdFrame'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">src</span> <span style="color: #339933;">=</span> <span style="color: #3366CC;">'LQ-336x280.html'</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #003366; font-weight: bold;">var</span> prm <span style="color: #339933;">=</span> Sys.<span style="color: #660066;">WebForms</span>.<span style="color: #660066;">PageRequestManager</span>.<span style="color: #660066;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
&nbsp;
  prm.<span style="color: #660066;">add_endRequest</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    $get<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'AdFrame'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">src</span> <span style="color: #339933;">=</span> $get<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'AdFrame'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">src</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Now, the page will load completely before the ad’s JavaScript include is evaluated. Depending on the layout of your page, this can dramatically decrease the perceived page load time.</p>
<h3>Conclusion</h3>
<p><strong>Do apply this technique ethically</strong>. Just because you <em>can</em> rotate ads as you desire, that doesn’t mean you <em>should.</em> For instance, if you cycle CPM ads as a result of trivial operations that wouldn’t previously have resulted in an impression, <strong>you’ll be cheating your advertisers</strong>.</p>
<p>If you’d like to see this in action, just take a look at the source for my sidebar ad. It’s implemented exactly as shown above, to take advantage of deferred loading.</p>
<p>The iframe does have a couple small disadvantages, but I think their flexibility far outweighs any drawbacks. <strong>What do you think?</strong></p>
<p><p>###</p>

<p>Originally posted at <a href="http://encosia.com">Encosia</a>.  If you're reading this elsewhere, come on over and see the original.</p></p>
<p><a href="http://encosia.com/2009/01/04/how-to-rotate-javascript-ads-during-aspnet-ajax-requests/">How to rotate JavaScript ads during ASP.NET AJAX requests</a></p>
<div class="feedflare">
<a href="http://feeds.encosia.com/~f/Encosia?a=E1DZVkvn"><img src="http://feeds.feedburner.com/~f/Encosia?d=41" border="0"></img></a> <a href="http://feeds.encosia.com/~f/Encosia?a=vptkeiyh"><img src="http://feeds.feedburner.com/~f/Encosia?d=1763" border="0"></img></a> <a href="http://feeds.encosia.com/~f/Encosia?a=buZiWE4X"><img src="http://feeds.feedburner.com/~f/Encosia?d=1747" border="0"></img></a> <a href="http://feeds.encosia.com/~f/Encosia?a=T5HDs6Ur"><img src="http://feeds.feedburner.com/~f/Encosia?i=T5HDs6Ur" border="0"></img></a> <a href="http://feeds.encosia.com/~f/Encosia?a=aqvbgjjq"><img src="http://feeds.feedburner.com/~f/Encosia?i=aqvbgjjq" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/Encosia/~4/2Hh4l7NoDqU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://encosia.com/2009/01/04/how-to-rotate-javascript-ads-during-aspnet-ajax-requests/feed/</wfw:commentRss>
		<slash:comments>33</slash:comments>
		<feedburner:origLink>http://encosia.com/2009/01/04/how-to-rotate-javascript-ads-during-aspnet-ajax-requests/</feedburner:origLink></item>
	</channel>
</rss><!-- Dynamic page generated in 1.572 seconds. --><!-- Cached page generated by WP-Super-Cache on 2009-07-06 09:15:06 -->
