06 Asp
06 Asp
with ASP.NET
object-oriented
event-based
allows rapid application development (RAD)
rich library of GUI elements (web controls)
users can define their own GUI elements
separation of layout (HTML) and logic (C#)
efficient (compiled server scripts)
automatic state management
authorisation / authentication
...
2
ASP.NET
Simple Dynamic Web Pages
Web Forms
Event Handling
Web Controls
Validators
User Controls
Custom Controls
State Management
Configuration of ASP.NET
Working with Visual Studio .NET
Static Web Pages
Pure HTML
My.html
<html> Request("My.html")
<head> Browser Server
<title>Simple HTML page</title> (IIS)
</head> Response(My.html)
<body>
<h1>Welcome</h1>
You are visitor number 1! My.html
</body>
</html>
4
Dynamic ASPX Pages
Computed values can be inserted into HTML code
Counter.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.IO" %>
<html>
<head> <title>Page counter</title> </head>
<body>
<h1>Welcome</h1>
You are visitor number <%
FileStream s = new FileStream("c:\\Data\\Counter.dat", FileMode.OpenOrCreate);
int n;
try {
BinaryReader r = new BinaryReader(s);
n = r.ReadInt32();
} catch { n = 0; } // if the file is empty
n++;
s.Seek(0, SeekOrigin.Begin);
BinaryWriter w = new BinaryWriter(s);
w.Write(n); s.Close();
Response.Write(n);
%> !
</body>
</html>
Control Panel
> Administrative Tools
> Computer Management
accessible as
http://<site-url>/<virtualDirName>/myfile.aspx
6
What Happens Behind the Scene?
client
(browser)
page object
*.html
.NET framework
7
HTML Code Returned by the Server
Counter.aspx Returned HTML code
8
Code in Script Tags
<%@ Page Language="C#" %> Counter.aspx
<%@ Import Namespace="System.IO" %>
<html>
<head>
<title>Page counter</title>
<script Language="C#" Runat="Server">
int CounterValue() {
FileStream s = new FileStream("c:\\Data\\Counter.dat", FileMode.OpenOrCreate);
...
n = r.ReadInt32();
n++;
...
return n;
}
</script>
</head>
<body>
<h1>Welcome</h1>
You are visitor number <%=CounterValue()%> !
</body>
</html>
9
Code Behind
Counter.aspx
<%@ Page Language="C#" Inherits="CounterPage" CodeFile="CounterPage.cs" %>
<html>
<head> <title>Page counter</title> </head>
<body>
<h1>Welcome</h1>
You are visitor number <%=CounterValue()%> !
</body>
</html>
CounterPage.cs
using System.IO;
11
Generated Page Class
System.Web.UI.Page
12
Generated Class Counter_aspx
namespace ASP {
using System.IO;
...
public class Counter_aspx : CounterPage {
private static bool __initialized = false;
private static ArrayList __fileDependencies;
public Counter_aspx() {
ArrayList dependencies;
if ((__initialized == false)) { ... }
}
public override string TemplateSourceDirectory {
get { return "/Samples"; }
}
private void __BuildControlTree(Control __ctrl) {
__ctrl.SetRenderMethodDelegate(new RenderMethod(this.__Render__control1));
}
private void __Render__control1(HtmlTextWriter __output, Control parameterContainer) {
__output.Write("\r\n<html>\r\n\t<head> <title>Page counter</title> </head>\r\n\t<body>\r\n\t\t" +
"<h1>Welcome</h1>\r\n\t\tYou are visitor number ");
__output.Write(CounterValue());
__output.Write(" !\r\n\t</body>\r\n</html>\r\n");
}
protected override void FrameworkInitialize() {
__BuildControlTree(this);
this.FileDependencies = __fileDependencies;
this.EnableViewStateMac = true; this.Request.ValidateInput();
}
...
}
} 13
ASP.NET
Simple Dynamic Web Pages
Web Forms
Event Handling
Web Controls
Validators
User Controls
Custom Controls
State Management
Configuration of ASP.NET
Working with Visual Studio .NET
HTML Forms (With CGI Scripts)
...
<body>
<form action="http://www.fake.com/cgi-bin/myprog" method="post">
<b>Balance:</b>
<input type="text" name="total" readonly value="0"> Euro<br>
<input type="text" name="amount">
<input type="submit" name="ok" value="Pay">
</form>
</body>
Problems
- CGI programming is tedious
- restricted to HTML elements
- must manage the state of text fields manually
when the page is sent back 15
Web Forms in ASP.NET
Adder.aspx
<%@ Page Language="C#" Inherits="AdderPage" CodeFile="Adder.aspx.cs"%>
<html>
<head><title>Account</title></head>
<body>
<form Runat="server">
<b>Balance:</b>
<asp:Label ID="total" Text="0" Runat="server"/> Euro<br><br>
<asp:TextBox ID="amount" Runat="server"/>
<asp:Button ID="ok" Text="Enter" Runat="server" />
</form>
</body>
</html>
16
Web Forms in ASP.NET
Adder.aspx
<%@ Page Language="C#" Inherits="AdderPage" CodeFile="Adder.aspx.cs"%>
<html>
<head><title>Account</title></head>
<body>
<form Runat="server">
<b>Balance:</b>
<asp:Label ID="total" Text="0" Runat="server"/> Euro<br><br>
<asp:TextBox ID="amount" Runat="server"/>
<asp:Button ID="ok" Text="Enter" OnClick="ButtonClick" Runat="server" />
</form>
</body>
</html>
Adder.aspx.cs
using System;
public partial class AdderPage : System.Web.UI.Page {
public void ButtonClick (object sender, EventArgs e) {
int totalVal = Convert.ToInt32(total.Text);
int amountVal = Convert.ToInt32(amount.Text);
total.Text = (totalVal + amountVal).ToString();
}
}
17
HTML Code Sent Back to the Browser
Counter.aspx HTML code that is sent back to the browser
<%@ Page Language="C#" <html>
Inherits="AdderPage" <head> <title>Account</title> </head>
CodeFile="Adder.aspx.cs"%> <body>
<html> <form name="_ctl0" method="post"
<head><title>Account</title></head> action="Adder.aspx" id="_ctl0">
<body> <input type="hidden" name="__VIEWSTATE"
<form Runat="server"> value="dDwxNTg0NTEzNzMyO3Q8O2w8aTwxP" +
<b>Balance:</b> "js+O2w8dDw7bDxpPDE+Oz47bDx0PHA8cDxs"+
<asp:Label ID="total" Text="0" "PFRleHQ7PjtsPDEwMDs+Pjs+Ozs+Oz4+Oz4+" +
Runat="server"/> Euro<br><br> "Oz7uOgbDI3uKWY/X5D1Fw8zmjTZkwg==" />
<asp:TextBox ID="amount" <b>Balance:</b>
Runat="server"/> <span id="total">100</span>
<asp:Button ID="ok" Euro<br><br>
Text="Enter" <input type="text" name="amount"
OnClick="ButtonClick" value="100" id="amount" />
Runat="server" /> <input type="submit" name="ok"
</form> value="Enter" id="ok" />
</body> </form>
</html> </body>
</html>
18
General Notation for Web Controls
<asp:ClassName PropertyName="value" ... Runat="server" />
Example
<asp:Label ID="total" Text="Hello" ForeColor="Red" Runat="server" />
public class Label: WebControl { All web control classes are in the
public virtual string ID { get {...} set {...} } namespace System.Web.UI
public virtual string Text { get {...} set {...} }
public virtual Color ForeColor { get {...} set {...} }
...
}
Alternative Notation
<asp:Label ID="total" ForeColor="Red" Runat="server" >
Hello
</asp:Label>
19
Advantages of Web Forms
• The page is an object
one can access all its properties and methods:
page.IsPostBack, page.User, page.FindControl(), ...
20
Web Controls (selection)
TextBox
Button DataGrid
RadioButton ...
CheckBox
21
Web Control Hierarchy
Control
ID
Page
Visible
22
ASP.NET
Simple Dynamic Web Pages
Web Forms
Event Handling
Web Controls
Validators
User Controls
Custom Controls
State Management
Configuration of ASP.NET
Working with Visual Studio .NET
Event-based Processing
mouse click
Client Server
24
Kinds of Events
Control Event When does the event occur?
all Init • after the control was created
Load • after the data that were sent by the
browser have been loaded into
the control
PreRender • before HTML code for this control
is generated
Unload • before the control is removed
from memory
Button Click when the button was clicked
TextBox TextChanged when the contents of the TextBox
changed
CheckBox CheckedChanged when the state of the CheckBox
changed
ListBox SelectedIndexChanged when a new item from the list has
been selected
25
Round Trip of a Web Page
TextBox
Click
Button
1. Creation
create page object and its controls
Client Server
26
Round Trip of a Web Page
TextBox Init
Click
Button Init
2. Initialisation
- raise Init events
Client Server
27
Round Trip of a Web Page
TextBox Load
Click
Button Load
3. Loading
- load controls with the values that the user
has entered (page state)
- raise Load events
Client Server
28
Round Trip of a Web Page
Page
Label
TextBox
Button
4. Action
handle event(s)
(Click, TextChanged, ...)
Client Server
29
Round Trip of a Web Page
Page PreRender
Label PreRender
TextBox PreRender
HTML
<html> Button PreRender
... + page state
<input type="text" ...>
<input type="button" ...>
5. Rendering
...
</html> - raise PreRender events
- call Render methods of all controls, which
render the controls to HTML
Client Server
30
Round Trip of a Web Page
Page Unload
Label Unload
TextBox Unload
<html> Button Unload
...
<input type="text" ...>
<input type="button" ...>
6. Unloading
...
</html> - raise Unload events for cleanup actions
Client Server
31
Which Events Cause a Round Trip?
Round trip events (cause an immediate round trip)
Click <asp:Button Text="click me" Runat="server"
OnClick="DoClick" />
32
ASP.NET
Simple Dynamic Web Pages
Web Forms
Event Handling
Web Controls
Validators
User Controls
Custom Controls
State Management
Configuration of ASP.NET
Working with Visual Studio .NET
Web Control Hierarchy
Control
WebControl
Button
TextBox
Label
BaseValidator
...
CheckBox
RadioButton
ListControl
ListBox
DropDownList
Image
ImageButton
Calendar
ValidationSummary
...
TemplateControl
Page
UserControl
34
Class Control
public class Control: ... { Properties
public virtual string ID { get; set; } name of the control
public virtual ControlCollection Controls { get; } nested controls
public virtual Control Parent { get; } enclosing control
public virtual Page Page { get; set; } page to which the control belongs
public virtual bool Visible { get; set; } should the control be visible?
protected virtual StateBag ViewState { get; } state of this control (see later)
public virtual bool EnableViewState { get; set; } should the state be persistent?
... Methods
public virtual bool HasControls(); does the control have nested controls?
public virtual Control FindControl (string id); searches for a nested control with the name id
public virtual void DataBind(); loads data from a data source
protected virtual void LoadViewState (object state); loads the state from the request stream
protected virtual object SaveViewState(); saves the state to the response stream
protected virtual Render (HtmlTextWriter w); renders the control to HTML
... Events
public event EventHandler Init; after the control was created
public event EventHandler Load; after the state was loaded from the request
public event EventHandler DataBinding; after DataBind was called
public event EventHandler PreRender; before the control is rendered to HTML
public event EventHandler Unload; before the control is released
...
}
35
Properties of Class Control
Containment relationship
Page
Controls Button ListBox TextBox
Page Parent
Controls
Page
ListItem ListItem ListItem
ViewState
38
WebControl (Other Properties)
BorderStyle
public enum BorderStyle {
NotSet, None, Dotted, Dashed,
Solid, Double, Groove, Ridge,
Inset, OutSet
}
Enabled
displays the control,
<asp:Button Enabled="false" ... /> but deactivates it
TabIndex
<asp:TextBox TabIndex="3" ... /> sequence in which the
<asp:TextBox TabIndex="2" ... /> controls are visited
<asp:TextBox TabIndex="1" ... /> TAB TAB when the TAB key is
pressed
39
Class Button
public class Button: WebControl {
//--- properties caption of the button
public string Text { get; set; }
public string CommandName { get; set; } for handling
public string CommandArgument { get; set; } Command events.
public bool CausesValidation { get; set; } should the validators run when the
//--- events page is sent to the server?
public event EventHandler Click; default = true
public event CommandEventHandler Command;
}
40
Button (Command Event)
Command Event
useful if multiple buttons on a page should be handled by the same event handler
<form Runat="server">
<asp:Label ID="label" Text="100.00" Runat="server" />
<br><br>
<asp:Button Text="+ 10%"
CommandName="add" CommandArgument="0.1"
OnCommand="DoCommand" Runat="server" />
<asp:Button Text="- 5%"
CommandName="sub" CommandArgument="0.05"
OnCommand="DoCommand" Runat="server" />
</form>
<asp:TextBox TextMode="MultiLine"
Rows="2" Columns="15" Wrap="true" Runat="server" />
line 1
line 2
line 3
</asp:TextBox> 42
Class CheckBox
public class CheckBox: WebControl { public enum TextAlign {
//--- properties Left, Right
public virtual bool Checked { get; set; } }
public virtual string Text { get; set; }
public virtual TextAlign TextAlign { get; set; }
public virtual bool AutoPostBack { get; set; }
//--- events
public event EventHandler CheckedChanged; raised when Checked changes
}
<form Runat="server">
<asp:CheckBox ID="apples" Text="Apples" Runat="server" /><br>
<asp:CheckBox ID="pears" Text="Pears" Runat="server" /><br>
<asp:CheckBox ID="bananas" Text="Bananas" Runat="server" /><br>
<asp:Button Text="Buy" OnClick="DoClick" Runat="server" /> <br><br>
<asp:Label ID="label" Runat="server" />
</form>
<form Runat="server">
<p>Select method of payment:</p>
<asp:RadioButton ID="cash" Text="cash" GroupName="payment"
OnCheckedChanged="RadioChanged" AutoPostBack="true"
Runat="server" /><br>
<asp:RadioButton ID="cheque" Text="cheque" GroupName="payment"
OnCheckedChanged="RadioChanged" AutoPostBack="true"
Runat="server" /><br>
<asp:RadioButton ID="card" Text="credit card" GroupName="payment"
OnCheckedChanged="RadioChanged" AutoPostBack="true"
Runat="server" /><br><br>
<asp:Label ID="label" Runat="server" />
</form>
47
ListBox (Even Simpler)
If Text and Value are equal, one can use the followin simple solution
<form Runat="server">
<asp:ListBox ID="list" Rows="3" AutoPostBack="true"
OnSelectedIndexChanged="Show" Runat="server" /> <br><br>
<asp:Button Text="Fill" OnClick="Fill" Runat="server" /> <br><br>
<asp:Label ID="lab" Runat="server" />
</form>
48
ListBox (List Generated From a Database)
<form OnInit="PageInit" Runat="server">
<asp:ListBox ID="list" DataTextField="LastName" DataValueField="EmployeeID"
OnSelectedIndexChanged="HandleSelect" AutoPostBack="true" Runat="server" /><br>
<asp:Label ID="label" Runat="server" />
</form>
51
DataGrid (Formatting)
public class DataGrid: BaseDataList { public enum GridLines {
//--- properties Both, Horizontal, None, Vertical
... }
public virtual GridLines GridLines { get; set; }
public virtual int CellPadding { get; set; }
public virtual int CellSpacing { get; set; }
public virtual bool ShowHeader { get; set; }
public virtual bool ShowFooter { get; set; } Text Text
public virtual TableItemStyle AlternatingItemStyle { get; }
public virtual TableItemStyle HeaderStyle { get; }
public virtual TableItemStyle FooterStyle { get; } CellPadding CellSpacing
public virtual TableItemStyle ItemStyle { get; }
public virtual TableItemStyle SelectedItemStyle { get; }
...
}
53
DataGrid (Column Kind)
<asp:BoundColumn ... Is automatically bound to a column of the data source
DataField = "dbColumnName"
54
DataGrid (Event Handling)
Kind of the raised event
56
DataGrid (Example With ButtonColumn)
57
DataGrid (Code Behind for the Previous Example)
public partial class BasePage: System.Web.UI.Page {
DataView dataView;
public void PageLoad (object sender, EventArgs e) {
DataSet ds;
if (!IsPostBack) {
... // load ds from the database
Session["Data"] = ds;
} else ds = (DataSet)Session["Data"];
dataView = ds.Tables["Employees"].DefaultView;
grid.DataSource = dataView;
grid.DataBind();
}
public void DeleteRow (object sender, DataGridCommandEventArgs e) {
dataView.Delete(e.Item.DataSetIndex); // deletes data only in the DataSet
grid.DataSource = dataView; // but not in the database
grid.DataBind();
}
public void SelectRow (object sender, EventArgs e) {
grid.SelectedItemStyle.BackColor = System.Drawing.Color.Gray;
label.Text = grid.SelectedItem.Cells[1].Text + " " + grid.SelectedItem.Cells[2].Text;
}
}
58
ASP.NET
Simple Dynamic Web Pages
Web Forms
Event Handling
Web Controls
Validators
User Controls
Custom Controls
State Management
Configuration of ASP.NET
Working with Visual Studio .NET
Validators
Objects for plausibility checks
Label
BaseValidator
60
Validators (Example)
Name:
<asp:TextBox ID="name" Runat="server" />
<asp:RequiredFieldValidator ControlToValidate="name" Text="*"
ErrorMessage="You must enter a name" Runat="server" />
<br>
Age:
<asp:TextBox ID="age" Runat="server" />
<asp:RangeValidator ControlToValidate="age" Text="*"
MinimumValue="0" MaximumValue="100" Type="Integer"
ErrorMessage="The age must be between 0 and 100" Runat="server" />
<asp:Button Text="Submit" OnClick="DoClick" Runat="server" />
<asp:ValidationSummary Runat="server" />
61
ASP.NET
Simple Dynamic Web Pages
Web Forms
Event Handling
Web Controls
Validators
User Controls
Custom Controls
State Management
Configuration of ASP.NET
Working with Visual Studio .NET
User Controls (Example)
Group of controls that can be used like a single control
63
User Controls (Code Behind)
MoneyField.ascx.cs
using System;
public partial class MoneyFieldBase : System.Web.UI.UserControl {
public string Text {
get { return amount.Text; }
set { amount.Text = value; }
}
private double OldRate {
get { return ViewState["rate"] == null ? 1 : (double)ViewState["rate"]; }
set { ViewState["rate"] = value; }
}
public void Select (object sender, EventArgs arg) {
try {
double val = Convert.ToDouble(amount.Text);
double newRate = Convert.ToDouble(currency.SelectedItem.Value);
double newVal = val / OldRate * newRate;
amount.Text = newVal.ToString("f2");
OldRate = newRate;
} catch (Exception) {
amount.Text = "0";
}
}
}
64
User Controls (Usage)
Multiple instances of them can be used on the same page
<%@ Page Language="C#" %>
<%@ Register TagPrefix="my" TagName="MoneyField" Src="MoneyField.ascx" %>
<html>
<body>
<form Runat="server">
Amount 1: <my:MoneyField ID="field1" Text="100" Runat="server" /><br>
Amount 2: <my:MoneyField ID="field2" Runat="server" />
</form>
</body>
</html>>
65
ASP.NET
Simple Dynamic Web Pages
Web Forms
Event Handling
Web Controls
Validators
User Controls
Custom Controls
State Management
Configuration of ASP.NET
Working with Visual Studio .NET
Custom Controls (Example)
Allow you to implement completely new functionality (e.g. text folding)
Used as follows
<%@ Page Language="C#" %>
<%@ Register TagPrefix="my" Namespace="Folds" Assembly="Fold" %>
<html> <body>
<form Runat="server">
<my:Fold Text="..." AlternateText="..." Runat="server" />
</form>
</body> </html>
69
ASP.NET
Simple Dynamic Web Pages
Web Forms
Event Handling
Web Controls
Validators
User Controls
Custom Controls
State Management
Configuration of ASP.NET
Working with Visual Studio .NET
3 Kinds of States
Page state
e.g. contents of TextBoxes, state of CheckBoxes, ...
Session state (session = all requests from the same client within a certain time)
e.g. shopping cart, email address of a client, ...
Application state (Application = all aspx files in the same virtual directory)
e.g. configuration data, number of sessions, ...
application
session
C request + page state /Samples
l response + page state x.aspx
i
e S y.aspx
session state e
n z.aspx
t session r
C v application
l e state
i r
e session state
n
t 71
How to Access State Information
Page state
writing: ViewState["counter"] = counterVal;
reading: int counterVal = (int) ViewState["counter"];
Session state
writing: Session["cart"] = shoppingCart;
reading: DataTable shoppingCart = (DataTable) Session["cart"];
Application state
writing: Application["database"] = databaseName;
reading: string databaseName = (string) Application["databaseName"];
72
Class Page
public class Page: TemplateControl { IsValid
//--- properties true, if none of the validators
public ValidatorCollection Validators { get; } on the page reported an error
public bool IsValid { get; }
public bool IsPostBack { get; } IsPostBack
public virtual string TemplateSourceDirectory { get; } true, if the page was sent to the
public HttpApplicationState Application { get; } server in a round trip. If the page
public virtual HttpSessionState Session { get; }
was requested for the first time
public HttpRequest Request { get; }
IsPostBack == false
public HttpResponse Response { get; }
...
TemplateSourceDirectory
//--- methods
public string MapPath(string virtualPath); current virtual directory,
public virtual void Validate(); e.g. "/Samples"
...
} Application and Session
application state and session state
MapPath(virtPath)
maps the virtual directory to the physical one Request und Response
HTTP request and HTTP response
Validate()
starts all validators on the page
73
Class HttpRequest
public class HttpRequest { UserHostName
public string UserHostName { get; } domain name of the client
public string UserHostAddress { get; }
public string HttpMethod { get; } UserHostAddress
public HttpBrowserCapabilities Browser { get; } IP number of the client
public NameValueCollection Form { get; }
public NameValueCollection QueryString { get; }
public NameValueCollection Cookies { get; }
public NameValueCollection ServerVariables { get; }
...
}
74
HttpRequest (Request and Form Parameters)
<form Runat="server">
<asp:TextBox ID="text1" Runat="server" /><br>
<asp:TextBox ID="text2" Runat="server" /><br>
<asp:CheckBox ID="checkbox" Text="box" Runat="server" /><br>
<asp:Button ID="button" Text="Send" OnClick="DoClick" Runat="server" />
<asp:Label ID="lab" Runat="server" />
</form>
Query string
par1 = 123
par2 = Hello
Form parameters
__VIEWSTATE = dDwxMTYxMTk1 ...
text1 = John
text2 = Miller
checkbox = on
button = Send 75
Class HttpResponse
public class HttpResponse { ContentType
//--- properties MIME type (e.g. text/html)
public string ContentType { get; set; }
public TextWriter Output { get; } Output
public int StatusCode { get; set; } HTML response stream; can be
public HttpCookieCollection Cookies { get; set; } written to with Write
...
//--- methods
StatusCode
public void Write(string s); // various overloaded versions e.g. 200 for "ok" or
public void Redirect(string newURL); 404 for "page not found"
...
}
Test1.aspx
<form Runat="server">
Name: <asp:TextBox ID="name" Runat="server" />
<asp:Button Text="Send" OnClick="DoClick" Runat="server" />
</form>
Welcome.aspx
Welcome <%= Request.QueryString["name"] %> ! 76
ASP.NET
Simple Dynamic Web Pages
Web Forms
Event Handling
Web Controls
Validators
User Controls
Custom Controls
State Management
Configuration of ASP.NET
Working with Visual Studio .NET
machine.config and web.config
79
Example: Tracing
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.web>
<trace enabled="true" pageOutput="true" />
...
</system.web>
...
</configuration>
80
Authorization
Who may visit the pages of a specific directory?
The directory must have a web.config file with the following contents
81
Authentication
4 kinds
None No authentication.
All users are anonymous.
Windows Uses the login name and the password of the Windows login.
Makes only sense for local servers.
Passport Users are redirected to the login page of the Passport server
where they can authenticate themselves (with their user name and password).
82
Forms Authentication (Configuration)
web.config
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.web>
<authorization>
<deny users="?" />
</authorization>
<authentication mode="Forms">
<forms loginUrl="Login.aspx" name="mycookie" protection="All" timeout="20">
<credentials passwordFormat="MD5">
<user name="peter" password="85C69322756E01FD4A7A22DE55E19743"/>
<user name="wolfgang" password="85C69322756E01FD4A7A22DE55E19743"/>
</credentials>
</forms>
</authentication> string encryptedPwd =
... FormsAuthentication.HashPasswordForStoringInConfigFile("myPwd", "MD5");
</system.web>
...
</configuration>
The users "peter" and "wolfgang" as well as their passwords are stored on the server
83
Authentication (How it Works)
directory requiring authentication
1. Anonymous user tries to
access A.aspx
A.aspx B.aspx C.aspx
2. Because of <deny users="?"/>
and <forms loginUrl="Login.aspx">
the user is redirected to Login.aspx
web.config
<deny users="?" />
..
<forms loginUrl="Login.aspx" ...>
84
Login.aspx
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Security" %>
<html>
<head> validates against the credentials in web.config
<title>Login page</title>
<script Language="C#" Runat="server"> create persistent cookie?
void Authenticate (object sender, EventArgs e) {
if (FormsAuthentication.Authenticate(user.Text, pwd.Text) || user.Text == "Karin")
FormsAuthentication.RedirectFromLoginPage(user.Text, false);
else
msg.Text = "-- authentication failed";
}
</script>
</head>
<body>
<form Runat="server">
<asp:TextBox ID="user" Runat="server"/> Name<br>
<asp:TextBox ID="pwd" TextMode="Password" Runat="server"/> Password<br><br>
<asp:Button ID="button" Text="Login" OnClick="Authenticate" Runat="server" />
<br><br>
<asp:Label ID="msg" Runat="server" />
</form>
</body>
85
</html>
User Identification With Cookies
How does ASP.NET remember if a user is already authenticated?
88
Composing a GUI With Drag & Drop
Solution
Explorer
Toolbox
Property
Window
Used to switch between
design view and HTML view
89
HTML View
90
Event Handling
Double click on a Button creates an event handler in the code behind
91
Executing the Page
Menu: Debug | Start
92
New Features in ASP.NET 2.0
• Master pages
• Navigation
• Themes and skins
• Personalisation
• Authentication and membership classes
• New Controls for database access
• ...
Idea
Uniform layout for all pages
My.master Page1.aspx http://domain/virtualdir/Page1.aspx
<%@ Master %> <%@ Page masterPageFile="My.master" %>
<asp:Content
... Title area ... ContentPlaceHolderId="Stuff"
runat="server">
... Links ...
<asp:ContentPlaceHolder
id="Stuff"
runat="server"/> </asp:Content>
Page2.aspx http://domain/virtualdir/Page2.aspx
<asp:Content
ContentPlaceHolderId="Stuff"
runat="server">
</asp:Content>
94
Characteristics of Master Pages
• May contain arbitrary HTML code and arbitrary ASP.NET web controls
• May have a code behind
• Can be nested
<%@ Master language="C#" %> Main.master
...
<asp:ContentPlaceHolder id="Submaster" runat="server" />
96
New Features in ASP.NET 2.0
• Master pages
• Navigation
• Themes and skins
• Personalisation
• Authentication and membership classes
• New Controls for database access
• ...
Site Maps
Page hierarchy of an application is described in XML
web.sitemap
<?xml version="1.0" encoding="utf-8" ?>
<siteMap>
<siteMapNode title="Articles" description="Home" url="Articles.aspx" > Each of these pages
<siteMapNode title="Computers" url="Computers.aspx">
uses the same Master.
<siteMapNode title="PCs" url="PCs.aspx" />
<siteMapNode title="Notebooks" url="Notebooks.aspx" />
This Master contains
</siteMapNode> a TreeView control.
<siteMapNode title="Printers" url="Printers.aspx"> Thus the TreeView is
<siteMapNode title="Laser" url="Laser.aspx" /> re-displayed on every
<siteMapNode title="InkJet" url="InkJet.aspx" /> page.
</siteMapNode>
</siteMapNode>
</siteMap>
Shows the path to the current page if this page belongs to a Sitemap
99
New Features in ASP.NET 2.0
• Master pages
• Navigation
• Themes and skins
• Personalisation
• Authentication and membership classes
• New Controls for database access
• ...
Themes and Skins
Allow users to define default settings for web controls
Theme: collection of skins; stored in a file with the ending .skin in an App_Themes subdirectory
MyApp Fancy.skin
My.aspx <asp:Label .../>
App_Themes <asp:Button .../>
Fancy
<asp:TextBox ...>/
Images Plain.skin
Fancy.skin <asp:Label .../>
Plain <asp:Button .../>
Plain.skin <asp:TextBox ...>/
101
Setting a Theme
Globally for the whole application
<configuration> web.config
<system.web>
<pages theme="Fancy" />
...
</system.web>
</configuration>
• Master pages
• Navigation
• Themes and skins
• Personalisation
• Authentication and membership classes
• New Controls for database access
• ...
Personalisation
Allows the creation of user profiles
• Stored as name/value pairs
• Name and type are defined in web.config
<system.web>
<profile>
<properties>
<add name="User" type="System.String" />
<add name="LastVisit" type="System.DateTime" />
</properties>
</profile>
</system.web>
106
Example: Personalized Theme
Defining a user profile property Theme of type String
<profile>
<properties>
<add name="Theme" type="System.String"/>
</properties>
</profile>
Users can set their preferred theme during one of their visits
void SetTheme(object sender, EventArgs e) {
Profile.Theme = textBox.Text;
}
107
New Features in ASP.NET 2.0
• Master pages
• Navigation
• Themes and skins
• Personalisation
• Authentication and membership classes
• New Controls for database access
• ...
Login Controls 1/2
LoginStatus displays
Login if the user is not yet logged in
<asp:LoginStatus Runat="server" />
Logout if the user is logged in
PasswordRecovery
<asp:PasswordRecovery Runat="server">
<MailDefinition
from="mailto:[email protected]"
cc="your password" />
</asp:PasswordRecovery>
• If unknown users try to access a member page they are redirected to the login page.
112
Authentication
Access to protected member pages
somewhere.aspx protected member page
login.aspx
<asp:Login .../> no user yes
known?
yes user no
known? 113
Roles
Class Roles (in System.Web.Security)
• manages user roles (e.g. Admin, Employee, ...)
static void CreateRole(string roleName) {...}
static void AddUserToRole(string userName, string roleName) {...}
...
114
New Features in ASP.NET 2.0
• Master pages
• Navigation
• Themes and skins
• Personalisation
• Authentication and membership classes
• New Controls for database access
• ...
Visualization of Database Tables
AccessDataSource, SqlDataSource, XmlDataSource
<asp:AccessDataSource ID="data" Runat="server"
DataFile="db.mdb"
SelectCommand="SELECT id, name, subject FROM Students" />
• The web control specifies the database name and the SQL command
• Creates a DataSet that can be displayed in a ListBox, DropDownList, GridView, etc.
GridView
<asp:GridView DataSourceID="data" Runat="server" AllowSorting="true" />
116
DropDownList With AccessDataSource
<asp:AccessDataSource ID="data" Runat="server"
DataFile="db.mdb"
SelectCommand="SELECT DISTINCT subject FROM Students" />
117
Parameters of Select Commands
<asp:TextBox id="subj" AutoPostBack="true" OnTextChanged="..." Runat="server" />
118
Editing a GridView
<asp:AccessDataSource ID="data" Runat="server"
DataFile="db.mdb" column values
SelectCommand="SELECT id, name, subject FROM Students"
UpdateCommand="UPDATE Students SET name=@name, subject=@subject WHERE id=@id"
DeleteCommand="DELETE FROM Students WHERE id=@id" />
119
Detailed View of a Database Record
DetailsView
<asp:AccessDataSource ID="data" Runat="server"
DataFile="db.mdb"
SelectCommand="SELECT id, name, subject FROM Students" />
120
Summary
Summary
Advantages of ASP.NET over ASP
• object-oriented
• event-based
• predefined and user-defined web controls
• separation between layout (HTML) and business logic (e.g. C#)
• compiled code instead of interpreted server scripts
• convenient state management
Examples available at
http://dotnet.jku.at/book/samples/ Examples from the book
http://dotnet.jku.at/book/exercises/ Exercises from the book
http://dotnet.jku.at/buch/solutions/ Solutions to the exercises
122