Showing posts with label Metro. Show all posts
Showing posts with label Metro. Show all posts

Thursday, August 9, 2012

Promises: jQuery deferred object vs WinJS Promise

When I was adjusting my Linq2IndexedDB library to enable Windows 8 development, I had some little issues porting the jQuery promises to WinJS promises. In this post I will show you some differences I had issues with and how I fixed them.

Passing context

The first problem I ran into: WinJS promises doesn’t support passing a context. Because I don’t take advantage of the context yet, this wasn’t an issue for me yet. I easily solved it by writing a wrapper around the 2 promises. In case of the jQuery promise, the context gets passed. And in case of the WinJS promise, I just ignore it for the moment and hope it will get implemented in the future.

   1: function promiseWrapper(promise) {
   2:     if (isMetroApp) {
   3:         return new WinJS.Promise(function(completed, error, progress){
   4:             promise({
   5:                 complete: function (context, args) {
   6:                     completed(args);
   7:                 },
   8:                 error: function (context, args) {
   9:                     error(args);
  10:                 },
  11:                 progress: function (context, args) {
  12:                     progress(args);
  13:                 }
  14:             });
  15:         });
  16:     } else if (typeof ($) === "function" && $.Deferred) {
  17:         return $.Deferred(function (dfd) {
  18:             promise({
  19:                 complete: function (context, args) {
  20:                     dfd.resolveWith(context, [args]);
  21:                 },
  22:                 error: function (context, args) {
  23:                     dfd.rejectWith(context, [args]);
  24:                 },
  25:                 progress: function (context, args) {
  26:                     dfd.notifyWith(context, [args]);
  27:                 }
  28:             });
  29:         }).promise();
  30:     }
  31: }

Passing multiple parameters


A second problem I had was the fact that the WinJS only allows one argument to be passed when calling a complete, error or progress callback. Because I needed to pass multiple values in my library, I needed to rewrite every complete, error and progress method I called. Instead of just passing multiple arguments to the callback methods, I needed to wrap the arguments into an array so they could be passed as single argument.


But that wasn’t enough. Because the jQuery promise is smart enough to convert an array of arguments into a callback with multiple arguments, I needed to wrap the array of arguments into an other array (If you look in the sample above, you will see in case of the jQuery promise, brackets (‘[]’) were added around the args argument.). I needed to do this, because it was the only way to get the same signature when working with the WinJS & jQuery promise.



   1: promiseWrapper(function (pw) {
   2:     pw.complete(context, [arg1, arg2]);
   3: });

Progress Event Doesn’t fire in Winjs promise


The last issue I suffered was the fact that a progress event in didn’t fire in some cases. After a little investigation, I came to the conclusion that I was calling the progress event, before the promise object got created. I first noticed this when I was creating a transaction on the IndexedDB API. When a transaction was created, I fired a progress event with the transaction data. In other methods, where I needed the transaction, I used this the progress call to execute my queries. Once the transaction was committed, the complete event got fired. Because the progress call never got called, the query was never executed. This way the transaction was immediately committed and the complete callback got called without any action taken.


To fix this I delayed the progress call a little bit. By adding a setTimeout of 1 ms I noticed my problem was solved, and my progress events got called.



   1: if (isMetroApp) {
   2:     setTimeout(function () {
   3:         var txn = db.transaction(objectStoreNames, transactionType); 
   4:         txn.oncomplete = function (e) {
   5:             pw.complete(txn, [txn, e]);
   6:         };   
   7:         pw.progress(txn, [txn]);
   8:     }, 1);
   9: }

Conclusion


As seen above working with the WinJS is a slice different of working with the deferred object in jQuery. But with the given workarounds, it is possible to solve the most issues. I hope that Microsoft will take a look at the jQuery deferred object in the future and add some of the jQuery capabilities (context, multiple arguments) into the WinJS promises. And hopefully the progress bug gets solved, so the ugly setTimeout can disappear in my code.

Monday, May 7, 2012

Using LINQ to Indexed DB

While the library is still under development, I want to take some time to explain how you can use this framework, and show how easy it gets to work with the Indexed DB. As mentioned before, the library is based on the on the Promises context. This way we can easily handle all the async callbacks on which the Indexed DB API is based, and provide a uniform object to the developer for handling the results and/or errors. And by using the progress callback, we can provide returning multiple records one by one instead of a whole collection in the complete callback. For more information about promises:

Another strength of the library is, that you get the opportunity to let it auto build it’s structure. It’s not necessary to provide the database structure. You can just start writing queries, and the library will take care of the creation of tables and indexes. This way it can easily be used for writing POCs or demo applications. This means when ever you are mentioning a string value in the from method that isn’t known in the object store collection, it will be created for you.

But enough about the theory, let us watch some code.

Setting UP Linq2indexeddb

The first thing you need to do is getting the linq2indexeddb library. You can do this by getting the JS script files from codeplex. The only thing you need to make sure is: the sort.js and where.js file need to be in a “Script” folder under the root of the project. These files are used to preform web worker tasks and are hardcoded referenced for now.

Or VS developers can use Nuget Packages:

Once you have the linq2indexeddb library, the next thing you need to do is adding a reference to it in your page. Note, if you are using the jQuery version, you need to add a reference to the jQuery framework first.

using Linq2indexeddb

Once all the references are added, we can start using the library. The first thing you need to do is creating a instance of the linq2indexeddb object. You can do this by calling the linq2indexeddb method on the window object. This method accepts 3 parameters:

  • The first one is the name of the database u want to use.
  • The second one is a database configuration object. More on that later on the post.
  • The last is an Boolean which allows you to enable logging. By default this is disabled
   1: var db = window.linq2indexedDB("dbName", dbConfig, false);

Configuring the database


When opening/creating the database, you can provide a database configuration. Here you can configure the object stores and indexes you want to use. There are several ways to do the configuration, but one thing needs to be provided at all time: the version of the database. This makes sure that the database will have the correct structure we need.



   1: var dbConfig = {};
   2: dbConfig.version = 1;

A second thing we need to do, is providing a way to define the structure. In the current implementation of the library, there are 4 ways to do this. For now I would advise you to use the definition. This doesn’t require you to write the create/delete statements your self. But if you do want to, you can make use of the promises present in the linq2indexeddb.core to create/delete object stores and indexes.


onupgradeneeded

This a function that gets called when the database needs to get updated to the most recent version you provided in the configuration object. 3 parameters are passed to this function:



  • Transaction: on this transaction you can create/delete object stores and indexes
  • The current version of the database
  • The version the database is upgrading to.


   1: dbConfig.onupgradeneeded = 
   2:     function (transaction, oldVersion, newVersion){
   3:         // Code to upgrade the db structure
   4:     }

The onupgradeneeded callback is the only one that can’t be used in combination with one of the other ways to define the function


schema

The schema is an object which defines the several versions as a key/value. The key keeps the version it targets and in the value an upgrade function. In this function you can add your code to upgrade the database to the version given in the key. The upgrade function has one parameter:



  • Transaction: on this transaction you can create/delete object stores and indexes


   1: dbConfig.schema = {
   2:     1: function (transaction){
   3:             // Code to upgrade the db structure to version 1
   4:        }
   5:     2: function (transaction){
   6:             // Code to upgrade the db structure to version 2
   7:        }
   8: }

Note: If the database needs to upgrade from version 0 to 2, the upgrade function of version 1 gets called first. When the upgrade to version 1 is done, the upgrade function of version 2 gets called.


definition

The definition object is the only way to define your database structure without having to write upgrade code. The object keeps a collection of objects which describe what needs to be added or removed for a version. Each object exists out of the following properties:



  • Version: The version where for the definitions are.
  • objectStores: Collection of objects that define an object store

    • name: the name of the object store
    • objectStoreOptions

      • autoincrement: defines if the key is handled by the database
      • keyPath: the name of the property that keeps the key for the object store

    • remove: indicates if the object store must be removed

  • indexes: Collection of objects that define an index

    • objectStoreName: the name of the object store where the index needs to be created on
    • propertyName: the name of the property where for we want to add an index
    • indexOptions

      • unique: defines if the value of this property needs to be unique
      • multirow: Defines the way keys are handled that have an array value in the key

    • remove: indicates if the index must be removed

  • defaultData: Collection of default data that needs to be added in the version

    • objectStoreName: the name of the object store where we want to add the data
    • data: the data we want to add
    • key: the key of the data
    • remove: indicates if the data needs to be removed


   1: dbConfig.definition= [{
   2:     version: 1,
   3:     objectStores: [{ name: "ObjectStoreName"
   4:                        , objectStoreOptions: { autoIncrement: false
   5:                                              , keyPath: "Id" } 
   6:                    }]
   7:     indexes: [{ objectStoreName: "ObjectStoreName"
   8:                   , propertyName: "PropertyName"
   9:                   , indexOptions: { unique: false, multirow: false } 
  10:               }],
  11:     defaultData: [{ objectStoreName: ObjectStoreName
  12:                       , data: { Id: 1, Description: "Description1" }
  13:                       , remove: false },
  14:                   { objectStoreName: ObjectStoreName
  15:                       , data: { Id: 2, Description: "Description2" }
  16:                       , remove: false },
  17:                   { objectStoreName: ObjectStoreName
  18:                         , data: { Id: 3, Description: "Description3" }
  19:                         , remove: false }]
  20: }];

onversionchange

This a function that gets called when the database needs to get updated to the most recent version you provided in the configuration object. But in contrast to the onupgradeneeded callback, this function can be called multiple times. For example if an database is upgrading from version 0 to version 2, the onversionchange will be called 2 times. Once for version 1 and once for version 2.  2 parameters are passed to the function:



  • Transaction: on this transaction you can create/delete object stores and indexes
  • The version of the database it is upgrading to.


   1: dbConfig.onversionchange = 
   2:     function (transaction, version){
   3:         // Code to upgrade the db structure
   4:     }


Querying data


Once the database structure is created, we can start querying on it. On the linq2indexeddb object we have a field linq which holds all the linq functionality. The first method you always need to call is the from method. This method excepts only one parameter, the name of the object store we want to work on. Once we have this we can start inserting, updating, deleting and selecting data from it.



   1: // inserting data, key is optional
   2: db.linq.from("objectstore").insert({}, key);
   3: // updating data, key is optional
   4: db.linq.from("objectstore").update({}, key);
   5: // removing data
   6: db.linq.from("objectstore").remove(id);
   7: // clears all data from the object store
   8: db.linq.from("objectstore").clear();
   9: // gets a single record by his key
  10: db.linq.from("objectstore").get(key);
  11: // selects all objects
  12: db.linq.from("objectstore").select();

But the library also provides ways to filter data. This can be done by calling the where method. This accepts the name of the property we want to filter on as parameter. On this you can call the filter you want to add. For now these are limited to the following:



  • equals(value)
  • between(value1, value2, value1included, value2included)
  • greaterThen(value, valueIncluded)
  • smallerThen(value, valueIncluded)
  • inArray(arrayOfObjects)
  • like(value)

So if we want to select all the objects which have a field called '”property” and have the value “value” we write the following query:



   1: db.linq.from("objectstore").where("property").equals("value").select()

If you want to add multiple filters you need to do the following:



   1: db.linq.from("objectstore")
   2:        .where("property").equals("value")
   3:        .and("anotherproperty").greaterThen(4)
   4:        .select()

You are also able to sort your data:



  • orderBy(propertyName)

  • orderByDesc(propertyName)


   1: db.linq.orderBy("property").select()

As last, the library also enables you to get only a subset of the properties stored in the objects



   1: db.linq.from("objectstore").select(["property1", "property2"])


Conclusion


This was a brief introduction of the functionalities of the linq2indexeddb library. In future post I will go more in-depth into the advanced functionalities like linq2indexeddb.core. If you have any suggestions, bugs, additions,… about the library, feel free to contact me. Hope you enjoy using the library.

Wednesday, March 28, 2012

Developing metro apps (HTML & JS): My point of view

Last Friday I attended the first windows 8 developer day in Belgium. A great opportunity to learn a bit more about developing Metro apps. One of the demos given by Giorgio Sardo showed how easy a HTML 5 application could be copied and pasted into a Metro app without having to rework even a single line of code. At first sight this looks pretty amazing, but I got me thinking.
The first thing I noticed is the fact that the HTML 5 application was actually a game. That is one of the reasons it could be easily ported to a Metro app. If we would want to port a business app like an e-commerce site, that wouldn’t be so easy. One of the important issues when developing Metro apps is the design. The philosophy of Microsoft when designing an application is that all applications have a similar look & feel and should react on the same way.
Almost all websites are designed for a single resolution and that is in contrast with the Metro philosophy where all apps should optimize their viewport for every screen. This means you’ll have to redesign your application so it changes its content to fit to the screen. Also you should implement the capabilities to change the view depending on the position of your device (landscape or portrait mode) and the multitask options which allows you to run multiple applications side by side.
Next to the Metro design these Metro apps should at least have some specific windows 8 features like redefined search and sharing capabilities. It's only at this point you really start to take advantage of some of the new windows 8 features. But the most important thing you should implement is the live tile. This must engage the user to consume your application. You can do this by providing the user real-time information about your app.
A second consideration is the fact when you just copy and paste your web application, you don’t take advantage of all the possibilities present in WinRT. With WinRT you can make calls to the operating system. For example you can access the webcam, save a file to the file system; share data … Developing Metro apps with JavaScript also brings the WinJS namespace. In here we find the Promise object that enables an easy way for the developer to handle asynchronous calls. Because all calls that take more than 50ms are preformed asynchronous by default, this can come in handy when you are making WinRT calls.
After the theoretical part, it was time for the real work: an App-a-thon. Here we got the possibility to put all our theoretical knowledge into practice. Together with 4 RealDolmen colleagues (Maarten Balliauw, Xavier Decoster, Wesley Cabus and Angelo Trotta) we developed a metro Nuget Package Explorer. This allows the users to view NuGet repositories and their package details. All this information gets retrieved from the given feeds and gets stored in an IndexedDB for performance. The application is completely build in HTML5 and uses JavaScript for the logic.
Surprisingly, developing this application went pretty fast. I took some time to adjust to the fact your writing a client application with JavaScript, but all knowledge about JavaScript in the past, could be reused pretty easy. There was one thing we were struggling with. When working with the promises you have to be very careful to call objects in the UI-thread, otherwise you can get some strange exceptions.
Conclusion
After a whole day Windows 8, I really excited to start develop metro apps. Enabling developers to develop a metro app in HTML/JS was definitely a good choice Microsoft made. This way a whole new group of developers can start building Metro apps. But the business has to be aware that you can’t just copy and paste your web app in a Metro project and call it Metro app. Metro apps have a philosophy and that should be respected. Also it would be a shame if you wouldn’t take advantage of all the new features that Metro apps provide.
I’m looking forward to the next app-a-thon and hope that our team can come together again to win the contest this time. (Ended second last time.)
Currently I’m trying to port our Linq2IndexedDB project to use the WinJS promises instead of the jQuery promise. I hope to announce this feature in the near future.