ASP NET Begynnerkurs PDF
ASP NET Begynnerkurs PDF
ASP.NET
1. ASP.NET Modellen
2. Programmeringsmodellen
3. Master Page
4. Håndtering av datakilder
5. Håndtering av brukere
9:00 Start
10.30-10.45: Break
11.45-12.30: Lunch
13.15-13.30: Break
14.15-14.30: Break
15.15-15.20: Break
16.00: End
Current position
Experience
The Webbrowser gets the files from the webserver over the HTTP
protocol
Code
ASPX Generate File
Engine
Parse
Request
ASPX Page
File Instantiate
Class
Request File
Response Page
Response Class
Instantiate
Execute
Web Client Server
VB C++ C# JScript
ASP.NET
Web Web Forms
Services
To be able to run your first asp.net application, code the following file
HelloWorld.aspx:
<%@ Page Language="C#" %>
<html>
<body>
<% Response.Write("Hello world from asp.net"); %>
</body>
</html>
Colour-coding
Auto formatting
Client-event
generation
Flow Layout
Optional fixed position
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Hello world
</div>
</form>
</body>
</html>
Default.aspx.cs
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
<script type="text/javascript">
<!--
alert('The time is: 08.11.2005
10:22:40')// -->
</script>
Tracing
<trace enabled= true"
requestLimit="10"
pageOutput= true"
traceMode="SortByTime"
/>
Trace Options
Enabled
Tracing information will be stored. Information can be accessed through
http://site/trace.axd
RequestLimit
Store tracing information for this many requests
PageOutput
Allows trace output to also appear at the bottom of the page.
TraceMode
Allows trace information to be sorted by time or category.
VB C++ C# JScript
«use»
«use»
«manage»
MyUnmangedApplication
.NET Runtime
«use»
«use»
WIN32 API
«use»
Windows
A library
Basic operating system services
Process creation, threads management etc.
Windows display services
Security credentials verification
Web services
Database connections
:C# Code
Compile (csc)
Load
Already JIT ed ?
More code
No Yes
:Native Code
Server-programmable objects
Properties, method and events
Built-in controls
HTML Controls
Web Controls
Intrinsic Controls
List Controls
Validation Controls
Rich Controls
All web server and validation controls follows the XML element/type
description:
<asp:X runat="server" attribute = value"> Contents </asp:X>
X
Name of the ASP.NET server control
attribute = value
One or more attribute specification
Contents
Specifics the control content, if any
Attributes
ID="Label1"
runat="server
Wrap functionality
ASP.NET markup
<asp:Label ID="Label1" runat="server" Text="Label">
</asp:Label>
Renders as HTML
<span id="Label1">Label</span>
Programatic access
Label1.Text = "Hello World!";
ASP.NET markup
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
TextMode
<input name="TextBox1" type="text"
SingleLine id="TextBox1" />
Password <input name="TextBox2" type="password"
id="TextBox3" />
MultiLine
<textarea name="TextBox3" rows="2"
cols="20" id="TextBox1" />
AutoPostback property
Causes a PostBack when the Text property has changed
TextChanged event
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
string userInput = TextBox1.Text;
}
ASP.NET markup
<asp:Button ID="Button1" runat="server" Text= Trykk her!" />
Renders as HTML
<input type="submit" name="Trykk her!" value="Button" id="Button1" />
ASP.NET markup
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="1" Selected="True">Oslo</asp:ListItem>
<asp:ListItem Value="2">Bergen</asp:ListItem>
<asp:ListItem Value="3">Trondheim</asp:ListItem>
</asp:DropDownList>
Renders as HTML
<select name="DropDownList1" id="DropDownList1">
<option selected="selected" value="1">Oslo</option>
<option value="2">Bergen</option>
<option value="3">Trondheim</option>
</select>
WebForm1.aspx.cs
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
Server roundtrip
Button pressed
HTTP postback
WebForm1() :WebForm1
clickButton
clickButton :Button
Page_Load
clickButton_Click()
RequiredFieldValidator
RangeValidator
CompareValidator
RegularExpressionValidator
CustomValidator
Manages scripts
References, Localization
Calls Sys.Application.initialize()
Starts the lifecycle events
Instant AJAX
Requires a ScriptManager
Triggers collection
Add an outside button as AsyncPostBackTrigger
Add an inside button as PostBack Trigger
Application state
Shared across multiple clients, connected to your web application
global.asax
HttpApplication is the base class
void Application_Start()
{
DataSet bookingDS = new DataSet();
Application[ bookingDS ] = bookingDS ;
}
bookingpage.aspx
Session state
Is shared across single client requests with a unique client
session id
Session id:
Generated automatically when the browser hits the page for the
first time
Client session is identified by passing the session id between
client and server
Can be either
a session cookie called ASP.NET_SessionId
or
cookieless with a string included in the URL:
http://server/<site/>(uqwkag45e35fp455t2qav155)/default.aspx
Cleanup resources in
Session_End() procedure in global.asax
void Session_Start() {
// initialize
Session[ SelectedRoomName ] = Nordpolen ;
}
Write session
Read session
void Page_Load( object Src, EventArgs e) {
RoomTextBox.Text =
(string)Session[ SelectedRoomName ];
}
Global.asax
Contains predefined Event Handlers:
case (RoomShape.uShape):
. . .
}
RoomName.Text= room.Name;
}
}
Master Page
Content Page
</asp:Content>
A ContentPlaceHolder is placed on
the master page
It will be filled by the content of the
pages that uses this master page
A table, containing a Image and Label are added to the maser page
<body>
<form id="form1" runat="server">
<div style="background-color: gainsboro">
<table>
<tr>
<td>
<asp:Image ID="Image1" runat="server"
ImageUrl="~/Image/BookingLogo.gif" />
</td>
<td style="background-color: gainsboro" valign="bottom">
<asp:Label ID="Label1" runat="server" Font-Names="Arial"
Font-Size="44pt" Text="MegaBooking">
</asp:Label>
</td>
</tr>
</table>
</div>
<asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
</asp:contentplaceholder>
</form>
</body>
<asp:Content
ContentPlaceHolderID="ContentPlaceHolder1 RunAt="server">
</asp:Content>
SiteMap
A site map is an XML file that describes the structure of the pages
SiteMapPath
A visual control that depicts the path to the current page
Menu
Displays the information in menu form
TreeView
Displays the hierarchical structure of the pages
Web.sitemap
<?xml version="1.0" encoding="utf-8" ?>
</siteMap>
xxxx.aspx
Highly customizable UI
Menu Events
MenuItemClick: Fired when a menu item is clicked
MenuItemDataBound: Fired when a menu item binds to a data source
Web.sitemap
<?xml version="1.0" encoding="utf-8" ?>
</siteMapNode>
</siteMap>
xxxx.aspx
<asp:SiteMapDataSource ID="SiteMap" RunAt="server" />
<asp:Menu DataSourceID="SiteMap" RunAt="server" />
Fire events
CheckChanged, SelectedNodeChanged
TreeNodeCollapsed, TreeNodeExpanded
</siteMapNode>
</siteMap>
xxxx.aspx
<asp:SiteMapDataSource ID="SiteMap" RunAt="server" />
<asp:TreeView DataSourceID="SiteMap" RunAt="server" />
Highly customizable UI
Nodes can be stylized and templatized
Separators can be stylized and templatized
ObjectDataSource
Any class that implements IEnumerable, DataSet or DataReader
SqlDataSource
Connects data-binding controls to SQL databases
AccessDataSource
Connects data-binding controls to Access databases
XmlDataSource
Connects data-binding controls to XML data
SiteMapDataSource
Connects site navigation controls to site map data
Configure it
public RoomList()
{
rooms= roomDS.Tables.Add("Room");
rooms.Columns.Add("Name");
rooms.Columns.Add("Size");
rooms.Rows.Add("Sydpolen", 100);
rooms.Rows.Add("Nordpolen", 100);
rooms.AcceptChanges();
}
xxx.aspx
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:CateringDBConnectionString %>
SelectCommand="SELECT [Name], [Size], [RoomID] FROM [Room]">
</asp:SqlDataSource>
Web.config
...
<connectionStrings>
<add name="CateringDBConnectionString"
connectionString="Data Source=.;
Initial Catalog=CateringDB;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
...
Properties
DataFile
Path to data source
SQL commands:
SelectCommand, InsertCommand, UpdateCommand,
DeleteCommand
DataSourceMode
Specifies whether DataSet or DataReader is used (default =
DataSet)
...
...
Key properties
DataFile
Path to file containing XML data
TransformFile
Path to file containing XSL style sheet
XPath
XPath expression used to filter data
DataSourceID
Connects to the DataSource
<asp:XmlDataSource ID="XmlDataSource1" . . .
Rooms.xml
<?xml version="1.0" encoding="utf-8"?>
<RoomsDS>
<Room name="South" />
<Room name="North" />
<Room name="West" />
<Room name="East" />
</RoomsDS>
xxx.aspx
Highly customizable UI
Highly customizable UI
xxx.aspx
...
<asp:DetailsView ID="DetailsView1" runat="server" Height="50px"
Width="125px" AllowPaging="True" DataSourceID="SqlDataSource1">
<Fields>
<asp:CommandField ShowDeleteButton="True"
ShowEditButton="True" ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
...
Web Browser
Internet
WebBrowser Data Object
WebBrowser Dataset
Server
ADO.NET
Disconnected data architecture
Datasets are complete relational views of data
XML and XML schema
DataSet
DataAdapter Data Source
DataTable
SelectCommand
SelectCommand
Fill
Fill
Update
Update Connection
Connection
UpdateCommand
UpdateCommand
DataAdapter
DataTable
SelectCommand
SelectCommand
Fill
Fill
Update
Update
UpdateCommand
UpdateCommand
BookingAdminView
BookingApp
BookingView
BookingDB
Package == namespace
C# 3.0
<book>
<title/>
<author/>
<year/>
<price/>
</book>
Extension methods:
Allow an existing type to be extended with new methods
The type of the first parameter will be the type that is extended
Lambda expressions
Miniature functions created on the fly.
class Room
{
public string Name { set; get; }
public int Seats { set; get; }
public bool HasAudio { set; get; }
public string City { set; get; }
}
class RoomsInCity
{
public string City { set; get; }
public int Count { set; get; }
}
[Table]
class Room
{
[Column(IsPrimaryKey = true)]
public string Name;
[Column]
public int Seats;
}
DataContext:
Acts as a factory for generating tables that you can query.
. . .
Room norpolen = rooms.Single(r => r.Name == "Nordpolen");
norpolen.Seats = 20;
dataContext.SubmitChanges();
rooms = dataContext.GetTable<Room>();
foreach (var room in rooms)
{
Console.WriteLine(room.Name+", has " +room.Seats+" seats");
}
Nordpolen, has 20 seats
Nansen, has 80 seats
Amundsen, has 70 seats
DataTable *
Data:: DataTable
Data for a single table. Consists of one or
more DataColumns. When populated the
data will be contained in DataRows.
*
Data:: DataColumn * Data:: DataRow
DataColumn DataRow
ds.Tables[index].Rows[index].GetChildRows("relation");
ds.Tables[index].Rows[index].GetChildRows("relation");
ds.Tables[index].Rows[index].GetParentRow("relation");
ds.Tables[index].Rows[index].GetParentRow("relation");
ds.Tables[
ds.Tables[ Room
Room ].Rows[0].GetChildRows("RoomBooking");
].Rows[0].GetChildRows("RoomBooking");
Room Booking
GetChildRows
GetParentRow
DataSet
TableAdapter
Database
Data
Data Data
command
connection adapter
collection
Typed XML
DataSet
Typed datasets
Custom wrapper classes, subclassing
DataSets, DataTable, DataColumn and DataRow classes
Define properties for each column
Columns can be accessed by names instead of column numbers
. . .
foreach(DataRow row in roomTable.Rows)
Console.WriteLine("Room name=" + row[1] + " Size=" + row[2]);
. . .
foreach(RoomRow roomRow in roomTable.Rows)
Console.WriteLine("Room name="+ roomRow.name+" Size=" + roomRow.size);
Visual Studio can build the XML Schema files from a database
Creating a Database:
In Solution Explorer
Add > New Item > SQL
DataBase
In DataSource Window:
Data > Show Data Sources
Select Tables to add to your DataSet
Resulting DataSet
Contains GetDataBy
RoomID as input parameter
RoomDataTable RoomRow
bookingDataSet
TestBookingDB.cs
DropDownList
Enable for automatic postback
Global.asax
public class Global : System.Web.HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
ParticipantDS participantDS = new ParticipantDS();
if (System.IO.File.Exists(Server.MapPath(Utility.FileName)))
participantDS.ReadXml(Server.MapPath(Utility.FileName));
Application["ParticipantDS"] = participantDS;
}
void loadListBox()
{
participantDropDownList.Items.Clear();
foreach(ParticipantDS.ParticipantRow p in participantDS.Participant)
participantDropDownList.Items.Add(
new ListItem(p.Name, p.ParticipantID.ToString()));
}
. . .
Before After
To a site
<configuration>
<system.web>
<pages theme="BasicBlue" />
</system.web>
</configuration>
Programmatically
vroot
Theme name =
Subdirectory name
App_Themes
SKIN
Shocking-
SKIN
Pink
SKIN
Autumn-
SKIN
Leaves
xxx.aspx
<asp:ListBox ID="ListBox1" runat="server">
<asp:ListItem>North</asp:ListItem>
<asp:ListItem>South</asp:ListItem>
<asp:ListItem>West</asp:ListItem>
<asp:ListItem>East</asp:ListItem>
</asp:ListBox>
~\App_Themes\Shock\HotPink.skin
<asp:ListBox runat="server" Font-Names="Script MT Bold"
Font-Size="20pt" Width="213px"/>
~\App_Themes\Shock\HotPink.skin
...
<asp:DropDownList runat="server" BackColor= pink" ForeColor="white"
SkinID= Pink" />
...
xxx.aspx
...
<asp:DropDownList ID="Countries" SkinID= Pink" RunAt="server" />
...
Administrering av en website.
Håndtering av flere brukere med ulike roller.
Sikre tilgang til sidene i en webløsning?
Authentication
Validates user credentials
Types of authentication
Windows
Passport, centralized services provided by Microsoft
Forms,
Authorization
Determine whether request is permitted
ChangePassword
UI for changing passwords
CreateUserWizard
UI for creating new user accounts
Login
UI for entering and validating user names and passwords
LoginName
Displays authenticated user names
LoginStatus
UI for logging in and logging out
LoginView
Displays different views based on login status and roles
PasswordRecovery
UI for recovering forgotten passwords
Incorporates RequiredFieldValidators
<html>
<body>
<form runat="server">
<asp:Login RunAt="server" />
</form>
</body>
</html>
Authenticate
Fired when the user clicks the Log In button. Purpose: to authenticate
the user by validating his or her login credentials
LoggedIn
Fired following a successful login
LoggingIn
Fired when the user clicks the Log In button. Purpose: to prevalidate
login credentials (e.g., make sure e-mail address is well-formed)
LoginError
Fired when an attempted login fails
try
{
Membership.CreateUser ("Jeff", "imbatman", "[email protected]");
}
catch (MembershipCreateUserException e)
{
// Find out why CreateUser failed
switch (e.StatusCode)
{
case MembershipCreateStatus.DuplicateUsername:
...
case MembershipCreateStatus.DuplicateEmail:
...
case MembershipCreateStatus.InvalidPassword:
...
default:
}
}
Controls Other
Login LoginStatus LoginView OtherLogin
Login
Login LoginStatus LoginView Controls
Controls
Membership API
Membership
Membership MembershipUser
MembershipUser
Membership Providers
Other
OtherMembership
Membership
SqlMembershipProvider
SqlMembershipProvider Providers
Providers
Membership
Data
Other
SQL Server Data Stores
MembeshipUser
Represents individual users registered in the membership data store
Includes numerous properties for getting and setting user info
Includes methods for retrieving, changing, and resetting passwords
if (Roles.Enabled)
{
Roles.IsUserInRole("Developer");
statusLabel.Text += " - Welcome to the developer community";
}
<configuration>
<system.web>
<roleManager enabled="true" />
</system.web>
</configuration>
if (!Roles.RoleExists ("Developers"))
{
Roles.CreateRole ("Developers");
}
Web Service
Open
Internet
Protocols A programmable service accessible
via standard Web protocols
Your Web
Service
Passed to
Calls Assemblies
SOAP Request
asmx
File
ASP
Engine
MyApp.exe
Instantiate
MyDate
Point your
browser to the
The following operations are supported. For a formal definition,
location and
observe please review the Service Description.
Now
Press Now and
observe XML
output
And a WebService.cs
Containing the C# code, as for an ordinary ASP.NET application
public class WebService : System.Web.Services.WebService
{
public Service1()
{
//InitializeComponent();
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
Compile and run the project and observe it in the web browser
C:\course\C#>
class NowWrapper
{
static void Main(string[] args)
{
MyDate date= new MyDate();
Console.WriteLine(date.Now());
}
}
The process of splitting tags and code, making the proxy class etc.
Is automated by Visual Studio
Use separate project types for the Web Service and the Client
<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/"
SOAP:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP:Header>
<t:Transaction xmlns:t="some-URI" SOAP:mustUnderstand="1">
5
</t:Transaction>
</SOAP:Header>
<SOAP:Body>
<m:Deposit xmlns:m="Some-URI">
<m:amount>200</m:amount>
</m:Deposit>
</SOAP:Body>
</SOAP:Envelope>
A Web service
Makes the internet XML
Web Web
accessible from an Service Service
application Internet
XML
Web
Application
using System;
using WebClient.localhost;
namespace WebClient
{
class Class1
{
static void Main(string[] args)
{
Service1 simpleService= new Service1();
double d1=1;
double d2=2;
double result= simpleService.add(d1,d2);
Console.WriteLine("Result: {0}+{1}={2}",d1,d2,result);
}
}
}