DECLARE @SQLString nvarchar(500);
DECLARE @Count int;
SET @SQLString = N'SELECT @CountOUT = Count(1)
FROM M_Location WHERE SeqID =' + cast (1 as varchar(20));

EXECUTE sp_executesql @SQLString, N'@CountOUT int OUTPUT', @CountOUT = @Count OUTPUT;
SELECT @Count;
SELECT 
        i.name AS IndexName,
        OBJECT_NAME(ic.OBJECT_ID) AS TableName,
        COL_NAME(ic.OBJECT_ID,ic.column_id) AS ColumnName
FROM   
        SYS.INDEXES AS i INNER JOIN
        SYS.INDEX_COLUMNS AS ic ON  i.OBJECT_ID = ic.OBJECT_ID                                 AND i.index_id = ic.index_id WHERE   i.is_primary_key = 1





Validation Controls

 RequiredFieldValidator

<asp:RequiredFieldValidator ID="rfvFirstName" runat="server" ControlToValidate="txtFirstName" Display="None" ErrorMessage="First Name is required." SetFocusOnError="true" ValidationGroup="Entry"/>

<asp:RequiredFieldValidator ID="rfvJobStatus" runat="server" ControlToValidate="ddlJobStatus" InitialValue="0" Display="None" ErrorMessage="Job Status is required." SetFocusOnError="true" ValidationGroup="Entry"></asp:RequiredFieldValidator>

RangeValidator


Type : Integer,String,Double,Date and Currency
<asp:RangeValidator ID="rngValTxtAge" Type="Integer" MinimumValue="0" MaximumValue="100"
ControlToValidate="txtTest" SetFocusOnError="true" ErrorMessage="Invalid Age" ValidationGroup ="Entry" runat="server"></asp:RangeValidator>

RegularExpressionValidator


<asp:RegularExpressionValidator runat="server" ID="revSSN" ControlToValidate="txtSSN"  Display="None" ValidationExpression="^(\d{9})$" ValidationGroup="Entry"
ErrorMessage="Please enter a SSN number in the format:<br />#########"
SetFocusOnError="true" />

CompareValidator


Type : Integer,String,Double,Date and Currency

<asp:CompareValidator ID="cvDOB" runat="server" ErrorMessage="Invalid Date of Birth"
Operator="DataTypeCheck" Display="None" Type="Date" ControlToValidate="txtDateOfBirth"
ValidationGroup="Entry" />

CustomValidator

Example 1 :
<asp:CustomValidator ID="cvEmplovee" runat="server" ControlToValidate="txtEmployees" Display="None" ClientValidationFunction="CheckInputLen" ErrorMessage="Your Employee length is over 7500 characters."></asp:CustomValidator>

Example 2 :

Pass the ListBox and Validate the SelectionList Using Custom Validator


function ValidateFunction(sender, args) {

var ctl = document.getElementById(sender.controltovalidate);
args.IsValid = ctl.options.length > 0;
}

<asp:CustomValidator runat="server" ID="cusCustom" ControlToValidate="ListBoxID" ValidateEmptyText="true" ValidationGroup="Go" ClientValidationFunction="ValidateFunction"  ErrorMessage="Please Select atleast one" Display="none" />

ValidationSummary


<asp:ValidationSummary ID="ValidationSummay1" runat="server" ShowMessageBox="true" ShowSummary="false" ValidationGroup="Entry" />

DynamicValidator

Encrypt and Decrypt Method
-----------------------------------------

CREATE
TABLE #T(ID INT IDENTITY(1,1), PWD VARCHAR(MAX))INSERT INTO #T VALUES(EncryptByPassPhrase('7622','123@2011'))SELECT * FROM #TSELECT
CONVERT(VARCHAR, DECRYPTByPassPhrase('7622', PWD)) FROM#T


'7622' is an ID for getting the encrypted values


pwdencrypt and Pwdcompare -----------------------------


CREATE TABLE #Login(id_num int, pwd varbinary (255))-- encryptiondeclare @hashedValue varbinary (MAX)SET @hashedValue = pwdencrypt('123') INSERT INTO #Login(id_num,pwd) VALUES (1,@hashedValue)SET @hashedValue = pwdencrypt('123')INSERT

INTO #Login (id_num,pwd) VALUES (2,@hashedValue)
declare
@hashedValue varbinary (MAX)SELECT TOP 1 @hashedValue = pwd FROM #Login WHERE id_num = 2-- ComparisonSELECT pwdcompare ('123', @hashedValue) AS [Success of check] SELECT * FROM #Login

INSERT
INTO #Login (id_num,pwd) VALUES (3,CONVERT(varbinary (255),0x01002D60BA07FE612C8DE537DF3BFCFA49CD9968324481C1A8A8FE612C8DE537DF3BFCFA49CD9968324481C1A8A8

))

declare
@hashedValue varbinary (MAX)SELECT TOP 1 @hashedValue = pwd FROM #Login WHERE id_num = 3-- ComparisonSELECT pwdcompare ('123', @hashedValue) AS [Success of check]
SELECT
* FROM #LoginDROP TABLE #Login




Generally, web applications are based on stateless HTTP protocol which does not retain any information about user requests. In typical client and server communication using HTTP protocol, page is created each time the page is requested.

Types of State Management :
Client-Side  : Viewstate, Cookie, Hiddenfields, ControlState, QueryStrings (URL)
Server-Side : Application, Session
Client side State management Options:
Bandwidth should be considered while implementing client side state management options because they involve in each roundtrip to server. Example: Cookies are exchanged between client and server for each page request.
Viewstate:
Viewstate can be used to store state information for a single user. Viewstate is a built in feature in web controls to persist data between page post backs. You can set View State on/off for each control using EnableViewState property. By default, EnableViewState property will be set to true. Viewstate mechanism poses performance overhead. Viewstate information of all the controls on the page will be submitted to server on each post back. To reduce performance penalty, disable Viewstate for all the controls for which you don't need state. (Data grid usually doesn't need to maintain state). You can also disable Viewstate for the entire page by adding EnableViewState=false to @page directive. View state data is encoded as binary Base64 - encoded which add approximately 30% overhead. Care must be taken to ensure viewstate for a page is smaller in size. Viewstate can be used using following syntax in an ASP.NET web page.
// Add item to ViewState
ViewState["myviewstate"]  = myValue;
 
//Reading items from ViewStateResponse.Write(ViewState["myviewstate"]);

Advantages:
  • Simple for page level data
  • Encrypted 
  • Can be set at the control level
Disadvantages:
  • Overhead in encoding View State values
  • Makes a page heavy
The ViewState Chunking mechanism allow you to split the ViewState content into several chunks/hidden fields. The reason behind using this feature is that some proxies and firewalls will deny access to the aspx page that contains a huge ViewState size by enabling the chunking mechanism that will allow you to bypass this policy.

You can enable ViewState chunking by setting the MaxPageStateFieldLength property the web.config of your asp.net application, this property should be added to the "pages" section in the web.config and it will specify the maximum size of the ViewState in bytes.

If the ViewState size is larger than the value of the MaxPageStateFieldLength than it will be splitted automatically into several hidden fields.

Set the property in the web.config as per the following:
<pages maxPageStateFieldLength="5">

ViewState Example:

Note that you should reconsider the way you are using the ViewState (ViewState optimization, maybe disabling it in some cases) when it has large size.
Cookie:

A cookie is a small piece of text stored on user's computer. Usually, information is stored as name-value pairs. Cookies are used by websites to keep track of visitors. Every time a user visits a website, cookies are retrieved from user machine and help identify the user.

Let's see an example, which makes use of cookies to customize web page.

if (Request.Cookies["UserId"] != null)
    lbMessage.text = "Dear" + Request.Cookies["UserId"].Value + ", Welcome to our website!";
else
    lbMessage.text = "Guest,welcome to our website!";
If you want to store client's information use the below code
Response.Cookies["UserId"].Value=username;
Advantages:
  • Simplicity
Disadvantages:
  • Cookies can be disabled on user browsers
  • Cookies are transmitted for each HTTP request/response causing overhead on bandwidth
  • Inappropriate for sensitive data
Hidden fields:
Hidden fields are used to store data at the page level. As its name says, these fields are not rendered by the browser. It's just like a standard control for which you can set its properties. Whenever a page is submitted to server, hidden fields values are also posted to server along with other controls on the page. Now that all the asp.net web controls have built in state management in the form of view state and new feature in asp.net 2.0 control state, hidden fields functionality seems to be redundant. We can still use it to store insignificant data. We can use hidden fields in ASP.NET pages using following syntax
protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;
 
//to assign a value to Hidden field
Hidden1.Value="Create hidden fields";
//to retrieve a value
string str=Hidden1.Value;
Advantages:
  • Simple to implement for a page specific data
  • Can store small amount of data so they take less size.
Disadvantages:
  • Inappropriate for sensitive data
  • Hidden field values can be intercepted(clearly visible) when passed over a network

Query strings:
Query strings are usually used to send information from one page to another page. They are passed along with URL in clear text. Now that cross page posting feature is back in asp.net 2.0, Query strings seem to be redundant. Most browsers impose a limit of 255 characters on URL length. We can only pass smaller amounts of data using query strings. Since Query strings are sent in clear text, we can also encrypt query values. Also, keep in mind that characters that are not valid in a URL must be encoded using Server.UrlEncode.
Let's assume that we have a Data Grid with a list of products, and a hyperlink in the grid that goes to a product detail page, it would be an ideal use of the Query String to include the product ID in the Query String of the link to the product details page (for example, productdetails.aspx?productid=4).
When product details page is being requested, the product information can be obtained by using the following codes:
string productid;
productid=Request.Params["productid"];            
Advantages:
  • Simple to Implement
Disadvantages:
  • Human Readable 
  • Client browser limit on URL length
  • Cross paging functionality makes it redundant 
  • Easily modified by end user
Control State:
Control State is new mechanism in ASP.NET 2.0, which addresses some of the shortcomings of View State. Control state can be used to store critical, private information across post backs. Control state is another type of state container reserved for controls to maintain their core behavioral functionality whereas View State only contains state to maintain control's contents (UI). Control State shares same memory data structures with View State. Control State can be propagated even though the View State for the control is disabled. For example, new control Grid View in ASP.NET 2.0 makes effective use of control state to maintain the state needed for its core behavior across post backs. Grid View is in no way affected when we disable View State for the Grid View or entire page
Server Side State management:
As name implies, state information will be maintained on the server. Application, Session, Cache and Database are different mechanisms for storing state on the server.
Care must be taken to conserve server resources. For a high traffic web site with large number of concurrent users, usage
of sessions object for state management can create load on server causing performance degradation
Application object:
Application object is used to store data which is visible across entire application and shared across multiple user sessions. Data which needs to be persisted for entire life of application should be stored in application object.
In classic ASP, application object is used to store connection strings. It's a great place to store data which changes infrequently. We should write to application variable only in application_Onstart event (global.asax) or application.lock event to avoid data conflicts. Below code sample gives idea
Application.Lock();
Application["mydata"]="mydata";
Application.UnLock();
Session object:
Session object is used to store state specific information per client basis. It is specific to particular user. Session data persists for the duration of user session you can store session's data on web server in different ways. Session state can be configured using the <session State> section in the application's web.config file. 
Configuration information:
<sessionState mode = <"inproc" | "sqlserver" | "stateserver">
 cookieless = <"true" | "false">
 timeout = <positive integer indicating the session timeout in minutes>
 sqlconnectionstring = <SQL connection string that is only used in the SQLServer mode>
 server = <The server name that is only required when the mode is State Server>
 port = <The port number that is only required when the mode is State Server>
      
Mode:
This setting supports three options. They are InProc, SQLServer, and State Server

Cookie less:
This setting takes a Boolean value of either true or false to indicate whether the Session is a cookie less one.
Timeout:
This indicates the Session timeout vale in minutes.  This is the duration for which a user's session is active.  Note that the session timeout is a sliding value; Default session timeout value is 20 minutes

SqlConnectionString:
This identifies the database connection string that names the database used for mode SQLServer.

Server:
In the out-of-process mode State Server, it names the server that is running the required Windows NT service: aspnet_state.

Port:
This identifies the port number that corresponds to the server setting for mode State Server.  Note that a port is an unsigned integer that uniquely identifies a process running over a network.
You can disable session for a page using EnableSessionState attribute. You can set off session for entire application by setting mode=off in web.config file to reduce overhead for the entire application.
Session state in ASP.NET can be configured in different ways based on various parameters including scalability, maintainability and availability
  • In process mode (in-memory)- State information is stored in memory of web server
  • Out-of-process mode- session state is held in a process called aspnet_state.exe that runs as a windows service.
  • Database mode รข€“ session state is maintained on a SQL Server database.
In process mode:
This mode is useful for small applications which can be hosted on a single server. This model is most common and default method to store session specific information. Session data is stored in memory of local web server
Configuration information:
<sessionState mode="Inproc"
 sqlConnectionString="data source=server;user id=userid;password=password"
 cookieless="false" timeout="20" />
Advantages:
  • Fastest mode 
  • Simple configuration
Disadvantages:
  • Session data will be lost if the worker process or application domain recycles
  • Not ideal for web gardens and web farms
Out-of-process Session mode (state server mode):
This mode is ideal for scalable and highly available applications. Session state is held in a process called aspnet_state.exe that runs as a windows service which listens on TCP port 42424 by default. You can invoke state service using services MMC snap-in or by running following net command from command line.
Net start aspnet_state
Configuration information:

<sessionState mode="StateServer"
 StateConnectionString="tcpip=127.0.0.1:42424"
 sqlConnectionString="data source=127.0.0.1;user id=freelance; password=freelance"
 cookieless="false" timeout="20"/>
                                                           
Advantages:
  • Supports web farm and web garden configuration
  • Session data is persisted across application domain recycles. This is achieved by using separate worker process for maintaining state
Disadvantages:
  • Out-of-process mode provides slower access compared to In process
  • Requires serializing data  
SQL-Backed Session state:
ASP.NET sessions can also be stored in a SQL Server database. Storing sessions in SQL Server offers resilience that can serve sessions to a large web farm that persists across IIS restarts.

SQL based Session state is configured with aspnet_regsql.exe. This utility is located in .NET Framework's installed directory
 C:\<windows>\microsoft.net\framework\<version>. Running this utility will create a database which will manage the session state.
Configuration Information:
<sessionState mode="SQLServer"
  sqlConnectionString="data source=server;user id=freelance;password=freelance"
  cookieless="false" timeout="20" />
Advantages:
  • Supports web farm and web garden configuration
  • Session state is persisted across application domain recycles and even IIS restarts    when session is maintained on different server.
Disadvantages:
  • Requires serialization of objects
Choosing between client side and Server side management techniques is driven by various factors including available server resources, scalability and performance. We have to leverage both client side and server side state management options to build scalable applications. 
When leveraging client side state options, ensure that little amount of insignificant information is exchanged between page requests. 
Various parameters should be evaluated when leveraging server side state options including size of application, reliability and robustness. Smaller the application, In process is the better choice. We should account in the overheads involved in serializing and deserializing objects when using State Server and Database based session state. Application state should be used religiously.

Refernce :

http://www.codeproject.com/Articles/32545/Exploring-Session-in-ASP-Net

 

When a page request is sent to the Web server, the page is run through a series of events during its creation and disposal.
-          PreInit
-          Init 
-          InitComplete 
-          PreLoad 
-          Load 
-          Control event(s) – PostBack
-          LoadComplete 
-          PreRender 
-          SaveStateComplete 
-          Render 
-          UnLoad 

PreInit : The entry point of the page life cycle. Here we can access the master pages and themes. You can dynamically set the values of master pages and themes in this event. You can also dynamically create controls in this event.
Example :  protected void Page_PreInit(object sender, EventArgs e)    {}

Init : This event fires after each control has been initialized, each control's UniqueID is set and any skin settings have been applied. Here we can change initialization values.

EXAMPLE : protected void Page_Init(object sender, EventArgs e) {}

InitComplete : Raised once all initializations of the page and its controls have been completed. Till now the viewstate values are not yet loaded, hence you can use this event to make changes to view state that you want to make sure are persisted after the next postback 

EXAMPLE : protected void Page_InitComplete(object sender, EventArgs e) {}

PreLoad : Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance          

                        (1)Loads ViewState : ViewState data are loaded to controls
Note : The page viewstate is managed by ASP.NET and is used to persist information over a page roundtrip to the server. Viewstate information is saved as a string of name/value pairs and contains information such     as control text or value. The viewstate is held in the value property of a hidden <input> control that is passed from page request to page request.          

                        (2)Loads Postback data : postback data are now handed to the page controls              
                        Note : During this phase of the page creation, form data that was posted to the server (termed postback data in ASP.NET) is processed against each control that requires it. Hence, the page fires the LoadPostData event and parses through the page to find each control and updates the control state with the correct postback data. ASP.NET updates the correct control by matching the control's unique ID with the name/value pair in the NameValueCollection. This is one reason that ASP.NET requires unique IDs for each control on any given page. 

EXAMPLE : protected override void OnPreLoad(EventArgs e) {}
Load  : The important thing to note about this event is the fact that by now, the page has been restored to its previous state in case of postbacks. Code inside the page load event typically checks for PostBack and then sets control properties appropriately. This method is typically used for most code, since this is the first place in the page lifecycle that all values are restored. Most code checks the value of IsPostBack to avoid unnecessarily resetting state. You may also wish to call Validate and check the value of IsValid in this method. You can also create dynamic controls in this method.

EXAMPLE : protected void Page_Load(object sender, EventArgs e){ }

Control event(s)- (PostBack) : ASP.NET now calls any events on the page or its controls that caused the PostBack to occur. This might be a button’s click event or a dropdown's selectedindexchange event, For example.These are the events, the code for which is written in your code-behind class(.cs file). 

EXAMPLE : protected void Button1_Click(object sender, EventArgs e){ }

LoadComplete : This event signals the end of Load. 

EXAMPLE : protected void Page_LoadComplete(object sender, EventArgs e){  }

PreRender : Allows final changes to the page or its control. This event takes place after all regular PostBack events have taken place. This event takes place before saving ViewState, so any changes made here are saved. For example : After this event, you cannot change any property of a button or change any viewstate value. Because, after this event, SaveStateComplete and Render events are called. 

EXAMPLE :protected override void OnPreRender(EventArgs e){ }

SaveStateComplete : Prior to this event the view state for the page and its controls is set. Any changes to the page’s controls at this point or beyond are ignored.

EXAMPLE : protected override void OnSaveStateComplete(EventArgs e){ }

Render : This is a method of the page object and its controls (and not an event). At this point, ASP.NET calls this method on each of the page’s controls to get its output. The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display a control at the browser.
 Note:  Right click on the web page displayed at client's browser and view the Page's Source. You will not find any aspx server control in the code. Because all aspx controls are converted to their respective HTML representation. Browser is capable of displaying HTML and client side scripts. 
EXAMPLE : protected void Page_Render(object sender, EventArgs e){  }
// Render stage goes here. This is not an event

 (11)UnLoad This event is used for cleanup code. After the page's HTML is rendered, the objects are disposed of. During this event, you should destroy any objects or references you have created in building the page. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object. Cleanup can be performed on-      
            (a)Instances of classes i.e. objects
             (b)Closing opened files
             (c)Closing database connections. 
EXAMPLE : protected void Page_UnLoad(object sender, EventArgs e)   {}

Step by step for creating virtual Directory











Also Checking the Credential for running .net framework,









Class Modifiers

The class is one of the two basic encapsulation constructs in C# (the other being the struct). Every executable statement must be placed inside a class or struct. Classes define reference types that are the basic building blocks of C# programs, and they are the architectural blueprint for the "objects" in OOP.
A class can be...

abstract: An instance of the class cannot be created.Usually this means the class is intended to serve as a base class.

sealed: The class cannot serve as a base class for another class (it can't be derived from). A class cannot be both abstract and sealed.

internal: The class is only accessible from other classes in the same assembly. This is the default access for non-nested types. If no modifier is specified, the class has internal access.

new: Used only with nested classes. "New" indicates that the class hides an inherited member of the same name.

private: A nested class that can only be accessed inside the class in which it is defined.

public: Instances of this class are available to any class that wants to access it.

Constructor Modifiers


A class defines data members, methods and nested types. A constructor is a special method that is normally used to initialize the data members of a class, and its name is always the same as the name of the class. Constructors have no return value, and any number of constructors can be defined within a class. If no constructor is defined, the C# compiler provides a default constructor having no parameters.

Methods


Methods are always defined within the bounds of a class or struct. Methods can be instance (called as an instance of the type within which the method is defined) or static, where the method is associated with the type itself. Methods can be declared as virtual, abstract , or sealed. Methods can be overloaded, overridden and hidden.

Access Modifiers

Access modifiers are specified as part of the method declaration syntax and can be:

Internal , private , protected , protected internal , public

If no modifier is specified, the method is given private access.

virtual methods can be overriden by a derived class using the override keyword.

abstract methods must be overriden in a derived class. If any method of a class is abstract, the 
entire class must be declared as abstract.

sealed methods are methods that override an inherited virtual method having the same signature. When a method is sealed, it cannot be overriden in a derived class.

Method Access Modifiers

public indicates the method is freely accessible inside and outside of the class in which it is defined.

internal means the method is only accessible to types defined in the same assembly.

protected means the method is accessible in the type in which it is defined, and in derived types of that type. This is used to give derived classes access to the methods in their base class.

protected internal means the method is accessible to types defined in the same assembly or to types in a derived assembly.

private methods are only accessible in the class in which they are defined.