<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2titles.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemtitles.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Stephen Walther</title>
	
	<link>http://stephenwalther.com/blog</link>
	<description>ASP.NET MVC, Windows Metro, JavaScript</description>
	<lastBuildDate>Wed, 02 May 2012 15:15:21 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/StephenWalther" /><feedburner:info uri="stephenwalther" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:feedFlare href="http://add.my.yahoo.com/rss?url=http%3A%2F%2Ffeeds.feedburner.com%2FStephenWalther" src="http://us.i1.yimg.com/us.yimg.com/i/us/my/addtomyyahoo4.gif">Subscribe with My Yahoo!</feedburner:feedFlare><feedburner:feedFlare href="http://www.newsgator.com/ngs/subscriber/subext.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2FStephenWalther" src="http://www.newsgator.com/images/ngsub1.gif">Subscribe with NewsGator</feedburner:feedFlare><feedburner:feedFlare href="http://www.bloglines.com/sub/http://feeds.feedburner.com/StephenWalther" src="http://www.bloglines.com/images/sub_modern11.gif">Subscribe with Bloglines</feedburner:feedFlare><feedburner:feedFlare href="http://www.netvibes.com/subscribe.php?url=http%3A%2F%2Ffeeds.feedburner.com%2FStephenWalther" src="http://www.netvibes.com/img/add2netvibes.gif">Subscribe with Netvibes</feedburner:feedFlare><feedburner:feedFlare href="http://fusion.google.com/add?feedurl=http%3A%2F%2Ffeeds.feedburner.com%2FStephenWalther" src="http://buttons.googlesyndication.com/fusion/add.gif">Subscribe with Google</feedburner:feedFlare><feedburner:feedFlare href="http://www.pageflakes.com/subscribe.aspx?url=http%3A%2F%2Ffeeds.feedburner.com%2FStephenWalther" src="http://www.pageflakes.com/ImageFile.ashx?instanceId=Static_4&amp;fileName=ATP_blu_91x17.gif">Subscribe with Pageflakes</feedburner:feedFlare><feedburner:feedFlare href="http://www.plusmo.com/add?url=http%3A%2F%2Ffeeds.feedburner.com%2FStephenWalther" src="http://plusmo.com/res/graphics/fbplusmo.gif">Subscribe with Plusmo</feedburner:feedFlare><feedburner:feedFlare href="http://www.live.com/?add=http%3A%2F%2Ffeeds.feedburner.com%2FStephenWalther" src="http://tkfiles.storage.msn.com/x1piYkpqHC_35nIp1gLE68-wvzLZO8iXl_JMledmJQXP-XTBOLfmQv4zhj4MhcWEJh_GtoBIiAl1Mjh-ndp9k47If7hTaFno0mxW9_i3p_5qQw">Subscribe with Live.com</feedburner:feedFlare><feedburner:feedFlare href="http://www.addtoany.com/?linkname=Stephen%20Walther&amp;linkurl=http%3A%2F%2Ffeeds.feedburner.com%2FStephenWalther&amp;type=feed" src="http://www.addtoany.com/addfr-b.gif">Add to Any Feed Reader</feedburner:feedFlare><feedburner:browserFriendly>Get the latest news, tips, and articles on ASP.NET MVC by subscribing to Stephen Walther's blog.</feedburner:browserFriendly><item>
		<title>Ajax Control Toolkit May 2012 Release</title>
		<link>http://feedproxy.google.com/~r/StephenWalther/~3/C-nTqgH2SCs/ajax-control-toolkit-may-2012-release.aspx</link>
		<comments>http://stephenwalther.com/blog/archive/2012/05/01/ajax-control-toolkit-may-2012-release.aspx#comments</comments>
		<pubDate>Tue, 01 May 2012 16:46:46 +0000</pubDate>
		<dc:creator>Stephen.Walther</dc:creator>
				<category><![CDATA[ACT]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>

		<guid isPermaLink="false">http://stephenwalther.com/blog/?p=509</guid>
		<description><![CDATA[I’m happy to announce the May 2012 release of the Ajax Control Toolkit. This newest release of the Ajax Control Toolkit includes a new file upload control which displays file upload progress. We’ve also added several significant enhancements to the existing HtmlEditorExtender control such as support for uploading images and Source View. You can download [...]]]></description>
			<content:encoded><![CDATA[<p>I’m happy to announce the May 2012 release of the Ajax Control Toolkit. This newest release of the Ajax Control Toolkit includes a new file upload control which displays file upload progress. We’ve also added several significant enhancements to the existing HtmlEditorExtender control such as support for uploading images and Source View.
<p>You can download and start using the newest version of the Ajax Control Toolkit by entering the following command in the Library Package Manager console in Visual Studio:
<p>Install-Package AjaxControlToolkit
<p>Alternatively, you can download the latest version of the Ajax Control Toolkit from CodePlex:
<p><a href="http://AjaxControlToolkit.CodePlex.com">http://AjaxControlToolkit.CodePlex.com</a><br />
<h3>The New Ajax File Upload Control</h3>
<p>The most requested new feature for the Ajax Control Toolkit (according to the CodePlex Issue Tracker) has been support for file upload with progress. We worked hard over the last few months to create an entirely new file upload control which displays upload progress.
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image002.jpg"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="clip_image002" border="0" alt="clip_image002" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image002_thumb.jpg" width="628" height="255"></a>
<p>Here is a sample which illustrates how you can use the new AjaxFileUpload control:
<pre class="brush: xml;">&lt;%@ Page Language="C#" AutoEventWireup="true" CodeBehind="01_FileUpload.aspx.cs" Inherits="WebApplication1._01_FileUpload" %&gt;
&lt;html&gt;
&lt;head runat="server"&gt;
    &lt;title&gt;Simple File Upload&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form id="form1" runat="server"&gt;
    &lt;div&gt;

    &lt;ajaxToolkit:ToolkitScriptManager runat="server" /&gt;

    &lt;ajaxToolkit:AjaxFileUpload
        id="ajaxUpload1"
        OnUploadComplete="ajaxUpload1_OnUploadComplete"
        runat="server"  /&gt;

    &lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The page above includes a ToolkitScriptManager control. This control is required to use any of the controls in the Ajax Control Toolkit because this control is responsible for loading all of the scripts required by a control. </p>
<p>The page also contains an AjaxFileUpload control. The UploadComplete event is handled in the code-behind for the page:
<pre class="brush: csharp;">namespace WebApplication1
{
    public partial class _01_FileUpload : System.Web.UI.Page
    {
        protected void ajaxUpload1_OnUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
        {
            // Generate file path
            string filePath = "~/Images/" + e.FileName;

            // Save upload file to the file system
            ajaxUpload1.SaveAs(MapPath(filePath));
        }
    }
}
</pre>
<p>The UploadComplete handler saves each uploaded file by calling the AjaxFileUpload control’s SaveAs() method with a full file path. </p>
<p>Here’s a video which illustrates the process of uploading a file: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image003.gif"><img style="display: inline" title="clip_image003" alt="clip_image003" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image003_thumb.gif" width="800" height="600"></a> </p>
<p>Warning: in order to write to the Images folder on a production IIS server, you need Write permissions on the Images folder. You need to provide permissions for the IIS Application Pool account to write to the Images folder. To learn more, see: </p>
<p><a href="http://learn.iis.net/page.aspx/624/application-pool-identities/">http://learn.iis.net/page.aspx/624/application-pool-identities/</a> </p>
<h4>Showing File Upload Progress</h4>
<p>The new AjaxFileUpload control takes advantage of HTML5 upload progress events (described in the <a href="http://www.w3.org/TR/XMLHttpRequest2/">XMLHttpRequest Level 2</a> standard). This standard is supported by Firefox 8+, Chrome 16+, Safari 5+, and Internet Explorer 10+. In other words, the standard is supported by the most recent versions of all browsers except for Internet Explorer which will support the standard with the release of Internet Explorer 10. </p>
<p>The AjaxFileUpload control works with all browsers, even browsers which do not support the new XMLHttpRequest Level 2 standard. If you use the AjaxFileUpload control with a downlevel browser – such as Internet Explorer 9 &#8212; then you get a simple throbber image during a file upload instead of a progress indicator. </p>
<p>Here’s how you specify a throbber image when declaring the AjaxFileUpload control:
<pre class="brush: xml;">&lt;%@ Page Language="C#" AutoEventWireup="true" CodeBehind="02_FileUpload.aspx.cs" Inherits="WebApplication1._02_FileUpload" %&gt;
&lt;html&gt;
&lt;head id="Head1" runat="server"&gt;
    &lt;title&gt;File Upload with Throbber&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form id="form1" runat="server"&gt;
    &lt;div&gt;

    &lt;ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" /&gt;

    &lt;ajaxToolkit:AjaxFileUpload
        id="ajaxUpload1"
        OnUploadComplete="ajaxUpload1_OnUploadComplete"
        ThrobberID="MyThrobber"
        runat="server"  /&gt;

        &lt;asp:Image
            id="MyThrobber"
            ImageUrl="ajax-loader.gif"
            Style="display:None"
            runat="server" /&gt;

    &lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Notice that the page above includes an image with the Id MyThrobber. This image is displayed while files are being uploaded. </p>
<p>I use the website <a href="http://AjaxLoad.info">http://AjaxLoad.info</a> to generate animated busy wait images. </p>
<h4>Drag-And-Drop File Upload</h4>
<p>If you are using an uplevel browser then you can drag-and-drop the files which you want to upload onto the AjaxFileUpload control. The following video illustrates how drag-and-drop works: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image004.gif"><img style="display: inline" title="clip_image004" alt="clip_image004" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image004_thumb.gif" width="800" height="600"></a> </p>
<p>Remember that drag-and-drop <i>will not</i> work on Internet Explorer 9 or older. </p>
<h4>Accepting Multiple Files</h4>
<p>By default, the AjaxFileUpload control enables you to upload multiple files at a time. When you open the file dialog, use the CTRL or SHIFT key to select multiple files. </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image005.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="clip_image005" border="0" alt="clip_image005" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image005_thumb.png" width="629" height="658"></a> </p>
<p>If you want to restrict the number of files that can be uploaded then use the MaximumNumberOfFiles property like this:
<pre class="brush: xml;">&lt;ajaxToolkit:AjaxFileUpload
    id="ajaxUpload1"
    OnUploadComplete="ajaxUpload1_OnUploadComplete"
    ThrobberID="throbber"
    MaximumNumberOfFiles="1"
    runat="server"  /&gt;
</pre>
<p>In the code above, the maximum number of files which can be uploaded is restricted to a single file. </p>
<h4>Restricting Uploaded File Types </h4>
<p>You might want to allow only certain types of files to be uploaded. For example, you might want to accept only image uploads. In that case, you can use the AllowedFileTypes property to provide a list of allowed file types like this:
<pre class="brush: xml;">&lt;ajaxToolkit:AjaxFileUpload
    id="ajaxUpload1"
    OnUploadComplete="ajaxUpload1_OnUploadComplete"
    ThrobberID="throbber"
    AllowedFileTypes="jpg,jpeg,gif,png"
    runat="server"  /&gt;
</pre>
<p>The code above prevents any files except jpeg, gif, and png files from being uploaded. </p>
<h3>Enhancements to the HTMLEditorExtender</h3>
<p>Over the past months, we spent a considerable amount of time making bug fixes and feature enhancements to the existing HtmlEditorExtender control. I want to focus on two of the most significant enhancements that we made to the control: support for Source View and support for uploading images. </p>
<h4>Adding Source View Support to the HtmlEditorExtender</h4>
<p>When you click the Source View tag, the HtmlEditorExtender changes modes and displays the HTML source of the contents contained in the TextBox being extended. You can use Source View to make fine-grain changes to HTML before submitting the HTML to the server. </p>
<p>For reasons of backwards compatibility, the Source View tab is disabled by default. To enable Source View, you need to declare your HtmlEditorExtender with the DisplaySourceTab property like this:
<pre class="brush: xml;">&lt;%@ Page Language="C#" AutoEventWireup="true" CodeBehind="05_SourceView.aspx.cs" Inherits="WebApplication1._05_SourceView" %&gt;
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
&lt;html&gt;
&lt;head id="Head1" runat="server"&gt;
    &lt;title&gt;HtmlEditorExtender with Source View&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form id="form1" runat="server"&gt;
    &lt;div&gt;

    &lt;ajaxToolkit:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server" /&gt;

    &lt;asp:TextBox
        id="txtComments"
        TextMode="MultiLine"
        Columns="60"
        Rows="10"
        Runat="server" /&gt;

    &lt;ajaxToolkit:HtmlEditorExtender
        id="HEE1"
        TargetControlID="txtComments"
        DisplaySourceTab="true"
        runat="server"  /&gt;

    &lt;/div&gt;
    &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The page above includes a ToolkitScriptManager, TextBox, and HtmlEditorExtender control. The HtmlEditorExtender extends the TextBox so that it supports rich text editing. </p>
<p>Notice that the HtmlEditorExtender includes a DisplaySourceTab property. This property causes a button to appear at the bottom of the HtmlEditorExtender which enables you to switch to Source View: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image006.gif"><img style="display: inline" title="clip_image006" alt="clip_image006" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image006_thumb.gif" width="800" height="600"></a> </p>
<p>Note: when using the HtmlEditorExtender, we recommend that you set the DOCTYPE for the document. Otherwise, you can encounter weird formatting issues. </p>
<h4>Accepting Image Uploads</h4>
<p>We also enhanced the HtmlEditorExtender to support image uploads (another very highly requested feature at CodePlex). The following video illustrates the experience of adding an image to the editor: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image007.gif"><img style="display: inline" title="clip_image007" alt="clip_image007" src="http://stephenwalther.com/blog/wp-content/uploads/2012/05/clip_image007_thumb.gif" width="800" height="600"></a> </p>
<p>Once again, for backwards compatibility reasons, support for image uploads is disabled by default. Here’s how you can declare the HtmlEditorExtender so that it supports image uploads:
<pre class="brush: xml;">&lt;ajaxToolkit:HtmlEditorExtender
    id="MyHtmlEditorExtender"
    TargetControlID="txtComments"
    OnImageUploadComplete="MyHtmlEditorExtender_ImageUploadComplete"
    DisplaySourceTab="true"
    runat="server" &gt;
    &lt;Toolbar&gt;
        &lt;ajaxToolkit:Bold /&gt;
        &lt;ajaxToolkit:Italic /&gt;
        &lt;ajaxToolkit:Underline /&gt;
        &lt;ajaxToolkit:InsertImage /&gt;
    &lt;/Toolbar&gt;
&lt;/ajaxToolkit:HtmlEditorExtender&gt;
</pre>
<p>There are two things that you should notice about the code above. First, notice that an InsertImage toolbar button is added to the HtmlEditorExtender toolbar. This HtmlEditorExtender will render toolbar buttons for bold, italic, underline, and insert image. </p>
<p>Second, notice that the HtmlEditorExtender includes an event handler for the ImageUploadComplete event. The code for this event handler is below:
<pre class="brush: csharp;">using System.Web.UI;
using AjaxControlToolkit;

namespace WebApplication1
{
    public partial class _06_ImageUpload : System.Web.UI.Page
    {

        protected void MyHtmlEditorExtender_ImageUploadComplete(object sender, AjaxFileUploadEventArgs e)
        {
            // Generate file path
            string filePath = "~/Images/" + e.FileName;

            // Save uploaded file to the file system
            var ajaxFileUpload = (AjaxFileUpload)sender;
            ajaxFileUpload.SaveAs(MapPath(filePath));

            // Update client with saved image path
            e.PostedUrl = Page.ResolveUrl(filePath);
        }
    }
}
</pre>
<p>Within the ImageUploadComplete event handler, you need to do two things: </p>
<p>1) Save the uploaded image (for example, to the file system, a database, or Azure storage) </p>
<p>2) Provide the URL to the saved image so the image can be displayed within the HtmlEditorExtender </p>
<p>In the code above, the uploaded image is saved to the ~/Images folder. The path of the saved image is returned to the client by setting the AjaxFileUploadEventArgs PostedUrl property. </p>
<p>Not surprisingly, under the covers, the HtmlEditorExtender uses the AjaxFileUpload. You can get a direct reference to the AjaxFileUpload control used by an HtmlEditorExtender by using the following code:
<pre class="brush: csharp;">void Page_Load()
{
    var ajaxFileUpload = MyHtmlEditorExtender.AjaxFileUpload;
    ajaxFileUpload.AllowedFileTypes = "jpg,jpeg";
}
</pre>
<p>The code above illustrates how you can restrict the types of images that can be uploaded to the HtmlEditorExtender. This code prevents anything but jpeg images from being uploaded. </p>
<h3>Summary</h3>
<p>This was the most difficult release of the Ajax Control Toolkit to date. We iterated through several designs for the AjaxFileUpload control – with each iteration, the goal was to make the AjaxFileUpload control easier for developers to use. My hope is that we were able to create a control which Web Forms developers will find very intuitive. </p>
<p>I want to thank the developers on the Superexpert.com team for their hard work on this release.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/StephenWalther?a=C-nTqgH2SCs:O8opVesil9M:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/C-nTqgH2SCs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stephenwalther.com/blog/archive/2012/05/01/ajax-control-toolkit-may-2012-release.aspx/feed</wfw:commentRss>
		<slash:comments>21</slash:comments>
		<feedburner:origLink>http://stephenwalther.com/blog/archive/2012/05/01/ajax-control-toolkit-may-2012-release.aspx</feedburner:origLink></item>
		<item>
		<title>ASP.NET Connections Spring 2012 Talks and Code</title>
		<link>http://feedproxy.google.com/~r/StephenWalther/~3/D20Z2ceY5n0/asp-net-connections-spring-2012-talks-and-code.aspx</link>
		<comments>http://stephenwalther.com/blog/archive/2012/04/09/asp-net-connections-spring-2012-talks-and-code.aspx#comments</comments>
		<pubDate>Mon, 09 Apr 2012 12:13:57 +0000</pubDate>
		<dc:creator>Stephen.Walther</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Talks]]></category>

		<guid isPermaLink="false">http://stephenwalther.com/blog/?p=493</guid>
		<description><![CDATA[Thank you everyone who attended my ASP.NET Connections talks last week in Las Vegas. I’ve attached the slides and code for the three talks that I delivered: &#160; Using jQuery to interact with the Server through Ajax – In this talk, I discuss the different ways to communicate information between browser and server using Ajax. [...]]]></description>
			<content:encoded><![CDATA[<p>Thank you everyone who attended my ASP.NET Connections talks last week in Las Vegas. I’ve attached the slides and code for the three talks that I delivered:</p>
<p>&nbsp;</p>
<ul>
<li><a href="/downloads/Talks/ASPNETConnectionsSpring2012/Walther_jQueryAjax.zip">Using jQuery to interact with the Server through Ajax</a> – In this talk, I discuss the different ways to communicate information between browser and server using Ajax. I explain the difference between the different types of Ajax calls that you can make with jQuery. I also discuss the differences between the JavaScriptSerializer, the DataContractJsonSerializer, and the JSON.NET serializer.
<p>&nbsp;</p>
<li><a href="/downloads/Talks/ASPNETConnectionsSpring2012/Walther_MVCValidation.zip">ASP.NET Validation In-Depth</a> – In this talk, I distinguish between View Model Validation and Domain Model Validation. I demonstrate how you can use the validation attributes (including the new .NET 4.5 validation attributes), the jQuery Validation library, and the HTML5 input validation attributes to perform View Model Validation. I then demonstrate how you can use the IValidatableObject interface with the Entity Framework to perform Domain Model Validation.
<p>&nbsp;</p>
<li><a href="/downloads/Talks/ASPNETConnectionsSpring2012/Walther_MVVM.zip">Using the MVVM Pattern with JavaScript Views</a> – In this talk, I discuss how you can create single page applications (SPA) by taking advantage of the open-source KnockoutJS library and the ASP.NET Web API. </li>
</ul>
<p>&nbsp;</p>
<p>Be warned that the sample code is contained in Visual Studio 11 Beta projects. If you don’t have this version of Visual Studio, then you will need to open the code samples in Notepad.</p>
<p>Also, I apologize for getting the code for these talks posted so slowly. I’ve been down with a nasty case of the flu for the past week and haven’t been able to get to a computer.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/StephenWalther?a=D20Z2ceY5n0:o7OV_qQ3nOA:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/D20Z2ceY5n0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stephenwalther.com/blog/archive/2012/04/09/asp-net-connections-spring-2012-talks-and-code.aspx/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://stephenwalther.com/blog/archive/2012/04/09/asp-net-connections-spring-2012-talks-and-code.aspx</feedburner:origLink></item>
		<item>
		<title>Metro: Introduction to CSS 3 Grid Layout</title>
		<link>http://feedproxy.google.com/~r/StephenWalther/~3/UXt3Tc7yYsU/metro-introduction-to-css-3-grid-layout.aspx</link>
		<comments>http://stephenwalther.com/blog/archive/2012/03/19/metro-introduction-to-css-3-grid-layout.aspx#comments</comments>
		<pubDate>Tue, 20 Mar 2012 00:01:22 +0000</pubDate>
		<dc:creator>Stephen.Walther</dc:creator>
				<category><![CDATA[Metro]]></category>

		<guid isPermaLink="false">http://stephenwalther.com/blog/?p=490</guid>
		<description><![CDATA[The purpose of this blog post is to provide you with a quick introduction to the new W3C CSS 3 Grid Layout standard. You can use CSS Grid Layout in Metro style applications written with JavaScript to lay out the content of an HTML page. CSS Grid Layout provides you with all of the benefits [...]]]></description>
			<content:encoded><![CDATA[<p>The purpose of this blog post is to provide you with a quick introduction to the new W3C CSS 3 Grid Layout standard. You can use CSS Grid Layout in Metro style applications written with JavaScript to lay out the content of an HTML page. CSS Grid Layout provides you with all of the benefits of using HTML tables for layout without requiring you to actually use any HTML table elements.<br />
<h3>Doing Page Layouts without Tables</h3>
<p>Back in the 1990’s, if you wanted to create a fancy website, then you would use HTML tables for layout. For example, if you wanted to create a standard three-column page layout then you would create an HTML table with three columns like this:
<pre class="brush: xml;">&lt;table height="100%"&gt;
&lt;tr&gt;
  &lt;td valign="top" width="300px" bgcolor="red"&gt;
    Left Column, Left Column, Left Column,
    Left Column, Left Column, Left Column,
    Left Column, Left Column, Left Column
  &lt;/td&gt;
  &lt;td valign="top" bgcolor="green"&gt;
    Middle Column, Middle Column, Middle Column,
    Middle Column, Middle Column, Middle Column,
    Middle Column, Middle Column, Middle Column
  &lt;/td&gt;
  &lt;td valign="top" width="300px" bgcolor="blue"&gt;
    Right Column, Right Column, Right Column,
    Right Column, Right Column, Right Column,
    Right Column, Right Column, Right Column
  &lt;/td&gt;
&lt;/tr&gt;
&lt;/table&gt;
</pre>
<p>When the table above gets rendered out to a browser, you end up with the following three-column layout: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image002.jpg"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image002" border="0" alt="clip_image002" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image002_thumb.jpg" width="628" height="279"></a> </p>
<p>The width of the left and right columns is fixed – the width of the middle column expands or contracts depending on the width of the browser. </p>
<p>Sometime around the year 2005, everyone decided that using tables for layout was a bad idea. Instead of using tables for layout &#8212; it was collectively decided by the spirit of the Web &#8212; you should use Cascading Style Sheets instead. </p>
<p>Why is using HTML tables for layout bad? Using tables for layout breaks the semantics of the TABLE element. A TABLE element should be used only for displaying tabular information such as train schedules or moon phases. Using tables for layout is bad for accessibility (The Web Content Accessibility Guidelines 1.0 is explicit about this) and using tables for layout is bad for separating content from layout (see <a href="http://CSSZenGarden.com">http://CSSZenGarden.com</a>). </p>
<p>Post 2005, anyone who used HTML tables for layout were encouraged to hold their heads down in shame. </p>
<p>That’s all well and good, but the problem with using CSS for layout is that it can be more difficult to work with CSS than HTML tables. For example, to achieve a standard three-column layout, you either need to use absolute positioning or floats. Here’s a three-column layout with floats:
<pre class="brush: xml;">&lt;style type="text/css"&gt;
#container {
  min-width: 800px;
}

#leftColumn {
  float: left;
  width: 300px;
  height: 100%;
  background-color:red;
}

#middleColumn {
  background-color:green;
  height: 100%;
}

#rightColumn {
  float: right;
  width: 300px;
  height: 100%;
  background-color:blue;
}
&lt;/style&gt;

&lt;div id="container"&gt;
  &lt;div id="rightColumn"&gt;
    Right Column, Right Column, Right Column,
    Right Column, Right Column, Right Column,
    Right Column, Right Column, Right Column
  &lt;/div&gt;
  &lt;div id="leftColumn"&gt;
    Left Column, Left Column, Left Column,
    Left Column, Left Column, Left Column,
    Left Column, Left Column, Left Column
  &lt;/div&gt;
  &lt;div id="middleColumn"&gt;
    Middle Column, Middle Column, Middle Column,
    Middle Column, Middle Column, Middle Column,
    Middle Column, Middle Column, Middle Column
  &lt;/div&gt;
&lt;/div&gt; 
</pre>
<p>The page above contains four DIV elements: a container DIV which contains a leftColumn, middleColumn, and rightColumn DIV. The leftColumn DIV element is floated to the left and the rightColumn DIV element is floated to the right. Notice that the rightColumn DIV appears in the page before the middleColumn DIV – this unintuitive ordering is necessary to get the floats to work correctly (see <a href="http://stackoverflow.com/questions/533607/css-three-column-layout-problem">http://stackoverflow.com/questions/533607/css-three-column-layout-problem</a>). </p>
<p>The page above (almost) works with the most recent versions of most browsers. For example, you get the correct three-column layout in both Firefox and Chrome: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image0041.jpg"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image004" border="0" alt="clip_image004" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image004_thumb1.jpg" width="628" height="263"></a> </p>
<p>And the layout mostly works with Internet Explorer 9 except for the fact that for some strange reason the min-width doesn’t work so when you shrink the width of your browser, you can get the following unwanted layout: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image0061.jpg"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image006" border="0" alt="clip_image006" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image006_thumb1.jpg" width="628" height="191"></a> </p>
<p>Notice how the middle column (the green column) bleeds to the left and right. </p>
<p>People have solved these issues with more complicated CSS. For example, see: </p>
<p><a href="http://matthewjamestaylor.com/blog/holy-grail-no-quirks-mode.htm">http://matthewjamestaylor.com/blog/holy-grail-no-quirks-mode.htm</a> </p>
<p>But, at this point, no one could argue that using CSS is easier or more intuitive than tables. It takes work to get a layout with CSS and we know that we could achieve the same layout more easily using HTML tables. </p>
<h3>Using CSS Grid Layout</h3>
<p>CSS Grid Layout is a new W3C standard which provides you with all of the benefits of using HTML tables for layout without the disadvantage of using an HTML TABLE element. In other words, CSS Grid Layout enables you to perform table layouts using pure Cascading Style Sheets. The CSS Grid Layout standard is still in a “Working Draft” state (it is not finalized) and it is located here: </p>
<p><a href="http://www.w3.org/TR/css3-grid-layout/">http://www.w3.org/TR/css3-grid-layout/</a> </p>
<p>The CSS Grid Layout standard is only supported by Internet Explorer 10 and there are no signs that any browser other than Internet Explorer will support this standard in the near future. This means that it is only practical to take advantage of CSS Grid Layout when building Metro style applications with JavaScript. </p>
<p>Here’s how you can create a standard three-column layout using a CSS Grid Layout:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;

&lt;style type="text/css"&gt;

html, body, #container {
  height: 100%;
  padding: 0px;
  margin: 0px;
}

#container {
  display: -ms-grid;
  -ms-grid-columns: 300px auto 300px;
  -ms-grid-rows: 100%;
}

#leftColumn {
  -ms-grid-column: 1;
  background-color:red;
}

#middleColumn {
  -ms-grid-column: 2;
  background-color:green;
}

#rightColumn {
  -ms-grid-column: 3;
  background-color:blue;
}
&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;div id="container"&gt;
  &lt;div id="leftColumn"&gt;
    Left Column, Left Column, Left Column,
    Left Column, Left Column, Left Column,
    Left Column, Left Column, Left Column
  &lt;/div&gt;
  &lt;div id="middleColumn"&gt;
    Middle Column, Middle Column, Middle Column,
    Middle Column, Middle Column, Middle Column,
    Middle Column, Middle Column, Middle Column
  &lt;/div&gt;
  &lt;div id="rightColumn"&gt;
    Right Column, Right Column, Right Column,
    Right Column, Right Column, Right Column,
    Right Column, Right Column, Right Column
  &lt;/div&gt;
&lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>When the page above is rendered in Internet Explorer 10, you get a standard three-column layout: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image008.jpg"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image008" border="0" alt="clip_image008" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image008_thumb.jpg" width="628" height="339"></a> </p>
<p>The page above contains four DIV elements: a container DIV which contains a leftColumn DIV, middleColumn DIV, and rightColumn DIV. </p>
<p>The container DIV is set to Grid display mode with the following CSS rule:
<pre class="brush: xml;">#container {
  display: -ms-grid;
  -ms-grid-columns: 300px auto 300px;
  -ms-grid-rows: 100%;
}
</pre>
<p>The display property is set to the value “-ms-grid”. This property causes the container DIV to lay out its child elements in a grid. </p>
<p>(Notice that you use “-ms-grid” instead of “grid”. The “-ms-“ prefix is used because the CSS Grid Layout standard is still preliminary. This implementation only works with IE10 and it might change before the final release.) </p>
<p>The grid columns and rows are defined with the “-ms-grid-columns” and “-ms-grid-rows” properties. The style rule above creates a grid with three columns and one row. The left and right columns are fixed sized at 300 pixels. The middle column sizes automatically depending on the remaining space available. </p>
<p>The leftColumn, middleColumn, and rightColumn DIVs are positioned within the container grid element with the following CSS rules:
<pre class="brush: xml;">#leftColumn {
  -ms-grid-column: 1;
  background-color:red;
}

#middleColumn {
  -ms-grid-column: 2;
  background-color:green;
}

#rightColumn {
  -ms-grid-column: 3;
  background-color:blue;
} 
</pre>
<p>The “-ms-grid-column” property is used to specify the column associated with the element selected by the style sheet selector. The leftColumn DIV is positioned in the first grid column, the middleColumn DIV is positioned in the second grid column, and the rightColumn DIV is positioned in the third grid column.</p>
<p>I find using CSS Grid Layout to be just as intuitive as using an HTML table for layout. You define your columns and rows and then you position different elements within these columns and rows. Very straightforward. </p>
<h3>Creating Multiple Columns and Rows</h3>
<p>In the previous section, we created a super simple three-column layout. This layout contained only a single row. In this section, let’s create a slightly more complicated layout which contains more than one row: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image010.jpg"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image010" border="0" alt="clip_image010" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image010_thumb.jpg" width="628" height="382"></a> </p>
<p>The following page contains a header row, a content row, and a footer row. The content row contains three columns:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;

&lt;style type="text/css"&gt;

html, body, #container {
  height: 100%;
  padding: 0px;
  margin: 0px;
}

#container {
  display: -ms-grid;
  -ms-grid-columns: 300px auto 300px;
  -ms-grid-rows: 100px 1fr 100px;
}

#header {
  -ms-grid-column: 1;
  -ms-grid-column-span: 3;
  -ms-grid-row: 1;
  background-color: yellow;
}

#leftColumn {
  -ms-grid-column: 1;
  -ms-grid-row: 2;
  background-color:red;
}

#middleColumn {
  -ms-grid-column: 2;
  -ms-grid-row: 2;
  background-color:green;
}

#rightColumn {
  -ms-grid-column: 3;
  -ms-grid-row: 2;
  background-color:blue;
}

#footer {
  -ms-grid-column: 1;
  -ms-grid-column-span: 3;
  -ms-grid-row: 3;
  background-color: orange;
}

&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;div id="container"&gt;
  &lt;div id="header"&gt;
    Header, Header, Header
  &lt;/div&gt;

  &lt;div id="leftColumn"&gt;
    Left Column, Left Column, Left Column,
    Left Column, Left Column, Left Column,
    Left Column, Left Column, Left Column
  &lt;/div&gt;
  &lt;div id="middleColumn"&gt;
    Middle Column, Middle Column, Middle Column,
    Middle Column, Middle Column, Middle Column,
    Middle Column, Middle Column, Middle Column
  &lt;/div&gt;
  &lt;div id="rightColumn"&gt;
    Right Column, Right Column, Right Column,
    Right Column, Right Column, Right Column,
    Right Column, Right Column, Right Column
  &lt;/div&gt;
  &lt;div id="footer"&gt;
    Footer, Footer, Footer
  &lt;/div&gt;
&lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>In the page above, the grid layout is created with the following rule which creates a grid with three rows and three columns:
<pre class="brush: xml;">#container {
  display: -ms-grid;
  -ms-grid-columns: 300px auto 300px;
  -ms-grid-rows: 100px 1fr 100px;
}
</pre>
<p>The header is created with the following rule:
<pre class="brush: xml;">#header {
  -ms-grid-column: 1;
  -ms-grid-column-span: 3;
  -ms-grid-row: 1;
  background-color: yellow;
}
</pre>
<p>The header is positioned in column 1 and row 1. Furthermore, notice that the “-ms-grid-column-span” property is used to span the header across three columns. </p>
<h3>CSS Grid Layout and Fractional Units</h3>
<p>When you use CSS Grid Layout, you can take advantage of fractional units. Fractional units provide you with an easy way of dividing up remaining space in a page. </p>
<p>Imagine, for example, that you want to create a three-column page layout. You want the size of the first column to be fixed at 200 pixels and you want to divide the remaining space among the remaining three columns. The width of the second column is equal to the combined width of the third and fourth columns. </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image012.jpg"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image012" border="0" alt="clip_image012" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image012_thumb.jpg" width="628" height="287"></a> </p>
<p>The following CSS rule creates four columns with the desired widths:
<pre class="brush: xml;">#container {
  display: -ms-grid;
  -ms-grid-columns: 200px 2fr 1fr 1fr;
  -ms-grid-rows: 1fr;
}  
</pre>
<p>The fr unit represents a fraction. The grid above contains four columns. The second column is two times the size (2fr) of the third (1fr) and fourth (1fr) columns. When you use the fractional unit, the remaining space is divided up using fractional amounts. </p>
<p>Notice that the single row is set to a height of 1fr. The single grid row gobbles up the entire vertical space. </p>
<p>Here’s the entire HTML page:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;

&lt;style type="text/css"&gt;

html, body, #container {
  height: 100%;
  padding: 0px;
  margin: 0px;
}

#container {
  display: -ms-grid;
  -ms-grid-columns: 200px 2fr 1fr 1fr;
  -ms-grid-rows: 1fr;
}

#firstColumn {
  -ms-grid-column: 1;
  background-color:red;
}

#secondColumn {
  -ms-grid-column: 2;
  background-color:green;
}

#thirdColumn {
  -ms-grid-column: 3;
  background-color:blue;
}

#fourthColumn {
  -ms-grid-column: 4;
  background-color:orange;
}

&lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;div id="container"&gt;
  &lt;div id="firstColumn"&gt;
  First Column, First Column, First Column
  &lt;/div&gt;
  &lt;div id="secondColumn"&gt;
  Second Column, Second Column, Second Column
  &lt;/div&gt;
  &lt;div id="thirdColumn"&gt;
  Third Column, Third Column, Third Column
  &lt;/div&gt;
  &lt;div id="fourthColumn"&gt;
  Fourth Column, Fourth Column, Fourth Column
  &lt;/div&gt;
&lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>&nbsp;<br />
<h3>Summary</h3>
<p>There is more in the CSS 3 Grid Layout standard than discussed in this blog post. My goal was to describe the basics. If you want to learn more than you can read through the entire standard at <a href="http://www.w3.org/TR/css3-grid-layout/">http://www.w3.org/TR/css3-grid-layout/</a> </p>
<p>In this blog post, I described some of the difficulties that you might encounter when attempting to replace HTML tables with Cascading Style Sheets when laying out a web page. I explained how you can take advantage of the CSS 3 Grid Layout standard to avoid these problems when building Metro style applications using JavaScript. CSS 3 Grid Layout provides you with all of the benefits of using HTML tables for laying out a page without requiring you to use HTML table elements.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/StephenWalther?a=UXt3Tc7yYsU:Qtrx-_R3O2c:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/UXt3Tc7yYsU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stephenwalther.com/blog/archive/2012/03/19/metro-introduction-to-css-3-grid-layout.aspx/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://stephenwalther.com/blog/archive/2012/03/19/metro-introduction-to-css-3-grid-layout.aspx</feedburner:origLink></item>
		<item>
		<title>HTML5 Form Validation</title>
		<link>http://feedproxy.google.com/~r/StephenWalther/~3/8RPvFaqnsmg/html5-form-validation.aspx</link>
		<comments>http://stephenwalther.com/blog/archive/2012/03/13/html5-form-validation.aspx#comments</comments>
		<pubDate>Wed, 14 Mar 2012 03:27:59 +0000</pubDate>
		<dc:creator>Stephen.Walther</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://stephenwalther.com/blog/?p=476</guid>
		<description><![CDATA[The latest versions of Google Chrome (16+), Mozilla Firefox (8+), and Internet Explorer (10+) all support HTML5 client-side validation. It is time to take HTML5 validation seriously. The purpose of the blog post is to describe how you can take advantage of HTML5 client-side validation regardless of the type of application that you are building. [...]]]></description>
			<content:encoded><![CDATA[<p>The latest versions of Google Chrome (16+), Mozilla Firefox (8+), and Internet Explorer (10+) all support HTML5 client-side validation. It is time to take HTML5 validation seriously.
<p>The purpose of the blog post is to describe how you can take advantage of HTML5 client-side validation regardless of the type of application that you are building. You learn how to use the HTML5 validation attributes, how to perform custom validation using the JavaScript validation constraint API, and how to simulate HTML5 validation on older browsers by taking advantage of a jQuery plugin. Finally, we discuss the security issues related to using client-side validation.<br />
<h3>Using Client-Side Validation Attributes</h3>
<p>The HTML5 specification discusses several attributes which you can use with INPUT elements to perform client-side validation including the <i>required</i>, <i>pattern, min, max, step, and maxlength</i> attributes.
<p>For example, you use the <i>required</i> attribute to require a user to enter a value for an INPUT element. The following form demonstrates how you can make the firstName and lastName form fields required:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
    &lt;title&gt;Required Demo&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;form&gt;
        &lt;label&gt;
            First Name:
            &lt;input required title="First Name is Required!" /&gt;
        &lt;/label&gt;
        &lt;label&gt;
            Last Name:
            &lt;input required title="Last Name is Required!" /&gt;
        &lt;/label&gt;
        &lt;button&gt;Register&lt;/button&gt;
    &lt;/form&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>If you attempt to submit this form without entering a value for firstName or lastName then you get the validation error message: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image0011.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image001" border="0" alt="clip_image001" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image001_thumb1.png" width="617" height="237"></a> </p>
<p>Notice that the value of the title attribute is used to display the validation error message “First Name is Required!”. The title attribute does not work this way with the current version of Firefox. If you want to display a custom validation error message with Firefox then you need to include an x-moz-errormessage attribute like this:
<pre class="brush: xml;">&lt;input required title="First Name is Required!" 

     x-moz-errormessage="First Name is Required!" /&gt; 
</pre>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image0021.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image002" border="0" alt="clip_image002" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image002_thumb1.png" width="604" height="229"></a> </p>
<p>The <i>pattern</i> attribute enables you to validate the value of an INPUT element against a regular expression. For example, the following form includes a social security number field which includes a <i>pattern</i> attribute:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
    &lt;title&gt;Pattern&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;form&gt;
        &lt;label&gt;
            Social Security Number:
            &lt;input required pattern="^\d{3}-\d{2}-\d{4}$"
                title="###-##-####" /&gt;
        &lt;/label&gt;
        &lt;button&gt;Register&lt;/button&gt;
    &lt;/form&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The regular expression in the form above requires the social security number to match the pattern ###-##-####: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image003.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image003" border="0" alt="clip_image003" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image003_thumb.png" width="604" height="229"></a> </p>
<p>Notice that the input field includes both a <i>pattern</i> and a <i>required</i> validation attribute. If you don’t enter a value then the regular expression is never triggered. You need to include the <i>required</i> attribute to force a user to enter a value and cause the value to be validated against the regular expression. </p>
<h3>Custom Validation</h3>
<p>You can take advantage of the HTML5 constraint validation API to perform custom validation. You can perform any custom validation that you need. The only requirement is that you write a JavaScript function. </p>
<p>For example, when booking a hotel room, you might want to validate that the Arrival Date is in the future instead of the past:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
    &lt;title&gt;Constraint Validation API&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;form&gt;
        &lt;label&gt;
            Arrival Date:
            &lt;input id="arrivalDate" type="date" required /&gt;
        &lt;/label&gt;
        &lt;button&gt;Submit Reservation&lt;/button&gt;
    &lt;/form&gt;

    &lt;script type="text/javascript"&gt;

        var arrivalDate = document.getElementById("arrivalDate");

        arrivalDate.addEventListener("input", function() {
            var value = new Date(arrivalDate.value);
            if (value &lt; new Date()) {
                arrivalDate.setCustomValidity("Arrival date must be after now!");
            } else {
                arrivalDate.setCustomValidity("");
            }

        });

    &lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The form above contains an input field named arrivalDate. Entering a value into the arrivalDate field triggers the input event. </p>
<p>The JavaScript code adds an event listener for the input event and checks whether the date entered is greater than the current date. If validation fails then the validation error message “Arrival date must be after now!” is assigned to the arrivalDate input field by calling the setCustomValidity() method of the validation constraint API. Otherwise, the validation error message is cleared by calling setCustomValidity() with an empty string. </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image004.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image004" border="0" alt="clip_image004" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image004_thumb.png" width="548" height="246"></a> </p>
<h3>HTML5 Validation and Older Browsers</h3>
<p>But what about older browsers? For example, what about Apple Safari and versions of Microsoft Internet Explorer older than Internet Explorer 10? </p>
<p>What the world really needs is a jQuery plugin which provides backwards compatibility for the HTML5 validation attributes. If a browser supports the HTML5 validation attributes then the plugin would do nothing. Otherwise, the plugin would add support for the attributes. </p>
<p>Unfortunately, as far as I know, this plugin does not exist. I have not been able to find any plugin which supports both the <i>required</i> and <i>pattern</i> attributes for older browsers, but does not get in the way of these attributes in the case of newer browsers. </p>
<p>There are several jQuery plugins which provide partial support for the HTML5 validation attributes including: </p>
<p>· jQuery Validation &#8212; <a href="http://docs.jquery.com/Plugins/Validation">http://docs.jquery.com/Plugins/Validation</a> </p>
<p>· html5Form &#8212; <a href="http://www.matiasmancini.com.ar/jquery-plugin-ajax-form-validation-html5.html">http://www.matiasmancini.com.ar/jquery-plugin-ajax-form-validation-html5.html</a> </p>
<p>· h5Validate &#8212; <a href="http://ericleads.com/h5validate/">http://ericleads.com/h5validate/</a> </p>
<p>The jQuery Validation plugin – the most popular JavaScript validation library – supports the HTML5 <i>required</i> attribute, but it does not support the HTML5 <i>pattern</i> attribute. Likewise, the html5Form plugin does not support the <i>pattern</i> attribute. </p>
<p>The h5Validate plugin provides the best support for the HTML5 validation attributes. The following page illustrates how this plugin supports both the <i>required</i> and <i>pattern</i> attributes:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
    &lt;title&gt;h5Validate&lt;/title&gt;
    &lt;style type="text/css"&gt;
        .validationError {
            border: solid 2px red;
        }
        .validationValid {
            border:  solid 2px green;
        }
    &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;form id="customerForm"&gt;
        &lt;label&gt;
            First Name:
            &lt;input id="firstName" required /&gt;
        &lt;/label&gt;
        &lt;label&gt;
            Social Security Number:
            &lt;input id="ssn" required pattern="^\d{3}-\d{2}-\d{4}$"
                title="Expected pattern is ###-##-####" /&gt;
        &lt;/label&gt;
        &lt;input type="submit" /&gt;
    &lt;/form&gt;

    &lt;script type="text/javascript" src="Scripts/jquery-1.4.4.min.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript" src="Scripts/jquery.h5validate.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;

        // Enable h5Validate plugin
        $("#customerForm").h5Validate({
            errorClass: "validationError",
            validClass: "validationValid"
        });

        // Prevent form submission when errors
        $("#customerForm").submit(function (evt) {
            if ($("#customerForm").h5Validate("allValid") === false) {
                evt.preventDefault();
            }
        });

    &lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>When an input field fails validation, the validationError CSS class is applied to the field and the field appears with a red border. When an input field passes validation, the validationValid CSS class is applied to the field and the field appears with a green border. </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image006.jpg"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image006" border="0" alt="clip_image006" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image006_thumb.jpg" width="628" height="167"></a> </p>
<p>From the perspective of HTML5 validation, the h5Validate plugin is the best of the plugins. It adds support for the <i>required</i> and <i>pattern</i> attributes to browsers which do not natively support these attributes such as IE9. However, this plugin does not include everything in my wish list for a perfect HTML5 validation plugin. </p>
<p>Here’s my wish list for the perfect <i>back compat</i> HTML5 validation plugin: </p>
<p>1. The plugin would disable itself when used with a browser which natively supports HTML5 validation attributes. The plugin should not be too greedy – it should not handle validation when a browser could do the work itself. </p>
<p>2. The plugin should simulate the same user interface for displaying validation error messages as the user interface displayed by browsers which natively support HTML5 validation. Chrome, Firefox, and Internet Explorer all display validation errors in a popup. The perfect plugin would also display a popup. </p>
<p>3. Finally, the plugin would add support for the setCustomValidity() method and the other methods of the HTML5 validation constraint API. That way, you could implement custom validation in a standards compatible way and you would know that it worked across all browsers both old and new. </p>
<h3>Security</h3>
<p>It would be irresponsible of me to end this blog post without mentioning the issue of security. It is important to remember that any client-side validation &#8212; including HTML5 validation &#8212; can be bypassed. </p>
<p>You should use client-side validation with the intention to create a better user experience. Client validation is great for providing a user with immediate feedback when the user is in the process of completing a form. However, client-side validation cannot prevent an evil hacker from submitting unexpected form data to your web server. </p>
<p>You should always enforce your validation rules on the server. The only way to ensure that a required field has a value is to verify that the required field has a value on the server. The HTML5 <i>required</i> attribute does not guarantee anything. </p>
<h3>Summary</h3>
<p>The goal of this blog post was to describe the support for validation contained in the HTML5 standard. You learned how to use both the <i>required</i> and the <i>pattern</i> attributes in an HTML5 form. We also discussed how you can implement custom validation by taking advantage of the setCustomValidity() method. </p>
<p>Finally, I discussed the available jQuery plugins for adding support for the HTM5 validation attributes to older browsers. Unfortunately, I am unaware of any jQuery plugin which provides a perfect solution to the problem of backwards compatibility.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/StephenWalther?a=8RPvFaqnsmg:cSImsWpY_DM:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/8RPvFaqnsmg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stephenwalther.com/blog/archive/2012/03/13/html5-form-validation.aspx/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://stephenwalther.com/blog/archive/2012/03/13/html5-form-validation.aspx</feedburner:origLink></item>
		<item>
		<title>Introduction to the ASP.NET Web API</title>
		<link>http://feedproxy.google.com/~r/StephenWalther/~3/KKqqBS-mvWE/introduction-to-the-asp-net-web-api.aspx</link>
		<comments>http://stephenwalther.com/blog/archive/2012/03/05/introduction-to-the-asp-net-web-api.aspx#comments</comments>
		<pubDate>Mon, 05 Mar 2012 23:16:52 +0000</pubDate>
		<dc:creator>Stephen.Walther</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://stephenwalther.com/blog/?p=463</guid>
		<description><![CDATA[I am a huge fan of Ajax. If you want to create a great experience for the users of your website – regardless of whether you are building an ASP.NET MVC or an ASP.NET Web Forms site &#8212; then you need to use Ajax. Otherwise, you are just being cruel to your customers. We use [...]]]></description>
			<content:encoded><![CDATA[<p>I am a huge fan of Ajax. If you want to create a great experience for the users of your website – regardless of whether you are building an ASP.NET MVC or an ASP.NET Web Forms site &#8212; then you need to use Ajax. Otherwise, you are just being cruel to your customers.
<p>We use Ajax extensively in several of the ASP.NET applications that my company, <a href="http://superexpert.com">Superexpert.com</a>, builds. We expose data from the server as JSON and use jQuery to retrieve and update that data from the browser.
<p>One challenge, when building an ASP.NET website, is deciding on which technology to use to expose JSON data from the server. For example, how do you expose a list of products from the server as JSON so you can retrieve the list of products with jQuery? You have a number of options (too many options) including ASMX Web services, WCF Web Services, ASHX Generic Handlers, WCF Data Services, and MVC controller actions.
<p>Fortunately, the world has just been simplified. With the release of ASP.NET 4 Beta, Microsoft has introduced a new technology for exposing JSON from the server named the <i>ASP.NET Web API</i>. You can use the ASP.NET Web API with both ASP.NET MVC and ASP.NET Web Forms applications.
<p>The goal of this blog post is to provide you with a brief overview of the features of the new ASP.NET Web API. You learn how to use the ASP.NET Web API to retrieve, insert, update, and delete database records with jQuery. We also discuss how you can perform form validation when using the Web API and use OData when using the Web API.<br />
<h3>Creating an ASP.NET Web API Controller</h3>
<p>The ASP.NET Web API exposes JSON data through a new type of controller called an API controller. You can add an API controller to an existing ASP.NET MVC 4 project through the standard Add Controller dialog box.
<p>Right-click your Controllers folder and select Add, Controller. In the dialog box, name your controller MovieController and select the <b>Empty API controller</b> template:
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image001.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image001" border="0" alt="clip_image001" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image001_thumb.png" width="608" height="397"></a>
<p>A brand new API controller looks like this:
<pre class="brush: csharp;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;

namespace MyWebAPIApp.Controllers
{
    public class MovieController : ApiController
    {
    }
}
</pre>
<p>An API controller, unlike a standard MVC controller, derives from the base ApiController class instead of the base Controller class. </p>
<h3>Using jQuery to Retrieve, Insert, Update, and Delete Data</h3>
<p>Let’s create an Ajaxified Movie Database application. We’ll retrieve, insert, update, and delete movies using jQuery with the MovieController which we just created. Our Movie model class looks like this:
<pre class="brush: csharp;">namespace MyWebAPIApp.Models
{
    public class Movie
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Director { get; set; }
    }
}
</pre>
<p>Our application will consist of a single HTML page named Movies.html. We’ll place all of our jQuery code in the Movies.html page. </p>
<h4>Getting a Single Record with the ASP.NET Web API</h4>
<p>To support retrieving a single movie from the server, we need to add a Get method to our API controller:
<pre class="brush: csharp;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MyWebAPIApp.Models;

namespace MyWebAPIApp.Controllers
{
    public class MovieController : ApiController
    {

        public Movie GetMovie(int id)
        {
            // Return movie by id
            if (id == 1)
            {
                return new Movie
                {
                    Id = 1,
                    Title = "Star Wars",
                    Director = "Lucas"
                };
            }

            // Otherwise, movie was not found
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }

    }
}
</pre>
<p>In the code above, the GetMovie() method accepts the Id of a movie. If the Id has the value 1 then the method returns the movie Star Wars. Otherwise, the method throws an exception and returns 404 Not Found HTTP status code. </p>
<p>After building your project, you can invoke the MovieController.GetMovie() method by entering the following URL in your web browser address bar: <a href="http://localhost:[port]/api/movie/1">http://localhost:[port]/api/movie/1</a> (You’ll need to enter the correct randomly generated port). </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image002.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image002" border="0" alt="clip_image002" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image002_thumb.png" width="283" height="435"></a> </p>
<p>In the URL api/movie/1, the first “api” segment indicates that this is a Web API route. The “movie” segment indicates that the MovieController should be invoked. You do not specify the name of the action. Instead, the HTTP method used to make the request – GET, POST, PUT, DELETE &#8212; is used to identify the action to invoke. </p>
<p>The ASP.NET Web API uses different routing conventions than normal ASP.NET MVC controllers. When you make an HTTP GET request then any API controller method with a name that starts with “GET” is invoked. So, we could have called our API controller action GetPopcorn() instead of GetMovie() and it would still be invoked by the URL api/movie/1. </p>
<p>The default route for the Web API is defined in the Global.asax file and it looks like this:
<pre class="brush: csharp;">routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);
</pre>
<p>We can invoke our GetMovie() controller action with the jQuery code in the following HTML page:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
    &lt;title&gt;Get Movie&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;div&gt;
        Title: &lt;span id="title"&gt;&lt;/span&gt;
    &lt;/div&gt;
    &lt;div&gt;
        Director: &lt;span id="director"&gt;&lt;/span&gt;
    &lt;/div&gt;

    &lt;script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt; 

        getMovie(1, function (movie) {
            $("#title").html(movie.Title);
            $("#director").html(movie.Director);
        });

        function getMovie(id, callback) {
            $.ajax({
                url: "/api/Movie",
                data: { id: id },
                type: "GET",
                contentType: "application/json;charset=utf-8",
                statusCode: {
                    200: function (movie) {
                        callback(movie);
                    },
                    404: function () {
                        alert("Not Found!");
                    }
                }
            });
        }

    &lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>In the code above, the jQuery $.ajax() method is used to invoke the GetMovie() method. Notice that the Ajax call handles two HTTP response codes. When the GetMove() method successfully returns a movie, the method returns a 200 status code. In that case, the details of the movie are displayed in the HTML page. </p>
<p>Otherwise, if the movie is not found, the GetMovie() method returns a 404 status code. In that case, the page simply displays an alert box indicating that the movie was not found (hopefully, you would implement something more graceful in an actual application). </p>
<p>You can use your browser’s Developer Tools to see what is going on in the background when you open the HTML page (hit F12 in the most recent version of most browsers). For example, you can use the Network tab in Google Chrome to see the Ajax request which invokes the GetMovie() method: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image004.jpg"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image004" border="0" alt="clip_image004" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image004_thumb.jpg" width="628" height="404"></a> </p>
<h4>Getting a Set of Records with the ASP.NET Web API</h4>
<p>Let’s modify our Movie API controller so that it returns a collection of movies. The following Movie controller has a new ListMovies() method which returns a (hard-coded) collection of movies:
<pre class="brush: csharp;">using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MyWebAPIApp.Models;

namespace MyWebAPIApp.Controllers
{
    public class MovieController : ApiController
    {

        public IEnumerable&lt;Movie&gt; ListMovies()
        {
            return new List&lt;Movie&gt; {
                new Movie {Id=1, Title="Star Wars", Director="Lucas"},
                new Movie {Id=1, Title="King Kong", Director="Jackson"},
                new Movie {Id=1, Title="Memento", Director="Nolan"}
            };
        }

    }
}
</pre>
<p>Because we named our action ListMovies(), the default Web API route will never match it. Therefore, we need to add the following custom route to our Global.asax file (at the top of the RegisterRoutes() method):
<pre class="brush: csharp;">routes.MapHttpRoute(
    name: "ActionApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);
</pre>
<p>This route enables us to invoke the ListMovies() method with the URL <a href="http://localhost:15296/api/movie/listmovies">/api/movie/listmovies</a>. </p>
<p>Now that we have exposed our collection of movies from the server, we can retrieve and display the list of movies using jQuery in our HTML page:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
    &lt;title&gt;List Movies&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;div id="movies"&gt;&lt;/div&gt;

    &lt;script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;

        listMovies(function (movies) {
            var strMovies="";
            $.each(movies, function (index, movie) {
                strMovies += "&lt;div&gt;" + movie.Title + "&lt;/div&gt;";
            });
            $("#movies").html(strMovies);

        });

        function listMovies(callback) {
            $.ajax({
                url: "/api/Movie/ListMovies",
                data: {},
                type: "GET",
                contentType: "application/json;charset=utf-8",
            }).then(function(movies){
                callback(movies);
            });
        }

    &lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>&nbsp;
<p>&nbsp;
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image005.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image005" border="0" alt="clip_image005" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image005_thumb.png" width="595" height="679"></a> </p>
<h4>Inserting a Record with the ASP.NET Web API</h4>
<p>Now let’s modify our Movie API controller so it supports creating new records:
<pre class="brush: csharp;">public HttpResponseMessage&lt;Movie&gt; PostMovie(Movie movieToCreate)
{
    // Add movieToCreate to the database and update primary key
    movieToCreate.Id = 23;

    // Build a response that contains the location of the new movie
    var response = new HttpResponseMessage&lt;Movie&gt;(movieToCreate, HttpStatusCode.Created);
    var relativePath = "/api/movie/" + movieToCreate.Id;
    response.Headers.Location = new Uri(Request.RequestUri, relativePath);
    return response;
}
</pre>
<p>The PostMovie() method in the code above accepts a movieToCreate parameter. We don’t actually store the new movie anywhere. In real life, you will want to call a service method to store the new movie in a database. </p>
<p>When you create a new resource, such as a new movie, you should return the location of the new resource. In the code above, the URL where the new movie can be retrieved is assigned to the Location header returned in the PostMovie() response. </p>
<p>Because the name of our method starts with “Post&#8221;, we don’t need to create a custom route. The PostMovie() method can be invoked with the URL /Movie/PostMovie – just as long as the method is invoked within the context of a HTTP POST request. </p>
<p>The following HTML page invokes the PostMovie() method.
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
    &lt;title&gt;Create Movie&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;

        var movieToCreate = {
            title: "The Hobbit",
            director: "Jackson"
        };
        createMovie(movieToCreate, function (newMovie) {
            alert("New movie created with an Id of " + newMovie.Id);
        });

        function createMovie(movieToCreate, callback) {
            $.ajax({
                url: "/api/Movie",
                data: JSON.stringify( movieToCreate ),
                type: "POST",
                contentType: "application/json;charset=utf-8",
                statusCode: {
                    201: function (newMovie) {
                        callback(newMovie);
                    }
                }
            });
        }

    &lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>This page creates a new movie (the Hobbit) by calling the createMovie() method. The page simply displays the Id of the new movie: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image006.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image006" border="0" alt="clip_image006" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image006_thumb.png" width="595" height="679"></a> </p>
<p>The HTTP Post operation is performed with the following call to the jQuery $.ajax() method:
<pre class="brush: js;">$.ajax({
    url: "/api/Movie",
    data: JSON.stringify( movieToCreate ),
    type: "POST",
    contentType: "application/json;charset=utf-8",
    statusCode: {
        201: function (newMovie) {
            callback(newMovie);
        }
    }
});
</pre>
<p>Notice that the type of Ajax request is a POST request. This is required to match the PostMovie() method. </p>
<p>Notice, furthermore, that the new movie is converted into JSON using JSON.stringify(). The JSON.stringify() method takes a JavaScript object and converts it into a JSON string. </p>
<p>Finally, notice that success is represented with a 201 status code. The HttpStatusCode.Created value returned from the PostMovie() method returns a 201 status code. </p>
<h4>Updating a Record with the ASP.NET Web API</h4>
<p>Here’s how we can modify the Movie API controller to support updating an existing record. In this case, we need to create a PUT method to handle an HTTP PUT request:
<pre class="brush: csharp;">public void PutMovie(Movie movieToUpdate)
{
    if (movieToUpdate.Id == 1) {
        // Update the movie in the database
        return;
    }

    // If you can't find the movie to update
    throw new HttpResponseException(HttpStatusCode.NotFound);
}
</pre>
<p>Unlike our PostMovie() method, the PutMovie() method does not return a result. The action either updates the database or, if the movie cannot be found, returns an HTTP Status code of 404. </p>
<p>The following HTML page illustrates how you can invoke the PutMovie() method:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
    &lt;title&gt;Put Movie&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;

        var movieToUpdate = {
            id: 1,
            title: "The Hobbit",
            director: "Jackson"
        };
        updateMovie(movieToUpdate, function () {
            alert("Movie updated!");
        });

        function updateMovie(movieToUpdate, callback) {
            $.ajax({
                url: "/api/Movie",
                data: JSON.stringify(movieToUpdate),
                type: "PUT",
                contentType: "application/json;charset=utf-8",
                statusCode: {
                    200: function () {
                        callback();
                    },
                    404: function () {
                        alert("Movie not found!");
                    }
                }
            });
        }

    &lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<h4>Deleting a Record with the ASP.NET Web API</h4>
<p>Here’s the code for deleting a movie:
<pre class="brush: csharp;">public HttpResponseMessage DeleteMovie(int id)
{
    // Delete the movie from the database

    // Return status code
    return new HttpResponseMessage(HttpStatusCode.NoContent);
}
</pre>
<p>This method simply deletes the movie (well, not really, but pretend that it does) and returns a No Content status code (204). </p>
<p>The following page illustrates how you can invoke the DeleteMovie() action:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
    &lt;title&gt;Delete Movie&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;

        deleteMovie(1, function () {
            alert("Movie deleted!");
        });

        function deleteMovie(id, callback) {
            $.ajax({
                url: "/api/Movie",
                data: JSON.stringify({id:id}),
                type: "DELETE",
                contentType: "application/json;charset=utf-8",
                statusCode: {
                    204: function () {
                        callback();
                    }
                }
            });
        }

    &lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<h3>Performing Validation</h3>
<p>How do you perform form validation when using the ASP.NET Web API? Because validation in ASP.NET MVC is driven by the Default Model Binder, and because the Web API uses the Default Model Binder, you get validation for free. </p>
<p>Let’s modify our Movie class so it includes some of the standard validation attributes:
<pre class="brush: csharp;">using System.ComponentModel.DataAnnotations;
namespace MyWebAPIApp.Models
{
    public class Movie
    {
        public int Id { get; set; }

        [Required(ErrorMessage="Title is required!")]
        [StringLength(5, ErrorMessage="Title cannot be more than 5 characters!")]
        public string Title { get; set; }

        [Required(ErrorMessage="Director is required!")]
        public string Director { get; set; }
    }
}
</pre>
<p>In the code above, the Required validation attribute is used to make both the Title and Director properties required. The StringLength attribute is used to require the length of the movie title to be no more than 5 characters. </p>
<p>Now let’s modify our PostMovie() action to validate a movie before adding the movie to the database:
<pre class="brush: csharp;">public HttpResponseMessage PostMovie(Movie movieToCreate)
{
    // Validate movie
    if (!ModelState.IsValid)
    {
        var errors = new JsonArray();
        foreach (var prop in ModelState.Values)
        {
            if (prop.Errors.Any())
            {
                errors.Add(prop.Errors.First().ErrorMessage);
            }
        }
        return new HttpResponseMessage&lt;JsonValue&gt;(errors, HttpStatusCode.BadRequest);
    }

    // Add movieToCreate to the database and update primary key
    movieToCreate.Id = 23;

    // Build a response that contains the location of the new movie
    var response = new HttpResponseMessage&lt;Movie&gt;(movieToCreate, HttpStatusCode.Created);
    var relativePath = "/api/movie/" + movieToCreate.Id;
    response.Headers.Location = new Uri(Request.RequestUri, relativePath);
    return response;
}
</pre>
<p>If ModelState.IsValid has the value false then the errors in model state are copied to a new JSON array. Each property – such as the Title and Director property &#8212; can have multiple errors. In the code above, only the first error message is copied over. The JSON array is returned with a Bad Request status code (400 status code). </p>
<p>The following HTML page illustrates how you can invoke our modified PostMovie() action and display any error messages:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
    &lt;title&gt;Create Movie&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;script type="text/javascript" src="Scripts/jquery-1.6.2.min.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript"&gt;

        var movieToCreate = {
            title: "The Hobbit",
            director: ""
        };

        createMovie(movieToCreate,
            function (newMovie) {
                alert("New movie created with an Id of " + newMovie.Id);
            },
            function (errors) {
                var strErrors = "";
                $.each(errors, function(index, err) {
                    strErrors += "*" + err + "\n";
                });
                alert(strErrors);
            }
        );

        function createMovie(movieToCreate, success, fail) {
            $.ajax({
                url: "/api/Movie",
                data: JSON.stringify(movieToCreate),
                type: "POST",
                contentType: "application/json;charset=utf-8",
                statusCode: {
                    201: function (newMovie) {
                        success(newMovie);
                    },
                    400: function (xhr) {
                        var errors = JSON.parse(xhr.responseText);
                        fail(errors);
                    }
                }
            });
        }

    &lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The createMovie() function performs an Ajax request and handles either a 201 or a 400 status code from the response. If a 201 status code is returned then there were no validation errors and the new movie was created. </p>
<p>If, on the other hand, a 400 status code is returned then there was a validation error. The validation errors are retrieved from the XmlHttpRequest responseText property. The error messages are displayed in an alert: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image007.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image007" border="0" alt="clip_image007" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image007_thumb.png" width="356" height="133"></a> </p>
<p>(Please don’t use JavaScript alert dialogs to display validation errors, I just did it this way out of pure laziness) </p>
<p>This validation code in our PostMovie() method is pretty generic. There is nothing specific about this code to the PostMovie() method. In the following video, Jon Galloway demonstrates how to create a global Validation filter which can be used with any API controller action: </p>
<p><a href="http://www.asp.net/web-api/overview/web-api-routing-and-actions/video-custom-validation">http://www.asp.net/web-api/overview/web-api-routing-and-actions/video-custom-validation</a> </p>
<p>His validation filter looks like this:
<pre class="brush: csharp;">using System.Json;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace MyWebAPIApp.Filters
{
    public class ValidationActionFilter:ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var modelState = actionContext.ModelState;
            if (!modelState.IsValid)
            {
                dynamic errors = new JsonObject();
                foreach (var key in modelState.Keys)
                {
                    var state = modelState[key];
                    if (state.Errors.Any())
                    {
                        errors[key] = state.Errors.First().ErrorMessage;
                    }
                }
                actionContext.Response = new HttpResponseMessage&lt;JsonValue&gt;(errors, HttpStatusCode.BadRequest);
            }
        }
    }
}
</pre>
<p>And you can register the validation filter in the Application_Start() method in the Global.asax file like this:
<pre class="brush: csharp;">GlobalConfiguration.Configuration.Filters.Add(new ValidationActionFilter());
</pre>
<p>After you register the Validation filter, validation error messages are returned from any API controller action method automatically when validation fails. You don’t need to add any special logic to any of your API controller actions to take advantage of the filter. </p>
<h3>Querying using OData </h3>
<p>The OData protocol is an open protocol created by Microsoft which enables you to perform queries over the web. The official website for OData is located here: </p>
<p><a href="http://odata.org">http://odata.org</a> </p>
<p>For example, here are some of the query options which you can use with OData: </p>
<p>· $orderby – Enables you to retrieve results in a certain order. </p>
<p>· $top – Enables you to retrieve a certain number of results. </p>
<p>· $skip – Enables you to skip over a certain number of results (use with $top for paging). </p>
<p>· $filter – Enables you to filter the results returned. </p>
<p>The ASP.NET Web API supports a subset of the OData protocol. You can use all of the query options listed above when interacting with an API controller. The only requirement is that the API controller action returns its data as IQueryable. </p>
<p>For example, the following Movie controller has an action named GetMovies() which returns an IQueryable of movies:
<pre class="brush: csharp;">public IQueryable&lt;Movie&gt; GetMovies()
{
    return new List&lt;Movie&gt; {
        new Movie {Id=1, Title="Star Wars", Director="Lucas"},
        new Movie {Id=2, Title="King Kong", Director="Jackson"},
        new Movie {Id=3, Title="Willow", Director="Lucas"},
        new Movie {Id=4, Title="Shrek", Director="Smith"},
        new Movie {Id=5, Title="Memento", Director="Nolan"}
    }.AsQueryable();
}
</pre>
<p>If you enter the following URL in your browser: </p>
<p><a href="http://localhost:15296/api/movie?$top=2&amp;$orderby=Title">/api/movie?$top=2&amp;$orderby=Title</a> </p>
<p>Then you will limit the movies returned to the top 2 in order of the movie Title. You will get the following results: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image008.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="clip_image008" border="0" alt="clip_image008" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/clip_image008_thumb.png" width="542" height="386"></a> </p>
<p>By using the $top option in combination with the $skip option, you can enable client-side paging. For example, you can use $top and $skip to page through thousands of products, 10 products at a time.</p>
<p>The $filter query option is very powerful. You can use this option to filter the results from a query. Here are some examples: </p>
<p><b>Return every movie directed by Lucas:</b> </p>
<p>/api/movie?$filter=Director eq &#8216;Lucas&#8217; </p>
<p><b>Return every movie which has a title which starts with ‘S’:</b> </p>
<p>/api/movie?$filter=startswith(Title,&#8217;S') </p>
<p><b>Return every movie which has an Id greater than 2:</b> </p>
<p>/api/movie?$filter=Id gt 2 </p>
<p>The complete documentation for the $filter option is located here: </p>
<p><a href="http://www.odata.org/developers/protocols/uri-conventions#FilterSystemQueryOption">http://www.odata.org/developers/protocols/uri-conventions#FilterSystemQueryOption</a> </p>
<h3>Summary</h3>
<p>The goal of this blog entry was to provide you with an overview of the new ASP.NET Web API introduced with the Beta release of ASP.NET 4. In this post, I discussed how you can retrieve, insert, update, and delete data by using jQuery with the Web API. </p>
<p>I also discussed how you can use the standard validation attributes with the Web API. You learned how to return validation error messages to the client and display the error messages using jQuery. </p>
<p>Finally, we briefly discussed how the ASP.NET Web API supports the OData protocol. For example, you learned how to filter records returned from an API controller action by using the $filter query option. </p>
<p>I’m excited about the new Web API. This is a feature which I expect to use with almost every ASP.NET application which I build in the future.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/StephenWalther?a=KKqqBS-mvWE:rl3lORFi_80:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/KKqqBS-mvWE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stephenwalther.com/blog/archive/2012/03/05/introduction-to-the-asp-net-web-api.aspx/feed</wfw:commentRss>
		<slash:comments>25</slash:comments>
		<feedburner:origLink>http://stephenwalther.com/blog/archive/2012/03/05/introduction-to-the-asp-net-web-api.aspx</feedburner:origLink></item>
		<item>
		<title>Metro: Understanding CSS Media Queries</title>
		<link>http://feedproxy.google.com/~r/StephenWalther/~3/BWU56gyIubM/metro-understanding-css-media-queries.aspx</link>
		<comments>http://stephenwalther.com/blog/archive/2012/02/29/metro-understanding-css-media-queries.aspx#comments</comments>
		<pubDate>Wed, 29 Feb 2012 08:27:08 +0000</pubDate>
		<dc:creator>Stephen.Walther</dc:creator>
				<category><![CDATA[Metro]]></category>

		<guid isPermaLink="false">http://stephenwalther.com/blog/?p=385</guid>
		<description><![CDATA[If you are building a Metro style application then your application needs to look great when used on a wide variety of devices. Your application needs to work on tiny little phones, slates, desktop monitors, and the super high resolution displays of the future. Your application also must support portable devices used with different orientations. [...]]]></description>
			<content:encoded><![CDATA[<p>If you are building a Metro style application then your application needs to look great when used on a wide variety of devices. Your application needs to work on tiny little phones, slates, desktop monitors, and the super high resolution displays of the future.
<p>Your application also must support portable devices used with different orientations. If someone tilts their phone from portrait to landscape mode then your application must still be usable.
<p>Finally, your Metro style application must look great in different states. For example, your Metro application can be in a “snapped state” when it is shrunk so it can share screen real estate with another application.
<p>In this blog post, you learn how to use Cascading Style Sheet media queries to support different devices, different device orientations, and different application states. First, you are provided with an overview of the W3C Media Query recommendation and you learn how to detect standard media features.
<p>Next, you learn about the Microsoft extensions to media queries which are supported in Metro style applications. For example, you learn how to use the –ms-view-state feature to detect whether an application is in a “snapped state” or “fill state”.
<p>Finally, you learn how to programmatically detect the features of a device and the state of an application. You learn how to use the msMatchMedia() method to execute a media query with JavaScript.<br />
<h3>Using CSS Media Queries</h3>
<p>Media queries enable you to apply different styles depending on the features of a device. Media queries are not only supported by Metro style applications, most modern web browsers now support media queries including Google Chrome 4+, Mozilla Firefox 3.5+, Apple Safari 4+, and Microsoft Internet Explorer 9+.<br />
<h4>Loading Different Style Sheets with Media Queries </h4>
<p>Imagine, for example, that you want to display different content depending on the horizontal resolution of a device. In that case, you can load different style sheets optimized for different sized devices.
<p>Consider the following HTML page:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
    &lt;title&gt;U.S. Robotics and Mechanical Men&lt;/title&gt;

    &lt;link href="main.css" rel="stylesheet" type="text/css" /&gt;

    &lt;!-- Less than 1100px --&gt;
    &lt;link href="medium.css" rel="stylesheet" type="text/css"
        media="(max-width:1100px)" /&gt;

    &lt;!-- Less than 800px --&gt;
    &lt;link href="small.css" rel="stylesheet" type="text/css"
         media="(max-width:800px)" /&gt;

&lt;/head&gt;
&lt;body&gt;
    &lt;div id="header"&gt;
        &lt;h1&gt;U.S. Robotics and Mechanical Men&lt;/h1&gt;
    &lt;/div&gt;

    &lt;!-- Advertisement Column --&gt;
    &lt;div id="leftColumn"&gt;
        &lt;img src="advertisement1.gif" alt="advertisement" /&gt;
        &lt;img src="advertisement2.jpg" alt="advertisement" /&gt;
    &lt;/div&gt;

    &lt;!-- Product Search Form --&gt;
    &lt;div id="mainContentColumn"&gt;
        &lt;label&gt;Search Products&lt;/label&gt;
        &lt;input id="search" /&gt;&lt;button&gt;Search&lt;/button&gt;
    &lt;/div&gt;

    &lt;!-- Deal of the Day Column --&gt;
    &lt;div id="rightColumn"&gt;
        &lt;h1&gt;Deal of the Day!&lt;/h1&gt;
        &lt;p&gt;
            Buy two cameras and get a third camera for free! Offer
            is good for today only.
        &lt;/p&gt;
    &lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The HTML page above contains three columns: a leftColumn, mainContentColumn, and rightColumn. When the page is displayed on a low resolution device, such as a phone, only the mainContentColumn appears: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image0013.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="clip_image001" border="0" alt="clip_image001" src="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image001_thumb3.png" width="229" height="340"></a> </p>
<p>When the page is displayed in a medium resolution device, such as a slate, both the leftColumn and the mainContentColumns are displayed: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image0024.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="clip_image002" border="0" alt="clip_image002" src="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image002_thumb4.png" width="416" height="340"></a> </p>
<p>Finally, when the page is displayed in a high-resolution device, such as a computer monitor, all three columns are displayed: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image0031.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="clip_image003" border="0" alt="clip_image003" src="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image003_thumb1.png" width="561" height="340"></a> </p>
<p>Different content is displayed with the help of media queries. The page above contains three style sheet links. Two of the style links include a media attribute:
<pre class="brush: xml;">&lt;link href="main.css" rel="stylesheet" type="text/css" /&gt;

&lt;!-- Less than 1100px --&gt;
&lt;link href="medium.css" rel="stylesheet" type="text/css"
    media="(max-width:1100px)" /&gt;

&lt;!-- Less than 800px --&gt;
&lt;link href="small.css" rel="stylesheet" type="text/css"
     media="(max-width:800px)" /&gt;
</pre>
<p>The main.css style sheet contains default styles for the elements in the page. </p>
<p>The medium.css style sheet is applied when the page width is less than 1100px. This style sheet hides the rightColumn and changes the page background color to lime:
<pre class="brush: css;">html { 

   background-color: lime; 

} 

#rightColumn { 

   display:none; 

} 
</pre>
<p>Finally, the small.css style sheet is loaded when the page width is less than 800px. This style sheet hides the leftColumn and changes the page background color to red:
<pre class="brush: css;">html { 

   background-color: red; 

} 

#leftColumn { 

   display:none; 

} 
</pre>
<p>The different style sheets are applied as you stretch and contract your browser window. You don’t need to refresh the page after changing the size of the page for a media query to be applied: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image004.gif"><img style="display: inline" title="clip_image004" alt="clip_image004" src="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image004_thumb.gif" width="800" height="600"></a> </p>
<h3>Using the @media Rule </h3>
<p>You don’t need to divide your styles into separate files to take advantage of media queries. You can group styles by using the @media rule. </p>
<p>For example, the following HTML page contains one set of styles which are applied when a device’s orientation is portrait and another set of styles when a device’s orientation is landscape:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset="utf-8" /&gt;
    &lt;title&gt;Application1&lt;/title&gt;

    &lt;style type="text/css"&gt;

        html {
            font-family:'Segoe UI Semilight';
            font-size: xx-large;
        }

        @media screen and (orientation:landscape) {
            html {
                background-color: lime;
            }

            p.content {
                width: 50%;
                margin: auto;
            }
        }

        @media screen and (orientation:portrait) {
            html {
                background-color: red;
            }

            p.content {
                width: 90%;
                margin: auto;
            }
        }

    &lt;/style&gt;

&lt;/head&gt;
&lt;body&gt;

&lt;p class="content"&gt;
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
    Maecenas porttitor congue massa. Fusce posuere, magna sed
    pulvinar ultricies, purus lectus malesuada libero, sit
    amet commodo magna eros quis urna.
&lt;/p&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>When a device has a landscape orientation then the background color is set to the color lime and the text only takes up 50% of the available horizontal space: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image006.jpg"><img style="background-image: none; border-right-width: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="clip_image006" border="0" alt="clip_image006" src="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image006_thumb.jpg" width="244" height="169"></a> </p>
<p>When the device has a portrait orientation then the background color is red and the text takes up 90% of the available horizontal space: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image007.png"><img style="background-image: none; border-right-width: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="clip_image007" border="0" alt="clip_image007" src="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image007_thumb.png" width="191" height="244"></a> </p>
<h3>Using Standard CSS Media Features</h3>
<p>The official list of standard media features is contained in the W3C CSS Media Query recommendation located here: </p>
<p><a href="http://www.w3.org/TR/css3-mediaqueries/">http://www.w3.org/TR/css3-mediaqueries/</a> </p>
<p>Here is the official list of the 13 media features described in the standard: </p>
<p>· width – The current width of the viewport </p>
<p>· height – The current height of the viewport </p>
<p>· device-width – The width of the device </p>
<p>· device-height – The height of the device </p>
<p>· orientation – The value portrait or landscape </p>
<p>· aspect-ratio – The ratio of width to height </p>
<p>· device-aspect-ratio – The ratio of device width to device height </p>
<p>· color – The number of bits per color supported by the device </p>
<p>· color-index – The number of colors in the color lookup table of the device </p>
<p>· monochrome – The number of bits in the monochrome frame buffer </p>
<p>· resolution – The density of the pixels supported by the device </p>
<p>· scan – The values progressive or interlace (used for TVs) </p>
<p>· grid – The values 0 or 1 which indicate whether the device supports a grid or a bitmap </p>
<p>Many of the media features in the list above support the min- and max- prefix. For example, you can test for the min-width using a query like this:
<pre class="brush: css;">(min-width:800px)
</pre>
<p>You can use the logical and operator with media queries when you need to check whether a device supports more than one feature. For example, the following query returns true only when the width of the device is between 800 and 1,200 pixels:
<pre class="brush: css;">(min-width:800px) and (max-width:1200px)
</pre>
<p>Finally, you can use the different media types – all, braille, embossed, handheld, print, projection, screen, speech, tty, tv &#8212; with a media query. For example, the following media query only applies to a page when a page is being printed in color:
<pre class="brush: css;">print and (color)
</pre>
<p>If you don’t specify a media type then media type <i>all</i> is assumed. </p>
<h3>Using Metro Style Media Features</h3>
<p>Microsoft has extended the standard list of media features which you can include in a media query with two custom media features: </p>
<p>· -ms-high-contrast – The values any, black-white, white-black </p>
<p>· -ms-view-state – The values full-screen, fill, snapped, device-portrait </p>
<p>You can take advantage of the –ms-high-contrast media feature to make your web application more accessible to individuals with disabilities. In high contrast mode, you should make your application easier to use for individuals with vision disabilities. </p>
<p>The –ms-view-state media feature enables you to detect the state of an application. For example, when an application is snapped, the application only occupies part of the available screen real estate. The snapped application appears on the left or right side of the screen and the rest of the screen real estate is dominated by the fill application (Metro style applications can only be snapped on devices with a horizontal resolution of greater than 1,366 pixels). </p>
<p>Here is a page which contains style rules for an application in both a snap and fill application state:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset="utf-8" /&gt;
    &lt;title&gt;MyWinWebApp&lt;/title&gt;

    &lt;style type="text/css"&gt;

        html {
            font-family:'Segoe UI Semilight';
            font-size: xx-large;
        }

        @media screen and (-ms-view-state:snapped) {
            html {
                background-color: lime;
            }
        }

        @media screen and (-ms-view-state:fill) {
            html {
                background-color: red;
            }
        }

    &lt;/style&gt;

&lt;/head&gt;
&lt;body&gt;

&lt;p class="content"&gt;
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
    Maecenas porttitor congue massa. Fusce posuere, magna sed
    pulvinar ultricies, purus lectus malesuada libero, sit
    amet commodo magna eros quis urna.
&lt;/p&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>When the application is snapped, the application appears with a lime background color: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image0091.jpg"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="clip_image009" border="0" alt="clip_image009" src="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image009_thumb1.jpg" width="628" height="397"></a> </p>
<p>When the application state is fill then the background color changes to red: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image0111.jpg"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="clip_image011" border="0" alt="clip_image011" src="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image011_thumb1.jpg" width="628" height="397"></a> </p>
<p>When the application takes up the entire screen real estate – it is not in snapped or fill state – then no special style rules apply and the application appears with a white background color. </p>
<h3>Querying Media Features with JavaScript</h3>
<p>You can perform media queries using JavaScript by taking advantage of the window.msMatchMedia() method. This method returns a MSMediaQueryList which has a matches method that represents success or failure. </p>
<p>For example, the following code checks whether the current device is in portrait mode:
<pre class="brush: js;">if (window.msMatchMedia("(orientation:portrait)").matches) {
    console.log("portrait");
} else {
    console.log("landscape");
}            
</pre>
<p>If the matches property returns true, then the device is in portrait mode and the message “portrait” is written to the Visual Studio JavaScript Console window. Otherwise, the message “landscape” is written to the JavaScript Console window. </p>
<p>You can create an event listener which triggers code whenever the results of a media query changes. For example, the following code writes a message to the JavaScript Console whenever the current device is switched into or out of Portrait mode:
<pre class="brush: js;">window.msMatchMedia("(orientation:portrait)").addListener(function (mql) {
    if (mql.matches) {
        console.log("Switched to portrait");
    }
});
</pre>
<p>Be aware that the event listener is triggered whenever the result of the media query changes. So the event listener is triggered both when you switch from landscape to portrait and when you switch from portrait to landscape. For this reason, you need to verify that the matches property has the value true before writing the message. </p>
<h3>Summary</h3>
<p>The goal of this blog entry was to explain how CSS media queries work in the context of a Metro style application written with JavaScript. First, you were provided with an overview of the W3C CSS Media Query recommendation. You learned about the standard media features which you can query such as width and orientation. </p>
<p>Next, we focused on the Microsoft extensions to media queries. You learned how to use –ms-view-state to detect whether a Metro style application is in “snapped” or “fill” state. You also learned how to use the msMatchMedia() method to perform a media query from JavaScript.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/StephenWalther?a=BWU56gyIubM:8w3zyTn09Lg:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/BWU56gyIubM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stephenwalther.com/blog/archive/2012/02/29/metro-understanding-css-media-queries.aspx/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://stephenwalther.com/blog/archive/2012/02/29/metro-understanding-css-media-queries.aspx</feedburner:origLink></item>
		<item>
		<title>Metro: Using Templates</title>
		<link>http://feedproxy.google.com/~r/StephenWalther/~3/21i8HQfrIIY/metro-using-templates.aspx</link>
		<comments>http://stephenwalther.com/blog/archive/2012/02/27/metro-using-templates.aspx#comments</comments>
		<pubDate>Mon, 27 Feb 2012 22:34:44 +0000</pubDate>
		<dc:creator>Stephen.Walther</dc:creator>
				<category><![CDATA[Metro]]></category>

		<guid isPermaLink="false">http://stephenwalther.com/blog/?p=365</guid>
		<description><![CDATA[The goal of this blog post is to describe how templates work in the WinJS library. In particular, you learn how to use a template to display both a single item and an array of items. You also learn how to load a template from an external file. Why use Templates? Imagine that you want [...]]]></description>
			<content:encoded><![CDATA[<p>The goal of this blog post is to describe how templates work in the WinJS library. In particular, you learn how to use a template to display both a single item and an array of items. You also learn how to load a template from an external file.<br />
<h3>Why use Templates?</h3>
<p>Imagine that you want to display a list of products in a page. The following code is bad:
<pre class="brush: js;">var products = [
    { name: "Tesla", price: 80000 },
    { name: "VW Rabbit", price: 200 },
    { name: "BMW", price: 60000 }
];

var productsHTML = "";
for (var i = 0; i &lt; products.length; i++) {
    productsHTML += "&lt;h1&gt;Product Details&lt;/h1&gt;"
        + "&lt;div&gt;Product Name: " + products[i].name + "&lt;/div&gt;"
        + "&lt;div&gt;Product Price: " + products[i].price + "&lt;/div&gt;";
}

document.getElementById("productContainer").innerHTML = productsHTML;
</pre>
<p>In the code above, an array of products is displayed by creating a for..next loop which loops through each element in the array. A string which represents a list of products is built through concatenation. </p>
<p>The code above is a designer’s nightmare. You cannot modify the appearance of the list of products without modifying the JavaScript code. </p>
<p>A much better approach is to use a template like this:
<pre class="brush: xml;">&lt;div id="productTemplate"&gt;
    &lt;h1&gt;Product Details&lt;/h1&gt;
    &lt;div&gt;
        Product Name:
        &lt;span data-win-bind="innerText:name"&gt;&lt;/span&gt;
    &lt;/div&gt;
    &lt;div&gt;
        Product Price:
        &lt;span data-win-bind="innerText:price"&gt;&lt;/span&gt;
    &lt;/div&gt;
&lt;/div&gt;
</pre>
<p>A template is simply a fragment of HTML that contains placeholders. Instead of displaying a list of products by concatenating together a string, you can render a template for each product. </p>
<h3>Creating a Simple Template</h3>
<p>Let’s start by using a template to render a single product. The following HTML page contains a template and a placeholder for rendering the template:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;Application1&lt;/title&gt;

    &lt;!-- WinJS references --&gt;
    &lt;link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet"&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/base.js"&gt;&lt;/script&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/ui.js"&gt;&lt;/script&gt;

    &lt;!-- Application1 references --&gt;
    &lt;link href="/css/default.css" rel="stylesheet"&gt;
    &lt;script src="/js/default.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;!-- Product Template --&gt;
    &lt;div id="productTemplate"&gt;
        &lt;h1&gt;Product Details&lt;/h1&gt;
        &lt;div&gt;
            Product Name:
            &lt;span data-win-bind="innerText:name"&gt;&lt;/span&gt;
        &lt;/div&gt;
        &lt;div&gt;
            Product Price:
            &lt;span data-win-bind="innerText:price"&gt;&lt;/span&gt;
        &lt;/div&gt;
    &lt;/div&gt;

    &lt;!-- Place where Product Template is Rendered --&gt;
    &lt;div id="productContainer"&gt;&lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>In the page above, the template is defined in a DIV element with the id productTemplate. The contents of the productTemplate are not displayed when the page is opened in the browser. The contents of a template are automatically hidden when you convert the productTemplate into a template in your JavaScript code. </p>
<p>Notice that the template uses data-win-bind attributes to display the product name and price properties. You can use both data-win-bind and data-win-bindsource attributes within a template. To learn more about these attributes, see my earlier blog post on WinJS data binding: </p>
<p><a href="http://stephenwalther.com/blog/archive/2012/02/26/windows-web-applications-declarative-data-binding.aspx">http://stephenwalther.com/blog/archive/2012/02/26/windows-web-applications-declarative-data-binding.aspx</a> </p>
<p>The page above also includes a DIV element named productContainer. The rendered template is added to this element. </p>
<p>Here’s the code for the default.js script which creates and renders the template:
<pre class="brush: js;">(function () {
    "use strict";

    var app = WinJS.Application;

    app.onactivated = function (eventObject) {
        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {

            var product = {
                name: "Tesla",
                price: 80000
            };

            var productTemplate = new WinJS.Binding.Template(document.getElementById("productTemplate"));
            productTemplate.render(product, document.getElementById("productContainer"));

        }
    };

    app.start();
})();
</pre>
<p>In the code above, a single product object is created with the following line of code:
<pre class="brush: js;">var product = { 

   name: "Tesla", 

   price: 80000 

}; 
</pre>
<p>Next, the productTemplate element from the page is converted into an actual WinJS template with the following line of code:
<pre class="brush: js;">var productTemplate = new WinJS.Binding.Template(document.getElementById("productTemplate"));
</pre>
<p>The template is rendered to the templateContainer element with the following line of code:
<pre class="brush: js;">productTemplate.render(product, document.getElementById("productContainer"));
</pre>
<p>The result of this work is that the product details are displayed: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image0023.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="clip_image002" border="0" alt="clip_image002" src="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image002_thumb3.png" width="628" height="397"></a> </p>
<p>Notice that you do not need to call WinJS.Binding.processAll(). The Template render() method takes care of the binding for you. </p>
<h3>Displaying an Array in a Template</h3>
<p>If you want to display an array of products using a template then you simply need to create a for..next loop and iterate through the array calling the Template render() method for each element.
<pre class="brush: js;">(function () {
    "use strict";

    var app = WinJS.Application;

    app.onactivated = function (eventObject) {
        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {

            var products = [
                { name: "Tesla", price: 80000 },
                { name: "VW Rabbit", price: 200 },
                { name: "BMW", price: 60000 }
            ];

            var productTemplate = new WinJS.Binding.Template(document.getElementById("productTemplate"));
            var productContainer = document.getElementById("productContainer");

            var i, product;
            for (i = 0; i &lt; products.length; i++) {
                product = products[i];
                productTemplate.render(product, productContainer);
            }
        }
    };

    app.start();
})();
</pre>
<p>After each product in the array is rendered with the template, the result is appended to the productContainer element. </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image0041.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="clip_image004" border="0" alt="clip_image004" src="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image004_thumb1.png" width="628" height="397"></a> </p>
<p>No changes need to be made to the HTML page discussed in the previous section to display an array of products instead of a single product. The same product template can be used in both scenarios. </p>
<h3>Rendering an HTML TABLE with a Template</h3>
<p>When using the WinJS library, you create a template by creating an HTML element in your page. One drawback to this approach of creating templates is that your templates are part of your HTML page. In order for your HTML page to validate, the HTML within your templates must also validate. </p>
<p>This means, for example, that you cannot enclose a single HTML table row within a template. The following HTML is invalid because you cannot place a TR element directly within the body of an HTML document: </p>
<p>&nbsp;
<pre class="brush: xml;">&lt;!-- Product Template --&gt; 

&lt;tr&gt; 

   &lt;td data-win-bind="innerText:name"&gt;&lt;/td&gt; 

   &lt;td data-win-bind="innerText:price"&gt;&lt;/td&gt; 

&lt;/tr&gt; 
</pre>
<p>This template won’t validate because, in a valid HTML5 document, a TR element must appear within a THEAD or TBODY element. Instead, you must create the entire TABLE element in the template. The following HTML page illustrates how you can create a template which contains a TR element: </p>
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;Application1&lt;/title&gt;

    &lt;!-- WinJS references --&gt;
    &lt;link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet"&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/base.js"&gt;&lt;/script&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/ui.js"&gt;&lt;/script&gt;

    &lt;!-- Application1 references --&gt;
    &lt;link href="/css/default.css" rel="stylesheet"&gt;
    &lt;script src="/js/default.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;

    &lt;!-- Product Template --&gt;
    &lt;div id="productTemplate"&gt;
    &lt;table&gt;
    &lt;tbody&gt;
    &lt;tr&gt;
        &lt;td data-win-bind="innerText:name"&gt;&lt;/td&gt;
        &lt;td data-win-bind="innerText:price"&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;/tbody&gt;
    &lt;/table&gt;
    &lt;/div&gt;

    &lt;!-- Place where Product Template is Rendered --&gt;
    &lt;table&gt;
        &lt;thead&gt;
            &lt;tr&gt;
                &lt;th&gt;Name&lt;/th&gt;&lt;th&gt;Price&lt;/th&gt;
            &lt;/tr&gt;
        &lt;/thead&gt;
        &lt;tbody id="productContainer"&gt;
        &lt;/tbody&gt;
    &lt;/table&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>&nbsp;</p>
<p>In the HTML page above, the product template includes TABLE and TBODY elements: </p>
<pre class="brush: xml;">&lt;!-- Product Template --&gt;
&lt;div id="productTemplate"&gt;
&lt;table&gt;
&lt;tbody&gt;
&lt;tr&gt;
    &lt;td data-win-bind="innerText:name"&gt;&lt;/td&gt;
    &lt;td data-win-bind="innerText:price"&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/div&gt;
</pre>
<p>We discard these elements when we render the template. The only reason that we include the TABLE and THEAD elements in the template is to make the HTML page validate as valid HTML5 markup. </p>
<p>Notice that the productContainer (the target of the template) in the page above is a TBODY element. We want to add the rows rendered by the template to the TBODY element in the page. </p>
<p>The productTemplate is rendered in the default.js file:
<pre class="brush: js;">(function () {
    "use strict";

    var app = WinJS.Application;

    app.onactivated = function (eventObject) {
        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {

            var products = [
                { name: "Tesla", price: 80000 },
                { name: "VW Rabbit", price: 200 },
                { name: "BMW", price: 60000 }
            ];

            var productTemplate = new WinJS.Binding.Template(document.getElementById("productTemplate"));
            var productContainer = document.getElementById("productContainer");

            var i, product, row;
            for (i = 0; i &lt; products.length; i++) {
                product = products[i];
                productTemplate.render(product).then(function (result) {
                    row = WinJS.Utilities.query("tr", result).get(0);
                    productContainer.appendChild(row);
                });
            }

        }
    };

    app.start();
})();
</pre>
<p>When the product template is rendered, the TR element is extracted from the rendered template by using the WinJS.Utilities.query() method. Next, only the TR element is added to the productContainer:
<pre class="brush: js;">productTemplate.render(product).then(function (result) {
    row = WinJS.Utilities.query("tr", result).get(0);
    productContainer.appendChild(row);
});
</pre>
<p>I discuss the WinJS.Utilities.query() method in depth in a previous blog entry: </p>
<p><a href="http://stephenwalther.com/blog/archive/2012/02/23/windows-web-applications-query-selectors.aspx">http://stephenwalther.com/blog/archive/2012/02/23/windows-web-applications-query-selectors.aspx</a> </p>
<p>When everything gets rendered, the products are displayed in an HTML table: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image0061.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="clip_image006" border="0" alt="clip_image006" src="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image006_thumb1.png" width="628" height="468"></a></p>
<p>You can see the actual HTML rendered by looking at the Visual Studio DOM Explorer window:</p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/image.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/image_thumb.png" width="690" height="599"></a></p>
<p>&nbsp;</p>
<h3>Loading an External Template</h3>
<p>Instead of embedding a template in an HTML page, you can place your template in an external HTML file. It makes sense to create a template in an external file when you need to use the same template in multiple pages. For example, you might need to use the same product template in multiple pages in your application. </p>
<p>The following HTML page does not contain a template. It only contains a container that will act as a target for the rendered template:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;Application1&lt;/title&gt;

    &lt;!-- WinJS references --&gt;
    &lt;link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet"&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/base.js"&gt;&lt;/script&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/ui.js"&gt;&lt;/script&gt;

    &lt;!-- Application1 references --&gt;
    &lt;link href="/css/default.css" rel="stylesheet"&gt;
    &lt;script src="/js/default.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;    

    &lt;!-- Place where Product Template is Rendered --&gt;
    &lt;div id="productContainer"&gt;&lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The template is contained in a separate file located at the path /templates/productTemplate.html: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/image1.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/image_thumb1.png" width="354" height="322"></a></p>
<p>&nbsp;
<p>Here’s the contents of the productTemplate.html file:
<pre class="brush: xml;">&lt;!-- Product Template --&gt;
&lt;div id="productTemplate"&gt;
    &lt;h1&gt;Product Details&lt;/h1&gt;
    &lt;div&gt;
        Product Name:
        &lt;span data-win-bind="innerText:name"&gt;&lt;/span&gt;
    &lt;/div&gt;
    &lt;div&gt;
        Product Price:
        &lt;span data-win-bind="innerText:price"&gt;&lt;/span&gt;
    &lt;/div&gt;
&lt;/div&gt;
</pre>
<p>Notice that the template file only contains the template and not the standard opening and closing HTML elements. It is an HTML fragment. </p>
<p>If you prefer, you can include all of the standard opening and closing HTML elements in your external template – these elements get stripped away automatically:
<pre class="brush: xml;">&lt;html&gt;
    &lt;head&gt;&lt;title&gt;product template&lt;/title&gt;&lt;/head&gt;
    &lt;body&gt;

    &lt;!-- Product Template --&gt;
    &lt;div id="productTemplate"&gt;
        &lt;h1&gt;Product Details&lt;/h1&gt;
        &lt;div&gt;
            Product Name:
            &lt;span data-win-bind="innerText:name"&gt;&lt;/span&gt;
        &lt;/div&gt;
        &lt;div&gt;
            Product Price:
            &lt;span data-win-bind="innerText:price"&gt;&lt;/span&gt;
        &lt;/div&gt;
    &lt;/div&gt;

    &lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Either approach – using a fragment or using a full HTML document&nbsp; &#8212; works fine. </p>
<p>Finally, the following default.js file loads the external template, renders the template for each product, and appends the result to the product container:
<pre class="brush: js;">(function () {
    "use strict";

    var app = WinJS.Application;

    app.onactivated = function (eventObject) {
        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {

            var products = [
                { name: "Tesla", price: 80000 },
                { name: "VW Rabbit", price: 200 },
                { name: "BMW", price: 60000 }
            ];

            var productTemplate = new WinJS.Binding.Template(null, { href: "/templates/productTemplate.html" });
            var productContainer = document.getElementById("productContainer");

            var i, product, row;
            for (i = 0; i &lt; products.length; i++) {
                product = products[i];
                productTemplate.render(product, productContainer);
            }
        }
    };

    app.start();
})();
</pre>
<p>The path to the external template is passed to the constructor for the Template class as one of the options:
<pre class="brush: js;">var productTemplate = new WinJS.Binding.Template(null, {href:"/templates/productTemplate.html"});
</pre>
<p>When a template is contained in a page then you use the first parameter of the WinJS.Binding.Template constructor to represent the template – instead of null, you pass the element which contains the template. When a template is located in an external file, you pass the href for the file as part of the second parameter for the WinJS.Binding.Template constructor. </p>
<h3>Summary</h3>
<p>The goal of this blog entry was to describe how you can use WinJS templates to render either a single item or an array of items to a page. We also explored two advanced topics. You learned how to render an HTML table by extracting the TR element from a template. You also learned how to place a template in an external file.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/StephenWalther?a=21i8HQfrIIY:jkamZdm1ekE:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/21i8HQfrIIY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stephenwalther.com/blog/archive/2012/02/27/metro-using-templates.aspx/feed</wfw:commentRss>
		<slash:comments>6</slash:comments>
		<feedburner:origLink>http://stephenwalther.com/blog/archive/2012/02/27/metro-using-templates.aspx</feedburner:origLink></item>
		<item>
		<title>Metro: Declarative Data Binding</title>
		<link>http://feedproxy.google.com/~r/StephenWalther/~3/4i6oc8XnItE/metro-declarative-data-binding.aspx</link>
		<comments>http://stephenwalther.com/blog/archive/2012/02/26/metro-declarative-data-binding.aspx#comments</comments>
		<pubDate>Mon, 27 Feb 2012 05:09:07 +0000</pubDate>
		<dc:creator>Stephen.Walther</dc:creator>
				<category><![CDATA[Metro]]></category>

		<guid isPermaLink="false">http://stephenwalther.com/blog/?p=355</guid>
		<description><![CDATA[The goal of this blog post is to describe how declarative data binding works in the WinJS library. In particular, you learn how to use both the data-win-bind and data-win-bindsource attributes. You also learn how to use calculated properties and converters to format the value of a property automatically when performing data binding. By taking [...]]]></description>
			<content:encoded><![CDATA[<p>The goal of this blog post is to describe how declarative data binding works in the WinJS library. In particular, you learn how to use both the data-win-bind and data-win-bindsource attributes. You also learn how to use calculated properties and converters to format the value of a property automatically when performing data binding.
<p>By taking advantage of WinJS data binding, you can use the Model-View-ViewModel (MVVM) pattern when building Metro style applications with JavaScript. By using the MVVM pattern, you can prevent your JavaScript code from spinning into chaos. The MVVM pattern provides you with a standard pattern for organizing your JavaScript code which results in a more maintainable application.<br />
<h3>Using Declarative Bindings</h3>
<p>You can use the data-win-bind attribute with any HTML element in a page. The data-win-bind attribute enables you to bind (associate) an attribute of an HTML element to the value of a property.
<p>Imagine, for example, that you want to create a product details page. You want to show a product object in a page.
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image0021.jpg"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="clip_image002" border="0" alt="clip_image002" src="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image002_thumb1.jpg" width="628" height="419"></a>
<p>In that case, you can create the following HTML page to display the product details:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;Application1&lt;/title&gt;

    &lt;!-- WinJS references --&gt;
    &lt;link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet"&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/base.js"&gt;&lt;/script&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/ui.js"&gt;&lt;/script&gt;

    &lt;!-- Application1 references --&gt;
    &lt;link href="/css/default.css" rel="stylesheet"&gt;
    &lt;script src="/js/default.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;    

    &lt;h1&gt;Product Details&lt;/h1&gt;

    &lt;div class="field"&gt;
        Product Name:
        &lt;span data-win-bind="innerText:name"&gt;&lt;/span&gt;
    &lt;/div&gt;
    &lt;div class="field"&gt;
        Product Price:
        &lt;span data-win-bind="innerText:price"&gt;&lt;/span&gt;
    &lt;/div&gt;
    &lt;div class="field"&gt;
        Product Picture:
        &lt;br /&gt;
        &lt;img data-win-bind="src:photo;alt:name" /&gt;
    &lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The HTML page above contains three data-win-bind attributes – one attribute for each product property displayed. You use the data-win-bind attribute to set properties of the HTML element associated with the data-win-attribute. The data-win-bind attribute takes a semicolon delimited list of element property names and data source property names: </p>
<p>data-win-bind=”elementPropertyName:datasourcePropertyName; elementPropertyName:datasourcePropertyName;…” </p>
<p>In the HTML page above, the first two data-win-bind attributes are used to set the values of the innerText property of the SPAN elements. The last data-win-bind attribute is used to set the values of the IMG element’s src and alt attributes. </p>
<p>By the way, using data-win-bind attributes is perfectly valid HTML5. The HTML5 standard enables you to add custom attributes to an HTML document just as long as the custom attributes start with the prefix data-. So you can add custom attributes to an HTML5 document with names like data-stephen, data-funky, or data-rover-dog-is-hungry and your document will validate. </p>
<p>The product object displayed in the page above with the data-win-bind attributes is created in the default.js file:
<pre class="brush: js;">(function () {
    "use strict";

    var app = WinJS.Application;

    app.onactivated = function (eventObject) {
        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {

            var product = {
                name: "Tesla",
                price: 80000,
                photo: "/images/TeslaPhoto.png"
            };

            WinJS.Binding.processAll(null, product);
        }
    };

    app.start();
})();
</pre>
<p>In the code above, a product object is created with a name, price, and photo property. The WinJS.Binding.processAll() method is called to perform the actual binding (Don’t confuse WinJS.Binding.processAll() and WinJS.UI.processAll() – these are different methods). </p>
<p>The first parameter passed to the processAll() method represents the root element for the binding. In other words, binding happens on this element and its child elements. If you provide the value null, then binding happens on the entire body of the document (document.body). </p>
<p>The second parameter represents the data context. This is the object that has the properties which are displayed with the data-win-bind attributes. In the code above, the product object is passed as the data context parameter. Another word for data context is <em>view model</em>.&nbsp;<br />
<h3>Creating Complex View Models</h3>
<p>In the previous section, we used the data-win-bind attribute to display the properties of a simple object: a single product. However, you can use binding with more complex view models including view models which represent multiple objects. </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/02/image.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://stephenwalther.com/blog/wp-content/uploads/2012/02/image_thumb.png" width="628" height="412"></a> </p>
<p>For example, the view model in the following default.js file represents both a customer and a product object. Furthermore, the customer object has a nested address object:
<pre class="brush: js;">(function () {
    "use strict";

    var app = WinJS.Application;

    app.onactivated = function (eventObject) {
        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {

            var viewModel = {
                customer: {
                    firstName: "Fred",
                    lastName: "Flintstone",
                    address: {
                        street: "1 Rocky Way",
                        city: "Bedrock",
                        country: "USA"
                    }
                },
                product: {
                    name: "Bowling Ball",
                    price: 34.55
                }
            };

            WinJS.Binding.processAll(null, viewModel);

        }
    };

    app.start();
})();
</pre>
<p>The following page displays the customer (including the customer address) and the product. Notice that you can use dot notation to refer to child objects in a view model such as customer.address.street.
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;Application1&lt;/title&gt;

    &lt;!-- WinJS references --&gt;
    &lt;link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet"&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/base.js"&gt;&lt;/script&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/ui.js"&gt;&lt;/script&gt;

    &lt;!-- Application1 references --&gt;
    &lt;link href="/css/default.css" rel="stylesheet"&gt;
    &lt;script src="/js/default.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;    

    &lt;h1&gt;Customer Details&lt;/h1&gt;

    &lt;div class="field"&gt;
        First Name:
        &lt;span data-win-bind="innerText:customer.firstName"&gt;&lt;/span&gt;
    &lt;/div&gt;
    &lt;div class="field"&gt;
        Last Name:
        &lt;span data-win-bind="innerText:customer.lastName"&gt;&lt;/span&gt;
    &lt;/div&gt;
    &lt;div class="field"&gt;
        Address:
        &lt;address&gt;
            &lt;span data-win-bind="innerText:customer.address.street"&gt;&lt;/span&gt;
            &lt;br /&gt;
            &lt;span data-win-bind="innerText:customer.address.city"&gt;&lt;/span&gt;
            &lt;br /&gt;
            &lt;span data-win-bind="innerText:customer.address.country"&gt;&lt;/span&gt;
        &lt;/address&gt;
    &lt;/div&gt;

    &lt;h1&gt;Product&lt;/h1&gt;

    &lt;div class="field"&gt;
        Name:
        &lt;span data-win-bind="innerText:product.name"&gt;&lt;/span&gt;
    &lt;/div&gt;

    &lt;div class="field"&gt;
        Price:
        &lt;span data-win-bind="innerText:product.price"&gt;&lt;/span&gt;
    &lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>A view model can be as complicated as you need and you can bind the view model to a view (an HTML document) by using declarative bindings. </p>
<h3>Creating Calculated Properties</h3>
<p>You might want to modify a property before displaying the property. </p>
<p>For example, you might want to format the product price property before displaying the property. You don’t want to display the raw product price “80000”. Instead, you want to display the formatted price “$80,000”. </p>
<p>You also might need to combine multiple properties. For example, you might need to display the customer full name by combining the values of the customer first and last name properties. </p>
<p>In these situations, it is tempting to call a function when performing binding. For example, you could create a function named fullName() which concatenates the customer first and last name. Unfortunately, the WinJS library does not support the following syntax:
<pre class="brush: js;">&lt;span data-win-bind=”innerText:fullName()”&gt;&lt;/span&gt;
</pre>
<p>Instead, in these situations, you should create a new property in your view model that has a getter. For example, the customer object in the following default.js file includes a property named fullName which combines the values of the firstName and lastName properties:
<pre class="brush: js;">(function () {
    "use strict";

    var app = WinJS.Application;

    app.onactivated = function (eventObject) {
        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {

            var customer = {
                firstName: "Fred",
                lastName: "Flintstone",
                get fullName() {
                    return this.firstName + " " + this.lastName;
                }
            };

            WinJS.Binding.processAll(null, customer);

        }
    };

    app.start();
})();
</pre>
<p>The customer object has a firstName, lastName, and fullName property. Notice that the fullName property is defined with a getter function. When you read the fullName property, the values of the firstName and lastName properties are concatenated and returned. </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image004.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="clip_image004" border="0" alt="clip_image004" src="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image004_thumb.png" width="628" height="397"></a> </p>
<p>The following HTML page displays the fullName property in an H1 element. You can use the fullName property in a data-win-bind attribute in exactly the same way as any other property.
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;Application1&lt;/title&gt;

    &lt;!-- WinJS references --&gt;
    &lt;link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet"&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/base.js"&gt;&lt;/script&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/ui.js"&gt;&lt;/script&gt;

    &lt;!-- Application1 references --&gt;
    &lt;link href="/css/default.css" rel="stylesheet"&gt;
    &lt;script src="/js/default.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;    

    &lt;h1 data-win-bind="innerText:fullName"&gt;&lt;/h1&gt;

    &lt;div class="field"&gt;
        First Name:
        &lt;span data-win-bind="innerText:firstName"&gt;&lt;/span&gt;
    &lt;/div&gt;
    &lt;div class="field"&gt;
        Last Name:
        &lt;span data-win-bind="innerText:lastName"&gt;&lt;/span&gt;
    &lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<h3>Creating a Converter</h3>
<p>In the previous section, you learned how to format the value of a property by creating a property with a getter. This approach makes sense when the formatting logic is specific to a particular view model. </p>
<p>If, on the other hand, you need to perform the same type of formatting for multiple view models then it makes more sense to create a converter function. A converter function is a function which you can apply whenever you are using the data-win-bind attribute. </p>
<p>Imagine, for example, that you want to create a general function for displaying dates. You always want to display dates using a short format such as 12/25/1988. The following JavaScript file – named converters.js – contains a shortDate() converter:
<pre class="brush: js;">(function (WinJS) {

    var shortDate = WinJS.Binding.converter(function (date) {
        return date.getMonth() + 1 +
            "/" + date.getDate() +
            "/" + date.getFullYear();
    });

    // Export shortDate
    WinJS.Namespace.define("MyApp.Converters", {
        shortDate: shortDate
    });

})(WinJS);
</pre>
<p>The file above uses the Module Pattern, a pattern which is used through the WinJS library. To learn more about the Module Pattern, see my blog entry on namespaces and modules: </p>
<p><a href="http://stephenwalther.com/blog/archive/2012/02/22/windows-web-applications-namespaces-and-modules.aspx">http://stephenwalther.com/blog/archive/2012/02/22/windows-web-applications-namespaces-and-modules.aspx</a> </p>
<p>The file contains the definition for a converter function named shortDate(). This function converts a JavaScript date object into a short date string such as 12/1/1988. </p>
<p>The converter function is created with the help of the WinJS.Binding.converter() method. This method takes a normal function and converts it into a converter function. </p>
<p>Finally, the shortDate() converter is added to the MyApp.Converters namespace. You can call the shortDate() function by calling MyApp.Converters.shortDate(). </p>
<p>The default.js file contains the customer object that we want to bind. Notice that the customer object has a firstName, lastName, and birthday property. We will use our new shortDate() converter when displaying the customer birthday property: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image006.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="clip_image006" border="0" alt="clip_image006" src="http://stephenwalther.com/blog/wp-content/uploads/2012/02/clip_image006_thumb.png" width="628" height="397"></a>
<pre class="brush: js;">(function () {
    "use strict";

    var app = WinJS.Application;

    app.onactivated = function (eventObject) {
        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {

            var customer = {
                firstName: "Fred",
                lastName: "Flintstone",
                birthday: new Date("12/1/1988")
            };

            WinJS.Binding.processAll(null, customer);

        }
    };

    app.start();
})();
</pre>
<p>We actually use our shortDate converter in the HTML document. The following HTML document displays all of the customer properties:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;Application1&lt;/title&gt;

    &lt;!-- WinJS references --&gt;
    &lt;link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet"&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/base.js"&gt;&lt;/script&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/ui.js"&gt;&lt;/script&gt;

    &lt;!-- Application1 references --&gt;
    &lt;link href="/css/default.css" rel="stylesheet"&gt;
    &lt;script src="/js/default.js"&gt;&lt;/script&gt;
    &lt;script type="text/javascript" src="js/converters.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;    

    &lt;h1&gt;Customer Details&lt;/h1&gt;

    &lt;div class="field"&gt;
        First Name:
        &lt;span data-win-bind="innerText:firstName"&gt;&lt;/span&gt;
    &lt;/div&gt;
    &lt;div class="field"&gt;
        Last Name:
        &lt;span data-win-bind="innerText:lastName"&gt;&lt;/span&gt;
    &lt;/div&gt;
    &lt;div class="field"&gt;
        Birthday:
        &lt;span data-win-bind="innerText:birthday MyApp.Converters.shortDate"&gt;&lt;/span&gt;
    &lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Notice the data-win-bind attribute used to display the birthday property. It looks like this:
<pre class="brush: xml;">&lt;span data-win-bind="innerText:birthday MyApp.Converters.shortDate"&gt;&lt;/span&gt; 
</pre>
<p>The shortDate converter is applied to the birthday property when the birthday property is bound to the SPAN element’s innerText property. </p>
<h3>Using data-win-bindsource</h3>
<p>Normally, you pass the view model (the data context) which you want to use with the data-win-bind attributes in a page by passing the view model to the WinJS.Binding.processAll() method like this:
<pre class="brush: js;">WinJS.Binding.processAll(null, viewModel);
</pre>
<p>As an alternative, you can specify the view model declaratively in your markup by using the data-win-datasource attribute. For example, the following default.js script exposes a view model with the fully-qualified name of MyWinWebApp.viewModel:
<pre class="brush: js;">(function () {
    "use strict";

    var app = WinJS.Application;

    app.onactivated = function (eventObject) {
        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {

            // Create view model
            var viewModel = {
                customer: {
                    firstName: "Fred",
                    lastName: "Flintstone"
                },
                product: {
                    name: "Bowling Ball",
                    price: 12.99
                }
            };

            // Export view model to be seen by universe
            WinJS.Namespace.define("MyWinWebApp", {
                viewModel: viewModel
            });

            // Process data-win-bind attributes
            WinJS.Binding.processAll();

        }
    };

    app.start();
})();
</pre>
<p>In the code above, a view model which represents a customer and a product is exposed as MyWinWebApp.viewModel. </p>
<p>The following HTML page illustrates how you can use the data-win-bindsource attribute to bind to this view model:
<pre class="brush: xml;">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset="utf-8"&gt;
    &lt;title&gt;Application1&lt;/title&gt;

    &lt;!-- WinJS references --&gt;
    &lt;link href="//Microsoft.WinJS.0.6/css/ui-dark.css" rel="stylesheet"&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/base.js"&gt;&lt;/script&gt;
    &lt;script src="//Microsoft.WinJS.0.6/js/ui.js"&gt;&lt;/script&gt;

    &lt;!-- Application1 references --&gt;
    &lt;link href="/css/default.css" rel="stylesheet"&gt;
    &lt;script src="/js/default.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;    

    &lt;h1&gt;Customer Details&lt;/h1&gt;
    &lt;div data-win-bindsource="MyWinWebApp.viewModel.customer"&gt;
        &lt;div class="field"&gt;
            First Name:
            &lt;span data-win-bind="innerText:firstName"&gt;&lt;/span&gt;
        &lt;/div&gt;
        &lt;div class="field"&gt;
            Last Name:
            &lt;span data-win-bind="innerText:lastName"&gt;&lt;/span&gt;
        &lt;/div&gt;
    &lt;/div&gt;

    &lt;h1&gt;Product&lt;/h1&gt;
    &lt;div data-win-bindsource="MyWinWebApp.viewModel.product"&gt;
        &lt;div class="field"&gt;
            Name:
            &lt;span data-win-bind="innerText:name"&gt;&lt;/span&gt;
        &lt;/div&gt;

        &lt;div class="field"&gt;
            Price:
            &lt;span data-win-bind="innerText:price"&gt;&lt;/span&gt;
        &lt;/div&gt;
    &lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>The data-win-bindsource attribute is used twice in the page above: it is used with the DIV element which contains the customer details and it is used with the DIV element which contains the product details. </p>
<p>If an element has a data-win-bindsource attribute then all of the child elements of that element are affected. The data-win-bind attributes of all of the child elements are bound to the data source represented by the data-win-bindsource attribute. </p>
<h3>Summary</h3>
<p>The focus of this blog entry was data binding using the WinJS library. You learned how to use the data-win-bind attribute to bind the properties of an HTML element to a view model. We also discussed several advanced features of data binding. We examined how to create calculated properties by including a property with a getter in your view model. We also discussed how you can create a converter function to format the value of a view model property when binding the property. Finally, you learned how to use the data-win-bindsource attribute to specify a view model declaratively.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/StephenWalther?a=4i6oc8XnItE:1PmNZSTNypE:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/4i6oc8XnItE" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stephenwalther.com/blog/archive/2012/02/26/metro-declarative-data-binding.aspx/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://stephenwalther.com/blog/archive/2012/02/26/metro-declarative-data-binding.aspx</feedburner:origLink></item>
		<item>
		<title>Metro: Understanding Observables</title>
		<link>http://feedproxy.google.com/~r/StephenWalther/~3/gLmgH0I66h8/metro-understanding-observables.aspx</link>
		<comments>http://stephenwalther.com/blog/archive/2012/02/25/metro-understanding-observables.aspx#comments</comments>
		<pubDate>Sat, 25 Feb 2012 17:21:36 +0000</pubDate>
		<dc:creator>Stephen.Walther</dc:creator>
				<category><![CDATA[Metro]]></category>

		<guid isPermaLink="false">http://stephenwalther.com/blog/?p=345</guid>
		<description><![CDATA[The goal of this blog entry is to describe how the Observer Pattern is implemented in the WinJS library. You learn how to create observable objects which trigger notifications automatically when their properties are changed. Observables enable you to keep your user interface and your application data in sync. For example, by taking advantage of [...]]]></description>
			<content:encoded><![CDATA[<p>The goal of this blog entry is to describe how the Observer Pattern is implemented in the WinJS library. You learn how to create observable objects which trigger notifications automatically when their properties are changed.
<p>Observables enable you to keep your user interface and your application data in sync. For example, by taking advantage of observables, you can update your user interface automatically whenever the properties of a product change. Observables are the foundation of declarative binding in the WinJS library.
<p>The WinJS library is not the first JavaScript library to include support for observables. For example, both the KnockoutJS library and the Microsoft Ajax Library (now part of the Ajax Control Toolkit) support observables.<br />
<h3>Creating an Observable</h3>
<p>Imagine that I have created a product object like this:
<pre class="brush: js; gutter: false;">var product = {
    name: "Milk",
    description: "Something to drink",
    price: 12.33
};
</pre>
<p>Nothing very exciting about this product. It has three properties named name, description, and price. </p>
<p>Now, imagine that I want to be notified automatically whenever any of these properties are changed. In that case, I can create an <i>observable product</i> from my product object like this:
<pre class="brush: js; gutter: false;">var observableProduct = WinJS.Binding.as(product);
</pre>
<p>This line of code creates a new JavaScript object named observableProduct from the existing JavaScript object named product. This new object also has a name, description, and price property. However, unlike the properties of the original product object, the properties of the observable product object trigger notifications when the properties are changed. </p>
<p>Each of the properties of the new observable product object has been changed into accessor properties which have both a getter and a setter. For example, the observable product price property looks something like this:
<pre class="brush: js; gutter: false;">price: { 

   get: function () { return this.getProperty(“price”); } 

   set: function (value) { this.setProperty(“price”, value); } 

} 
</pre>
<p>When you read the price property then the getProperty() method is called and when you set the price property then the setProperty() method is called. The getProperty() and setProperty() methods are methods of the observable product object. </p>
<p>The observable product object supports the following methods and properties: </p>
<p>· addProperty(name, value) – Adds a new property to an observable and notifies any listeners. </p>
<p>· backingData – An object which represents the value of each property. </p>
<p>· bind(name, action) – Enables you to execute a function when a property changes. </p>
<p>· getProperty(name) – Returns the value of a property using the string name of the property. </p>
<p>· notify(name, newValue, oldValue) – A private method which executes each function in the _listeners array. </p>
<p>· removeProperty(name) – Removes a property and notifies any listeners. </p>
<p>· setProperty(name, value) – Updates a property and notifies any listeners. </p>
<p>· unbind(name, action) – Enables you to stop executing a function in response to a property change. </p>
<p>· updateProperty(name, value) – Updates a property and notifies any listeners. </p>
<p>So when you create an observable, you get a new object with the same properties as an existing object. However, when you modify the properties of an observable object, then you can notify any listeners of the observable that the value of a particular property has changed automatically. </p>
<p>Imagine that you change the value of the price property like this:
<pre class="brush: js; gutter: false;">observableProduct.price = 2.99;
</pre>
<p>In that case, the following sequence of events is triggered: </p>
<p>1. The price setter calls the setProperty(“price”, 2.99) method </p>
<p>2. The setProperty() method updates the value of the backingData.price property and calls the notify() method </p>
<p>3. The notify() method executes each function in the collection of listeners associated with the price property </p>
<h4>Creating Observable Listeners</h4>
<p>If you want to be notified when a property of an observable object is changed, then you need to register a listener. You register a listener by using the bind() method like this:
<pre class="brush: js;">(function () {
    "use strict";

    var app = WinJS.Application;

    app.onactivated = function (eventObject) {
        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {

            // Simple product object
            var product = {
                name: "Milk",
                description: "Something to drink",
                price: 12.33
            };

            // Create observable product
            var observableProduct = WinJS.Binding.as(product);

            // Execute a function when price is changed
            observableProduct.bind("price", function (newValue) {
                console.log(newValue);
            });

            // Change the price
            observableProduct.price = 2.99;

        }
    };

    app.start();
})();
</pre>
<p>In the code above, the bind() method is used to associate the price property with a function. When the price property is changed, the function logs the new value of the price property to the Visual Studio JavaScript console. </p>
<p>The price property is associated with the function using the following line of code:
<pre class="brush: js; gutter: false;">// Execute a function when price is changed
observableProduct.bind("price", function (newValue) {
   console.log(newValue);
});
</pre>
<h4>Coalescing Notifications</h4>
<p>If you make multiple changes to a property – one change immediately following another – then separate notifications won’t be sent. Instead, any listeners are notified only once. The notifications are coalesced into a single notification. </p>
<p>For example, in the following code, the product price property is updated three times. However, only one message is written to the JavaScript console. Only the last value assigned to the price property is written to the JavaScript Console window:
<pre class="brush: js; gutter: false;">// Simple product object
var product = {
    name: "Milk",
    description: "Something to drink",
    price: 12.33
};

// Create observable product
var observableProduct = WinJS.Binding.as(product);

// Execute a function when price is changed
observableProduct.bind("price", function (newValue) {
    console.log(newValue);
});

// Change the price
observableProduct.price = 3.99;
observableProduct.price = 2.99;
observableProduct.price = 1.99;
</pre>
<p>Only the last value assigned to price, the value 1.99, appears in the console: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/image3.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/image_thumb3.png" width="433" height="194"></a> </p>
<p>If there is a time delay between changes to a property then changes result in different notifications. For example, the following code updates the price property every second:
<pre class="brush: js; gutter: false;">// Simple product object
var product = {
    name: "Milk",
    description: "Something to drink",
    price: 12.33
};

// Create observable product
var observableProduct = WinJS.Binding.as(product);

// Execute a function when price is changed
observableProduct.bind("price", function (newValue) {
    console.log(newValue);
});

// Add 1 to price every second
window.setInterval(function () {
    observableProduct.price += 1;
}, 1000);
</pre>
<p>In this case, separate notification messages are logged to the JavaScript Console window: </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/image4.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/image_thumb4.png" width="435" height="348"></a> </p>
<p>If you need to prevent multiple notifications from being coalesced into one then you can take advantage of promises. I discussed WinJS promises in a previous blog entry: </p>
<p><a href="http://stephenwalther.com/blog/archive/2012/02/22/windows-web-applications-promises.aspx">http://stephenwalther.com/blog/archive/2012/02/22/windows-web-applications-promises.aspx</a> </p>
<p>Because the updateProperty() method returns a promise, you can create different notifications for each change in a property by using the following code:
<pre class="brush: js; gutter: false;">// Change the price
observableProduct.updateProperty("price", 3.99)
   .then(function () {
      observableProduct.updateProperty("price", 2.99)
         .then(function () {
            observableProduct.updateProperty("price", 1.99);
         });
    });
</pre>
<p>In this case, even though the price is immediately changed from 3.99 to 2.99 to 1.99, separate notifications for each new value of the price property are sent. </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/image5.png"><img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/image_thumb5.png" width="435" height="219"></a> </p>
<h4>Bypassing Notifications</h4>
<p>Normally, if a property of an observable object has listeners and you change the property then the listeners are notified. However, there are certain situations in which you might want to bypass notification. In other words, you might need to change a property value silently without triggering any functions registered for notification. </p>
<p>If you want to change a property without triggering notifications then you should change the property by using the backingData property. The following code illustrates how you can change the price property silently:
<pre class="brush: js; gutter: false;">// Simple product object
var product = {
    name: "Milk",
    description: "Something to drink",
    price: 12.33
};

// Create observable product
var observableProduct = WinJS.Binding.as(product);

// Execute a function when price is changed
observableProduct.bind("price", function (newValue) {
    console.log(newValue);
});

// Change the price silently
observableProduct.backingData.price = 5.99;
console.log(observableProduct.price); // Writes 5.99 
</pre>
<p>The price is changed to the value 5.99 by changing the value of backingData.price. Because the observableProduct.price property is not set directly, any listeners associated with the price property are not notified. </p>
<p>When you change the value of a property by using the backingData property, the change in the property happens synchronously. However, when you change the value of an observable property directly, the change is always made asynchronously. </p>
<h3>Summary</h3>
<p>The goal of this blog entry was to describe observables. In particular, we discussed how to create observables from existing JavaScript objects and bind functions to observable properties. You also learned how notifications are coalesced (and ways to prevent this coalescing). Finally, we discussed how you can use the backingData property to update an observable property without triggering notifications. </p>
<p>In the next blog entry, we’ll see how observables are used with declarative binding to display the values of properties in an HTML document.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/StephenWalther?a=gLmgH0I66h8:FKRAkJJ9InE:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/gLmgH0I66h8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stephenwalther.com/blog/archive/2012/02/25/metro-understanding-observables.aspx/feed</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://stephenwalther.com/blog/archive/2012/02/25/metro-understanding-observables.aspx</feedburner:origLink></item>
		<item>
		<title>Metro: Understanding the default.js File</title>
		<link>http://feedproxy.google.com/~r/StephenWalther/~3/o3Wg0uhHGok/metro-understanding-the-default-js-file.aspx</link>
		<comments>http://stephenwalther.com/blog/archive/2012/02/24/metro-understanding-the-default-js-file.aspx#comments</comments>
		<pubDate>Fri, 24 Feb 2012 17:44:43 +0000</pubDate>
		<dc:creator>Stephen.Walther</dc:creator>
				<category><![CDATA[Metro]]></category>

		<guid isPermaLink="false">http://stephenwalther.com/blog/?p=339</guid>
		<description><![CDATA[The goal of this blog entry is to describe &#8212; in painful detail &#8212; the contents of the default.js file in a Metro style application written with JavaScript. When you use Visual Studio to create a new Metro application then you get a default.js file automatically. The file is located in a folder named \js\default.js. [...]]]></description>
			<content:encoded><![CDATA[<p>The goal of this blog entry is to describe &#8212; in painful detail &#8212; the contents of the default.js file in a Metro style application written with JavaScript. When you use Visual Studio to create a new Metro application then you get a default.js file automatically. The file is located in a folder named \js\default.js.
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/image9.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/image_thumb9.png" width="957" height="666"></a>
<p>The default.js file kicks off all of your custom JavaScript code. It is the main entry point to a Metro application. The default contents of the default.js file are included below:
<pre class="brush: js;">// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
    "use strict";

    var app = WinJS.Application;

    app.onactivated = function (eventObject) {
        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
            if (eventObject.detail.previousExecutionState !== Windows.ApplicationModel.Activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            WinJS.UI.processAll();
        }
    };

    app.oncheckpoint = function (eventObject) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // eventObject.setPromise().
    };

    app.start();
})();
</pre>
<p>There are several mysterious things happening in this file. The purpose of this blog entry is to dispel this mystery. </p>
<h3>Understanding the Module Pattern</h3>
<p>The first thing that you should notice about the default.js file is that the entire contents of this file are enclosed within a self-executing JavaScript function:
<pre class="brush: js;">(function () {

   ...

})();
</pre>
<p>Metro applications written with JavaScript use something called the <i>module pattern</i>. The module pattern is a common pattern used in JavaScript applications to create private variables, objects, and methods. Anything that you create within the module is encapsulated within the module. </p>
<p>Enclosing all of your custom code within a module prevents you from stomping on code from other libraries accidently. Your application might reference several JavaScript libraries and the JavaScript libraries might have variables, objects, or methods with the same names. By encapsulating your code in a module, you avoid overwriting variables, objects, or methods in the other libraries accidently. </p>
<h3>Enabling Strict Mode with “use strict”</h3>
<p>The first statement within the default.js module enables JavaScript strict mode:
<pre class="brush: js;">'use strict';
</pre>
<p>Strict mode is a new feature of ECMAScript 5 (the latest standard for JavaScript) which enables you to make JavaScript more strict. For example, when strict mode is enabled, you cannot declare variables without using the var keyword. The following statement would result in an exception:
<pre class="brush: js;">hello = "world!";
</pre>
<p>When strict mode is enabled, this statement throws a ReferenceError. When strict mode is not enabled, a global variable is created which, most likely, is not what you want to happen. I’d rather get the exception instead of the unwanted global variable. </p>
<p>The full specification for strict mode is contained in the ECMAScript 5 specification (look at Annex C): </p>
<p><a href="http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf">http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf</a> </p>
<h3>Aliasing the WinJS.Application Object</h3>
<p>The next line of code in the default.js file is used to alias the WinJS.Application object:</p>
<pre class="brush: js;">var app = WinJS.Application;
</pre>
<p>This line of code enables you to use a short-hand syntax when referring to the WinJS.Application object: for example,&nbsp; app.onactivated instead of WinJS.Application.onactivated. The WinJS.Application object&nbsp; represents your running Metro application.</p>
<h3>Handling Application Events</h3>
<p>The default.js file contains an event handler for the WinJS.Application activated event:
<pre class="brush: js;">app.onactivated = function (eventObject) {
    if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
        if (eventObject.detail.previousExecutionState !== Windows.ApplicationModel.Activation.ApplicationExecutionState.terminated) {
            // TODO: This application has been newly launched. Initialize
            // your application here.
        } else {
            // TODO: This application has been reactivated from suspension.
            // Restore application state here.
        }
        WinJS.UI.processAll();
    }
};
</pre>
<p>This WinJS.Application class supports the following events: </p>
<p>· loaded – Happens after browser DOMContentLoaded event. After this event, the DOM is ready and you can access elements in a page. This event is raised before external images have been loaded. </p>
<p>· activated – Triggered by the Windows.UI.WebUI.WebUIApplication activated event. After this event, the WinRT is ready.</p>
<p>· ready – Happens after both loaded and activated events. </p>
<p>· unloaded – Happens before application is unloaded. </p>
<p>The following default.js file has been modified to capture each of these events and write a message to the Visual Studio JavaScript Console window:
<pre class="brush: js;">(function () {
    "use strict";

    var app = WinJS.Application;

    WinJS.Application.onloaded = function (e) {
        console.log("Loaded");
    };

    WinJS.Application.onactivated = function (e) {
        console.log("Activated");
    };

    WinJS.Application.onready = function (e) {
        console.log("Ready");
    }

    WinJS.Application.onunload = function (e) {
        console.log("Unload");
    }

    app.start();
})();
</pre>
<p>When you execute the code above, a message is written to the Visual Studio JavaScript Console window when each event occurs with the exception of the Unload event (presumably because the console is not attached when that event is raised). </p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/image10.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/image_thumb10.png" width="433" height="172"></a></p>
<p>&nbsp;<br />
<h3>Handling Different Activation Contexts</h3>
<p>The code for the activated handler in the default.js file looks like this:
<pre class="brush: js;">app.onactivated = function (eventObject) {
    if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
        if (eventObject.detail.previousExecutionState !== Windows.ApplicationModel.Activation.ApplicationExecutionState.terminated) {
            // TODO: This application has been newly launched. Initialize
            // your application here.
        } else {
            // TODO: This application has been reactivated from suspension.
            // Restore application state here.
        }
        WinJS.UI.processAll();
    }
};
</pre>
<p>Notice that the code contains a conditional which checks the Kind of the event (the value of e.detail.kind). The startup code is executed only when the activated event is triggered by a Launch event, </p>
<p>The ActivationKind enumeration has the following values: </p>
<p>· launch </p>
<p>· search </p>
<p>· shareTarget </p>
<p>· file </p>
<p>· protocol </p>
<p>· fileOpenPicker</p>
<p>· fileSavePicker</p>
<p>· cacheFileUpdater</p>
<p>· contactPicker </p>
<p>· device </p>
<p>· printTaskSettings </p>
<p>· cameraSettings </p>
<p>Metro style applications can be activated in different contexts. For example, a camera application can be activated when modifying camera settings. In that case, the ActivationKind would be CameraSettings. Because we want to execute our JavaScript code when our application first launches, we verify that the kind of the activation event is an ActivationKind.Launch event. </p>
<p>There is a second conditional within the activated event handler which checks whether an application is being newly launched or whether the application is being resumed from a suspended state. When running a Metro application with Visual Studio, you can use Visual Studio to simulate different application execution states by taking advantage of the Debug toolbar and the new Debug Location toolbar.&nbsp;
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/image11.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/image_thumb11.png" width="141" height="39"></a></p>
<p><a href="http://stephenwalther.com/blog/wp-content/uploads/2012/03/image12.png"><img style="background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="http://stephenwalther.com/blog/wp-content/uploads/2012/03/image_thumb12.png" width="101" height="35"></a></p>
<h3>Handling the checkpoint Event</h3>
<p>The default.js file also includes an event handler for the WinJS.Application checkpoint event:
<pre class="brush: js;">app.oncheckpoint = function (eventObject) {
    // TODO: This application is about to be suspended. Save any state
    // that needs to persist across suspensions here. You might use the
    // WinJS.Application.sessionState object, which is automatically
    // saved and restored across suspension. If you need to complete an
    // asynchronous operation before your application is suspended, call
    // eventObject.setPromise().
};
</pre>
<p>The checkpoint event is raised when your Metro application goes into a suspended state. The idea is that you can save your application data when your application is suspended and reload your application data when your application resumes.</p>
<h3>Starting the Application</h3>
<p>The final statement in the default.js file is the statement that gets everything going:
<pre class="brush: js;">app.start();
</pre>
<p>Events are queued up in a JavaScript array named eventQueue . Until you call the start() method, the events in the queue are not processed. If you don’t call the start() method then the Loaded, Activated, Ready, and Unloaded events are never raised. </p>
<h3>Summary</h3>
<p>The goal of this blog entry was to describe the contents of the default.js file which is the JavaScript file which you use to kick off your custom code in a Windows Metro style application written with JavaScript. In this blog entry, I discussed the module pattern, JavaScript strict mode, handling first chance exceptions, WinJS Application events, and activation contexts.</p>
<div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/StephenWalther?a=o3Wg0uhHGok:U4x33LRzi0M:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/StephenWalther?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/StephenWalther/~4/o3Wg0uhHGok" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://stephenwalther.com/blog/archive/2012/02/24/metro-understanding-the-default-js-file.aspx/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://stephenwalther.com/blog/archive/2012/02/24/metro-understanding-the-default-js-file.aspx</feedburner:origLink></item>
	</channel>
</rss>

