Search This Blog

Monday, December 21, 2009

How Internet Search Engines Work



























Always: Make every page on your site accessible via a text-based link - as opposed to Javascript, Flash, DHTML, etc. The Googly Spider only understands text.
Keep the number of links on a given page less than 100. This is from Google's Webmaster Guidelines .
Use the TITLE tag: give every page on the site a complete and meaningful

difference between Temp tables and Table variables in Sql Server

            Difference between Temp tables and Table variables in Sql Server

1)      Transaction logs are not recorded for the table variables. They are variables and thus aren't bound to a transaction.
      Temp tables behave same as normal tables and are bound by transactions.
2)      Any procedure with a temporary table cannot be pre-compiled, while an execution plan of procedures with table variables can be statically compiled in advance. Pre-compiling a script gives a major advantage to its speed of execution. This advantage can be dramatic for long procedures, where recompilation can be too pricy.
3)      Table variables exist only in the same scope as variables. Contrary to the temporary tables, they are not visible in inner stored procedures and in exec (string) statements. Also, they cannot be used in an insert/exec statement.
4)      As a rule of thumb, for small to medium volumes of data and simple usage scenarios you should use table variables.
5)      If we use Temporary Table in a stored procedure, we should drop it at the end. It is not necessary in the case of Table variable.

A simple example shows this difference quite nicely:

GO
 BEGIN TRAN
        declare @var table (id int, data varchar(20) )
        create table #temp (id int, data varchar(20) )
       
        insert into @var
        select 1, 'data 1' union all
        select 2, 'data 2' union all
        select 3, 'data 3'
       
        insert into #temp
        select 1, 'data 1' union all
        select 2, 'data 2' union all
        select 3, 'data 3'
       
        select * from #temp
        select * from @var

ROLLBACK

select * from @var
if object_id('tempdb..#temp') is null
    select '#temp does not exist outside the transaction'

GO

We see that the table variable still exists and has all it's data unlike the temporary table that doesn't exists when the transaction rollbacked.

Saturday, December 19, 2009

STANDARD QUERY OPERATORS



LINQ examples, Keywords, faq's

.

In Visual Studio you can write LINQ queries in Visual Basic or C# with SQL Server databases, XML documents, ADO.NET Datasets, and any collection of objects that supports IEnumerable or the generic IEnumerable<(Of <(T>)>) interface. LINQ support for the ADO.NET Entity Framework is also planned, and LINQ providers are being written by third parties for many Web services and other database implementations.

• SQL Server databases: LINQ to SQL
• XML documents: LINQ to XML
• ADO.NET Datasets: LINQ to DataSet
• .NET collections, files, strings and so on: LINQ to Objects

Query Keywords (C#)

from
Specifies a data source and a range variable (similar to an iteration variable).

where
Filters source elements based on one or more Boolean expressions separated by logical AND and OR operators ( && or || ).

select
Specifies the type and shape that the elements in the returned sequence will have when the query is executed.

group
Groups query results according to a specified key value.

into
Provides an identifier that can serve as a reference to the results of a join, group or select clause.

orderby
Sorts query results in ascending or descending order based on the default comparer for the element type.

join
Joins two data sources based on an equality comparison between two specified matching criteria.

let
Introduces a range variable to store sub-expression results in a query expression.

in
Contextual keyword in a join clause.

on
Contextual keyword in a join clause.

equals
Contextual keyword in a join clause.

by
Contextual keyword in a group clause.

ascending
Contextual keyword in an orderby clause.

descending
Contextual keyword in an orderby clause.


Generation of c# class based on Database tables, Procs etc by using following command(in VS Command prompt)

sqlmetal /server:ServerName /database:DBName /namespace:LinqEnabledWebSite /code:ClasssName.cs /language:csharp /user:uid /password:pwd /sprocs


LINQ Queries


// Northwnd inherits from System.Data.Linq.DataContext.
Northwnd nw = new Northwnd(@"northwnd.mdf");
var companyNameQuery = from cust in nw.Customers where cust.City == "London" select cust.CompanyName;

LINQ FAQ’s

Q. What is LINQ?

LINQ is a set of language features introduced in .NET 3.5 (shipping Visual Studio 2008) that allow you to write queries similar to SQL like statements in Visual Basic or C# programs (other language support is available, but these are the main ones). LINQ knows the data-source you are trying to query (SQL Server, object collection, or another source) and executes the query expression returning the result in the form you ask.


Q. What is LINQ to SQL?
LINQ to SQL is a specific LINQ implementation for SQL Server. LINQ to SQL converts LINQ queries written in C# or Visual Basic into dynamic SQL, execute it on the server and marshal the results in return. LINQ to SQL also supports making changes to the returned objects and applying those updates back to the database. These updates can be applied by the LINQ framework using dynamic SQL or Stored Procedures. See: LINQ to SQL main page, and LINQ to SQL 5 minute overview.



Q. How do I enable LINQ to SQL in my code?
To use LINQ to SQL in Visual Studio 2008 -

1) add a reference to the System.Data.Linq.dll (if it is grayed out, go to your project properties and set the target framework to .NET 3.5)
2) add the following using statement at the top of your class file: using System.Data.Linq;



Q. What versions of C# Supports LINQ?
C#3.0 that ships in the .NET 3.5 framework as part of Visual Studio 2008 supports LINQ. It was possible to run a LINQ preview in Visual Studio 2005 mid 2006, but as the beta releases of Visual Studio 2008 became available this support was dropped.


Q. Do I need to know LINQ syntax to program?
No. Developing using LINQ is completely optional. LINQ does remove a lot of the traditional ADO.NET complexity.


Q. What .NET languages currently support LINQ?
Currently C# and Visual Basic shipping with the .NET Framework 3.5 (in Visual Studio 2008) have specific language features and debugger support for LINQ.


Q. Am I exposed to SQL Injection attacks?
No. LINQ to SQL passes all data to the database via SQL parameters. So, although the SQL query is composed dynamically, the values are substitued server side through parameters safeguarding against the most common cause of SQL injection attacks. Security is a big topic though, so stay diligant!


Q. Does LINQ to SQL support Stored Procedures?
Yes. LINQ to SQL supports calling Stored Procedures by directly wrapping them in strongly typed C# or VB method signatures. It also supports you specifying a specific Insert, Update and Delete stored procedures to make the appropriate changes to the database based on onject updates made in C# and VB.


Q. How can I support Optional Parameters when calling a Stored Procedure through LINQ to SQL?
See this article on the subject: Stored Procedure Optional Parameters using LINQ to SQL


Q. Can LINQ to SQL perform batch updates and deletes? Or does it always do one row update at a time?
By default, LINQ to SQL will perform a single row update when datacontext.SubmitChanges() is called after many rows have been deleted, or modified.

LINQ Queries ( Joins )

join clause

The join clause is useful for associating elements from different source sequences that have no direct relationship in the object model. The only requirement is that the elements in each source share some value that can be compared for equality. For example, a food distributor might have a list of suppliers of a certain product, and a list of buyers. A join clause can be used, for example, to create a list of the suppliers and buyers of that product who are all in the same specified region.

A join clause takes two source sequences as input. The elements in each sequence must either be or contain a property that can be compared to a corresponding property in the other sequence. The join clause compares the specified keys for equality by using the special equals keyword. All joins performed by the join clause are equijoins. The shape of the output of a join clause depends on the specific type of join you are performing. The following are three most common join types:

• Inner join
• Group join
• Left outer join

Inner Join

The following example shows a simple inner equijoin. This query produces a flat sequence of “product name / category” pairs. The same category string will appear in multiple elements. If an element from categories has no matching products, that category will not appear in the results.

var innerJoinQuery =
from category in categories
join prod in products on category.ID equals prod.CategoryID
select new { ProductName = prod.Name, Category = category.Name };
//produces flat sequence


Group Join

A join clause with an into expression is called a group join.

var innerGroupJoinQuery =
from category in categories
join prod in products on category.ID equals prod.CategoryID into prodGroup
select new { CategoryName = category.Name, Products = prodGroup };

A group join produces a hierarchical result sequence, which associates elements in the left source sequence with one or more matching elements in the right side source sequence. A group join has no equivalent in relational terms; it is essentially a sequence of object arrays.

If no elements from the right source sequence are found to match an element in the left source, the join clause will produce an empty array for that item. Therefore, the group join is still basically an inner-equijoin except that the result sequence is organized into groups.

If you just select the results of a group join, you can access the items, but you cannot identify the key that they match on. Therefore, it is generally more useful to select the results of the group join into a new type that also has the key name, as shown in the previous example.

You can also, of course, use the result of a group join as the generator of another subquery:

var innerGroupJoinQuery2 =
from category in categories
join prod in products on category.ID equals prod.CategoryID into prodGroup
from prod2 in prodGroup
where prod2.UnitPrice > 2.50M
select prod2;


Left Outer Join

In a left outer join, all the elements in the left source sequence are returned, even if no matching elements are in the right sequence. To perform a left outer join in LINQ, use the DefaultIfEmpty method in combination with a group join to specify a default right-side element to produce if a left-side element has no matches. You can use null as the default value for any reference type, or you can specify a user-defined default type. In the following example, a user-defined default type is shown:

var leftOuterJoinQuery =
from category in categories
join prod in products on category.ID equals prod.CategoryID into prodGroup
from item in prodGroup.DefaultIfEmpty(new Product{Name = String.Empty, CategoryID = 0})
select new { CatName = category.Name, ProdName = item.Name };


The equals operator
A join clause performs an equijoin. In other words, you can only base matches on the equality of two keys. Other types of comparisons such as "greater than" or "not equals" are not supported. To make clear that all joins are equijoins, the join clause uses the equals keyword instead of the == operator. The equals keyword can only be used in a join clause and it differs from the == operator in one important way. With equals, the left key consumes the outer source sequence, and the right key consumes the inner source. The outer source is only in scope on the left side of equals and the inner source sequence is only in scope on the right side.

Monday, November 30, 2009

String Format for Double [C#]

The following examples show how to format float numbers to string in C#. You can use static method String.Format or instance methods double.ToString and float.ToString.

Digits after decimal point
This example formats double to string with fixed number of decimal places. For two decimal places use pattern „0.00“. If a float number has less decimal places, the rest digits on the right will be zeroes. If it has more decimal places, the number will be rounded.


// just two decimal places
String.Format("{0:0.00}", 123.4567); // "123.46"
String.Format("{0:0.00}", 123.4); // "123.40"
String.Format("{0:0.00}", 123.0); // "123.00"

Next example formats double to string with floating number of decimal places. E.g. for maximal two decimal places use pattern „0.##“.


// max. two decimal places
String.Format("{0:0.##}", 123.4567); // "123.46"
String.Format("{0:0.##}", 123.4); // "123.4"
String.Format("{0:0.##}", 123.0); // "123"

Digits before decimal point

If you want a float number to have any minimal number of digits before decimal point use N-times zero before decimal point. E.g. pattern „00.0“ formats a float number to string with at least two digits before decimal point and one digit after that.


// at least two digits before decimal point
String.Format("{0:00.0}", 123.4567); // "123.5"
String.Format("{0:00.0}", 23.4567); // "23.5"
String.Format("{0:00.0}", 3.4567); // "03.5"
String.Format("{0:00.0}", -3.4567); // "-03.5"


Thousands separator
To format double to string with use of thousands separator use zero and comma separator before an usual float formatting pattern, e.g. pattern „0,0.0“ formats the number to use thousands separators and to have one decimal place.

String.Format("{0:0,0.0}", 12345.67); // "12,345.7"
String.Format("{0:0,0}", 12345.67); // "12,346"

Zero
Float numbers between zero and one can be formatted in two ways, with or without leading zero before decimal point. To format number without a leading zero use # before point. For example „#.0“ formats number to have one decimal place and zero to N digits before decimal point (e.g. „.5“ or „123.5“).

Following code shows how can be formatted a zero (of double type).

String.Format("{0:0.0}", 0.0); // "0.0"
String.Format("{0:0.#}", 0.0); // "0"
String.Format("{0:#.0}", 0.0); // ".0"
String.Format("{0:#.#}", 0.0); // ""

Align numbers with spaces

To align float number to the right use comma „,“ option before the colon. Type comma followed by a number of spaces, e.g. „0,10:0.0“ (this can be used only in String.Format method, not in double.ToString method). To align numbers to the left use negative number of spaces.

String.Format("{0,10:0.0}", 123.4567); // " 123.5"
String.Format("{0,-10:0.0}", 123.4567); // "123.5 "
String.Format("{0,10:0.0}", -123.4567); // " -123.5"
String.Format("{0,-10:0.0}", -123.4567); // "-123.5 "

Custom formatting for negative numbers and zero
If you need to use custom format for negative float numbers or zero, use semicolon separator „;“ to split pattern to three sections. The first section formats positive numbers, the second section formats negative numbers and the third section formats zero. If you omit the last section, zero will be formatted using the first section.


String.Format("{0:0.00;minus 0.00;zero}", 123.4567); // "123.46"
String.Format("{0:0.00;minus 0.00;zero}", -123.4567); // "minus 123.46"
String.Format("{0:0.00;minus 0.00;zero}", 0.0); // "zero"

Some funny examples

As you could notice in the previous example, you can put any text into formatting pattern, e.g. before an usual pattern „my text 0.0“. You can even put any text between the zeroes, e.g. „0aaa.bbb0“.


String.Format("{0:my number is 0.0}", 12.3); // "my number is 12.3"
String.Format("{0:0aaa.bbb0}", 12.3); // "12aaa.bbb3"

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.

DELETE
FROM
MyTable
WHERE ID NOT IN
(
SELECT MAX(ID)
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
Builder
Separates object construction from its representation
Factory Method
Creates an instance of several derived classes
Prototype
A fully initialized instance to be copied or cloned
Singleton
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.

Adapter
Match interfaces of different classes
Bridge
Separates an object’s interface from its implementation
Composite
A tree structure of simple and composite objects
Decorator
Add responsibilities to objects dynamically
Facade
A single class that represents an entire subsystem
Flyweight
A fine-grained instance used for efficient sharing
Proxy
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
Command
Encapsulate a command request as an object
Interpreter
A way to include language elements in a program
Iterator
Sequentially access the elements of a collection
Mediator
Defines simplified communication between classes
Memento
Capture and restore an object's internal state
Observer
A way of notifying change to a number of classes
State
Alter an object's behavior when its state changes
Strategy
Encapsulates an algorithm inside a class
Template Method
Defer the exact steps of an algorithm to a subclass
Visitor
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);
            }
            gzip.Close();
            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));
}

}


References

There are a number of good resources I referred to for this article. A few of them are:
http://www.dotnetbips.com/articles/22d33d11-1a75-42c8-bbf6-ca1a345d3fcf.aspx
http://www.codeproject.com/aspnet/ViewStateCompression.asp
http://www.eggheadcafe.com/articles/20040613.asp

Conclusion

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

.
Introduction

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, http://aspnet.4guysfromrolla.com/articles/011404.aspx. 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

http://aspnet.4guysfromrolla.com/articles/011404.aspx 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.

Conclusion

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:
http://msdn2.microsoft.com/en-us/library/hdxfb6cy.aspx
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)
{
Response.Write("
\n");
Response.End();
}
}
For more information about the location.replace method, visit the following MSDN Web site:
http://msdn2.microsoft.com/en-us/library/ms536712.aspx

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:
http://msdn2.microsoft.com/en-us/library/ms536426.aspx

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:
http://msdn.microsoft.com/msdnmag/issues/06/00/ASPNET20Overview/default.aspx (http://msdn.microsoft.com/msdnmag/issues/06/00/ASPNET20Overview/default.aspx) For more information about how to implement client callbacks without using a postback, visit the following MSDN Web site:
http://msdn2.microsoft.com/en-us/library/ms178208.aspx (http://msdn2.microsoft.com/en-us/library/ms178208.aspx)


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:

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

InitComplete
This occurs when the page initialization is completed.

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

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

PreRenderComplete
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:

OOPS

.
Abstraction

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

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.

Tuesday, May 26, 2009

Exporting to Excel from SQL Server

--

INSERT INTO OPENROWSET('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=C:\Book.xls;',
'SELECT Name, Date FROM [Sheet1$]')
SELECT [Name], GETDATE() FROM msdb.dbo.sysjobs
GO


To use OPENROWSET command

1. The Excel file must exist. You can use a file as template.
2. Enable OPENROWSET command from SQL Server 2005 Surface Area Configuration
utility.

Thursday, May 14, 2009

How to set the Deafult Button in Web Pages

How to set the Deafult Button in User Control

protected void Page_Load(object sender, EventArgs e)
{
Page.Form.DefaultButton = ButtonId.UniqueID;
}


How to set the Deafult Button in Web Form


form id="thisForm" runat="server" defaultbutton="ButtonId"

Wednesday, May 6, 2009

10 Tips to Improve your LINQ to SQL Application Performance

I summed up 10 important points for me that needs to be considered during tuning your LINQ to SQL’s data retrieval and data modifying process:

1 – Turn off ObjectTrackingEnabled Property of Data Context If Not Necessary

2 – Do NOT Dump All Your DB Objects into One Single DataContext

3 – Use CompiledQuery Wherever Needed

4 – Filter Data Down to What You Need Using DataLoadOptions.AssociateWith

5 – Turn Optimistic Concurrency Off Unless You Need It

6 – Constantly Monitor Queries Generated by the DataContext and Analyze the Data You Retrieve

7 – Avoid Unnecessary Attaches to Tables in the Context


8 – Be Careful of Entity Identity Management Overhead

9 – Retrieve Only the Number of Records You Need

10 – Don’t Misuse CompiledQuery

Stored Procedure Optional Parameters using LINQ to SQL

By default using the LINQ to SQL DataContext design surface (or the SQL Metal command line tool), all parameters are created for a Stored Procedure signature. This essentially means that when coding against the stored procedure method in code, NO PARAMETER argument is optional.

For example; Consider the following stored procedure signature -


CREATE PROCEDURE [dbo].[ChangingInputParameters]
(
@p1 int, /* mandatory */
@p2 int = 2, /* optional integer */
@p3 nvarchar(15), /* mandatory nvarchar */
@p4 nvarchar(25) output /* input/output nvarchar */
)


Even though @p2 has a default value specified and is optional. The LINQ to SQL tools create a C# signature that always expects a value to be passed in. Whilst the designer tools support only the full signature, LINQ to SQL supports the mapping of any method signature to the Stored Procedure call. You just need to define it yourself.

Steps to update the DataContext within VS 2008 -

1. From within Visual Studio 2008, drag the StoredProcedure onto the DataContext (LINQ to SQL Data Class) designer window. This creates the following function definition in the data context code behind file.



[Function(Name="dbo.ChangingInputParameters")]
public ISingleResult ChangingInputParameters(
[Parameter(DbType="Int")] System.Nullable p1,
[Parameter(DbType="Int")] System.Nullable p2,
[Parameter(DbType="NVarChar(15)")] string p3,
[Parameter(DbType="NVarChar(25)")] ref string p4)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), p1, p2, p3, p4);
p4 = ((string)(result.GetParameterValue(3)));
return ((ISingleResult)(result.ReturnValue));
}


2. Create a new partial class for the data context (TIP: Cut and past the using clause, down to the DataContext class definition; Remove the attribute from the class and fix the curly-parenthesis). You should end up with a class looking like this -



namespace [... will vary ...]
{
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using System.ComponentModel;
using System;

public partial class ChangingInputParametersDataContext : System.Data.Linq.DataContext
{
}


3. Copy the original function definition in the code-behind file (e.g. ChangingInputParameters.designer.cs) to your new partial class file.


4. Remove the input arguments, including the in-line attribute declaring each argument as a Parameter.


5. Return output parameters (those marked INPUT/OUTPUT in SQL, and those marked with a 'ref' prefix in C# are accessed via their index position in this method declaration. Update 'x' in any lines getting the output parameter results, so that the correct parameter is mapped to the correct C# instance variable.


result.GetParameterValue(x)


You should have a method that looks like this -



// Modifying the parameter list by dropping the arguments from this list, and updating any OUT parameters...
[Function(Name = "dbo.ChangingInputParameters")]
public ISingleResult ChangingInputParameters(
[Parameter(DbType = "Int")] System.Nullable p1, // NOTICE: NO P2 Declaration! It is optional in the Stored Proc
[Parameter(DbType = "NVarChar(15)")] string p3,
[Parameter(DbType = "NVarChar(25)")] ref string p4)
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), p1, p3, p4);
p4 = ((string)(result.GetParameterValue(2))); // NOTICE: We had to update the index position because the methods arguments changed.
return ((ISingleResult)(result.ReturnValue));
}

Monday, May 4, 2009

COALESCE function instead of long CASE WHEN ... ELSE (T-SQL)

Instead of using long "SELECT ... CASE WHEN ... ELSE ..." construction, you can use the COALESCE function when you need to find a value that is not NULL. Lets review the following T-SQL expression, in which we need to select an available "source":

SELECT TheSource =
CASE
WHEN localSource IS NOT NULL THEN localSource
WHEN intranetSource IS NOT NULL THEN intranetSource
WHEN internetSource IS NOT NULL THEN internetSource
ELSE ''
END
FROM ...

Now lets rewrite the code above using COALESCE function:

SELECT TheSource =
COALESCE(localSource, intranetSource, internetSource, '')
FROM ...

Popular Posts