<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Some thoughts on web 2.0 development</title>
	<atom:link href="http://nraykov.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://nraykov.wordpress.com</link>
	<description>by Nikolay Raykov</description>
	<lastBuildDate>Wed, 30 Nov 2011 06:42:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='nraykov.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Some thoughts on web 2.0 development</title>
		<link>http://nraykov.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://nraykov.wordpress.com/osd.xml" title="Some thoughts on web 2.0 development" />
	<atom:link rel='hub' href='http://nraykov.wordpress.com/?pushpress=hub'/>
		<item>
		<title>ASP.NET MVC 3: Unobtrusive Client Side Validation</title>
		<link>http://nraykov.wordpress.com/2011/06/06/asp-net-mvc-3-unobtrusive-client-side-validation/</link>
		<comments>http://nraykov.wordpress.com/2011/06/06/asp-net-mvc-3-unobtrusive-client-side-validation/#comments</comments>
		<pubDate>Mon, 06 Jun 2011 19:51:14 +0000</pubDate>
		<dc:creator>Nikolay Raykov</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://nraykov.wordpress.com/?p=386</guid>
		<description><![CDATA[In this post we will look at one of the new features of the fresh new release of ASP.NET MVC 3 &#8211; using unobtrusive client side validation through the new HTML5 data-* attributes. I will show what these attributes look like and how they come into play. Client Validation by Default One of the main [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nraykov.wordpress.com&amp;blog=10545065&amp;post=386&amp;subd=nraykov&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post we will look at one of the new features of the fresh new release of ASP.NET MVC 3 &#8211; using unobtrusive client side validation through the new HTML5 <a href="http://dev.w3.org/html5/spec/Overview.html#embedding-custom-non-visible-data-with-the-data-attributes" target="_blank">data-*</a> attributes. I will show what these attributes look like and how they come into play.</p>
<p><strong><span style="text-decoration:underline;">Client Validation by Default</span></strong></p>
<p>One of the main differences between the new version and the previous two MVC 1 and MVC 2 is that client side validation is turned on by default. This is done using an AppSetting in the web.config file:</p>
<pre style="font-size:small;color:black;font-family:Consolas;background-color:#ffffff;overflow:auto;"><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">appSettings</span><span style="color:#0000ff;">&gt;</span>
  <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">add</span> <span style="color:#ff0000;">key</span><span style="color:#0000ff;">="ClientValidationEnabled"</span> <span style="color:#ff0000;">value</span><span style="color:#0000ff;">="true"</span><span style="color:#0000ff;">/&gt;</span>
<span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">appSettings</span><span style="color:#0000ff;">&gt; </span></pre>
<p>If you remember up until ASP.NET MVC 3 you had to explicitly specify that you want client side validation to be performed like this in your view:</p>
<pre style="font-size:small;color:black;font-family:Consolas;background-color:#ffffff;overflow:auto;"><span style="background-color:#ffff00;">&lt;%</span> Html.EnableClientValidation(); <span style="background-color:#ffff00;">%&gt;</span></pre>
<p>If you don&#8217;t want any validation in the browser you could turn it off by changing the AppSetting value of <em>ClientValidationEnabled</em> to false.</p>
<p><strong><span style="text-decoration:underline;">Unobtrusive Validation</span></strong></p>
<p>Validation in ASP.NET MVC is based on meta data provided by <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx" target="_blank">DataAnnotations<strong></strong></a>. There are quite a few classes that are really handy in describing what rules your properties must obey and the framework will take care of the rest. The HTML Helper classes (Html.TextBoxFor, Html.EditorFor, etc.) used to render different HTML controls look up these meta data attributes when the response is being generated and render the appropriate output so that validation can occur on the client&#8217;s browser.</p>
<p>By taking advantage of Unobtrusive JavaScript you don&#8217;t clatter your HTML markup with unnecessary JavaScript event handlers and so on. The HTML elements describe themselves through attributes and you get a HTML5 ready markup by default. Here is a sample UserModel class that I will use in a create user form annotated with validation attributes:</p>
<pre style="font-size:small;color:black;font-family:Consolas;background-color:#ffffff;overflow:auto;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> UserModel
{
    [Required]
    [StringLength(50)]
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">string</span> Username { get; set; }

    [Required]
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">string</span> Password { get; set; }

    [Required]
    [Compare(<span style="color:#006080;">"Password"</span>)]
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">string</span> ConfirmPassword { get; set; }

    [Required]
    [StringLength(50)]
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">string</span> FirstName { get; set; }

    [Required]
    [StringLength(50)]
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">string</span> LastName { get; set; }

    [Required]
    [StringLength(50)]
    [RegularExpression(<span style="color:#006080;">"^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2,4})$"</span>)]
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">string</span> Email { get; set; }
}</pre>
<p>When the user tries to submit the form with invalid data he/she will see the following messages:</p>
<p><a href="http://nraykov.files.wordpress.com/2011/06/Unobtrusive_Client_Side_Validation.png"><img class="aligncenter size-full wp-image-388" title="Unobtrusive Client Side Validation" src="http://nraykov.files.wordpress.com/2011/06/create_user_form.png?w=600&#038;h=433" alt="Unobtrusive Client Side Validation" width="600" height="433" /></a></p>
<p>If we look at the confirm password input element for example we will see the following HTML markup:</p>
<pre style="font-size:small;color:black;font-family:Consolas;background-color:#ffffff;overflow:auto;"><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">div</span> <span style="color:#ff0000;">class</span><span style="color:#0000ff;">="editor-field"</span><span style="color:#0000ff;">&gt;</span>
    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">input</span> <span style="color:#ff0000;">type</span><span style="color:#0000ff;">="password"</span> <span style="color:#ff0000;">name</span><span style="color:#0000ff;">="ConfirmPassword"</span> <span style="color:#ff0000;">id</span><span style="color:#0000ff;">="ConfirmPassword"</span> <span style="color:#ff0000;">data-val-required</span><span style="color:#0000ff;">="The ConfirmPassword field is required."</span> <span style="color:#ff0000;">data-val-equalto-other</span><span style="color:#0000ff;">="*.Password"</span> <span style="color:#ff0000;">data-val-equalto</span><span style="color:#0000ff;">="&amp;amp;#39;ConfirmPassword&amp;amp;#39; and &amp;amp;#39;Password&amp;amp;#39; do not match."</span> <span style="color:#ff0000;">data-val</span><span style="color:#0000ff;">="true"</span><span style="color:#0000ff;">&gt;</span>
    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">span</span> <span style="color:#ff0000;">data-valmsg-replace</span><span style="color:#0000ff;">="true"</span> <span style="color:#ff0000;">data-valmsg-for</span><span style="color:#0000ff;">="ConfirmPassword"</span> <span style="color:#ff0000;">class</span><span style="color:#0000ff;">="field-validation-valid"</span><span style="color:#0000ff;">&gt;&lt;/</span><span style="color:#800000;">span</span><span style="color:#0000ff;">&gt;</span>
<span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">div</span><span style="color:#0000ff;">&gt;</span></pre>
<p>As you can see there are a few data-val* attributes that add meta data to both this field and the span element that shows validation messages. Behind the scenes ASP.NET MVC uses <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/" target="_blank">jQuery Validation plugin </a>and the Unobtrusive validation support library for jQuery Validate written by Microsoft. If you however decide to turn unobtrusive validation off your HTML markup won&#8217;t include the new HTML5 data-* attributes but a JavaScript code that will set up the Validation plugin.</p>
<p>For the ConfirmPassword property I have used one new attribute that comes with this new release part of .NET Framework 4.0 &#8211; <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.compareattribute%28v=VS.98%29.aspx" target="_blank">CompareAttribute</a>. It gives you the ability to compare two properties of a model.</p>
<p><strong><span style="text-decoration:underline;">Summary</span></strong></p>
<p>As you can see ASP.NET MVC 3 is not lagging behind the current trends in web development utilizing some of the new HTML5 features and unobtrusive JavaScript. What I like about ASP.NET MVC and DataAnnotations is that we as developers don&#8217;t need to focus and waste too much time on simple validations like required fields, maximum length, etc. and focus on the business logic and any business rules that need to be enforced.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nraykov.wordpress.com/386/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nraykov.wordpress.com/386/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nraykov.wordpress.com/386/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nraykov.wordpress.com/386/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nraykov.wordpress.com/386/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nraykov.wordpress.com/386/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nraykov.wordpress.com/386/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nraykov.wordpress.com/386/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nraykov.wordpress.com/386/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nraykov.wordpress.com/386/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nraykov.wordpress.com/386/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nraykov.wordpress.com/386/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nraykov.wordpress.com/386/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nraykov.wordpress.com/386/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nraykov.wordpress.com&amp;blog=10545065&amp;post=386&amp;subd=nraykov&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nraykov.wordpress.com/2011/06/06/asp-net-mvc-3-unobtrusive-client-side-validation/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2dcb8f8bc7ac9875c26c582723fbda7d?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">nraykov</media:title>
		</media:content>

		<media:content url="http://nraykov.files.wordpress.com/2011/06/create_user_form.png" medium="image">
			<media:title type="html">Unobtrusive Client Side Validation</media:title>
		</media:content>
	</item>
		<item>
		<title>Architecting Loosely Coupled ASP.NET MVC Web Applications Talk</title>
		<link>http://nraykov.wordpress.com/2011/06/06/architecting-loosely-coupled-asp-net-mvc-web-applications-talk/</link>
		<comments>http://nraykov.wordpress.com/2011/06/06/architecting-loosely-coupled-asp-net-mvc-web-applications-talk/#comments</comments>
		<pubDate>Mon, 06 Jun 2011 19:50:24 +0000</pubDate>
		<dc:creator>Nikolay Raykov</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://nraykov.wordpress.com/?p=392</guid>
		<description><![CDATA[Last week Kaloyan Bochevski and I gave a talk for the Web Platform User Group at Microsoft, Bulgaria. The topic was Architecting Loosely Coupled ASP.NET MVC Web Applications. For both of us it was quite an interesting experience as it was our first presentation and we for sure have a lot to improve for any [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nraykov.wordpress.com&amp;blog=10545065&amp;post=392&amp;subd=nraykov&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Last week <a href="http://kbochevski.blogspot.com/" target="_blank">Kaloyan Bochevski</a> and I gave a talk for the Web Platform User Group at Microsoft, Bulgaria. The topic was Architecting Loosely Coupled ASP.NET MVC Web Applications. For both of us it was quite an interesting experience as it was our first presentation and we for sure have a lot to improve for any future talks we might have.</p>
<p><strong><span style="text-decoration:underline;">The agenda</span></strong></p>
<p><strong></strong>Our agenda covered a lot of areas even though it was mainly focused on how to design a loosely coupled ASP.NET MVC application. This was our list for the talk:</p>
<ul>
<li>Dependency Injection with Spring.NET</li>
<li>Custom Authentication</li>
<li>Custom Attributes</li>
<li>jQuery Grid with Model Binders</li>
<li><a href="http://nraykov.wordpress.com/2011/06/06/asp-net-mvc-3-unobtrusive-client-side-validation/">Unobtrusive Validation with Data Annotations</a></li>
<li>Security (XSS Anti-Forgery token)</li>
<li>Covariance &amp; Contravariance &#8211; IQueryable&lt;out T&gt; interface in .NET 4.0 and extension methods for .NET 3.5</li>
<li>Unit testing (NUnit, Selenium)</li>
</ul>
<p>Over the next few weeks we will post articles that cover some of the bullets in the list. Any comments would be greatly appreciated.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nraykov.wordpress.com/392/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nraykov.wordpress.com/392/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nraykov.wordpress.com/392/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nraykov.wordpress.com/392/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nraykov.wordpress.com/392/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nraykov.wordpress.com/392/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nraykov.wordpress.com/392/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nraykov.wordpress.com/392/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nraykov.wordpress.com/392/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nraykov.wordpress.com/392/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nraykov.wordpress.com/392/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nraykov.wordpress.com/392/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nraykov.wordpress.com/392/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nraykov.wordpress.com/392/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nraykov.wordpress.com&amp;blog=10545065&amp;post=392&amp;subd=nraykov&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nraykov.wordpress.com/2011/06/06/architecting-loosely-coupled-asp-net-mvc-web-applications-talk/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2dcb8f8bc7ac9875c26c582723fbda7d?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">nraykov</media:title>
		</media:content>
	</item>
		<item>
		<title>ASP.NET: PostBackUrl and How It Can Break ViewState</title>
		<link>http://nraykov.wordpress.com/2011/02/15/asp-net-postbackurl-and-how-it-can-break-viewstate/</link>
		<comments>http://nraykov.wordpress.com/2011/02/15/asp-net-postbackurl-and-how-it-can-break-viewstate/#comments</comments>
		<pubDate>Tue, 15 Feb 2011 20:12:03 +0000</pubDate>
		<dc:creator>Nikolay Raykov</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[CSharp]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://nraykov.wordpress.com/?p=360</guid>
		<description><![CDATA[I hadn&#8217;t done pure ASP.NET Web Forms development for quite a while and I had to create a really simple edit form. The requirement was to show a confirmation message if there are unsaved changes when the user clicks on a button which would redirect him to another page. It&#8217;s really straight forward but as [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nraykov.wordpress.com&amp;blog=10545065&amp;post=360&amp;subd=nraykov&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I hadn&#8217;t done pure ASP.NET Web Forms development for quite a while and I had to create a really simple edit form. The requirement was to show a confirmation message if there are unsaved changes when the user clicks on a button which would redirect him to another page. It&#8217;s really straight forward but as most seemingly simple things it turned out that it is somewhat trickier. I will explain every step I took down the road to get it done and what problems I encountered.</p>
<p><span style="text-decoration:underline;"><strong>Buttons and PostBackUrl</strong></span></p>
<p>I started with two buttons on the page:<br />
- <em>Save </em>button that triggers a postback to the server and persist the changes that the user made<br />
- <em>Return </em>button that posts back to the previous page &#8211; has its <strong>PostBackUrl</strong> property set to the url of the corresponding page</p>
<p>Then I wrote some JavaScript code that detects if there is any kind of change between the initial state of the page data and the current one when the user clicks the <em>Return </em>button. If nothing is changed the user was taken to the previous page. So far so good. But if there are some changes a confirmation message appears (I&#8217;m using a custom modal dialog, not the default browser&#8217;s confirmation dialog implementation) that notifies the user of unsaved pending changes and whether or not he/she wishes to navigate away from the current page anyway. This is where everything goes wrong. By default the ASP.NET Button control renders some JavaScript code for the <em>click</em> event of the button when <strong>PostBackUrl</strong> is set and it is executed regardless of my event handler.</p>
<p><em>Note: I am not attaching event handlers directly as attributes on DOM elements. Had I done this nothing would have messed up in my page. But this is really a bad way of doing client side development that is against unobtrusive JavaScript style.</em></p>
<p>Anyway this JavaScript code changes the form element&#8217;s <em>action </em>attribute with the value set for <strong>PostBackUrl</strong> and if the user decides that he/she wants to stay on the page and to save his/her changes the next time he/she clicks the <em>Save </em>button it will try to post back to the wrong page. Let&#8217;s say my page is called <em>Default.aspx</em> and I have another page <em>Defautl2.aspx. </em>Here is the rendered button:<em> </em></p>
<pre style="font-size:small;color:black;font-family:Consolas;background-color:#ffffff;overflow:auto;"><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">input</span> <span style="color:#ff0000;">type</span><span style="color:#0000ff;">="submit"</span> <span style="color:#ff0000;">id</span><span style="color:#0000ff;">="btnReturn"</span> <span style="color:#ff0000;">onclick</span><span style="color:#0000ff;">="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("btnReturn", "", false, "", "Default2.aspx", false, false))"</span> <span style="color:#ff0000;">value</span><span style="color:#0000ff;">="Return"</span> <span style="color:#ff0000;">name</span><span style="color:#0000ff;">="btnReturn"</span><span style="color:#0000ff;">&gt;</span></pre>
<p>As you can see there is a JavaScript function <em>WebForm_DoPostBackWithOptions</em> that gets called and receives a single parameter a helper object with all the necessary data to initiate a post back. As you can see the fifth parameter for the <em>WebForm_PostBackOptions</em> constructor is the page to which the post back would occur. Inside the <em>WebForm_DoPostBackWithOptions</em> the <em>action </em>attribute of the page&#8217;s form element is changed to <em>Default2.aspx</em>. This won&#8217;t be a problem if I was not preventing the postback from occurring. However I do prevent it and from now on any subsequent postback triggered by a control on the page would post back to <em>Default2.aspx.</em> But since the ViewState of the first page differs from that of the second one an exception is thrown:</p>
<h4><em><em>Validation of viewstate MAC failed. If this application is hosted  by a Web Farm or cluster, ensure that &lt;machineKey&gt; configuration  specifies the same validationKey and validation algorithm. AutoGenerate  cannot be used in a cluster.</em></em></h4>
<p>What is my solution then?<em><em><br />
</em></em></p>
<p><strong><span style="text-decoration:underline;">New form element</span></strong></p>
<p>I decided to go for a solution with another form element for the second page and get rid of the <strong>PostBackUrl </strong>property on the button. Now when the user decides not to leave the page no JavaScript code changes the <em>action</em> attribute of the form element and everything is the way it is supposed to be. If he/she chooses to go ahead and go to the previous page then the second form element is submitted and the user is taken to the previous page. Keep in mind that you should not define more than one form server element with <em>runat=&#8221;server&#8221;</em> attribute because ASP.NET supports only a single form element. You could either create it as a standard HTML element or add it dynamically on the page.<strong><span style="text-decoration:underline;"><br />
</span></strong></p>
<p><strong><span style="text-decoration:underline;">Summary</span></strong></p>
<p>This is not the first time I encounter this kind of exception but it was the first time I did for this kind of scenario and I was a bit puzzled in the beginning. So I needed to inspect what was going on behind the scenes and come up with a simple and quick solution. It was obvious that something is wrong when the button is clicked and debugging the injected function that makes the actual postback revealed it. There might be more elegant and clean solutions for resolving this issue so everyone is welcomed to share them.<strong><span style="text-decoration:underline;"><br />
</span></strong></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nraykov.wordpress.com/360/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nraykov.wordpress.com/360/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nraykov.wordpress.com/360/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nraykov.wordpress.com/360/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nraykov.wordpress.com/360/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nraykov.wordpress.com/360/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nraykov.wordpress.com/360/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nraykov.wordpress.com/360/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nraykov.wordpress.com/360/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nraykov.wordpress.com/360/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nraykov.wordpress.com/360/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nraykov.wordpress.com/360/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nraykov.wordpress.com/360/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nraykov.wordpress.com/360/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nraykov.wordpress.com&amp;blog=10545065&amp;post=360&amp;subd=nraykov&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nraykov.wordpress.com/2011/02/15/asp-net-postbackurl-and-how-it-can-break-viewstate/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2dcb8f8bc7ac9875c26c582723fbda7d?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">nraykov</media:title>
		</media:content>
	</item>
		<item>
		<title>DataAnnotations in Interfaces with Extension Methods</title>
		<link>http://nraykov.wordpress.com/2011/01/27/dataannotations-in-interfaces-with-extension-methods/</link>
		<comments>http://nraykov.wordpress.com/2011/01/27/dataannotations-in-interfaces-with-extension-methods/#comments</comments>
		<pubDate>Thu, 27 Jan 2011 18:54:01 +0000</pubDate>
		<dc:creator>Nikolay Raykov</dc:creator>
				<category><![CDATA[CSharp]]></category>

		<guid isPermaLink="false">http://nraykov.wordpress.com/?p=330</guid>
		<description><![CDATA[Today&#8217;s blog post is about encapsulating validation rules in interfaces. If you are to develop a loosely coupled, unit-testable application you are for sure going to use some Dependency Injection framework (take a look at this post for Spring.NET by Kaloyan Bochevski). In order to accomplish this you start by designing some interfaces for your [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nraykov.wordpress.com&amp;blog=10545065&amp;post=330&amp;subd=nraykov&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Today&#8217;s blog post is about encapsulating validation rules in interfaces. If you are to develop a loosely coupled, unit-testable application you are for sure going to use some Dependency Injection framework (take a look at <a title="MVC.NET and IoC using Spring .NET" href="http://kbochevski.blogspot.com/2010/03/mvcnet-and-ioc-using-spring-net.html" target="_blank">this post</a> for Spring.NET by Kaloyan Bochevski). In order to accomplish this you start by designing some interfaces for your different logical layers. There you end up with interface contract definitions which must be implemented by your classes. You could even go further than just declaring some methods and properties and put validation rules there. This way you would encapsulate almost everything in the interface contract so it wouldn&#8217;t be spread across different class files or assemblies.</p>
<p><strong><span style="text-decoration:underline;">Data Annotations</span></strong></p>
<p>DataAnnotations provide a great way of performing validation over data models in ASP.NET MVC and ASP.NET WebForms. Just by decorating your entity classes&#8217; properties with the necessary attributes you can get out of the box validation with no code at all. These special attribute classes can be found in System.ComponentModel assembly which needs to be referenced from your project in order to get you ready to do your validations. In ASP.NET MVC this goes even further because you could enable even client side validation of your forms that are bound to data annotated models &#8211; the framework injects JavaScript code that handles all of this as long as you include some JavaScript files and enable client side validation. You could decorate your properties and make them required, fall in a specific range of values, have maximum number of characters or abide more complex rules with regular expressions. Here is what a sample entity interface definition might look like:</p>
<pre style="font-size:small;color:black;font-family:Consolas;background-color:#ffffff;overflow:auto;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">interface</span> IPerson : IValidationEntity
{
    [Required]
    <span style="color:#0000ff;">string</span> FirstName { get; set; }

    [Required]
    <span style="color:#0000ff;">string</span> LastName { get; set; }

    [Range(5, 100)]
    <span style="color:#0000ff;">int</span> Age { get; set; }

    [Required]
    [StringLength(20)]
    <span style="color:#0000ff;">string</span> City { get; set; }

    [Required]
    [StringLength(20)]
    <span style="color:#0000ff;">string</span> Country { get; set; }
}</pre>
<p>If you are not developing against ASP.NET MVC or ASP.NET, let&#8217;s say for example you are doing a RESTful WCF service that needs to validate its input or you have some intermediary entities that are used to exchange information between different parts of a multi-layered system you could still take advantage of this validation model. Looking at the information for the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations(v=VS.90).aspx" target="_blank">System.ComponentModel.DataAnnotations Namespace</a> at MSDN you can immediately see that all of the attributes derive from  ValidationAttribute which has an IsValid() method. Basically we can get all validation attributes and check if the respective value is  valid &#8211; this is how it works under the hood after all. Since we would have several classes that need to be validated then we need to create some  common validation logic that we can reuse. This brings me to my next  point.</p>
<p><strong><span style="text-decoration:underline;">Extension Methods</span></strong></p>
<p>Extension methods provide a great deal of flexibility that I like to take advantage of whenever I can. In our scenario they will enable us to define some extensions over our interface and we will be able to validate all classes that implement this interface. First I&#8217;ll show you the definition of the interface:</p>
<pre style="font-size:small;color:black;font-family:Consolas;background-color:#ffffff;overflow:auto;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">interface</span> IValidationEntity
{
    <span style="color:#0000ff;">bool</span> Validate();
    IEnumerable&lt;<span style="color:#0000ff;">string</span>&gt; GetErrors();
}</pre>
<p>There are only two methods that we need to develop:</p>
<pre style="font-size:small;color:black;font-family:Consolas;background-color:#ffffff;overflow:auto;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">class</span> ValidationExtensions
{
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> <span style="color:#0000ff;">bool</span> IsValid&lt;T&gt;(<span style="color:#0000ff;">this</span> T entity)
        <span style="color:#0000ff;">where</span> T : IValidationEntity
    {
        Type t = entity.GetType();
        Type[] tInterfaces = t.GetInterfaces();

        <span style="color:#0000ff;">bool</span> isValid = <span style="color:#0000ff;">true</span>;
        <span style="color:#0000ff;">foreach</span> (var ifc <span style="color:#0000ff;">in</span> tInterfaces)
        {
            <span style="color:#0000ff;">foreach</span> (var prop <span style="color:#0000ff;">in</span> ifc.GetProperties())
            {
                var propVal = prop.GetValue(entity, <span style="color:#0000ff;">null</span>);
                <span style="color:#0000ff;">foreach</span> (ValidationAttribute attr <span style="color:#0000ff;">in</span> prop.GetCustomAttributes(<span style="color:#0000ff;">typeof</span>(ValidationAttribute), <span style="color:#0000ff;">true</span>))
                {
                    <span style="color:#0000ff;">if</span> (attr.IsValid(propVal))
                        <span style="color:#0000ff;">continue</span>;

                    isValid = <span style="color:#0000ff;">false</span>;
                    <span style="color:#0000ff;">break</span>;
                }

                <span style="color:#0000ff;">if</span> (!isValid)
                    <span style="color:#0000ff;">break</span>;
            }

            <span style="color:#0000ff;">if</span> (!isValid)
                <span style="color:#0000ff;">break</span>;
        }

        <span style="color:#0000ff;">return</span> isValid;
    }

    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">static</span> IEnumerable&lt;<span style="color:#0000ff;">string</span>&gt; GetValidationErrors&lt;T&gt;(<span style="color:#0000ff;">this</span> T entity)
        <span style="color:#0000ff;">where</span> T : IValidationEntity
    {
        Type t = entity.GetType();
        Type[] tInterfaces = t.GetInterfaces();

        <span style="color:#0000ff;">foreach</span> (var ifc <span style="color:#0000ff;">in</span> tInterfaces)
        {
            <span style="color:#0000ff;">foreach</span> (var prop <span style="color:#0000ff;">in</span> ifc.GetProperties())
            {
                var propVal = prop.GetValue(entity, <span style="color:#0000ff;">null</span>);
                <span style="color:#0000ff;">foreach</span> (ValidationAttribute attr <span style="color:#0000ff;">in</span> prop.GetCustomAttributes(<span style="color:#0000ff;">typeof</span>(ValidationAttribute), <span style="color:#0000ff;">true</span>))
                {
                    <span style="color:#0000ff;">if</span> (attr.IsValid(propVal))
                        <span style="color:#0000ff;">continue</span>;

                    <span style="color:#0000ff;">yield</span> <span style="color:#0000ff;">return</span> attr.FormatErrorMessage(prop.Name);
                }
            }
        }
    }
}</pre>
<p><em>IsValid</em> checks if there are errors at all and <em>GetValidationErrors</em> returns a generic collection with descriptive error messages if we ever need to return some meaningful information (in case of a RESTful service). Both methods use reflection to get to the validation metadata that we have defined. The only interesting thing in the code above is that we need to iterate over the attributes of the class&#8217;s interfaces otherwise they won&#8217;t be available to us.</p>
<p>You could <a title="DataAnnotations sample" href="http://www.box.net/shared/a5v1p47k0g" target="_blank">download</a> a sample console application that utilizes the idea of defining validation rules on the interface.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nraykov.wordpress.com/330/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nraykov.wordpress.com/330/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nraykov.wordpress.com/330/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nraykov.wordpress.com/330/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nraykov.wordpress.com/330/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nraykov.wordpress.com/330/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nraykov.wordpress.com/330/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nraykov.wordpress.com/330/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nraykov.wordpress.com/330/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nraykov.wordpress.com/330/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nraykov.wordpress.com/330/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nraykov.wordpress.com/330/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nraykov.wordpress.com/330/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nraykov.wordpress.com/330/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nraykov.wordpress.com&amp;blog=10545065&amp;post=330&amp;subd=nraykov&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nraykov.wordpress.com/2011/01/27/dataannotations-in-interfaces-with-extension-methods/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2dcb8f8bc7ac9875c26c582723fbda7d?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">nraykov</media:title>
		</media:content>
	</item>
		<item>
		<title>How to Handle Forms Authentication Timeout During an AJAX Request</title>
		<link>http://nraykov.wordpress.com/2010/10/26/how-to-handle-forms-authentication-timeout-during-an-ajax-request/</link>
		<comments>http://nraykov.wordpress.com/2010/10/26/how-to-handle-forms-authentication-timeout-during-an-ajax-request/#comments</comments>
		<pubDate>Tue, 26 Oct 2010 18:57:00 +0000</pubDate>
		<dc:creator>Nikolay Raykov</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[CSharp]]></category>

		<guid isPermaLink="false">http://nraykov.wordpress.com/?p=296</guid>
		<description><![CDATA[I stumbled upon an interesting issue the other day &#8211; how to respond to an error during an AJAX request after a period of user inactivity and a session expiration of the logged in user. In such situation you should either redirect the user to the login page or show a modal dialog where he/she [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nraykov.wordpress.com&amp;blog=10545065&amp;post=296&amp;subd=nraykov&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I stumbled upon an interesting issue the other day &#8211; how to respond to an error during an AJAX request after a period of user inactivity and a session expiration of the logged in user. In such situation you should either redirect the user to the login page or show a modal dialog where he/she could enter his or her credentials and continue their work. But this seemingly simple task turned out to be not so trivial. Here is the scenario:</p>
<ul>
<li>the user logs in</li>
<li>after a period of inactivity the session times out</li>
<li>the user makes some action which triggers an AJAX request to the server which results in a response with a status code of 302 (Redirect) and the URL to the login page</li>
<li>the browser parses the response and issues a request to the provided redirection URL</li>
<li>the AJAX request completes, the response is the HTML markup of the login page with a status code of 200 (OK) which results in an error because the expected data type is JSON and it cannot be parsed correctly</li>
</ul>
<p>The problem occurs during the last two points and the inability to determine the right cause of the error. It took me an hour or so to pinpoint and understand why this is happening. After this I tried some ideas and came up with a really simple solution.</p>
<p>What I needed was to pass the information to the XmlHttpRequest object that the user&#8217;s session had expired and to show a modal dialog so he or she could enter his or her credentials. That&#8217;s why I had to get rid of the redirection but only for AJAX requests because I still needed unauthenticated users to be redirected to the login page for non-AJAX requests. In order to do that I removed the <strong>Response.RedirectLocation</strong> in the <strong>Application_EndRequest</strong> event inside the Global.asax file:</p>
<pre style="font-size:small;color:black;font-family:Consolas;background-color:#ffffff;overflow:auto;"><span style="color:#0000ff;">protected</span> <span style="color:#0000ff;">void</span> Application_EndRequest(<span style="color:#0000ff;">object</span> sender, EventArgs args)
{
    HttpContextWrapper context = <span style="color:#0000ff;">new</span> HttpContextWrapper(Context);
    <span style="color:#0000ff;">if</span> (context.Response.StatusCode == 302 &amp;&amp; context.Request.IsAjaxRequest())
        context.Response.RedirectLocation = <span style="color:#0000ff;">string</span>.Empty;
}</pre>
<p>After that it was easy to check the status code in the error handler of the AJAX request and since I knew that a 302 status code is sent by my application only when the user is not authenticated I was able to respond accordingly.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nraykov.wordpress.com/296/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nraykov.wordpress.com/296/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nraykov.wordpress.com/296/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nraykov.wordpress.com/296/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nraykov.wordpress.com/296/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nraykov.wordpress.com/296/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nraykov.wordpress.com/296/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nraykov.wordpress.com/296/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nraykov.wordpress.com/296/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nraykov.wordpress.com/296/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nraykov.wordpress.com/296/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nraykov.wordpress.com/296/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nraykov.wordpress.com/296/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nraykov.wordpress.com/296/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nraykov.wordpress.com&amp;blog=10545065&amp;post=296&amp;subd=nraykov&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nraykov.wordpress.com/2010/10/26/how-to-handle-forms-authentication-timeout-during-an-ajax-request/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2dcb8f8bc7ac9875c26c582723fbda7d?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">nraykov</media:title>
		</media:content>
	</item>
		<item>
		<title>Show Save As Dialog With Content-Disposition Response Header</title>
		<link>http://nraykov.wordpress.com/2010/06/27/show-save-as-dialog-with-content-disposition-response-header/</link>
		<comments>http://nraykov.wordpress.com/2010/06/27/show-save-as-dialog-with-content-disposition-response-header/#comments</comments>
		<pubDate>Sun, 27 Jun 2010 11:15:08 +0000</pubDate>
		<dc:creator>Nikolay Raykov</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://nraykov.wordpress.com/?p=266</guid>
		<description><![CDATA[In this post I will talk about how you can force the browser to show a Save As dialog with a predefined filename. For the purpose of my example I will build on my previous post. Applicability This might be really useful in some type of applications &#8211; a file manager, email client application like [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nraykov.wordpress.com&amp;blog=10545065&amp;post=266&amp;subd=nraykov&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this post I will talk about how you can force the browser to show a Save As dialog with a predefined filename. For the purpose of my example I will build on my previous <a href="2010/06/17/output-xml-using-strongly-typed-views-in-asp-net-mvc/" target="_blank">post</a>.</p>
<p><span style="text-decoration:underline;"><strong>Applicability</strong></span></p>
<p>This might be really useful in some type of applications &#8211; a file manager, email client application like Gmail (downloading file attachments) and exporting data into different formats. You could rely on the browser to show Save As dialog but that might not be the case. It will prompt you to save a file if it can&#8217;t render its contents (the content type is unknown) but it will set the filename to the url it was downloaded from (you do not have a choice to give it a more proper name). Luckily there is a special response header part of the HTTP Specification that accomplishes that.</p>
<p><span style="text-decoration:underline;"><strong>Content-Disposition Header</strong></span></p>
<p>The <a href="http://www.ietf.org/rfc/rfc2183.txt" target="_blank"><em>Content-Disposition</em></a> header is optional and gives you the ability to explicitly specify the file name of the requested resource and force the showing of a Save As dialog. The file resource could be specified as <em>inline </em>(default one)<em> </em>or <em>attachment</em>. If omitted the browser tries to render it as if it is specified as <em>inline.</em> In our case we need to set it as an <em>attachment </em>so that we can force the Show As dialog to pop up:</p>
<pre style="font-size:small;color:black;font-family:Consolas;background-color:#ffffff;overflow:auto;">Content-Disposition: attachment</pre>
<p>With the <em>filename </em>parameter we notify what the file name of the requested resource should be. We can give it any meaningful name we want. If the requested relative url is the following <em>/MySite/Export</em> and the <em>filename </em>parameter is missing then the file name that the browser would suggest<em> </em>will be<em> Export</em>. This is in no way user-friendly. Here is how we can set the file name using the <em>Content-Disposition </em>header:</p>
<pre style="font-size:small;color:black;font-family:Consolas;background-color:#ffffff;overflow:auto;">Content-Disposition: attachment; filename=ExportedUser_06272010.xml</pre>
<p>Now the Save As dialog would suggest the file be saved as ExportedUser_06272010.xml. You can implement any kind of naming convention for your application and make it more user-friendly.</p>
<p><span style="text-decoration:underline;"><strong>Server side modifications</strong></span></p>
<p>Since we already know how to accomplish everything we can change the action method responsible for exporting users to xml from my previous <a href="2010/06/17/output-xml-using-strongly-typed-views-in-asp-net-mvc/" target="_blank">post</a>:</p>
<pre style="font-size:small;color:black;font-family:Consolas;background-color:#ffffff;overflow:auto;">[HttpPost]
<span style="color:#0000ff;">public</span> ActionResult Export()
{
    User user = HttpContext.Cache[<span style="color:#006080;">"user"</span>] <span style="color:#0000ff;">as</span> User;
    <span style="color:#0000ff;">if</span> (user == <span style="color:#0000ff;">null</span>)
        <span style="color:#0000ff;">return</span> View(<span style="color:#006080;">"Index"</span>);

    HttpContext.Response.AddHeader(<span style="color:#006080;">"Content-Disposition"</span>, <span style="color:#0000ff;">string</span>.Format(<span style="color:#006080;">"attachment; filename={0}_{1}.xml"</span>, user.FirstName, user.LastName));
    <span style="color:#0000ff;">return</span> View(<span style="color:#006080;">"User"</span>, user);
}</pre>
<p>The important part is where we add the <em>Content-Disposition </em>header to the response using the AddHeader method on the HttpContext&#8217;s Response property. If we start the application and click on the Export button the Save As dialog pops up:</p>
<div id="attachment_286" class="wp-caption aligncenter" style="width: 610px"><a href="http://nraykov.files.wordpress.com/2010/06/content-disposition1.png"><img class="size-full wp-image-286" title="Content-Disposition Header" src="http://nraykov.files.wordpress.com/2010/06/content-disposition1.png?w=600&#038;h=234" alt="Content-Disposition Header" width="600" height="234" /></a><p class="wp-caption-text">Content-Disposition Header</p></div>
<p><span style="text-decoration:underline;"><strong>Summary</strong></span></p>
<p>In some scenarios you need to have control over the browser and force it to show the Save As dialog and explicitly set the file name of the resource. This is accomplished with the <em>Content-Disposition </em>response header. I have attached the updated <a href="http://www.box.net/shared/gi2ld1xia0">application </a>so you can play around with it.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nraykov.wordpress.com/266/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nraykov.wordpress.com/266/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nraykov.wordpress.com/266/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nraykov.wordpress.com/266/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nraykov.wordpress.com/266/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nraykov.wordpress.com/266/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nraykov.wordpress.com/266/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nraykov.wordpress.com/266/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nraykov.wordpress.com/266/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nraykov.wordpress.com/266/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nraykov.wordpress.com/266/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nraykov.wordpress.com/266/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nraykov.wordpress.com/266/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nraykov.wordpress.com/266/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nraykov.wordpress.com&amp;blog=10545065&amp;post=266&amp;subd=nraykov&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nraykov.wordpress.com/2010/06/27/show-save-as-dialog-with-content-disposition-response-header/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2dcb8f8bc7ac9875c26c582723fbda7d?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">nraykov</media:title>
		</media:content>

		<media:content url="http://nraykov.files.wordpress.com/2010/06/content-disposition1.png" medium="image">
			<media:title type="html">Content-Disposition Header</media:title>
		</media:content>
	</item>
		<item>
		<title>Output XML Using Strongly Typed Views in ASP.NET MVC</title>
		<link>http://nraykov.wordpress.com/2010/06/17/output-xml-using-strongly-typed-views-in-asp-net-mvc/</link>
		<comments>http://nraykov.wordpress.com/2010/06/17/output-xml-using-strongly-typed-views-in-asp-net-mvc/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 20:01:59 +0000</pubDate>
		<dc:creator>Nikolay Raykov</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>

		<guid isPermaLink="false">http://nraykov.wordpress.com/?p=260</guid>
		<description><![CDATA[Recently I had to create an export to XML functionality in an ASP.NET MVC application. The first thing that came up to my mind was to use LINQ to XML to serialize my entity and then write it to the output stream with the FileStreamResult class. It could not be much more easy, right? But [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nraykov.wordpress.com&amp;blog=10545065&amp;post=260&amp;subd=nraykov&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Recently I had to create an export to XML functionality in an ASP.NET MVC application. The first thing that came up to my mind was to use LINQ to XML to serialize my entity and then write it to the output stream with the <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.filestreamresult.aspx" target="_blank">FileStreamResult</a> class. It could not be much more easy, right? But what is really a single HTML page &#8211; one irregular XML document (XHTML is well formed XML). Then I give it a thought and realized that I could use a strongly typed view for my entity and have it change its content type to <em>text/xml</em>.</p>
<p><span style="text-decoration:underline;"><strong>XML View</strong></span></p>
<p>Here is my sample User class that would be used to generate the XML file:</p>
<pre style="font-size:small;color:black;font-family:Consolas;background-color:#ffffff;overflow:auto;"><span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> User
{
    [Required(ErrorMessage = <span style="color:#006080;">"First Name is required"</span>)]
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">string</span> FirstName { get; set; }

    [Required(ErrorMessage = <span style="color:#006080;">"Last Name is required"</span>)]
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">string</span> LastName { get; set; }

    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">string</span> Street { get; set; }
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">string</span> City { get; set; }

    [Required(ErrorMessage = <span style="color:#006080;">"Country is required"</span>)]
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">string</span> Country { get; set; }

    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">string</span> PhoneNumber { get; set; }

    [Required(ErrorMessage = <span style="color:#006080;">"Email Address is required"</span>)]
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">string</span> EmailAddress { get; set; }

    [Required(ErrorMessage = <span style="color:#006080;">"Age is required"</span>)]
    [Range(0, 100, ErrorMessage = <span style="color:#006080;">"Age must be between 0 and 100"</span>)]
    <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">int</span> Age { get; set; }
}</pre>
<p>In Solution Explorer right click on your view folder and choose Add &gt; View. On the following dialog enter the name of the view and check the <em>Create a strongly-typed view</em> checkbox which enables you to select a view data class. Finally click on the <em>Add </em>button and you have created the view.</p>
<p>Now you are ready to edit its contents. The first thing you need to do is to change the <em>ContentType</em> attribute of the Page directive to <em>text/xml</em>:</p>
<pre style="font-size:small;color:black;font-family:Consolas;background-color:#ffffff;overflow:auto;"><span style="background-color:#ffff00;">&lt;%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage&lt;ExportToXml.Models.User&gt;" ContentType="text/xml" %&gt;</span></pre>
<p>This way you tell your ASP.NET MVC application to change the response header for this resource. The client&#8217;s browser would parse it and render the document as XML since it knows how to handle such type of resources.</p>
<p>Replace any other generated content with the XML you want to output. This is what the XML markup for my entity looks like:</p>
<pre style="font-size:small;color:black;font-family:Consolas;background-color:#ffffff;overflow:auto;"><span style="background-color:#ffff00;">&lt;%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage&lt;ExportToXml.Models.User&gt;" ContentType="text/xml" %&gt;</span><span style="color:#0000ff;">&lt;?</span><span style="color:#800000;">xml</span> <span style="color:#ff0000;">version</span><span style="color:#0000ff;">="1.0"</span> <span style="color:#ff0000;">encoding</span><span style="color:#0000ff;">="utf-8"</span> ?<span style="color:#0000ff;">&gt;</span>
<span style="color:#0000ff;">&lt;</span><span style="color:#800000;">User</span><span style="color:#0000ff;">&gt;</span>
    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">FirstName</span><span style="color:#0000ff;">&gt;</span><span style="background-color:#ffff00;">&lt;%</span>= Model.FirstName <span style="background-color:#ffff00;">%&gt;</span><span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">FirstName</span><span style="color:#0000ff;">&gt;</span>
    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">LastName</span><span style="color:#0000ff;">&gt;</span><span style="background-color:#ffff00;">&lt;%</span>= Model.LastName <span style="background-color:#ffff00;">%&gt;</span><span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">LastName</span><span style="color:#0000ff;">&gt;</span>
    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">Street</span><span style="color:#0000ff;">&gt;</span><span style="background-color:#ffff00;">&lt;%</span>= Model.Street <span style="background-color:#ffff00;">%&gt;</span><span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">Street</span><span style="color:#0000ff;">&gt;</span>
    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">City</span><span style="color:#0000ff;">&gt;</span><span style="background-color:#ffff00;">&lt;%</span>= Model.City <span style="background-color:#ffff00;">%&gt;</span><span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">City</span><span style="color:#0000ff;">&gt;</span>
    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">Country</span><span style="color:#0000ff;">&gt;</span><span style="background-color:#ffff00;">&lt;%</span>= Model.Country <span style="background-color:#ffff00;">%&gt;</span><span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">Country</span><span style="color:#0000ff;">&gt;</span>
    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">PhoneNumber</span><span style="color:#0000ff;">&gt;</span><span style="background-color:#ffff00;">&lt;%</span>= Model.PhoneNumber <span style="background-color:#ffff00;">%&gt;</span><span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">PhoneNumber</span><span style="color:#0000ff;">&gt;</span>
    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">EmailAddress</span><span style="color:#0000ff;">&gt;</span><span style="background-color:#ffff00;">&lt;%</span>= Model.EmailAddress <span style="background-color:#ffff00;">%&gt;</span><span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">EmailAddress</span><span style="color:#0000ff;">&gt;</span>
    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">Age</span><span style="color:#0000ff;">&gt;</span><span style="background-color:#ffff00;">&lt;%</span>= Model.Age <span style="background-color:#ffff00;">%&gt;</span><span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">Age</span><span style="color:#0000ff;">&gt;</span>
<span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">User</span><span style="color:#0000ff;">&gt;</span></pre>
<p>As you can see it&#8217;s all really simple, no rocket science. Just be sure to put the declaration of the XML right after the page directive (not on a new line) otherwise it won&#8217;t be parsed properly by the browser.</p>
<p><span style="text-decoration:underline;"><strong>Action Method</strong></span></p>
<p>The action method responsible for returning the XML document has a return type of <em>ActionResult </em>and calls the <em>View </em>helper method passing the name of the view and the entity that would be exported:</p>
<pre style="font-size:small;color:black;font-family:Consolas;background-color:#ffffff;overflow:auto;">[HttpPost]
<span style="color:#0000ff;">public</span> ActionResult Export()
{
    User user = HttpContext.Cache[<span style="color:#006080;">"user"</span>] <span style="color:#0000ff;">as</span> User;
    <span style="color:#0000ff;">if</span> (user == <span style="color:#0000ff;">null</span>)
        <span style="color:#0000ff;">return</span> View(<span style="color:#006080;">"Index"</span>);

    <span style="color:#0000ff;">return</span> View(<span style="color:#006080;">"User"</span>, user);
}</pre>
<p>As you can see if there is no user in the cache the default view is rendered, otherwise the strongly typed XML view is rendered passing the user entity instance.</p>
<p><span style="text-decoration:underline;"><strong>Putting It All Together</strong></span></p>
<p>Now that we have created this we can create an user and then export it. This is what the create user page looks like:</p>
<div id="attachment_269" class="wp-caption aligncenter" style="width: 610px"><a href="http://nraykov.files.wordpress.com/2010/06/xml_view_1.png"><img class="size-full wp-image-269" title="Create User" src="http://nraykov.files.wordpress.com/2010/06/xml_view_1.png?w=600&#038;h=229" alt="Create User" width="600" height="229" /></a><p class="wp-caption-text">Create User</p></div>
<p style="text-align:center;">
<p>After the user is created clicking on the <em>Export</em> button will call the <em>Export </em>action method which will render the strongly typed XML view. The generated XML is the following:</p>
<div id="attachment_270" class="wp-caption aligncenter" style="width: 610px"><a href="http://nraykov.files.wordpress.com/2010/06/xml_view_2.png"><img class="size-full wp-image-270" title="Generated XML" src="http://nraykov.files.wordpress.com/2010/06/xml_view_2.png?w=600&#038;h=332" alt="Generated XML" width="600" height="332" /></a><p class="wp-caption-text">Generated XML</p></div>
<p><strong><span style="text-decoration:underline;">Summary</span></strong></p>
<p>Using this technique is really simple and makes your code more readable and maintainable because you are relying on declarative code. If you need to make a change you just edit your view&#8217;s aspx page and you are ready &#8211; no need to recompile and redeploy on the production server. Keep in mind that this solution might not be applicable to your scenario &#8211; it is just one way to solve a problem. In a future post I will show you how you can make the browser show a <em>Save As </em>dialog with a specific file name (very useful in some situations).</p>
<p>You could download this sample application from <a href="http://www.box.net/shared/zryoblrack" target="_self">here</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nraykov.wordpress.com/260/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nraykov.wordpress.com/260/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nraykov.wordpress.com/260/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nraykov.wordpress.com/260/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nraykov.wordpress.com/260/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nraykov.wordpress.com/260/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nraykov.wordpress.com/260/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nraykov.wordpress.com/260/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nraykov.wordpress.com/260/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nraykov.wordpress.com/260/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nraykov.wordpress.com/260/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nraykov.wordpress.com/260/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nraykov.wordpress.com/260/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nraykov.wordpress.com/260/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nraykov.wordpress.com&amp;blog=10545065&amp;post=260&amp;subd=nraykov&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nraykov.wordpress.com/2010/06/17/output-xml-using-strongly-typed-views-in-asp-net-mvc/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2dcb8f8bc7ac9875c26c582723fbda7d?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">nraykov</media:title>
		</media:content>

		<media:content url="http://nraykov.files.wordpress.com/2010/06/xml_view_1.png" medium="image">
			<media:title type="html">Create User</media:title>
		</media:content>

		<media:content url="http://nraykov.files.wordpress.com/2010/06/xml_view_2.png" medium="image">
			<media:title type="html">Generated XML</media:title>
		</media:content>
	</item>
		<item>
		<title>Using IIS 7 Output Caching Capabilities</title>
		<link>http://nraykov.wordpress.com/2010/04/08/using-iis-7-output-caching-capabilities/</link>
		<comments>http://nraykov.wordpress.com/2010/04/08/using-iis-7-output-caching-capabilities/#comments</comments>
		<pubDate>Thu, 08 Apr 2010 19:08:07 +0000</pubDate>
		<dc:creator>Nikolay Raykov</dc:creator>
				<category><![CDATA[IIS 7]]></category>
		<category><![CDATA[Performance Optimization]]></category>

		<guid isPermaLink="false">http://nraykov.wordpress.com/?p=233</guid>
		<description><![CDATA[One of the great features of IIS 7 server is output caching. If you are performance enthusiast you have for sure taken advantage of caching in one way or another. If not this will be a chance for you to find out how easy it is to enable output caching for the entire server, single [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nraykov.wordpress.com&amp;blog=10545065&amp;post=233&amp;subd=nraykov&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>One of the great features of IIS 7 server is output caching. If you are performance enthusiast you have for sure taken advantage of caching in one way or another. If not this will be a chance for you to find out how easy it is to enable output caching for the entire server, single web site or on a more granular level. Just a few settings in the applicationHost.config or your application&#8217;s web.config files are what you need. If you do not feel at ease editing some configuration files you could use the IIS Manager as well.</p>
<p><strong><span style="text-decoration:underline;">Configuration files</span></strong></p>
<p>You could configure your server by editing the<em> applicationHost.config </em>file located at the following path &#8211; <em>%windir%\system32\inetsrv\config. </em>It is the main file for the IIS 7 server that defines all settings for all sites, applications, application pools, etc. If you choose to edit this file you should be aware that the settings you enter will be applied globally. If you only want a single site or application to be affected you could edit its <em>web.config </em>file. Regardless of which file you edit the syntax is the same.</p>
<p>There are two ways for invalidating the cache &#8211; using a timeout period (<em>CacheForTimePeriod</em>) or detecting a change in the resource file (<em>CacheUntilChange</em>). Below is a sample configuration that uses both ways for caching:</p>
<pre style="font-size:small;color:black;font-family:Consolas;background-color:#ffffff;overflow:auto;"><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">configuration</span><span style="color:#0000ff;">&gt;</span>
...
  <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">system.webServer</span><span style="color:#0000ff;">&gt;</span>
    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">caching</span> <span style="color:#ff0000;">enabled</span><span style="color:#0000ff;">="true"</span> <span style="color:#ff0000;">enableKernelCache</span><span style="color:#0000ff;">="true"</span><span style="color:#0000ff;">&gt;</span>
      <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">profiles</span><span style="color:#0000ff;">&gt;</span>
        <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">add</span> <span style="color:#ff0000;">extension</span><span style="color:#0000ff;">=".png"</span> <span style="color:#ff0000;">policy</span><span style="color:#0000ff;">="CacheUntilChange"</span> <span style="color:#0000ff;">/&gt;</span>
        <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">add</span> <span style="color:#ff0000;">extension</span><span style="color:#0000ff;">=".gif"</span> <span style="color:#ff0000;">policy</span><span style="color:#0000ff;">="CacheForTimePeriod"</span> <span style="color:#ff0000;">duration</span><span style="color:#0000ff;">="12:00:00"</span> <span style="color:#0000ff;">/&gt;</span>
      <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">profiles</span><span style="color:#0000ff;">&gt;</span>
    <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">caching</span><span style="color:#0000ff;">&gt;</span>
  <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">system.webServer</span><span style="color:#0000ff;">&gt;</span>
<span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">configuration</span><span style="color:#0000ff;">&gt;</span></pre>
<p>You could tell the IIS 7 server to cache a resource based on different criteria. In order to do this use the following attributes:</p>
<p>- varyByQueryString &#8211; caches different versions based on the query string</p>
<p>- varyByHeaders &#8211; caches different versions based on the request headers</p>
<p>You should be aware that when you are using <em>CacheForTimePeriod </em>the browser won&#8217;t make a request to the server. This does not apply to <em>CacheUntilChange </em>- a request is made but the response might not be full, e.g. the file hasn&#8217;t changed since the last request and the server returns a 304 status code indicating that the file must be loaded from the browser&#8217;s cache.</p>
<p>If you want to take advantage of kernel mode caching you could just replace the <em>policy </em>attribute with the <em>kernelCachePolicy</em> one. There are some limitations of the kernel mode output caching though &#8211; <em>varyByHeaders </em>is not supported.</p>
<p>If you have a scenario where you need greater control over what gets cached and customize it to your needs you might consider applying policies on a per folder basis. Here is a sample configuration that sets up the output caching for a single folder:</p>
<pre style="font-size:small;color:black;font-family:Consolas;background-color:#ffffff;overflow:auto;"><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">configuration</span><span style="color:#0000ff;">&gt;</span>
...
  <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">location</span> <span style="color:#ff0000;">path</span><span style="color:#0000ff;">="Images"</span><span style="color:#0000ff;">&gt;</span>
    <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">system.webServer</span><span style="color:#0000ff;">&gt;</span>
      <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">staticContent</span><span style="color:#0000ff;">&gt;</span>
        <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">clientCache</span> <span style="color:#ff0000;">cacheControlMode</span><span style="color:#0000ff;">="UseMaxAge"</span> <span style="color:#ff0000;">cacheControlMaxAge</span><span style="color:#0000ff;">="12:00:00"</span><span style="color:#0000ff;">/&gt;</span>
      <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">staticContent</span><span style="color:#0000ff;">&gt;</span>
    <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">system.webServer</span><span style="color:#0000ff;">&gt;</span>
  <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">location</span><span style="color:#0000ff;">&gt;</span>
<span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">configuration</span><span style="color:#0000ff;">&gt;</span></pre>
<p>Every file located under the <em>Images </em>folder would be cached on the client&#8217;s browser for 12 hours. If you are sure that some of your resources will not change on a regular basis you could set up a greater time period, i.e. 1 year.</p>
<p><strong><span style="text-decoration:underline;">GUI Configuration</span></strong></p>
<p>You could set up these policies from inside IIS Manager as well with almost no effort on your side. To configure the output caching globally for a given file extension select the Output Caching feature and click <em>Add&#8230;</em> You will be presented with the following dialog:</p>
<div id="attachment_241" class="wp-caption aligncenter" style="width: 610px"><a href="http://nraykov.files.wordpress.com/2010/04/output_caching_1.png"><img class="size-full wp-image-241" title="Output Caching Feature" src="http://nraykov.files.wordpress.com/2010/04/output_caching_1.png?w=600&#038;h=320" alt="Output Caching Feature" width="600" height="320" /></a><p class="wp-caption-text">Output Caching Feature</p></div>
<p>There is another feature that you could use to configure the response headers and control the output caching. Choose <em>HTTP Response Headers </em>and click on the <em>Set Common Headers&#8230; </em>action link and you will see the following dialog:</p>
<div id="attachment_242" class="wp-caption aligncenter" style="width: 610px"><a href="http://nraykov.files.wordpress.com/2010/04/output_caching_2.png"><img class="size-full wp-image-242" title="HTTP Response Headers Feature" src="http://nraykov.files.wordpress.com/2010/04/output_caching_2.png?w=600&#038;h=323" alt="HTTP Response Headers Feature" width="600" height="323" /></a><p class="wp-caption-text">HTTP Response Headers Feature</p></div>
<p>These headers could be applied on a per folder basis. If you need to add additional response headers you could use the <em>Add&#8230;</em> action link button as well.</p>
<p>As you can see all the settings that you could configure from IIS Manager could be edited by hand in your configuration file.</p>
<p><strong><span style="text-decoration:underline;">Summary</span></strong></p>
<p>In this blog post I showed you how you can set up a cache policy for your web application both through web.config and IIS Manager. Different kinds of applications could improve their performance significantly from the built-in output caching capabilities in IIS7. It is really easy to set them up and there is no excuse for anyone not taking advantage of them. Of course you could implement your own custom caching policies that do not rely on IIS7 &#8211; just implement the <em>IHttpHandler </em>interface which gives you an opportunity to intercept the request and perform whatever suits your scenario and return the necessary response.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nraykov.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nraykov.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nraykov.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nraykov.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nraykov.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nraykov.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nraykov.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nraykov.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nraykov.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nraykov.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nraykov.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nraykov.wordpress.com/233/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nraykov.wordpress.com/233/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nraykov.wordpress.com/233/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nraykov.wordpress.com&amp;blog=10545065&amp;post=233&amp;subd=nraykov&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nraykov.wordpress.com/2010/04/08/using-iis-7-output-caching-capabilities/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2dcb8f8bc7ac9875c26c582723fbda7d?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">nraykov</media:title>
		</media:content>

		<media:content url="http://nraykov.files.wordpress.com/2010/04/output_caching_1.png" medium="image">
			<media:title type="html">Output Caching Feature</media:title>
		</media:content>

		<media:content url="http://nraykov.files.wordpress.com/2010/04/output_caching_2.png" medium="image">
			<media:title type="html">HTTP Response Headers Feature</media:title>
		</media:content>
	</item>
		<item>
		<title>Ext JS Grid &#8211; rowclick and rowdblclick Issues</title>
		<link>http://nraykov.wordpress.com/2010/02/15/ext-js-grid-rowclick-and-rowdblclick-issues/</link>
		<comments>http://nraykov.wordpress.com/2010/02/15/ext-js-grid-rowclick-and-rowdblclick-issues/#comments</comments>
		<pubDate>Mon, 15 Feb 2010 20:36:25 +0000</pubDate>
		<dc:creator>Nikolay Raykov</dc:creator>
				<category><![CDATA[Ext Js]]></category>
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://nraykov.wordpress.com/?p=213</guid>
		<description><![CDATA[Last week I found an interesting issue regarding the rowclick and rowdblclick events. Here is the scenario: I have a page with an Ext JS Grid populated with some data that the user can act upon &#8211; edit fields, show field specific context menus, do some operations, etc. There is this specific requirement that the [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nraykov.wordpress.com&amp;blog=10545065&amp;post=213&amp;subd=nraykov&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Last week I found an interesting issue regarding the <em>rowclick </em>and <em>rowdblclick</em> events. Here is the scenario:</p>
<p>I have a page with an Ext JS Grid populated with some data that the user can act upon &#8211; edit fields, show field specific context menus, do some operations, etc. There is this specific requirement that the user can single click and double click a row. These are completely different actions, therefore a different operation must be performed. However due to the intrinsic browser behavior of the click event when you double click the result is somewhat unexpected &#8211; two click events and one double click event are fired. And this is where all the problems began &#8211; the code for the click event is executed twice before the double click event even though you would expect only the double click event handler to be called.</p>
<p><em>Note: I made my tests on Firefox, Google Chrome and Internet Explorer 8. Double click caused a single click event to be fired only on IE8.</em></p>
<p>Here is a screenshot of the event firing sequence in Firefox when you double click on a grid&#8217;s row:</p>
<div id="attachment_220" class="wp-caption aligncenter" style="width: 610px"><a href="http://nraykov.files.wordpress.com/2010/02/rowclick_browser_behavior_ff.png"><img class="size-full wp-image-220 " title="rowclick browser behavior" src="http://nraykov.files.wordpress.com/2010/02/rowclick_browser_behavior_ff.png?w=600&#038;h=447" alt="rowclick browser behavior" width="600" height="447" /></a><p class="wp-caption-text">rowdblclick Default Browser Behavior</p></div>
<p style="text-align:center;">
<p>This browser behavior caused some performance issues for my application, so I had to come up with some kind of a workaround.</p>
<p><span style="text-decoration:underline;"><strong>Workaround</strong></span></p>
<p>I came up with a simple solution which defers the call to the <em>rowclick</em> event handler in time so that the <em>rowdblclick</em> event handler be called and use a helper variable to indicate that double click took place. Here is the <em>rowclick </em>event handler:</p>
<pre style="font-size:small;color:black;font-family:Consolas;background-color:#ffffff;overflow:auto;">'rowclick': function(){
    window.setTimeout(function(){
        if (!isDblClick) log.innerHTML += '<span style="color:#0000ff;">&lt;</span><span style="color:#800000;">div</span><span style="color:#0000ff;">&gt;</span>row click<span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">div</span><span style="color:#0000ff;">&gt;</span>';
    }, 0);
}</pre>
<p>Calling the system function setTimeout even with 0 milliseconds does not mean that the code will be executed right away. The reason for that is that setTimeout is not executed as high priority function and the interval that it waits will be more than what you have specified. This little trick causes the <em>rowclick </em>event to be fired only once before the <em>rowdblclick </em>event. If you want to completely be sure that it won&#8217;t be fired just increase the interval as much as you find appropriate. But keep in mind that it should be reasonably small as you would want the <em>rowclick </em>event handler to be executed fast enough when the user performs a single row click.</p>
<p>Here is the <em>rowdblclick </em>event handler code:</p>
<pre style="font-size:small;color:black;font-family:Consolas;background-color:#ffffff;overflow:auto;">'rowdblclick': function(){
    isDblClick = true;
    log.innerHTML += '<span style="color:#0000ff;">&lt;</span><span style="color:#800000;">div</span><span style="color:#0000ff;">&gt;</span>row double click<span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">div</span><span style="color:#0000ff;">&gt;</span>';

    window.setTimeout(function(){
        isDblClick = false;
    }, 0);
}</pre>
<p>At the end of the event handler the helper variable <em>isDblClick </em>is set to false so that you would be sure that the <em>rowdblclick </em>event handler is done. Again you could set a greater interval if you need to. The following screenshot shows what is the the output of the <em>rowdblclick </em>event with this workaround in place:</p>
<div id="attachment_221" class="wp-caption aligncenter" style="width: 610px"><a href="http://nraykov.files.wordpress.com/2010/02/rowclick_browser_behavior_ff2.png"><img class="size-full wp-image-221" title="rowclick browser behavior workaround" src="http://nraykov.files.wordpress.com/2010/02/rowclick_browser_behavior_ff2.png?w=600&#038;h=463" alt="rowclick browser behavior workaround" width="600" height="463" /></a><p class="wp-caption-text">rowdblclick Browser Behavior Workaround</p></div>
<p style="text-align:center;">
<p>If you want to be certain that only the <em>rowdblclick </em>event handler would be executed you could increase the deferring of the <em>rowclick </em>event handler. You could download the source code for this workaround from <a href="http://www.box.net/shared/4ur10g7ydk" target="_blank">here</a>.</p>
<p><strong><span style="text-decoration:underline;">Summary</span></strong></p>
<p>This is just a simple workaround for this issue that partially fixed my performance issues &#8211; I made some other code tweaks that drastically improved the speed of execution. As an overall result the time of execution dropped more than 2.5 times. However, be advised that this is not a bulletproof solution for the problem &#8211; it depends on the performance load of the browser and how long it takes for your event handler to finish executing. The best advise I can give you though is to use only one of these events if it is appropriate for your scenario. If this is not an option then you could use this workaround or some other tricks.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nraykov.wordpress.com/213/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nraykov.wordpress.com/213/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nraykov.wordpress.com/213/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nraykov.wordpress.com/213/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nraykov.wordpress.com/213/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nraykov.wordpress.com/213/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nraykov.wordpress.com/213/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nraykov.wordpress.com/213/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nraykov.wordpress.com/213/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nraykov.wordpress.com/213/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nraykov.wordpress.com/213/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nraykov.wordpress.com/213/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nraykov.wordpress.com/213/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nraykov.wordpress.com/213/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nraykov.wordpress.com&amp;blog=10545065&amp;post=213&amp;subd=nraykov&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nraykov.wordpress.com/2010/02/15/ext-js-grid-rowclick-and-rowdblclick-issues/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2dcb8f8bc7ac9875c26c582723fbda7d?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">nraykov</media:title>
		</media:content>

		<media:content url="http://nraykov.files.wordpress.com/2010/02/rowclick_browser_behavior_ff.png" medium="image">
			<media:title type="html">rowclick browser behavior</media:title>
		</media:content>

		<media:content url="http://nraykov.files.wordpress.com/2010/02/rowclick_browser_behavior_ff2.png" medium="image">
			<media:title type="html">rowclick browser behavior workaround</media:title>
		</media:content>
	</item>
		<item>
		<title>JavaScript: Arrays vs Objects</title>
		<link>http://nraykov.wordpress.com/2010/02/01/javascript-arrays-vs-objects/</link>
		<comments>http://nraykov.wordpress.com/2010/02/01/javascript-arrays-vs-objects/#comments</comments>
		<pubDate>Mon, 01 Feb 2010 21:09:48 +0000</pubDate>
		<dc:creator>Nikolay Raykov</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Performance Optimization]]></category>

		<guid isPermaLink="false">http://nraykov.wordpress.com/?p=187</guid>
		<description><![CDATA[Overview More and more web applications place an even heavier burden on the client-side &#8211; user-driven UIs, games even LOB applications take to some extent part of their code-behind logic off the servers and onto the clients&#8217; browsers. There is a constant battle between rival browsers for increasing the speed of JavaScript execution and page [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nraykov.wordpress.com&amp;blog=10545065&amp;post=187&amp;subd=nraykov&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><span style="text-decoration:underline;"><strong>Overview</strong></span></p>
<p>More and more web applications place an even heavier burden on the client-side &#8211; user-driven UIs, games even LOB applications take to some extent part of their code-behind logic off the servers and onto the clients&#8217; browsers. There is a constant battle between rival browsers for increasing the speed of JavaScript execution and page rendering. Every several months a new version of a Firefox, Google Chrome, Safari and Opera comes out that claims it improves the speed of execution by a factor of&#8230; you know it. But that does not mean that we developers should wait for the next major release and hope for the best that our application will not hang and will work smoothly.</p>
<p><span style="text-decoration:underline;"><strong>The Problem</strong></span></p>
<p>If we are to develop a highly responsive resource intensive application we should try to minimize every single long running operation. One of these time consuming operations is when we work with arrays. Everyone knows that in order to get a specific element an iteration should be made. If the element is at the beginning of the array you will be lucky but that won&#8217;t be the average case. If you hold some of your data on the client in order to prevent hitting the server which in turn might make an additional call(s) to the DB server you should ensure that it will be accessible in the most appropriate manner. Then how would you go about storing this data? The solution to the problem seems a very simple one &#8211; arrays.</p>
<p>The data that comes from the database has a very natural way of presenting itself as a collection or array in every language. But is it the most efficient way? Certainly not. C# offers Hashtables and Dictionaries for accessing objects using keys. How can you do something similar in JavaScript. The answer is using Objects.</p>
<p>JavaScript is an object-oriented language at its heart that offers a lot of power when used right. Let&#8217;s say that you have a collection of employees (ID, Name and Job Position) that you need to hit on a regular basis. Why would you try to iterate over them every time that you need one of them when you could directly access it? For this purpose you create a helper object that will hold all the data from the array (yes, you will have to iterate it but it will be done only once in order to initialize your object). Or you could even write a custom JSON serializer class which will directly output it as a JSON Object, hence no additional overhead on the client.</p>
<p>JavaScript objects are similar to a C# Hashtable &#8211; they have a key and value. You can take advantage of this feature and use the IDs of the employees as keys and the other properties as a value. Since IDs should be unique you are guaranteed that every employee is uniquely identifiable.</p>
<p>Here is the code that I use to create my helper object:</p>
<pre style="font-size:small;color:black;font-family:Consolas;background-color:#ffffff;overflow:auto;">var obj = {};
for (var i = 0; i <span style="color:#0000ff;">&lt;</span> emp.length; i++){
    var curr = emp[i];
    obj[curr.ID] = { Name: curr.Name, Position: curr.Position };
}</pre>
<p>Now you will be able to use the ID to access the employee properties with no overhead.</p>
<pre style="font-size:small;color:black;font-family:Consolas;background-color:#ffffff;overflow:auto;">function findEmp(id){
    return helperObj[id];
};</pre>
<p>I have prepared a simple test page that initializes an array with just 1000 elements which are then mapped to a helper object. I have used the Firefox API to profile the JavaScript execution and show the time it takes for each operation. Accessing the properties through the helper object can be several times faster (this depends on the index of the element inside the array and/or the load on the browser).</p>
<p>Here is a screenshot of running the Profiler for my test page:</p>
<div id="attachment_192" class="wp-caption aligncenter" style="width: 610px"><a href="http://nraykov.files.wordpress.com/2010/02/arrays_vs_objects.png"><img class="size-full wp-image-192" title="JavaScript Arrays vs Objects" src="http://nraykov.files.wordpress.com/2010/02/arrays_vs_objects.png?w=600&#038;h=101" alt="JavaScript Arrays vs Objects" width="600" height="101" /></a><p class="wp-caption-text">JavaScript Arrays vs Objects</p></div>
<p>As you can see the call to <em>findEmpIteratively </em>(which uses the array)<em> </em>took 0.146 milliseconds (for 124th element) to complete &#8211; that&#8217;s nothing and it happens in a blink of an eye but compared to <em>findEmp </em>(0.003 milliseconds)<em> </em>it is huge. Don&#8217;t forget that beside calling this function you would then use this employee data to do something else &#8211; open a dialog, create some elements, apply CSS styles to them, etc. At the end the overall time that would take to complete the operation the user requested will be much more than that. So it is worthwhile to investigate an issue like that.</p>
<p><span style="text-decoration:underline;"><strong>Summary</strong></span></p>
<p>There is no doubt that some trick like this will help you in a way but it will not solve all your performance problems. You must plan and have a clear picture in your head what is going on and what you have to do to optimize your code. There are times when using an array will suffice &#8211; for example if you are using it just to create some HTML elements when rendering the page. What is best depends on the specific scenario &#8211; if you are regularly iterating over the same array, you could replace it with a JavaScript object.</p>
<p>If you would like to see the source code for this test, you could download it <a href="http://www.box.net/shared/fzjzb4nhd2" target="_blank">here</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/nraykov.wordpress.com/187/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/nraykov.wordpress.com/187/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/nraykov.wordpress.com/187/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/nraykov.wordpress.com/187/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/nraykov.wordpress.com/187/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/nraykov.wordpress.com/187/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/nraykov.wordpress.com/187/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/nraykov.wordpress.com/187/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/nraykov.wordpress.com/187/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/nraykov.wordpress.com/187/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/nraykov.wordpress.com/187/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/nraykov.wordpress.com/187/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/nraykov.wordpress.com/187/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/nraykov.wordpress.com/187/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=nraykov.wordpress.com&amp;blog=10545065&amp;post=187&amp;subd=nraykov&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://nraykov.wordpress.com/2010/02/01/javascript-arrays-vs-objects/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/2dcb8f8bc7ac9875c26c582723fbda7d?s=96&#38;d=http%3A%2F%2F0.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&#38;r=G" medium="image">
			<media:title type="html">nraykov</media:title>
		</media:content>

		<media:content url="http://nraykov.files.wordpress.com/2010/02/arrays_vs_objects.png" medium="image">
			<media:title type="html">JavaScript Arrays vs Objects</media:title>
		</media:content>
	</item>
	</channel>
</rss>
