April 2011 - Posts
Working with Client-Side Storage Using datajs Store API
One of the interesting features that datajs library includes is a store API which abstract the use of client-side storage mechanisms. You can use the store API in order to have a storage layer in your client-side and therefore reduce the calls for the server. Since datajs is only in alpha then this API might change in the future but even so I’ll explain and show a how to use it in this post.
datajs Storage Options
datajs currently provides an abstraction layer on top of the following three client-side storage options:
- In-memory – the datajs team implemented an in memory storage mechanism that can be used with the datajs library.
- DOM Storage – I wrote about this client storage type in the past. Most of the new browsers (IE, Chrome, Firefox, Opera and more) include implementation for DOM Storage which is a key-value dictionary that exists on client-side.
- IndexedDB – this is a new HTML5 specification that is being developed these days and therefore it is only experimental. Most of the browsers haven’t implemented this feature yet. Even so, datajs team is exploring this option and when the browsers will provide IndexedDB implementation you’ll be able to use it through datajs.
datajs Store API
The first thing that you’ll want to do when you use the store API is to create the storage object. In order to do that you will have to call the createStore function. The function gets two parameters – the name of the storage and the mechanism to use underneath. The mechanism parameter is optional and can get one of the following options:
- best – datajs will use the modern API that exists in the user’s browser. This is the default value so if you won’t provide a value to the mechanism parameter datajs will choose the best option for you.
- memory – datajs will use the in-memory implementation that is provided in the library.
- dom – datajs will use the Dom Storage implementation.
- indexeddb – datajs will use the IndexedDB implementation.
Here an example of creating a new storage object that uses Dom Storage:
var store = datajs.createStore('MyStorage', 'dom');
After you have created the store object you can start using the store API. The API includes many simple functions such as add, remove, update, lookup and more. For further reading about those methods go to store API page. One of the things that you will notice about the API is that all the API functions work asynchronously (they get success and error callbacks).
datajs Store API Example
Lets look at a simple example:
<!DOCTYPE html>
<html>
<head runat="server">
<title>datajs Example</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js" type="text/javascript"></script>
<script src="Scripts/datajs-0.0.3.min.js" type="text/javascript"></script>
</head>
<body>
<form id="form1">
<div>
Insert data into drop down list. The data is saved into datajs storage.
<div>
<input type="text" id="data" /><input type="button" id="btnInsert" value="Save" />
</div>
<div>
<select id="storedData">
</select>
</div>
</div>
<script type="text/javascript">
var store;
$(document).ready(function () { store = datajs.createStore("MyStorage"); $("#btnInsert").click(function () { var insertedValue = $("#data").val(); store.add(insertedValue, insertedValue,
function (key, value) { $(document.createElement("option")).val(value).text(key).appendTo($("#storedData")); }, function (error) { alert(error.message);
});
});
})
</script>
</form>
</body>
</html>
Lets explore the example. First of all you can see that I use jQuery along with datajs. datajs is a library that is focusing on handling data which is a complimentary to things that jQuery does. So you can choose to use jQuery, datajs or both of them in the same application. In the sample, I’ve created a simple page that insert data from a textbox into a drop down list. As a side affect the data is also saved into a client-side storage. In the JavaScript code I first create the storage using the createStore function. Since I’m not giving a mechanism as a second parameter the datajs will use the best mechanism that exists in my browser. I then wire the click event for the insert button. The event will extract the value from the textbox and insert it into the datajs created storage using the add function. After the successful insert the success callback function will be called and will insert the data into the drop down list. If an error occurs the error callback will alert the user of the error.
Summary
In this post I gave you a simple taste of datajs’s store API. If this is something that interests you the datajs team looks for feedback about their decisions. Some of their questions are written in the store API page.
I Have Joined The Conversation
One picture is worth a thousand words:

Making a JSONP Call to a WCF Data Service using datajs
During MIX11 I attended a very interesting session about datajs which was
presented by Asad Khan and Marcelo Lopez Ruiz. As I promised in my previous post, in this post I’ll show you how to make a JSONP call to a WCF Data Service using datajs library.
A Little About datajs
datajs is a very promising JavaScript library which is currently being built by Microsoft as an open source in CodePlex. The library as described in its CodePlex site is “a new cross-browser JavaScript library that enables data-centric web applications by leveraging modern protocols such as JSON and OData and HTML5-enabled browser features. It's designed to be small, fast and easy to use”. Some of it current features are the ability to communicate with OData services and APIs to work with local data through browser features such as Web Storage (and in the future IndexedDB). For further reading about datajs go to the its documentation or download the library and play with it (there is also a NuGet package for it).
Making JSONP Call using datajs
Here is the implementation of the same JSONP call functionality from the previous post but using datajs:
<!DOCTYPE html>
<html>
<head id="Head1" runat="server">
<title>JSONP Call using datajs</title>
<script src="Scripts/datajs-0.0.3.min.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<output id="result">
</output>
</form>
<script type="text/javascript">
OData.defaultHttpClient.enableJsonpCallback = true;
OData.read("http://localhost:23330/SchoolDataService.svc/Courses",
function (data, request) {
var output = document.getElementById('result');
for (var i = 0; i < data.results.length; i++) {
var div = document.createElement('div');
div.innerHTML = data.results[i].Title;
output.appendChild(div);
}
});
</script>
</body>
</html>
A few things to notice in the example:
- I add the script to datajs which exists in my web application project under the Scripts directory.
- You need to enable JSONP through the OData.defaultHttpClient.enableJsonpCallback which is disabled by default.
- Use the OData.Read function to make the call to the service (no need to add the format or callback query parameters like I did in the previous post since they are added automatically).
Pay attention that in a real world application you would probably like to disable JsonpCallback after you make the call.
Summary
datajs is still in Alpha version and it is only in its starting point. It tries to provide a common solution around the data problem in the client side development. I expect it to grow and to supply more capabilities in the future. In this post I showed how to use it in order to make a JSONP call to a JSONP enabled WCF Data Service.
Combining WCF Data Services, JSONP and jQuery
During Mike Flasko’s session at MIX11,
he showed how to create a JSONP aware WCF Data Service with a JSONPSupportBehavior attribute that is available for download from MSDN code gallery (and is supposed to be a part of Microsoft.Data.Services.Extensions namespace). In this post I’ll show a simple example that uses the attribute and jQuery in order to make a JSONP cross domain call for a WCF Data Service.
Setting up the Environment
First I started by creating two different ASP.NET web applications. The first application includes the calling page and the second includes the WCF Data Service. Then, I created in the second web application an Entity Framework model and the WCF Data Service from that model. I also added the JSONPSupportBehavior.cs class that exists in the link I supplied earlier. The class includes the implementation of JSONPSupportBehavior which implements the WCF IDispatchMessageInspector interface. Also it includes the JSONPSupportBehaviorAttribute which I use in my code. The code is simple and looks like:
[JSONPSupportBehavior]
public class SchoolDataService : DataService<SchoolEntities>
{
// This method is called only once to initialize service-wide policies.
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}
}
Making the JSONP Call
In the second web application I’ve created a web form that will hold the JSONP call example. Here is the code that makes the call:
<!DOCTYPE html>
<html>
<head runat="server">
<title>JSONP Call</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js" type="text/javascript"></script>
</head>
<body>
<form id="form1" runat="server">
<output id="result">
</output>
</form>
<script type="text/javascript">
$.getJSON('http://localhost:23330/SchoolDataService.svc/Courses?$format=json&$callback=?',
function (response) {
$.each(response.d, function (index, value) {
var div = document.createElement('div');
div.innerHTML = value.Title;
$('#result').append(div);
})
});
</script>
</body>
</html>
Lets explore the web form code:
At first I use Microsoft CDN in order to retrieve the jQuery library. Then, I’ve created a HTML5 output element in order to append to it the output of the call. In the main script I use jQuery’s getJSON function which is calling the WCF Data Service. Pay attention that in order to get a JSON response from the WCF Data Service you need to use the $format=json query string parameter. After I retrieve the data I iterate and create a div element for each course title that was retrieved. This is done in the success function that I wired in the getJSON function call. Here is the output of running the code:

Summary
In the post I supplied a simple example of making a JSONP call to a WCF Data Service using jQuery. This sort of solution can help you to consume WCF Data Services that exists in other domains from your client side. In a follow up post I’ll show the same example using the new datajs library.
Configuring WCF Data Services using Lambda Expressions
One of the things that I avoid when I’m writing code is the use “magic strings”.
Hardcoded strings are a code smell and should be rarely used. When using WCF Data Service configuration object you’ll have to pass the entity set’s string name to the configuration methods which as I wrote I would like to avoid. This is why in today’s post I’m going to extend the DataServiceConfiguration object to support lambda expressions instead of string parameters.
Data Service Configuration Extensions
I’ve created a simple static class that includes two new extension methods: SetEntitySetAccessRule<DataSource> and SetEntitySetPageSize<DataSource>. Both of the methods extends the DataServiceConfiguration object and add the functionality of receiving a lambda expression that will hold the entity set name. Here is the class implementation:
public static class DataServiceConfigurationExtensions
{ public static void SetEntitySetAccessRule<DataSource>(this DataServiceConfiguration config,
Expression<Func<DataSource, object>> expression,
EntitySetRights rights)
where DataSource : class
{ string entitySetName = GetEntitySetName(expression);
config.SetEntitySetAccessRule(entitySetName, rights);
}
public static void SetEntitySetPageSize<DataSource>(this DataServiceConfiguration config,
Expression<Func<DataSource, object>> expression,
int pageSize)
where DataSource : class
{ string entitySetName = GetEntitySetName(expression);
config.SetEntitySetPageSize(entitySetName, pageSize);
}
private static string GetEntitySetName<DataSource>(Expression<Func<DataSource, object>> expression)
{ MemberExpression memberExpression = expression.Body as MemberExpression;
if (memberExpression == null)
{ throw new ArgumentException("Must be a member expression"); }
return memberExpression.Member.Name;
}
}
And here is how you’ll use this implementation while configuring your data service:
public class SchoolDataService : DataService<SchoolEntities>
{ public static void InitializeService(DataServiceConfiguration config)
{ config.SetEntitySetAccessRule<SchoolEntities>(c => c.Courses, EntitySetRights.All);
config.SetEntitySetPageSize<SchoolEntities>(c => c.Courses, 10);
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
}
}
Now, if a name of an entity set will change you’ll get compilation error instead of runtime error. Also this way is less error prone and it is more clean. Since the InitializeService method is being called only once then the impact on performance is negligible.
Summary
Using “magic strings” is a bad habit. In this post I showed a simple solution for using lambda extensions instead of strings while configuring a WCF Data Service.
Spreading Inheritance Tree Mapping Across Assemblies in Code First
Today I helped a client to solve a problem regarding EF4.1 Code First.
The issue that they banged their heads with was an inheritance tree mapping in their model which is spread across two different assemblies. When they run the application they always got the same exception – “mapping and metadata information could not be found for entitytype ‘entity name’”. So they sent me a sample solution and I checked it and gave them the solution.
The Client Provided Model
In one class library there are the following two classes:
namespace CodeFirstTest
{
public class Base
{
public int Id { get; set; }
}
public class DeriveB : Base
{
}
}
In another console application there is another derived class for the Base class:
namespace CodeFirstTest
{
public class DeriveA : Base
{
}
}
Also, in the same console application they have created the context:
namespace CodeFirstTest
{
public class TheContext : DbContext
{
public TheContext()
{
}
public DbSet<Base> MyModel { get; set; }
}
}
Running the following code will produce the “mapping and metadata information could not be found for entitytype ‘entity name’” exception:
namespace CodeFirstTest
{
class Program
{
static void Main(string[] args)
{
Database.SetInitializer<TheContext>(new DropCreateDatabaseIfModelChanges<TheContext>());
using (TheContext ctx = new TheContext())
{
var obj1 = new DeriveA();
ctx.MyModel.Add(obj1);
var obj2 = new DeriveB();
ctx.MyModel.Add(obj2);
obj2 = new DeriveB();
ctx.MyModel.Add(obj2);
ctx.SaveChanges();
}
using (TheContext ctx = new TheContext())
{
var res = ctx.MyModel.Where(b => b.Id == 2).SingleOrDefault();
}
}
}
}
The Solution
First I reproduced the exception and then tried to figure out what might be the mapping error that they get. Since the problem is in the entity type mapping then it must be caused by things like:
- Type mismatches
- Misspelled properties
- Properties that are missing
- More
The solution to the problem is to add mapping to all the entities in the context. In order to do that you will have to override the OnModelCreating method and map all the entities:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Base>();
modelBuilder.Entity<DeriveA>();
modelBuilder.Entity<DeriveB>();
}
This solves the problem and produces the relevant database when the console application is running.
Summary
It took me a short period of time in order to find the mapping problem that my client had. The solution for the problem is simple but I would expect that Code First will supply the solution within. Maybe in vNext…
Wrapping Up the MIX11 Experience
I got back home yesterday’s evening after ~20 hours on flights.
This is the time to wrap up the MIX11 conference experience. Here are all the posts I wrote during the conference:
Summary of MIX11 announcements -
- IE10 Preview 1 was released and can be download from here
- A new tools update for ASP.NET MVC3 was released
- WebMatrix got an update
- Windows Azure has some new features
- The next version of Windows Phone 7 – Mango – is coming soon
- Silverlight 5 beta is available for download
- Kinect Windows SDK is being built and will be available soon
I got to meet a lot of new people and also hooked up with people I met in MIX10. All in all, since I came with no expectations then I can tell that the conference was better then MIX10 in its content but there were less announcements then in last year.
MIX11 Third Day Sessions Summary
Here is a summary of the sessions I attended in the third day of MIX11:
The Future of HTML5
In the session Giorgio Sardo talked about
- What is HTML5? – HTML’s new specifications which are getting specified by W3C, IETF and ECMA in working groups for each specification out of ~100 specifications.
Microsoft thinks that HTML5 is ready to go to Last Call phase in May 2011 – meaning it will need to go to RC and then recommendation afterward. - Microsoft approach for HTML5 – releasing every 8-12 weeks new previews for IE in order to get feedback from developers (IE9 had 8 previews). Microsoft invest a lot in interoperability in order that all the browsers will work in the same way. Microsoft innovate with emerging standards by putting new implementations of standards in the HTML5 labs site as experiments.
- HTML5 labs – You can find there experiment prototype implementation for WebSockets, IndexedDB, FileAPI and Media Capture API and to test it yourself and of course deliver feedback to Microsoft about the prototypes. Microsoft suggested new specifications to W3C like tracking protection, speech API and more.
- HMTL6 – Microsoft vision about HTML next version – introduction of interoperability process, future proof innovation, background compatibility and modularization specifications and focus efforts.
Things that Giorgio expects in the future – better integration of SVG + HTML + CSS, DRM video, Full Screen APIs, better device support and accessibility.
OData Roadmap
Pablo Castro talked about what to expect of vNext of Open Data Protocol. Pablo introduced OData and then deep dive into the features to expect in vNext:
- Functionality -
- Better queries – new “any” and “all” filter operators, conditions on collections of related entities and nested queries.
- Better inheritance support – allow navigation properties in subtypes and unlocking full use of inheritance in models.
- Geospatial support.
- Efficiency -
- Refreshing data – using a new link in the protocol which the rel attribute’s value is http://odata.org/delta to indicate what is the refresh policy or in JSON “__delta” property in the JSON object. OData Paging feature and deltas will work together.
- Extensibility
- For metadata, query language, wire formats and more. This will be achieved by using Shared Vocabularies.
- In a few months the new features that were discussed in the session will be released. The implementation in .NET should be expected around Q1 of 2012.
WCF Web APIs
In the session Glenn Block talked about the rational for building the WCF web API framework. Then Glenn drilled down into the framework. He showed how standards play well with Web API implementation with an example using of HTML5 WebSockets. Then he built a web site using the Web API.
For further information about WCF Web APIs go to WCF community site.
Data in HTML5 World
The session started by presenting classic web applications (using Ajax and server platforms). The session discussed how to create data centric web application. Asad Khan and Marcelo Lopez Ruiz presented datajs which is a cross browser JavaScript library which is focusing on data and all the data implementation in HTML5 such as Local Storage. It also support full write-back to servers, batching, pre-fetching, metadata, cache configuration, eviction policy, works over Web Storage today and in the future with IndexedDB. In old browsers you will also get the same experience since the library has a fallback implementation.
You can use NuGet in order to grab datajs and to explore it or get it from here.
MIX11 Second Day Sessions Summary
Here is a summary of the sessions I attended in the second day of MIX11:
An Overview of the MS Web Stack of Love
In the session Scott Hanselman showed a lot of demos in the Microsoft web platform.
The things that Scott showed:
- ASP.NET MVC 3 + new tools
- IIS Express
- NuGet
- EF4.1
- Glimpse – a new open source package which is FireBug like tool for MVC framework.
Get the insight of the flow of your MVC application.
Knockout.js: Helping you build dynamic JavaScript UIs with MVVM and ASP.NET
Steve Sanderson presented a small introduction to knockout.js library. The library enables rich client-side interactivity, MVVM pattern and wide browser support. What it does is automatic dependency tracking, declarative binding and integrated templating. You can download the library from here.
Building Data-Centric N-Tier Applications with jQuery
Brad Olenick talked a little about what is coming in vNext for WCF Data Services which will include jQuery client, AppFabric integration and rich OData support. Then Brad presented the jQuery client for WCF Data Services – RIA/JS.
RIA/JS is available in two ways:
Scaffolding
Steve Sanderson explained what is scaffolding (generating code to make the process of development faster) and then deep dive into demos of GUI scaffolding, command-line scaffolding, T4 templates customization and more.
Reactive Extensions for JavaScript (RxJS)
Brat De Smet talked about a new JavaScript library that introduces JavaScript observable sequences and observers which help to implement the asynchronous programming with abstraction to scenarios like timers, XMLHTTPRequests, jQuery Ajax requests and more.
This is it for the second day of MIX11.
MIX11 Second Keynote Session Summary
I’m currently attending the MIX11 second keynote session.
Here are some of the things that you might consider to checkout in the following weeks:
- The next version of Windows Phone 7 – Mango – is coming
- 16 additional languages will be added in the next version (still without Hebrew)
- More countries will be added for apps creation
- More countries will be added for apps commerce
- Mango will include new features like
- Search capability for your installed apps
- Search extras that are connected to you search results
- Mango will include support for IE9 as a browser for the phone
- Meaning that the same markup on PC can be viewed in the phone (but will less capability for hardware acceleration)
- HTML5 support included in IE9 and now in the phone browser
- Phone integration
- Metro UI controls
- Live Tiles
- Custom ringtones
- Sockets
- Database
- More launchers and choosers
- Raw camera access
- Raw Compass access
- Raw Gyro access
- Motion sensor API will be available on Mango
- Multi-tasking support in Mango
- Fast apps switching
- Background: Audio, downloads, alarms etc.
- Live Agents in order to save battery
- Angry Birds app will be available May 25th

- Developer tools for Mango will be available next month
- Improved emulator – location, gestures and more
- New profiling support (identify hot spots in your app for example)
- Performance enhancements in Mango
- Scrolling and input
- Image decode
- Garbage collection
- Memory usage
- 1500 new APIs in Mango. For example
- Local SQL CE database
- Network sockets support
- Silverlight and XNA combination
- Silverlight 5 beta is available for download
- Hardware decode
- Trickplay
- Remote controls support
- A lot of new APIs such as 3D, Data Binding debugging and more
- Kinect Windows SDK is being built and will be available soon
P.S – Every attendee in the conference is getting a Kinect sensor 
MSDN Session: Internet Explorer 9 & HTML5 Videos
On March 30th I had a MSDN session about IE9 and HTML5. The session was recorded and can be viewed (in Hebrew) in two parts:
- Part 1 - available for watching in Channel9
- Part 2 - available for watching in Channel9
Enjoy!
MIX11 First Day Sessions Summary
In the first day at MIX11 conference I attended the following sessions:
Hot from the Labs – HTML5 WebSockets
The first session after the keynotes was about HTML5 Web Sockets which has a Microsoft first draft implementation on HTML5 Labs. The concept of “Real Time Web” is very crucial and hard to implement (using push or polling messages to and from the client). In order to address the problem of client server communication (Bidirectional, Single TCP socket, In & Out of the browser and more) the HTML5 Web Sockets specification was created. The Specifications contain two specification groups: IETF WebSockets protocol and W3C WebSockets API. After the introduction Paul Batun showed the audience how to use the API from HTML5 Labs WebSockets implementation (using the WebSocketsService base class, overriding the OnMessage method and building a WebSocketHost in console application) and built a Hello World demo. Paul also showed the WebSockets URI conventions and a little bit about the client server handshake. It was a very interesting session.
Visit HTML5 Labs for more details and start working with the WebSockets prototype.
50 Performance Tricks to Make Your HTML5 Web Sites Faster
Jason Weber talked about things like an inside look at browser performance and how it is important to understand it, principles for web performance, and then gave a deep dive into 50 specific rules for performance tuning in a web site. Here is the list of 50 best practices he suggest:
- Quickly respond to network request
- Careful about redirect, avoid metadata refresh
- Minimize the server time for requests
- Use CDNs (Content Distribution Network)
- Maximize concurrent connections
- Reuse connections
- Minimize Bytes Downloaded
- GZIP compress network traffic
- Provide cacheable content
- Send conditional requests (If-Modified-Since header)
- Cache data requests in browser cache
- Standardize on file capitalization convention
- Efficiency Structure Static Markup
- Load pages in latest browser mode (HTML5)
- Use HTTP header to specify legacy IE modes (for example X-UA-Compatible meta tag)
- Link Style sheets at top of page
- Never link style sheets at bottom of page
- Avoid using @import for hierarchical styles
- Avoid embedded and inline styles
- Only include necessary styles
- Optimize Media Usage
- Image Formats: PNG (by default), JPEG, JPEG-XR
- Use native image resolutions
- Avoid death by 1000 images (don’t download ton of images)
- Use image sprites
- Create your sprites by hand
- Replace images with CSS3 gradients
- Replace images with CSS3 border radius
- Embed small images through DataURI (specify an image as a 64 byte string)
- Replace large images with inline SVG
- Avoid complex SVG paths
- Video: user preview images
- Leverage CSS3 transforms
- Proactively download your next resource
- Write Fast JavaScript
- Avoid linking JavaScript in head
- Avoid inline JavaScript
- Link JavaScript at end of file
- Use the defer attribute when head is the only option
- Remove duplicate code
- Standardize on a single framework
- Don’t include script to be cool
- Minify your BLOCKED SCRIPT character removal
- Minify your BLOCKED SCRIPT compaction
- Minify your BLOCKED SCRIPT inlining
- Initiate JavaScript on DOMContentLoaded event
- Initialize JavaScript on demand
- JSON is always faster than XML for data
- Use native JSON methods
- Use regular expressions sparingly (never include regular expression in page load)
- Ceil/Floor your double precision floats
- Minimize DOM interactions
- Built in DOM methods always more efficient
- Use .innerHTML to construct your page
- Batch markup changes
- Maintain a small and healthy DOM (keep the elements number below 1000)
- Know What Your Running Application is Doing
- Understand JavaScript timers (setTimeout, setInterval)
- Minimize and align timers
- Align animation to the display frame (16.7)
Pragmatic JavaScript, jQuery & Ajax with ASP.NET
Damian Edwards talked about Ajax Control Toolkit which got an update on 1 April ,jQuery and Nuget support for jQuery versioning , how to build a simple jQuery plugin (by showing a isDirty plugin), Unobtrusive and JQuery UI, Comet implementation with a HTTP Handler, a little bit about Knockout js and Amplify js. A lot of information in one hour session.
That is all for today.
MIX11 Keynote Session Summary
I’m currently attending the MIX11 Keynote session. Here are some of the things that you might consider to
checkout in the following weeks:
- IE10 Preview was released and can be download from here.
- A new tools update for ASP.NET MVC3 was released and includes:
- EF4.1 support
- jQuery 1.5 and Modernizr support
- Scaffolding support
- New Controller templates
- More
- WebMatrix update
- Orchard CMS new release
- Windows Azure new upgrades
- Access Control Service V2
- Caching
- CDN support
MIX11 Here I Come
Tomorrow I’m flying to Las Vegas in order to attend MIX11 conference.
Since most of my work is web-oriented, it is very natural that I going to the biggest Microsoft web conference and of course the bonus is that it is in Vegas. This is going to be my second round to Vegas and MIX since last year I also attended the conference and enjoyed it.
One of the things I really liked last year was to mix with a lot of passionate professionals and to meet a lot of interesting people. I remind you that if you are going to be there you can meet me. Use my Blog’s Contact Form in order to do that or just grab me in Mandalay Bay’s halls and start talking.
One last thing, Sela Group (the company I work for) is sending 14 senior consultant and senior architects to MIX11. For example you’ll be able to meet Ido Flatow the main writer of WCF 4 MOC course, Shai Raiten Scrat creator, Alex Golesh, and more.
I hope to see you there!
Web Workers in HTML5
Is these application demands sound familiar:
- Using background I/O operations
- Web services polling
- Processing large amount of data
- Running an algorithm in the background
- More
If you are working in Windows environment you will probably use a background worker (or another thread) for achieving these demands in order to make your application more responsive. In web environment this was impossible since JavaScript is a single threaded environment. You couldn’t run multiple scripts simultaneously but you could make hacks by using functions like setInterval. In HTML5 a new API is currently developed in order to enable web applications to run background scripts. In this post I’m going to explain this API – Web Workers – and to show you how you can use them today with most of the major browsers (not including IE9).
What are Web Workers?
Web Workers API is being developed currently. The Web Workers are background workers that run scripts in parallel to their main page. The Web Worker itself is independent of any user interface scripts. They allow thread-like operations on the client side that include message-passing mechanism for coordination or data retrieval. If you expected to have a long-lived process, to have a high start-up performance cost, and a high per-instance memory cost Web Workers can be a good solution.
How to use Web Workers API?
The specification for Web Workers specify two kinds of workers – Dedicated Workers and Shared Workers. The first kind wraps a given task and perform it. The second can have multiple connections and uses ports for posting messages.
The first thing to do in order to use the Web Workers API is to create the worker and pass it an execution script URL. Here is an example for how to do that with Dedicated Workers:
var worker = new Worker('worker.js');
In Shared Web Workers you will create a SharedWorker object instead of Worker object:
var worker = new SharedWorker('worker.js');
When you create a Web Worker it exposes the following events which help the main page to communicate with the worker:
- onerror – signals that an error occurred in the worker
- onmessage – enables to receive worker messages back in the main page. Those messages are raised by the postMessage inner worker event
Also, the worker exposes the following inner functions:
- terminate – stops the worker’s execution
- postMessage – posts a message for the listeners of the onmessage event in the main page
In Shared Web Workers you have an addition inner event – onconnect and also the port object. I won’t discuss Shared Web Workers so you can read about them in the Web Workers current draft. After we understand a little bit about What are Web Workers and their API lets look at an example.
Web Workers Example
The following example shows how to create a Web Worker and run it in order to call a simple Echo web service.
The service echo the data it receives and its implementation looks like:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class EchoService : WebService
{
[WebMethod]
public string Echo(string msg)
{
return msg;
}
}
The only interesting thing here is the ScriptService attribute that enables client scripts to call the service.
Next lets look at the worker.js file:
var xhr;
function getData(url, params) {
try {
xhr = new XMLHttpRequest();
xhr.open('POST', url, false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
postMessage(xhr.responseText);
}
}
};
xhr.send(params);
} catch (e) {
postMessage('Error occured');
}
}
function callWSMethod() {
getData("http://localhost:30051/WebWorkers/EchoService.asmx/Echo?msg=Hello", "msg=Hello");
}
callWSMethod();
In the worker’s script there are two functions. The first function (getData) is used to make the request to the service and to post messages back to the main page when the data returns from the service. The second function (callWSMethod) just call the first function with some test data.
The last piece of code is the main page itself:
<!DOCTYPE HTML>
<html>
<head>
<title>Worker example: Simple Ajax Call</title>
</head>
<body>
<p>
Result:
<output id="result">
</output></p>
<script type="text/javascript">
var worker = new Worker('worker.js');
worker.onmessage = function (event) {
document.getElementById('result').innerHTML = event.data;
};
</script>
</body>
</html>
As you can see the Web Worker is being created by using the worker.js file and a handler is wire to the onmessage event. The handler inserts the data returned by the postMessage function (that exists inside the worker.js) into an output element (a new HTML5 element for outputs). You can try this example on Chrome and then you’ll get the following result:

This is a very simple example and you can start thinking how to take this API to the next level in order to do more interesting things.
Summary
Lets sum up, Web Workers API enables the creation of background scripts which can communicate with the main page. This ability is very powerful and can help web developers to create more responsive UI and to achieve things that couldn’t be achieved in web applications in the past. Currently Web Workers are only a draft but there are browsers that support them currently such as Chrome, FireFox and Opera. For further details about Web Workers you can read the Web Workers current draft.