66
.NET Framework The .NET Framework is a managed, type-safe environment for developing and executing applications. The .NET Framework manages all aspects of program execution, like, allocation of memory for the storage of data and instructions, granting and denying permissions to the application, managing execution of the application and reallocation of memory for resources that are not needed. The .NET Framework is designed for cross-language compatibility. Cross-language compatibility means, an application written in Visual Basic .NET may reference a DLL file written in C#. A Visual Basic .NET class might be derived from a C# class or vice versa. The .NET Framework consists of two main components: CommonLanguageRuntime Class Libraries Common Language Specification (CLS) It is a set of rules, which should be followed by the dotnet languages to be interoperable with other dotnet languages. a. We cannot have global variables or global methods. b. We cannot have pointers. c. We should not depend on case sensitivity for declaring variable names. d. All the variables should be CLS specific (like unsigned int available in C# but not in VB.Net, so those kinds of variable declarations should be avoided). e. All the Exceptions must be derived from the Exception class.

ASP.net_XML_Basics at a Glance

  • Upload
    rajesh

  • View
    72

  • Download
    2

Embed Size (px)

DESCRIPTION

Basics of ASP.net and XML

Citation preview

Page 1: ASP.net_XML_Basics at a Glance

.NET Framework

The .NET Framework is a managed, type-safe environment for developing and executing applications. The .NET Framework manages all aspects of program execution, like, allocation of memory for the storage of data and instructions, granting and denying permissions to the application, managing execution of the application and reallocation of memory for resources that are not needed. The .NET Framework is designed for cross-language compatibility. Cross-language compatibility means, an application written in Visual Basic .NET may reference a DLL file written in C#. A Visual Basic .NET class might be derived from a C# class or vice versa.

The .NET Framework consists of two main components:

CommonLanguageRuntime Class Libraries

Common Language Specification (CLS)

It is a set of rules, which should be followed by the dotnet languages to be interoperable with other dotnet languages.

a. We cannot have global variables or global methods.b. We cannot have pointers.c. We should not depend on case sensitivity for declaring variable names.d. All the variables should be CLS specific (like unsigned int available in C# but not in

VB.Net, so those kinds of variable declarations should be avoided).e. All the Exceptions must be derived from the Exception class.

Common Language Runtime (CLR)

The CLR is described as the "execution engine" of .NET. It provides the environment within which the programs run. It's this CLR that manages the execution of programs and provides core services, such as code compilation, memory allocation, thread management, and garbage collection. Through the Common Type System (CTS), it enforces strict type safety,

Page 2: ASP.net_XML_Basics at a Glance

and it ensures that the code is executed in a safe environment by enforcing code access security. The software version of .NET is actually the CLR version.

Working of the CLR

When the .NET program is compiled, the output of the compiler is not an executable file but a file that contains a special type of code called the Microsoft Intermediate Language (MSIL), which is a low-level set of instructions understood by the common language run time. This MSIL defines a set of portable instructions that are independent of any specific CPU. It's the job of the CLR to translate this Intermediate code into an executable code when the program is executed making the program to run in any environment for which the CLR is implemented. And that's how the .NET Framework achieves Portability. This MSIL is turned into executable code using a JIT (Just in Time) complier. The process goes like this, when .NET programs are executed, the CLR activates the JIT complier. The JIT complier converts MSIL into native code on a demand basis as each part of the program is needed. Thus the program executes as a native code even though it is compiled into MSIL making the program to run as fast as it would if it is compiled to native code but achieves the portability benefits of MSIL.

Class Libraries

Class library is the second major entity of the .NET Framework which is designed to integrate with the common language runtime. This library gives the program access to runtime environment. The class library consists of lots of prewritten code that all the applications created in VB .NET and Visual Studio .NET will use. The code for all the elements like forms, controls and the rest in .NET applications actually comes from the class library.

ASP.NET Page Life Cycle

Page 3: ASP.net_XML_Basics at a Glance

1. StartHTTP Runtime

Global.asax is parsed and compiled.PreInit

Check for IsPostBack. Page control tree is created. Set the Master page dynamically. Set the StyleSheetTheme property. Set the Culture property. Read or set the Profile property values.

2. Page InitializationPage_Init

Read or change Control properties. Setup handlers for events. Load external template files.

LoadViewState () Load application persistent information to controls. Specify how ViewState is stored. Specify how ViewState is mapped to the internal state. 

3. LoadPage_Load

If this is the first time page is being processed, then perform initial data binding.

Page 4: ASP.net_XML_Basics at a Glance

Read and update control properties.4. ValidationValidate ()

Validate information assigned to validation controls. 5. Event HandlingPage_DataBinding ()

   Bind data sources to controls.  Page_PreRender

   Make final modifications to the page    Change the control tree structure.

SaveViewState ()6. RenderingPage_Render

       Make changes to the HTML of a page.        Write text for controls on a page.

7. UnloadPage_Dispose

   Discard objects used in the page, including the Page object. Page_Unload

   Close open files.    Close open database connections.    Finish logging or other request-specific tasks.

Shared Code Folders in ASP.NET If your Web application includes code that you want to share between pages, you can

keep the code in one of two special folders underneath the root of your Web application, the

Bin folder and the App_Code folder. When you create these folders and store particular

types of files in them, ASP.NET handles the files in special ways.

Bin Folder

You can store compiled assemblies in the Bin folder, and other code anywhere in the Web

application (such as code for pages) automatically references it and the class is then

available to all pages.

Assemblies in the Bin folder do not need to be registered. The presence of a .dll file in the

Bin folder is sufficient for ASP.NET to recognize it. If you change the .dll and write a new

version of it to the Bin folder, ASP.NET detects the update and uses the new version of

the .dll for new page requests from then on.

Page 5: ASP.net_XML_Basics at a Glance

App_Code Folder

You can store source code in the App_Code folder, and it will be automatically compiled at

run time. The resulting assembly is accessible to any other code in the Web application. The

App_Code folder therefore works much like the Bin folder, except that you can store source

code in it instead of compiled code. The App_Code folder and its special status in an

ASP.NET Web application makes it possible to create custom classes and other source-code-

only files and use them in your Web application without having to compile them

independently.

The App_Code folder can contain source code files written as traditional class files — that is,

files with a .vb extension, .cs extension, and so on. However, it can also include files that are

not explicitly in a specific programming language. Examples include .wsdl (Web service

description language) files and XML schema (.xsd) files. ASP.NET can compile these files into

assemblies.

The App_Code folder can contain as many files and subfolders as you need. You can

organize your source code in any way that you find convenient, and ASP.NET will still

compile all of the code into a single assembly that is accessible to other code anywhere in

the Web application.

Multiple Programming Languages in the App_Code Folder

Because the source code in the App_Code folder is compiled into a single assembly, all the

files in the App_Code folder must be in the same programming language. For example, the

App_Code folder cannot include source code in both Visual Basic and C#.

However, you can configure your Web application to treat subfolders of the App_Code folder

as separate compilable units. Each folder can then contain source code in a different

programming language. The configuration is specified by creating a codeSubDirectories

element in the compilation element of the Web.config file and adding a reference to the

subfolder. The following example illustrates how you would configure subfolders named

VBCode and CSCode to compile into separate assemblies:

<compilation debug="false">

<CodeSubDirectories>

<add directoryName="VBCode" />

<add directoryName="CSCode" />

</codeSubDirectories>

</compilation>

User Controls

Page 6: ASP.net_XML_Basics at a Glance

User control's file cannot be executed as a standalone Web Forms. User controls are

included in a Web Forms page using a Register directive:

<%@ Register Src="FragmentCaching.ascx" TagName="FragmentCaching"

TagPrefix="uc1" %>

The TagPrefix determines a unique namespace for the user control (so that multiple user controls with the same name can be differentiated from each other).

The TagName is the unique name for the user control (you can choose any name).

The Src attribute is the virtual path to the user control--for example "FragmentCaching.ascx”.

After registering the user control, we may place the user control tag in the Web Forms page just as you would an ordinary server control (including the runat="server" attribute):

<uc1:FragmentCaching ID="FragmentCaching1" runat="server" />

Difference between User Control and Custom Control

User Control Custom Control

User controls are compiled dynamically at run time

Web custom controls are compiled components that run on the server.

Web user controls are easy to make, but they can be less convenient to use in advanced scenarios

Web custom controls are compiled code, which makes them easier to use but more difficult to create.

They cannot be added to the Toolbox and they are represented by a simple placeholder when added to a page

Once you have created the control you can add it to the Toolbox and display it in a visual designer

The only way to share the user control between applications is to put a separate copy in each application

In addition you can install a single copy of the Web custom control in the global assembly cache and share it between applications.

Maintenance is difficult if modifications are done.

Maintenance easier if modifications are done.

It is an .ascx file It is a DLL

Page 7: ASP.net_XML_Basics at a Glance

ASP.NET State ManagementWeb form pages are HTTP-Based, they are stateless, which means they don’t know whether

the requests are all from the same client, and pages are destroyed and recreated with each

round trip to the server, therefore information will be lost. Hence State Management

technique in ASP.NET provides a way to persist information between requests by using

View state

Control state

Hidden fields

Cookies

Query strings

Application state

Session state

Profile Properties

Client-Based State Management Options

There is no information maintained on the server between round trips. Information will be stored in the page or on the client’s computer.

View state:

When the page is processed, the current state of the page and controls is

hashed into a string and saved in the page as a hidden field, or multiple hidden fields if the

amount of data stored in the ViewState property exceeds the specified value in the

MaxPageStateFieldLength property. When the page is posted back to the server, the page

parses the view-state string at page initialization and restores property information in the

page.

<%@ Page ViewStateEncryptionMode="Always"... %> //To Encrypt ViewState

ArrayList myarrayList = new ArrayList();ViewState.Add("arrayListInViewState", myarrayList);// Storing in ViewStatemyarrayList = (ArrayList)ViewState["arrayListInViewState"]; // Retrieving

Control state:

The ControlState property allows you to persist property information that is

specific to a control and cannot be turned off like the ViewState property. By default,

control state is stored in hidden fields on the page. To fully utilize control state, you must

write code to save and load control state.

Hidden Field:

Page 8: ASP.net_XML_Basics at a Glance

ASP.NET allows you to store information in a HiddenField control, which renders as a

standard HTML hidden field. A hidden field does not render visibly in the browser, but you

can set its properties just as you can with a standard control. When a page is submitted to

the server, the content of a hidden field is sent in the HTTP form collection along with the

values of other controls. A hidden field acts as a repository for any page-specific information

that you want to store directly in the page. A HiddenField control stores a single variable in

its Value property and must be explicitly added to the page

* In order for hidden-field values to be available during page processing, you must submit

the page using an HTTP POST command. If you use hidden fields and a page is processed

in response to a link or an HTTP GET command, the hidden fields will not be available.

<asp:hiddenfield id="MyHiddenField" value="" runat="server"/> Form1.MyHiddenField.value = Form1.MyTextBox.value;

Cookies

A cookie is a small amount of data that is stored either in a text file on the client file system

or in-memory in the client browser session. It contains site-specific information that the

server sends to the client along with page output. Cookies can be temporary (with specific

expiration times and dates) or persistent.

You can use cookies to store information about a particular client, session, or application.

The cookies are saved on the client device, and when the browser requests a page, the

client sends the information in the cookie along with the request information. The server can

read the cookie and extract its value. A typical use is to store a token (perhaps encrypted)

indicating that the user has already been authenticated in your application.

Query Strings

A query string is information that is appended to the end of a page URL. A typical query

string might look like the following example:

http://www.contoso.com/listwidgets.aspx?category=basic & price=100

In the URL path above, the query string starts with a question mark (?) and includes two

attribute/value pairs, one called "category" and the other called "price."

*In order for query string values to be available during page processing, you must submit

the page using an HTTP GET command. That is, you cannot take advantage of a query

string if a page is processed in response to an HTTP POST command.

Page 9: ASP.net_XML_Basics at a Glance

Server-Based State Management Options

Server-based state management, you can decrease the amount of information sent to

the client in order to preserve state, however it can use costly resources on the server.

Application State

ASP.NET allows you to save values using application state — which is an instance of the

HttpApplicationState class — for each active Web application. Application state is a global

storage mechanism that is accessible from all pages in the Web application. Thus,

application state is useful for storing information that needs to be maintained between

server round trips and between requests for pages.

Session State

ASP.NET allows you to save values by using session state — which is an instance of the

HttpSessionState class — for each active Web-application session.

Session state is similar to application state, except that it is scoped to the current browser

session. If different users are using your application, each user session will have a different

session state. In addition, if a user leaves your application and then returns later, the second

user session will have a different session state from the first.

Profile Properties

ASP.NET provides a feature called profile properties, which allows you to store user-specific

data. This feature is similar to session state, except that the profile data is not lost when a

user's session expires. The profile-properties feature uses an ASP.NET profile, which is stored

in a persistent format and associated with an individual user. The ASP.NET profile allows you

to easily manage user information without requiring you to create and maintain your own

database. In addition, the profile makes the user information available using a strongly

typed API that you can access from anywhere in your application. You can store objects of

any type in the profile.

ASP.NET includes a SqlProfileProvider class that allows you to store profile data in a SQL

database.

Because data that is placed in profile properties is not stored in application memory, it is

preserved through Internet Information Services (IIS) restarts and worker-process restarts

without losing data

Client-Side Script from the Code-Behind Class

Page 10: ASP.net_XML_Basics at a Glance

1. Page.ClientScript.RegisterClientScriptBlock (key, script)

RegisterClientScriptBlock the script is emitted after the start of the <form> element, but before the form's contents.

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MyScript", "if (document.images) {" + "OMOver = new Image;" + "OMOut = new Image;" + "OMOver.src = 'error.gif';" + "OMOut.scr ='Globe.gif';" + "}" + "else {" + "OMOver = '';" + "OMOut = '';" + "}", true);ImageButton1.Attributes.Add("onmouseover","this.src = OMOver.src; window.status='Oh Yes! Click here!';");ImageButton1.Attributes.Add("onmouseout","this.src = OMOut.scr; window.status='out';");

2. Page.ClientScript.RegisterStartupScript (key, script)

RegisterStartupScript, on the other hand, adds the specified script at the end of the form, after all form fields. Use RegisterStartupScript to place client-side script that interacts with the rendered HTML elements.Ex:

Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", "function AlertHello() { alert('Hello ASP.NET'); }", true);

Button1.Attributes["onclick"] = "AlertHello()";Button2.Attributes["onclick"] = "AlertHello()";

Flow in which Client-Side Elements Are Rendered

< Form >Page.OnFormRender ();MyBase.RenderChildren ();Page.OnFormPostRender ();</form>

Page.OnFormRender () 1. RegisterHiddenField. 2. __VIEWSTATE. 3. RegisterClientScriptBlock

MyBase.RenderChildren () Renders all the contents with in the Web Form.

Page.OnFormPostRender () 1. RegisterArrayDeclaration 2. RegisterStartupScript

Page 11: ASP.net_XML_Basics at a Glance

RegisterHiddenField (hiddenFieldName, hiddenFieldValue)

A hidden field is a form field that is not displayed, but whose value is sent on the form's submission. The syntax for creating a hidden form field is <input type="hidden" name="name" value="value" />

The RegisterHiddenField method accepts two input parameters: the name of the hidden field and the value. For example, to create a hidden form field with the name foo and the value bar, use the following code:RegisterHiddenField("foo", "bar")

This would add a hidden form field within the page's <form> element, like so:

<form name="_ctl0" method="post" action="test.aspx" id="_ctl0"><input type="hidden" name="foo" value="bar" /> ...</form>

Get and Post:

Using "get" to pass information sends the information appended to the request for

the processing page. It tends to be simpler and you can troubleshoot any problems simply

by looking at the address bar in your browser since all values passed are displayed there.

This is also the primary weakness of this method. The data being passed is visible and is

limited in size to the maximum length of a request string.

Ex: http://www.asp101.com/samples/getpost.asp?Text=Hello+World

Using "post" to pass information sends the information embedded in a header during the

request for the processing page. Its main advantage is that you can send larger amounts of

information. It also doesn't make that information visible in the address bar of the browser

which is nice if you are using the "hidden" input type. The value of this type is still readily

available to the user by using view source, but the average user won't see it or be confused

by any information you may need to pass from your form for processing.

Ex: http://www.asp101.com/samples/getpost.asp

Button.OnClientClick Property 

Gets or sets the client-side script that executes when a Button control's Click event is

raised.

Use the OnClientClick property to specify additional client-side script that executes

when a Button control's Click event is raised. The script that you specify for this

property is rendered in the Button control's OnClick attribute in addition to the

control's predefined client-side script.

Page 12: ASP.net_XML_Basics at a Glance

Example:

<script type="text/javascript">function Navigate(){ javascript:window.open("http://www.microsoft.com");} </script>

<asp:button id="Button2" text="Open Website" onclientclick="Navigate()" runat="server" onclick="Button1_Click" /><asp:label id="Label1" runat="server"/>

In Code-behind File:

protected void Button1_Click(object sender, EventArgs e) { Label1.Text = "Thank you for visiting our site.";

}In the above example, Onclick of button will call javascript Navigate function then it will call

Button1_Click.

AdRotator Class Displays an advertisement banner on a Web page.

Use the AdRotator control to display a randomly selected advertisement banner on

the Web page. The displayed advertisement can change whenever the page

refreshes.

Advertisement information is stored in a separate XML file. The XML file allows you to

maintain a list of advertisements and their associated attributes. Attributes include

the path to an image to display, the URL to link to when the control is clicked, the

alternate text to display when the image in not available, a keyword, and the

frequency of the advertisement.

As an alternative source of data to an XML file, it is possible to provide advertisement

information through a call-back event. This event can also be used in combination

with the XML file to extend the behavior of the AdRotator control, such as

redirecting to another page. See the AdvertisementFile property for additional

information on the file format.

A new advertisement is selected whenever the Web page refreshes. An Impressions

attribute can be assigned to each advertisement. It controls how often an

advertisement is selected relative to the other advertisements in the advertisement

file.

Page 13: ASP.net_XML_Basics at a Glance

Example:

<asp:adrotator ID="Adrotator1" AdvertisementFile="ads.xml" BorderColor="black"

BorderWidth=1 runat="server"/>

In ads.xml

<?xml version="1.0" encoding="utf-8" ?><Advertisements>

<Ad> <ImageUrl>images/banner1.gif</ImageUrl> <NavigateUrl>http://www.microsoft.com</NavigateUrl> <AlternateText>Alt Text</AlternateText> <Keyword>Computers</Keyword> <Impressions>80</Impressions> </Ad>

<Ad> <ImageUrl>images/banner2.gif</ImageUrl> <NavigateUrl>http://www.microsoft.com</NavigateUrl> <AlternateText>Alt Text</AlternateText> <Keyword>Computers</Keyword> <Impressions>80</Impressions> </Ad>

<Ad> <ImageUrl>images/banner3.gif</ImageUrl> <NavigateUrl>http://www.microsoft.com</NavigateUrl> <AlternateText>Alt Text</AlternateText> <Keyword>Computers</Keyword> <Impressions>80</Impressions> </Ad>

</Advertisements>

DataGrid Class:

Displays ADO.NET data in a scrollable grid. The DataGridView control replaces and adds functionality to the DataGrid control; however, the DataGrid control is retained for both backward compatibility and future use

The System.Windows.Forms.DataGrid displays Web-like links to child tables. You

can click on a link to navigate to the child table. When a child table is displayed, a

back button appears in the caption that can be clicked to navigate back to the parent

table. The data from the parent rows is displayed below the caption and above the

column headers. You can hide the parent row information by clicking the button to

the right of the back button.

Page 14: ASP.net_XML_Basics at a Glance

To display a table in the System.Windows.Forms.DataGrid at run time, use the

SetDataBinding method to set the DataSource and DataMember properties to a valid

data source. The following data sources are valid:

A DataTable, DataView, DataSet, DataViewManager

A single dimension array

Any component that implements the IListSource/IList interface

For more information about the DataSet class, see Using DataSets in ADO.NET.

You can create a grid that enables users to edit data but prevents them from adding

new rows by using a DataView as the data source and setting the AllowNew

property to false.

  Name Description

CancelCommand Occurs when the Cancel button is clicked for an item in the DataGrid control.

DataBinding  Occurs when the server control binds to a data source. (inherited from Control)

DeleteCommand Occurs when the Delete button is clicked for an item in the DataGrid control.

Disposed  Occurs when a server control is released from memory, which is the last stage of the server control lifecycle when an ASP.NET page is requested. (inherited from Control)

EditCommand Occurs when the Edit button is clicked for an item in the DataGrid control.

Init  Occurs when the server control is initialized, which is the first step in its lifecycle. (inherited from Control)

ItemCommand Occurs when any button is clicked in the DataGrid control.

ItemCreated Occurs on the server when an item in the DataGrid control is created.

ItemDataBound Occurs after an item is data bound to the DataGrid control.

Load  Occurs when the server control is loaded into the Page object. (inherited from Control)

PageIndexChanged Occurs when one of the page selection elements is clicked.

PreRender  Occurs after the Control object is loaded but prior to rendering. (inherited from Control)

SelectedIndexChanged 

Occurs when a different item is selected in a data listing control between posts to the server. (inherited from

Page 15: ASP.net_XML_Basics at a Glance

BaseDataList)

SortCommand Occurs when a column is sorted.

Unload  Occurs when the server control is unloaded from memory. (inherited from Control)

UpdateCommand Occurs when the Update button is clicked for an item in the DataGrid control.

//DataGrid Example<asp:DataGrid id="MyDataGrid" runat="server" BorderColor="black"

BorderWidth="1" GridLines="Both" CellPadding="3" CellSpacing="0" Font-Name="Verdana" Font-Size="8pt"

HeaderStyle-BackColor="#aaaadd" AutoGenerateColumns="false"> <Columns> <asp:HyperLinkColumn HeaderText="Details" DataNavigateUrlField="IntegerValue"

DataNavigateUrlFormatString="detailspage.aspx?id={0}" DataTextField="StringValue" Target="_new"/> <asp:BoundColumn HeaderText="Date/Time" DataField="DateTimeValue"/> <asp:BoundColumn HeaderText="True/False" DataField="BoolValue"/> <asp:BoundColumn HeaderText="Price" DataField="CurrencyValue" DataFormatString="{0:c}" ItemStyle-HorizontalAlign="right"/> </Columns></asp:DataGrid>

In Code-Behind file:

protected void Page_Load(object sender, EventArgs e){ MyDataGrid.DataSource = CreateDataSource(); MyDataGrid.DataBind(); MyList.DataSource = CreateDataSource(); MyList.DataBind();

}ICollection CreateDataSource(){ DataTable dt = new DataTable(); DataRow dr;

dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32))); dt.Columns.Add(new DataColumn("StringValue", typeof(string))); dt.Columns.Add(new DataColumn("DateTimeValue", typeof(DateTime))); dt.Columns.Add(new DataColumn("BoolValue", typeof(bool))); dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));

for (int i = 0; i < 9; i++) { dr = dt.NewRow(); dr[0] = i; dr[1] = "Item " + i.ToString();

Page 16: ASP.net_XML_Basics at a Glance

dr[2] = DateTime.Now; dr[3] = (i % 2 != 0) ? true : false; dr[4] = 1.23 * (i + 1);

dt.Rows.Add(dr); }

DataView dv = new DataView(dt); return dv;}

DataList Class:

Displays the items from a data source by using templates. You can customize the appearance and contents of the control by manipulating the templates that make up the different components of the DataList control, such as the ItemTemplate and HeaderTemplate. By default, the DataList displays its data in an HTML <table>. However, unlike the DataGrid, with the DataList you can specify via the RepeatColumns how many DataSource records should appear per HTML <table> row.

The contents of the DataList control can be manipulated by using templates. The following table lists the supported templates.

Template Name Description

AlternatingItemTemplate If defined, provides the content and layout for alternating items in the DataList. If not defined, ItemTemplate is used.

EditItemTemplate If defined, provides the content and layout for the item currently being edited in the DataList. If not defined, ItemTemplate is used.

FooterTemplate If defined, provides the content and layout for the footer section of the DataList. If not defined, a footer section will not be displayed.

HeaderTemplate If defined, provides the content and layout for the header section of the DataList. If not defined, a header section will not be displayed.

ItemTemplate Required template that provides the content and layout for items in the DataList.

SelectedItemTemplate If defined, provides the content and

Page 17: ASP.net_XML_Basics at a Glance

layout for the currently selected item in the DataList. If not defined, ItemTemplate is used.

SeparatorTemplate If defined, provides the content and layout for the separator between items in the DataList. If not defined, a separator will not be displayed.

At the very minimum, the ItemTemplate needs to be defined to display the items in the DataList control. Additional templates can be used to provide a custom look to the DataList control.You can also show or hide different parts of the control. The following table lists the properties that control which parts are shown or hidden.

Property Description

ShowFooter Shows or hides the footer section of the DataList control.

ShowHeader Shows or hides the header section of the DataList control.

The display direction of a DataList control can be vertical or horizontal. Set the RepeatDirection property to specify the display direction.The layout of the DataList control is controlled with the RepeatLayout property. Setting this property to RepeatLayout.Table will display the DataList in a table format, while RepeatLayout.Flow displays the DataList without a table structure.

DataList Example:

<asp:datalist id="MyList" RepeatDirection="Horizontal" showfooter=true borderwidth=0 runat=server>

<HeaderTemplate> <table cellpadding=1 cellspacing=0 > <tr> <td colspan=4> <b><font face="Verdana" size=3>Product Listing </font></b> </td> </tr> <tr> <td colspan=4 height=5 bgcolor="000000"></td> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td colspan=3 style="font-size:10pt"> <b><%# DataBinder.Eval(Container.DataItem, "StringValue")%></b> <%# DataBinder.Eval(Container.DataItem, "DateTimeValue")%>

</td> <td align=right style="font-size:10pt">

<b><%# DataBinder.Eval(Container.DataItem, "CurrencyValue", "{0:c}")%> </b>

</td> </tr> </ItemTemplate>

Page 18: ASP.net_XML_Basics at a Glance

<SeparatorTemplate> <tr> <td colspan=4 height=1 bgcolor="000000"></td> </tr> </SeparatorTemplate> <FooterTemplate> <tr> <td colspan=4 height=5 bgcolor="000000"></td> </tr> </table> </FooterTemplate> </asp:datalist>

Repeater Class:

A data-bound list control that allows custom layout by repeating a specified template

for each item displayed in the list.

The Repeater control is a basic templated data-bound list. It has no built-in layout or

styles, so you must explicitly declare all layout, formatting, and style tags within the

control's templates.

The Repeater control is the only Web control that allows you to split markup tags

across the templates. To create a table using templates, include the begin table tag

(<table>) in the HeaderTemplate, a single table row tag (<tr>) in the

ItemTemplate, and the end table tag (</table>) in the FooterTemplate.

The Repeater control has no built-in selection capabilities or editing support. You

can use the ItemCommand event to process control events that are raised from the

templates to the control.

The Repeater control provides two properties to support data binding. To bind data

to any object that implements the System.Collections.IEnumerable interface (such as

a System.Data.DataView, a System.Collections.ArrayList, a

System.Collections.Hashtable, or an array), or the IListSource interface, use the

DataSource property to specify the data source. When you set the DataSource

property, you must manually write the code to perform data binding. To

automatically bind the Repeater control to a data source represented by a data

source control, set the DataSourceID property to the ID of the data source control to

use. When you set the DataSourceID property, the Repeater control automatically

binds to the specified data source control on the first request. Therefore, you do not

need to explicitly call the DataBind method unless you have changed data-related

properties of the Repeater control.

A Repeater control binds its ItemTemplate and AlternatingItemTemplate to either

the data model declared and referenced by its DataSource property or the data

Page 19: ASP.net_XML_Basics at a Glance

source control specified by its DataSourceID property. The HeaderTemplate,

FooterTemplate, and SeparatorTemplate are not data-bound.

If the Repeater control's data source is set but no data is returned, the control

renders the HeaderTemplate and FooterTemplate with no items. If the data

source is a null reference (Nothing in Visual Basic), the Repeater is not rendered.

At a minimum, every Repeater control must define an ItemTemplate. However,

other optional templates described in the following table can be used to customize

the appearance of the list. Data binding is by,

<td><%# DataBinder.Eval(Container.DataItem,"Name") %> </td>

Template name Description

ItemTemplate Defines the content and layout of items within the list. This template is required.

AlternatingItemTemplate

If defined, determines the content and layout of alternating (zero-based odd-indexed) items. If not defined, ItemTemplate is used.

SeparatorTemplate If defined, is rendered between items (and alternating items). If not defined, a separator is not rendered.

HeaderTemplate If defined, determines the content and layout of the list header. If not defined, a header is not rendered.

FooterTemplate If defined, determines the content and layout of the list footer. If not defined, a footer is not rendered.

Example:Cdcatalog.xml file

<?xml version="1.0" encoding="utf-8" ?><catalog> <cd> <title>Empire Burlesque</title> <artist>Bob Dylan</artist> <country>USA</country> <company>Columbia</company> <price>10.90</price> <year>1985</year> </cd> <cd> <title>Hide your heart</title> <artist>Bonnie Tyler</artist> <country>UK</country> <company>CBS Records</company> <price>9.90</price> <year>1988</year> </cd>

Page 20: ASP.net_XML_Basics at a Glance

</catalog>

In aspx file:<asp:Repeater id="MyRepeater" runat="server">

<HeaderTemplate> <table border="1" width="100%"> <tr> <th>Title</th> <th>Artist</th> <th>Country</th> <th>Company</th> <th>Price</th> <th>Year</th> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td><%#DataBinder.Eval(Container.DataItem, "title")%></td> <td><%#DataBinder.Eval(Container.DataItem, "artist")%></td> <td><%#DataBinder.Eval(Container.DataItem, "country")%></td> <td><%#DataBinder.Eval(Container.DataItem, "company")%></td> <td><%#DataBinder.Eval(Container.DataItem, "price")%></td> <td><%#DataBinder.Eval(Container.DataItem, "year")%></td> </tr> </ItemTemplate> <AlternatingItemTemplate> <tr bgcolor="#e8e8e8"> <td><%#DataBinder.Eval(Container.DataItem, "title")%></td> <td><%#DataBinder.Eval(Container.DataItem, "artist")%></td> <td><%#DataBinder.Eval(Container.DataItem, "country")%></td> <td><%#DataBinder.Eval(Container.DataItem, "company")%></td> <td><%#DataBinder.Eval(Container.DataItem, "price")%></td> <td><%#DataBinder.Eval(Container.DataItem, "year")%></td> </tr> </AlternatingItemTemplate> <FooterTemplate> </table> </FooterTemplate></asp:Repeater>

In Code-Behind file:protected void Page_Load(object sender, EventArgs e) { DataSet ds = new DataSet(); ds.ReadXml(MapPath("cdcatalog.xml")); MyRepeater.DataSource = ds;

MyRepeater.DataBind();}

Example2

<asp:Repeater ID="Repeater1" OnItemCreated="OnItemCreated" OnItemCommand="OnItemCommand" runat="server"> <SeparatorTemplate> <tr> <td><b> ****************** </b></td> </tr>

Page 21: ASP.net_XML_Basics at a Glance

</SeparatorTemplate> <HeaderTemplate> MY REPEATER <br /> <table> <tr> <td>Name</td> <td>Platform</td> </tr> </HeaderTemplate> <AlternatingItemTemplate> <tr style="background-color:Bisque"> <td><%# DataBinder.Eval(Container.DataItem,"Name") %> </td> <td> <asp:Button Text=<%# DataBinder.Eval(Container.DataItem, "Platform") %> runat="server" /></td> </tr> </AlternatingItemTemplate> <ItemTemplate> <tr style="background-color:Azure"> <td><%# DataBinder.Eval(Container.DataItem,"Name") %> </td> <td> <asp:Button Text=<%# DataBinder.Eval(Container.DataItem, "Platform") %> runat="server" /></td> </tr> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater>

InCode Behindprotected void Page_Load(object sender, EventArgs e) {

if (!IsPostBack) { ArrayList myarray = new ArrayList(); myarray.Add(new myclass("Rajesh", "C#")); myarray.Add(new myclass("praveen", "ASP.NET")); myarray.Add(new myclass("Hameed", "VB.NET")); Repeater1.DataSource = myarray; Repeater1.DataBind(); } public void OnItemCommand(Object Sender, RepeaterCommandEventArgs e) { } public void OnItemCreated(Object Sender, RepeaterItemEventArgs e) { } public void OnItemDataBound(Object Sender, RepeaterItemEventArgs e) { }}public class myclass { private string name; private string platform; public string Name {

Page 22: ASP.net_XML_Basics at a Glance

get { return name; } } public string Platform { get { return platform; } }

public myclass(string x, string y) { this.name = x; this.platform = y; }}

Difference between datagrid, datalist and repeater?

Ans:1 When displaying data in an ASP.NET Web page, many Web developers choose the data Web control they are most familiar with, which is typically the DataGrid. However, such blind decisions are not wise as there is no universally "best" data Web control. Rather, when deciding what data Web control to use for a given Web page, ask yourself a variety of questions to determine which control is best suited for the task at hand. Do you want to allow the user to sort through the data? Does the data need to be presented in a format other than an HTML <table>? Will this page be heavily visited, thereby making performance a key concern? The DataGrid Web control provides the greatest feature set of the three data Web controls, with its ability to allow the end-user to sort, page, and edit its data. The DataGrid is also the simplest data Web control to get started with, as using it requires nothing more than adding a DataGrid to the Web page and writing a few lines of code. The ease of use and impressive features comes at a cost, though, namely that of performance: the DataGrid is the least efficient of the three data Web controls, especially when placed within a Web form. With its templates, the DataList provides more control over the look and feel of the displayed data than the DataGrid. Using templates, however, typically requires more development time than using the DataGrid's column types. The DataList also supports inline editing of data, but requires a bit more work to implement than the DataGrid. Unfortunately, providing paging and sorting support in the DataList is not a trivial exercise. Making up for these lacking built-in features, the DataList offers better performance over the DataGrid.

Finally, the Repeater control allows for complete and total control of the rendered HTML markup. With the Repeater, the only HTML emitted are the values of the databinding statements in the templates along with the HTML markup specified in the templates—no "extra" HTML is emitted, as with the DataGrid and DataList. By requiring the developer to specify the complete generated HTML markup, the Repeater often requires the longest development time. Furthermore, the Repeater does not offer built-in editing, sorting, or paging support. However, the Repeater does boast the best performance of the three data Web controls. Its performance is comparable to the DataList's, but noticeably better than the DataGrid's.Ans:2

Datagrid has paging while Datalist doesnt. Datalist has a property called RepeatDirection = vertical/horizontal. (This is of

great help in designing layouts). This is not there in Datagrid. A repeater is used when more intimate control over html generation is required. When only checkboxes/radiobuttons are repeatedly served then a checkboxlist or

radiobuttonlist are used as they involve fewer overheads than a Datagrid. The Repeater repeats a chunk of HTML you write, it has the least functionality of the

Page 23: ASP.net_XML_Basics at a Glance

three. DataList is the next step up from a Repeater; accept you have very little control over the HTML that the control renders. DataList is the first of the three controls that allow you Repeat-Columns horizontally or vertically. Finally, the DataGrid is the motherload. However, instead of working on a row-by-row basis, you’re working on a column-by-column basis. DataGrid caters to sorting and has basic paging for your disposal. Again you have little contro, over the HTML. NOTE: DataList and DataGrid both render as HTML tables by default. Out of the 3 controls, I use the Repeater the most due to its flexibility w/ HTML. Creating a Pagination scheme isn't that hard, so I rarely if ever use a DataGrid. Occasionally I like using a DataList because it allows me to easily list out my records in rows of three for instance.

Ans:3 Datagrid is most restrictive as regards to customization followed by DataList and

finally Repeater is the most customizable.

Datagrid has built in paging, sorting and editing capabilities which are not there with the other two controls. So if you want users to sort / page / edit data, datagrid is the natural choice.

DataList and repeater have better performance than datagrid. So if performance is a major concern, for example, a site with large number of concurrent visitors, then you could think of datalist or repeater.

Repeater is the most customizable. It allows you to create structures like nested lists, for example.

A datagrid row displays one record from the data source, while a datalist row can display more than one records (set by RepeatColumns property)

Datagrid and Datalist are derived from WebControl while Repeater is not, and so does not have the stylistic properties of web controls.

All are similar in that they have a datasource property and ItemCreated, ItemDataBound and ItemCommand events.

GridView Class: 

Displays the values of a data source in a table where each column represents a field

and each row represents a record. The GridView control allows you to select, sort, and edit

these items.

The GridView control is used to display the values of a data source in a table. Each

column represents a field, while each row represents a record. The GridView control

supports the following features:

Binding to data source controls, such as SqlDataSource.

Built-in sorting capabilities.

Built-in updating and deleting capabilities.

Built-in paging capabilities.

Built-in row selection capabilities.

Page 24: ASP.net_XML_Basics at a Glance

Programmatic access to the GridView object model to dynamically set properties,

handle events, and so on.

Multiple key fields.

Multiple data fields for the hyperlink columns.

Customizable appearance through themes and styles.

Note:

If you are familiar with the DataGrid control from the .NET Framework version 1.0, the GridView control is the successor to the DataGrid control.

Column Fields:

Each column in the GridView control is represented by a DataControlField object. By

default, the AutoGenerateColumns property is set to true, which creates an

AutoGeneratedField object for each field in the data source. Each field is then rendered as a

column in the GridView control in the order that each field appears in the data source.

You can also manually control which column fields appear in the GridView control by

setting the AutoGenerateColumns property to false and then defining your own column

field collection. Different column field types determine the behavior of the columns in the

control. The following table lists the different column field types that can be used.

Column field type Description

BoundField Displays the value of a field in a data source. This is the default column type of the GridView control.

ButtonField Displays a command button for each item in the GridView control. This allows you to create a column of custom button controls, such as the Add or the Remove button.

CheckBoxField Displays a check box for each item in the GridView control. This column field type is commonly used to display fields with a Boolean value.

CommandField Displays predefined command buttons to perform selecting, editing, or deleting operations.

HyperLinkField Displays the value of a field in a data source as a hyperlink. This column field type allows you to bind a second field to the hyperlink's URL.

ImageField Displays an image for each item in the GridView control.

TemplateField Displays user-defined content for each item in the GridView control according to a specified template. This column field type allows you to create a custom column field.

To define a column field collection declaratively, first add opening and closing <Columns>

tags between the opening and closing tags of the GridView control. Next, list the column

Page 25: ASP.net_XML_Basics at a Glance

fields that you want to include between the opening and closing <Columns> tags. The

columns specified are added to the Columns collection in the order listed. The Columns

collection stores all the column fields in the control and allows you to programmatically

manage the column fields in the GridView control.

Explicitly declared column fields can be displayed in combination with automatically generated

column fields. When both are used, explicitly declared column fields are rendered first, followed

by the automatically generated column fields.

Note:

Automatically generated column fields are not added to the Columns collection.

Binding to Data:

The GridView control can be bound to a data source control (such as SqlDataSource,

ObjectDataSource, and so on), as well as any data source that implements the

System.Collections.IEnumerable interface (such as System.Data.DataView,

System.Collections.ArrayList, or System.Collections.Hashtable). Use one of the following

methods to bind the GridView control to the appropriate data source type:

To bind to a data source control, set the DataSourceID property of the GridView

control to the ID value of the data source control. The GridView control automatically

binds to the specified data source control and can take advantage of the data source

control's capabilities to perform sorting, updating, deleting, and paging functionality.

This is the preferred method to bind to data.

To bind to a data source that implements the System.Collections.IEnumerable

interface, programmatically set the DataSource property of the GridView control to the

data source and then call the DataBind method. When using this method, the

GridView control does not provide built-in sorting, updating, deleting, and paging

functionality. You need to provide this functionality by using the appropriate event.

For more information on data binding, see Accessing Data with ASP.NET.

Note:

This control can be used to display user input, which might include malicious client script. Check any information that is sent from a client for executable script, SQL statements, or other code before displaying it in your application. Whenever possible, it is strongly recommended that values are HTML-encoded before they are displayed in this control (the BoundField class HTML-encodes values by default). ASP.NET provides an input request validation feature to block script and HTML in user input. Validation server controls are also

Page 26: ASP.net_XML_Basics at a Glance

provided to assess user input. For more information, see Introduction to the Validation Controls.

Data Operations:

The GridView control provides many built-in capabilities that allow the user to sort,

update, delete, select, and page through items in the control. When the GridView control is

bound to a data source control, the GridView control can take advantage of the data source

control's capabilities and provide automatic sorting, updating, and deleting functionality.

Note:

The GridView control can provide support for sorting, updating, and deleting with other types of data sources; however, you will need to provide an appropriate event handler with the implementation for these operations.

Sorting allows the user to sort the items in the GridView control with respect to a

specific column by clicking on the column's header. To enable sorting, set the AllowSorting

property to true.

The automatic updating, deleting, and selection functionalities are enabled when a

button in a ButtonField or TemplateField column field, with a command name of "Edit",

"Delete", and "Select", respectively, is clicked. The GridView control can automatically add

a CommandField column field with an Edit, Delete, or Select button if the

AutoGenerateEditButton, AutoGenerateDeleteButton, or AutoGenerateSelectButton property

is set to true, respectively.

Note:

Inserting records into the data source is not directly supported by the GridView control. However, it is possible to insert records by using the GridView control in conjunction with the DetailsView or FormView control. For more information, see DetailsView or FormView, respectively.

Instead of displaying all the records in the data source at the same time, the

GridView control can automatically break the records up into pages. To enable paging, set

the AllowPaging property to true.

You can also show or hide different parts of the control. The following table lists the

properties that control which parts are shown or hidden.

Property Description

ShowFooter Shows or hides the footer section of the GridView control.

Page 27: ASP.net_XML_Basics at a Glance

ShowHeader Shows or hides the header section of the GridView control.

GridView Events:

The GridView control provides several events that you can program against. This

allows you to run a custom routine whenever an event occurs. The following table lists the

events supported by the GridView control.

Event Description

PageIndexChanged Occurs when one of the pager buttons is clicked, but after the GridView control handles the paging operation. This event is commonly used when you need to perform a task after the user navigates to a different page in the control.

PageIndexChanging Occurs when one of the pager buttons is clicked, but before the GridView control handles the paging operation. This event is often used to cancel the paging operation.

RowCancelingEdit Occurs when a row's Cancel button is clicked, but before the GridView control exits edit mode. This event is often used to stop the canceling operation.

RowCommand Occurs when a button is clicked in the GridView control. This event is often used to perform a task when a button is clicked in the control.

RowCreated Occurs when a new row is created in the GridView control. This event is often used to modify the contents of a row when the row is created.

RowDataBound Occurs when a data row is bound to data in the GridView control. This event is often used to modify the contents of a row when the row is bound to data.

RowDeleted Occurs when a row's Delete button is clicked, but after the GridView control deletes the record from the data source. This event is often used to check the results of the delete operation.

RowDeleting Occurs when a row's Delete button is clicked, but before the GridView control deletes the record from the data source. This event is often used to cancel the deleting operation.

RowEditing Occurs when a row's Edit button is clicked, but before the GridView control enters edit mode. This event is often used to cancel the editing operation.

RowUpdated Occurs when a row's Update button is clicked, but after the GridView control updates the row. This event is often used to check the results of the update operation.

RowUpdating Occurs when a row's Update button is clicked, but before the GridView control updates the row. This event is often used to

Page 28: ASP.net_XML_Basics at a Glance

cancel the updating operation.

SelectedIndexChanged Occurs when a row's Select button is clicked, but after the GridView control handles the select operation. This event is often used to perform a task after a row is selected in the control.

SelectedIndexChanging

Occurs when a row's Select button is clicked, but before the GridView control handles the select operation. This event is often used to cancel the selection operation.

Sorted Occurs when the hyperlink to sort a column is clicked, but after the GridView control handles the sort operation. This event is commonly used to perform a task after the user clicks on a hyperlink to sort a column.

Sorting Occurs when the hyperlink to sort a column is clicked, but before the GridView control handles the sort operation. This event is often used to cancel the sorting operation or to perform a custom sorting routine.

Example:

<asp:GridView ID="grdvw_Contacts" CssClass="gridview" OnPageIndexChanging="grdvw_Contacts_PageIndexChanging"

OnSorting="grdvw_Contacts_Sorting" runat="server" DataKeyNames="Cont_ID" AutoGenerateColumns="false"> <Columns> <asp:TemplateField> <HeaderTemplate> <asp:Label ID="lbl_Select" Text="Select" runat="server" /> </HeaderTemplate> <ItemTemplate> <asp:CheckBox ID="chk_ContactID" runat="server" /> </ItemTemplate> <ItemStyle CssClass="select_column" /> <HeaderStyle CssClass="chkboxHeaderStyle" /> </asp:TemplateField> <asp:BoundField HeaderText="Name" DataField="Cont_Name"

SortExpression="Cont_Title" ItemStyle-CssClass="list_column"

HeaderStyle-CssClass="HeaderStyle" /> <asp:BoundField HeaderText="Title" DataField="Cont_Title"

SortExpression="Cont_Title"ItemStyle-CssClass="list_column"HeaderStyle-CssClass="HeaderStyle" />

<asp:HyperLinkField HeaderText="Contact Type" DataNavigateUrlFields="Cont_ID"

DataNavigateUrlFormatString="ContactInfo.aspx? LinkName=EditContactInfo&ContactID={0}" DataTextField="Cont_ContactType"SortExpression="Cont_ContactType" >

<ItemStyle CssClass="list_column" /> <HeaderStyle CssClass="HeaderStyle" /> </asp:HyperLinkField> <asp:BoundField HeaderText="Company" DataField="Cont_Company"

Page 29: ASP.net_XML_Basics at a Glance

SortExpression="Cont_Company" ItemStyle-CssClass="list_column"

HeaderStyle-CssClass="HeaderStyle" /> </Columns></asp:GridView>

if (!Page.IsPostBack){

grdvw_Contacts.DataSource = GetContactsData(); grdvw_Contacts.AllowPaging = true; grdvw_Contacts.PageSize = 7; grdvw_Contacts.AllowSorting = true; grdvw_Contacts.DataBind();}protected ICollection GetContactsData(){ string strUsername; DataTable dt = new DataTable(); DataRow dr;

dt.Columns.Add(new DataColumn("Cont_ID", typeof(Int32))); dt.Columns.Add(new DataColumn("Cont_Name", typeof(string))); dt.Columns.Add(new DataColumn("Cont_Title", typeof(string))); dt.Columns.Add(new DataColumn("Cont_ContactType", typeof(string))); dt.Columns.Add(new DataColumn("Cont_Company", typeof(string))); if (IsChildUser) {

strUsername = webService.GetParentUsername(Session["Username"].ToString());

} else { strUsername = Session["Username"].ToString(); }

foreach (EngageIP.ViewContact contact in webService.GetContacts(strUsername))

{ if (contact.ContactType == "Billing Contact") { IsBillingCont = true; } dr = dt.NewRow(); dr[0] = contact.ID; dr[1] = contact.Name; dr[2] = contact.Title; dr[3] = contact.ContactType; dr[4] = contact.Company; dt.Rows.Add(dr); }

if (dt.Rows.Count == 0) { dr = dt.NewRow();

Page 30: ASP.net_XML_Basics at a Glance

dt.Rows.Add(dr); }

DataView dv = new DataView(dt); Session["dv_Contacts"] = dv; return dv; }

void grdvw_Contacts_PageIndexChanging(object sender,GridViewPageEventArgs e){ grdvw_Contacts.DataSource = GetContactsData(); grdvw_Contacts.PageIndex = e.NewPageIndex; grdvw_Contacts.DataBind();}

void grdvw_Contacts_Sorting(object sender,GridViewSortEventArgs e){ ViewState["sortexpression"] = e.SortExpression; if (ViewState["sortdirection"] == null) { ViewState["sortdirection"] = "asc"; } else { if (ViewState["sortdirection"].ToString() == "asc") { ViewState["sortdirection"] = "desc"; } else { ViewState["sortdirection"] = "asc"; } }

DataView dv = (DataView)Session["dv_Contacts"]; if (ViewState["sortexpression"] != null) { dv.Sort = ViewState["sortexpression"].ToString() + " "

+ ViewState["sortdirection"].ToString(); } grdvw_Contacts.DataSource = dv; grdvw_Contacts.DataBind();}

GridView Sorting

<form id="form1" runat="server"> <div> <asp:GridView ID="MyGridView" AutoGenerateColumns="False" OnSorting="OnSorting" OnPageIndexChanging="OnPaging" OnPageIndexChanged="OnPaged" OnRowCommand="OnRowCommand" runat="server"> <Columns> <asp:BoundField HeaderText="CustomerID" DataField="CustomerID" SortExpression="CustomerID"/>

Page 31: ASP.net_XML_Basics at a Glance

<asp:BoundField HeaderText="ContactName" DataField="ContactName" SortExpression="ContactName"/> <asp:BoundField HeaderText="CompanyName" DataField="CompanyName" SortExpression="CompanyName"/> <asp:HyperLinkField HeaderText="HyperLink" DataNavigateUrlFields="CustomerID" DataNavigateUrlFormatString="SmallWindow.aspx?id={0}" DataTextField="ContactTitle" /> <asp:TemplateField HeaderText="TextBox"> <ItemTemplate> <asp:TextBox ID="box" runat="server"> </asp:TextBox> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="ListBox"> <ItemTemplate> <asp:DropDownList ID="DDLbox" DataTextField="City" DataValueField = "City" DataSource= '<%# GetDataforDDL() %>' runat="server"> </asp:DropDownList> </ItemTemplate> </asp:TemplateField> <asp:ButtonField ButtonType="Button" HeaderText="Button" Text="Button" /> </Columns> </asp:GridView> <br /> <br /> <asp:Label ID="Label1" runat="server"></asp:Label><br /> <asp:Button ID="Button1" runat="server" Text="Button" /> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox></div></form>

InCodeBehind protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { MyGridView.DataSource = GetData(); MyGridView.AllowPaging = true; MyGridView.PageSize = 10; MyGridView.AllowSorting = true; MyGridView.DataBind(); } } protected void OnSorting(object sender, GridViewSortEventArgs e) { ViewState["sortexpression"] = e.SortExpression; if (ViewState["sortdirection"] == null) { ViewState["sortdirection"] = "asc"; } else { if (ViewState["sortdirection"].ToString() == "asc"){ ViewState["sortdirection"] = "desc"; } else { ViewState["sortdirection"] = "asc"; }

Page 32: ASP.net_XML_Basics at a Glance

} DataView dv = (DataView)Session["dv_CDRHistory"]; if (ViewState["sortexpression"] != null) { dv.Sort = ViewState["sortexpression"].ToString() + " " + ViewState["sortdirection"].ToString(); } MyGridView.DataSource = dv; MyGridView.DataBind(); } protected void OnPaging(object sender, GridViewPageEventArgs e) { MyGridView.DataSource = GetData(); MyGridView.PageIndex = e.NewPageIndex; MyGridView.DataBind(); } protected void OnPaged(Object sender, EventArgs f) { int currentPage = MyGridView.PageIndex + 1; // Display the current page number. Label1.Text = "Page " + currentPage.ToString() + " of " + MyGridView.PageCount.ToString() + ".";

} protected ICollection GetData() { SqlConnection myconn=new SqlConnection (ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ToString()); SqlDataAdapter myadapter = new SqlDataAdapter("Select CustomerID,ContactName,CompanyName,ContactTitle,City from Customers", myconn); SqlCommandBuilder mybuilder = new SqlCommandBuilder(myadapter); DataSet ds = new DataSet(); myadapter.Fill(ds); DataTable dt = ds.Tables[0]; DataView dv = new DataView(dt); Session["dv_CDRHistory"] = dv; return dv; } protected ICollection GetDataforDDL() { SqlConnection myconn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ToString()); SqlDataAdapter myadapter = new SqlDataAdapter("Select City from Customers", myconn); SqlCommandBuilder mybuilder = new SqlCommandBuilder(myadapter); DataSet ds2 = new DataSet(); myadapter.Fill(ds2); DataTable dt2 = ds2.Tables[0]; DataView dv2 = new DataView(dt2); return dv2; } protected void OnRowCommand(Object sender,GridViewCommandEventArgs e) { int rowID=Convert.ToInt32(e.CommandArgument); GridViewRow myrow=MyGridView.Rows[rowID];

Page 33: ASP.net_XML_Basics at a Glance

TextBox2.Text = ((DropDownList)myrow.FindControl("DDLbox")).SelectedValue.ToString(); TextBox3.Text = ((TextBox)myrow.FindControl("box")).Text.ToString(); }

GridView Syntax:

<asp:GridView AllowPaging = "True | False" AllowSorting = "True | False" AutoGenerateColumns = "True | False" AutoGenerateDeleteButton = "True | False" AutoGenerateEditButton = "True | False" AutoGenerateSelectButton = "True | False" DataSource = "string" DataSourceID = "string" ID = "string" OnDataBinding = "DataBinding event handler" OnDataBound = "DataBound event handler" OnPageIndexChanged = "PageIndexChanged event handler" OnPageIndexChanging = "PageIndexChanging event handler" OnRowCancelingEdit = "RowCancelingEdit event handler" OnRowCommand = "RowCommand event handler" OnRowCreated = "RowCreated event handler" OnRowDataBound = "RowDataBound event handler" OnRowDeleted = "RowDeleted event handler" OnRowDeleting = "RowDeleting event handler" OnRowEditing = "RowEditing event handler" OnRowUpdated = "RowUpdated event handler" OnRowUpdating = "RowUpdating event handler" OnSelectedIndexChanged = "SelectedIndexChanged event handler" OnSelectedIndexChanging = "SelectedIndexChanging event handler" OnSorted = "Sorted event handler" OnSorting = "Sorting event handler" PageIndex = integer > </asp:GridView>

Edit Mode: The fields that are marked readonly = false will change into TextBoxes when the Row_Editing event triggers

// Editing mode void myGridView_RowEditing(object sender, GridViewEditEventArgs e){ myGridView.EditIndex = e.NewEditIndex; BindData();}

Page 34: ASP.net_XML_Basics at a Glance

Cancel Edit:If you don't like to edit the row you can press cancel link button which will fire the RowCancelingEdit event. The code to turn the row back to its original form is quite simple and straight forward.

// Cancel Edit Modevoid myGridView_RowCancelingEdit(object sender,GridViewCancelEditEventArgs e){ myGridView.EditIndex = -1; BindData(); }

Selecting Row: Selecting row event is fired when you make a click on the select link. If you need any particular item in that row you can easily select it using the cells property:The Cells start with index '0' which means Cell[0] is CategoryID , Cell[1] is CategoryName and so on.

// Selecting rowvoid myGridView_SelectedIndexChanged(object sender, EventArgs e){ // This will contain the selectedValue of the row string selectedCategory = myGridView.SelectedRow.Cells[1].Text;}

Update Row:For updating the row we first need to get the value from the row that is entered by the user into the Textbox. For this purpose you can change the bound column into a Template column which will make is easier to locate the item. After changing the CategoryName column to a tem plated column we can easily use the RowUpdating event to find the Text entered by the user.

void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e){ GridViewRow row = myGridView.Rows[e.RowIndex]; if (row != null) { TextBox t = row.FindControl("TextBox1") as TextBox; if (t != null) { Response.Write("The Text Entered is" + t.Text); }}

Paging: Paging can also be easily enabled in the grid view control. Its just like DataGrid from Asp.net 1.1. First you need to make set the allow paging property to true. And you can also set the page size. Here is a small code sample that will enable paging.

Page 35: ASP.net_XML_Basics at a Glance

// Grid View Paging void myGridView_PageIndexChanging(object sender, GridViewPageEventArgs e){ myGridView.PageIndex = e.NewPageIndex; BindData(); }

Authentication and Authorization

Authentication is the process of obtaining some sort of credentials from the users and using those credentials to verify the user's identity. Authorization is the process of allowing an authenticated user to access or deny resources.Internet Information Services (IIS), controls authentication and authorization in ASP.net applications.

ASP.NET authentication process

ASP.NET does not run by itself it run inside the process of IIS. So there are twoauthentication layers which exist in ASP.NET system. First authentication happens atthe IIS level and then at the ASP.NET level depending on the WEB.CONFIG file.

* IIS first checks to make sure the incoming request comes from an IP addressthat is allowed access to the domain. If not it denies the request.* Next IIS performs its own user authentication if it configured to do so. Bydefault IIS allows anonymous access, so requests are automaticallyauthenticated, but you can change this default on a per – application basiswith in IIS.* If the request is passed to ASP.net with an authenticated user, ASP.net checksto see whether impersonation is enabled. If impersonation is enabled, ASP.netacts as though it were the authenticated user. If not ASP.net acts with its ownconfigured account.* Finally the identity from step 3 is used to request resources from the operatingsystem. If ASP.net authentication can obtain all the necessary resources itgrants the users request otherwise it is denied. Resources can include muchmore than just the ASP.net page itself you can also use .Net’s code accesssecurity features to extend this authorization step to disk files, Registry keysand other resources.

Various ways of authentication techniques in ASP.NET.

1. authentication mode=”windows” 2. authentication mode=”passport”3. authentication mode=”forms”4. Custom authentication where you might install an ISAPI filter in IIS that

Page 36: ASP.net_XML_Basics at a Glance

compares incoming requests to list of source IP addresses, and considersrequests to be authenticated if they come from an acceptable address. In thatcase, you would set the authentication mode to none to prevent any of the.net authentication providers from being triggered.

Windows authentication and IIS If you select windows authentication for your ASP.NET application, you also have toconfigure authentication within IIS. This is because IIS provides Windows authentication. IIS gives you a choice for four different authentication methods:Anonymous, basic, digest and windows integrated

Anonymous authentication, IIS doesn’t perform any authentication. Any one is allowed to access the ASP.NET application.Basic authentication, users must provide a windows username and password to connect. How ever this information is sent over the network in clear text, which makes basic authentication very much insecure over the internet.Digest authentication, users must still provide a windows user name andpassword to connect. However the password is hashed before it is sent across the network. Digest authentication requires that all users be running Internet Explorer 5 or later and that windows accounts to stored in active directory.Windows integrated authentication, passwords never cross the network.Users must still have a username and password

Passport authenticationPassport authentication lets you to use Microsoft’s passport service to authenticate users of your application. If your users have signed up with passport, and you configure the authentication mode of the application to the passport authentication, all authentication duties are off-loaded to the passport servers. Passport uses an encrypted cookie mechanism to indicate authenticated users. If users have already signed into passport when they visit your site, they’ll be considered authenticated by ASP.NET. Otherwise they’ll be redirected to the passport servers to log in. When they are successfully log in, they’ll be redirected back to your site.

Forms authenticationForms authentication provides you with a way to handle authentication using your own custom logic with in an ASP.NET application. When a user requests a page for the application, ASP.NET checks for the presence of a special session cookie. If the cookie is present, ASP.NET assumes the user is authenticated and processes the request. If the cookie isn’t present, ASP.NET redirects the user to a web form you provide

<authentication mode="Forms"> <forms loginUrl="LoginPage.aspx"> <credentials passwordFormat="Clear"> <user name="rajesh" password="anand"/> </credentials> </forms></authentication><authorization> <deny users="?" /></authorization>

Using in page

if (FormsAuthentication.Authenticate(UserName.Text, Password.Text))

Page 37: ASP.net_XML_Basics at a Glance

FormsAuthentication.RedirectFromLoginPage(UserName.Text, chkPersistCookie.Checked);//Here the (chkPersistCookie.Checked) is a bool value to keep the cookie persisted for longer time(50 yrs if not customed)or according to user requestelse lblMessage.Text = "Invalid login credentials";

Caching Caching allows you to store commonly used items in the memory and thus not create them from scratch when they are requested. There are different types of Caching available in the .NET framework.Caching helps us to achieve three important aspects of Quality Of Service:

Performance - Caching improves application performance by minimizing data retrieval and formatting operations.

Scalability - Since caching minimizes data retrieval and formatting operations, it reduces the load on server resources thus increasing the scalability of the application.

Availability - Since the application uses data from a cache, the application will survive failures in other systems and databases.

Caching Options in ASP.NETASP.NET supports three types of caching for Web-based applications:

Page Level Caching (called Output Caching) Page Fragment Caching (often called Partial-Page Output Caching) Programmatic or Data Caching

Output Caching Page level, or output caching, caches the HTML output of dynamic requests to ASP.NET Web pages. The way ASP.NET implements this (roughly) is through an Output Cache engine. Each time an incoming ASP.NET page request comes in, this engine checks to see if the page being requested has a cached output entry. If it does, this cached HTML is sent as a response; otherwise, the page is dynamically rendered, its output is stored in the Output Cache engine. Output Caching is particularly useful when you have very static pages.

Syntax: <%@ OutputCache Duration=5 VaryByParam="None" %> Duration - The time in seconds of how long the output should be cached. After the

specified duration has elapsed, the cached output will be removed and page content generated for the next request. That output will again be cached for 5 seconds and the process repeats.

VaryByParam - This attribute is compulsory and specifies the querystring parameters to vary the cache. In the above snippet, we have specified the VaryByParam attribute as None which means the page content to be served is the same regardless of the parameters passed through the querystring If there are two requests to the same page with varying querystring parameters, e.g. PageCachingByParam.aspx?id=12 and PageCachingByParam.aspx?id=15 and separate page content is generated for each of them, the directive should be:

<%@OutputCache Duration=5 VaryByParam="id" %>

Partial-Page Output Caching

Page 38: ASP.net_XML_Basics at a Glance

Partial-Page Output Caching, or page fragment caching, allows specific regions of pages to be cached. ASP.NET provides a way to take advantage of this powerful technique, requiring that the part(s) of the page you wish to have cached appear in a User Control. One way to specify that the contents of a User Control should be cached is to supply an OutputCache directive at the top of the User Control. That's it! The content inside the User Control will now be cached for the specified period, while the ASP.NET Web page that contains the User Control will continue to serve dynamic content. (Note that for this you should not place an OutputCache directive in the ASP.NET Web page that contains the User Control - just inside of the User Control.)

<%@ OutputCache Duration=5 VaryByParam="None" %> should be specified at the top of the User Control

Data Caching ASP.NET also supports caching of data as objects. We can store objects in memory and use them across various pages in our application. This feature is implemented using the Cache class. This cache has a lifetime equivalent to that of the application. Objects can be stored as name value pairs in the cache. A string value can be inserted into the cache as follows,

Cache["name"]="Rajesh"; The stored string value can be retrieved like this if (Cache["name"] != null) Label1.Text= Cache["name"].ToString();

To insert objects into the cache, the Add method or different versions of the Insert method of the Cache class can be used. One of the overloads of the Insert method is used as follows:

Cache. Insert("Name", strName, new CacheDependency (Server.MapPath ("name.txt"), DateTime.Now.AddMinutes(2), TimeSpan.Zero , CacheItemPriority.High, null);

The CacheItemPriority enumeration has members to set various priority values. The CacheItemPriority.High assigns a priority level to an item so that the item is least likely to be deleted from the cache.

Web Services Web services make use of the SOAP protocol, which is a standard defined by many companies. A big advantage of Web services is its platform-independence.

Page 39: ASP.net_XML_Basics at a Glance

First, you can find a Web service that has been registered in a registration directory

service. This directory service returns information about the Web service. It's not a requirement that a Web service be registered with Universal Description, Discovery, and Integration (UDDI). You can get information about Web services from other sources.

The description of the service is presented in the Web Services Description Language (WSDL) format. The description specifies the data that can be sent to the Web service, and what data can be received.

The description of the Web service tells you what methods can be called. The methods will be called using SOAP, so all the method calls including the arguments must be converted to the SOAP protocol.

With the .NET Framework, it is easy to create and consume Web services. The three major namespaces that deal with Web services are:

The classes in the namespace System.Web.Services are used to create Web services.

With the namespace System.Web.Services.Description, you can describe Web services via WSDL.

With System.Web.Services.Protocols you can create SOAP requests and responses.

Difference between Web Service And .Net Remoting

ASP.NET Web Services .NET Remoting

Protocol Can be accessed only over HTTP Can be accessed over any protocol (including TCP, HTTP, SMTP and so on)

State Web services work in a stateless Provide support for both stateful and

Page 40: ASP.net_XML_Basics at a Glance

Management environment stateless environments through Singleton and SingleCall objects

Type System

Web services support only the data types defined in the XSD type system, limiting the number of objects that can be serialized.

Using binary communication, .NET Remoting can provide support for rich type system

Interoperability

Web services support interoperability across platforms, and are ideal for heterogeneous environments.

.NET remoting requires the client be built using .NET, enforcing homogenous environment.

Reliability Highly reliable due to the fact that Web services are always hosted in IIS

Can also take advantage of IIS for fault isolation. If IIS is not used, application needs to provide plumbing for ensuring the reliability of the application.

Extensibility

Provides extensibility by allowing us to intercept the SOAP messages during the serialization and deserialization stages.

Very extensible by allowing us to customize the different components of the .NET remoting framework.

Ease-of-Programming

Easy-to-create and deploy. Complex to program.

Validation Controls

ASP.NET validation controls provide two ways of validation: Server-side or Client-side. The nice thing about these Validation controls is that it will perform client-side validation when it detects the browser is able (unless client-side validation has been disabled). Thus reducing roundtrips. And it will perform server-side where necessary. With ASP.NET, there are six (6) controls included. They are:

The RequiredFieldValidator Control The CompareValidator Control The RangeValidator Control The RegularExpressionValidator Control The CustomValidator Control

Validator Control Basics All of the validation controls inherit from the base class BaseValidator so they all have a series of properties and methods that are common to all validation controls. Some of them are:

ControlToValidate - This value is which control the validator is applied to. ErrorMessage - This is the error message that will be displayed in the validation

summary. Display - This controls how the error message is shown. Here are the possible

options: o None (The validation message is never displayed.) o Static (Space for the validation message is allocated in the page layout.) o Dynamic (Space for the validation message is dynamically added to the page

if validation fails.)

RequiredFieldValidator Control The first control we have is the RequiredFieldValidator Control. As it's obvious, it makes sure that a user inputs a value.

Page 41: ASP.net_XML_Basics at a Glance

<asp:RequiredFieldValidator id="valRequired" runat="server" ControlToValidate="textbox1" ErrorMessage="* You must enter a value into textbox1" Display="Dynamic">* </asp:RequiredFieldValidator>

In this example, we have a textbox which will not be valid until the user types something in. Inside the validator tag, we have a single *. The text in the innerhtml will be shown in the controltovalidate if the control is not valid. It should be noted that the ErrorMessage attribute is not what is shown. The ErrorMessage tag is shown in the Validation Summary.

The CompareValidator Control Usage of this CompareValidator is for confirming new passwords, checking if a departure date is before the arrival date, etc.

Operator: Equal; NotEqual; GreaterThan; GreaterThanEqual; LessThan; LessThanEqual; DataTypeCheck

Type: String; Integer; Double; Date; Currency

Here the Date in TextBox2 should be greater than TextBox2

<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="TextBox1" ControlToValidate="TextBox2" Display="Dynamic" ErrorMessage="CompareValidator" Operator="GreaterThan" Type="Date"> </asp:CompareValidator>

Here the TextBox1 value should be greater than 50

<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="TextBox1" Display="Dynamic" ValueToCompare="50" Type="Integer" Operator="GreaterThan" ErrorMessage="CompareValidator"> </asp:CompareValidator>

The RangeValidator Control Range validator control is another validator control which checks to see if a control value is within a valid range. The attributes that are necessary to this control are: MaximumValue, MinimumValue, and Type.

<asp:RangeValidator id="valRange" runat="server" ControlToValidate="textbox1" MaximumValue="12/31/1998" MinimumValue="1/1/1998" Type="Date" Display="static" ErrorMessage="* The date must be between 1/1/1998 and 12/13/1998">* </asp:RangeValidator>

The RegularExpressionValidator Control The regular expression validator is one of the more powerful features of ASP.NET , they check for the validationexpression specified.

Page 42: ASP.net_XML_Basics at a Glance

Here the validator checks for valid Email

<asp:RegularExpressionValidator id="valRegEx" runat="server" ControlToValidate="TextBox4" display="dynamic" ValidationExpression=".*@.*\..*" ErrorMessage="* Your entry is not a valid e-mail address." </asp:RegularExpressionValidator>

The CustomValidator Control The final control we have included in ASP.NET is one that adds great flexibility to our validation abilities. We have a custom validator where we get to write out own functions and pass the control value to this function.

<asp:CustomValidator id="valCustom" runat="server" ControlToValidate="textbox1" display="dynamic" ClientValidationFunction="ClientValidate" OnServerValidate="ServerValidatefunction" ErrorMessage="*This box is not valid">* </asp:CustomValidator>

void ServerValidatefunction(ref Object objSource, ref ServerValidateEventArgs objArgs);

ClientValidationFunction is usually a javascript function included in the html to the user. OnServerValidate is the function that is server-side to check for validation if client does not support client-side validation.

Validation Summary

<asp:ValidationSummary id="valSummary" runat="server" HeaderText="Errors:" ShowSummary="true" ShowMessageBox="true" DisplayMode="List"/>

The validation summary control will collect all the error messages of all the non-valid controls and put them in a tidy list. The list can be either shown on the web page (as shown in the example above) or with a popup box (by specifying ShowMessageBox="True")

Application domain

An application domain is the CLR equivalent of an operation system's process. An application domain is used to isolate applications from one another. This is the same way an operating system process works. The separation is required so that applications do not affect one another. This separation is achieved by making sure than any given unique virtual address space runs exactly one application and scopes the resources for the process or application domain using that address space.

However, a CLR application domain is separate from a process. It is contained within an operating system process. A single CLR operating system process can contain multiple application domains. There are some major pluses to having application domains within a single process.

Page 43: ASP.net_XML_Basics at a Glance

Lower system cost - many application domains can be contained within a single system process.

The application in an application domain can be stopped without affecting the state of another application domain running in the same process.

A fault or exception in on application domain will not affect other application domains or crash the entire process that hosts the application domains.

Configuration information is part of an application domains scope, not the scope of the process.

Each application domain can have different security access levels assigned to them, all within a single process.

Code in one application domain cannot directly access code in another application domain.

So you see, the CLR is like a mini-operating system. It runs a single process that contains a bunch of sub-process, or application domains.

* Direct communication cannot be achieved across application domains. Application domains can still talk to each other by passing objects via marshalling by value (unbound objects), marshalling by reference through a proxy (AppDomain-bound objects). There is a third type of object called a context-bound object which can be marshalled by reference across domains and also within the context of its own application domain. Because of the verifiable type-safety of managed code, the CLR can provide fault isolation between domains at a much lower cost than an operating system process can.

using System;namespace AppdomainCreation_Console{ class Program { static void Main(string[] args) { //Instantiate AppDomainSetup object AppDomainSetup appDomainSetup = new AppDomainSetup(); //Configure AppDomainSetup Setup Information Directory where CLR will look during probing to resolve private assemblies.By default this is the directory containing the assembly. appDomainSetup.ApplicationBase = @"c:\Test"; //Configuration name file used by code loaded into assembly.By default it is stored in the same folder as the assembly. If we set applicationBase then it should be in same folder. appDomainSetup.ConfigurationFile = "AD.Config"; //Semicolon-separated list of directories that the runtime uses when probing for private assemblies. these directories are relative to the directory specified in ApplicationBase. appDomainSetup.PrivateBinPath = "bin;plugins;external"; //Remember to save a Reference to the new AppDomain as this Cannot be retrieved any other way AppDomain appDomain = AppDomain.CreateDomain("My First Domain", null, appDomainSetup); Console.WriteLine("AppDomain Created, Press ENTER"); Console.ReadLine(); } }}

Page 44: ASP.net_XML_Basics at a Glance

ASP.NET session state can be managed in three different ways:

InProc - Stored in the aspnet_wp.exe process area. The session data is lost when the process or the application domain is recycled.

StateServer - Session state is stored in a separate process (aspnet_state.exe) which can be stored in a different machine. Since it can be stored in a different machine, this option will work in a web farm scenario.

SQLServer - Session state is stored in a SQL Server database. This option will also work in a web farm scenario.

Both in StateServer and SQLServer options, we need to ensure that the objects we cache are serializable as data storages are out-of-process systems. Both these options have impact on the application performance as data retrieval and saving operations take more time when compared to the InProc option. So based on our application requirement we should choose the option that best suits our requirement.

------------------------------------------------------------------------------------------

What’s difference between Authentication and authorization? These two concepts seem altogether similar but there is wide range of difference. Authentication is verifying the identity of a user and authorization is process where we check does this identity have access rights to the system. In short we can say the following authentication is the process of obtaining some sort of credentials from the users and using those credentials to verify the user’s identity. Authorization is the process of allowing an authenticated user access to resources. Authentication is always precedes to Authorization; even if your application lets anonymous users connect and use the application, it still authenticates them as being anonymous.

------------------------------------------------------------------------------------------What’s the sequence in which ASP.NET events are processed? * Page_Init. * Page_Load. * Control events * Page_Unload event.Page_init event only occurs when first time the page is started, but Page_Load occurs in Subsequent request of the page.

------------------------------------------------------------------------------------------In which event are the controls fully loaded?Page_load event guarantees that all controls are fully loaded. Controls are also accessed in Page_Init events but you will see that viewstate is not fully loaded during this event.

------------------------------------------------------------------------------------------How can we identify that the Page is PostBack?Page object has an “IsPostBack” property which can be checked to know that is the page is posted back.

------------------------------------------------------------------------------------------What is event bubbling?Server controls like Datagrid, DataList and Repeater can have other child controls inside them. Example DataGrid can have combo box inside datagrid.These child control do not

Page 45: ASP.net_XML_Basics at a Glance

raise there events by themselves, rather they pass the event to the container parent (Which can be a DataGrid, DataList, repeater), which passed to the page as “ItemCommand” event.

------------------------------------------------------------------------------------------

How do we assign page specific attributes? Page attributes are specified using the @Page directive.

------------------------------------------------------------------------------------------

What’s the use of @ Register directives? @Register directive informs the compiler of any custom server control added to the page.

------------------------------------------------------------------------------------------What’s the use of SmartNavigation property?It’s a feature provided by ASP.NET to prevent flickering and redrawing when the page is posted back.Note: - This is only supported for IE browser.

------------------------------------------------------------------------------------------What is AppSetting Section in “Web.Config” file?Web.Config file defines configuration for a webproject.Using “AppSetting” section we can define user defined values. Example below defined is “ConnectionString” section which will be used through out the project for database connection.<configuration><appSettings><add key="ConnectionString" value="server=xyz; pwd=www; database=testing" /></appSettings>

------------------------------------------------------------------------------------------Where is ViewState information stored? In HTML Hidden Fields.

------------------------------------------------------------------------------------------

How many types of validation controls are provided by ASP.NET ? There are main six types of validation controls: -

RequiredFieldValidator It checks does the control have any value. It’s used when you want the control should not be empty.

RangeValidator Checks if the value in validated control is in that specific range. Example TxtCustomerCode should not be more than eight characters.

CompareValidator Checks that the value in controls should match the value in other control. Example Textbox TxtPie should be equal to 3.14.

RegularExpressionValidator When we want the control value should match with a specific regular expression.

CustomValidator Used to define User Defined validation.

Page 46: ASP.net_XML_Basics at a Glance

ValidationSummary Displays summary of all current validation errors.

------------------------------------------------------------------------------------------Can you explain what “AutoPostBack” feature in ASP.NET is? If we want the control to automatically postback in case of any event, we will need to check this attribute as true. Example on a ComboBox change we need to send the event immediately to the server side then set the “AutoPostBack” attribute to true. ------------------------------------------------------------------------------------------What’s the use of “GLOBAL.ASAX” file? It allows executing ASP.NET application level events and setting application-level variables.

------------------------------------------------------------------------------------------What’s the difference between “Web.Config” and “Machine.Config”?“Web.Config” files apply settings to each web application, while “Machine.Config” fileapply settings to all ASP.NET applications.

------------------------------------------------------------------------------------------What’s difference between Server.Transfer and Response.Redirect? Following are the major differences between them:- * Response.Redirect sends message to the browser saying it to move to some different page. While Server.Transfer does not send any message to the browser but rather redirects the user directly from the server itself. So in Server.Transfer there is no round trip while Response.Redirect has a round trip and hence puts a load on server.

* Using Server.Transfer you can not redirect to a page on different server Example if your server is www.yahoo.com you cannot use Server.Transfer to move to www.microsoft.com but you can move to www.yahoo.com/travels, i.e. within websites. This cross server redirect is possible only using Response.Redirect.

* URL will not be changed and hence Query string will not be seen in the URL when using Server.Transfer whereas it will be seen in the Response.Redirect, but we can use Querystring in both cases.

* With Server.Transfer you can preserve your information. It has a parameter called as “preserveForm”. So the existing query string etc. will be able in the calling page. In Response.Redirect you can maintain the state. You can but has lot of drawbacks. If you are navigating with in the same website use “Server.Transfer” or else go for “Response.Redirect ()” ------------------------------------------------------------------------------------------What is impersonation in ASP.NET? By default, ASP.NET executes in the security context of a restricted user account on the local machine. Sometimes you need to access network resources such as a file on a shared drive, which requires additional permissions. One way to overcome this restriction is to use impersonation. With impersonation, ASP.NET can execute the request using the identity of the client who is making the request, or ASP.NET can impersonate a specific account you specify in Web.Config.

What is meant by Strong Name?The combination of Assembly Name, Version and Key is called Strong Name with which Dot Net Runtime differentiates the shared assembly.

Page 47: ASP.net_XML_Basics at a Glance

What is a diffgram?The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML.  A good use is reading database data to an XML file to be sent to a Web Service. 

Client Callbacks Client Callback is a new feature in ASP.NET 2.0. It allows calling server side events

asynchronously, without causing postback.

Describe the role of inetinfo.exe, aspnet_isapi.dll and aspnet_wp.exe in the page loading process.

The ASP.NET ISAPI extension (aspnet_isapi.dll) runs in the IIS process address space

(inetinfo.exe) and forwards requests for ASP.NET file types to the ASP.NET worker process

through a named pipe.

Specific ASP.NET file types are mapped to the ASP.NET ISAPI extension by mappings defined

within the IIS metabase. Mappings for standard ASP.NET file types

(including .aspx, .asmx, .rem, .soap) are established when the .NET Framework is installed.

Inetinfo.exe is the Microsoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension), the ISAPI filter aspnet_isapi.dll takes care of it by passing the request to the actual worker process aspnet_wp.exe.

Code Access Security in the .NET Framework

Code access security (CAS) is a new feature provided by the .NET Common Language Runtime. CAS is a security model that lets you grant or deny execution permissions to an assembly according to its "properties," called evidence, such as its strong name or publisher.

XML-Extensible Markup Language

XML parsers

Page 48: ASP.net_XML_Basics at a Glance

Programs that read XML documents and analyze them by examining their individual elements are known as XML parsers, and they will reject any document that contains illegal XML.Parsers which will validate if a XML doc is valid or not is called validating parsersXML Documents A complete set of data in XML is known as an XML document. An XML document could be a physical file on your computer or just a string in memory. However, it has to be complete in itself.

XML Elements XML elements consist of an opening tag, the data within the element, and a closing tag. Example<book>Tristram Shandy</book>Elements can also contain other elements, so you could modify this <book> element to include the author as well as the title by adding two sub elements: <book> <title>Tristram Shandy</title> <author>Lawrence Sterne</author></book>

All opening tags should have closed tag except Empty Element. Eg.<book /> (or) <book></book>

Attributes As well as storing data within the body of the element, you can also store data within attributes, which are added within the opening tag of an element. Attributes are in the form name="value" where the value of the attribute must be enclosed in either single or double quotes. For example:<book title="Tristram Shandy"></book> (or)<book title='Tristram Shandy'></book>

Elements are a better choice if there's a possibility that you'll need to add more information about that piece of data later — you can always add a sub element or an attribute to an element, but you can't do that for attributes. Arguably, elements are more readable and more elegant .On the other hand, attributes consume less bandwidth if the document is sent over a network without compression (with compression there's not much difference) and are convenient for holding information that isn't essential to every user of the document

The XML Declaration Should be the first node ( all individual elements) if used.

<?xml version="1.0"?> (or) <?xml version="1.0" encoding=”UTF-16”?>

Unlike relational data, in which every row has the same number of columns, there's no restriction on the number of sub elements an element can have. And, although XML documents are often structured similarly to relational data, with an element for each record, XML documents don't need any predefined structure at all. Relational databases always define the structure of the information before any data can be added, information can be stored in XML without this initial overhead, which makes it a very convenient way to store small blocks of data.XML Namespaces XML namespaces should be unique. In XML namespaces each Specific elements or attributes are associated with a specific namespace using a prefix, followed by a colon. For

Page 49: ASP.net_XML_Basics at a Glance

example, <wrox:book> represents a <book> element that resides in the wrox namespace.To identify a prefix with a specific namespace, the xmlns:prefix attribute is used<?xml version="1.0"?><books> <book xmlns:wrox="http://www.wrox.com"> <wrox:title>Beginning C#</wrox:title> <wrox:author>Karli Watson</wrox:author> </book></books>

Validating XML Documents XML supports two ways of defining which elements and attributes can be placed in a document and in what order: Document Type Definitions (DTDs) and schemas.Schemas There are two separate formats for schemas supported by .NET — XML Schema Definition language (XSD) and XML-Data Reduced schemas (XDR). Elements in XSD schemas must belong to the namespace http://www.w3.org/2001/XMLSchema. If this namespace isn't included, the schema elements won't be recognized.To associate the XML document with an XSD schema in another file, you need to add a schema- location element to the root element:

<?xml version="1.0"?><books schemalocation="file://C:\BegVCSharp\XML\books.xsd">> <book> <title>Beginning Visual C#</title> <author>Karli Watson</author> <code>7582</code> </book> <book> <title>Professional C# 2nd Edition</title> <author>Simon Robinson</author> <code>7043</code> </book></books>

Take a quick look at an example XSD schema:

<schema xmlns="http://www.w3.org/2001/XMLSchema"> <element name="books"> <complexType> <choice maxOccurs="unbounded"> <element name="book"> <complexType> <sequence> <element name="title" /> <element name="author" /> <element name="code" /> </sequence> </complexType> </element> </choice> <attribute name="schemalocation" />

Page 50: ASP.net_XML_Basics at a Glance

</complexType> </element></schema>

Using XML Programmatically

protected void Button1_Click(object sender, EventArgs e){ listBoxXmlNodes.Items.Clear(); // Clear ListBox XmlDocument myxmldocument = new XmlDocument(); // Load the XML document myxmldocument.Load(@"C:\Inetpub\wwwroot\example\XMLFile.xml"); // Use recursion to loop through the document. XmlNode rootnode = myxmldocument.DocumentElement; RecurseXmlDocument(rootnode);}

private void RecurseXmlDocument(XmlNode root){ // Make sure we don't do anything if if (root == null) return; if (root is XmlElement) // Root is an XmlElement type { // first, print the name listBoxXmlNodes.Items.Add(root.Name); // Then check if there are any child nodes and if there are, call this // method again to print them. if (root.HasChildNodes) RecurseXmlDocument(root.FirstChild);

// Finally check to see if there are any siblings and if there are // call this method again to have them printed. if (root.NextSibling != null) RecurseXmlDocument(root.NextSibling); } else if (root is XmlText) { // Print the text. string text = ((XmlText)root).Value; listBoxXmlNodes.Items.Add(text); } else if (root is XmlComment) { // Print text. string text = root.Value; listBoxXmlNodes.Items.Add(text.PadLeft(text.Length + indent));

// Then check if there are any child nodes, and if there are call this // method again to print them. if (root.HasChildNodes) RecurseXmlDocument(root.FirstChild);

// Finally, check to see if there are any siblings, and if there are // call this method again to have them printed. if (root.NextSibling != null) RecurseXmlDocument(root.NextSibling); }}

Page 51: ASP.net_XML_Basics at a Glance

protected void Button2_Click(object sender, EventArgs e){ XmlDocument myxmldocument = new XmlDocument(); // Load the XML document myxmldocument.Load(@"C:\Inetpub\wwwroot\example\XMLFile.xml"); XmlNode rootnode = myxmldocument.DocumentElement; // Create the new nodes. XmlElement newBook = myxmldocument.CreateElement("book"); XmlElement newTitle = myxmldocument.CreateElement("title"); XmlElement newAuthor = myxmldocument.CreateElement("author"); XmlElement newCode = myxmldocument.CreateElement("code"); XmlText title = myxmldocument.CreateTextNode("Visual C# 3rd Edition"); XmlText author = myxmldocument.CreateTextNode("Karli Watson et al"); XmlText code = myxmldocument.CreateTextNode("1234567890"); XmlComment comment = myxmldocument.CreateComment("The book u are reading");

// Insert the elements. newBook.AppendChild(comment); newBook.AppendChild(newTitle); newBook.AppendChild(newAuthor); newBook.AppendChild(newCode); newTitle.AppendChild(title); newAuthor.AppendChild(author); newCode.AppendChild(code); rootnode.InsertAfter(newBook, rootnode.FirstChild);

myxmldocument.Save(@"C:\Inetpub\wwwroot\example\XMLFile.xml");}

XmlNode. RemoveAll() -- this method will remove all child nodes in the node on which it is Including attributesXmlNode. RemoveChild() -- This method will remove a single child in the node on which it is called. The method returns the node that has been removed from from the document, but you can reinsert it if you change your mind.

XPath XPath is a language for finding information in an XML document. XPath is used to navigate through elements and attributes in an XML document.XPath is a query language for XML documents much as SQL is for relational databases

XmlDocument mydoc = new XmlDocument();mydoc.Load(@"C:\Inetpub\wwwroot\example\books.xml");XmlNodeList mynodelist = mydoc.SelectNodes("/bookstore/book");XmlNodeList mynodelist2 = mydoc.SelectNodes("/bookstore/book/price/text()");XmlNodeList mynodelist3=mydoc.SelectNodes("/bookstore/book[price>35]/price");XmlNodeList mynodelist4=mydoc.SelectNodes("/bookstore/book[price>35]/title");

XSL – Extensible StyleSheet Language<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

XSL consists of three parts: XSLT (XSL Transformations) - a language for transforming XML documents XPath (XML Path Language)- a language for navigating in XML documents

Page 52: ASP.net_XML_Basics at a Glance

XSL-FO - a language for formatting XML documents To link XSL (Style sheet) to the XML Document add the code in the XML document:

<?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?>

The <xsl:template> Element The <xsl:template> element is used to build templates. Ex: <xsl:template match="/">The match attribute is used to associate a template with an XML element. (match="/" defines the whole document)

The <xsl:value-of> Element The <xsl:value-of> element can be used to extract the value of an XML element and add it to the output stream of the transformation.

<td> <xsl:value-of select="catalog/cd/title"/> </td> <td> <xsl:value-of select="catalog/cd/artist"/> </td>

Note: The value of the select attribute is an XPath expression. An XPath expression works like navigating a file system; where a forward slash (/) selects subdirectories.

The <xsl:for-each> Element The XSL <xsl:for-each> element can be used to select every XML element of a specified node-set.

<xsl:for-each select="catalog/cd"> <tr> <td> <td> </tr> </xsl:for-each>

We can even filter the records using a code like below, <xsl:for-each select="catalog/cd[artist='Bob Dylan']">

The <xsl:sort> Element To sort the output, simply add an <xsl:sort> element inside the <xsl:for-each> element in the XSL file.

<xsl:for-each select="catalog/cd"> <xsl:sort select="artist"/> </xsl:for-each>

The <xsl:if> Element To put a conditional if test against the content of the XML file, add an <xsl:if> element to the XSL document.

<xsl:for-each select="catalog/cd"> <xsl:if test="price &gt; 10"> </xsl:if> </xsl:for-each>

Page 53: ASP.net_XML_Basics at a Glance

The value of the required test attribute contains the expression to be evaluated.The code above will only output the title and artist elements of the CDs that has a price that is higher than 10.

The <xsl:choose> Element To insert a multiple conditional test against the XML file, add the <xsl:choose>, <xsl:when>, and <xsl:otherwise> elements to the XSL file <td> <xsl:value-of select="title"/> </td> <xsl:choose> <xsl:when test="price &gt; 10"> <td bgcolor="#ff00ff"> <xsl:value-of select="artist"/> </td> </xsl:when> <xsl:otherwise> <td> <xsl:value-of select="artist"/> </td> </xsl:otherwise> </xsl:choose>

Full XSL Document<?xml version="1.0" encoding="utf-8"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"><xsl:template match="/"> <html> <body> <h2>My CD Collection</h2> <table border="1"> <tr bgcolor="#9acd32"> <th align="left">Title</th> <th align="left">Artist</th> </tr> <xsl:for-each select="catalog/cd"> <xsl:sort select="artist"/> <tr> <td><xsl:value-of select="title"/></td> <td><xsl:value-of select="artist"/></td> </tr> </xsl:for-each> </table> </body> </html></xsl:template></xsl:stylesheet>

The <xsl:apply-templates> Element The <xsl:apply-templates> element applies a template to the current element or to the current element's child nodes.If we add a select attribute to the <xsl:apply-templates> element it will process only the child element that matches the value of the attribute. We can use the select attribute to specify the order in which the child nodes are processed.

Using JavaScript to do the transformation. By using a JavaScript, we can:

do browser-specific testing use different style sheets according to browser and user needs

Page 54: ASP.net_XML_Basics at a Glance

In aspx file:<body> <form id="form1" runat="server"> <script type="text/javascript"> // Load XML var xml = new ActiveXObject("Microsoft.XMLDOM") xml.async = false xml.load("cdcatalog.xml") // Load the XSL var xsl = new ActiveXObject("Microsoft.XMLDOM") xsl.async = false xsl.load("cdcatalog.xsl") // Transform document.write(xml.transformNode(xsl)) </script></body>