12 June 2012

How to parse a ASP.Net JSON formatted date in C#

ASP.Net serializes a date to JSON in a Microsoft specific format:

/Date(1338505200000)/

The value 1338505200000 is the number of milliseconds since January 1st 1970 UTC.

The data can be parsed in C# removing the placeholders "/Date(" and ")/" and parsing it as:

string jsonDate = "/Date(1338505200000)/"; jsonDate = jsonDate .Replace("/Date(", string.Empty); jsonDate = jsonDate.Replace(")/", string.Empty);

var date = new DateTime(1970, 1, 1, 0, 0, 0, 0).AddMilliseconds(long.Parse(jsonDate));

jQuery Deferred for Asynchronous callbacks

jQuery Deferred is a convenient way to perform Asynchronous callbacks.
For example, during the load of a page if you are performing a javaScript operation that takes some time to execute, an asynchronous callback can be used. The page will load without blocking.

jQuery has the $.Deferred() feature that can register multiple callbacks and invoke them.
The deferred.done() adds an handler to be called when the Deferred object is resolved (doneCallbacks).
The deferred.resolve() resolves a Deferred object and calls any doneCallbacks with the given args.

The following code is an example usage:
var deferred = new $.Deferred();

deferred.done(function(message) { 
    // Put the code to execute asynchronously here
    alert(message);
});

deferred.resolve('"hello world!!!"');
There is a lot more about the Deferred Object in the jQuery documentation.

01 June 2012

KnockoutJS force viewModel update

The KnockoutJS (KO) has a binding parameter named valueUpdate that defines which browser event KO should use to detect changes.

The default is on change: As the documentation says: "change" (default)
- updates your view model when the user moves the focus to a different control, or in the case of select elements, immediately after any change

Now let us say that you are using the jquery datepicker on a textbox.
After the date is selected the texbox has the value, but KO doesn't update the value on it's model, because there isn't any change event on the control.

To force that KO updates the model for the date textbox, the change event must be fired:
$("#textboxID").trigger("change");

Another possible solution is to create a custom binding for the jQuery datepicker.
The skeleton to specifiy a custom binding is:
ko.bindingHandlers.myCustomBinding = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel) {

    },
    update: function(element, valueAccessor, allBindingsAccessor, viewModel) {

    }
};
You can create a datepicker binding:
ko.bindingHandlers.datepicker= {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
      var parameters = allBindingsAccessor().datepickerParameters || {};
      $(element).datepicker(parameters);

       //handle the field changing
    },
    update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
       //handle the field changing
    }
};

and use it as: