You are on page 1of 72

Deccansoft Software Services HTML Tags

Tag Name Code Example Browser View


<!-- comment <!--This can be viewed in the HTML part of a document--> Nothing will show
<A HREF="http://www.yourdomain.com/">Visit Our
<A - anchor Visit Our Site
Site</A>
<B> bold <B>Example</B> Example
<BIG> big (text) <BIG>Example</BIG> Example
body of
<BODY> HTML <BODY>The content of your HTML page</BODY> Contents of your web page
document
The contents of your web page
<BR> line break The contents of your page<BR>The contents of your page
The contents of your web page
<CENTER> center <CENTER>This will center your contents</CENTER> This will center your contents
<DL>
<DT>Definition Term Definition Term
definition <DD>Definition of the term Definition of the term
<DD>
description <DT>Definition Term Definition Term
<DD>Definition of the term Definition of the term
</DL>
<DL>
<DT>Definition Term Definition Term
definition <DD>Definition of the term Definition of the term
<DL>
list <DT>Definition Term Definition Term
<DD>Definition of the term Definition of the term
</DL>
<DL>
<DT>Definition Term Definition Term
definition <DD>Definition of the term Definition of the term
<DT>
term <DT>Definition Term Definition Term
<DD>Definition of the term Definition of the term
</DL>
This is an Example of using
<EM> emphasis This is an <EM>Example</EM> of using the emphasis tag
the emphasis tag
embed <EMBED src="yourfile.mid" width="100%" height="60"
<EMBED>
object align="center">

<EMBED src="yourfile.mid" autostart="true" hidden="false"


embed loop="false">
<EMBED>
object <noembed><bgsound src="yourfile.mid"
loop="1"></noembed> Music will begin playing when your
page is loaded and will only play
one time. A control panel will be
displayed to enable your visitors to
stop the music.
<FONT> font <FONT FACE="Times New Roman">Example</FONT> Example
<FONT FACE="Times New Roman"
<FONT> font
SIZE="4">Example</FONT> Example
<FONT FACE="Times New Roman" SIZE="+3"
<FONT> font
COLOR="#FF0000">Example</FONT> Example
Deccansoft Software Services HTML Tags

<FORM action="mailto:you@yourdomain.com"> Name:


Name: <INPUT name="Name" value="" size="10"><BR>
<FORM> form Email: <INPUT name="Email" value="" size="10"><BR> Email:
<CENTER><INPUT type="submit"></CENTER> Submit Query
</FORM>

<H1> heading 1 <H1>Heading 1 Example</H1>


Heading 1
Example
<H2> heading 2 <H2>Heading 2 Example</H2> Heading 2 Example
<H3> heading 3 <H3>Heading 3 Example</H3> Heading 3 Example
<H4> heading 4 <H4>Heading 4 Example</H4> Heading 4 Example

<H5> heading 5 <H5>Heading 5 Example</H5> Heading 5 Example


<H6> heading 6 <H6>Heading 6 Example</H6> Heading 6 Example

heading of
<HEAD>Contains elements describing the
<HEAD> HTML Nothing will show
document</HEAD>
document

horizontal Contents of your web page


<HR> <HR>
rule
Contents of your web page
Contents of your web page
horizontal
<HR> <HR WIDTH="50%" SIZE="3">
rule
Contents of your web page
Contents of your web page
horizontal
<HR> <HR WIDTH="50%" SIZE="3" NOSHADE>
rule
Contents of your web page
hypertext <HTML><HEAD><META><TITLE>Title of your web
<HTML> markup page</TITLE></HEAD><BODY>HTML web page Contents of your web page
language contents</BODY></HTML>
<I> italic <I>Example</I> Example
<IMG SRC="Earth.gif" WIDTH="41" HEIGHT="41"
<IMG> image
BORDER="0" ALT="a sentence about your web site">
Example 1:
Example 1:
<FORM METHOD=post ACTION="/cgi-bin/example.cgi">
<INPUT> input field
<INPUT type="text" size="10" maxlength="30"> Submit
<INPUT type="Submit" VALUE="Submit">
</FORM>
Example 3:

<FORM METHOD=post ACTION="/cgi-bin/example.cgi">


<TABLE BORDER="0" CELLSPACING="0" Example 3:
CELLPADDING="2"><TR><TD
<INPUT> input field
BGCOLOR="#8463FF"><INPUT type="text" size="10"
MAXLENGTH="30"></TD><TD BGCOLOR="#8463FF"
VALIGN="Middle"> <INPUT type="image" name="submit"
src="yourimage.gif"></TD></TR> </TABLE>
</FORM>
<INPUT> input field Example 4: Example 4:
Deccansoft Software Services HTML Tags

<FORM METHOD=post ACTION="/cgi-bin/example.cgi">


Enter Your Comments:<BR>
<TEXTAREA wrap="virtual" name="Comments" rows=3
cols=20 MAXLENGTH=100></TEXTAREA><BR>
<INPUT type="Submit" VALUE="Submit">
<INPUT type="Reset" VALUE="Clear">
</FORM> Submit Clear

Example 5:

<FORM METHOD=post ACTION="/cgi-bin/example.cgi">


<CENTER>
Select an option: Example 5:
<SELECT>
<OPTION >option 1 option 2
Select an option:
<INPUT> input field <OPTION SELECTED>option 2
<OPTION>option 3 Submit
<OPTION>option 4
<OPTION>option 5
<OPTION>option 6
</SELECT><BR>
<INPUT type="Submit" VALUE="Submit"></CENTER>
</FORM>
Example 6:
Example 6:
Select an option:
<FORM METHOD=post ACTION="/cgi-bin/example.cgi">
Select an option:<BR> Option 1
<INPUT type="radio" name="option"> Option 1 Option 2
<INPUT type="radio" name="option" CHECKED> Option 2
<INPUT type="radio" name="option"> Option 3 Option 3
<BR>
<INPUT> input field
<BR> Select an option:
Select an option:<BR>
<INPUT type="checkbox" name="selection"> Selection 1 Selection 1
<INPUT type="checkbox" name="selection" CHECKED>
Selection 2
Selection 2
<INPUT type="checkbox" name="selection"> Selection 3 Selection 3
<INPUT type="Submit" VALUE="Submit">
Submit
</FORM>

Example 1: Example 1:

<MENU> • List item 1


<LI type="disc">List item 1 o List item 2
<LI type="circle">List item 2 ƒ List item 3
<LI type="square">List item 3
</MENU>
<LI> list item
Example 2:
Example 2:

<OL type="i"> i. List item 1


<LI>List item 1 ii. List item 2
<LI>List item 2 iii. List item 3
<LI>List item 3 iv. List item 4
<LI>List item 4
Deccansoft Software Services HTML Tags

</OL>
Visit our <A
<LINK> link Visit our site
HREF="http://www.yourdomain.com/">site</A>
<MENU> • List item 1
<LI type="disc">List item 1 o List item 2
<MENU> menu <LI type="circle">List item 2 ƒ List item 3
<LI type="square">List item 3
</MENU>
<META name="Description" content="Description of your
site">
<META> meta Nothing will show
<META name="keywords" content="keywords describing
your site">
<META HTTP-EQUIV="Refresh"
<META> meta Nothing will show
CONTENT="4;URL=http://www.yourdomain.com/">
<META> meta <META http-equiv="Pragma" content="no-cache"> Nothing will show
<META> meta <META name="rating" content="General"> Nothing will show
<META> meta <META name="ROBOTS" content="ALL"> Nothing will show
<META NAME="ROBOTS"
<META> meta Nothing will show
content="NOINDEX,FOLLOW">
Numbered Numbered

<OL> 1. List item 1


<LI>List item 1 2. List item 2
<LI>List item 2 3. List item 3
<LI>List item 3 4. List item 4
<LI>List item 4
</OL>
Numbered Special Start
Numbered Special Start
5. List item 1
<OL start="5"> 6. List item 2
<LI>List item 1 7. List item 3
<LI>List item 2 8. List item 4
<LI>List item 3
<LI>List item 4 Lowercase Letters
</OL>
<OL> ordered list a. List item 1
Lowercase Letters b. List item 2
c. List item 3
<OL type="a"> d. List item 4
<LI>List item 1
<LI>List item 2 Capital Letters Special Start
<LI>List item 3
<LI>List item 4
C. List item 1
</OL>
D. List item 2
E. List item 3
F. List item 4
Capital Letters Special Start
Lowercase Roman Numerals
<OL type="A" start="3">
<LI>List item 1
<LI>List item 2 i. List item 1
<LI>List item 3 ii. List item 2
<LI>List item 4 iii. List item 3
Deccansoft Software Services HTML Tags

</OL> iv. List item 4

Lowercase Roman Numerals Capital Roman Numerals Special


Start
<OL type="i">
<LI>List item 1 VII. List item 1
<LI>List item 2 VIII. List item 2
<LI>List item 3 IX. List item 3
<LI>List item 4 X. List item 4
</OL>

Capital Roman Numerals Special Start

<OL type="I" start="7">


<LI>List item 1
<LI>List item 2
<LI>List item 3
<LI>List item 4
</OL>
<FORM METHOD=post ACTION="/cgi-bin/example.cgi">
<CENTER>
Select an option:
<SELECT>
<OPTION>option 1 Select an option:
listbox option 2
<OPTION> <OPTION SELECTED>option 2
option
<OPTION>option 3
<OPTION>option 4
</SELECT><BR>
</CENTER>
</FORM>
This is an example displaying the use of the paragraph tag. This is an example displaying the
<P> This will create a line break and a space between use of the paragraph tag.
lines.
This will create a line break and a
Example 1:<BR> space between lines.
<BR>
<P align="left"> Example 1:
This is an example<BR>
displaying the use<BR> This is an example
<P> paragraph of the paragraph tag.<BR> displaying the use
<BR> of the paragraph tag.
Example 2:<BR>
<BR> Example 2:
<P align="right">
This is an example<BR> This is an example
displaying the use<BR> displaying the use
of the paragraph tag.<BR> of the paragraph tag.
<BR>
Example 3:<BR>
<SMALL> small (text) <SMALL>Example</SMALL> Example

strong
<STRONG> <STRONG>Example</STRONG> Example
emphasis
Example 1: Example 1:
<TABLE> table
Column 1 Column 2
<TABLE BORDER="4" CELLPADDING="2"
Deccansoft Software Services HTML Tags

CELLSPACING="2" WIDTH="100%">
<TR>
<TD>Column 1</TD> Example 2:
<TD>Column 2</TD>
</TR>
</TABLE> Column 1 Column 2

Example 2: (Internet Explorer)


Example 3:
<TABLE BORDER="2" BORDERCOLOR="#336699"
CELLPADDING="2" CELLSPACING="2" WIDTH="100%">
<TR> Column 1 Column 2
<TD>Column 1</TD> Row 2 Row 2
<TD>Column 2</TD>
</TR>
</TABLE>

Example 3:

<TABLE CELLPADDING="2" CELLSPACING="2"


WIDTH="100%">
<TR>
<TD BGCOLOR="#CCCCCC">Column 1</TD>
<TD BGCOLOR="#CCCCCC">Column 2</TD>
</TR>
<TR>
<TD>Row 2</TD>
<TD>Row 2</TD>
</TR>
</TABLE>
<TABLE BORDER="2" CELLPADDING="2"
CELLSPACING="2" WIDTH="100%">
<TR>
<TD> table data <TD>Column 1</TD>
Column 1 Column 2
<TD>Column 2</TD>
</TR>
</TABLE>
<DIV align="center"><TABLE>
<TR>
<TH>Column 1</TH>
<TH>Column 2</TH>
<TH>Column 3</TH>
</TR>
<TR>
<TD>Row 2</TD>
<TD>Row 2</TD> Column 1 Column 2 Column 3
table <TD>Row 2</TD> Row 2 Row 2 Row 2
<TH>
header </TR> Row 3 Row 3 Row 3
<TR> Row 4 Row 4 Row 4
<TD>Row 3</TD>
<TD>Row 3</TD>
<TD>Row 3</TD>
</TR>
<TR>
<TD>Row 4</TD>
<TD>Row 4</TD>
<TD>Row 4</TD>
Deccansoft Software Services HTML Tags

</TR>
</TABLE>
</DIV>
document Title of your web page will be
<TITLE> <TITLE>Title of your HTML page</TITLE>
title viewable in the title bar.
<TABLE BORDER="2" CELLPADDING="2"
CELLSPACING="2" WIDTH="100%">
<TR>
<TR> table row <TD>Column 1</TD> Column 1 Column 2
<TD>Column 2</TD>
</TR>
</TABLE>
<TT> teletype <TT>Example</TT> Example
<U> underline <U>Example</U> Example
Example 1:<BR>
<BR> Example 1:
<UL>
<LI>List item 1 • List item 1
<LI>List item 2 • List item 2
</UL>
<BR>
unordered Example 2:<BR>
<UL> Example 2:
list <UL type="disc">
<LI>List item 1
<LI>List item 2 • List item 1
<UL type="circle"> • List item 2
<LI>List item 3 o List item 3
<LI>List item 4 o List item 4
</UL>
</UL>
Deccansoft Software Services Html / Javascript– Classroom
------------------------------------------------------------------------------------------------------------------------------------------
HTML Form Demo
<HTML>
<HEAD>
<TITLE>Form Demo</TITLE>
</HEAD>
<BODY BGCOLOR="yellow">
<FORM NAME="MyForm" ACTION="Next.html" METHOD="post">
Name: <INPUT TYPE="text" NAME="txtName"> <BR>
Password: <INPUT TYPE="password" NAME="txtPassword">
<BR>
Gender <BR>
<INPUT TYPE="radio" NAME="rbnGender" CHECKED> Male
<INPUT TYPE="radio" NAME="rbnGender">Female <BR>
Hobbies <BR>
<INPUT TYPE="checkbox" NAME="chkMusic" CHECKED>Music
<INPUT TYPE="checkbox" NAME="chkDance">Dance <BR>
Address:<br>
<TEXTAREA rows="4" columns="5"></TEXTAREA><BR>
How do you rate my site
<SELECT>
<OPTION>Good</OPTION>
<OPTION>Average</OPTION>
<OPTION>Poor</OPTION>
</SELECT><BR>
<INPUT TYPE="button" NAME="btnHello" VALUE="Hello">
<INPUT TYPE="reset" VALUE="Clear">
<INPUT TYPE="submit" VALUE="Submit">
</FORM>
</BODY>
</HTML>
Javascript For LOOP
<SCRIPT LANGUAGE="JavaScript">
for (var i=1;i<=10;i++)
{
if(i==4) continue;
if(i==7) break;
document.writeln(i);
}
</SCRIPT>
Select tag
<form name="Form1">
<select name="s1">
<SCRIPT LANGUAGE="Javascript">
for(i=1;i<=100;i++)
document.write("<option value=" + i + ">" + i + "</option>")
</script>
</select>
</form>
JavaScript Dialogs
<SCRIPT LANGUAGE="JavaScript">
document.writeln("<H1 ALIGN=center>This is Java Script</H1>");
window.alert("This is alert box");
alert(window.confirm("This is confirm box"));
var a,b;
a = window.prompt("Enter value of a","10");
b = window.prompt("Enter value of b","20");
var p,q;
p = parseInt(a);
q = parseInt(b);
var c;
c = p+q;
window.alert("Sum is " + c);

1
Deccansoft Software Services Html / Javascript– Classroom
</SCRIPT>

Validations Of Data
<html>
<head>
<title>Validations</title>
<script language="JavaScript">
function btnHit_Click()
{
window.alert("You have hit me");
}
function txtPassword_Focus()
{
var name=document.MyForm.txtName.value;
var len = name.length;
while (len == 0)
{
window.alert("Enter Name");
name = window.prompt("Enter Name","");
len = name.length;
document.MyForm.txtName.value=name;
}
}
function txtEmail_Change()
{
var email = document.MyForm.txtEmail.value;
var p1,p2,diff;
p1 = email.indexOf("@");
p2 = email.indexOf(".");
diff = p2 - p1;
if((p1== -1) || (p2 == -1) || (diff < 1))
window.alert("Not a valid Email");
}
</script>
</head>
<body>
<form name="MyForm">
Name: <input type="text" name="txtName"> <BR>
Password: <input TYPE="password" name="txtPassword" OnFocus="txtPassword_Focus()"><BR>
Email : <input type="text" name="txtEmail" OnChange="txtEmail_Change()">
<input type="submit" value="Submit">
<input type="reset" value="Clear">
<input type="button" name="btnHit" value="Hit Me" OnClick="btnHit_Click()">
</form>
</body>
</html>

2
Deccansoft Software Services Html / Javascript– Classroom
--------------------------------------------------------------------------------------------------------------------------------------------------------
<html>
<head>
<script language="javascript">
function div_Click()
{
if (document.forms[0].elements["n2"].value == 0)
{
alert('Value of denominator cannot be zero');
return false;
}
else
return true;
}
</script>
<body>
<form action="math.jsp" method="post">
N1 <input type=text name=n1><br>
N2 <input type=text name=n2><br>
<input type="submit" name="op" value="Add">
<input type="submit" name="op" value="Sub">
<input type="submit" name="op" value="Mul">
<input type="submit" name="op" value="Div" onClick="return div_Click()">
</form>
</body>
</html>

o Form tag cannot be nested inside another form tag.


o Input type’s button and reset and disabled elements name and value pair is not submitted to the server.
o Input type = button is used only for writing client side JavaScript code.
o Input type=checkbox submits name and value pair only if the checkbox is checked otherwise nothing is submitted. If
value is not provided the default value posted is “on”
o To group radio buttons, same name must be given to them. And only the name-value pair of the radio button selected
will be submitted to server.
o For select, name of select and value of the option selected is submitted to server.
o Select tag with size attribute is rendered as Listbox otherwise its rendered as DropDownList
o For Textarea, name of text area and value of textarea is submitted to server.
o Input type=image behaves as submit button where as <img> tag renders static image.
o A form can have more than one submit button, but only the name-value pair of the submit button used to post the
form is included with the request.
o If the form has input type=”file” then its enctype=”multipart/form-data” must be set.

3
Deccansoft Software Services – ASP.NET Web Programming Introduction
HTTP Protocol
• A Request is submitted to server using HTTP protocol
• HTTP Protocol is safe for internet type of scenario and is the default protocol used by the web browsers.
• HTTP is a stateless protocol. This is because it doesn’t know whether the request that has been made is part of an ongoing
correspondence or just a single message.
• HTTP is a W3C specification.
• HTTP communicates only in the String Format.

HTTP Request Structure(BrowserÆServer) HTTP Response Structure(ServerÆBrowser)


1. Request Line. 1. Status Line.
2. Request Header. 2. Response Headers.
3. Message Body (Posted Data). 3. Message Body.

Request Line: Method Path Protocol / Version


Example: Get/Post Demo/default.htm http / 1.1

Request Header: These are the name value pairs submitted by the browser to the server .It contains the information about the browser
and the OS on the client machine.

Message Body is the stream of name value pairs submitted to server when the form is submitted using the method POST.

CGI Environmental Variables: It’s a collection of name value pairs including request headers and information about the server in a
context of a given request.

<form name=”Form1” action=”demo.asp” method=”post” target=”frameName” enctype=””>


<input type=”…..
<input type=”submit” name=”s1” value=”Submit”>
</form>

When the form is submitted by clicking on the submit button it would submit the Name/ Value pair of every input elements in the form.

About Get and Post Methods:


GET Method:
1. All the name value pairs are submitted as a query string.
2. It’s not secured.
3. Length of the string is restricted.
4. This is the default method
5. If get method is used and if the page is refreshed it would not prompt before the request is submitted again.
POST Method:
1. Length of the string is not restricted in Post Method.
2. Post Method is secured.
3. Name-Value pairs cannot be seen in location bar of the web browser.
4. Use this method if the o/p rendered depends upon the posted data and varies based on the input provided.
5. If post method is used and if the page is refreshed it would prompt before the request is submitted again.

Status Line: Status Code / Description


1xx Informational
2xx Success
3xx Redirect
4xx Not Authorized / Not Authenticated.
5xx Server Error

o Every web server has a default directory and by default on IIS it is: c:\inetpub\wwwroot\
o From Browser: Http://servername(IP):PortNo/Directory/default.Html

What is ASP?

1
Deccansoft Software Services – ASP.NET Web Programming Introduction
• ASP is a server side scripting technology that enables scripts (embedded in web pages) to be executed by an Internet server
• An ASP file is just the same as an HTML file
• An ASP file can contain text, HTML, XML, and scripts
• Scripts in an ASP file are executed on the server
• An ASP file has the file extension ". asp"

How does it Work?

• When a browser requests an HTML file, the server just returns the file without doing any processing.
• When a browser requests an ASP file, IIS passes the request to the ASP engine (ASP.DLL) on the server
• The ASP engine reads the file, line by line, and executes the scripts in the file
• Finally, the output rendered is returned to the browser as plain HTML.

ASP Objects: Request, Response, Session, Application, Server, ObjectContext & AspError.

<%……%> It contains the server side code and the code is in VBScript. The code out side the delimiter is Client side code and is as it is
rendered to the client.

<% Response.Write(“hello”) %> or <%=”hello”%> are same.

Form Tag:
<form action=”URL” method=”Post”…>
<input name=”n1” type=”text/password/submit/reset/button/checkbox/radio/hidden/file/image” …>
<textarea name=”t1“></textarea>
<select name=”s1” …>
<option value=”v1”>t1</option>
<option value=”v2”>t2</option>
...
</select>
</form>
o Form tag cannot be nested inside another form tag.
o Input type’s button and reset and disabled elements name and value pair is not submitted to the server.
o Input type = button is used only for writing client side JavaScript code.
o Input type=checkbox submits name and value pair only if the checkbox is checked otherwise nothing is submitted. If value is
not provided the default value posted is “on”
o To group radio buttons, same name must be given to them. And only the name-value pair of the radio button selected will be
submitted to server.
o For select, name of select and value of the option selected is submitted to server.
o Input type=image behaves as submit button where as <img> tag renders static image.
o For Textarea, name of text area and value of textarea is submitted to server.
o Select tag with size attribute is rendered as Listbox.
o A form can have more than one submit button, but only the name-value pair of the submit button used to post the form is
included with the request.
o If the form has input type=”file” then its enctype=”multipart/form-data” must be set.

2
Deccansoft Software Services – ASP.NET Introduction and Architecture
ASP.NET is a framework for developing web based applications using MS.NET.

New in ASP .NET

ƒ Better language support


ƒ Programmable controls
ƒ Event-driven programming
ƒ XML-based components
ƒ User authentication, with accounts and roles
ƒ Higher scalability
ƒ Increased performance - Compiled code
ƒ Easier configuration and deployment
ƒ Not fully ASP compatible

ASP .NET Controls


ASP .NET contains a large set of HTML controls. Almost all HTML elements on a page can be defined as ASP .NET control
objects that can be controlled by scripts.
ASP .NET also contains a new set of object oriented input controls, like programmable list boxes and validation controls.
A new data grid control supports sorting, data paging, and everything you expect from a dataset control.

Event Aware Controls


All ASP .NET objects on a Web page can expose events that can be processed by ASP .NET code.
Load, Click and Change events handled by code makes coding much simpler and much better organized.

ASP .NET Components

ASP .NET components are heavily based on XML. Like the new AD Rotator, that uses XML to store advertisement
information and configuration

User Authentication
ASP .NET supports forms-based user authentication, including cookie management and automatic redirecting of unauthorized
logins.

User Accounts and Roles


ASP .NET allows for user accounts and roles, to give each user (with a given role) access to different server code and
executables.

High Scalability
Server to server communication has been greatly enhanced, making it possible to scale an application over several servers. One
example of this is the ability to run XML parsers, XSL transformations and even resource hungry session objects on other
servers.

Compiled Code
The first request for an ASP .NET page on the server will compile the ASP .NET code and keep a cached copy in memory. The
result of this is greatly increased performance.

Easy Configuration
Configuration of ASP .NET is done with plain text files.
Configuration files can be uploaded or changed while the application is running. No need to restart the server. No more
metabase or registry puzzle

Easy Deployment
No more server restart to deploy or replace compiled code. ASP .NET simply redirects all new requests to the new code.

Compatibility
ASP .NET is not fully compatible with earlier versions of ASP, so most of the old ASP code will need some changes to run
under ASP .NET.
To overcome this problem, ASP .NET uses a new file extension ".aspx". This will make ASP .NET applications able to run side
by side with standard ASP applications on the same server.

Creating a new ASP.NET application:

1
Deccansoft Software Services – ASP.NET Introduction and Architecture
o File Æ New Website
File System Æ It uses ASP.NET Development Server and for every web application a new instance of ASP.NET
Development Server Starts
HTTP Æ it uses IIS server.

Points to be noted / observed:


1. Every Webform has an extension “.aspx”
2. A Webform doesn’t have action attribute and it always submits to itself. Even if the action attributed is provided to the
Server side form it is ignored by the ASP.NET framework.
3. The default method rendered for the Webform in ASP.NET is “POST”
4. Here the UI is separated from the Business Code/ Event Handlers.
<%@ Page AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>.

AppDomain: An AppDomain is a logical connection of one or more thread with in a process. If a thread of one App domain
wants to access the thread of another app domain, it has to use inter-process communication (IPC). A process can have more
than one AppDomain and each AppDomain is independent of another AppDomain. If a thread in one AppDomain crashed, only
other threads of that AppDomain are affected and threads in other AppDomains would continue to run.

ASPNET_WP.EXE

App Domain

Life Cycle of a WebForm:


When the Web Server receives the request for the file with the extension .aspx, it forwards it to aspnet_isapi.dll which is an
ISAPI application executing within the web server process. This ISAPI application is then responsible for launching the
aspnet_wp.exe worker process.

In the Worker process a new AppDomain is created for every web application.
And for every Request a new thread is created in the AppDomain.

From. Default.aspx form a Compile form of


class is constructed and is + Default.aspx.cs
compiled.

Dynamic Class created


by ASP.NET framwork

Compiled Persisted Executed and Output is rendered


to the browser
Note: From second request onwards the framework uses the persisted form for executing the request.

ASP.NET now
1. Creates an instance of the WebForm class
Note: For every trip made to the server i.e. for first request or even if the form is submitted the new instance the page class is
created.
Note: When the web form class is instantiated, the controls of the class are not yet created or instantiated hence the constructor
of web form cannot be used for setting or getting control properties.

2
Deccansoft Software Services – ASP.NET Introduction and Architecture

2. Based on the server side tags (runat=”server”) the controls are instanced and based on tag attributes the control properties
are set.

Server TagÆ Server Object Æ Client Tag


<asp: TextBox Æ Instance of Textbox Æ <input type = “text” …>

Attributes Æ Properties Æ Attribute for client tag.


Text = “Attribute” Value = “Attribute”

So the final output rendered for


<asp:TextBox runat=”server” id=”TextBox1” Text=”Demo”/>
is
<input type=”text” name=”TextBox1” id=”TextBox1” value=”Demo”>

Note: All the Objects created (for controls and page) are ready for garbage collection once the response of the page is rendered
to be web browser i.e. for every request new objects are created.

public partial class _Default : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
TextBox1.Text = "Load";
}
protected void Page_Init(object sender, EventArgs e)
{
TextBox1.Text = "Init";
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.ForeColor = System.Drawing.Color.Red;
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Response.Write("TextChanged");
}
protected void Button2_Click(object sender, EventArgs e)
{
}
}
Instance of class is created
and constructor is executed Æ Init Æ ------------------------------ Æ Load -- -- control events Æ PreRender

On Post Back, the control uses the name-value pair (on its behalf)
submitted (new state) by the browser and __VIEWSTATE (Old State)
and sets its state (restores its state as it was before rendering the page in previous
response).

• Any type of initialization of the control must be done in Load (and preferably in if (!IsPostBack) ). It is not recommended
to set or get control properties in Init event handler of Page because only after init event of page the control is said to be
completely initialized.
• When the page is rendered, every control adds its current state to the hidden element “__VIEWSTATE”. For a response
there is only one VIEWSTATE rendered in which all the controls add their current state.
• When the form is submitted after Init and before Load event, the control uses the data in the hidden element
“__VIEWSTATE” and restores its complete state.

Note: For the explanation of the above feature take an example of ForeColor Property of TextBox.

EnableViewState=False
On a round trip we are not rendering the output of the same page / webform, the EnableViewState Property of the controls on
the page can be set to false. But if done so any change in state of the control during the page life cycle is not added to the hidden
element __VIEWSTATE and thus if round trip is made page the old state is not restored.
3
Deccansoft Software Services – ASP.NET Introduction and Architecture
For raising events: When the form is posted every control compares its name values pair submitted with the old state in
__VIEWSTATE. If it’s different the control raises an appropriate event on the server.

AutoPostBack=true, it renders the required java script to browser to programmatically post the form to the server i.e. a
javascript function “__doPostBack()” is rendered and the same is mapped to its client side event of the control.

Event Handling in WebForms


<%@ Page AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>

AutoEventWireup is set to true the events of page class are mapped to the event handlers based on the name of the event
handler method i.e. (Page_ <eventname>(. . .)

o In C# preferable AutoEventWireup should be set to “true”.


o In C# for event handlers of page class we can override the approximate method of the parent class i.e. instead of writing
Page_Load method as event handler we can also override OnLoad method in the class.
o AutoEventWireup is not used for anything other than Page Events.

Note: Either if an event of the control is handled or if a roundtrip to server renders the output of the same WebForm
“EnableViewState” property of the control must not be set to false.

The Events of the controls will fire only after the load event of the page, but the decision to raise the event or not is taken after
“Init” and before “Load” event of the page.

Writing Custom Classes in WebApplication


All the classes must be placed under the folder App_Code (this folder must be created in root directory of the web application).
/Appname/App_Code/Demo.vb
The classes under the folder App_Code are all dynamically compiled at run time and can be used in any Webform of the Web
application (irrespective of the language it is coded in).

To use more than one programming language in same WebApplication:


/Appname/App_Code/CSFiles/Demo.cs
/Appname/App_Code/VBFiles/Demo.vb

Right click on Project Æ Add New ItemÆWeb Configuration File.


To make the compiler know that VB code and C# code has to compiled using appropriate compilers write the following in
web.config:
<system.web>
<compilation debug="true">
<codeSubDirectories>
<add directoryName=”VBFiles”/>
<add directoryName=”CSFiles”/>
</codeSubDirectories>
</compilation>
<system.web>
Comparison between Response.Redirect and Server.Transfer.

page1.aspx

Page1.aspx Page1.aspx

Request Redirect (“page2.aspx”) Server Transfer(“page2.aspx”)

Page2.aspx

Page2.aspx

o Server.Transfer can be used only for switching from one web form to another web form of the same application and it
retains the context in which the actually requested webform is executing.

4
Deccansoft Software Services – ASP.NET Introduction and Architecture
o Redirect submits the response to the browser asking browser to send a request for the new url and thus all the context of the
previous request is lost when the new url is executing.
o Redirect can be used for switching from one a webform of one webapplication to a webform in another webapplication.
o On refresh, If Redirect is used it will send the request for the new page whereas if Transfer is used browser submits the
request for original page.

5
Deccansoft Software Services – ASP.NET Basic Controls

Types of Server Controls:


1. HTML Server Controls - Traditional HTML tags - System.Web.UI.HtmlControls
2. Web Server Controls - ASP.NET Controls – System.Web.UI.WebControls

HTML Controls are by default treated as text in ASP.NET. To make these elements programmable add runat="server" attribute
to the HTML elements. This attribute indicates that the element should be treated as a server control. The “id” attribute is added
to identify the server control. The id reference can be used to manipulate the server control at run time.

Web Server Controls: Web server controls are special ASP.NET tags understood by the ASP.NET server.

Like HTML server controls, Web server controls are also created on the server and they require a runat="server" attribute to
work. However, Web server controls do not necessarily map to any existing HTML elements and they may represent more
complex elements.

Label: Renders SPAN tag to the client.


Properties: Text

Textbox: Can render either <input type=”text” or <input type=”password” or <textarea> tags
Properties: Text, TextMode (SingleLine/MultiLine/Password), ReadOnly, MaxLength, AutoPostBack, AutoCompleteType
Event: TextChanged

Button: Can render either <input type=”button” or <input type=”submit”…


Properties: Text, OnClientClick, UseSubmitBehavior, CommandName, CommandArgument, CausesValidation.
Events: Click, Command
//Add the following <script> block to “<HEAD>” section of aspx page.
<script language=”javascript” type=”text/javascript”>
function CanSubmit()
{
return confirm(“Are You Sure?”); //Confirm shows a dialog box with OK and Cancel Button.
}
</script>

<asp:Button onClientClick=”return CanSubmit()” UseSubmitBehavior=”true” …./>


Renders <input type=”submit”….>

<asp:Button onClientClick=”if (!CanSubmit()) return;” UseSubmitBehavior=”false” …./>


Renders <input type=”button”….>

Note: In Javascript if OnClick of Submit Button return false, the form is not submitted to server.
Examlpe:
<asp:Button ID="btn1 " runat="server" OnClick="btn _Click" Text="Button1" OnCommand="btn_Command"
CommandName="C1" />
<asp:Button ID="btn2 " runat="server" OnClick="btn _Click" Text="Button2" OnCommand="btn_Command"
CommandName="C2" />
<asp:Button ID="btn3 " runat="server" OnClick="btn _Click" Text="Button3" OnCommand="btn_Command"
CommandName="C3" />
Note: All the button “Click” and “Command” events are mapped to the same Event Handlers.

protected void btn _Click(object sender, EventArgs e)


{
Button btn = (Button) sender; //sender is reference to the control on which we have clicked.
Response.Write(btn.Text);
}
protected void btn _Command(object sender, CommandEventArgs e)
{
Response.Write(e.CommandName);
}

LinkButton: renders <A href=”__doPostBack(…)” …> -Used for posting the form to server.
Properties: Text, OnClientClick, CommandName, CommandArgument, CausesValidation.
Events: Click, Command

1
Deccansoft Software Services – ASP.NET Basic Controls

ImageButton: renders <input type=”image” …>


Properties: Text, ImageUrl, OnClientClick, CommandName, CommandArgument, CausesValidation.
Events: Click, Command

HyperLink: <A href=”Url”… - Used for linking to another page of the webapplication and not posting the form.
Properties: Text, ImageUrl, NavigateUrl, Target, OnClientClick

CheckBox: renders <input type=”Checkbox” …


Properties: Text, Checked
Event: Click

RadioButton: renders <input type=”radio” . Its inherited from CheckBox class.


Properties: Text, Checked, GroupName (must be same for grouping the radio buttons)
Event: Click

ListControl: It’s a common parent for DropDownList, ListBox, CheckBoxList, RadioButtonList, BulletedList
Properties: Items, SelectedIndex, SelectedItem, SelectedValue, Text, AppendDataBoundItems, DataText, AutoPostBack
Methods: ClearSelection
Event: SelectedIndexChanged

ListItem: renders based on container tag in which it is used.


Properties: Text, Value, Selected

DropDownList: renders <select tag

ListBox: renders <select size=”x” …


Properties: Rows (maps to size attribute), SelectionMode (Single / Multiple)
Method: GetSelectedIndices() as Integer()

CheckboxList: renders <input type=”checkbox”… for every ListItem


Properties: RepeatColumns, RepeatDirection, RepeatLayout

RadioButtonList: renders <input type=”radio” … for every ListItem


Properties: RepeatColumns, RepeatDirection, RepeatLayout

Example:
<asp:CheckBoxList ID="lst" runat="server" RepeatColumns="3" RepeatDirection="Horizontal"
AutoPostBack="True" OnSelectedIndexChanged="lst_SelectedIndexChanged"/>
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
for (int i = 0; i < 10; i++)
{
ListItem li = new ListItem();
li.Text = "Item" + i; //Displayed for every item
li.Value = i.ToString(); //Submitted if this item is selected
lst.Items.Add(li);
}
}
}
protected void lst_SelectedIndexChanged(object sender, EventArgs e)
{
//Response.Write(lst.SelectedValue); // For Single Selected
//Form multiple items selected
string str = "";
foreach (ListItem li in lst.Items)
{
if (li.Selected)
str += li.Value + " ";
}
Response.Write(str);

2
Deccansoft Software Services – ASP.NET Basic Controls

}
Literal Control: renders just text without any tag
Properties: Text

FileUpload: reders <input type=”file” ….>


<form……enctype =”multipart /form data”>
When the Form with Fileupload control is rendered, the enctype attribute is automatically added to the rendered client side form
tag.
if (FileUpload1.HasFile)
{
string pp = MapPath("~/UploadedFiles/" + FileUpload1.FileName);
//For a given Virtual Path, MapPath return Physical Path.
if (System.IO.File.Exists(pp))
{
Response.Write("Already exiting...");
return;
}
FileUpload1.SaveAs(pp);
Response.Write("Uploaded...");
//byte[] b=FileUpload1.Filebytes;
//System.IO.Stream s=FileUpload1.FileContent;
}
Fileupload control doesnot retain its state on roundtrip.

Calander:
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
Response.Write(Calendar1.SelectedDate.ToShortDateString());
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.IsWeekend)
e.Day.IsSelectable = false;
if (e.Day.Date.DayOfWeek == DayOfWeek.Thursday)
e.Cell.BackColor = System.Drawing.Color.Red;
}
protected void Calendar1_VisibleMonthChanged(object sender, MonthChangedEventArgs e)
{
Calendar1.SelectedDate = new DateTime(e.NewDate.Year, e.NewDate.Month, Calendar1.SelectedDate.Day);
}

3
Deccansoft Software Services – ASP.NET Basic Controls

For chkMultiple set AutoPostBack to True


if (rbnMove.Checked )
lst2.Items.RemoveAt(lst2.SelectedIndex);
}
protected void btnMoveAllRight_Click(. . .)
{
if (chkMultiple.Checked)
{

}
else
{
foreach (ListItem item in lst1.Items)
lst2.Items.Add(lst1.SelectedValue);
if (rbnMove.Checked)
lst1.Items.Clear()
}
}
protected void btnMoveAllLeft_Click(. . .)
{
protected void btnAdd_Click(. . .) if (chkMultiple.Checked)
{ {
if (rbnList1.Checked)
lst1.Items.Add(txtName.Text); }
else if (rbnList2.Checked) else
lst2.Items.Add(txtName.Text); {
} foreach (ListItem item in lst2.Items)
protected void btnDelete_Click(. . .) lst1.Items.Add(lst2.SelectedValue);
{ if (rbnMove.Checked)
if (rbnList1.Checked) lst2.Items.Clear()
lst1.Items.RemoveAt(lst1.SelectedIndex); }
else if (rbnList2.Checked) }
lst2.Items.RemoveAt(lst2.SelectedIndex); protected void chkMultiple_CheckedChanged(. . .)
} {
protected void btnModify_Click(. . .) if (chkMultiple.Checked )
{ {
if (rbnList1.Checked) btnMoveLeft.Visible = false;
lst1.SelectedItem.Text = txtName.Text; btnMoveRight. Visible = false;
else if (rbnList2.Checked ) lst1. SelectionMode = ListSelectionMode.Multiple;
lst2.SelectedItem.Text = txtName.Text; lst2. SelectionMode = ListSelectionMode.Multiple;
} }
protected void btnRemoveAll_Click(. . .) else
{ {
if (rbnList1.Checked) btnMoveLeft. Visible = true;
lst1.Items.Clear(); btnMoveRight. Visible = true;
else if (rbnList2.Checked ) lst1.SelectionMode = ListSelectionMode.Single;
lst2.Items.Clear(); lst2.SelectionMode = ListSelectionMode.Single;
} }
protected void btnMoveRight_Click(. . .) }
{ If Multiple is Checked then btnMoveRight and btnMoveLeft
txtName.Text = lst1.SelectedItem.Text; should be hidden and when btnMoveAllRight is clicked all
ListItem li = new ListItem(); the selected items in the List1 should be Copied / Moved to
li.Text = txtName.Text; List2. Similarly if btnMoveAllLeft is clicked then all the
lst2.Items.Add(li); selected items in the List2 should be copied / moved to List1
if (rbnMove.Checked )
lst1.Items.RemoveAt(lst1.SelectedIndex); If Multiple is Un-Checked then btnMoveRight and
} btnMoveLeft should be Visible and when btnMoveAllRight
protected void btnMoveLeft_Click(. . .) is clicked all the items in the List1 should be Copied /
{ Moved to List2. Similarly if btnMoveAllLeft is clicked then
txtName.Text = lst2.SelectedItem.Text; all items in the List2 should be copied / moved to List1. If
ListItem li = new ListItem(); btnMoveRight is clicked then copy / move the selected item
li.Text = txtName.Text; from List1 to List2 and if btnMoveLeft is clicked then
lst1.Items.Add(li); copy/move selected item in List2 to List1
4
Deccansoft Software Services – ASP.NET Validation Controls

• With one Server Control we can have more than one validation control associated but the same validation control cannot be
associated with multiple server controls.

BaseValidator: It is the parent of all the validation controls.


Validation Controls inherited from BaseValidator control are,
RequiredFieldValidator, RangeValidator, CompareValidator, RegularExpressionValidator, CustomValidator.

Properties of BaseValidator:
ControlToValidate, ErrorMessage, Text, Display (Static/Dynamic/None), SetFocusOnError, ToolTip, EnableClientScript
,ValidationGroup

ValidationSummary: Is used to display the collection of error message on the page at a given location. It shows the ErrorMessage
poperty of all the controls whose validation has failed.
Properties: ShowMessageBox, ShowSummary:

Sample:
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />

RequiredField Validator: To ensure that the user does not skip an entry and is used for every control in asp.net.
Properties: InitialValue

Sample:
First Name<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvFirstName " runat="server"
ErrorMessage="Please provide the value for First Name" ControlToValidate="txtFirstName"
SetFocusOnError="True">
Text= “Required”
</asp:RequiredFieldValidator>

Last Name<asp:TextBox ID="txtLastName" runat="server" Text= “Not Applicable “></asp:TextBox>


<asp:RequiredFieldValidator ID="rfvLastName " runat="server"
ErrorMessage="Please provide the value for Last Name" ControlToValidate="txtLastName"
InitialValue=”Not Applicable”
SetFocusOnError="True"
Text= “Required”/>
</asp:RequiredFieldValidator>

<asp:DropDownList ID="ddl" runat="server">


<asp:ListItem Value="-1">(Select One)</asp:ListItem>
<asp:ListItem Value="1">One</asp:ListItem>
<asp:ListItem Value="2">Two</asp:ListItem>
<asp:ListItem Value="3">Three</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvDDl" runat="server" ControlToValidate="ddl"
ErrorMessage="Please select a value in ddl" InitialValue="-1">*</asp:RequiredFieldValidator>

CompareValidator: Compares a user’s entry against a constant value, against the value of another control.
Property: ValueToCompare, ControlToCompare, Type, Operator

Sample:
Password: <asp:TextBox ID="txtPassword"runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvPassword" runat="server"
ControlToValidate="txtPassword"
Display="Dynamic"
ErrorMessage="Please provide the value for Password">
1
Deccansoft Software Services – ASP.NET Validation Controls

Text=”Required”
</asp:RequiredFieldValidator>

Confirm Password<asp:TextBox ID="txtConfirmPassword"runat="server">


</asp:TextBox>
<asp:CompareValidator ID="cvConfirmPassword" runat="server"
ControlToCompare="txtPassword"
ControlToValidate="txtConfirmPassword"
Display="Dynamic"
ErrorMessage="The Password and Confirm Passoword must be same">
Text=”Must be same as Password”
Operator=”Equal”
</asp:CompareValidator><br />

Date of Birth: <asp:TextBox ID="txtDOB" runat="server"></asp:TextBox>


<asp:CompareValidator ID="cvDob" runat="server"
ControlToValidate="txtDob"
ErrorMessage="Please provide a valid DOB"
Operator="DataTypeCheck" ‘This only does Datatype check and not value comparision.
Type="Date">
Text=”Invalid Date Format”
</asp:CompareValidator><br />

RangeValidator: Checks that a users entry is between lower and upper boundaries.
Properties: MinimumValue, MaximumValue, Type

Sample:
Value <asp:TextBox ID="txtValue" runat="server"></asp:TextBox>
<asp:RangeValidator ID="rvValue" runat="server"
ControlToValidate="txtValue"
ErrorMessage="Please provide the value in range of 1 to 100"
MaximumValue="100"
MinimumValue="1"
Type="Integer">
Text=”Valid Range: 1 – 100”
</asp:RangeValidator><br />

RegularExpressionValidator: It Checks the users entry matches a pattern defined by a regularexpression.


Properties: ValidationExpression

Sample:
Email<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="revtxtEmail" runat="server"
ControlToValidate="txtEmail"
ErrorMessage="Please provide a valid e-mail id"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([- .]\w+)*">
Text=”Invalid e-mail id”
</asp:RegularExpressionValidator>

Custom Validator: Checks the user's entry using validation logic that you write yourself.
Properties: ClientValidationFunction
Sample:
<head>
<script language=”javascript”>
function IsOdd(src,args) //src is reference to ValidationControl.

2
Deccansoft Software Services – ASP.NET Validation Controls

{
if (args.Value % 2 == 0)
{
args.IsValid = false;
src.errormessage = args.Value + " is not an odd number"
}
</script>
</head>

OddValue: <asp:TextBox ID="txtOddValue" runat="server"></asp:TextBox>


<asp:CustomValidator ID="cvOddValue" runat="server"
ErrorMessage="Please provide an Odd number"
ClientValidationFunction="IsOdd"
ControlToValidate="txtOddValue">
</asp:CustomValidator><br />

Additional Features

Button Controls:
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click" />
<asp:Button ID="btnCancel" runat="server" Text="Cancel" CausesValidation="False" /><br />
If Cancel button is clicked the form is submitted to server with out doing any client side validation.

In one webform (aspx page) we can have only one server side form tag.
ValidationGroup Property: Is used to group all the validation control into a single group. A form can have more than one group of
controls and based on the group of the button clicked, only controls in given group are validated.
Example:
<asp:ValidationSummary ID="ValidationSummary2" runat="server" ValidationGroup="g1"/>
Name: <asp:TextBox ID="txtName" runat="server" ValidationGroup="g1"/ >
<asp:RequiredFieldValidator ID="rfvName" runat="server"
ControlToValidate="txtName" ErrorMessage="Please provide the value for txtName"
ValidationGroup="g1"/>
<asp:Button ID="btnSave" runat="server" Text="Save" ValidationGroup="g1" />

Misc Topics
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Page.Validate("");//Validates all the validation controls on the page
ValidationSummary1.Style["display"] = "none";
//It does not display the ErrorMessages for the first time.
}
else
{
ValidationSummary1.Style["display"] = "";
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (!Page.IsValid) //validation is done on server-side, This is needed if the browser doesn’t support javascript.
return;
//Write here code for taking data from controls and using for what ever purpose it might be for.
Response.Write("Saved...");
}
• Page.Validators - It’s a collection of all validators in that page.
• We can disable the validation control if we don’t want them to work on both client and server side (Enabled = False)

3
Deccansoft Software Services – ASP.NET Validation Controls

• The Server Controls which can be validated using Validation Controls are TextBox, FileUpload, DropDownList,ListBox etc…i.e.
not all Server controls can be validated using Validation Controls.

4
Deccansoft Software Services – ASP.NET CrossPostBack
By Default every WebForm Posts the form to itself but if Buton’s PostBackUrl is set to a Url of another page then the Form is
Posted to that Url instead of itself.

Page1.aspx
<asp:Label ID="lblDemo" runat="server"></asp:Label>
<asp:TextBox ID="txtDemo" runat="server"></asp:TextBox><br />
<asp:Button ID="btnPostBack" runat="server" OnClick="btnPostBack_Click" Text="PostBack" />
<asp:Button ID="btnCrossPostBack" runat="server" OnClick="btnCrossPostBack_Click"
PostBackUrl="~/CrossPostBack/Page2.aspx" Text="Cross Post Back" />

Page1.aspx.cs
public partial class CrossPostBack_Page1 : System.Web.UI.Page
{
protected void btnPostBack_Click(object sender, EventArgs e)
{
lblDemo.Text = txtDemo.Text;
}
public string DemoText
{
get
{
return txtDemo.Text;
}
}
}

Page2.aspx:
<%@PreviousPageType VirtualPath=”CrossPostBackDemo/Page1.aspx”%>

And the following Label to the WebForm.


<asp:Label ID="lblDemo" runat="server"></asp:Label>

Page2.aspx.cs
public partial class CrossPostBack_Page2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage == null) //Its true if a user is directly coming to this page.
Response.Redirect("Page1.aspx");
TextBox pptxtDemo = (TextBox)PreviousPage.FindControl("txtDemo");
if (pptxtDemo != null)
lblDemo.Text = pptxtDemo.Text;
//Or You can access the public property of previous page (DemoText)
if (PreviousPage.IsCrossPagePostBack)
{
Response.Write("<br>This is CrossPostBack<br>");
lblDemo1.Text = PreviousPage.DemoText; //DemoText is the property added to the class Page1
}
else
Response.Write("<br>This is Server.Transfer<br>");
}
}

<%@PreviouspageType VirtualPath=”CrossPostBackDemo/Page1.aspx”%>
• If the above directive is not used then the datatype of the property this.PreviousPage is “System.Web.UI.Page” but if this
directive is present in “Page2.aspx” then the datatype of “this.PreviousPage” would be the dynamic class inherited from
“Page2”.
• After adding this directive to Page2.aspx, we can access the public properties declared in the class Page1 of “Page1.aspx.cs”
file. This can be done using “PreviousPage” property of “Page” class. Example: PreviousPage.DemoText
• Once the above directive is used only from Page1.aspx we can come to Page2.aspx.
Additional Notes:
• Page.IsCrossPostBack is always false.
• PreviousPage.IsCrossPostBack is true if it is CrossPostback is used and false if it is Server.Transfer is used.

1
Deccansoft Software Services – ASP.NET MasterPages & UserControls

MasterPage:
• The extension of MasterPage is ‘.master’.
• MasterPage cannot be directly invoked from the client because it just acts as a template for the other Content Pages.
• In a MasterPage we can have content either inside ContentPlaceHolder or outside ContentPlaceHolder. Only content inside of
ContentPlaceHolder can be customized in the child pages
• We can have multiple masters in one web application.
• A MasterPage can have a MasterPage but studio does not support at design time so the customization of it has to be done in
Html view only.
• The child page content can be placed only in content tag.
• Controls of MasterPage will be programmed in the MasterPage and child page but child page control will never be
programmed in MasterPage.
• A master page of one web application cannot be used in another web application.
• The MasterPageFile property of a webform can be set dynamically but it should be done either in or before the Page_PreInit
event of the WebForm. Page.MasterPageFile= ”…./MasterPage.master”.
• The order of execution of events Load (Page) Æ Load (Master) Æ LoadComplete (Master) i.e if we want to overwrite a
control property of a control already set in master page then we must do that in the LoadComplete event of the page.

Example:
Adding a MasterPage to the Project
1. Create a folder MasterPageDemo.
2. Add to it a new MasterPage file (MainMaster.master)
3. Add to it the controls / content as mentioned below.

Step 1: MainMaster.master
<form id="form1" runat="server">
Header...
<br /><asp:Label ID="lblMaster"runat="server"Text="Label"></asp:Label>
<br />
<asp:ContentPlaceHolder id="cphFirst" runat="server">
Text=” This is First Content Place Holder(Default)”
</asp:contentplaceholder>
<br />
<asp:ContentPlaceHolder ID="cphSecond" runat="server">
This is Second Content Place Holder(Default)
<br /><br />
<asp:Label ID="lblContent" runat="server" Text="Label"></asp:Label>
<asp:TextBox ID="txtContent" runat="server"></asp:TextBox>
<asp:Button ID="btnContent"runat="server" OnClick="btnContent_Click" Text="Master Page"/>
</asp:ContentPlaceHolder>
<br /> Footer...
</form>

Step 2: Code Page (MainMaster.master.cs)


protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Load - MasterPage<br>");
if (!IsPostBack)
lblMaster.Text = "MASTER";
}
protected void btnContent_Click(object sender, EventArgs e)
{
lblContent.Text = txtContent.Text;
}
public Label MasterLabel
{
get
{
return lblMaster;
}
}
Step 3: Adding Child Page and Linking to master.
Add a New WebForm (Default.aspx) (Check MasterPage Checkbox)

1
Deccansoft Software Services – ASP.NET MasterPages & UserControls

Step 4: Default.aspx
RightClick on 2nd ContentPlaceHolder and select Create Custom Content and make the required changes.

<%@ Page Language="C#" MasterPageFile="MainMaster.master" AutoEventWireup="true" CodeFile="Default.aspx.cs"


Inherits="MasterPagesDemo_Default" Title="Child Page" %>

Note: If MasterPage is selected for a child page “MasterPageFile” attribute is added to the Page Directive of the Child page

<%@ MasterType VirtualPath="~/MasterPagesDemo/MainMaster.master" %>


<asp:Content ID="Content1" runat="server" ContentPlaceHolderID="cphFirst">
Text=”First Content Page...” <br />
<asp:TextBox ID="txtChildPage" runat="server"></asp:TextBox>
<asp:Button ID="btnChildPage"runat="server" Text="ChildPage" OnClick="btnChildPage_Click/>
</asp:Content>

Step 4: To default.aspx add the following code.


protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Load - Child Page<br>");
}
protected void Page_LoadComplete(object sender,EventArgs e)
{
Response.Write("Load Complete- Child Page<br>");
}
protected void btnChildPage_Click(object sender,EventArgs e)
{
//Get reference to Label control (lblMaster) in the master page.
Label lblMaster = (Label)Master.FindControl("lblMaster");
lblMaster.Text = txtChildPage.Text;

//Setting label text via master page property i.e MasterLabel


Master.MasterLabel.Text = txtChildPage.Text ;
//The above line would work only if <%@MasterPage Directive is added to current page

//Accessing control in ContentPlaceholder of Master page.


Label lblContent = (Label) Master.FindControl("cphSecond").FindControl("lblContent");
lblContent.Text = txtChildPage.Text;
}
Working with UserControls
Overview of UserControls:
• They have the extension - .ascx
• The ascx file has a Control Directive and the class is Inherited from “System.Web.UI.UserControl”
• For customizing the UserControl Public properties must be added to it. These public properties in most of the
circumstances wrap around the control which is added to the UserControl.
• User control does not have design time facility when used in a WebForm.
• The Properties of the usercontrol can be set by setting the attributes for the tag used in WebForm.
Sample:
1. Create a folder UserControlDemo.
2. Add WebUserControl (HelloControl.ascx)
3. Add to it the controls as mentioned below in the ascx file.

Step 1: HelloControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="HelloControl.ascx.cs"
Inherits="UserControlDemo_HelloControl" %>

<asp:Label ID="lblCaption" runat="server" Text="Name:"></asp:Label>


<asp:TextBox ID="txtFirstName" runat="server" OnTextChanged="NameChanged"/>
<asp:TextBox ID="txtLastName" runat="server" OnTextChanged="NameChanged"/>
<input id="btnSayHello" type="button" value="Say Hello" onclick="return
btnSayHello_onclick(<%= txtFirstName.ClientID %>,<%= txtLastName.ClientID %>)" />

2
Deccansoft Software Services – ASP.NET MasterPages & UserControls

Step 2: HelloControls.acsx.cs: To this file add the following code.


public partial class UserControlDemo_HelloControl : System.Web.UI.UserControl
{
//This event is raised when either FirstName or LastName is changed.
public event EventHandler RealNameChanged;
protected void Page_Load(object sender, EventArgs e)
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "k1",
" function btnSayHello_onclick(fn,ln)\n" +
" {\n" +
" alert(fn.value + \" \" + ln.value) \n" +
" }\n"
, true);
}
public string RealName
{
get {
return txtFirstName.Text + " " + txtLastName.Text;
}
set {
txtFirstName.Text = value.Split(' ')[0];
txtLastName.Text = value.Split(' ')[1];
}
}
//The Following property is used in the webform to set the Text of Label.
public string Caption
{
get {
return lblCaption.Text;
}
set {
lblCaption.Text = value;
}
}
//Following method acts as a event handler for TextChanged event of both txtFirstName and txtLastName textboxes.
bool eventRaised;
protected void NameChanged(object sender, EventArgs e)
{
if (!eventRaised) //If the event is not raised then raise the event.
{
//Following code is used for raising the event RealNameChanged.
if (RealNameChanged != null)
RealNameChanged(this, EventArgs.Empty); /
eventRaised = true;
}
}
}

Step 3: Add a WebForm to the Application - Default.aspx


Step 4: Drag-Drop Hello UserControl on the webform.
<%@ Register Src="HelloControl.ascx" TagName="HelloControl" TagPrefix="uc1" %>

Step 5: Add a Button to the webform.

Step 6: <uc1:HelloControl ID="hcName" runat="server" Caption=”Your Name”


RealName="Test Test" OnRealNameChanged="txtName_RealNameChanged" />

<uc1:HelloControl ID="hcFathersName" runat="server" RealName="Z Y" Caption="Fathers Name" />

<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />

Step 7: protected void btnSubmit_Click(object sender, EventArgs e)


{
3
Deccansoft Software Services – ASP.NET MasterPages & UserControls

Response.Write(hcName.RealName);
Response.Write("<br>" + hcFathersName.RealName);
}
//Handles the RealNameChnaged event raised by the UserControl.
protected void txtName_RealNameChanged(object sender,EventArgs e)
{
Response.Write("Name Changed");
}

4
Deccansoft Software Services State Management Techniques

Static / Shared member in WebForm Class


• It can used for Sharing data between requests by any user but its scope is local to the WebForm in which it is declared.
public partial class Default : System.Web.UI.Page In this example the value of InstanceConter is
{ always “1” because with every request a new
public static int SharedCounter; instance of the webform is created and
public int InstanceCounter; InstanceCounter always by default gets intialized to
protected void Page_Load(object sender, EventArgs e) “0”.
{
SharedCounter += 1; The value of the SharedCounter increments with
InstanceCounter += 1; every request (irrespective of the client) because all
Response.Write("Press F5 and refresh the page<br>"); the instances of the webform share a single copy of
Response.Write("Instance Counter : " + InstanceCounter + SharedCounter because it’s a Shared/Static member
"<br>"); of the class.
Response.Write("Shared Counter : " + SharedCounter + "<br>");
}
}

Static / Shared Members in Global Class in App_Code folder


public static class GlobalSettings We can write a class in App_Code folder and it can be shared by all the
{ webforms in the web application. By making the members of the class as
public static int Counter; shared we can store data in that member in one webform and access that in
public static void SomeGlobalMethod() another webform. The data in such variables is shared by all the clients.
{}
}

ViewState
• Its of type StateBag and is used for storing state/data to be used in postback to the same webform.
• ViewState being hidden element in form tag rendered , its different for different client & is submitted to server only if form is
submitted or posted.
• ViewState is a collection of Key-Value pairs, where Key is of type String and Value is of type Object. But only those
objects which are marked as Serializable can be stored in ViewState.
• ViewState cannot be programed on client because the value of it is encrypted before it is rendered to the browser.
• If ViewState of the page is disabled (<%@Page EnableViewState=”False”) then anything added to it is not retained.

//Storing Integer in PropertyBag //Storing a serializable object (Demo) in PropertyBag


protected void Page_Load(object sender, EventArgs e) protected void Page_Load(object sender, EventArgs e)
{ {
int n; Demo d;
if (ViewState["cnt"] == null) if (ViewState["do"] == null)
n = 0; {
else d = new Demo();
n = (int) ViewState["cnt"]; d.N = 1;
n++; }
ViewState["cnt"] = n; else
Response.Write(n.ToString()); {
} d = (Demo)ViewState["do"];
-------------------------------------------------------------------------- d.N++;
[Serializable()] }
public class Demo ViewState["do"] = d;
{ Response.Write(d.N.ToString());
public int N; }
}

HiddenField
1. It can store data which is of type string and cannot store custom objects.
2. It can be programmed on the server and also on the client in Javascript.
protected void Page_Load(object sender, EventArgs e)
{
int n;
1
Deccansoft Software Services State Management Techniques

if (HiddenField1.value == “”)
n = 0;
else
n = Convert.ToInt32(HiddenField1.value);
n++;
HiddenField1.value = n.ToString();
Response.Write(n.ToString());
}
QueryString
• It is ideal for transfering of data from one page to other when using either hyperlink or Response.Redirect.
• It’s a collection of Key-Value pairs and both are of datatype string.
• The value of QueryString parameter must be encoded using Server.UrlEncode.

In Page1.aspx:
Faculty Name:
<asp:TextBox ID="txtFaculty" runat="server"></asp:TextBox>
<asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" /><br />
<br />
<br />
<asp:HyperLink ID=" hlnkPage2" runat="server"
NavigateUrl="~/StateManagement/Page2.aspx">Page2</asp:HyperLink></div>

In Page_Load Event Handler


hlnkPage2.NavigateUrl = "Page2.aspx?Faculty=" + Server.UrlEncode("F1+F2") + "&Timings=6.30PM";
In Button btnSubmit _Click Event handler
Response.Redirect("Page2.aspx?Faculty=" + Server.UrlEncode(txtFaculty.Text) + "&Timings=6.30PM");
string faculty = txtFaculty.Text;
string url = "QueryStringPage2.aspx?Faculty=" + Server.UrlEncode(faculty) + "&Timings=6.30PM");
//Response.Redirect(url);
Server.Transfer(url);

------------
In Page2.aspx
In Page_Load Event handler
Response.Write(Request.QueryString[“Faculty”] + “<br>”);
Response.Write(Request.QueryString[“Timings”] + “<br>”);

HttpContext (Context):
• Its an object created on server for every request from the web browser and thus its life time is same as the lifetime of the
request in which code from different files in the web application including master pages, webform, user control, custom
classes etc…
• If a Key-Value pair is added to the context of a request, it can be retrieved back from the context anytime during that requests
lifetime.
• It can be used for managing state while switching from one page to another using Server.Transfer.
• Here Key is of type string and value is of type Object

P1.aspx

Context.Items.Add(“k1”,”value1”)

Server. Transfer (“P2.aspx”)

P2.aspx
var = Context.Items [“k1”]

In Page1.aspx
In Button Click
Context.Items.Add(“k1”,”value1”); //Add a key value pair to the context.
Server.Transfer(“Page2.aspx”);
In Page2.aspx
In Page Load: Response.Write(Context.Items[“k1”].ToString()) //Retrieve from context the Value based on the key.

2
Deccansoft Software Services State Management Techniques

Note: Using HttpContext.Current we can get the reference to the context of the current request in any part of the web
application.
HttpCookie
• Cookies are used for Sharing data across webforms requested by same user/client and the data is stored on client/browser
machine.
• A cookie is a name value pair generated on behalf of a particular client and saved on the client machine.
• With every request the browser automatically includes all the cookies appropriate to that request.The cookie Name-Value
pairs are submitted in the form of request header called “Cookie” and they are saved on the server in the form of CGI
environmental variable called as HTTP_COOKIE.
• Http_Cookie: c1=v1 & c2=v2 & c3=v3.
• Cookies generated on server(added to the response) are rendered to the browser in a form of response header called
“Set_Cookie”.
• Every response cookie has name, value, domain, path, expires and secure attributes.These attributes are used by browser
while deciding whether to include the cookie in the request or not.
Note: Domain, Path, Expires and Secure attributes are not inlcuded with a cookie in the request.

Types of Cookies:
1. Persistent Cookie: Cookies which are permanantly stored on the client machine in a file. This cookie values are shared by all
the browser instances running on that machine.
2. NonPersistent Cookie This Cookies which are temporarily stored in the browsers memory. This are not shared across
browser instance and are also called as Session Cookie.

Request.Cookies is a collection of HttpCookie objects contructed for every cookie included in the request.
Response.Cookies is a collection of HttpCookie objects created for every cookie to be included in the response so that these
cookies can be appended to the existing list of cookies on the client machine.

• Every browser resticts the size of each cookie (approx to 4KB) and also the total number of cookies (to 20) which it would
accept from a given domain.
• If a cookie added to the response is already existing on the client and also if its domain and path attributes match to the new
cookie, the value of the old cookie is overwritten with the value of new cookie.
• If a cookie has been created by explicitly setting its domain and path properties then while expiring / destroying that cookie,
we have to set these properties to the same value otherwise the browser would treat that as a different cookie.

Default values for the properties of Cookie


Value Æ ”” Path Æ ”/” Expires Æ NPC (Non persistent cookie) Domain Æ ”<Current domain of the website>”
Secure Æ False
<form id="form1" runat="server">
Name: <asp:TextBox ID="txtKey" runat="server"></asp:TextBox>
Value: <asp:TextBox ID="txtValue" runat="server"></asp:TextBox>
<asp:CheckBox ID="chkPersistance" runat="server" Text="Persistance" />
<asp:CheckBox ID="chkSecured" runat="server" Text="Securred" /><br />
<asp:Button ID="btnSetCookie" runat="server" OnClick="btnSetCookie_Click" Text="Set Cookie" />
<asp:Button ID="btnGetCookie" runat="server" OnClick="btnGetCookie_Click" Text="Get Cookie" />
<asp:Button ID="btnDestroyCookie" runat="server" OnClick="btnDestroyCookie_Click" Text="Destroy Cookie" />
<asp:Button ID="btnGetAllCookies" runat="server" OnClick="btnGetAllCookies_Click" Text="Get All Cookies" />
Cookie Dictionary Name: <asp:TextBox ID="txtDictionaryName" runat="server"></asp:TextBox><br />
<asp:Button ID="btnAddToDictionary" runat="server" OnClick="btnAddToDictionary_Click" Text="Add To Dictionary"/ >
<asp:Button ID="btnShowDictionary" runat="server" OnClick="btnShowDictionary_Click" Text="Show Dictionary" />
<asp:Label ID="lblValue" runat="server"></asp:Label>
</form>
protected void btnSetCookie_Click(. . .) protected void btnGetCookie_Click(. . .)
{ {
HttpCookie c = new HttpCookie(txtKey.Text); HttpCookie c = Request.Cookies[txtKey.Text];
c.Value = txtValue.Text; if (c == null)
c.Domain = Request.Url.DnsSafeHost txtValue.Text = "Missing";
c.Path = Request.ApplicationPath; else
if (chkPersistance.Checked) txtValue.Text = c.Value;
c.Expires = DateTime.MaxValue; }
if (chkSecured.Checked)
c.Secure = true;
Response.Cookies.Add(c);

3
Deccansoft Software Services State Management Techniques

}
protected void btnGetAllCookies_Click(. . .) protected void btnDestroyCookie_Click(. . .)
{ {
lblValue.Text = ""; HttpCookie c = new HttpCookie(txtKey.Text);
foreach (String key in Request.Cookies) c.Expires = DateTime.Now.AddDays(-1);
lblValue.Text += key + " " + Request.Cookies[key].Value + Response.Cookies.Add(c);
"<br>"; }
}

CookieDictionary: A cookie which has many SubKey - value pairs is called as “CookieDictionary”.
Note: while using CookieDictionary don’t use character “&” in its SubKey or Value.
protected void btnAddToDictionary_Click(. . .) protected void btnShowDictionary_Click(. . .)
{ {
HttpCookie cookie = HttpCookie cookie =
Request.Cookies[txtDictionaryName.Text]; Request.Cookies[txtDictionaryName.Text];
if (cookie == null) if (cookie == null)
cookie = new HttpCookie(txtDictionaryName.Text); return;
cookie.Values[txtKey.Text] = txtValue.Text; lblValue.Text = "";
cookie.Expires = DateTime.MaxValue; foreach (string key in cookie.Values)
Response.Cookies.Add(cookie); lblValue.Text += key + "-" + cookie.Values[key] + "<br>";
} }

HttpSessionState
A session is an object on server having key-value pairs created on the server on behalf of every client. This object is created on
the first request from the client and the same object is reused for all subsequent requests by that client.

In session key-value pair is of type string-object and hence in session we can store any type of data unlike cookies where we can
only store strings. Also sessions can store any amount of data and also we can have unlimited numbers key-value pairs.

When a new session is created a unique ID is assigned to it and the same is rendered in the response as a non-persistent cookie.
With all subsequent requests the browser includes this cookie and asp.net uses it for deciding about which session object to be
used for that client’s request.

There is time out period defined for every session. The default is 20 minutes. If the time after the last request by the client exceeds
the timeout period then the session corresponding to that client is automatically destroyed on the server.
Programmatically a session can be destroyed using Session.Abandon() but the session i.e variables and its data would be
destroyed only in subsequent requests.
Session.RemoveAll() removes all keys in the session but the session is not destroyed.

Note: A persistent cookie will share the value across browser instances where as a session does not share its value.

protected void Page_Load(object sender, EventArgs e)


{
if (Session["cnt"] == null)
Session["cnt"] = 0;
Session["cnt"] = (int)Session["cnt"] + 1;
lblSession.Text = Session["cnt"].ToString();

//If the session is managed using URI url must be modified as below.
string url = "http://" + Request.Url.Host + ":" + Request.Url.Port +
Response.ApplyAppPathModifier(Request.ApplicationPath) + "/Demo.aspx";
Response.Write(url);
}

In some cases we may not want to use sessions in the web page then we set the page directive attribute EnableSessionState to
false.
<%@ Page …. EnableSessionState=”false” %>

EnabledSessionState True / False / Readonly.


Session.IsReadOnly: This property is used to check if the session is read only or not.
Session.IsNewSession: This property is used to check if it is the first request from the client.

4
Deccansoft Software Services State Management Techniques

In web.config:
<SessionState timeout=”30” cookieless=”UseUri” CookieName=”Demo” mode=”InProc”
stateConnectionString=”tcpip=localhost:42424” />
WebGarden & WebFarm
• If a single instance of a web application spans over the multiple instances of the webserver running on the same machine is
then it is called as WebGarden,
• If a single instance of a web application spans over the multiple instances of the webserver running on the different machine
is then it is called as WebFarm,

If session is used for a web application on webfarm or webgarden the sessionState mode must be set to either StateServer or
SqlServer. State server is a windows service and can be started using ControlPanel Æ AdminstrativeTools Æ Services Æ
ASP.NET StateService.

HttpApplicationState
DataType of Application is HttpApplicationState.
An Application object is used for sharing name-value pairs across different web pages and is irrespective of the client requesting
them.
If we want to send data from one page to another i.e. for example a textbox value in page1 to a label in page2. There are two ways
to go to page2.

if (Application["cnt"] == null)
Application ["cnt"] = 0;
Application.Lock() ;
Application ["cnt"] = (int) Application ["cnt"] + 1;
Application.Unlock();
lblApplication.Text = Application ["cnt"].ToString();

About Web Applications / Virtual Directory

An ASP.NET Web Application is collection of files Pages, HTTP Handlers, HTTP Modules and code within the scope of a
physical directory or its sub directory for which a virtual directory is created.

How to create a virtual directory?


StartÆProgramsÆAdministrativeToolsÆInternet Information Server
ÆDefault WebsiteÆ Right clickÆNewÆVirtual Directory
Then Mention the virtual directory name and physical directory name(Need not be same)

There is another way to create the virtual directory


i.e. Right click on the physical directoryÆpropertiesÆwebsharingÆshare with Alias name.

• Default Physical Directory of a website in IIS: c:\Inetpub\wwwroot


• Irrespective of the location of the physical folder a virtual directory can be created in IIS. Only then the content of it can
behave as a WebApplication.
• A virtual directory can be created either under root directory of the website or under another virtual directory.

Physical Directory Virtual Directory


C:\Inetpub\wwwroot /
C:\Inetpub\wwwroot\Demo1 /Demo1
D:\DemoWebApp 1 /DemoWebApp1
D:\DemoWebApp 1\Demo1 /DemoWebApp2

Http://Servername/D1/D2
For the above path D2 is the web application provided, it represents a virtual directory.
(Whose physical directory may or may not be in D1)

A virtual directory can be created under another virtual directory is an independent directory / Web Application.
C:\D1 Æ /D1 ---- here D1 is virtual directory
C:\D2 Æ /D1/D2 --- here D2 Application is used.

5
Deccansoft Software Services State Management Techniques

If the same content has to be accessible from different URL’s, multiple virtual directories can be created for the selected physical
directory i.e for one physical directory we can have more than one virtual directories.

Note:
• Physical directory and Virtual directory names need not be same.
• In Asp.Net for every web application a new App-Domain is created and thus every application has its own sessions and
applications data which is not shared with web pages in other web applications.
• In the above example a Session variable created in D2 cannot be accessed in D1.

HttpApplication Class / Global.asax


The root directory of a web application has a special significance and certain content can be present on in that folder. It can have a
special file called as “Global.asax”. ASP.Net framework uses the content in the global.asax and creates a class which is inherited
from HttpApplication.

During the lifetime of an application, AP.NET maintains a pool of Global.asax defined HttpApplication instances. When an
application receives an http request, the ASP.Net page framework assigns one of these instances to process that request. That
instance is responsible for managing the entire lifetime of the request it is assigned to and the instance an only be reused after the
request has been completed when it is returned to the pool.

The instance members in Global.asax cannot be used for sharing data across requests but static member can be.
Global.asax can contain the event handlers of HttpApplication object and some other important methods which would execute at
various points in a web application.

Some important Events / Methods of HttpApplication Objects:

Application_Start: When the application receives the first request and it is loaded to create the App-Domain.
Application_End: When the web server is shutdown and the web applications are unloaded.
Session_Start: When the first request comes from a given client and a session is created.
Session_End: When the session times out or is abandon.
Application_BeginRequest: Is executed just before processing of the webform for every request.
Application_EndRequest: After processing the webform, before rendering the output.
Application_Error: Is executed for handling any type of unhandled exception raised in any of the WebForm’s of the application
and thus can be used for centralized exception handling

Category.aspx
protected void Page_Load(object sender, EventArgs e)
{
lblCatID.Text = Request.QueryString["CatId"];
}
Global.asax
protected void Application_Error(object sender,EventArgs e)
{
Exception ex;
ex = Content.Error.InnerException;
//Context.Error return HttpException object and it would contain the reference to the actual exception in InnerException property.
if (ex is ApplicationExeption)
{
//Do the logging of exception here into some file.
Server.Transfer(“SiteNotWorking.aspx”);
Context.ClearError();
}
}
protected void Application_BeginRequest(object sender,EventArgs e)
{
string path = Request.Path.ToLower();
Response.Write(path + "<br>");
if (path.IndexOf("jobs.aspx") != -1)
Context.RewritePath("category.aspx", "", "catId=1");
else if (path.IndexOf("development.aspx") != -1)
Context.RewritePath("category.aspx", "", "catId=2");
else if (path.IndexOf("training.aspx") != -1)
6
Deccansoft Software Services State Management Techniques

Context.RewritePath("category.aspx", "", "catId=3");


}

Note: We can handle Error event of the page so that for any unhandled runtime exception in that webform this event handler is
executed. Only if Context.ClearError() is not executed the error propogates to Application_Error event handler in global.asax.

In DemoForm.aspx
protected void Page_Error(Object sender,EventArgs e)
{
Exception ex = Context.Error;
Response.Write(ex.Message);
}

//////
<div><asp:Label ID="lblError" runat="server" Text=""></asp:Label> </div>
Username:<asp:TextBox ID="txtUsername" runat="server"></asp:TextBox> <br />
Password:<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox> <br />
<asp:CheckBox ID="chkRemember" runat="server" Text="Remember my u/p on this machine" /><br />
<asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" />

protected void Page_Load(object sender, EventArgs e)


{
if (!IsPostBack)
{
HttpCookie cookie = Request.Cookies["AuthCookie"];
if (cookie != null)
Response.Redirect("~/");
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
string un = txtUsername.Text;
string pwd = txtPassword.Text;
if (un == pwd)
{
if (chkRemember.Checked)
{
HttpCookie cookie = new HttpCookie("AuthCookie");
cookie.Value = un;
cookie.Expires = DateTime.MaxValue;
Response.Cookies.Add(cookie);
}
Response.Redirect("~/");
}
else
lblError.Text = "Invalid u/p";
}

<asp:LinkButton ID="lnkLogout" runat="server" OnClick="lnkLogout_Click">Logout</asp:LinkButton>


//Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
HttpCookie cookie = Request.Cookies["AuthCookie"];
if (cookie != null)
Response.Write(cookie.Value);
}
protected void lnkLogout_Click(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("AuthCookie");

7
Deccansoft Software Services State Management Techniques

cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
Response.Redirect("LoginForm.aspx");
}

8
Deccansoft Software Services – ASP.NET web.config, Custom Errors, URL Rewriting, Trace

Configuration File (web.config):


Web.config is an xml based configuration file containing all configuration settings for the webforms present in same
directory and sub directory.
It can be present in any directory of a web application it overrides and extends the configuration setting of the parent
directory web.config.
Note:
• Because of the above behavior the directory structure of web app can be planned based on the configuration settings for
the various web forms.
• A web.config contains sections, few of which must be present only in either machine.config or in web app root directory.
(Machine.config is the global configuration file which contains configuration settings for all types of .Net application
running on that machine)

Web.config Default.aspx
<configuration> protected void Page_Load(object sender, EventArgs e)
<appSettings> {
<add key="k1" value="v1" /> lblvalue1.Text = ConfigurationManager.AppSettings["k1"];
<add key="k2" value="v2" /> lblvalue2.Text = ConfigurationManager.AppSettings["k2"];
<add key=”k3” value=”v3”/> lblvalue3.Text = ConfigurationManager.AppSettings["k3"];
</appSettings> }
</configuration>
Note: We have to add reference to System.Configuration (Right click on project -> Add Reference

Custom Errors:
<customErrors mode="RemoteOnly" defaultRedirect="Errors.aspx">
<error statusCode="404" redirect="~/"/>
<error statusCode="500" redirect="~/ServerError.aspx"/>
</customErrors>
• Mode=”RemoteOnly” means redirect the request to error page only if the request comes from remote client.
• Mode=”Off” for both local and remote users it renders error description and does not redirect it.
• Mode=”On” for both local and remote users it redirects to the error page.
When we redirect to Custom error page, the querystring parameter “aspxerrorpath” is appended to the url and its value is the
url of the page which actually has an error.

Note: In every webform “Error” event can be handled for a page. When ever an exception occurs it first tries to see for the
error Event Handler of the page, then Error Event Handler of the application and then it goes to Custom Error.
Because of the runtime Exception and the Custom errors, if the user is restricted to some page we cannot get the details about
the exception which has occurred.

Most of the attributes which we can set for <%@Page can also be set at application level in web.config file.
<pages validateRequest="true" maintainScrollPositionOnPostBack="true" >
ValidateRequest set to true will not allow tags to be posted and accepted by the page.

URL Re-Writing:
URL Re-Writing is a process where the path of the URL is rewritten. This is done with the help of
Context.RewritePath(….). An alternate way is add UrlMapping in web.config
<urlMappings>
<add url="~/jobs.aspx" mappedUrl="~/Category.aspx?CatId=1"/>
<add url="~/development.aspx" mappedUrl="~/Category.aspx?CatId=2"/>
<add url="~/training.aspx" mappedUrl="~/Category.aspx?CatId=3"/>
</urlMappings>
Tracing
<trace enabled="true" pageOutput="true" requestLimit="10" localOnly="true"
traceMode="SortByTime" writeToDiagnosticsTrace="true" />
<%@ Page Trace=”true” TraceMode=”SortByTime” …..%>

Trace.Write(“ … “) & Trace.Warn(“ … “); - Are used for writing to Trace output so that we can find the amount of time a
block of code has taken.

To view trace summary from browser we have to use: http://localhost/AppName/Trace.axd

1
Deccansoft Software Services – ASP.NET web.config, Custom Errors, URL Rewriting, Trace

Updating Web.Config Programmatically

<configuration>
<connectionStrings>
<add name="test"
connectionString="Server=test;uid=test;password=test;Database=t
est;" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<trace enabled="true" />
<identity impersonate="false" />
<compilation debug="true" strict="false"
explicit="true" />
<authentication mode="Windows" />
</system.web>
</configuration>

Imports System.Web.Configuraion
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim cnfg As System.Configuration.Configuration
'cnfg =Configuration.GetWebConfiguration( Request.ApplicationPath)
cnfg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath)
Dim trace As TraceSection = DirectCast(cnfg.GetSection("system.web/trace"), TraceSection)
If trace IsNot Nothing Then trace.Enabled = chkEnabled.Checked
Dim ids As IdentitySection = DirectCast(cnfg.GetSection("system.web/identity"), IdentitySection)
If ids IsNot Nothing Then ids.Impersonate = chkImpersonate.Checked
Dim au As AuthenticationSection = DirectCast(cnfg.GetSection("system.web/authentication"), AuthenticationSection)
If au IsNot Nothing Then au.Mode = ddlmode.SelectedValue
Dim cm As CompilationSection = DirectCast(cnfg.GetSection("system.web/compilation"), CompilationSection)
If cm IsNot Nothing Then
cm.Debug = chkCDebug.Checked
cm.Explicit = chkcexplicit.Checked
cm.Strict = chkCstrict.Checked
End If
Dim cs As System.Configuration.ConnectionStringsSection
cs = DirectCast(cnfg.GetSection("connectionStrings"), System.Configuration.ConnectionStringsSection)
If cs IsNot Nothing Then cs.ConnectionStrings(1).ConnectionString = txtCs.Text
cnfg.Save()
End Sub

2
Deccansoft Software Services – ASP.NET Authentication and Authorization

Authentication: The act of determining the identity of the requesting entity is known as authentication. The user must present
the credentials such as a name / password pair in order to be authenticated.

Authorization: Once the request is authenticated, it must be determined whether that identity can access the given resource or
not. This process is known as authorization.

Types of Authentication
1. Windows
2. Forms
3. Passport

Windows Authentication
When we use ASP.NET Windows’s authentication, ASP.NET attaches a Windows Principal object to the current request.

By default the web browser along with the request does not include any identity of the client. In such cases web server treats
such request as anonymous request. If anonymous users are allowed access authentication is not required on web server..

IIS Authenticates the user based on the underline user accounts created on the Operation System.

StartÆSettingsÆControlPanelÆAdministrativeToolsÆIIS(Internet Information Services) ÆRight click on web


applicationÆPropertiesÆDirectory SecurityÆclick on First Edit Button

Types of Windows Authentication.


1. Basic Authentication
2. Integrated Windows Authentication.

Integrated Authentication:
• In integrated windows authentication browser by default uses the identity of currently logged in user and using the same
IIS authenticates the client.
• If the default logged-in user is not authorized then the client is shown a dialog asking for a different identity credentials.
• In integrated windows authentication the username and password is encrypted on client and submitted to the server.
• It works on in Internet Explorer

Basic Authentication:
• If IIS denies access to anonymous users it generates response for anonymous request, showing a dialog on the browser
asking for identity credentials of the client.
• In Basic authentication the username and password are submitted as plain text unless HTTPS is used.
• It works with the web browser.

Note: Either Integrated Windows Authentication should be checked or Basic Authentication should be checked. If both are
checked Integrated Windows Authentication takes the precedence.

Limitation:
Windows authentication is good only for Intranet application because for every identity supported on the server a login as to be
created on the domain of the web server.

Step 1.
/Web.config (Applications Root directory web.config file)
<authentication mode="Windows" /> ---This section can be present only in the root directory web.config and thus for one Web
Application only one type of Authentication mode can be Supported.

Step 2:
/SecurityDemo/Web.config
<configuration>.
<system.web>
<authorization> - This section can be present in any directory web.config file
<deny users ="?"/> ---All Anonymous users are denied access
<deny roles=”BUILTIN/Administrators”/> ---All administrators are denied access
<allow users=”*”/> -- Allow access to all users except anonymous and administrators.
</authorization>
</system.web>

1
Deccansoft Software Services – ASP.NET Authentication and Authorization

</configuration>
Interpretation: All the WebForms in the “SecurityDemo” folder are not accessible to Anonymous Users and Administrators.

Step3:
/SecurityDemo/UserDetails.aspx
protected void Page_Load(object sender, EventArgs e)
{
lblIsAuthenticated.Text =User.Identity.IsAuthenticated.ToString();
lblUsername.Text = User.Identity.Name; //Name of the current user is rendered
lblAuthenticationType.Text=User.Identity.AuthenticationType.ToString();
}

Forms Authentication
Step 1:
/Web.Config
<authentication mode="Forms">
<forms name ="__AUTHCOOKIE" defaultUrl=”~/” loginUrl ="~/SecurityDemo/LoginForm.aspx" timeout=”30”>
<credentials passwordFormat ="Clear">
<user name ="u1" password ="p1"/>
<user name ="u2" password ="p2"/>
</credentials>
</forms>
</authentication>

Step 2 & 3: Same as in Windows Authentication.

Step 4: Add to SecurityDemo folder – LoginForm.aspx


/SecurityDemo/LoginForm.aspx
protected void Page_Load(object sender, EventArgs e)
{
// A user will come to login page only if its either not authenticated or not authorized.
if (Request.IsAuthenticated) //If Authenticated means that the user is not Authorized.
lblError.Text = "Not Authorized";
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string log = txtLogin.Text;
string pwd = txtPassword.Text;
if (FormsAuthentication.Authenticate(log, pwd))
{
FormsAuthentication.RedirectFromLoginPage(log,ChkRememberMe.Checked);
/* FormsAuthentication.SetAuthCookie(log,chkRememberMe.Checked);
string returl = Request.QueryString["ReturnUrl"];
if (returl == null)
Response.Redirect("~/"); //The user has directly come to the login page.
else
Response.Redirect(returl); */
}
else
lblError.Text = "Invalid Login or Password";
}
In forms Authentication, IIS treats every request as Anonymous request.

If the request includes the cookie for authentication “__AUTHCOOKIE” then ASP.NET treats the client as authenticated
otherwise it is treated as anonymous.

If anonymous users are denied access and the request is not authenticated then ASP.Net redirects the users to login URL
(“SecurityDemo/LoginForm.aspx”).. When the user is redirected to the login page the url of the current page is appended as
query string parameter “ReturnUrl” to the Url of LoginPage

Note: A user is redirected to Login page either if not authenticated or not authorized

2
Deccansoft Software Services – ASP.NET Authentication and Authorization

If the User is Authenticated, then based on the value of authentication cookie (__AUTHCOOKIE) the user is Authorized
and for this it looks in “<authorization>” section in web.config.

Note: The value of User.Identity.Name is set from the value of __AUTHCOOKIE which mostly contains the username
used for login.

FormsAuthentication.Authenticate(string log, string pwd)


Verifies if the specified loging and password exists in the credentical section of web.config or not.

FormsAuthentication.SetAuthCookie(string loginname, bool isPersistentCookie)


This function adds to the response of the authentication cookie, the name of the cookie is taken from forms tag in
web.config and the value of the cookie is the first parameter. If the second parameter is true the cookie created is
persistant cookie otherwise created a non-persistent cookie.

FormsAuthentication.RedirectFromLoginPage(string loginname, bool isPersistentCookie)


Does two things 1. Add the authentication cookie to the response so that for all subsequent request the client can be
treated as authenticated. 2. Redirects the user to the Url as mentioned in the QueryString parameter “ReturnUrl”.

Step 5: Add Logout LinkButton to UserDetails.aspx.


protected void lbtnLogout_Click(object sender, EventArgs e)
{
FormsAuthentication.SignOut(); //Adds cookie to the response with expire date
Response.Redirect(FormsAuthentication.LoginUrl);
// FormsAuthentication.RedirecttoLoginPage();
}

To protect the password in web.config file (credential section)


Step 6: Add Encrypt Button to UserDetails.aspx
protected void btnEncrypt_Click(object sender, EventArgs e)
{
Response.Write(FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "SHA1"));
}
Step 7: Run the application and replace “p1”, “p2’ and “p3” in web.config with their hashed values.

Step 8: Change in /web.cofig


<credentials passwordFormat ="Clear"> to <credentials passwordFormat ="SHA1">

SHA1: 160 bit encryption & MD5: 128 bit encryption – Using both we can only encrypt data as they are One Way Hash
Algorithm.
Role Based Security

3
Deccansoft Software Services – ASP.NET Authentication and Authorization

Step 9:
Modify “/SecurityDemo/Web.config” as below
<authorization>
<deny users ="?"/>
<deny roles="r1"/> - Deny access to all users with Role “r1”.
</authorization>

Step 10: Add a button with id “btnForR2” to Userdetails.aspx


In /SecurityDemo/UserDetails.aspx
protected void Page_Load(object sender, EventArgs e)
{
btnForR2.Visible = User.IsInRole("r2"); //Checks if the current user has the role “r2” or not?
}

Step 11:
• Roles should be assigned to the request based on identity of the authenticated user and this should be done in
“Application_AuthenticateRequest” in Global.asax
Add the following to “/Global.asax”
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
string[] arRoles = new string[2];
switch (User.Identity.Name)
{
case “u1”:
arRoles[0] = “r1”;
arRoles[1] = “r3”;
case “u2”:
arRoles[0] = “r2”;
arRoles[1] = “r3”;
}
Context.User = new System.Security.Principal.GenericPrincipal(User.Identity, arRoles);
// (VERY VERY IMPORTANT – Don’t forget this.
}
}
Using Location Tag
Using <location path=”Demo.aspx”> we can specifically mention the Configuration Settings for a given WebForm
<configuration>
<location path="Unsecured.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
</configuration>
If any Configuration Seeting is enclosed within <location allowOverride=”false”> it is locked and cannot be overiden in the
subdirectory Configuration file.
Note: Location must be nested immediately under Configuration tag.
Examples using Response Object
Response.Clear(); Response.Clear();
Response.ContentType = "image/gif"; Response.ContentType = "text/txt";
Response.WriteFile("images/demo.gif"); Response.AppendHeader("content-disposition",
Response.End(); "attachment;filename=demo.txt");
Response.Clear(); Response.WriteFile("Demo.txt");
Response.ContentType = "application/msword"; Response.End();
Response.Write("<b>Hello</b>");
Response.End(); Response.AppendHeader("refresh", "5;url=Default2.aspx");

4
Deccansoft Software Services ASP.NET - Globalization
While dealing with multilingual If some dynamic (language independent) text has to be stored in the database table the column
datatypes to be taken must be either nChar, nVarchar, nText.

Creation of Resource Files

Local Resource File: These files must be present in the folder App_LocalResources and the filename is based on the name of
WebForm with which the resource file is associated with.
Steps:
• Create a new folder(Globalization). To the Folder Æ Add a new Item Æ WebForm(Default.aspx)
• To the Folder Æ RightClick Æ Add ASP.NET Folder Æ App_LocalResources
• To App_LocalResources Æ RightClick Æ Add a new Item Æ Resource File (provide name and Value pairs)

\AppName\GlobalicationDemo\Default.aspx.
\AppName\GlobalicationDemo\App_LocalResources\Default.aspx.resx – Culture Neutral Resource File.
\AppName\GlobalicationDemo\App_LocalResources\Default.aspx.fr.resx – French Neutral Resource File.
\AppName\GlobalicationDemo\App_LocalResources\Default.aspx.fr-BE.resx – French Belgium Resource File.
\AppName\GlobalicationDemo\App_LocalResources\Default.aspx.de.resx – German Neutral Resource File.

KEYS Default.aspx.resx Default.aspx.fr.resx Default.aspx.Fr-BE.resx Default.aspx.De.resx


lblAddressKey.ForeColor Black Red Pink Blue
lblAddressKey.Text Address1 in Address1 in French Address1 in Address1 in German
Default French - Belgium
lblRealNameForeColorKey Black Red Pink Blue
lblRealNameTextKey Deccansoft Deccansoft Deccansoft (in French Deccansoft (in German)
(from Default) (in French) Belgium)

In Glocal Resourse File in the folder App_GlobalResources: This is Global to all the WebForms in a given web application. It
can have any name and must be present in the Root directory of the web application.
• To the Application Æ RightClick Æ Add ASP.NET Folder Æ App_GlobalResources
• To App_GlobalResources Æ RightClick Æ Add a new Item Æ Resource File (provide name and Value pairs)

\AppName\App_GlobalResources\Settings.resx
\AppName\App_GlobalResources\Settings.fr.resx
\AppName\App_GlobalResources\Settings.fr-BE.resx
\AppName\App_GlobalResources\Settings.de.resx

KEYS Settings.aspx.resx Settings.aspx.fr.resx Settings.aspx.Fr-BE.resx Settings.aspx.De.resx


lblCompanyName Deccansoft (in Default) Deccansoft (in French) Deccansoft (in French Deccansoft (in German)
Belgium)

Any one of the following facilities can be used for associating the culture with the current thread /
request in execution.
Alternative 1
In Web.Config file:
<globalization culture=”de-AT” uiCulture=”de-AT” ….>
1. If configured here the value would remain same for the entire request for all the webforms of the project.

Alternative 2
• //In ASPX Page. If configured here then it has to be done for every page and the value to be mentioned must be constant or
“auto”
<%@ Page UICulture="auto" Culture="auto" . . . %> or
<%@ Page UICulture="de-AT" Culture="de-AT" . . . %>

Alternative 3
// Following function can be overridden in the webform and is specific to that webform/page only.
Protected Overrides Sub InitializeCulture()
Page.UICulture = "auto" ‘or Request.UserLanguages(0) or “de-AT” or Session[“lang”].ToString()
Page.Culture = "auto" ‘or Request.UserLanguages(0) or “de-AT” or Session[“lang”].ToString()
End Sub
1
Deccansoft Software Services ASP.NET - Globalization
• If the value of Culture or UICulture is set to “auto” then the value is taken must first value of request header “User-
Languages”. This header is initialized in by going to Tools Æ Internet Options Æ Languages.

Alternative 4
//Following should be written in Global.asax and this global to all the webforms of the application.
Protected Application_BeginRequest(. . .)
Dim ci As New CultureInfo(“de-AT”)
or CultureInfo(Session[“lang”].ToString()) //Assuming Session[“lang”] is already initialized.
System.Threading.Thread.CurrentThread.CurrentCulture = ci
System.Threading.Thread.CurrentThread.CurrentUICulture = ci
End Sub

Protected Sub Page_Load(. . .) Handles Me.Load


lblRealName.Text = GetLocalResourceObject("lblRealNameKeyText").ToString() //To read the value programatically
lblRealName.ForeColor =
System.Drawing.Color.FromName(GetLocalResourceObject("lblRealNameKeyForeColor").ToString())
lblDate.Text = Now.ToString() //The value is returned based on Culture settings of Current Thread
Dim amt As Decimal = 1000000.01
lblAmount.Text = amt.ToString("C") //The value is returned based on Culture settings of Current Thread
End Sub
We can use GetGlobalResourceObject for reading the Key – Value pair from Global resource file.

Designing the WebForm so that the labels are linked to Keys in Resource Files
Steps for setting the Explicit Expression:
• Select the control Æ RightClick Æ Properties Æ Goto Expressions
• On the lefthand side select the property to be initialized, set ExpressionType to Resources
• If the key has to be fetched from LocalResources File directly set ResourceKey. Otherwise, to fetch from GlobalResoucesFile
first set ClassKey with the value of GlobalResource Filename and then set ResourceKey

--------------------Explicit Expression From Local Resource File------------------


<asp:Label Text="<%$Resources:lblRealNameKeyText %>"
ForeColor="<%$Resources:lblRealNameKeyForeColor %>" ID="lblRealName" runat="server"/>

------------------Explicit Expression From Global Resource File---------------</strong>


<asp:Label Text="<%$ Resources:Settings, lblCompanyName %>" ID="lblCompanyName" runat="server"></asp:Label>

--------------------Implicit Expression-------------------
<asp:Label meta:ResourceKey="lblAddressKey" ID="lblAddress" runat="server"/>
Based on the key “lblAddressKey” the ForeColor and Text properties are automatically fetched from the resouce file.

-------------------Fetching Values Programatically-------


<asp:Label ID="lblRealName" runat="server" Font-Bold="False"></asp:Label>

--------------Culture Demos-------------------
<asp:Label ID="lblDate" runat="server"></asp:Label>
<asp:Label ID="lblAmount" runat="server"></asp:Label>

Notes:
• Based on the Culture value of the CurrentThread the Formatting functions (like Date or Currency) render their output.
• Based on UICulture of the CurrentThread the framework loads the appropirate resource file for all the culture specific
lookups.
• The Culture and UICulture values can be set either in Web.Config – Globalization Tag or Application_BeginRequest or in
<%Page Directive or in InitializeCulture method of page class. This is also the incresing order of their precedence.

For languages like Arabic and Urdu do the following

<HTML dir = “rtl” …>

2
Deccansoft Software Services – ASP.NET Web Caching
Types of Caching: Output Caching / Fragment Caching / Data Caching / Substitution Caching.

Output Caching
Here the response of the request is cached for a predefined period and the same is reused for all subsequent requests for
the same page.

CacheDemo/Cache.aspx:
<%@ OutputCache Duration="10" VaryByParam="txtDemo" VaryByHeader="referrer"
VaryByCustom="Browser" Location="ServerAndClient" NoStore="true"%>
<asp:Label ID="lblCurrentTime" runat="server"></asp:Label>
<asp:Label ID="lblDemo" runat="server"></asp:Label>&nbsp;
<asp:TextBox ID="txtDemo" runat="server"></asp:TextBox>
<asp:Button ID="btnDemo" runat="server" Text="Demo" />

CacheDemo/Cache.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
lblCurrentTime.Text = DateTime.Now.ToLongTimeString();
}
protected void btnDemo_Click (object sender, EventArgs e)
{
lblDemo.Text = txtDemo.Text;
}
• Duration and VaryByParam are the only required attributes and others are optional
• The value of “VaryByParam” can be either QueryString parameter name, Cookie Name, Form element Name or
Id of Control on the WebForm.
For every value of the parameter (parameters) mentioned in VaryByParam, a different cache copy of the response is
maintained on the server and reused for those values of parameters for subsequent request.
• VaryByParam can be “none” or “*” also. “*” means create separate cache copy if any parameter changes.
• VaryByCustom=”Browser” Æ For different browser types a different cache is created.
• Location:
Any Cache can be located on the browser (client) or Proxy or Server
None Cache is disabled everywhere
Downstream Cache can be located either on browser (client) or proxy.
Server Cache is located on the server
Client Cache is located on the browser (client).
ServerAndClient Cache on both Server and Client but not on Proxy
• NoStore=”true” Æ page should not be cached on the client irrespective of the browser settings (By Default it is
false).

To specify cache settings programmatically:


protected void Page_Load(object sender, EventArgs e)
{
lblCurrentTime.Text = DateTime.Now.ToLongTimeString();
Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
Response.Cache.SetExpires(new DateTime(2007,12,31,10,20,30); //For setting the absolute Data and Time.
//Response.Cache.SetMaxAge(new TimeSpan(0, 0, 10)); //For mentioning the relative Data and Time.
Response.Cache.VaryByHeaders["referrer"] = true;
Response.Cache.SetValidUntilExpires(true);
Response.Cache.VaryByParams["lblCurrentTime"] = true; //works only if SetValidUntilExpires is set to true
}
/Web.Config
<system.web>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="CacheInConfig" enabled="true" duration="10" location="ServerAndClient"/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>
</system.web>
In CacheDemo/Cache.aspx:
<%@ OutputCache VaryByParam="txtDemo" CacheProfile="CacheInConfig"%>
1
Deccansoft Software Services – ASP.NET Web Caching

Changes made to profile(i.e OutputCacheProfile) is automatically effected to all the webforms.


Fragment Caching
Here instead of caching the complete response of the page, only a small portion of it will be cached.

To the Project Æ Right clickÆ Add New itemÆWeb UserControl (CacheControl.ascx)

/CacheDemo/CacheControl.ascx: (UserControl)
<%@ OutputCache Duration="10" VaryByControl="none" %>
Note: when the output Cache directive is being used in UserControl replace “VaryByParam” attribute with
“VaryByControl” i.e for mentioning the Control Id, but for cookie / querystring / form element use “VaryByParam”

/CacheDemo/CacheContol.ascx.cs
protected void Page_Load(object sender, EventArgs e)
{
lblControl.Text = DateTime.Now.ToLongTimeString();
}

Drag and drop UserControl in /CacheDemo/Cache.aspx


Note: To see the effect of the Fragment caching comment OutputCache in the ASPX page.
Data Caching
Here instead of caching the response of the page we only cache the data used in making the response of the page.
When the memory is insufficient the Items in data cache automatically expires.
To the Project Æ Right clickÆ Add New itemÆText File (Demo.txt)

• Add a label lblDataCacheDemo to the aspx page.


/CacheDemo/Cache.aspx.cs:
using System.Web.Caching
protected void Page_Load(object sender, EventArgs e)
{
if (Cache["dt"] == null)
{
Cache["dt"] = DateTime.Now;
CacheDependency dep = new CacheDependency(MapPath("Demo.txt"));
//Cache.Insert("dt", DateTime.Now, dep);
//Cache.Insert("dt", DateTime.Now, dep, DateTime.Now.AddSeconds(10),
System.Web.Caching.Cache.NoSlidingExpiration);
Cache.Insert("dt", DateTime.Now, dep, System.Web.Caching.Cache.NoAbsoluteExpiration,
new TimeSpan(0, 0, 10));
}
DateTime dt = (DateTime)Cache["dt"];
lblDataCacheDemo.Text = dt.ToLongTimeString();
Response.AddCacheItemDependency("dt"); //Response of the page immediately expires if the data item expires
//Response.AddCacheItemDependencies; // Cache item is dependent on Array of data items
//Response.AddCacheDependency;
//Response.AddFileDependencies; // Cache item is dependent on array of files
//Response.AddFileDependency; // Cache item is dependent on single file
}
Note: To reflect the changes made to the code while working with data cache expiration policy, rebuild the website
(Build Æ Rebuild Website)
Substitution Caching
Here the complete page is cached but a portion of the page is computed everytime irrespective of output of page
computed or fetched from cache.

In CacheDemo/Cache.aspx: Drag and Drop Substitution Control on the WebForm


<asp:Substitution ID="sc" runat="server" MethodName="GetServerTime" />

/CacheDemo/Cache.aspx.cs:
static string GetServerTime(HttpContext context)
{
return DateTime.Now.ToLongTimeString();
}
The return value of the above function is rendered in position of Substitution Control.
2
Deccansoft Software Services – ASP.NET Web Caching

3
Deccansoft Software Services DataBoundControls

GridView Properties:
AllowPaging, AllowSorting, AlternatingRowStyle, AutoGenerateColumns, AutoGenerateDeleteButton,
AutoGenerateEditButton, AutoGenerateSelectButton, BottomPagerRow, Columns, DataKeyNames, DataKeys, DataMember,
DataSource, DataSourceID, EditIndex, EditRowStyle, EmptyDataRowStyle, EmptyDataTemplate, EmptyDataText,
FooterRow, FooterStyle, HeaderRow, PageCount, PageIndex, PagerSettings, PagerStyle, PagerTemplate, PageSize,
RowHeaderColumn, Rows, RowStyle, SelectedDataKey, SelectedIndex, SelectedRow, SelectedRowStyle, SelectedValue,
ShowFooter, ShowHeader, SortDirection, SortExpression, TopPagerRow

GripView Events:
RowCommand, SelectedIndexChanged, SelectedIndexChanging, Sorting, Sorted, RowUpdating, RowUpdated, RowDeleted,
RowDeleting, RowCreated, RowDataBounded, DataBinding, DataBound, PageIndexChanging, PageIndexChanged.

Types of Columns/Fields in GridView / DetailsView / FormsView


DataControlField: Its parent of all other Fields and is abstract class.
Properties: ControlStyle, FooterStyle, FooterText, HeaderText, ItemStyle, ShowHeader, SortExpression, Visible

BoundField: It renders Literal Control with in the cell.


Properties: DataField, DataFormatString, ApplyFormatInEditMode, HtmlEncode. InsertVisible. NullDisplayText, ReadOnly

Command Field: Its used only for the commands - (Select, Delete, Update, cancel, Edit, New)
Properties: ShowCancelButton, ShowDeleteButton, ShowEditButton, ShowInsertButton, ShowSelectButton, ButtonType,
CancelImageUrl, CancelText, CausesValidation, DeleteText, DeleteImageUrl, EditImageUrl,EditText, HeaderImageUrl,
InsertImageUrl, InsertText, InsertVisible, NewImageUrl, NewText, SelectImageUrl, SelectText, UpdateImageUrl, UpdateText,
ValidationGroup

CheckboxField: It renders Checkbox with the cell


Properties: ApplyFormatInEditMode, ControlStyle, ConvertEmptyStringToNull, DataField, DataFormatString, HtmlEncode,
InsertVisible, NullDisplayText, ReadOnly, Text

ButtonField: Its used for Custom commands


Properties: ButtonType, CausesValidation, CommandName, DataTextField, DataTextFormatString, ImageUrl, InsertVisible,
Text, ValidationGroup

HyperlinkField: It is used to Navigate to another page


Properties: DataNavigateUrlFields, DataNavigateUrlFormatString, DataTextField, DataTextFormatString, Target

ImageField: It is used to display image of the field in the cell.


Properties: AlternateText, ConvertEmptyStringToNull, DataAlternateTextField, DataAlternateTextFormatString,
DataImageUrlField, DataImageUrlFormatString, InsertVisible, NullDisplayText, NullImageUrl, ReadOnly

TemplateField: It is used if any of the field needs any kind of customization


Properties: ItemTemplate, EditItemTemplate, InsertItemTemplate, AlternatingItemTemplate, ConvertEmptyStringToNull

EmpGridViewDemo
1. Drag and Drop SqlDataSource, right click and goto Configure DataSource and provide valid ConnectionString click on Next,
Select TableName and its Columns, Click on Advanced Button and Check Generate Insert, Delete, Update Statements (Check
Optimistic Concurrency if required)
<asp:SqlDataSource ID="sdsEmp" runat="server" ConflictDetection="CompareAllValues"
ConnectionString="<%$ ConnectionStrings:MSNETConnectionString1 %>"
SelectCommand="SELECT [EmpId], [EmpName], [EmpSalary], [IsActive] FROM [Emp]"
InsertCommand="INSERT INTO [Emp] ([EmpName], [EmpSalary], [IsActive]) VALUES (@EmpName, @EmpSalary,
@IsActive)"
UpdateCommand="UPDATE [Emp] SET [EmpName] = @EmpName, [EmpSalary] = @EmpSalary, [IsActive] = @IsActive
WHERE [EmpId] = @original_EmpId AND [EmpName] = @original_EmpName AND [EmpSalary] = @original_EmpSalary
AND [IsActive] = @original_IsActive"
DeleteCommand="DELETE FROM [Emp] WHERE [EmpId] = @original_EmpId AND [EmpName] = @original_EmpName
AND [EmpSalary] = @original_EmpSalary AND [IsActive] = @original_IsActive"
OldValuesParameterFormatString="original_{0}">
<DeleteParameters>
<asp:Parameter Name="original_EmpId" Type="Int32" />

1
Deccansoft Software Services DataBoundControls
<asp:Parameter Name="original_EmpName" Type="String" />
<asp:Parameter Name="original_EmpSalary" Type="Decimal" />
<asp:Parameter Name="original_IsActive" Type="Boolean" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="EmpName" Type="String" />
<asp:Parameter Name="EmpSalary" Type="Decimal" />
<asp:Parameter Name="IsActive" Type="Boolean" />
<asp:Parameter Name="original_EmpId" Type="Int32" />
<asp:Parameter Name="original_EmpName" Type="String" />
<asp:Parameter Name="original_EmpSalary" Type="Decimal" />
<asp:Parameter Name="original_IsActive" Type="Boolean" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="EmpName" Type="String" />
<asp:Parameter Name="EmpSalary" Type="Decimal" />
<asp:Parameter Name="EmpName" Type="String" />
<asp:Parameter Name="EmpSalary" Type="Decimal" />
<asp:Parameter Name="IsActive" Type="Boolean" />
</InsertParameters>
</asp:SqlDataSource>

2. Drag and Drop GridView on the Form and set its DataSourceID Property.
3. Right Click Select Smart Tag and Check Enable Editing, Enable Selection, Enable Deleting, Enable Paging and Enable
Sorting.

<asp:GridView ID="gvEmp" runat="server" AutoGenerateColumns="False" DataKeyNames="EmpId" AllowSorting="True"


DataSourceID="sdsEmp" EmptyDataText="There are no data records to display." AllowPaging="True" >
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowSelectButton="True" />
<asp:BoundField DataField="EmpId" HeaderText="EmpId" ReadOnly="True" SortExpression="EmpId" />
<asp:BoundField DataField="EmpName" HeaderText="EmpName" SortExpression="EmpName" />
<asp:BoundField DataField="EmpSalary" HeaderText="EmpSalary" SortExpression="EmpSalary" />
<asp:CheckBoxField DataField="IsActive" HeaderText="IsActive" SortExpression="IsActive" />
</Columns>
</asp:GridView>

4. Run the WebForm and See the output.


5. Handle SelectedIndexChanged event of GridView

Protected Sub gvEmp_SelectedIndexChanged(. . .) Handles gvEmp.SelectedIndexChanged


' Test the Followin line with DataKeyNames = “EmpId"
Response.Write(gvEmp.SelectedValue)

Response.Write(gvEmp.SelectedDataKey.Value) ‘This Writes SelectedRows EmpId to the browser.


‘Test the following line with DataKeyNames = “EmpId, EmpName"
Response.Write(gvEmp.SelectedDataKey.Values("EmpName"))

'Dim ind As Integer


'ind = gvEmp.SelectedIndex
'Dim ename As String
'ename = gvEmp.DataKeys(ind)("EmpName") ‘Gets EmpName of row with index ind.
'Response.Write(ename)

'Dim gvr As GridViewRow = gvEmp.SelectedRow


'Response.Write(gvr.Cells(2).Text) ‘Gets the Text of the third cell (BoundField only) of a given Row in GridView.
CheckBox chk = CType(gvr.Cells(4).Controls(0),CheckBox)
Response.Write(chk.Checked.ToString())
End Sub

• Commands for which handlers / functionality is predefined: Select, Delete, Edit, Update, Cancel, New, Insert
• We can add custom commands to the gridview by adding ButtonField to the Columns collection.

2
Deccansoft Software Services DataBoundControls
Steps for adding Custom Commands to the GridView:
• Add a ButtonField to the GridView.
• Set its CommandName and Text Properties.
• Handle the RowCommand event of GridView
6. Add the following line in between <Columns> tag in GridView
<asp:ButtonField ButtonType="Button" CommandName="custom" HeaderText="Custom" Text="Custom" />

7. Handle RowCommand event of GridView.


Protected Sub gvEmp_RowCommand(. . .) //Used for handling all the custom commands in the grid view.
If (e.CommandName = "custom") Then
Dim indRow As Integer = Convert.ToInt32(e.CommandArgument)
Dim gvr As GridViewRow = gvEmp.Rows(indRow)
Response.Write(gvr.Cells(1).Text)
End If
or 'If (e.CommandName = "Custom") Then
'Dim empid As Integer
'Dim ind As Integer = Convert.ToInt32(e.CommandArgument);
'empid =DirectCast(gvEmp.DataKeys(ind)("EmpId"),Integer);
'Response.Write(empid);
'End If
End Sub

8. Adding HyperlinkField to the Grid.


<asp:HyperLinkField DataTextField="EmpName" DataNavigateUrlFields="EmpId,EmpName"
DataNavigateUrlFormatString="EmpDetails.aspx?EmpId={0}& EmpName={1}" Target="_blank" />

Note: We can set either Text (constant value)or DataTextField (DataField Name) property.

9. Image Field: It is used to display the image of the field.


<asp:ImageField DataImageUrlField="EmpName" DataImageUrlFormatString="EmpImages\{0}.jpg"
DataAlternateTextField="EmpName" DataAlternateTextFormatString="Name: {0}" />

10. Add another SqlDataSource to the WebForm. This time Set a where condition. In Add Where Clause dialog set Column as
EmpId, Operator as =, Source as Control, Control Id as gvEmp and and Click on Add Button.

<asp:SqlDataSource ID="dsEmpFiltered" runat="server" ConnectionString="<%$ ConnectionStrings:csMSNET %>"


DeleteCommand="DELETE FROM [Emp] WHERE [EmpId] = @original_EmpId "
InsertCommand="INSERT INTO [Emp] ([EmpId], [EmpName], [EmpSalary]) VALUES (@EmpId,@EmpName, @EmpSalary)"
SelectCommand="SELECT [EmpId], [EmpName], [EmpSalary] FROM [Emp] WHERE ([EmpId] = @EmpId)"
UpdateCommand="UPDATE [Emp] SET [EmpName] = @EmpName, [EmpSalary] = @EmpSalary
WHERE [EmpId] = @original_EmpId”>
<SelectParameters>
<asp:ControlParameter ControlID="gvEmp" DefaultValue="-1"
Name="EmpId" PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
<DeleteParameters>
<asp:Parameter Name="original_EmpId" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="EmpName" Type="String" />
<asp:Parameter Name="EmpSalary" Type="Decimal" />
<asp:Parameter Name="original_EmpId" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="EmpId" Type="Int32" />
<asp:Parameter Name="EmpName" Type="String" />
<asp:Parameter Name="EmpSalary" Type="Decimal" />
</InsertParameters>
</asp:SqlDataSource>

11. Add DetailsView to the WebForm and set its DataSourceId property to “dsEmpFiltered”
<asp:DetailsView ID="dvEmp" runat="server" AutoGenerateRows="False" CellPadding="4"
DataKeyNames="EmpId" DataSourceID="dsEmpFiltered"

3
Deccansoft Software Services DataBoundControls
GridLines="None">
<Fields>
<asp:BoundField DataField="EmpId" HeaderText="EmpId" ReadOnly="True" SortExpression="EmpId" />
<asp:BoundField DataField="EmpName" HeaderText="EmpName" SortExpression="EmpName" />
<asp:BoundField DataField="EmpSalary" HeaderText="EmpSalary" SortExpression="EmpSalary" />
<asp:CommandField ShowEditButton="True" ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
12. Handle ModeChanged event of DetailsView.
Protected Sub dvEmp_ModeChanged(. . .) Handles dvEmp.ModeChanged
If (dvEmp.CurrentMode == DetailsViewMode.ReadOnly) Then
gvEmp.Enabled = true;
Else
gvEmp.Enabled = false;
End If
End Sub

13. Handle ItemInserted event of DetailsView


Protected Sub dvEmp_ItemInserted(. . .) Handles dvEmp.ItemInserted
gvEmp.SelectedIndex = gvEmp.Rows.Count – 1
If (e.Exception IsNot Nothing)
lblError.Text = e.Exception.Message;
e.ExceptionHandled = True;
End If
End Sub
14. Add the following line to the SelectedIndexChanged event handler of GridView
dvEmp.ChangeMode(DetailsViewMode.ReadOnly)

Template Field: When ever any kind of customization is needed to a column or field, convert it into a TemplateField.
Rigthclick on GridViewÆ Show Smart Tag ÆClick on Edit Columns Æ Select the ColumnName Æ Click on the
hyperlink(convert this field into a TemplateField)
RightClick Æ EditTemplate Æ Select the Template
RightClick on the control (which you want to customize) Æ Click on DataBindings Æ Select the Properties (on the left hand side)
and provide the binding expression on the right hand side.
Bind (Two way Binding) ÆFetches the data and changes made to it is reflected
Eval (One way Binding) ÆIt just Fetches the data , changes made to it are not reflected

15. In DetailView convert the IsActive field to Templetefield


<asp:TemplateField HeaderText="IsActive" SortExpression="IsActive">
<ItemTemplate>
<asp:Label ID="lblIsActive" runat="server" Text='<%# GetYesOrNo(Eval("IsActive")) %>'/>
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="chkIsActive" runat="server" Checked='<%# IsEmpActive(Eval("IsActive")) %>' />
</EditItemTemplate>
<InsertItemTemplate>
<asp:CheckBox ID="chkIsActive" runat="server" Checked='<%# Bind("IsActive") %>' />
</InsertItemTemplate>
</asp:TemplateField>
Protected Function IsEmpActive(ByVal active As Object) As Boolean
If (IsDBNull(active)) Then
Return False
End If
Return Cbool(active)
End Function
Protected Function GetYesOrNo(ByVal value as object) as String
If (DBNull.Value == value) Then
Return "No"
ElseIf (CBool(value)) Then
Return "Yes"
Else
Return "No"
End Sub

4
Deccansoft Software Services DataBoundControls
Protected Sub dvEmp_ItemUpdating(sender as Object, e as DetailsViewUpdateEventArgs)
Dim chkIsActive as CheckBox =CType(dvEmp.FindControl("chkIsActive"), CheckBox)
e.NewValues("IsActive") = chkIsActive.Checked
End Sub
Note: e.NewValue collection should be used for setting values of those fields which are not updated using the DetailsView
and the value has to be set programatically.
16. In GridView add a new TemplateColumn for Delete. Now delete button will prompt the user before the row is deleted.
<asp:TemplateField>
<ItemTemplate>
<asp:Button CommandName="delete" runat="server" ID="btnDelete"
Text='<%#Eval("EmpName") %>'
OnClientClick="return confirm('Are you sure')" />
</ItemTemplate>
</asp:TemplateField>
Note: Any Control nested inside GridView cannot be directly used for programming

17. Steps for Calculating TotalSalary of a page:


a. In GridView Convert EmpSalary to Template Column
b. For GridView(Employee ) ShowFooter is set to true
c. Select the Column(EmpSalary) Æ RightClick Æ EditTemplate Æ EmpSalary
d. In the FooterTemplate place a label with Id lblTotalSalary
e. Handle RowDataBound event of gridview
f. Handle the RowDataBound event of the gridview.
Dim totalSalary as Decimal
Protected Sub gvEmp_RowDataBound(sender as Object, e as GridViewRowEventArgs)
If (e.Row.RowType = DataControlRowType.DataRow) Then
Dim drv As DataRowView
drv = CType(e.Row.DataItem, DataRowView)
totalSalary += CDec(drv("EmpSalary"))
If (CDec(drv("EmpSalary")) > 10000) Then
e.Row.ForeColor = System.Drawing.Color.Red
End If
If (e.Row.RowType == DataControlRowType.Footer)
Label lbl = CType(e.Row.FindControl("lblTotalSalary "),Label)
lbl.Text = totalSalary.ToString();
End if
End If
End Sub
Note: The above code also changes the ForeColor of Employees whose EmpSalary is greater than 10000.

18. Add FormsView to the Webform.


<asp:FormView ID="FormView1" runat="server" DataKeyNames="EmpId" DataSourceID="EmpDataSourceFiltered">
<ItemTemplate>
EmpId: <asp:Label ID="EmpIdLabel" runat="server" Text='<%# Eval("EmpId") %>'></asp:Label>
EmpName: <asp:Label ID="EmpNameLabel" runat="server" Text='<%# Eval("EmpName") %>'></asp:Label>
EmpSalary:<asp:Label ID="Label1" runat="server" Text='<%# Eval("EmpSalary") %>'></asp:Label><br />
<asp:LinkButton ID="EditButton" runat="server" CausesValidation="False" CommandName="Edit" ext="Edit"/>
<asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="False"
CommandName="Delete” Text="Delete"/>
<asp:LinkButton ID="NewButton" runat="server" CausesValidation="False" CommandName="New" Text="New" />
</ItemTemplate>
<EditItemTemplate>
EmpId: <asp:Label ID="EmpIdLabel1" runat="server" Text='<%# Eval("EmpId") %>'></asp:Label><br />
EmpName: <asp:TextBox ID="EmpNameTextBox" runat="server" Text='<%# Bind("EmpName") %>'/>
EmpSalary: <asp:TextBox ID="EmpSalaryTextBox" runat="server" Text='<%# Bind("EmpSalary") %>'/>
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True"
CommandName="Update" Text="Update"/>
<asp:LinkButton ID="UpdateCancelButton" runat="server" CausesValidation="False"
CommandName="Cancel" Text="Cancel"/>
</EditItemTemplate>
<InsertItemTemplate>
EmpId: <asp:TextBox ID="EmpIdTextBox" runat="server" Text='<%# Bind("EmpId") %>'/>
EmpName: <asp:TextBox ID="EmpNameTextBox" runat="server" Text='<%# Bind("EmpName") %>'/>

5
Deccansoft Software Services DataBoundControls
EmpSalary: <asp:TextBox ID="EmpSalaryTextBox" runat="server" Text='<%# Bind("EmpSalary") %>'/>
<asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True"
CommandName="Insert" Text="Insert"/>
<asp:LinkButton ID="InsertCancelButton" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel"/>
</InsertItemTemplate>
</asp:FormView>
DeptEmpGridViewDemo
Demo of using DropdownList in the column while the row is in edit more.
<asp:SqlDataSource ID="EmpDataSource"
SelectCommand="SELECT [EmpId], [EmpName], [EmpSalary], [DeptId] FROM [Emp]
UpdateCommand="UPDATE [Employee] SET [EmpName] = @EmpName, [EmpSalary] =
@EmpSalary, [DeptId] = @DeptId WHERE [EmpId] = @EmpId">
<UpdateParameters>
<asp:Parameter Name="EmpName" Type="String" />
<asp:Parameter Name="EmpSalary" Type="Decimal" />
<asp:Parameter Name="DeptId" Type="Int32" />
<asp:Parameter Name="EmpId" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>

<asp:GridView ID="gvEmp" DataKeyNames="EmpId” DataSourceId=” EmpDataSource”>


<Columns>
<asp:BoundField DataField="EmpId" HeaderText="EmpId" ReadOnly="True" SortExpression="EmpId" />
<asp:BoundField DataField="EmpName"HeaderText="EmpName" SortExpression="EmpName" />
<asp:BoundField DataField="EmpSalary" HeaderText="EmpSalary" SortExpression="EmpSalary" />
<asp:TemplateField HeaderText="DeptName">
<ItemTemplate>
<asp:Label ID="lblDept" runat="server" Text='<%# GetDeptName(Eval("DeptId")) %>' />
</ItemTemplate>
<EditItemTemplate>
<!-- The DropdownList is binded to Dept.DeptId column of the DeptDataSource -->
<asp:DropDownList ID="ddlDept" runat="server" DataSourceID="DeptDataSource"
DataTextField="DeptName" DataValueField="DeptId" SelectedValue='<%# Bind("DeptId") %>'>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
In DeptEmpGridViewDemo.aspx.cs
public partial class DeptEmpGridViewDemo : System.Web.UI.Page
{
DataSet ds=new DataSet(); //Used to store Department table data and is initialized in Page_Load
protected void Page_Load(object sender, EventArgs e)
{
SqlDataAdapter daDept = new SqlDataAdapter();
daDept.SelectCommand = new SqlCommand("select * from Department");
string cs = ConfigurationManager.ConnectionStrings["csMSNET"].ConnectionString
daDept.SelectCommand.Connection = new SqlConnection (cs);
daDept.Fill(ds, "Dept");
}
protected string GetDeptName(object id) // Is used while databinding with input as DeptId and returns DeptName.
{
DataRow[] drs = ds.Tables[0].Select("Deptid=" + id);
return drs[0]["DeptName"].ToString();
}
}
EmpDataList (DataListDemo)
Protected Sub dlEmp_EditCommand(. . .) Handles dlEmp.EditCommand
dlEmp.EditItemIndex = e.Item.ItemIndex
dlEmp.DataBind()

6
Deccansoft Software Services DataBoundControls
End Sub

Protected Sub dlEmp_UpdateCommand(. . .) Handles dlEmp.UpdateCommand


Dim empid As Integer, newempname As String, newempsalary As String, newisactive As Boolean
empid = CInt(dlEmp.DataKeys(e.Item.ItemIndex))

Dim txtName As TextBox


txtName = CType(e.Item.FindControl("txtEditEmpName"), TextBox)
newempname = txtName.Text

Dim txtSalary As TextBox


txtSalary = CType(e.Item.FindControl("txtEditEmpSalary"), TextBox)
newempsalary = txtSalary.Text

Dim chkIsActive As CheckBox


chkIsActive = CType(e.Item.FindControl("chkEditIsActive"), CheckBox)
newisactive = chkIsActive.Checked

Response.Write(empid & " " & newempname & " " & newempsalary & " " & newisactive)
‘Code to execute UPDATE Command

dlEmp.EditItemIndex = -1
dlEmp.DataBind()
End Sub

Protected Sub dlEmp_CancelCommand(. . .) Handles dlEmp.CancelCommand


dlEmp.EditItemIndex = -1
dlEmp.DataBind()
End Sub

Protected Sub dlEmp_DeleteCommand(. . .) Handles dlEmp.DeleteCommand


Dim empid As Integer
empid = CInt(dlEmp.DataKeys(e.Item.ItemIndex))
‘Code to execute DELETE Statement
dlEmp.DataBind()
End Sub

<asp:SqlDataSource ID="EmpDataSource" runat="server" ConnectionString = "<%$ ConnectionStrings:csMSNET %>"


SelectCommand="SELECT [EmpId], [EmpName], [EmpSalary], [IsActive] FROM [Emp]"/>

<asp:DataList ID="dlEmp" runat="server" DataKeyField="EmpId"


DataSourceID="EmpDataSource" RepeatColumns="3" RepeatDirection="Horizontal">
<ItemTemplate>
EmpId: <asp:Label ID="EmpIdLabel" runat="server" Text='<%# Eval("EmpId") %>'/><br />
EmpName: <asp:Label ID="EmpNameLabel" runat="server" Text='<%# Eval("EmpName") %>/'>
EmpSalary: <asp:Label ID="EmpSalaryLabel" runat="server" Text='<%# Eval("EmpSalary") %>'/>
IsActive: <asp:Label ID="IsActiveLabel" runat="server" Text='<%# Eval("IsActive") %>'/>
<asp:LinkButton ID="lnkEdit" CommandName="edit" runat="server" Text="Edit"/>
<asp:LinkButton ID="lnkDelete" CommandName="delete" runat="server" text="Delete"/>
<asp:LinkButton ID="lnkSelect" CommandName="select" runat="server" text="Select"/>
</ItemTemplate>
<EditItemTemplate>
EmpId: <asp:Label ID="EmpIdEditLabel" runat="server" Text='<%# Eval("EmpId") %>'></asp:Label><br />
EmpName: <asp:TextBox ID="txtEditEmpName" runat="server" Text='<%# Eval("EmpName") %>'/>
EmpSalary <asp:TextBox ID="txtEditEmpSalary" runat="server" Text='<%# Eval("EmpSalary") %>'/>
IsActive: <asp:CheckBox ID="chkEditIsActive" runat="server" Checked='<%# Eval("IsActive") %>'/>
<asp:LinkButton ID="lnkUpdate" CommandName="Update" runat="server" Text="Update"/>
<asp:LinkButton ID="lnkCancel" CommandName="Cancel" runat="server" text="Cancel"/>
</EditItemTemplate>
</asp:DataList>

Other Important Events of DataList: ItemCommand, ItemDataBound and ItemCreated.

7
Deccansoft Software Services – ASP.NET Security, Profile and WebParts

Steps for configuring SQL Server for Security in ASP.NET 2.0


Run the utility program aspnet_regsql.exe (from framework folder)

<configuration>
<connectionStrings>
<add name="csTestingDB" connectionString="data source=.\SQLEXPRESS;uid=sa;pwd=dss;database=DemoWebApp"
providerName="System.Data.SqlClient"/>
</connectionStrings>
<system.web>
<membership defaultProvider="SDSqlMembershipProvider">
<providers>
<add connectionStringName="csTestingDB" enablePasswordRetrieval="false"
name="SDSqlMembershipProvider" applicationName="/DemoWebApp" enablePasswordReset="true"
requiresQuestionAndAnswer="true" requiresUniqueEmail="false" passwordFormat="Hashed"
maxInvalidPasswordAttempts="5" minRequiredPasswordLength="7" minRequiredNonalphanumericCharacters="1"
passwordAttemptWindow="10" passwordStrengthRegularExpression=""
type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="SDSqlRoleProvider">
<providers>
<add connectionStringName="csTestingDB" applicationName="/DemoWebApp"
name="SDSqlRoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</roleManager>
</system.web>
</configuration>

Working with Profile Object

SetProfile.aspx GetProfile.aspx
RealName <asp:TextBox ID="txtRealName" runat="server"/> <asp:Button ID="btnGetProfile" runat="server"
Color <asp:TextBox ID="txtColor" runat="server"/> Text="Profile" />
Line1 <asp:TextBox ID="txtLine1" runat="server"/> Real Name: <asp:Label ID="lblRealName" runat="server">
Street <asp:TextBox ID="txtStreet" runat="server"/> Color: <asp:Label ID="lblColor" runat="server" />
City <asp:TextBox ID="txtCity" runat="server"/> Line1: <asp:Label ID="lblLine1" runat="server" />
<asp:Button ID="btnSetProfile" runat="server" Text="Set Profile" /> Street: <asp:Label ID="lblStreet" runat="server"/ >
City: <asp:Label ID="lblCity" runat="server"/>
SetProfile.aspx.vb GetProfile.aspx.vb
Protected Sub btnSetProfile_Click(. . .) Protected Sub btnGetProfile_Click.( . .)
Profile.RealName = txtRealName.Text lblRealName.Text = Profile.RealName
Profile.BackColor = Drawing.Color.FromName(txtColor.Text) lblColor.Text = Profile.BackColor.ToString()
Profile.Address.Line1 = txtLine1.Text lblLine1.Text = Profile.Address.Line1
Profile.Address.Street = txtStreet.Text lblStreet.Text = Profile.Address.Street
Profile.Address.City = txtCity.Text lblCity.Text = Profile.Address.City
End Sub End Sub

In Web.config
<profile enabled="true" defaultProvider="SDProfileProvider">
<providers>
<add name="SDProfileProvider" connectionStringName="csTestingDB" applicationName="/ DemoWebApp"
type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"/>
</providers>
<properties>
<add name="RealName" allowAnonymous="true"/>
1
Deccansoft Software Services – ASP.NET Security, Profile and WebParts

<add name="BackColor" type="System.Drawing.Color" allowAnonymous="true"


serializeAs="Binary"/>
<group name="Address">
<add name="Line1" type="System.String" allowAnonymous="true"/>
<add name="Street" type="System.String" allowAnonymous="true"/>
<add name="City" type="System.String" allowAnonymous="true"/>
</group>
</properties>
</profile>
WebParts
• Add a folder (WebPartsDemo).To the folder add a Webform and Web.Config. In Web.config deny access to annonymous users.
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
• From Web.Config.Comments (Framework folder) copy Webparts section and paste it in applications root directory Web.config.
• Change the ConnectionStringName and ProviderName, also set the defaultProvider
• Delete the Transformer section from Web.Config.
• Under authorization change “deny” to “allow”
• In the Webform drag and drop WebPartManager, change the ID to wpManager.
• Drag and Drop WebpartZone on the WebForm.
• Under WebPartZone add any control
Note: Every Control added is treated as one Webpart.

WebpartsDemo.aspx.vb
Protected Sub Page_Load() Handles Me.Load
If (Not IsPostBack) Then
For Each mode As WebPartDisplayMode In wpManager.SupportedDisplayModes
If (mode.IsEnabled(wpManager)) Then
Dim li As New ListItem(mode.Name)
ddlModes.Items.Add(li)
End If
Next
End If
End Sub
Protected Sub ddlModes_SelectedIndexChanged(. . .) Handles ddlModes.SelectedIndexChanged
wpManager.DisplayMode = wpManager.SupportedDisplayModes(ddlModes.SelectedValue)
End Sub
Protected Sub btnResetLayout_Click(. . .) Handles btnResetLayout.Click
wpManager.Personalization.ResetPersonalizationState()
End Sub
Protected Sub Page_PreRender(. . .) Handles Me.PreRender
lblCurrentScope.Text = wpManager.Personalization.Scope.ToString()
End Sub
Protected Sub btnToggleScope_Click(. . .) Handles btnToggleScope.Click
If (wpManager.Personalization.CanEnterSharedScope) Then
wpManager.Personalization.ToggleScope()
End If
End Sub

WebpartsDemo.aspx
<%@ Register Src="WPUserControl.ascx" TagName="WPUserControl" TagPrefix="uc1" %>

<asp:WebPartManager ID="wpManager" runat="server"/>


Current Scope: <asp:Label ID="lblCurrentScope" runat="server"></asp:Label>
<asp:Button ID="btnToggleScope" runat="server" Text="Toggle Scope" />

2
Deccansoft Software Services – ASP.NET Security, Profile and WebParts

Change Current Mode:<asp:DropDownList ID="ddlModes" runat="server" AutoPostBack="True"/>


]<asp:Button ID="btnResetLayout" runat="server" Text="Reset Layout" />
<asp:WebPartZone ID="WebPartZone1" runat="server">
<ZoneTemplate>
<asp:Button Title="Button" SubTitle="ST" ID="Button1" runat="server" Text="Button" />
<asp:Panel Title="Panel" ID="Panel1" runat="server" Height="50px" Width="125px">
<asp:RadioButton ID="RadioButton1" runat="server" GroupName="g1" Text="R1" />
<asp:RadioButton ID="RadioButton2" runat="server" GroupName="g1" Text="R2" />
<asp:RadioButton ID="RadioButton3" runat="server" GroupName="g1" Text="R3" />
</asp:Panel>
</ZoneTemplate>
</asp:WebPartZone>
<asp:WebPartZone ID="WebPartZone2" runat="server">
<ZoneTemplate>
<asp:DropDownList title="Dropdown" ID="DropDownList1" runat="server"/>
<uc1:WPUserControl ID="WPUserControl1" runat="server" /> <!-- UserControl as WebPart -->
</ZoneTemplate>
</asp:WebPartZone>
• PageCatalogPart is to restore all the closed WebParts which have been statically created
• DeclarativeCatalogPart is for adding WebParts dynamically to the zone at runtime
<asp:CatalogZone ID="CatalogZone1" runat="server">
<ZoneTemplate>
<asp:DeclarativeCatalogPart ID="DeclarativeCatalogPart1" runat="server">
<WebPartsTemplate>
<asp:Calendar ID="Calendar1" runat="server”></asp:Calendar>
</WebPartsTemplate>
</asp:DeclarativeCatalogPart>
<asp:PageCatalogPart ID="PageCatalogPart1" runat="server" />
</ZoneTemplate>
</asp:CatalogZone>
<asp:EditorZone ID="EditorZone1" runat="server">
<ZoneTemplate>
<asp:AppearanceEditorPart ID="AppearanceEditorPart1" runat="server" />
<asp:LayoutEditorPart ID="LayoutEditorPart1" runat="server" />
<asp:BehaviorEditorPart ID="BehaviorEditorPart1" runat="server" />
<asp:PropertyGridEditorPart ID="PropertyGridEditorPart1" runat="server" />
</ZoneTemplate>
</asp:EditorZone>

Types of Scopes:
Shared Scope: Default layout for all users
User Scope: Layout for a particular user
In Shared Scope the layout created becomes the default layout for all users unless they change the layout for themselves in UserScope

In web.config
<webParts>
<personalization>
<authorization>
<allow users="*" verbs="enterSharedScope"/>
</authorization>
</personalization>
</webParts>
<anonymousIdentification enabled="true"/>

3
Deccansoft Software Services – ASP.NET WebServices
Distributed Computing Architecture
Client Process Server Process

Actual
Client Proxy Stub Object

o Proxy is a Client Side representative of the Actual object. It implements the same set of interfaces as the actual object
implements.
o When the client requests for an instance of a remote object, the underlying services (Framework) creates the actual
object in the server process and the proxy in the client process, the client gets the reference to the local proxy object.
o Along with the actual object a “stub” object is created on server. The proxy and stub are connected with each other over
the socket and communicates with each other using a common protocol
o Whenever the client calls the method of the proxy, the implementation in Proxy serializes all the parameters of the
method and transports them to Stub i.e. proxy marshals the request to stub.
o On Server, Stub deserializes the request and passes the references of the objects as parameters to the actual method in
actual object.

SUN (Stanford University Network – RMI (Remote Method Invocation) - JRMP(Java RMI Protocol)
OMG (Object Management Group) – CORBA Common Object Request Broker Arch. -IIOP (Internet Interoperable Protocol
MS (Microsoft) - DCOM (Distributed Component Object Model) - DEC – Object RPC(Distributed Computing Environment)

Problem: Because the proxy and the stub are tightly coupled to each other they must use the common protocol for
communication. As the protocols used by RMI, COBRA and DCOM are native protocols they lack Interoperability.

WebService:
A WebService is a business object running on a middle tier and providing its functionality to any type of application using
“SOAP” (Simple Object Access Protocol) protocol.

SOAP = XML + HTTP. SOAP is a specification by W3C.

In .Net WebSevices are managed by ASP.NET Framework. They are mostly used for developing B-B (Business to Business)
services/application.

WSDL (Web Service Description Language):


It is an XML based document containing complete information of the webservice including methods and their parameters,
the URL etc...
For every webservice developed the corresponding WSDL document is distributed to the clients. The clients using a native
utility program generates a proxy class from a WSDL document.

File Æ New Web Site Æ ASP.NET Web Service


Rename Service.asmx to DemoService.asmx

In DemoService.asmx:

<%@ WebService Language="C#" CodeBehind="~/App_Code/DemoService.cs" Class="DemoService" %>

Note: All the methods of a webservice class to be used by the clients on internet must be marked as “WebMethod” (
attribute).
[WebMethod]
public int Add(int a, int b)
{
return a + b;
}

o Every SOAP request and response are made up of SOAPEnvelope. SOAPEnvelope has SOAPHeader, SOAPBody,
SOAPFault.
o SOAP always uses Http Post method and the SOAPEnvelope is submitted as MessageBody.

1
Deccansoft Software Services – ASP.NET WebServices
o A Webservice developed in .Net can be used by an Http Client also. Here the method name is submitted as the PathInfo
and the parameters are posted as a string of Name-Value pairs.
http:// ServerName/ApplicationName/ DemoService.asmx/ MethodName
POST /SepWebServices/Service.asmx HTTP/1.1
Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/Add"

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


<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<Add xmlns="http://tempuri.org/">
<a>int</a>
<b>int</b>
</Add>
</soap:Body>
</soap:Envelope>

HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length

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


<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<AddResponse xmlns="http://tempuri.org/">
<AddResult>int</AddResult>
</AddResponse>
</soap:Body>
</soap:Envelope>

Note: To view the WSDL document we can use the following URL
http://localhost/SepWebServices/Service.asmx?wsdl
Client Application: (In New Instance of VS.NET)
File Æ New Project Æ Windows Application
In the Solution Explorer Æ References Æ Right Click Æ Add Web Reference Æ In URL (give the Url of Web Service) Æ
Click on Go

Web reference name Æ localhost (Generally name of domain on which the webservice is hosted is used)Æ Click on Add
Reference
Note: When a WebService reference is added in VS.Net that is using add Web reference it automatically creates a proxy
class in the current project using a utility program called as WSDL.EXE. The same can be viewed by opening the file
Reference.cs. (Before this click on Show All Files in Solution Expolorer).

private void btnDemo_Click(object sender, EventArgs e)


{
localhost.DemoService ds = new localhost.DemoService();
MessageBox.Show(ds.Add(20, 50).ToString());
}

Note:

Working with PassByValue and PassByReference:

Unless it is pass by reference changes made to data will not be reflected on client in WebMethod.

2
Deccansoft Software Services – ASP.NET WebServices
In Demoservice add WebMethod

[WebMethod] [WebMethod] public class CA


public void Foo(int a, ref int b) public void Foo2( CA a1, ref CA a2) {
{ { public int m1;
a++; a1.m1++; }
b++; a2.m1++;
} }

In Client Application :
Note: After making any changes to the webservice, to reflect them in client application: Right Click on NameSpace of
WebService (Localhost) and Select Update Web Reference.
private void btnFoo_Click(object sender, EventArgs e) private void btnFoo2_Click(object sender, EventArgs e)
{ {
int m = 10; CA ma1 = new CA();
int n = 10; CA ma2 = new CA();
DemoService ds = new DemoService(); DemoService ds = new DemoService();
ds.Foo(m, ref n); ds.Foo2(ma1, ref ma2);
MessageBox.Show(m + " " + n); MessageBox.Show(ma1.m1 + " " + ma2.m1);
} }

o If the parameter of the web method is declared as “ByVal” (pass by value) then the reference type of argument is
serialized and transported only from client to server. Hence changes made to the paremeter are not reflected in the
client.
o If the parameter of the web method is declared as “ByRef” (pass by reference) then the reference type of argument is
serialized and transported in both the direction i.e from client to server and server to client. Hence changes made the to
parameter in the web method are also reflected in the client.

Note: In content of a WebMethod the behavior of the parameters is same for both class and structure. The behavior is like
value type not reference type.

Working with SoapHeader


• Because Soap depends on Http protocol the webservices are stateless objects.
• SoapHeader can be used for passing certain additional data to a WebMethod. Once a SoapHeader is associated with the
proxy on the client, the proxy automatically includes the data along every method called by it on webservice.

Step1: Write a class inheriting from SoapHeader


public class UserInfoHeader : SoapHeader
{
public string username, password;
}
Step2: Within Webservice class declare a public variable of custom SoapHeader type
public UserInfoHeader ui;
Step3: Attach a SoapHeader to a WebMethod using SoapHeader attribute.
SoapHeaderDirection.InOut means SoapHeader is exchanged in both the directions.
Step4: In the method we can use the reference variable
//[SoapHeader("ui",Direction=SoapHeaderDirection.InOut)]
[SoapHeader("ui")]
[WebMethod]
public int Add(int a,int b)
{
if (ui.username != ui.password)
throw new ApplicationException("UserName and Password are not correct");
return a+b;
}
Note: Invoke the webservice in the web browser and see how the SOAP Envelope of a given method with SOAP Header has
changed.
if a member of SOAP Header class is used for managing state between calls to the multiple webmethods by the client, then
the direction of the SOAP Header must be given as “InOut”.

Step5: In Client - Code for attaching SoapHeader to the proxy


private void btnSoapHeader_Click(object sender, EventArgs e)
{
3
Deccansoft Software Services – ASP.NET WebServices
DemoService ds = new DemoService();
UserInfoHeader ui = new UserInfoHeader();
ui.username = "a";
ui.password = "a";
ds.UserInfoHeaderValue = ui;// attaching header to proxy
MessageBox.Show(ds.Add(10, 20).ToString());
}

Asynchronous call to the WebMethod


If the webmethod is called asynchronously the client application never remains unresponsive while proxy has called and is
waiting for the return value of actual webservice webmethod.
For every WebMethod “X” in a webservice the following are added to or generated along with the proxy class.
The method X
The method XAsync
The event XCompleted
Add the delegate XCompletedEventHandler
A class XCompletedEventArgs

private void btnSoapHeader_Click(object sender, EventArgs e)


{
DemoService ds = new DemoService();
ds.AddAsync(1, 2); //Calling the method Asynchronously
ds.AddCompleted += new AddCompletedEventHandler(ds_AddCompleted);
//In VB.Net: AddHandler ds.AddCompleted ,New AddCompletedEventHandler(addressof ds_AddCompleted);
MessageBox.Show("Continue…");
}
void ds_AddCompleted(object sender, AddCompletedEventArgs e)
{ //This method is called by proxy when the actual method returns.
MessageBox.Show(e.Result.ToString());
}
Note: For Asynchronous call to a web method, we don’t have to make any changes to the webservice or its web method.
Security in WebService
WebServices supports only WindowsAuthentication because they don’t have any UserInterface and Forms / Passport
Authentication requires GUI.
Add a web.config to the DemoService and include the following code
<system.web>
<authentication mode="Windows" />
<authorization>
<deny users="?"/>
</authorization>
</system.web>
In IIS for the webservice vittual directory either set Integrated Windows / Basic Authentication.
[WebMethod]
public string SayHello()
{
return "Hello" +" "+ User.Identity.Name;
}
In ClientApplication add the following code
private void Security_Click(object sender, EventArgs e)
{
DemoService ds = new DemoService();
//ds.Credentials = System.Net.CredentialCache.DefaultCredentials;
//Code to explicitly set the username and password in the request.
System.Net.CredentialCache cc = new System.Net.CredentialCache();
System.Net.NetworkCredential nc = new System.Net.NetworkCredential(txtUsername, txtPassword.Text);
cc.Add(new Uri(ds.Url), "basic", nc);
cc.Add(new Uri(ds.Url), "NTLM", nc); //if NTLM doesn’t work then give “Negotiate”
ds.Credentials = cc;
MessageBox.Show(ds. SayHello());
}

4
Deccansoft Software Services – ASP.NET WebServices
System.Net.CredentialCache.DefaultCredentials includes the identity of the client using which we have logged on to the
client machine.

5
Deccansoft Software Services – MS.NET Remoting

Case 1
Server Side
1. Create a new class library project (Hello Library) with solution name as RemotingDemo.
2. Add to the Project a remote object class i.e. a class inherited from MarshalByRefObject.
3. Every Remote object must inherit from MarshalByRefObject.

Public Class HelloObject


Inherits MarshalByRefObject
Dim count As Integer
Public Function SayHello(ByVal name As String) As String
Count += 1
Return "Hello" & name & "Count:" & count
End Function
Public Sub New()
Console.WriteLine("HelloObject created")
End Sub
End Class

4. To the current solution add a Console application (Server)


5. Add to it the reference System.Runtime.Remoting (using MS.NET Tab) and Hellolibrary(Using Projects Tab)
Note: The Remote object is included in the classlibrary project so that the same library can be shared by server and client. On
client it is used by the remoting framework for reading its type Metadata and constructing the proxy class from it.
Types of Channels
• Http Channel is firewall friendly but slow
• Tcp Channel is faster but not firewall friendly
• Icp Channel can be used if both client and server are on same machine.

Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels
Imports system.Runtime.Remoting.Channels.Http
Imports System.Runtime.Remoting.Channels.Tcp
Imports HelloLibrary
Class program
Shared Sub Main()
Dim tc As New TcpChannel(1122)
Dim hc As New HttpChannel(1123)
ChannelServices.RegisterChannel(tc, False)
ChannelServices.RegisterChannel(hc, False)
RemotingConfiguration.RegisterWellKnownServiceType(GetType(HelloObject), "HO",
WellKnownObjectMode.Singleton)
Console.WriteLine("Server Started")
System.Threading.Thread.CurrentThread.Join()
End Sub
End Class

Client Side
1. Start New Studio Instance
2. Create a new Console Application.
3. Add the reference HelloLibrary(using Browse Tab) and System.Runtime.Remoting (using MS.NET tab).

Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Channels
Imports system.Runtime.Remoting.Channels.Http
Imports System.Runtime.Remoting.Channels.Tcp
Imports HelloLibrary
Class Program
Shared Sub Main()

1
Deccansoft Software Services – MS.NET Remoting
Dim tc As New TcpChannel(0) ‘if ‘0’ is passed then randomly any free port number is used.
Dim hc As New HttpChannel(0)
ChannelServices.RegisterChannel(tc, False)
ChannelServices.RegisterChannel(hc, False)
RemotingConfiguration.RegisterWellKnownClientType(GetType(HelloObject), "http://localhost:1123/HO")
Dim ho As New HelloObject()
Console.WriteLine(ho.SayHello("Test1"))
Console.WriteLine(ho.SayHello("Test2"))
End Sub
End Class

Notes:
RemotingConfiguration.RegisterWellKnownServiceType(GetType(HelloObject), "HO",
WellKnownObjectMode.Singleton)
• The above line is used to register the “HelloObject” with the remoting framework identifying itself with a unique name
“HO”.
• If registered as Singleton an instance of it is created when the server receives the first method call request from the client
and the same object is used for all subsequent calls to the class is created for SingleCall a new instance is created for every
method called from the client i.e object behavious as stateless.
Note: Allways run server application before running client application

Case 2: Create a Copy of Case 1 Project


Client Activated Object : For every client a new instance is created on its first request and the same is used by that client for
all its subsequent requests.
One server can have only one ClientActivated Object and hence name is not required for it.
Server Main
Replace
RemotingConfiguration.RegisterWellKnownServiceType …..
With
RemotingConfiguration.RegisterActivatedServiceType(GetType(HelloObject))

Client Main
Replace
RemotingConfiguration.RegisterWellKnownClientType
With
RemotingConfiguration.RegisterActivatedClientType(GetType(HelloObject), "http://localhost:1122")
Dim ho As New HelloObject()
Console.WriteLine(ho.SayHello("Test1"))
Console.WriteLine(ho.SayHello("Test2"))

Case 3: Create a Copy of Case1 for wellknown and Case 2 for Client activated
Working with Configuration file
Server Side ApplicationConfig File – App.Config
<configuration>
<system.runtime.remoting>
<application>
<service>
<!--<wellknown type="HelloLibrary.HelloObject, HelloLibrary" objectUri="HO" mode="Singleton" />-->
<activated type="HelloLibrary.HelloObject, HelloLibrary"/>
</service>
<channels>
<channel ref="http" port="1123"/>
<channel ref="tcp" port="1122"/>
</channels>
</application>
</system.runtime.remoting>
</configuration>

2
Deccansoft Software Services – MS.NET Remoting
In Server Main:
Replace
RemotingConfiguration.RegisterActivatedServiceType
With
RemotingConfiguration.Configure("Server.exe.config", False)

Client Side Application Config File: App.Config


<configuration>
<system.runtime.remoting>
<application>
<client url="http://localhost:1123/" >
<!--<wellknown type="HelloLibrary.HelloObject, HelloLibrary" url="http://localhost:1123/HO" />-->
<activated type="HelloLibrary.HelloObject, HelloLibrary" />
</client>
<channels>
<channel ref="http" port="0"/>
<channel ref="tcp" port="0"/>
</channels>
</application>
</system.runtime.remoting>
</configuration>
In Client Main:
Replace
RemotingConfiguration.RegisterActivatedClientType
With
RemotingConfiguration.Configure("Client.exe.config", False)

Case 4: Create a copy of Case 1


Replacing Class with Interface in the HelloLibrary

In HelloLibrary
Public Interface IHelloObject
Function SayHello(ByVal name As String) As String
End Interface

Modify the class and move to server project:


Imports HelloLibrary
Public Class HelloObject
Inherits MarshalByRefObject
Implements IHelloObject
Dim count As Integer
Public Function SayHello(ByVal name As String) As String Implements IHelloObject.SayHello
count += 1
Return "Hello " & name & " Count: " & count
End Function
Public Sub New()
Console.WriteLine("Hello object created")
End Sub
End Class

In Client application replace


RemotingConfiguration.RegisterWellKnownClientType(GetType(HelloObject), "http://localhost:1123/HO")
with
Dim ho As IHelloObject
ho=Activator.GetObject(GetType(IHelloObject), "http://localhost:1123/Ho")

Remove the previous reference to classlibrary and Add the reference to the library again.

3
Deccansoft Software Services – MS.NET Remoting
Case 5: Create a copy of Case 1
Asynchronously Calling Remote Method
1. Based on the method to be called Asynchronously using its signature declare a delegate
2. Using the same method declare an instance of delegate
3. Declare BeginInvoke and EndInvoke

Delegate Function SayHelloHandler(ByVal name As String) As String

Class Client
Shared Sub Main()
Dim tc As New TcpChannel(0)
Dim hc As New HttpChannel(0)
ChannelServices.RegisterChannel(tc, False)
ChannelServices.RegisterChannel(hc, False)

RemotingConfiguration.RegisterWellKnownClientType(GetType(HelloObject), "http://localhost:1123/HO")
Dim ho As New HelloObject()
'Following is syncronous call
'Console.WriteLine(ho.SayHello("Test"))

Dim delSH As New SayHelloHandler(AddressOf ho.SayHello)

Dim ar As IAsyncResult
'Following is Asyncronous call
ar = delSH.BeginInvoke("Test", Nothing, Nothing)
Console.WriteLine("Continue...")
While (Not ar.IsCompleted)
Console.WriteLine("Waiting...") ‘Can perform any other operation
Threading.Thread.Sleep(100)
End While
Dim res As String
res = delSH.EndInvoke(ar)
Console.WriteLine(res)
End Sub
End Class

Note: The code in server application does not need to be changed.

Working with CrystalReport

To the Project Æ Add a new Item Æ DataSet


To the Project Æ Add a new Item Æ CrystalReport (Emp.rpt)
Create a Typed DataSet.
Create rpt file using Typed DataSet
On the WebForm drag and drop CrystalReportViewer
For it create a new ReportSource with an appropriate filename
Path of file should be corrected
Write the following code in Page_Load

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load


Dim dta As New EmpDataSetTableAdapters.EmpTableAdapter
Dim dsEmp As New EmpDataSet
dta.Fill(dsEmp.Emp)
Dim employeeReport As New ReportDocument
employeeReport.Load(MapPath("CrystalReport1.rpt"))
employeeReport.SetDataSource(dsEmp.Tables(0))
CrystalReportViewer1.ReportSource = employeeReport
End Sub

4
Deccansoft Software Services – ASP.NET Email
Code to Send Mail Programatically

using System.Net.Mail;
using System.Net;

public enum MailFormat


{
Html = 1,
Text = 0,
}

public class EmailUtil


{
public static void SendMail(string from, string To, string cc, string bcc, System.Net.Mail.MailPriority priority,
string subject, string body, bool bodyFormat, System.Text.Encoding bodyEncoding, string attachment,
string SMTPServer, string SMTPUsername, string SMTPPassword)
{
MailMessage objMail;
objMail = new MailMessage(from, to);
if ((cc != ""))
objMail.CC.Add(cc);
if ((bcc != ""))
objMail.Bcc.Add(bcc);
objMail.Priority = priority;
objMail.Subject = subject;
objMail.IsBodyHtml = bodyFormat;
objMail.BodyEncoding = bodyEncoding;
objMail.Body = body;
if ((attachment != ""))
objMail.Attachments.Add(new Attachment(attachment));
SmtpClient objSmtpClient = null;
if ((SMTPServer != ""))
{
objSmtpClient = new SmtpClient(SMTPServer);
objSmtpClient.UseDefaultCredentials = false;
if (((SMTPUsername != "") && (SMTPPassword != "")))
{
NetworkCredential credential = new NetworkCredential(SMTPUsername, SMTPPassword);
objSmtpClient.Credentials = credential;
}
else
objSmtpClient.UseDefaultCredentials = true;
}
objSmtpClient.Send(objMail);
}
}
Deccansoft Software Services –ASP.NET AJAX

Defalt.aspx
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Ajax Demo</title>
<script type="text/javascript">
function btnGetTime_onclick()
{
var url="GetServerDateTime.aspx"
xmlHttp = GetXmlHttpObject(stateChanged)
xmlHttp.open("GET", url , true)
xmlHttp.send(null)
}
function stateChanged()
{
alert(xmlHttp.readyState)
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete")
alert(xmlHttp.responseText)
}
function GetXmlHttpObject(handler)
{
var objXmlHttp=null
if (navigator.userAgent.indexOf("MSIE")>=0)
{
var strName="Msxml2.XMLHTTP"
if (navigator.appVersion.indexOf("MSIE 5.5")>=0)
strName="Microsoft.XMLHTTP"
try
{
objXmlHttp=new ActiveXObject(strName)
objXmlHttp.onreadystatechange=handler
return objXmlHttp
}
catch(e)
{
alert("Error.... " + e)
return null
}
}
if (navigator.userAgent.indexOf("Mozilla")>=0)
{
objXmlHttp=new XMLHttpRequest()
objXmlHttp.onload=handler
objXmlHttp.onerror=handler
return objXmlHttp
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<input id="btnGetTime" type="button" value="Get Server Date & Time"
onclick="return btnGetTime_onclick()" /><br />
</form>
</body>
</html>

GetServerDateTime.aspx
Partial Class GetServerDateTime
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

1
Deccansoft Software Services –ASP.NET AJAX

Response.Clear()
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.Write(System.DateTime.Now.ToString())
Response.End()
'Page.MaintainScrollPositionOnPostBack = True
End Sub
End Class

Using AjaxPro Component.

Step 1: Download the latest Ajax.NET Professional files from www.schwarz-interactive.de


Step 2: Add a reference to the AjaxPro.2.dll
Step 3:Add following lines to your web.config:

<configuration>
<system.web>
<httpHandlers>
<add verb="POST,GET" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory, AjaxPro.2"/>
</httpHandlers>
</system.web>
</configuration>
Step 4: Now, you have to mark your .NET methods with an AjaxMethod attribute:
Partial Class _Default
Inherits System.Web.UI.Page
<AjaxPro.AjaxMethod()> _
Public Function GetServerTime() As Date
Return DateTime.Now
End Function
‘To use the .NET method on the client-side JavaScript you have to register the methods,
‘this will be done to register a complete class to Ajax.NET:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
AjaxPro.Utility.RegisterTypeForAjax(GetType(_Default))
End Sub
End Class

Step 5: Add button to the aspx page.


<input type=”button” OnClick="getServerTime();" Value="GetServerTime" />

Step 6: Add the following script to default.aspx page (in head section)
<script language="javascript">
function getServerTime()
{
_Default.GetServerTime(getServerTime_callback); // asynchronous call
}
// This method will be called after the method has been executed and the result has been sent to the client.
function getServerTime_callback(res)
{
alert(res.value);
}
</script>

2
Deccansoft Software Services SQL Cache Dependency
SQL Cache Invalidation:
1. Polling Based Invalidation
2. Callback Invalidation or Notification based Invalidation

Polling based Invalidation:


Step1: Go to command prompt via Microsoft Visual Studio
Run the command for enabling the database for SQL cache dependency
aspnet_regsql.exe -S “.\sqlexpress” -E -d “MSNET” –ed

Step2: Command for enabling the table for SQL cache dependency
aspnet_regsql.exe -S “.\sqlexpress” -E -d “MSNET” –t “Emp” -et

Step3: In web.config add the following code


<system.web>
<caching>
<sqlCacheDependency enabled="true" pollTime="2000">
<databases>
<add name="MSNETDB" connectionStringName="csMSNET"/>
</databases>
</sqlCacheDependency>
</caching>
</system.web>

Step4: Add the following directive to the page


<%@ OutputCache Duration="9999" VaryByParam="none" SqlDependency="MSNETDB:Emp" %>
Or
For caching only the data fetched by the SqlDataSource
<asp:SqlDataSource CacheDuration="Infinite" EnableCaching="true" SqlCacheDependency="MSNETDB:Empl"

Notification based Caching:


Step1: Run the command for enabling the database for SQL cache dependency
aspnet_regsql -S “.\sqlexpress” -E -d “MSNET” –ed

Step2: In Global.asax add the following code


void Application_Start(object sender, EventArgs e)
{
System.Data.SqlClient.SqlDependency.Start
(System.Configuration.ConfigurationManager.ConnectionStrings["csMSNET "].ConnectionString);
}
Step3: Add the following directive to the page
<%@ OutputCache Duration="99999" VaryByParam="none" SqlDependency="CommandNotification" %>

Note:
• All Table Names and Column Names are CaseSensitive and table must be fully qualified with the owner name i.e.
dbo.Emp
• In commands * should not be used, column names must be mentioned explicitly.
Or
For caching only the data fetched by the SqlDataSource
<asp:SqlDataSource CacheDuration="Infinite" EnableCaching="true" SqlCacheDependency="CommandNotification”>

You might also like