Tuesday 10 May 2011

Serializing DateTime values using JavaScriptSerializer class

As you know .NET Framework's System.Web.Script.Serialization.JavaScriptSerializer class can be used to to do C# to JSON serialization and JSON to C# deserialization. When JavaScriptSerializer serializes a DateTime into a JSON string it uses the Local DatetimeKind, unless otherwise specified while creating the DateTime, resulting in a potential problem while deserializing it. The reason is AJAX framework deserializes DateTime value assuming its Kind property is set to Utc format. So if the serialized DateTime is created using a different DateTimeKind deserialization will produce a different DateTime value.

For example assume your Local is GMT+1 and you have serialized the DateTime value "15-May-2011 00:00:00" using JavaScriptSerializer and passed it to a WCF method where you deserialize it. Here deserialization will produce a DateTime with the value "14-May-2011 23:00:00". This is because deserialization assumes the value is serialized using Utc DateTimeKind, which is nothing but GMT time, and it uses the same DateTimeKind.Utc to deserialize it. So it results in a DaTime value which is one hour (remember the Local is GMT+1) less than the original value.

The fix is do something similar to below code snippet before serializing which will make sure DateTimeKind.Utc will be used for serializing the value.

DateTime departureDate = DateTime.SpecifyKind(value, DateTimeKind.Utc);

And finally you will get the correct value after deserialzation in the WCF method or wherever you do it.

Click here to read more.

Wednesday 4 May 2011

How to check whether an element is visible or not using jQuery

jQuery(':visible') - Selects all elements that are visible.

Elements can be considered hidden for several reasons:

* They have a CSS display value of none.
* They are form elements with type="hidden".
* Their width and height are explicitly set to 0.
* An ancestor element is hidden, so the element is not shown on the page.

Elements with visibility: hidden or opacity: 0 are considered to be visible, since they still consume space in the layout. During animations that hide an element, the element is considered to be visible until the end of the animation. During animations to show an element, the element is considered to be visible at the start at the animation.

Below JavaScript is useful if you need to know if a specific object is visible:

if ( $('#elementid').is(':visible')){
// element is visible, do something
}

OR

if ($('#elementid:visible').length > 0){
// element is visible, do something
}