Professional Documents
Culture Documents
heading of
<HEAD>Contains elements describing the
<HEAD> HTML Nothing will show
document</HEAD>
document
Example 5:
Example 1: Example 1:
</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
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 3:
</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>
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.
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.
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.
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"
• 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.
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.
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.
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.
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.
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
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.
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.
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.
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.
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>(. . .)
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.
page1.aspx
Page1.aspx Page1.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
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.
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
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.
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
HyperLink: <A href=”Url”… - Used for linking to another page of the webapplication and not posting the form.
Properties: Text, ImageUrl, NavigateUrl, Target, OnClientClick
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
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
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
}
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.
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>
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>
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 />
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>
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”%>
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>
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.
Note: If MasterPage is selected for a child page “MasterPageFile” attribute is added to the Page Directive of the Child page
Step 1: HelloControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="HelloControl.ascx.cs"
Inherits="UserControlDemo_HelloControl" %>
2
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
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.
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 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”)
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.
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.
//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” %>
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();
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.
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.
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.
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
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" />
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
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.
1
Deccansoft Software Services – ASP.NET web.config, Custom Errors, URL Rewriting, Trace
<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.
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>
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.
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 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.
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.
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
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
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
--------------------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.
--------------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.
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>
<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).
/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();
}
/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.
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
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.
• 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" />
Note: We can set either Text (constant value)or DataTextField (DataField Name) property.
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.
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
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
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
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>
6
Deccansoft Software Services DataBoundControls
End Sub
Response.Write(empid & " " & newempname & " " & newempsalary & " " & newisactive)
‘Code to execute UPDATE Command
dlEmp.EditItemIndex = -1
dlEmp.DataBind()
End Sub
7
Deccansoft Software Services – ASP.NET Security, Profile and WebParts
<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>
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
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" %>
2
Deccansoft Software Services – ASP.NET Security, Profile and WebParts
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.
In .Net WebSevices are managed by ASP.NET Framework. They are mostly used for developing B-B (Business to Business)
services/application.
In DemoService.asmx:
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"
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: length
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).
Note:
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
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.
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.
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
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)
In HelloLibrary
Public Interface IHelloObject
Function SayHello(ByVal name As String) As String
End Interface
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
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 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
4
Deccansoft Software Services – ASP.NET Email
Code to Send Mail Programatically
using System.Net.Mail;
using System.Net;
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
<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 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
Step2: Command for enabling the table for SQL cache dependency
aspnet_regsql.exe -S “.\sqlexpress” -E -d “MSNET” –t “Emp” -et
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”>