Feeds:
Posts
Comments

Archive for July, 2007

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

Read Full Post »

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

Read Full Post »

       Dotnet provides automatic memory managenet using Dispose and Fibnalize method. You will find this in classes that acquire and hold on to resources such as file and window handles or network and database connections. This is the case because the Common Language Runtime (CLR) within which your .NET code runs implements nondeterministic finalization, meaning that the CLR ultimately decides when object instances are no longer able to be referenced and when those instances are deallocated in memory. The process of reclaiming memory by deallocating instances is referred to as garbage collection, or simply GC.

       Lets  have a look at Finalize method first and then we will look in to the Dispose method. Finalize method is implicitly called by GC when object reference is no longer available. C# user can not call Finalize method. There is no way to call finalize method using code in C#. VB.net developer can do !!!! When user creates a desructor for a class CLR will generates the Finalize method for that class. Look at the code below,

public class Base
{

          // Use C# destructor syntax for finalization code.
          ~Base()
         {
                // Simply call Dispose(false).
         }
}

Fig – (1) A class with Destructor

       Above code shows Base class which has a destructor. So when the object of this class is no longer referenced the destroctur will be called. Now the question is this is destructor where is Finalize method ? You can get your answer when you see the IL generated by this code.

 Fig – (2) IL generated for Destructor (~Base())

        You can see that CLR has generated finalize method for destructor. Method has try and finally block.  The code written in destructor by user is inside the try block and finally block contains call to finalize method of System.Object class which is a base class of all the classes in dotnet.

        Finalize is protected and, therefore, is accessible only through this class or a derived class.

        This method is automatically called after an object becomes inaccessible, unless the object has been exempted from finalization by a call to SuppressFinalize. During shutdown of an application domain, Finalize is automatically called on objects that are not exempt from finalization, even those that are still accessible. Finalize is automatically called only once on a given instance, unless the object is re-registered using a mechanism such as ReRegisterForFinalize and GC.SuppressFinalize has not been subsequently called.

         Every implementation of Finalize in a derived type must call its base type’s implementation of Finalize. This is the only case in which application code is allowed to call Finalize.

         Finalize operations have the following limitations:

  • The exact time when the finalizer executes during garbage collection is undefined. Resources are not guaranteed to be released at any specific time, unless calling a Close method or a Dispose method.
  • The finalizers of two objects are not guaranteed to run in any specific order, even if one object refers to the other. That is, if Object A has a reference to Object B and both have finalizers, Object B might have already finalized when the finalizer of Object A starts.
  • The thread on which the finalizer is run is unspecified.

         The Finalize method might not run to completion or might not run at all in the following exceptional circumstances:

  • Another finalizer blocks indefinitely (goes into an infinite loop, tries to obtain a lock it can never obtain and so on). Because the runtime attempts to run finalizers to completion, other finalizers might not be called if a finalizer blocks indefinitely.
  • The process terminates without giving the runtime a chance to clean up. In this case, the runtime’s first notification of process termination is a DLL_PROCESS_DETACH notification.

         The runtime continues to Finalize objects during shutdown only while the number of finalizable objects continues to decrease.

          If Finalize or an override of Finalize throws an exception, the runtime ignores the exception, terminates that Finalize method, and continues the finalization process.

Summary

          A type must implement Finalize when it uses unmanaged resources such as file handles or database connections that must be released when the managed object that uses them is reclaimed. See the IDisposable interface for a complementary and more controllable means of disposing resources.

          Finalize can take any action, including resurrecting an object (that is, making the object accessible again) after it has been cleaned up during garbage collection. However, the object can only be resurrected once; Finalize cannot be called on resurrected objects during garbage collection.

          [C#] Destructors are the C# mechanism for performing cleanup operations. Destructors provide appropriate safeguards, such as automatically calling the base type’s destructor. In C# code, Object.Finalize cannot be called or overridden.

 

Dispose

          Lets talk about dispose now. As desribe above CLR implicitly calls Finalize method. However what if user explicitly wants to realease the resources used by object. Here the Dispose the method comes in to the picture. 

          A type’s Dispose method should release all the resources that it owns. It should also release all resources owned by its base types by calling its parent type’s Dispose method. The parent type’s Dispose method should release all resources that it owns and in turn call its parent type’s Dispose method, propagating this pattern through the hierarchy of base types. To help ensure that resources are always cleaned up appropriately, a Dispose method should be callable multiple times without throwing an exception.

           A Dispose method should call the GC.SuppressFinalize method for the object it is disposing. If the object is currently on the finalization queue, GC.SuppressFinalize prevents its Finalize method from being called. Remember that executing a Finalize method is costly to performance. If your Dispose method has already done the work to clean up the object, then it is not necessary for the garbage collector to call the object’s Finalize method.

         See the sample code for implementation of Dispose method.

public class Base : IDisposable
{
         //Implement IDisposable.
        public void Dispose()
        {
               Dispose(true);
               GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
       {
               if (disposing)
               {
                       // Free other state (managed objects).
               }
               // Free your own state (unmanaged objects).
               // Set large fields to null.
       }

       // Use C# destructor syntax for finalization code.
      ~Base()
      {
               // Simply call Dispose(false).
               Dispose(false);
      }
}

// Design pattern for a derived class.
public class Derived : Base
{
       protected override void Dispose(bool disposing)
       {
                if (disposing)
                {
                         // Release managed resources.
                }
                // Release unmanaged resources.
               // Set large fields to null.
              // Call Dispose on your base class.
              base.Dispose(disposing);
       }
       // The derived class does not have a Finalize method
       // or a Dispose method with parameters because it inherits
       // them from the base class.
}

Fig – (3) Dispose pattern for Base and derived class.

 

Happy Programming !!

Read Full Post »

        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

    Lets assume that you have following data in Example table.

Fig – (2) Data in Example table.

      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.

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.

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

Read Full Post »

          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,

 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()
   {
   }
}

Read Full Post »