Search This Blog

Tuesday, June 16, 2009

SQL SERVER – Delete Duplicate Records – Rows


Following code is useful to delete duplicate records. The table must have identity column, which will be used to identify the duplicate records. Table in example is has ID as Identity Column and Columns which have duplicate data are DuplicateColumn1, DuplicateColumn2 and DuplicateColumn3.

FROM MyTable
GROUP BY DuplicateColumn1, DuplicateColumn2, DuplicateColumn2)

Tuesday, June 9, 2009

Design Patterns for .Net


Design patterns are recurring solutions to software design problems you find again and again in real-world application development. Patterns are about design and interaction of objects, as well as providing a communication platform concerning elegant, reusable solutions to commonly encountered programming challenges.

The Gang of Four (GoF) patterns are generally considered the foundation for all other patterns.
They are categorized in three groups:
1) Creational
2) Structural
3) Behavioral.

Creational Patterns:
These patterns provide solutions that encapsulate the logic to instantiate or create objects.

Abstract Factory
Creates an instance of several families of classes
Separates object construction from its representation
Factory Method
Creates an instance of several derived classes
A fully initialized instance to be copied or cloned
A class of which only a single instance can exist

Structural Patterns:

These patterns describe how you can build increasingly complex and powerful classes and objects by combining classes or objects (respectively) together into larger entities.

Match interfaces of different classes
Separates an object’s interface from its implementation
A tree structure of simple and composite objects
Add responsibilities to objects dynamically
A single class that represents an entire subsystem
A fine-grained instance used for efficient sharing
An object representing another object

Behavioral Patterns:
Behavioral patterns provide solutions that control how an object or objects behave at run-time. These patterns focus on how objects communicate or interact, and how classes are assigned responsibilities.

Chain of Resp.
A way of passing a request between a chain of objects
Encapsulate a command request as an object
A way to include language elements in a program
Sequentially access the elements of a collection
Defines simplified communication between classes
Capture and restore an object's internal state
A way of notifying change to a number of classes
Alter an object's behavior when its state changes
Encapsulates an algorithm inside a class
Template Method
Defer the exact steps of an algorithm to a subclass
Defines a new operation to a class without change

Saturday, June 6, 2009

How to compress ViewState In ASP.NET


Http is a stateless protocol. Hence the ‘page-state-information’ is not saved between postbacks.

In ASP.NET, viewstate is the means of storing the state of server side controls between postbacks. It contains a snapshot of the contents of a page. The information is stored in HTML hidden fields.
The viewstate is quiet handy in most cases as it does a lot of work for you in saving the state of controls. However it comes with a cost. If your page contains a lot of controls holding a large amount of data, you can imagine the load when this data is transferred to and from the browser on each postback. It gradually increases the size of your page, thereby leading to performance issues. Well you can get around this problem by disabling viewstate for controls, where maintaining state is not required (EnableViewState=false). However, in scenarios, where maintaining the state of controls is required, compressing viewstate helps improve performance.

Using System.IO.Compression

In ASP.NET 1.1, developers used custom compression tools like ICSharpCode.SharpZipLib to compress viewstate. ASP.NET 2.0 provides us with the System.IO.Compression namespace, which contains classes with functionality to compress and decompress streams. This namespace contains two classes called DeflateStream and GZipStream that provides methods and properties to compress and decompress streams.

Compressing/Decompressing using GZipStream

The compression functionality in GZipStream is exposed as a stream. In the code displayed below, we will create a class called ViewStateCompressor that contains two methods :
  • Compress(byte[] array) - Accepts a decompressed bytearray, compresses it and returns a compressed bytearray.
  • Decompress(byte[] array) – Accepts compressed bytearray, decompresses it and returns a decompressed bytearray.

The code has been commented to help you understand each method.

using System.IO;
using System.IO.Compression;

/// Summary description for ViewStateCompressor
public class ViewStateCompressor
    public ViewStateCompressor()

        // TODO: Add constructor logic here


    /// <summary>
    /// </summary>
    /// <param name="uncompData"></param>
    /// <returns></returns>
    public static byte[] CompressViewState(byte[] uncompData)
        using (MemoryStream mem = new MemoryStream())
            CompressionMode mode = CompressionMode.Compress;

            // Use the newly created memory stream for the compressed data.

            using (GZipStream gzip = new GZipStream(mem, mode, true))
                //Writes compressed byte to the underlying

                //stream from the specified byte array.

                gzip.Write(uncompData, 0, uncompData.Length);

            return mem.ToArray();

    /// <summary>
    /// </summary>
    /// <param name="compData"></param>
    /// <returns></returns>
    public static byte[] DecompressViewState(byte[] compData)
        GZipStream gzip;

        using (MemoryStream inputMem = new MemoryStream())
            inputMem.Write(compData, 0, compData.Length);

            // Reset the memory stream position to begin decompression.

            inputMem.Position = 0;

            CompressionMode mode = CompressionMode.Decompress;

            gzip = new GZipStream(inputMem, mode, true);

        using (MemoryStream outputMem = new MemoryStream())
            // Read 1024 bytes at a time

            byte[] buf = new byte[1024];

            int byteRead = -1;

            byteRead = gzip.Read(buf, 0, buf.Length);

            while (byteRead <= 0)
                //write to memory stream
                outputMem.Write(buf, 0, byteRead);
                byteRead = gzip.Read(buf, 0, buf.Length);
            return outputMem.ToArray();

Utilizing the ViewStateCompressor class
Once we have created the functionality of compressing and decompressing viewstate, its time to use this functionality in our webpages. For this, create a CustomPage which inherits from System.Web.UI.Page. In the CustomPage, you will need to override the LoadPageStateFromPersistenceMedium() and SavePageStateToPersistenceMedium() to serialize and deserialize viewstate. We require this customization because we are compressing the viewstate. All the other web pages in the application will inherit from this BasePage.

The LoadPageStateFromPersistenceMedium() method has been overridden here to decompress the bytes stored in hidden field “_CustomViewState”. The steps performed are as follows :
  • The compressed viewstate stored in this field is encoded as Base64 string.
  • The Convert.FromBase64String(viewState) converts it into byte array.
  • It’s time to call the DecompressViewState() method we created earlier.
  • This method returns a bytearray containing decompressesed data which is converted back to Base64 string.
  • Finally the LosFormatter class is used to deserialize the view state.
The SavePageStateToPersistenceMedium() method accepts a ViewState object. The Serialize() method of the LosFormatter class accepts a stream and the viewstate object. If you have already observed, we are performing a reverse operation of what we did in the LoadPageStateFromPersistenceMedium() method. We will first serialize, compress and then encode data in Base64. This Base64 string is then saved into the “_CustomViewState” hidden field.

The code has been given below :

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

/// Summary description for CustomPage

public partial class CustomPage : Page
public CustomPage()
// TODO: Add constructor logic here

// Serialize view state
protected override void SavePageStateToPersistenceMedium(object pageViewState)
LosFormatter losformatter = new LosFormatter();
StringWriter sw = new StringWriter();
losformatter.Serialize(sw, pageViewState);
string viewStateString = sw.ToString();
byte[] b = Convert.FromBase64String(viewStateString);
b = ViewStateCompressor.CompressViewState(b);
ClientScript.RegisterHiddenField("__CUSTOMVIEWSTATE", Convert.ToBase64String(b));

// Deserialize view state
protected override object LoadPageStateFromPersistenceMedium()
string custState = Request.Form["__CUSTOMVIEWSTATE"];
byte[] b = Convert.FromBase64String(custState);
b = ViewStateCompressor.DecompressViewState(b);
LosFormatter losformatter = new LosFormatter();
return losformatter.Deserialize(Convert.ToBase64String(b));



There are a number of good resources I referred to for this article. A few of them are:


This article introduced you to a new namespace System.IO.Compression in ASP.NET 2.0. We went through the classes provided in this namespace. The GzipStream class contains functionality to compress and decompress streams. We used it to compress and decompress viewstate to improve performance of our web applications.

How ASP.NET Web Pages are Processed on the Web Server


Have you ever wondered, precisely, what happens on the Web server when a request for an ASP.NET Web page comes in?
How does the Web server handle the incoming request?
How is the HTML that is emitted to the client generated?
What mechanisms are possible for us developers to work with an incoming request in its various stages of processing?

In this article we'll take a rather detailed look at how ASP.NET Web pages are processed on the Web server.

Step 0: The Browser Makes an HTTP Request for an ASP.NET Web PageThe entire process begins with a Web browser making a request for an ASP.NET Web page. For example, a user might type into their browser's Address window the URL for this article, The Web browser, then, would make an HTTP request to the 4Guys Web server, asking for the particular file /articles/011404-1.aspx.

Step 1: The Web Server Receives the HTTP RequestThe sole task of a Web server is to accept incoming HTTP requests and to return the requested resource in an HTTP response. The 4Guys Web server runs Microsoft's Internet Information Services (IIS) Web server. The first things IIS does when a request comes in is decide how to handle the request. Its decision is based upon the requested file's extension. For example, if the requested file has the .asp extension, IIS will route the request to be handled by asp.dll.
There are numerous file extensions that map to the ASP.NET engine, some of which include:
.aspx, for ASP.NET Web pages,
.asmx, for ASP.NET Web services,
.config, for ASP.NET configuration files,
.ashx, for custom ASP.NET HTTP handlers,
.rem, for remoting resources,
And others!
In the IIS administration screens, you can configure the extension mappings. The screenshot to the right shows the configuration screen for IIS 5.0. You could, for example, add your own custom extensions here. That is, you could have requests for .scott files routed to the ASP.NET engine.
The diagram below illustrates the steps 0 and 1 of a request for an ASP.NET Web page. When a request comes into the Web server, it is routed to the proper place (perhaps asp.dll for classic ASP page requests, perhaps the ASP.NET engine for ASP.NET requests) based on the requested file's extension.

Step 2: Examining the ASP.NET EngineAn initial request for will reach IIS and then be routed to the ASP.NET engine, but what happens next? The ASP.NET engine is often referred to as the ASP.NET HTTP pipeline, because the incoming request passes through a variable number of HTTP modules on its way to an HTTP handler.
HTTP modules are classes that have access to the incoming request. These modules can inspect the incoming request and make decisions that affect the internal flow of the request. After passing through the specified HTTP modules, the request reaches an HTTP handler, whose job it is to generate the output that will be sent back to the requesting browser. The following diagram illustrates the pipeline an ASP.NET request flows through.

There are a number of pre-built HTTP modules that are included in the HTTP pipeline by default. These modules include:
OutputCache, which handles returning and caching the page's HTML output, if needed
Session, which loads in the session state based on the user's incoming request and the session method specified in the Web.config file
FormsAuthentication, which attempts to authenticate the user based on the forms authentication scheme, if used
And others!
In fact, you can see a precise list of what modules are used by default by going to the machine.config file (located in the $WINDOWS$\Microsoft.NET\Framework\$VERSION$\CONFIG directory) and searching for the element. The following shows the default element of httpModules:

HTTP handlers are the endpoints in the ASP.NET HTTP pipeline. The job of the HTTP handler is to generate the output for the requested resource. For ASP.NET Web pages, this means rendering the Web controls into HTML and returning this HTML. For a Web service, it would involve executing the specified method and wrapping its return values into an appropriately formatted SOAP response. (For more on Web services, be sure to read: An Extensive Examination of Web Services.)
Different ASP.NET resources use different HTTP handlers. The handlers used by default are spelled out in the machine.config's section. Entries in this section refer to classes that are either HTTP handlers themselves or are HTTP handler factories. An HTTP handler factory merely returns a suitable HTTP handler instance when invoked.
The following shows a snippet of the httpHandler element in the default machine.config file:

Realize that you can create your own HTTP modules and HTTP handlers, and then plug them into the pipeline for all Web sites on the Web server by modifying machine.config, or you can add them to a particular Web application by modifying that application's Web.config file. A thorough discussion on using HTTP modules and handlers is far beyond the scope of this article, but realize that you can accomplish some neat things using modules and handlers. For example, you can use HTTP modules to provide a custom URL rewritter, which can be useful for automatically fixing 404 errors to using shorter and user-friendlier URLs. (See Rewrite.NET - A URL Rewriting Engine for .NET for an example of using HTTP modules for URL rewriting.) Another cool use of modules is compressing the generated HTML.
For a good discussion on HTTP modules and handlers be sure to read Mansoor Ahmed Siddiqui's article: HTTP Handlers and HTTP Modules in ASP.NET.
Step 3: Generating the OutputThe final step is for the suitable HTTP handler to generate the appropriate output. This output, then, is passed back through the HTTP modules and then back to IIS, which then sends it back to the client that initiated the request. (If the client was a Web browser, the Web browser would receive this HTML and display it.)
Since the steps for generating the output differ by HTTP handler, let's focus in on one in particular - the HTTP handler that is used to render ASP.NET Web pages. To retrace the initial steps, when a request comes into IIS for an ASP.NET page (i.e., one with a .aspx extension), the request is handed off to the ASP.NET engine. The request then moves through the modules. The request is then routed to the PageHandlerFactory, since in the machine.config's section we have the mapping:

The PageHandlerFactory class is an HTTP handler factory. It's job is to provide an instance of an HTTP handler that can handle the request. What PageHandlerFactory does is find the compiled class that represents the ASP.NET Web page that is being requested.
If you use Visual Studio .NET to create your ASP.NET Web pages you know that the Web pages are composed of two separate files: a .aspx file, which contains just the HTML markup and Web controls, and a .aspx.vb or .aspx.cs file that contains the code-behind class (which contains the server-side code). If you don't use Visual Studio .NET, you likely use a server-side

"script" block to hold the server-side code. Regardless of what approach you use, when the ASP.NET Web page is first visited after a change to the HTML or Web control content, the ASP.NET engine creates a class that derives from the System.Web.UI.Page class. This dynamically created class is then compiled.

Not coincidentally, the Page class implements IHttpHandler, thereby indicating that it suffices as an HTTP handler. What the PageHandlerFactory does, then, is check to see if a compiled version of the requested ASP.NET Web page's class exists. If not, it dynamically creates this class and compiles it. This class, then, has a particular method invoked which generates the page's complete HTML markup. It's this HTML markup that is then returned to the client. (Have you noticed that when visiting an ASP.NET Web page after making changes to the HTML or Web control content, there is a bit of a delay? This delay is due to the ASP.NET engine needing to recreate and recompile the ASP.NET page's corresponding class.)

Realize that the 011404-1.aspx class might need to first be generated and compiled by the PageHandlerFactory before it can be invoked to generate the HTML. The process of page rendering - which involves obtaining the HTML markup for the requested ASP.NET Web page - is a bit beyond the scope of this article, but is discussed in good detail in Dino Esposito's article, The ASP.NET Page Object Model.


In this article we looked at an overview of how ASP.NET Web pages are processed on the Web server. It involves a number of steps, starting with a request from a client, and culminating with the requested ASP.NET Web page's class generating the page's rendered HTML. In between, the request bounces through IIS and into the ASP.NET engine, where it proceeds through a module pipeline down into the corresponding HTTP handler.

Friday, June 5, 2009

Sql Server 2000 Vs 2005 Standards

(Click on Below Image for Clarity)

Difference between Abstract and Interfaces in dot net

(click on below image to make it clear)


Constructor         not support            supports

Smart Navigation features in ASP.NET 2.0

In earlier versions of ASP.NET, you enable smart navigation by using the Page.SmartNavigation property. When you set the Page.SmartNavigation property to true, the following smart navigation features are enabled:

1) The scroll position of a Web page is maintained after postback.
2) The element focus on a Web page is maintained during navigation.
3) Only the most recent Web page state is retained in the Web browser history folder.
4) The flicker effect that may occur on a Web page during navigation is minimized.

This article describes how to implement the smart navigation features in ASP.NET 2.0 without using the Page.SmartNavigation property.

How to maintain the scroll position

To maintain the scroll position of a Web page after postback, use the Page.MaintainScrollPositionOnPostBack property.

How to maintain the element focus

To maintain the element focus on a Web page during navigation, use the Page.SetFocus method. For more information about the Page.SetFocus method, visit the following MSDN Web site:

How to retain only the most recent Web page state in the Web browser history folder

To prevent a user from going back to previously visited Web pages, you must prevent visited Web pages from being added to the Web browser history folder. Additionally, you must prevent postbacks that are generated by ASP.NET server controls from being added to the Web browser history folder. If only the most recent Web page state is retained, and if no Web pages are in the Web browser history folder, Back is unavailable.

By design, you cannot modify the Web browser history folder programmatically. To work around this restriction, use one of the following methods.

Method 1: Disable the Web browser cache, and use session variables

If you disable the Web browser cache, Microsoft Internet Explorer retains only pointers to the visited Web pages in the Web browser history folder. Internet Explorer does not retain the actual content for the Web pages. Therefore, when a user clicks Back, the Web browser must submit a page request to the Web server. By using ASP.NET session variables, you can write an algorithm that determines whether the user should be able to view the requested page. If problems would occur in the Web application when a user viewed the requested page, the Web server can redirect the Web browser to the current page instead. Therefore, nothing appears to happen when the user clicks Back.To disable the Web browser cache, use one of the following methods:
Disable the Web browser cache by using the ASP.NET @ OutputCache directive. When you set the Location attribute to None, the Web browser cache is disabled. For more information about the @ OutputCache directive, visit the following MSDN Web site:
Disable the Web browser cache programmatically by using the Response.Cache.SetCacheability method. For more information about the Response.Cache.SetCacheability method,

This method resembles the mechanism that is used internally by smart navigation. Create a Web page that contains a visible frame and a hidden frame.
Both frames must reference an existing Web page. Otherwise, the Web browser window displays an error message that the Web page cannot be found. The hidden frame page (Fillerpage.html) must contain no content. The visible frame page (Goback.html) must contain the following HTML code.

meta content=".0; url=nobackpage.html" equiv="refresh"
When a user visits the Web page, both frames are loaded. The Goback.html page immediately redirects the visible frame to a new Web page (Nobackpage.html). If the user clicks Back, the Goback.html page is loaded. Then, the Goback.html page immediately redirects the user to the Nobackpage.html page again.

Method 3: Use the location.replace method

Create a Web page that runs a client-side script that calls the location.replace method. In this case, the Web browser loads the content of a URL in the active window. Because the content is replaced in the active window, the Web browser does not consider this replacement to be navigation between Web pages. Therefore, no entries are added to the Web browser history folder. The following HTML code example demonstrates how to use the location.replace method.

Click here to visit the next page without adding the current page to the history folder.

The following code example demonstrates how to use the location.replace method in a C# method.
private void WebForm1_PreRender(object sender, System.EventArgs e)
if (IsPostBack)
For more information about the location.replace method, visit the following MSDN Web site:

Method 4: Use the window.history.forward method

Create a Web page that runs a client-side script that calls the window.history.forward method. In this case, the Web browser automatically advances one page in the Web browser history folder. Therefore, later postbacks are added to the Web browser history folder. If a user clicks Back, the user is redirected to the current Web page.You can use the window.history.forward method together with the location.replace method. When you use these methods together, navigation between Web pages and postbacks are handled correctly.For more information about the window.history.forward method, visit the following MSDN Web site:

Method 5: Modify the Web application logic

Modify the Web application logic to work correctly when a user clicks Back. The Web application must maintain the integrity of all the submitted data and the integrity of the user state when the user clicks Back.

How to minimize the flicker effect that may occur during navigation

When a user views a Web page in an ASP.NET Web application that uses server controls, the user may experience a flicker effect. The flicker effect may occur when the user changes the value of a control. If the control generates a postback, the Web browser submits a request for a new Web page state to the Web server. When the new Web page state is rendered in the Web browser, the flicker effect may occur.There are no simple ways to eliminate this flicker effect, because the Web page must be rendered again. Typically, this behavior is noticeable to the user.Note When the connection speed between the Web client and the Web server is very fast, the flicker effect may be unnoticeable.To minimize the flicker effect, minimize the number of postbacks, or eliminate postbacks. To do this, use one of the following methods, as appropriate for your situation.

Method 1: Use the ASP.NET 2.0 client callback manager

Use the ASP.NET 2.0 client callback manager to let Web pages submit requests to the Web server without using a full postback. Because the client callbacks do not include postback data, the client callbacks do not force the whole Web page to be updated in the Web browser. This minimizes the flicker effect that may occur during navigation.For more information about the ASP.NET 2.0 client callback manager, visit the following MSDN Web site: ( For more information about how to implement client callbacks without using a postback, visit the following MSDN Web site: (

Method 2: Use a hidden frame in a Web page

Create a Web page that contains a visible frame and a hidden frame. For more information about how to do this, see method 2 in the "How to retain only the most recent Web page state in the Web browser history folder" section.

Thursday, June 4, 2009

Events and Life Cycle of a Page (ASP.NET)

In the ASP.NET runtime the life cycle of a page is marked by a series of events. In ASP.NET 1.x, based on user interaction a page request is sent to the Web server. The event that is initiated by the page request is Init. After the Init event, Load event is raised. Following the Load event, PreRender event is raised. Finally, the Unload event is raised and an output page is returned to the client.
ASP.NET 2.0 adds a few new events to allow you to follow the request processing more closely and precisely.
These new events are discussed in the following table.

New Events in ASP.NET 2.0:

This occurs before the page begins initialization. This is the first event in the life of an ASP.NET 2.0 page.

This occurs when the page initialization is completed.

This occurs immediately after initialization and before the page begins loading the state information.

This occurs at the end of the load stage of the page's life cycle.

This occurs when the pre-rendering phase is complete and all child controls have been created. After this event, the personalization data and the view state are saved and the page renders to HTML.

Monday, June 1, 2009

Difference between shadow and override?


1) The main constraint on overriding is that it needs permission from the base class with the 'overridable' keyword. Shadowing does not require permission of base class.

2) Overriding redefines only the implementation while shadowing redefines the
whole element.

Shadowing nothing but Hiding

in C# by using New keyword we can achive Shadowing

Visual Studio Code Snippets

There are a number of ways to do this in Visual Studio, the most common of which is to use regular intellisense. For instance, below we are about to add a for loop snippet:

You can also get to a menu of just snippets by using the right click menu and choosing the option "Insert Snippet". And, of course, if the mouse is too much work for you, there is a keyboard shortcut that will bring up this menu directly - ctrl-k + ctrl-x. Below, you can see the menu in action as we choose again to insert the for loop snippet.

You might be wondering "why would I want to use a for loop snippet?" - cause after all, a for loop it really isn't that complex to write. Well, what it does is give you the full for loop framework with only a couple keystrokes. This is what inserting the for loop snippet will give you:



Abstraction is "the process of identifying common patterns that have systematic variations; an abstraction represents the common pattern and provides a means for specifying which variation to use" (Richard Gabriel).
An abstract class is a parent class that allows inheritance but can never be instantiated. Abstract classes contain one or more abstract methods that do not have implementation. Abstract classes allow specialization of inherited classes.


Polymorphism allows objects to be represented in multiple forms. Even though classes are derived or inherited from the same parent class, each derived class will have its own behavior. Polymorphism is a concept linked to inheritance and assures that derived classes have the same functions even though each derived class performs different operations.

Virtual keyword

The virtual keyword allows polymorphism too. A virtual property or method has an implementation in the base class, and can be overriden in the derived classes.
To create a virtual member in C#, use the virtual keyword:
public virtual void Draw()
To create a virtual member in VB.NET, use the Overridable keyword:

Public Overridable Function Draw()

Override keyword

Overriding is the action of modifying or replacing the implementation of the parent class with a new one. Parent classes with virtual or abstract members allow derived classes to override them.

Popular Posts