Sunday, June 28, 2009

Best and simple approach to deal with JSON Dates problem

It might be very frustrating for the guys who decided to try for the so called great revolution using jQuery and asp.net,WCF and Linq in combination.

Their adventure with the code might come to an end first on the WCF configuration step or secondly handling the JSON serialization over the wire.

Although its really simple to configure the WCF service for your JSON wire transfer requirement but its certainly a little confusing.

Another problem which comes after successful configuration of the WCF services with your application is dealing with “Dates”.

This problem arises due to the fact that there no javascript literal called Date.Everytime we need a date we create a new object of the date such as:-

Date myDate = new Date(“28/04/2008”);

 

If you write the date like the below given syntax then its not the actual date but its only ordinary string which is of no use as such and does not solve our purpose.

var  myDate = “28/04/2008”;

So the response which you will receive from the server in the JSON format will contain all the dates in a surprising format which can be easily parsed if you are using Micorosft Ajax. But if you are on your own using direct jQuery $ajax() then your life is in trouble.

To workaround this strange Date problem there are few possible ways out of which :-

  1. Parse the response from the server on your own and just use the regex to remove \/ symbol and then evaluating the date string and converting it to Date($1) and returning this date.Although this method is the so called correct one but still its little too complicated and it seems to be the only standard workaround for solving this problem.Given below is some custom implementation for showing how you can parse and evaluate the response received from the server.Always keep in mind that this code would need some change if you are using some other type of replacer symbols in the JSON,this is just a reference example how to parse the response and then evaluating it to get the correct dates.
  $.ajax({
        type: "POST",
        url: pagePath + "/" + methodName,
        contentType: "application/json; charset=utf-8",
        data: paramList,
        dataType: "text",
        processData: false,
        success: function(msgg) {
            var msg = JSON.parse(msgg, function(key, value) {
                var a;
                if (value != null) {
                    if (value.toString().indexOf('Date') >= 0) {
                        a = /^\/Date\((-?[0-9]+)\)\/$/.exec(value);
                        if (a) {
                            var dt = new Date(parseInt(a[1], 10));
                            return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
                        }
                    }
                    return value;
                }
            });
            successFunction(msg);
        },
        error: function(xhr, status, error) {
            errorFunction(xhr, status, error);
        }
    });

Here in this example we are getting the actual response in the variable msgg.After invoking the success we are parsing the response and then we are searching for the Date values in the string where ever found we are removing the unnecessary symbols \/ and then parsing the 10 digit date and after this step converting it to actual date and finally returning the value.

Although its a little tricky approach but it works fine,you might have to change the parsing method a little bit as according to your needs to make it work for you.

2.Another simple solution is forget about the Date thing on the client side consider every thing as string on the client and also in your business logic and application layer.Although it doesn’t sounds good and many of us don’t agree on this but its the simplest possible workaround to make things work quickly.

So for achieving this no need to make any changes in your database schema just let the dates be dates only in your schema.

What we will do is we will pass date as string from the UI using BusinessObjects to the Service Layer and DataAccessLayer and after reaching the database we will convert these values back to string and while retrieving those dates from the database they should be converted again back to string so that we are not again running into the same old problem.

Converting date to string while retrieving back the date to be displayed somewhere on the page

CONVERT(CHAR(11),datemodified ,106) AS datemodified,
		CONVERT(CHAR(11),datecreated,106) AS datecreated	

There are various other choices available with changing the last code part to receive date in various other formats.

By using this mechanism you will never run into this date trouble again

Submit this story to DotNetKicks

del.icio.usSave Total0 users

Thursday, June 18, 2009

Differences between an abstract class and an interface in C#

Most of the new developers are always confused as when, where and why we should use an interface or an abstract class.Although both abstract classes and interfaces serve the same purpose to some extent but yet they are different in many terms.

Although both act as a sort of contract but there are some major differences in both of them which i will sum up in this article

  1. Interfaces belong to interface type where as abstract classes belong to class type
  2. Interface contain only abstract methods which the type who implements the interface should give its declaration whereas abstract class may contain both abstract methods as well as concrete methods.
  3. Abstract class can extend another class and implement multiple interfaces, where as an interface cannot be inherited from a class.
  4. If A is your abstract class and B is a class which extends A, then in this situation you can have B only extend from A not from any other class i.e no direct multiple inheritance is supported and this in a sense is achieved by interfaces as we can implement any no of interfaces for a given class.
  5. Both follow a different paradigm as interfaces are implemented  whereas classes are extended.

So both concepts are a kind of generalization and are used in situations where we cannot in reality define the object which we are talking about this line means for example if we say a car then its a very general specification and no such entity exists in real which we can say is a car.But if you say “Ferrari” then it does make sense and you can identify a unique instance.

So to define car’s action  we can use either abstract classes or  interfaces to declare the general car functionalities.

After doing that we can go ahead and create a Ferrari class which either can derive from your abstract class or can implement the interface created by you.

Using abstract classes or interfaces totally depends on what type of inheritance are you following if your applications is sounding to use multiple inheritance then its always better to go with interfaces and if you know that with a particular class the derived class need not be derived from another class then you can go ahead with abstract classes.

These are the main differences and some similarities between these two.If you want to add something else do leave a comment.

Happy Programming!!!!!!!

Submit this story to DotNetKicks

del.icio.usSave Total0 users

Tuesday, June 16, 2009

Ext.js 2.2 intellisense in Visual Studio 2008

Today i was playing with ext.js a very nice little java script framework which can give you very stunning UI at the end if you have little patience.

Although Visual Studio 2008 provides support for java script intellisense but it is rather bleak or dull so when it comes to jQuery there is a vsdoc file for our rescue.

But what about when you are playing with other javascript libraries like ext.js

So i found a very good link which talks about getting ext.js 2.2 intellisense in Visual Studio 2008 which i wanted to share with you all

http://www.spket.com/ext-intellisense-visual-studio.html

I will be doing a series of articles on ext.js in future as i have started playing with it.

Happy Programming !!!!!

Submit this story to DotNetKicks

del.icio.usSave Total0 users