Maarten Balliauw {blog}

Web development, NuGet, Microsoft Azure, PHP, ...


Creating an ASP.NET MVC application with Google Gears

Offline web applications… This term really sounds like 2 different things: offline, no network, and web application, online. Maarten, you speak in riddles man! Let me explain the term…

You probably have been working with Gmail or Google Docs. One of the features with those web applications is that they provide an “offline mode”, which allows you to access your e-mail and documents locally, when an Internet connection is not available. When a connection is available, those items are synchronized between your PC and the application server. This offline functionality is built using JavaScript and a Google product called Google Gears.

In this blog post, I will be building a simple notebook application using the ASP.NET MVC framework, and afterwards make it available to be used offline.

What is this Gears-thingy?

According to the Google Gears website: Gears is an open source project that enables more powerful web applications, by adding new features to your web browser:

  • Let web applications interact naturally with your desktop
  • Store data locally in a fully-searchable database
  • Run JavaScript in the background to improve performance

Sounds like a good thing. I always wanted to make a web application that I could use offline, too. After reading the tutorial on Google Gears, I learned some things. Google Gears consists of an offline JavaScript extension framework, installed on your PC, together with a SQLite database. Second, there are some different components built on this client side installation:

  • Factory – An object which enables access to all of the following bullets.
  • Blob – Blob storage, the ability to store anything on the client PC.
  • Database – Yes, a database! Running on the local PC and supporting SQL syntax. Cool!
  • Desktop – Interaction with the client PC’s desktop: you can add a shortcut to your application to the desktop and start menu.
  • Geolocation – Locate the physical position of the client’s PC, based on either GPS, Wifi, GSM or IP address location.
  • HttpRequest – Can be used to simulate AJAX calls to the local client PC.
  • LocalServer – A local web server, which can be used to cache certain pages and make them available offline.
  • Timer – A timer.
  • WorkerPool – A class that can be used to execute asynchronous tasks. Think "threading for JavaScript".

Picking some components to work with…

Choices for Google Gears and ASP.NET MVC Have a look at the list of components for Google Gears I listed… Those are a lot of options! I can make an ASP.NET MVC notebook application, and make things available offline in several manners:

  • Read-only offline access: I can use the LocalServer to simply cache all rendered pages for my notes and display these cached pages locally.
  • Synchronized offline access: I can use the Database component of Google Gears to create a local database containing notes and which I can synchronize with the ASP.NET MVC web application.

Note: Also check the architecture page on Google Gears documentation. It covers some strategies on the latter option.

Choices… But which to choose? Let’s not decide yet and first build the “online only” version of the application.

Building the ASP.NET MVC application

Not too many details, the application is pretty straightforward. It’s a simple ASP.NET MVC web application built on top of a SQL Server database using LINQ to SQL. I’ve used a repository pattern to access this data using a defined interface, so I can easily mock my data context when writing tests (which I will NOT for this blog post, but you know you should).

The data model is easy: ASP.NET membership tables (aspnet_Users) linked to a table Note, containing title, body and timestamp of last change.

On the ASP.NET MVC side, I’ve used this repository pattern and LINQ to SQL generated classes using the Add view… menu a lot (check ScottGu’s post on this to see the magic…). Here’s a screenshot of the application:


Feel free to download the source code of the ASP.NET MVC – only application: GearsForMvcDemo - MVC (4.12 mb)

Next steps: deciding the road to follow and implementing it in the ASP.NET MVC application…

Adding Google Gears support (“go offline”) – Read-only offline access

Refer to the choices I listed: “I can use the LocalServer to simply cache all rendered pages for my notes and display these cached pages locally.” Let’s try this one!

The tutorial on Google Gears’ LocalServer states we need a manifest.json file, containing all info related to which pages should be made available offline. Great, but I don’t really want to maintain this. On top of that, offline access will need different files for each user since every user has different notes and so on. Let’s create some helper logic for that!

Autogenerating the manifest.json class

Let’s add a new Controller: the GearsController. We will generate a list of urls to cache in here and disguise it as a manifest.json file. Here’s the disguise (to be added in your route table):


    new { controller = "Gears", action = "Index" }


And here’s (a real short snippet of) the controller, automatically adding a lot of URL’s that I want to be accessible offline. Make sure to download the example code (see further in this post) to view the complete GearsController class.


List<object> urls = new List<object>();

// … add urls …

// Create manifest
return Json(new
    betaManifestVersion = 1,
    version = "GearsForMvcDemo_0_1_0",
    entries = urls


The goodness of ASP.NET MVC! A manifest is built using JSON, and ASP.NET MVC plays along returning that from an object tree.

Going offline…

Next step: going offline! The tutorial I mentioned before contains some example files on how to do this. We need gears_init.js to set up the Google Gears environment. Check! We also need a JavaScript file setting up the local instance, caching data. Some development and… here it is: demo_offline.js.

This demo_offline.js script is built using jQuery and Google Gears code. Let’s step trough a small part, make sure to download the example code (see further in this post) to view the complete file contents.


// Bootstrapper (page load)
$(function() {
    // Check for Google Gears. If it is not present,
    // remove the "Go offline" link.
    if (! || !google.gears) {
        // Google Gears not present...
    } else {
        // Initialize Google Gears
        if (google.gears.factory.hasPermission)

        // Offline cache available?
        if (!google.gears.factory.hasPermission || (store != null && !store.currentVersion)) {
            // Wire up Google Gears
            $("#goOffline").click(function(e) {
                // Create store

                // Prevent default behaviour
        } else {
            // Check if we are online...
            checkOnline(function(isOnline) {
                if (isOnline) {
                    // Refresh data!
                } else {
                    // Make sure "Edit" and "Create" are disabled
                    $("a").each(function(index, item) {
                        if ($(item).text() == "Edit" || $(item).text() == "Create New") {
                            $(item).attr('disabled', true);
                            $(item).click(function(e) {

            // Provide "Clear cache" function
            $("#goOffline").text("Clear offline cache...").click(function(e) {
                // Remove store

                // Prevent default behaviour


What we are doing here is checking if Google gears has permisison to store data from this site on the local PC. If so, it is initialized. Next, we check if we already have something cached. If not, we wire up some code for the “Go offline” link, which will trigger the creation of a local cache on click. If we already have a cache, let’s do things different…

First, we call a simple method on the GearsController class (abstarcted in the checkOnline JavaScript function), checking if we can reach the server. If so, we assume we are online and ask Google Gears to check for updated contents. We always want the latest notes available! However, if this function says we are offline, we look for al links stating “Edit” or “Create New” on the current page and disable them. Read-only we said, so we are not caching “Edit” pages anyway. This is just cosmetics to make sure users will not see browser errors when clicking “Edit”.

 Going offline!

Conlusion for this approach

This approach is quite easy. It’s actually instructing Google Gears to cache some stuff periodically, backed up by an “is online” checker in the ASP.NET MVC application. This approach does feel cheap… I’m just creating local copies of all my rendered pages, probably consuming too much disk space and probably putting too much load on the server in the update checks.

Want to download and play? Here it is: GearsForMvcDemo - Offline (4.11 mb)

Adding Google Gears support (“go offline”) – Synchronized offline access

In the first approach, I concluded that I was consuming too much resources, both on client and server, to check for updates. Not good! Let’s try the second approach: “I can use the Database component of Google Gears to create a local database containing notes and which I can synchronize with the ASP.NET MVC web application.”

What needs to be done:

  • Keep the approach described above: we will still have to download some files to the local client PC. The UI will have to be available. Not that we will have to download all note details pages, but we want the UI to be available locally.
  • Add some more JavaScript: we should be able to access all data using JSON (as an extra alternative to just providing web-based views that the user can work with).
  • The above JavaScript should be extended: we need offline copies of that data, preferably stored in the Google Gears local database.
  • And yet: more JavaScript: a synchronization should occur between the local database and the data on the application server.

Ideally, this should look like the following, having a JavaScript based data layer available:

Google Gears Reference Architecture

Due to a lack of time, I will not be implementing this version currently. But hey, here's a nice blog post that should help you with this option: .NET on Gears: A Tutorial

Conlusion for this approach

The concept of this approach is still easy, but requires you to write a lot of JavaScript. However, due to the fact that you are only synchronizing some basic UI stuff and JSON data, local and server resources are utilized far less than in the first approach I took.


The concept of Google Gears is great! But I seriously think this kind of stuff should be available in EVERY browser, natively, and with the same API across different browsers. Storing data locally may bring more speed to your application, due to more advanced caching of UI elements as well as data. The fact that it also enables you to access your application offline makes it ideal for building web applications where connectivity is not always guaranteed. Think mobile workers, sales people, ..., all traveling with a local web application. Not to forget: Gears is currently also available for Windows Mobile 5 and 6, which means that ultra-mobile people can run your web application offline on their handheld device! No need for specific software for them!

By the way, also check this: .NET on Gears: A Tutorial. Interested in Silverlight on Gears? It has been done!

kick it on

Announcing my book: ASP.NET MVC 1.0 Quickly

ASP.NET MVC 1.0 Quickly It’s been quite a job, but there it is: Packt just announced my very first book on their site. It is titled “ASP.NET MVC 1.0 Quickly”, covering all aspects ASP.NET MVC offers in a to-the-point manner with hands-on examples. The book walks through the main concepts of the MVC framework to help existing ASP.NET developers to move on to a higher level. It includes clear instructions and lots of code examples. It takes a simple approach, thereby allowing you to work with all facets of web application development. Some keywords: Model-view-controller, ASP.NET MVC architecture and components, unit testing, mocking, AJAX using MS Ajax and jQuery, reference application and resources.

That’s it for the marketing part: let’s do a retrospective on the writing process itself. Oh and yes, those are my glasses on the cover. Photo was taken on the beach near Bray-Dunes (France).

When did you have the idea of writing a book?

I'm not sure about that. I've been blogging a lot on ASP.NET MVC last year, wrote an article for .NET magazine, did some presentations, ... It occurred to me that I had a lot of material which I could bundle. Together with that, my project manager jokingly said something like: "When will you write your first book? With all that blogging." So I did start bundling stories. First of all, I overlooked the whole ASP.NET MVC technology (preview 2 at that moment) and decided there were enough topics to talk about. A draft table of contents was built quite quick, but I gave up on writing. Too much information, not enough time, ...

A few weeks later, it must have been around the beginning of May, 2008, I did start writing a first chapter, thinking I'ld see how the writing itself would turn out, if it fit in my schedule, ... It worked out quite well, each 10-20 days gave me a new chapter. I also started looking for a publisher when I was finished with chapter 6 or so. Having reviewed some books for Packt, I contacted them with a proposal for my book.

After having a look at the other 6 upcoming books (here and here), we decided we could go for it, focusing on a hands-on book which rapidly guides you into the wonderful world of ASP.NET MVC.

How was your experience of writing your book?

Looking back, it was an interesting experience. I decided to write in English, which is not my native language. That was actually quite a hard one: writing in English is no problem, but writing a good, solid and interesting piece of text is just not that easy when writing longer texts than the average blog post. Another thing is that I tortured myself writing about a product that was not even beta yet! I started writing with ASP.NET MVC preview 3, updated it all to preview 4, 5, beta, release candidate, ... Lots of changes in the ASP.NET MVC API or concepts meant lots of changes to make in chapters I already wrote. Luckily, I survived :-)

I only contacted a publisher when I had finished 60% of my book. If you are considering writing: don't do this! Contact a publisher at a very early stage: they normally give you lots of advice upfront, which I only received after contacting them. Advice earlier along the way is always better, so that's something I would definately do different.

Speaking of advice: when writing was done, the book entered review phase. Different people received the draft version and could provide comments and suggestions. Thanks Stefan, Troy, Vivek, Jerry, Joydip and people at Packt for your time in reviewing my draft version! Reviewer comments really made the book better and required me to do some small rewrites, elaborate more on certain topics.

What tools did you use for writing?

There are some tools that you really need when writing a technical book. One of them is a text editor, in my case Microsoft Word 2007. Together with that, Visual Studio 2008 and regularly updated ASP.NET MVC versions were required. Being scared of losing data, I decided to also use a source control system for sample code ánd for my Word documents. All of these files were stored in a Subversion repository located on my server, being backed up every day to different locations. Doug Mahugh laughed at me when I said I was using Subversion, but it did a great job!

Other tools I used were Paint.NET and MwSnap, both for creating screenshots in my virtual PC running Windows Vista and Visual Studio 2008. I also used Achievo for time tracking purposes, since I was curious how much time this book writing would actually cost me.

How much time did you spend writing?

First of all, this is not going to be 100% accurate. I did track writing and development time during writing, but I already had a lot of material to work with. But here's an overview (numbers in hours):


That is right: writing a book consumes only a little more than 100 hours! But still, I already had lots of material. I'd say to double the number for an accurate timeframe.

Now I hear the next question coming... Here's the answer already: Yes, I have a girlfriend. We are working on our home (planning phase is done, searching a contractor at the moment), visiting family, doing daily stuff, blogging, work, ... It al worked out to fit together, but still: there have been some busy moments on evenings and weekends. Thanks, people around me, for being patient and caring during these busy moments!

Are you getting rich out of this?

Of course, I can grab a couple of beers (for a couple of times), but don't think writing a book will buy you a car... I just felt that I had lots of valuable information that I had to share, and writing a book seemed like the best option to do that. Creating a "to read"-list? Make sure to add ASP.NET MVC 1.0 Quickly to it.

kick it on

Replacement during my vacation: Wilson

This morning, I arrived at work after a great week of skiing in Pitztal, Austria. Unfortunately, I found my chair occupied by a new colleague looking a bit like Wilson. Good to see he enjoyed working early, like I do. But still, that was my seat and PC he was using… Thank you, dear colleagues, to see myself replaced by a plastic, smiling ball…

Wilson, my replacement

kick it on

Book review: Software Testing with Visual Studio Team System 2008

Software Testing with Visual Studio Team System 2008 Another book review, this time for Packt’s “Software Testing with Visual Studio Team System 2008”. The book introduces you to the main types of testing available in Visual Studio Team System 2008 for both desktop and web applications, and then walks you through deploying, running, and interpreting the results of tests.

The book starts with an overview of why you need testing and then lists all available test types in Visual Studio 2008. It also explains the differences between a stand alone Visual Studio 2008 and a Team Foundation Server backed version. Each chapter thereafter covers one of the test types in detail: unit tests, web tests, advanced web tests, load tests, manual tests, …

Next to these things, more information on how to deploy and run tests on a VSTS build server is provided. And when you work with a VSTS build server, chances are big reporting is enabled. These reports are also covered in detail, showing you how to interpret the data displayed.

I’ve been working with and giving training on Visual Studio 2008 for quite a while now, including a large part on Visual Studio and testing. To be honest, I think this book really covers all aspects of testing in Visual Studio 2008, making it an ideal reference for any development team working with VSTS. Here's the official product page at Packt.

kick it on

Saving a PHPExcel spreadsheet to Google Documents

As you may know, PHPExcel is built using an extensible model, supporting different input and output formats. The PHPExcel core class library features a spreadsheet engine, which is supported by IReader and IWriter instances used for reading and writing a spreadsheet to/from a file.

PHPExcel architecture

Currently, PHPExcel supports writers for Excel2007, Excel5 (Excel 97+), CSV, HTML and PDF. Wouldnt it be nice if we could use PHPExcel to store a spreadsheet on Google Documents? Let’s combine some technologies:

Creating a custom GoogleDocs writer

First, we need an implementation of PHPExcel_Writer_IWriter which will support writing stuff to Google Documents. Since Google accepts XLS files and Zend_Gdata provides an upload method, I think an overloaded version of PHPExcel’s integrated PHPExcel_Writer_Excel5 will be a good starting point.


class PHPExcel_Writer_GoogleDocs extends PHPExcel_Writer_Excel5 implements PHPExcel_Writer_IWriter {
        // ...


Since Google requires to log in prior to being able to interact with the documents stored on Google Documents, let’s also add a username and password field.


class PHPExcel_Writer_GoogleDocs extends PHPExcel_Writer_Excel5 implements PHPExcel_Writer_IWriter {
    private $_username;
    private $_password;

    public function setCredentials($username, $password) {
        $this->_username = $username;
        $this->_password = $password;


Next, let’s override the save() method. This method will save the document as an XLS spreadsheet somewhere, upload it to Google Docs and afterwards remove it from the file system. Here we go:


public function save($pFilename = null) {
        $googleDocsClient = Zend_Gdata_ClientLogin::getHttpClient($this->_username,
                $this->_password, Zend_Gdata_Docs::AUTH_SERVICE_NAME);
        $googleDocsService = new Zend_Gdata_Docs($googleDocsClient);
        $googleDocsService->uploadFile($pFilename, basename($pFilename), null,



Nothing more! This should be our new writer class.

Using the GoogleDocs writer

Now let’s try saving a spreadsheet to Google Docs. First of all, we load a document we have stored somewhere on the file system:


$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load("05featuredemo.xlsx");


Next, let’s use PHPExcel’s IOFactory class to load our PHPExcel_Writer_GoogleDocs class. We will also set credentials on it. Afterwards, we save.


$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'GoogleDocs');
$objWriter->setCredentials('', 'xxxxxxxx');


This should be all there is to it. Google Docs will now contain our spreadsheet created using PHPExcel.

Google Docs Image

Note that images are not displayed due to the fact that Google Docs seems to remove them when uploading a document. But hey, it’s a start!

You can download the full example code here (26.29 kb). Make sure you have PHPExcel, Zend Framework and Zend Gdata classes installed on your system.

New VISUG website online

VISUG - Visual Studio User Group BelgiumLast week, the new VISUG website has been released. VISUG stands for Visual Studio User Group Belgium and is one of the largest .NET related user groups in Belgium, providing technical sessions on different .NET related topics.

This new site not only features a new layout, but also some new features. One of the most useful features is that there now is finally an RSS feed listing upcoming events (such as 19 Februari’s Live Mesh event). The front page now also syndicates blog feeds from different members of the user group, containing lots of useful information regarding .NET. That being said, also check the new MSCommunity site which is a new website that gathers all event information for the main Microsoft user groups in Belgium (Sharepoint, SQL server, ITPro, …)