Introduction to HTML5 for ASP.NET Developers

Introduction

More and more web applications are harnessing the power of client side features of a browser. To that end HTML5 has many features to offer web developers. HTML markup, JavaScript and CSS have become more powerful and flexible than ever before. ASP.NET Developers must be well-versed with HTML5 features because all of the leading browsers are aggressively supporting them and newer web applications are bound to rely heavily on them. This article is intended to give you an overview of some key features of HTML5 from a developer's perspective. We won't go into too much detail of new HTML tags, CSS3 and such "markup" level features, instead we will focus on features more appealing to web developers.

Features of Interest

HTML5 is an emerging web standard that has received a great deal of attention from browser companies and the developer community. All of the major browsers, including Internet Explorer, FireFox, Chrome, Safari and Opera have support for HTML5 in varying degrees. Although not all of the browsers support all of the HTML5 features in the same way, web developers can still avail themselves of many of the benefits of HTML5 from the current releases of these browsers. All of these browser companies are aggressively working to provide full-fledge standardized support for HTML5 features. As far as this article is concerned we will focus on the following features of HTML5.

  • Local Storage
  • JavaScript Selectors
  • Web Sockets
  • Web Workers
  • Application Caching
  • Client side drawing
  • Custom attributes

Remember that HTML5 is a collective term used for new HTML elements, JavaScript enhancements and CSS 3 specifications. Throughout the article when we say HTML5 we mean one of these technologies and not just HTML markup tags.

New HTML Markup Tags

HTML5 adds many new tags to the existing set of markup elements. Though we won't discuss each and every tag in detail, here are a few tags that might be interesting to ASP.NET developers.

  • <audio> and <video> tags allow you to embed audio and video inside a web page respectively.
  • Forms can now have new elements - <datalist>, <keygen> and <output>. The <input> element now supports various input types such as url, email and datetime.
  • Elements such as <section>, <header> and <footer> allow you to design a page in a structured manner.

We won't go in too much detail about these tags in this article. See later sections of this article that talk about how various Microsoft tools support HTML5 schema and provide intellisense for these elements.

Local Storage

ASP.NET developers often used cookies to store small pieces of data on the client side. One of the limitations of using cookies is the amount of data that can be saved. For example, many browsers have size limit of 4,096 bytes for a single cookie. HTML5 local storage allows developers to store more data on the client side using JavaScript code. Local storage typically allows you to store up to 5 MB of data (different browsers may have slightly different limits). Local storage comes in two flavors viz. local storage and session storage (together they are often called Web Storage). Local storage is persisted on the client machine across browser sessions whereas session storage is persisted only for the current session. These storages can be accessed via JavaScript using localStorage and sessionStorage objects. The following code fragment illustrates how data can be saved and retrieved in localStorage object.

function SetData() {

    window.localStorage["myKey"] = document.getElementById("Text1").value;

    alert("Data saved!");

}

 

function GetData() {

    document.getElementById("Text2").value = window.localStorage["myKey"];

}

As you can see the SetData() JavaScript function stores values from a textbox into a localStorage key named myKey. The GetData() function then retrieves the previously stored key and assigns the value to another textbox. The localStorage and sessionStorage objects also expose methods to remove and clear items from the respective storages.

JavaScript Selectors

If you used JavaScript before you are probably aware of getElementById() and getElementByTagName() methods. These methods return elements based on supplied parameter (either ID or tag name). JavaScript now has two more selector methods viz. querySelector() and querySelectorAll(). The former method returns the first element from the matched result set whereas the later method returns all of the matching elements. The following code fragment shows how these methods can be used.

<ul>

<li id="id1" class="class1">ASP.NET</li>

<li class="class1">Windows Forms</li>

<li id="id2" class="class1">jQuery</li>

<li class="class2">MVC</li>

<li class="class2">WCF</li>

</ul>

var item = document.querySelector("li.class1");

alert(item.innerHTML);

var items = document.querySelectorAll("li.class1");

alert(items.length + " items found!");

var items = document.querySelectorAll("#id1,#id2");

alert(items.length + " items found!");

The call to querySelector() method returns the first <li> element whose class attribute is set to class1. Similarly, querySelectorAll() method that follows returns all the <li> elements whose class attribute is set to class1. The second call to querySelectorAll() method returns all the elements that have specified ID attribute.

Web Sockets

If you have ever programmed a desktop chat application then probably you are aware of socket programming. Web Sockets is essentially socket programming for web applications. Currently a popular approach to ping back server for some processing is AJAX. However, AJAX communication involves the client browser polling the server periodically. Web sockets, on the other hand, provide a two way communication channel where the server can send data to the client browser. The Web socket feature is still in evolving stages and there are concerns over security. In the days to come we may expect a standardized and secure form of web sockets supported by all of the leading browsers. 

Web Workers

Web workers bring multithreading to browser based applications. Web workers essentially allow you to load and execute a JavaScript file in a separate thread without affecting the responsiveness of the user interface. Not all browsers support web workers at this stage. A sample code fragment, shown below, shows how web workers can be used in FireFox.

HTML page

==========

var worker = new Worker("MyWorker.js");

worker.postMessage("Hello World");

worker.onmessage = function (evt) {

    alert(evt.data);

};

worker.onerror = function (evt) {

    alert("Error : " + evt.data);

};

MyWorker.js file

==================

onmessage = function (evt) {

    postMessage("Data processed : " + evt.data);

};

As you can see the Worker object refers to a JavaScript file to be loaded in a separate thread. The postMessage() method is used to send data to the code being executed from the file. The onmessage function displays the data received back from the code. The entire processing of MyWorker.js is happening in a separate thread and the end user is free to work with the web page user interface. 

Application Caching

Web applications require a live connection with the server in order to work properly. This always connected behavior can create problems of its own when the server goes offline for some reason or the network connection is lost temporarily. The Application Caching features of HTML5 tries to address these scenarios in two ways - client side SQL database (Web SQL) and Offline Application Caching APIs. In the former approach a local SQL database is used to store a local copy of data on which the user can work. The later approach makes use of a Cache Manifest file that stores a list of files that are to be cached locally. Note that the SQL database option (though initially proposed by W3C) is no longer actively pursued by W3C and may not become a standard across all the browsers.

Client Side Drawing

One of the reasons for the popularity of the web is the graphical user interface they offer to the end user. Images, animations, fonts and other interactive effects make a website appealing from an end user's perspective. However, one limitation that website developers often encounter is drawing graphics in the browser. As a solution, developers often resort to Flash or Silverlight based plug-ins or generate graphics on the fly at server side and then send it to the client. HTML5 does a great job in client side graphic rendering by offering what is known as the Canvas. The actual drawing can be carried out using JavaScript code and certain new graphic objects.

The HTML5 Canvas is very similar to a real life drawing canvas in that it allows you to draw shapes, text, backgrounds and many such drawing operations. Of course, HTML5 Canvas is browser based and is measured in pixels. At HTML markup level canvas is represented by the <canvas> tag. A basic usage of <canvas> tag is shown below.

<canvas id="myCanvas" width="500" height="500"></canvas>

Consider the following piece of code:

var myCanvas = document.getElementById('myCanvas');

var context = myCanvas.getContext('2d');

context.fillRect(10,10, 200, 100);

context.beginPath();

context.moveTo(125,350);

context.lineTo(100,600);

context.lineTo(45,450);

context.closePath();

context.stroke();

context.font = '20pt Arial';

context.fillText('Drawing text on the Canvas', 0, 100);

As you can see the getContext() method of canvas object returns a rendering context object. Various methods of the rendering context object such as fillRect(), lineTo() and fillText() allow you to draw on the canvas.

Custom Data Attributes

Traditionally HTML elements have a fixed set of attributes that can be assigned (either through markup or via JavaScript code). HTML5 introduces what is known as Custom Data Attributes that allow you to define custom attributes for an HTML element. These custom data attributes won't affect the user interface of the element in any way but you can access and manipulate them via JavaScript code. These attribute take the form of data-* where * is any custom name. e.g. data-firstname, data-birthdate and data-validationmessage. The following code shows how custom data attributes can be used.

<input type="text" id="Text1" data-validationmessage="Invalid Birth Date" />

<br />

<br />

<input type="button" value="Show Custom Data Attribute" onclick="OnClick();"/>

Notice how data-validationmessage defines a validation message for a textbox. The value of data-validationmessage attribute can then be retrieved as follows:

function OnClick() {

    var text1 = document.getElementById("Text1")

    alert(text1.getAttribute("data-validationmessage"););

    text1.setAttribute("data-validationmessage", "Birth date is invalid")

    alert(text1.getAttribute("data-validationmessage"));

}

The getAttribute() and setAttribute() methods essentially get and set the custom attribute value respectively. It would be interesting to note that ASP.NET MVC3 un-obstructive validation makes use of custom data attributes.

Now that you know about what HTML5 has to offer, let's see how Microsoft development tools support HTML5 markup. Note that these tools basically support HTML5 markup schema. Support for new JavaScript objects and code level features should come from the target browser.

HTML5 Support in Visual Studio 2010

When Visual Studio 2010 was released there was no in-built support for HTML5 schema and tags. However, Service Pack 1 fills that gap. With Visual Studio SP1 installed you can turn HTML5 support on using Tools > Options menu as shown below:

Visual Studio SP1 HTML5 support
Figure 1: Visual Studio SP1 HTML5 support

As you can see the HTML schema is set to HTML5. This will cause the HTML editor of Visual Studio to show HTML5 option like this:

The HTML schema is set to HTML5
Figure 2: The HTML schema is set to HTML5

You can then use intellisense for new HTML5 tags inside the pages. 

Intellisense for new HTML5 tags
Figure 3: Intellisense for new HTML5 tags

The future versions of Visual Studio will, of course, enhance and extend these features further.

HTML5 Support in Microsoft Expression Web

Microsoft Expression Web 4 also follows the path of Visual Studio for providing HTML5 support. When you install Service Pack 1 for Expression Web 4 you are able to set HTML5 schema using Tools > Page Editor Options menu item.

Microsoft Expression Web 4 Service Pack 1 Page Editor Options
Figure 4: Microsoft Expression Web 4 Service Pack 1 Page Editor Options

Notice the section titled "Doctype and Secondary Schema" that allows you to select the HTML5 option. Once selected you can get intellisense for HTML5 specific tags similar to Visual Studio 2010. 

HTML5 Support in WebMatrix

HTML5 support in WebMatrix is quite straightforward. When you create a new HTML page all you get is :

WebMatrix new HTML page
Figure 5: WebMatrix new HTML page

As you can see, unlike the default template of Visual Studio, this template is simple with DOCTYPE set to html. This is what is sufficient to start writing an HTML5 page.

Summary

HTML5 offers many new features for any ASP.NET developer. In addition to new markup tags, features such as local storage, JavaScript selectors, web sockets, web workers, client side drawing  and custom data attributes are important from an ASP.NET developer's perspective. Current Microsoft development tools such as Visual Studio 2010, Expression Web 4 and WebMatrix provide support for HTML5 schema through service packs and we can expect enhanced support for HTML5 in their future releases.



About the Author

Bipin Joshi

Bipin Joshi is a blogger and writes about apparently unrelated topics - Yoga & technology! A former Software Consultant by profession, Bipin has been programming since 1995 and has been working with the .NET framework ever since its inception. He has authored or co-authored half a dozen books and numerous articles on .NET technologies. He has also penned a few books on Yoga. He was a well known technology author, trainer and an active member of Microsoft developer community before he decided to take a backseat from the mainstream IT circle and dedicate himself completely to spiritual path. Having embraced Yoga way of life he now codes for fun and writes on his blogs. He can also be reached there.

Downloads