Monday, July 30, 2007

Debugging JavaScript in MAC Safari / Tool to debug JavaScript in Safari

      Safari has inbuilt debug menu for java script. By default it is hidden. Safari's "Debug" menu allows you to turn on the logging of JavaScript errors. To display the debug menu in Mac OS X, open a Terminal window and type:

            defaults write com.apple.Safari IncludeDebugMenu 1

      To display the debug menu in Safari 3.0 for Windows, use a text editor to add the following to the Preferences.plist file located at C:\Documents and Settings\USERNAME\Application Data\Apple Computer\Safari\Preferences.plist :

            <key>IncludeDebugMenu</key> <true/>

        Safari 1.3 and above supports explicit logging of arbitrary information - similar to Objective-C NSLog() - function by using window.console.log() in your JavaScript. All messages are routed to the JavaScript Console window and show up nicely in a dark green, to easily differentiate themselves from JavaScript exceptions.

            if(window.console)
           {
                window.console.log("I think therefore I code!"); 
           } 
           else
           { 
                alert("I think therefore I code!");
           }

        WebKit crew has released a JavaScript debugger tool Drosera to debug javascript in safari.

Happy Programming !!

Saturday, July 28, 2007

Session.SessionID is not unique

    I have seen many forums in which users are asking that Session.SessionID is not unique. You also have seen forums saying that "I am getting different value for SessionID on every page or in each post back." Yes they are correct !!!! "This is not possible. How can it be?", I know this is your reaction. We have read in all the books and seen practically that SessionID is unique, until user logs off or close the browser. This is also correct. Now you will say then why am I writing the story?

   Here is the actual fundamentals that I have observe practically. The session changes in each request (either post back or redirecting from one page to another page) until user has not insert any value in Session collection. This means server treats each request from new session if user has not entered any value in session. You can check this practically!!!

  Create a web application with two pages Default.aspx and Default2.aspx. Add one button and two lables on Default.aspx page. On page load of Default.aspx in if(!Page.IsPostBack) set any one lable's text to Session.SessionID. Now in click event of button set second lable's text to Session.SessionID. You can see that every time when post back occurs you have new value of SessionID. Amazing !!!!!!! You can check by redirecting to Default2.aspx page and print SessionID.

    Now, on Default.aspx page in if(!Page.IsPostBack) set Session["test"] = "1" or set any name value collection. Once you do this run the page. Click on button any number of time and you see that now SessionID is unique.

   Really Amazing!!!!

 

Happy Programming !!

Tuesday, July 24, 2007

Dispose and Finalize in Dot Net OR Maemory Management using Dispose and Finalize

       You can find article here

Happy Programming !!

Monday, July 23, 2007

Delete single row from duplicate rows in SQL Server 2005 and 2000

        Lets assume that you are using SQL Server 2005 for your current project. You found that you have few rows which have duplicate data in all the columns. Lets consider that you have table name "Example" which has two columns ID and Name.

CREATE TABLE [dbo].[Example]
(
[ID] [int] NOT NULL,
[Name] [nvarchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL
)
ON [PRIMARY]

Fig - (1) Create Statement for Table     

INSERT INTO [Example] ([ID],[Name]) VALUES (1,Chirag)
INSERT INTO [Example] ([ID],[Name]) VALUES (1,Chirag)
INSERT INTO [Example] ([ID],[Name]) VALUES (2,'Shailesh')
INSERT INTO [Example] ([ID],[Name]) VALUES (3,'Dipak')
INSERT INTO [Example] ([ID],[Name]) VALUES (4,'Mihir')
INSERT INTO [Example] ([ID],[Name]) VALUES (4,'Mihir')
INSERT INTO [Example] ([ID],[Name]) VALUES (4,'Piyush')

Fig - (2) Insert Script.

          You can see that first two and last three rows are duplicate rows. All the values in these rows are same.  Here is the insert script, if you want to do this practically in your local database.

       Now you want to delete duplicate rows in such a way that only one row will be exist after delete statement. First let me write the query which will give return all the duplicate rows from table.

SELECT
        [ID],[NAME],COUNT([ID])
FROM
        [Example]
GROUP BY
        [ID],[NAME]
HAVING
        COUNT([ID]) > 1

Fig - (3) Query to identify duplicate rows in table.

       Here I have used COUNT([ID]) in select statement as ID is not null filed. You can use any column which is not NULL. If all the columns in your table allows NULL value than you can use COUNT(*). The Difference between COUNT(Column Name) and COUNT(*) is, if your column allows null value and in table you have 5 records with 2 null values in ColumnA. If you use COUNT(ColumnA) it will returns 3 and if you use COUNT(*) it will returns 5. So COUNT(Column Name) ignores NULL value. Lets get back to our query. I have used all the column in SELECT and GROUP BY clause. You also have to write all the columns of your table in SELECT and GROUP BY clause. This way you can identify all the duplicates row from table.

        Lets assume that you have to delete the row which has value (1, 'Chirag') so that only one row remains. Here is the query, (Note: This will work only in SQL Sever 2005)

      DELETE TOP(1) FROM [Example] WHERE [ID] = 1

Fig - (3) Delete single row from duplicate rows.

          Here I have used TOP(1) , If you have n rows which has all the values same than you have to use TOP(n-1) so that only 1 row will be remain after delete statement. To delete all the duplicate rows you need to write a cursor as shown below,

DECLARE @ID int
DECLARE @NAME NVARCHAR(50)
DECLARE @COUNT int

DECLARE CUR_DELETE CURSOR FOR
SELECT [ID],[NAME],COUNT([ID]) FROM [Example] GROUP BY [ID],[NAME] HAVING COUNT([ID]) > 1

OPEN CUR_DELETE

FETCH NEXT FROM CUR_DELETE INTO @ID,@NAME,@COUNT
/* Loop through cursor for remaining ID */
WHILE @@FETCH_STATUS = 0
BEGIN

DELETE TOP(@COUNT -1) FROM [Example] WHERE ID = @ID

FETCH NEXT FROM CUR_DELETE INTO @ID,@NAME,@COUNT
END

CLOSE CUR_DELETE
DEALLOCATE CUR_DELETE

Fig - (4) Cursor to delete all duplicate  records

         This is all about deleting duplicate rows in SQL Server 2005.

       Now to do the same in SQL server 2000.  There is function called ROWCOUNT in SQL.  I have used same [Example] table. You can do this by,

SET ROWCOUNT 1
DELETE FROM [Example] WHERE [ID] = 1

Fig - (5) Delete duplicate row in SQL Server 2000

      ROWCOUNT function specify that how many rows will be affected by the statement which is immediately written below.  Here also you have to write  ROWCOUNT (n -1) to delete n duplicate rows such that only  1 row will remain in database.

Happy Programming !!

Tuesday, July 03, 2007

Anonymous Type in C#

          Anonymous types are a convenient language feature of C# and VB that enable developers to concisely define inline CLR types within code, without having to explicitly define a formal class declaration of the type.
           Anonymous types are particularly useful when querying and transforming/projecting/shaping data with LINQ.

            C# "Orcas" introduces a new var keyword that may be used in place of the type name when performing local variable declarations. 

             A common misperception that people often have when first seeing the new var keyword is to think that it is a late-bound or un-typed variable reference (for example: a reference of type Object or a late-bound object like in JavaScript).  This is incorrect -- the var keyword always generates a strongly typed variable reference.  Rather than require the developer to explicitly define the variable type, though, the var keyword instead tells the compiler to infer the type of the variable from the expression used to initialize the variable when it is first declared.

            The var keyword can be used to reference any type in C# (meaning it can be used with both anonymous types and explicitly declared types).  In fact, the easiest way to understand the var keyword is to look at a few examples of it using common explicit types.  For example, I could use the var keyword like below to declare three variables:

var a = 5;
var b = "5"
var c = 5.555;
var d = new Class();
var e = a;

int f = 6;
string g = "6"
double h = 6.666;

Fig - (1) Use of anonymous variable in code.

              You can look in to the IL code and found that IL is treating anonymous variables same as normal variable depending on their initialization. You can see the IL code below,

.method private hidebysig instance void UseOfAnonymousTypes() cil managed
{
// Code size 50 (0x32)
.maxstack 1
.locals init ([0] int32 a,
[1] string b,
[2] float64 c,
[3] class LearnLINQ.SimpleExamples d,
[4] int32 e,
[5] int32 f,
[6] string g,
[7] float64 h)
IL_0000: nop
IL_0001: ldc.i4.5
IL_0002: stloc.0
IL_0003: ldstr "5"
IL_0008: stloc.1
IL_0009: ldc.r8 5.5549999999999997
IL_0012: stloc.2
IL_0013: newobj instance void LearnLINQ.SimpleExamples::.ctor()
IL_0018: stloc.3
IL_0019: ldloc.0
IL_001a: stloc.s e
IL_001c: ldc.i4.6
IL_001d: stloc.s f
IL_001f: ldstr "6"
IL_0024: stloc.s g
IL_0026: ldc.r8 6.6660000000000004
IL_002f: stloc.s h
IL_0031: ret
} // end of method Class1::UseOfAnonymousTypes

 Fig - (2) IL generated for Anonymous Type

          As you can see that we have assigned 5 to "a". IL treats "a" as int32. Same is the case for remaining all. From this you can say that IL detects type of anonymous variable from their initialization. So you can declare anonymous variable without initializing it. Second rule for anonymous type is that you can not use Anonymous variable as a member of class, sturct or interface. So below line will not complile.

class LearnAnonymousType
{
       // Below line will give error
       var a = 5;
}

Fig - (3) Defining Anonymous variable as member field in class

    Third rule is that you can not pass or used for Anonymous type as a method argument. See below,

class LearnAnonymousType
{
       // Below line will give error
       function void sum(var Argument)
      {
      }
}

Fig - (4) Passing anonymous type as argument to function

     Fourth rule is, anonymous type can not be static.

      I hope this article has helped you in understanding the concept. Now lets have a simple quiz.

Quiz

Which of the following code fragments compile and which don't (and why)? Have fun!

Fragment 1

using System;
class Lti
{
   public static void Main()
   {
      var a;
      a = 123;
   }
}

Fragment 2

using System;
class Lti
{
   public static void Main()
   {
          int a = 123;
          var b = a;
   }
}

Fragment 3

using System;
using System.Collections.Generic;
class Lti
{
   public static void Main()
   {
              IEnumerable<string> l = new List<string>();
              var m = l;
              int i = m.Count;
   }
}

Fragment 4

using System;
using System.Collections.Generic;
class Lti
{
   private var a = 123;
   private const var b = 123;
   private static var c = 123;
   public static void Main()
   {
   }
}