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


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!!!!!!!


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 !!!!!


Integrating Paypal with Blogger or any other Blog Provider

If you want to earn from your blog you have many options such as Adsense,Adbrite,LakeQuincy Media and there are several other advertising giants which will help you make more money. But another good way to make money from your blog is by providing a way through  which users who want to donate you some bucks can directly donate it to you and the best possible solution which comes to my mind is PayPal. Here in this article i will show you how easy it is to integrate the paypal into your blog.I have done it on blogger,you can follow similar steps and embed it in any blogging platform

  • Login to your paypal account.And click on the Merchant Services tab.

  • After clicking the Merchant Services tab search for the word Donations and click it then you will see the below screen.
  • Fill the form and selecting your choice and preferred buttons and then click Create Button

  • After clicking on create button you will be provided with a code.Now you have to just place that code into your blog’s code to make it running.

  • I will show you how to integrate it into blogger
  • Login to your blogger account and go to Layout tab.Click on add a gadget

  • After adding a popup window will be opened.Just enter the heading which you want to be displayed and also write few lines of your own choice which you want to display.After writing all this just paste the code which you got above i.e after creation of your button.

  • Click Save and that’s it your paypal donation button is now integrated with your blogger blog.

Publishing Database to GoDaddy server using Database Publishing Wizard

GoDaddy shared hosting supports database publishing wizard which is a good news as earlier there were creepy means to publish the database to the godaddy servers.Now you can publish your database either in full or only the required objects to the godaddy server.

Follow the steps given in the below link to publish your database directly to the godaddy server http://products.secureserver.net/products/hosting/PublishingWithDPW.htm If you dont have Database Publishing Wizard already installed then you can download and install it from http://www.microsoft.com/downloads/details.aspx?FamilyId=56E5B1C5-BF17-42E0-A410-371A838E570A&displaylang=en After installation you will find the database publishing wizard in C:Program FilesMicrosoft SQL Server90ToolsPublishing1.2SqlPubWiz.exe But remember to backup your existing database prior to uploading or deleting the already existing database.


Part 1:- Some useful scripts which come handy while working with sql server 2005

    1. Getting all the primary key and foreign keys in a given database

select OBJECT_NAME(PARENT_OBJ) TABLE_NAME, 
CASE WHEN XTYPE ='F' 
THEN 'FORIEGN KEY' 
ELSE 'PRIMARY KEY' END KEY_TYPE , NAME KEY_NAME
from sysobjects 
where Xtype in ('F' , 'pK') 
ORDER BY XTYPE DESC 

This script can be used to get all the primary key and foreign key relationships within a given database.It sometimes can be helpful on a project with a complex database having hundreds and thousands of relationships and in such a database if you have to perform some major changes so you can have a quick look and you can know which all tables and relationship will be effected by these changes.

2. Delete All the Stored Procs for a particular database

Alter Procedure dbo.DeleteAllProcedures
As
      declare @procName varchar(500)
      declare cur cursor
            for select [name] from sys.objects where type = 'p'
      open cur
      fetch next from cur into @procName
      while @@fetch_status = 0
      begin
            if @procName <> 'DeleteAllProcedures'
                  exec('drop procedure ' + @procName)
                  fetch next from cur into @procName
      end
      close cur
      deallocate cur
Go

      Grant Execute On dbo.DeleteAllProcedures To Public

Go

This can only be handy when you want to delete all the user defined stored procs for a particular database

3.Change the default owner of a stored proc

USE YourDataBaseName
GO
DECLARE
  @OldOwner sysname,
  @NewOwner sysname

 SET @OldOwner = 'dbo'
 SET @NewOwner = 'dev'

DECLARE CURS CURSOR FOR
SELECT  name
FROM sysobjects
WHERE  type = 'p' 
AND
  uid = (SELECT uid FROM sysusers WHERE name = @OldOwner) 
AND 
  NOT name LIKE 'dt%' FOR READ ONLY  

DECLARE @ProcName sysname

OPEN CURS
FETCH CURS INTO @ProcName
WHILE @@FETCH_STATUS = 0
BEGIN
    IF @@VERSION >= 'Microsoft SQL Server 2005'
    BEGIN
        EXEC('alter schema ' + @NewOwner + ' transfer ' + @OldOwner + '.' + @ProcName)
        exec('alter authorization on ' + @NewOwner + '.' + @ProcName + ' to schema owner')
    END
    ELSE
        EXEC('sp_changeobjectowner ''' + @OldOwner + '.' + @ProcName + ''', ''' + @NewOwner + '''')

    FETCH CURS INTO @ProcName
END
CLOSE CURS
DEALLOCATE CURS

4.Finding any stored proc containing the text of your choice

SELECT ROUTINE_NAME, ROUTINE_DEFINITION 
    FROM INFORMATION_SCHEMA.ROUTINES 
    WHERE ROUTINE_DEFINITION LIKE '%yoursearchtext%' 
    AND ROUTINE_TYPE='PROCEDURE'

5.Reducing the size of your transaction log

dbcc shrinkfile (mydatabasename_log, 10);

This command will reduce the size of your database transaction log to 10MB. But if you are on production then you should not use this method to shrink your database, you should avoid shrinking the database without finding the probable reason why is it growing so fast.


Error 1045 when using MySQL or SQLyog

Yesterday i was playing with MySql and SqlYog.I m not much familier with both but as Mysql was needed on one of the project , so i was trying to learn it in a nutshell. Initially there were little setbacks and frustrations but later everything seemed easy.I find things a little different as i m from the Sql Server world.

As i keep on learning i will keep on sharing with you.So the first one is when i installed MySql and configured everything well but when i installed SqlYog and tried to connect them both i got this bad error saying “Error 1045.Access is denied for user abcdefgh@localhost………..” I was clueless of what went wrong after trying for sometime and googling to find nothing i tried some random things and wooola!! one of it did work just simple trick. Actually at every other place i found a solution where there was no password set for the users, so most of the posts told how to change the old password or revoke or grant permissions to the existing users. But i knew that mine was simple as i did everything right. So what happened was that when i installed mysql it asked me for username and password and i politely provided it with one of my favorite username and password. But after trying many times with sqlyog the things were still not looking good. So the simple thing here is while connecting with mysql from sqlyog it expects that you provide username as “root” not the one which you gave while installation and the password remains the same which you gave while installing mysql.   Although a very small tip but almost most newbie's may face this problem. Never loose hope there is always a workaround for everything. Happy Programming !!!!!!!!!!!!!!!!!!


Adobe Browser Labs Released:- Test your website in different browsers

If you are frustrated of first developing and designing a website and then checking it in different browsers then Adobe BrowserLabs online service is the one which will act as a soul-saver for you.

its an interesting online service which is in free testing preview face from which user can test unlimited no of webpages designed by him against variety of browsers. Currently it supports only limited registrations but its a must watch service which can reduce your pain. You can get more information about it  from :- http://labs.adobe.com/technologies/browserlab/  Happy Programming!!!!!!


StatCounter:- A valuable and simple tool to analyze,share your traffic stats with others,and ultimately increase your traffic

Most of us use Google Analytics which is free to analyze our traffic and this is a good practice, but self analysis of your website should be augmented by sharing your traffic stats to the whole world.

This cannot be done through analytics as such, there are many other services which can do this but in my personal preference i use stat counter to achieve this for me. StatCounter is a paid service but there is also a fully functional free version which is out there to try and believe me the free version is also as powerful as the paid version for a normal user. StatCounter gives you a quick way to analyze your traffic data,although analytics gives much better presentation of the data but still for the simplicity sake i prefer stat counter. One more benefit for which i use stat counter is its summary area which you can share with other people. Although you can face one problem while using statcounter that how to enable showing stats to guest user to your blog or your website. By default if you provide the link given by stat counter it will ask you the login credentials but if you just append &guest=1 after the link as shown in figure" then whenever the user clicks the link from his website he will be redirected to the summary page of your project in the stat counter. I personally use both stat counter and google analytics to keep track of traffic on my websites.