0% found this document useful (0 votes)
142 views190 pages

ASP NET Begynnerkurs PDF

Uploaded by

Rui
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
142 views190 pages

ASP NET Begynnerkurs PDF

Uploaded by

Rui
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 190

Introduksjon til webutvikling med

ASP.NET

Av: Arne Laugstøl ([email protected])


ProgramUtvikling A/S (www.put.no)
(Ver: VS2088-1.0)

© PROGRAM UTVIKLING.no WebExpress - page - 1


Introduction

1. ASP.NET Modellen
2. Programmeringsmodellen
3. Master Page
4. Håndtering av datakilder
5. Håndtering av brukere

© PROGRAM UTVIKLING.no WebExpress - page - 2


Course Schedule

The course will follow this schedule:

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

© PROGRAM UTVIKLING.no WebExpress - page - 3


Course Instructor

Background and education

Current position

Experience

© PROGRAM UTVIKLING.no WebExpress - page - 4


Participants

How many of you are involved in Web-development daily


Without any programming ?

Any programmers here?


Which languages do you use
C#
VB.Net
Java
Php
Other

© PROGRAM UTVIKLING.no WebExpress - page - 5


1. ASP.NET modellen

1.Webutvikling Visual Studio 2005


Hvordan behandles en ASP .NET side av rammeverket?
Hva foregår på klient- og serversiden?

© PROGRAM UTVIKLING.no WebExpress - page - 6


HTML, HTTP and the World Wide Web

HTML was originally created as a way to create a link from one


document to another

HTML documents are read using a webbrowser

The Webbrowser gets the files from the webserver over the HTTP
protocol

After fetching the document, the webserver and the webbrowser


disconnect from eachother

© PROGRAM UTVIKLING.no WebExpress - page - 7


Dynamic Web Pages

Dynamic pages are created at the server at the time of a request, by


modifying or creating from scratch the documents as they re sent
from the webserver

IIS and ASP.NET create the dynamic content

© PROGRAM UTVIKLING as C#.NET - page - 8


ASP.NET Page Execution

Code
ASPX Generate File
Engine

Parse

Request
ASPX Page
File Instantiate
Class
Request File

Response Page
Response Class
Instantiate
Execute
Web Client Server

© PROGRAM UTVIKLING.no WebExpress - page - 9


.NET Framework & ASP

VB C++ C# JScript

Common Language Specification

ASP.NET
Web Web Forms
Services

ADO.NET: Data and XML

Base Class Library

Common Language Runtime

© PROGRAM UTVIKLING.no WebExpress - page - 10


Web server options

When you make a new web-site


Choose among different type of
sites

File System Site


Simplest alternative
Put your files in the file system

HTTP Web Site


Using eiter local or remote Web-
server (IIS)

FTP Web Site


Create and maintain a web site
on an FTP server

© PROGRAM UTVIKLING.no WebExpress - page - 11


Using the Embedded Web Server

A local Web sever for quick testing is embedded in VS2008


A small piece of executable code
Doesn t have all the features of a full blown Web server, such as IIS

Starting the Web server


WebDev.WebServer /port:4711 /path:"c:\kurs" /vpath:/KursWeb
Port: [Optional] An unused port between 1 and 65535, the default is
80 (usable if you do not also runs IIS on the same port)
Path: Physical path to the directory where the Web application is
rooted
Vpath: Virtual path to the application

Displaying the Page in IE


http://localhost:4711/KursWeb/HelloWorld.aspx

© PROGRAM UTVIKLING.no WebExpress - page - 12


Hello world from ASP.NET

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>

Observe the output


Hello world from asp.net

© PROGRAM UTVIKLING.no WebExpress - page - 13


What is ASP

Active Server Pages.NET (ASP.NET)


Allows dynamic creation of documents on a web server when they are
requested via HTTP
Mostly HTML pages, but could be WML pages for Wap Browsers

ASP.NET is fully integrated with the .NET framework


Complete access to server-side .NET framework classes
Includes support for C#, VB,

Can separate code and tags:

Old asp file:


ASP.NET

code <tags> code


<tags>
Form1.aspx Form1.aspx.cs
Form1.asp

© PROGRAM UTVIKLING.no WebExpress - page - 14


Split Code and Tags

We normally split the


application into a tag file
(HelloWorld.aspx) and a code
file (HelloWorld.cs)

These are the only files that


we are using.

Just a plain copying of files


no installation
no registry update
HelloWorld.aspx:
<%@ Page language="C#" inherits="HelloPage" src="HelloWorld.cs" %>
<html>
<body>
<br>
Testing - Hello world
</body>
</html>

© PROGRAM UTVIKLING.no WebExpress - page - 15


Split Code and Tags

We don t have to compile anything.


HelloWorld.cs
using System;
using System.Web.UI;
public partial class HelloPage : Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("<h1>Hello from asp page</h1>");
}
}

Just point the browser to the aspx


page, and observe the result:

© PROGRAM UTVIKLING.no WebExpress - page - 16


Sending Parameters to an ASP Page

The QueryString object contains a collection of all parameters


submitted in an HTTP Get request
For instance, you may have a link in a page like the following
<a href=HelloWorld.aspx?name=Arne&ID=2312 > < /a>

Could be accessed in HelloWorld.cs


string name= Request.QueryString["name"];
string id= Request.QueryString["ID"];

The Request object contains much more information, such as


Url, Path, ServerVariables, Headers, HttpMethod and browser
capability
HttpBrowserCapabilities bc = Request.Browser;
string browserName= bc.Browser;
string operatingSystem= bc.Platform;

© PROGRAM UTVIKLING.no WebExpress - page - 17


HTML Designer

Visual Studio includes tools for making the html stuff

HTML and server control statement completion

Colour-coding

Auto formatting

Client-event
generation

© PROGRAM UTVIKLING.no WebExpress - page - 18


Web Forms Designer

Drag/Drop WYSIWYG Form


Designer
WebForms

Flow Layout
Optional fixed position

Double-click to write code


behind controls

The dialog shows Default.aspx in


design mode

© PROGRAM UTVIKLING.no WebExpress - page - 19


Generated Code

The generated aspx code references the file Default.aspx.cs


Will contain the actual code we have to make
Will run on the server
Default.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
. . .

<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Hello world
</div>
</form>
</body>
</html>

© PROGRAM UTVIKLING.no WebExpress - page - 20


The Generated C# Code File

The generated C# code, will be a normal source file


Much like the one that was generated for normal Windows application
(Windows forms)

Default.aspx.cs
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
}

© PROGRAM UTVIKLING.no WebExpress - page - 21


Insert Client Script into a Page

Add the following code


protected void Page_Load( object sender, EventArgs e)
{
string scriptStr = "alert('The time is: " + DateTime.Now + "')";
Page.ClientScript.RegisterClientScriptBlock(GetType(),
"My timealert", scriptStr, true );

It will result in the following client source

<script type="text/javascript">
<!--
alert('The time is: 08.11.2005
10:22:40')// -->
</script>

© PROGRAM UTVIKLING.no WebExpress - page - 22


Error Pages

Redirect Certain Errors to Certain Pages

<customErrors mode="On defaultRedirect="Error.aspx">


<error statusCode="404" redirect="errorpage404.aspx" />
</customErrors>

<customErrors mode= RemoteOnly defaultRedirect="Error.aspx >


<error statusCode="404" redirect="errorpage404.aspx" />
</customErrors>

© PROGRAM UTVIKLING.no WebExpress - page - 23


Tracing

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.

© PROGRAM UTVIKLING.no WebExpress - page - 24


Trace Log

Writing to the Trace Log

Trace.Write( Page_Load , Entering Event );


Trace.Warn( GetCustomer , Invalid Argument );

© PROGRAM UTVIKLING.no WebExpress - page - 25


2. Programmeringsmodellen

Lær mer om ASP.NET kontrollere.


Innblikk i håndtering av tilstander i applikasjoner og sesjoner.

© PROGRAM UTVIKLING.no WebExpress - page - 26


Framework, Languages, and Tools

VB C++ C# JScript

Common Language Specification

ASP.NET Windows Forms

Data and XML

Base Class Library

Common Language Runtime

Windows COM+ Services

© PROGRAM UTVIKLING.no WebExpress - page - 27


.NET Components

«use»

.NET Base Classes


MyManagedApplication:exe

«use»
«manage»

MyUnmangedApplication
.NET Runtime

«use»
«use»

WIN32 API
«use»
Windows

© PROGRAM UTVIKLING.no WebExpress - page - 28


What is .NET

A library
Basic operating system services
Process creation, threads management etc.
Windows display services
Security credentials verification
Web services
Database connections

A runtime environment for your programs


.NET runtime (also known as Common Language Runtime CLR)
An execution manager for your code
Management of processes, threads, memory, I/O etc.
A layer between Windows OS and your application

© PROGRAM UTVIKLING.no WebExpress - page - 29


JIT Compilation

:C# Code
Compile (csc)

:Assembly (IL code) Check for security and load

Load

Execute managed code

Already JIT ed ?
More code
No Yes

Just in time compilation (JIT) Execute code

:Native Code

© PROGRAM UTVIKLING.no WebExpress - page - 30


ASP.NET Server Controls

Server-programmable objects
Properties, method and events

Encapsulate both behaviour and rendering


Can vary the rendering to support multiple browsers or Web clients

Users can create server controls


Derived from existing controls

Built-in controls
HTML Controls
Web Controls
Intrinsic Controls
List Controls
Validation Controls
Rich Controls

© PROGRAM UTVIKLING.no WebExpress - page - 31


Dragging a Control from Studio onto a Form

Drag a control from the toolbox onto the form


Code is generated
Both HTML code and C# code are added to the project source files
WebForm1.aspx and WebForm1.aspx.cs

© PROGRAM UTVIKLING.no WebExpress - page - 32


Adding Server 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

Example: A new button is added to our form (WebForm1.aspx)


<asp:Button id="clickButton" runat="server OnClick="Button1_Click"
Text="Click me"></asp:Button>

© PROGRAM UTVIKLING.no WebExpress - page - 33


HTML Controls

Copied Directly to HTML Output


Except runat="server" attribute

Accesible from the CodeBehind


By adding the runat="server" attribute

We can use HTML tables for layout


HTML table has better designer support
than <asp:table />

© PROGRAM UTVIKLING as C#.NET - page - 34


Server Controls

Attributes
ID="Label1"
runat="server

Programatic access to properties, methods


and events

Wrap functionality

Emits standard HTML when rendered

Can store state information in ViewState


or ControlState

© PROGRAM UTVIKLING as C#.NET - page - 35


Label

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!";

Has properties and events

© PROGRAM UTVIKLING as C#.NET - page - 36


TextBox

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;
}

© PROGRAM UTVIKLING as C#.NET - page - 37


Button

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" />

Causes postback when clicked


Handle the Click event
protected void Button1_Click(object sender, EventArgs e)
{
//Do something usefull...
}

The LinkButton and ImageButton controls provide the same


funtionality, but with a different UI
They implement the IButtonControl interface

© PROGRAM UTVIKLING as C#.NET - page - 38


DropDownList

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>

Setting the AutoPostback property will cause a postback when the


selected item has changed

The ListBox provides similar functionality, but with a different UI


CheckListBox, RadioButtonList

© PROGRAM UTVIKLING as C#.NET - page - 39


The Generated Code File

Event handlers were added for us


We have to add our specific code

WebForm1.aspx.cs
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}

private void Button1_Click(object sender, System.EventArgs e)


{
clickButton.Text = "Pressed";
}
}

© PROGRAM UTVIKLING.no WebExpress - page - 40


PostBack

Server roundtrip

Caused by an event on a control


Clicking a Button
Selecting an item
Checking a CheckBox
Choosing a RadioButton

Posts back data within the HTML <form> elements


Which button was clicked
The text of a TextBox
The selection in a ListBox

© PROGRAM UTVIKLING as C#.NET - page - 41


Page Event Life Cycle

:Browser :.NET framework

Button pressed
HTTP postback
WebForm1() :WebForm1

clickButton
clickButton :Button

Page_Load

clickButton_Click()

© PROGRAM UTVIKLING.no WebExpress - page - 42


IsPostBack

The IsPostBack property is used to determine wether the page is


requested as a result of a postback
The click of a button
Selection in a list with the AutoPostBack property set

protected void Page_Load(object sender, EventArgs e)


{
if (!IsPostBack)
{
//Populate controls only on first request
Person[] persons = Person.GetPersons();
ListBox1.Items.AddRange(persons);
}
}

State is kept in ViewState

© PROGRAM UTVIKLING as C#.NET - page - 43


What is Validation

Validation is making sure that input has valid values


Types of validation
Is this an integer between 1 and 100?
Is this empty?
Is this a valid date in the past?
Is this an email address?
ASP.NET Validation Controls
Run at client (using JScript) if possible
Run at server allways

© PROGRAM UTVIKLING as C#.NET - page - 44


Different Types of Validators

RequiredFieldValidator
RangeValidator
CompareValidator
RegularExpressionValidator
CustomValidator

© PROGRAM UTVIKLING as C#.NET - page - 45


RequiredFieldValidator

Checks if a control has a value or not

<asp:ListBox ID="_colorsListBox" runat="server"></asp:ListBox>

<asp:RequiredFieldValidator ID="_colorRequiredFieldValidator" runat="server"


ErrorMessage="You must select a color!" ControlToValidate="_colorsListBox"
Text="*">
</asp:RequiredFieldValidator>

InitialValue property defines the no value


Defaults to an empty string

© PROGRAM UTVIKLING as C#.NET - page - 46


What is AJAX?

Asyncronous JavaScript and XML

Use of clientside technologies


XmlHttpRequest
JScript
The Document Object Model (DOM)
CSS

Enabling Out-of-band communication with server


Without reloading the entire page

Changing the current page without reloading it

© PROGRAM UTVIKLING as C#.NET - page - 47


ScriptManager

Manages scripts
References, Localization

Serves the correct scripts as needed


ASP.NET AJAX Client Library
UpdatePanel, ProgressBar, Timer controls
Debug version or release version
Our own scripts
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Scripts>
<asp:ScriptReference Path="myScript.js" />
</Scripts>
</asp:ScriptManager>

Calls Sys.Application.initialize()
Starts the lifecycle events

© PROGRAM UTVIKLING as C#.NET - page - 48


UpdatePanel

Instant AJAX

AJAX-ifies ordinary PostBacks


Compatible with most standard ASP.NET controls
Marks a part of the page for update via AJAX
Reduces screen flicker

Requires a ScriptManager

© PROGRAM UTVIKLING as C#.NET - page - 49


UpdatePanel

UpdateMode defaults to Always


Panel is automatically updated on all AJAX calls

ChildrenAsTriggers defaults to true


All child controls in an updatepanel use AJAX

Triggers collection
Add an outside button as AsyncPostBackTrigger
Add an inside button as PostBack Trigger

© PROGRAM UTVIKLING as C#.NET - page - 50


Timer

The Timer control is a trigger


Will trigger a postback if neither
set as AsyncPostBackTrigger
or
placed inside UpdatePanel

Don t trust the accuracy of the timer

© PROGRAM UTVIKLING as C#.NET - page - 51


Keep Waiting

When an operation takes time, it s nice to tell the


users we re alive!

© PROGRAM UTVIKLING as C#.NET - page - 52


Ajax Control Toolkit

The ASP.NET AJAX Control Toolkit

A shared source project built on top of the Microsoft ASP.NET


AJAX framework.

Provides a array of controls that can be used out of the box to


create an interactive Web experience.

Download the Ajax Control Toolkit:


http://asp.net/ajax/ajaxcontroltoolkit

© PROGRAM UTVIKLING as C#.NET - page - 53


Application State

Application state
Shared across multiple clients, connected to your web application

It can be accessed through the Page object s Application


property
public sealed class HttpApplicationState :
NameObjectCollectionBase

Initialize state in the global.asax s Application_Start procedure

Application state is not shared in a web farm or web garden

© PROGRAM UTVIKLING.no WebExpress - page - 54


Application State

global.asax
HttpApplication is the base class

void Application_Start()
{
DataSet bookingDS = new DataSet();
Application[ bookingDS ] = bookingDS ;
}

bookingpage.aspx

void Page_Load(Object Src, EventArgs e)


{
DataSet bookingSs = (DataSet)Application[ bookingDs ];
bookingGrid.Source = ds.Tables[0].BookingView;
bookingGrid.DataBind();
}

© PROGRAM UTVIKLING.no WebExpress - page - 55


Session State

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

© PROGRAM UTVIKLING.no WebExpress - page - 56


Session State

Access session state through the Page Session property


public class HttpSessionState : ICollection, IEnumerable

Initialize session state in


Session_Start() procedure in global.asax

Cleanup resources in
Session_End() procedure in global.asax

© PROGRAM UTVIKLING.no WebExpress - page - 57


Session State
global.asax

void Session_Start() {
// initialize
Session[ SelectedRoomName ] = Nordpolen ;
}

Write session

void Page_Load( object Src, EventArgs e) {


Session[ SelectedRoomName ] = TextBox1.Text;
}

Read session
void Page_Load( object Src, EventArgs e) {
RoomTextBox.Text =
(string)Session[ SelectedRoomName ];
}

© PROGRAM UTVIKLING.no WebExpress - page - 58


Global Methods

Global.asax
Contains predefined Event Handlers:

protected void Application_Start(object sender, EventArgs e)


Called when the very first request appears
Useful for loading site specific information

protected void Application_End(object sender, EventArgs e)

protected void Session_Start(object sender, EventArgs e)


Called upon the first request from a new user

protected void Session_End(object sender, EventArgs e)


Called when the application times out, or the user logs off

© PROGRAM UTVIKLING.no WebExpress - page - 59


User Controls

User Control: A mini WebForm


Created using ASP.NET code
Could be reused in multiple ASP.NET pages
Can define properties and methods

© PROGRAM UTVIKLING.no WebExpress - page - 60


A Room User Control

A User Control: Room User Control


Shows the shape of a meeting
room
Using
Bitmap file
Label

© PROGRAM UTVIKLING.no WebExpress - page - 61


RoomUserCtrl.ascx

Inserting a UserControl to your site


Adding a Image and a Label

<%@ Control Language="C#" AutoEventWireup="true"


CodeFile="RoomUserCtrl.ascx.cs" Inherits="RoomUserCtrl" %>
<asp:Image ID="Image1" runat="server" ImageUrl="~/Image/uShape.jpg" Style="z-index: 100;
left: 0px; position: absolute; top: 0px" />
<asp:Label ID="Label1" runat="server" Style="z-index: 102; left: 137px; position: absolute;
top: 65px" Text="Sydpolen" Font-Bold="True" Font-Names="Arial" Font-Size="20pt">
</asp:Label>

© PROGRAM UTVIKLING.no WebExpress - page - 62


RoomUserCtrl.ascx.cs

public class RoomUserCtrl : System.Web.UI.UserControl


{
Room room;
public Room Room{ set {room=value;}}

private void Page_Load(object sender, System.EventArgs e)


{
if (room != null)
{
switch(room.Shape)
{
case (RoomShape.schoolClass):
ShapeImage.ImageUrl="classRoom.bmp";
break;

case (RoomShape.uShape):
. . .
}
RoomName.Text= room.Name;
}
}

© PROGRAM UTVIKLING.no WebExpress - page - 63


Using The New Controller in Default.aspx
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs"
AutoEventWireup="false" Inherits="ControlTest.WebForm1" %>
<%@ Register TagPrefix="UC" TagName="RoomUserCtrl" Src="RoomUserCtrl.ascx" %>
<HTML>
<HEAD> . . . </HEAD>
<body> <form runat="server">
<asp:Label id="Label1" runat="server" Font-Size="14pt"
Font-Names="Arial" Font-Bold="True">Rooms</asp:Label>
<p></p>
<asp:listbox id="roomListBox" runat="server" Width="210px" Height="96px"
AutoPostBack="True"
Font-Size="14pt" Font-Names="Arial"></asp:listbox>
<p></p>
<UC:roomuserctrl id= RoomUserCtrl1" runat="server"></UC:roomuserctrl>
</form>
</body>
</HTML>

© PROGRAM UTVIKLING.no WebExpress - page - 64


Default.aspx.cs

public class WebForm1 : System.Web.UI.Page


{
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialise the page here
Room room= new Room("Sydpolen",RoomShape.schoolClass);
roomList.Add(room);
roomList.Add(new Room("Nordpolen",RoomShape.uShape));
roomList.Add(new Room("Vest pasasjen",RoomShape.blank));
roomList.Add(new Room("Øst pasasjen",RoomShape.tShape));
if (!IsPostBack)
{
roomListBox.DataSource= roomList;
roomListBox.DataBind();
}
else
roomCtrl.Room= (Room)roomList[roomListBox.SelectedIndex];
}

© PROGRAM UTVIKLING.no WebExpress - page - 65


3. Master Page

Håndtereing en hovedside forskjellige innholdssider.


Vi ser nærmere på håndtering av felles utseende med
"Themes & Skin og navigering med menyer og
trekontrollere.

© PROGRAM UTVIKLING.no WebExpress - page - 66


Master Pages

Master Page

Content Page

© PROGRAM UTVIKLING.no WebExpress - page - 67


Master Page Basics
Masters define common content and placeholders
(<asp:ContentPlaceHolder>)

Content pages reference masters and fill placeholders with content


(<asp:Content>)

Site.master default.aspx http://.../default.aspx

<%@ Page MasterPage-


<%@ Master %> File="Site.master" %>
<asp:Content
ContentPlaceHolderID=
"Main" RunAt="server" />
<asp:ContentPlaceHolder
ID="Main"
RunAt="server" />

</asp:Content>

© PROGRAM UTVIKLING.no WebExpress - page - 68


Adding a Master Page

Creating a master page is done in this steps

Adding a new master page into your site


Designing the master page
Adding the content pages that uses the master page

© PROGRAM UTVIKLING.no WebExpress - page - 69


The New Master Page

A ContentPlaceHolder is placed on
the master page
It will be filled by the content of the
pages that uses this master page

You can add anything you want


surrounding the placeholder
It will be replicated on pages that
uses this master page

© PROGRAM UTVIKLING.no WebExpress - page - 70


Adding Controls To The Master Page

A table, containing a Image and Label are added to the maser page

© PROGRAM UTVIKLING.no WebExpress - page - 71


Master Page Source

<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>

© PROGRAM UTVIKLING.no WebExpress - page - 72


Applying a Master Page

<%@ Page MasterPageFile="~/Site.master" %>

<asp:Content
ContentPlaceHolderID="ContentPlaceHolder1 RunAt="server">

This content fills the place holder "Main"


defined in the master page

</asp:Content>

© PROGRAM UTVIKLING.no WebExpress - page - 73


Adding a New Web Form

Check the Select Master Page

© PROGRAM UTVIKLING.no WebExpress - page - 74


Ready For New Content

© PROGRAM UTVIKLING.no WebExpress - page - 75


The New Page Is Running

© PROGRAM UTVIKLING.no WebExpress - page - 76


MainPage.aspx Tags

The new page content is placed in an <asp:Content >, that refers


back to the ContentPlaceHolder, that was defined in the master page
There is no <html >, <!DOCTYPE >, <body> or <form>

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master"


AutoEventWireup="true" CodeFile="MainPage.aspx.cs" Inherits="MainPage"
Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1"
Runat="Server">
<asp:Calendar ID="Calendar1" runat="server" . . .
</asp:Calendar>
</asp:Content>

© PROGRAM UTVIKLING.no WebExpress - page - 77


Site Navigation

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

© PROGRAM UTVIKLING.no WebExpress - page - 78


Adding a Web Sitemap

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


<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode url="" title="" description="">
<siteMapNode url="" title="" description="" />
<siteMapNode url="" title="" description="" />
</siteMapNode>
</siteMap>

© PROGRAM UTVIKLING.no WebExpress - page - 79


Filling In The Site Map

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

<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >


<siteMapNode url="MainPage.aspx" title="Main Page" description="Main Page">
<siteMapNode url="Room.aspx" title="Room configuration"
description="Configuration of Rooms" />
<siteMapNode url="Equipment.aspx" title="Equipment configuration"
description="Configuration of Equipment" />
<siteMapNode url="Bookings.aspx" title="Active Bookings"
description="Display of booking" >
<siteMapNode url="RoomBookings.aspx" title="Rooms Booking"
description="Room Booking" />
<siteMapNode url="EquipmentBookings.aspx" title="Equipment Bookings"
description="Equipment bookings" />
</siteMapNode>
</siteMapNode>

</siteMap>

© PROGRAM UTVIKLING.no WebExpress - page - 80


Hiding the Root

xxxx.aspx

<asp:SiteMapDataSource ID="SiteMap" RunAt="server"


ShowStartingNode="false />
<asp:Menu DataSourceID="SiteMap" RunAt="server" />

© PROGRAM UTVIKLING.no WebExpress - page - 81


Adding A Menu Control

© PROGRAM UTVIKLING.no WebExpress - page - 82


Menu Controls

Drop-down/fly-out menus for Web pages


Items are navigable or selectable
Can be oriented horizontally or vertically

Content defined by MenuItem objects


MenuItems can be added declaratively, programmatically, or through data
binding

Highly customizable UI

Menu Events
MenuItemClick: Fired when a menu item is clicked
MenuItemDataBound: Fired when a menu item binds to a data source

© PROGRAM UTVIKLING.no WebExpress - page - 83


Menus and Site Maps

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

<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >


<siteMapNode url="MainPage.aspx" title="Main Page" description="Main Page">
. . . .

</siteMapNode>

</siteMap>

xxxx.aspx
<asp:SiteMapDataSource ID="SiteMap" RunAt="server" />
<asp:Menu DataSourceID="SiteMap" RunAt="server" />

© PROGRAM UTVIKLING.no WebExpress - page - 84


SiteMapDataSource

Data source control representing site maps


Site map = List of pages and URLs
Nodes can include descriptive text

Permits TreeViews and Menus to be populated with links through data


binding

Supports "security trimming"


Specified nodes visible only to specified roles

Provider-based for flexible data storage

© PROGRAM UTVIKLING.no WebExpress - page - 85


TreeView Controls

Render hierarchical data as trees


Expandable and collapsible branches
Nodes are navigable, selectable, or static and can include check boxes

Content defined by TreeNode objects


TreeNodes can be added declaratively, programmatically, or through data
binding
TreeNodes can also be demand-loaded

Fire events
CheckChanged, SelectedNodeChanged
TreeNodeCollapsed, TreeNodeExpanded

© PROGRAM UTVIKLING.no WebExpress - page - 86


Using a TreeView Controller

Adding a TreeView controler to the master page


Binding it to a SiteMapDataSource

© PROGRAM UTVIKLING.no WebExpress - page - 87


TreeView and Site Maps
Web.sitemap
<?xml version="1.0" encoding="utf-8" ?>

<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >


<siteMapNode url="MainPage.aspx" title="Main Page" description="Main Page">
. . . .

</siteMapNode>

</siteMap>

xxxx.aspx
<asp:SiteMapDataSource ID="SiteMap" RunAt="server" />
<asp:TreeView DataSourceID="SiteMap" RunAt="server" />

© PROGRAM UTVIKLING.no WebExpress - page - 88


Example without a SiteMapDataSource

<asp:TreeView ShowLines="true" Font-Name="Verdana" Font-Size="10pt" ... >


<SelectedNodeStyle BackColor="Yellow" />
<HoverNodeStyle BackColor="LightBlue" />
<Nodes>
<asp:TreeNode Text="Not selectable" SelectAction="None" RunAt="server">
<asp:TreeNode Text="Selectable" SelectAction="Select" RunAt="server" >
<asp:TreeNode Text="Click to expand or collapse"
SelectAction="Expand" Runat="server">
<asp:TreeNode Text="Click to select and expand or collapse"
SelectAction="SelectExpand" Runat="server">
<asp:TreeNode Text="Check box node" ShowCheckBox="true"
Runat="server">
<asp:TreeNode Text="Click to navigate" NavigateUrl="..."
Runat="server" />
</asp:TreeNode>
</asp:TreeNode>
</asp:TreeNode>
</asp:TreeNode>
</asp:TreeNode>
</Nodes>
</asp:TreeView>
© PROGRAM UTVIKLING.no WebExpress - page - 89
SiteMapPath Control

"Bread crumbs" showing path to page


By default, renders current node as static text
By default, renders parent nodes as hyperlinks

Highly customizable UI
Nodes can be stylized and templatized
Separators can be stylized and templatized

© PROGRAM UTVIKLING.no WebExpress - page - 90


4 Håndtering av datakilder

Listekontroller med kobling mot databaser.


Hvordan konfigurere SQL Server 2005 Express?
Håndtering av en-til-mange-relasjoner.

© PROGRAM UTVIKLING.no WebExpress - page - 91


Data-Driven controls

Simplified data binding


Data source controls
Data controls
GridView and DetailsView controls
Editing with GridView and DetailsView

© PROGRAM UTVIKLING.no WebExpress - page - 92


DataSource Controls

Declarative (no-code) data binding


Have no rendering, represent a particular backend data store

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

© PROGRAM UTVIKLING.no WebExpress - page - 93


ObjectDataSource

Declarative binding to data components


Leverage middle-tier data access components
Keep data access code separate from UI layer

Two-way data binding


SelectMethod, InsertMethod, UpdateMethod, and DeleteMethod

Optional caching of query results

© PROGRAM UTVIKLING.no WebExpress - page - 94


Adding an ObjectDataSource

Drag an ObjectDataSource from the Toolbox onto the page


Situated the data compartment

Configure it

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"


DataObjectTypeName="System.Data.DataRow" DeleteMethod="Delete"
InsertMethod="Insert" SelectMethod="GetData" TypeName= RoomList"
UpdateMethod="Update">
</asp:ObjectDataSource>

Drag a GridView onto the page


Connect it to the DataSource

© PROGRAM UTVIKLING.no WebExpress - page - 95


Binding to an ObjectDataStore

public class RoomList


{
DataSet roomDS = new DataSet();
DataTable rooms;

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();
}

public DataSet GetData()


{
return roomDS;
}
. . .
}

© PROGRAM UTVIKLING.no WebExpress - page - 96


SqlDataSource

Declarative data binding to SQL databases


Any database served by a managed provider

Two-way data binding


SelectCommand defines query semantics
InsertCommand, UpdateCommand, and DeleteCommand define update
semantics

xxx.aspx
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:CateringDBConnectionString %>
SelectCommand="SELECT [Name], [Size], [RoomID] FROM [Room]">
</asp:SqlDataSource>

© PROGRAM UTVIKLING.no WebExpress - page - 97


Configuration strings

In the <configuration> section in the Web.config file

Web.config
...
<connectionStrings>
<add name="CateringDBConnectionString"
connectionString="Data Source=.;
Initial Catalog=CateringDB;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
...

© PROGRAM UTVIKLING.no WebExpress - page - 98


SqlDataSource and Caching

SqlDataSource supports declarative caching of results through these


properties:
EnableCaching
Specifies whether caching is enabled (default = false)
CacheDuration
Length of time in seconds results should be cached
CacheExpirationPolicy
Specifies whether cache duration is sliding or absolute

<asp:SqlDataSource ID="Countries" RunAt="server"


...
EnableCaching="true" CacheDuration="60" />

© PROGRAM UTVIKLING.no WebExpress - page - 99


AccessDataSource

<asp:AccessDataSource ID="AccessDataSource1" runat="server"


DataFile="~/App_Data/booking.mdb"
SelectCommand="SELECT [Name], [RoomSize] FROM
[Room]"></asp:AccessDataSource>

Properties
DataFile
Path to data source

SQL commands:
SelectCommand, InsertCommand, UpdateCommand,
DeleteCommand

DataSourceMode
Specifies whether DataSet or DataReader is used (default =
DataSet)

© PROGRAM UTVIKLING.no WebExpress - page - 100


XmlDataSource

Supports caching and XSL transformations


One-way data binding only; no updating
Caching, same as for SqlDataSource

...

<asp:XmlDataSource ID="Rates" DataFile="Rooms.xml" RunAt="server" />

...

Key properties
DataFile
Path to file containing XML data
TransformFile
Path to file containing XSL style sheet
XPath
XPath expression used to filter data

© PROGRAM UTVIKLING.no WebExpress - page - 101


Data-bound controls

Categories of data-bound controls


List controls
DropDownList, CheckBoxList, RadioButtonList, BulletList
Iterative controls
Repeater, DataList, DataGrid, GridView, DetailsView, FormView

DataSourceID
Connects to the DataSource

<asp:XmlDataSource ID="XmlDataSource1" . . .

<asp:BulletedList ID="BulletedList1" DataSourceID="XmlDataSource1 . . .

© PROGRAM UTVIKLING.no WebExpress - page - 102


RadioButtonList

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

<asp:XmlDataSource ID="XmlDataSource1 DataFile="~/App_Data/Rooms.xml" . . .


<asp:RadioButtonList ID="RadioButtonList1" runat="server
DataSourceID="XmlDataSource1 DataTextField="name">

© PROGRAM UTVIKLING.no WebExpress - page - 103


The GridView Control

Enhanced DataGrid control


Renders sets of records as HTML tables

Built-in sorting, paging, selecting, updating, and deleting support

Supports rich assortment of field types, including CheckBoxFields


Declared in <Columns> element

Highly customizable UI

© PROGRAM UTVIKLING.no WebExpress - page - 104


GridView Tasks

© PROGRAM UTVIKLING.no WebExpress - page - 105


Configuring the GridView

<asp:GridView ID="GridView1" runat="server" AllowSorting="True"


AutoGenerateColumns="False" CellPadding="4" DataKeyNames="RoomID"
DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None">
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="Size" HeaderText="Size" SortExpression="Size" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
</Columns>
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>

© PROGRAM UTVIKLING.no WebExpress - page - 106


GridView Example

© PROGRAM UTVIKLING.no WebExpress - page - 107


The DetailsView Control

Renders individual records


Pair with GridView for master-detail views
Or use without GridView to display individual records

Built-in paging, inserting, updating, deleting

Uses same field types as GridView


Declared in <Fields> element

Highly customizable UI

© PROGRAM UTVIKLING.no WebExpress - page - 108


DetailsView Source

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>
...

© PROGRAM UTVIKLING.no WebExpress - page - 109


Working with ADO.NET

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

© PROGRAM UTVIKLING.no WebExpress - page - 110


ADO.NET overview

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

© PROGRAM UTVIKLING.no WebExpress - page - 111


Architecture 3 tiers

View Application Database

BookingAdminView

BookingApp

BookingView
BookingDB

«framework» «framework» «framework»


System.Windows System.Data System.Data.OleDb

Package == namespace

© PROGRAM UTVIKLING.no WebExpress - page - 112


LINQ Overview

C# 3.0

.NET Language Integrated Query

LINQ to LINQ to LINQ to LINQ to LINQ to


Objects DataSets SQL Entities XML

<book>
<title/>

<author/>
<year/>
<price/>
</book>

Objects Relational XML

© PROGRAM UTVIKLING.no WebExpress - page - 113


LINQ

LINQ, or Language Integrated Query


Features for writing structured type-safe queries over local object
collections and remote data sources.

LINQ enables you to


Query any collection implementing IEnumerable<>,
Array, list, or XML DOM,
Remote data sources, such as tables in SQL Server.

LINQ benefits of both compile-time type checking and dynamic query


composition

© PROGRAM UTVIKLING.no WebExpress - page - 114


Extension methods

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

public static class RoomHelper


{
public static string LongRoomName(this Room room)
{
return "The name of the room:" + room.Name;
}
}
class Program
{
static void Main(string[] args)
{
Room r = new Room();
r.Name = "Sydpolen";
Console.WriteLine(r.LongRoomName());
}
} The name of the room:Sydpolen
© PROGRAM UTVIKLING.no WebExpress - page - 115
Lambda expressions

Lambda expressions
Miniature functions created on the fly.

Function name Input parameter Expression (body)

Func<int, int> square = x => x * x;


Console.WriteLine(square(3)); // 9

A lambda expression has the following form:


(parameters) => expression-or-statement-block

A lambda expression's code can be a statement block


x => {return x * x;};

© PROGRAM UTVIKLING.no WebExpress - page - 116


A class to work with

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; }
}

© PROGRAM UTVIKLING.no WebExpress - page - 117


Load Rooms

static IEnumerable<Room> LoadRooms()


{
List<Room> rooms = new List<Room>();
rooms.Add(new Room {
Name= "North", City="Oslo", Seats=20, HasAudio=true });
rooms.Add(new Room {
Name= "West", City="Bergen", Seats=30, HasAudio=true });
rooms.Add(new Room {
Name= "South", City="Bergen", Seats=40, HasAudio=false });
rooms.Add(new Room {
Name= "East", City="Oslo", Seats=50, HasAudio=false });
return rooms;
}

© PROGRAM UTVIKLING.no WebExpress - page - 118


The Problem: Find Rooms In City

static void Main(string[] args)


{
// Get a list of number of rooms in each city
List<RoomsInCity> roomInCityList = new List<RoomsInCity>();
foreach (Room room in LoadRooms())
{
RoomsInCity roomsInCity=
roomInCityList.Find(r => r.City == room.City);
if (roomsInCity == null)
{
roomInCityList.Add(
new RoomsInCity { City = room.City, Count = 1 });
}
else
roomsInCity.Count++; Oslo - 2
} Bergen - 2
foreach (RoomsInCity rc in roomInCityList)
{
Console.WriteLine(rc.City + " - " + rc.Count);
}
}

© PROGRAM UTVIKLING.no WebExpress - page - 119


Using Implicit Typed Local Variable

//List<RoomsInCity> roomInCityList = new List<RoomsInCity>();


//foreach (Room room in LoadRooms())

var roomInCityList = new List<RoomsInCity>();


foreach (var room in LoadRooms())
{
. . .

© PROGRAM UTVIKLING.no WebExpress - page - 120


Collection Initializers

A collection initializer must be of a type IEnumerable


For each specified element in order, the collection initializer invokes the
Add method

static IEnumerable<Room> LoadRooms()


{
List<Room> rooms = new List<Room>();
rooms.Add(new Room {
Name= "North", City="Oslo", Seats=20, HasAudio=true });
. . .
static IEnumerable<Room> LoadRooms()
{
var rooms = new List<Room>()
{
new Room{Name="North", City="Oslo", Seats=20, HasAudio=true },
new Room{Name="West", City="Bergen", Seats=30, HasAudio=true },
new Room{Name="South", City="Bergen", Seats=40, HasAudio=false},
new Room{Name="East", City="Oslo", Seats=50, HasAudio=false }
};
return rooms;
}

© PROGRAM UTVIKLING.no WebExpress - page - 121


Using Linq Queries

// Get all rooms with audio


var audioRooms= Enumerable.Where(LoadRooms(), room => room.HasAudio);

foreach (Room room in audioRooms)


{
Console.WriteLine(room.Name + " - has audio");
}
North - has audio
West - has audio

© PROGRAM UTVIKLING.no WebExpress - page - 122


Query comprehensions

Query comprehension syntax.


A special syntax for writing queries

Here's the preceding query expressed in comprehension syntax :

var audioRooms = from room in LoadRooms()


where room.HasAudio
select room;

foreach (Room room in audioRooms)


{
Console.WriteLine(room.Name + " - has audio");
}
North - has audio
West - has audio

© PROGRAM UTVIKLING.no WebExpress - page - 123


The Solution: Using Linq Queries

var rooms = new List<Room>()


{
new Room{Name="North", City="Oslo", HasAudio=true },
new Room{Name="West", City="Bergen", HasAudio=true },
new Room{Name="South", City="Bergen", HasAudio=false},
new Room{Name="East", City="Oslo", HasAudio=false }
};
var roomInCityList =
from room in rooms
group room by room.City into g
select new
{ City = g.Key, Count = g.Count() };

foreach (var rc in roomInCityList)


{
Console.WriteLine(rc.City + " - " + rc.Count);
}
Oslo - 2
Bergen - 2

© PROGRAM UTVIKLING.no WebExpress - page - 124


LINQ to SQL
using System.Data.Linq.Mapping;

[Table]
class Room
{
[Column(IsPrimaryKey = true)]
public string Name;
[Column]
public int Seats;
}

The [Table] attribute:


Tells LINQ to SQL that an object of this type represents a row in a
database table. By default, it assumes the table name matches the
class name

The [Column] attribute:


Maps a field or property to a column in a table

© PROGRAM UTVIKLING.no WebExpress - page - 125


DataContext

DataContext:
Acts as a factory for generating tables that you can query.

DataContext dataContext = new DataContext(@"connection-string");


Table<Room> rooms = dataContext.GetTable <Room>( );
foreach (var room in rooms)
{
Console.WriteLine(room.Name+", has " +room.Seats+" seats");
}
Nordpolen, has 50 seats
Nansen, has 80 seats
Amundsen, has 70 seats

var bigRooms = from room in rooms


where room.Seats > 60
select room;
Nansen, has 80 seats
Amundsen, has 70 seats

© PROGRAM UTVIKLING.no WebExpress - page - 126


Tracking Changes

DataContext also keeps track of any changes that you make


So that it is possible to write the changes back to the SQL-server:

. . .
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

© PROGRAM UTVIKLING.no WebExpress - page - 127


Auto-Generating Tables

LINQ to SQL entity classes need to follow the structure of their


underlying tables
It can be generated automatically from an existing database schema.
They will be strongly typed.

Add a new item: LINQ to SQL classes

© PROGRAM UTVIKLING.no WebExpress - page - 128


Using The Strongly Typed DataContext

RoomDataContext roomContext = new RoomDataContext();


foreach (var room in roomContext.Rooms)
{
Console.WriteLine(room.Name + ", has " + room.Seats + " seats");
}

Nordpolen, has 20 seats


Nansen, has 80 seats
Amundsen, has 70 seats

© PROGRAM UTVIKLING.no WebExpress - page - 129


The Basic ADO Model

The main classes in the general ADO model (namespace System.data)

DataSet Data:: DataSet


Houses the whole set of data. Could possibly
be the entire database

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

Describes a column in a DataTable, has Contains data for a single row in a


properties such as name and type DataTable, akin to a record in a database
table, or a row from a spreadsheet

© PROGRAM UTVIKLING.no WebExpress - page - 130


Using Relation

Getting all Booking to the first Room

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

© PROGRAM UTVIKLING.no WebExpress - page - 131


Typed DataSet

TableAdapter
Database
Data
Data Data
command
connection adapter
collection

.Update(col1, col2, ) as Int


.FillByName(DataTable, fName) as Int
.Insert(col1, col2, ) as Int
.GetByName(fName) as DataTable
.Delete(pkCol1, [pkCol2]) as Int
.Update(DataTable)

Typed XML
DataSet

© PROGRAM UTVIKLING.no WebExpress - page - 132


Typed 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 and maintain these classes


By use of XML Schema files

Visual Studio can build the XML Schema files from a database

© PROGRAM UTVIKLING.no WebExpress - page - 133


Creating a Database

Creating a Database:
In Solution Explorer
Add > New Item > SQL
DataBase

Generates a SQL Server 2005


Express instance (.mdf)
A free single user version of SQL
Server 2005

© PROGRAM UTVIKLING.no WebExpress - page - 134


Adding Tables and Relations

In Server Explorer Window:


Select Tables and insert new Tables
Add new Tables, Relations,
Constraints etc.

In DataSource Window:
Data > Show Data Sources
Select Tables to add to your DataSet

© PROGRAM UTVIKLING.no WebExpress - page - 135


Configuration of a DataSet

Typed DataSet contains


Typed DataTable
Typed TableDataAdapter
Collection of Queries

Can add userd defined Queries to the


TableDataAdapter

© PROGRAM UTVIKLING.no WebExpress - page - 136


TableAdapeter Query Configuration Wizard

© PROGRAM UTVIKLING.no WebExpress - page - 137


Adding a Query

© PROGRAM UTVIKLING.no WebExpress - page - 138


Specifying Query Parameters

Testing the Query:

© PROGRAM UTVIKLING.no WebExpress - page - 139


Resulting DataSet

Resulting DataSet
Contains GetDataBy
RoomID as input parameter

© PROGRAM UTVIKLING.no WebExpress - page - 140


The Generated Classes

Observe the new classes

Booking is a DataSet that contains


RoomRow, RoomDataTable .

By use of the generated .xsd file


We can also generate XML
Read and Write file

We can mange the new RoomDataTable


Insert, delete and update rows

DataSet DataTable DataRow

RoomDataTable RoomRow
bookingDataSet

© PROGRAM UTVIKLING.no WebExpress - page - 141


Testing the TableAdapter And DataSet

TestBookingDB.cs

public int RoomSizeCount()


{
int totSize = 0;
bookingDataSet bookingDS = new bookingDataSet();
RoomTableAdapter roomTA = new RoomTableAdapter();
roomTA.Fill(bookingDS.Room);
foreach (bookingDataSet.RoomRow room in bookingDS.Room)
{
totSize += room.RoomSize;
}
return totSize; Using Room Property
}

© PROGRAM UTVIKLING.no WebExpress - page - 142


Generating XML From the Data Set

We now have the description of the data set in an XML schema


We can also read and write XML files
The files are plain text, and can be edited in Notepad.
C:\course\C#\Code\BookingDB\Booking.xml
<?xml version="1.0" standalone="yes"?>
<Booking xmlns="http://tempuri.org/Booking.xsd">
<Room>
<ID>1</ID>
<name>Fossekallen</name>
<size>100</size>
</Room>
<Room>
<ID>2</ID> Added source lines in TestBookingDB.cs
<name>Sliperiet</name> Booking.RoomRow r= ds.Room.NewRoomRow();
<size>40</size> r.ID= 5;
</Room> r.name= "Pub'en";
<Room>
<ID>5</ID> r.size= 60;
<name>Pub'en</name> ds.Room.AddRoomRow(r);
<size>60</size> ds.WriteXml(".\\Booking.xml");
</Room>
</Booking>

© PROGRAM UTVIKLING.no WebExpress - page - 143


Making an ASP.NET Application

Making a Participant Management Form


Used to
Register new Participants
Delete participants
Send information to all participants

Create an ASP.NET Web Site


Create a ParticipantMgtForm
Add
Labels, TextBoxes,
Buttons and Hyperlinks

DropDownList
Enable for automatic postback

© PROGRAM UTVIKLING.no WebExpress - page - 144


Adding an XML File as a Database

Right click on the project header in Solution Explorer


select Add -> New Item
Select DataSet, call it Participants.xsd and accept AppCode folder
Cancel the TableAdapter wizard
Drag out a DataTable from the toolbox, and configure it

Select Schema from the menu


and Generate DataSet
In Class View observe the new Participants DataSet,
ParticipantDataTabel and ParticipantDataRow

Still in Class View in Global, select:


Application_Start(..)

© PROGRAM UTVIKLING.no WebExpress - page - 145


Adding an XML File as a Database

Right click on the project header in Solution Explorer


select Add -> New Item
Select DataSet, call it Participants.xsd
accept AppCode folder
Cancel the TableAdapter wizard
Drag a DataTable from the toolbox

Select App_Data folder, in Soloution Explorer


Add a new XML file to your site
Add a Participant DataSet

© PROGRAM UTVIKLING.no WebExpress - page - 146


Add A Few Rows
View the XML file as DataGrid
Add some participants

Viewing the XML file in normal mode

<?xml version="1.0" standalone="yes"?>


<ParticipantDS xmlns="http://tempuri.org/ParticipantDS.xsd">
<Participant>
<ParticipantID>1</ParticipantID>
<Name>Edel Gran</Name>
<Email>[email protected]</Email>
<WebAdress>www.skog.no</WebAdress>
</Participant>
<Participant>
<ParticipantID>2</ParticipantID>
<Name>Petter Smart</Name>
<Email>[email protected]</Email>
<WebAdress>wwww.disney.com</WebAdress>
</Participant>
</ParticipantDS>

© PROGRAM UTVIKLING.no WebExpress - page - 147


Making the Global Methods

Adding a Global Application Class (Global.asax)


Loading the DataSet, and keeping the data alive at the Server

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;
}

© PROGRAM UTVIKLING.no WebExpress - page - 148


Loading the Drop Down List

Things to do when the page get loaded


Default.cs
public class _Default : System.Web.UI.Page
{
ParticipantDS participantDS;
private void Page_Load(object sender, System.EventArgs e)
{
participantDS= (ParticipantDS) Application["ParticipantDS"];
if (!IsPostBack)
loadListBox();
}

void loadListBox()
{
participantDropDownList.Items.Clear();
foreach(ParticipantDS.ParticipantRow p in participantDS.Participant)
participantDropDownList.Items.Add(
new ListItem(p.Name, p.ParticipantID.ToString()));
}
. . .

© PROGRAM UTVIKLING.no WebExpress - page - 149


Adding and Deleting Participants
Default.cs
private void NewButton_Click(object sender, System.EventArgs e)
{
ParticipantDS.ParticipantRow
p = participantDS.Participant.NewParticipantRow();
p.Name = NameTextBox.Text;
p.Email = EmailTextBox.Text;
p.WebAdress = wwwTextBox.Text;
participantDS.Participant.AddParticipantRow(p);
loadListBox();
participantDS.WriteXml(Server.MapPath(Utility.FileName));
}
private void DeleteButton_Click(object sender, System.EventArgs e)
{
if (participantDropDownList.SelectedIndex >= 0)
{
ParticipantDS.ParticipantRow p = (ParticipantDS.ParticipantRow)
participantDS.Participant.Rows.
Find(participantDropDownList.SelectedValue);
if (p != null)
{
p.Delete();
loadListBox();
participantDS.WriteXml(Server.MapPath(Utility.FileName));
}
}
}

© PROGRAM UTVIKLING.no WebExpress - page - 150


Themes and Skins

Mechanism for theming controls, pages, and sites by group-initializing


control properties

Skin = Visual attributes for control(s)


Physically stored in .skin files
Default skins and named skins

Theme = Collection of one or more skins


Physically stored in Themes subfolders
Global themes and local themes

© PROGRAM UTVIKLING.no WebExpress - page - 151


Applying a Theme to a Page

<%@ Page Theme="BasicBlue">

Before After

© PROGRAM UTVIKLING.no WebExpress - page - 152


Applying a Theme

To a site

<configuration>
<system.web>
<pages theme="BasicBlue" />
</system.web>
</configuration>

Programmatically

void Page_PreInit (Object sender, EventArgs e)


{
Page.Theme = "BasicBlue";
}

© PROGRAM UTVIKLING.no WebExpress - page - 153


Themes

vroot
Theme name =
Subdirectory name

App_Themes

SKIN
Shocking-
SKIN
Pink

SKIN
Autumn-
SKIN
Leaves

© PROGRAM UTVIKLING.no WebExpress - page - 154


Applying a Theme

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>

<%@ Page Theme="Shock . . . %> Added to the xxx.aspx page

~\App_Themes\Shock\HotPink.skin
<asp:ListBox runat="server" Font-Names="Script MT Bold"
Font-Size="20pt" Width="213px"/>

© PROGRAM UTVIKLING.no WebExpress - page - 155


Named Skins

Skins without SkinIDs are default skins

Skins with SkinIDs are named skins


SkinIDs must be unique per control type
Can be defined in same SKIN file as default skins or in separate files

Use controls' SkinID properties to apply named skins

© PROGRAM UTVIKLING.no WebExpress - page - 156


Using a Named Skins

~\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" />
...

© PROGRAM UTVIKLING.no WebExpress - page - 157


5. Håndtering av brukere

Administrering av en website.
Håndtering av flere brukere med ulike roller.
Sikre tilgang til sidene i en webløsning?

© PROGRAM UTVIKLING.no WebExpress - page - 158


Security

Reasons for Security


Prevent access to areas of your Web server
Record and store secure relevant user data

Security Configuration in Web.Config


<authorization>, <authentication>, ...

Authentication
Validates user credentials
Types of authentication
Windows
Passport, centralized services provided by Microsoft
Forms,

Authorization
Determine whether request is permitted

© PROGRAM UTVIKLING.no WebExpress - page - 159


Login Controls

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

© PROGRAM UTVIKLING.no WebExpress - page - 160


Login Status

<asp:LoginView ID="LoginView1" runat="server">


<AnonymousTemplate>
You are anonymous - <asp:LoginStatus ID="LoginStatus2" runat="server" />
</AnonymousTemplate>
<LoggedInTemplate>
Logged in as user:
<asp:LoginName ID="LoginName1" runat="server" />
<asp:LoginStatus ID="LoginStatus2" runat="server" />
</LoggedInTemplate>
</asp:LoginView>

© PROGRAM UTVIKLING.no WebExpress - page - 161


The Login Control

Standard UI for logging in users

Integrates with membership service


Calls ValidateUser automatically
No-code validation and logins

Also works without membership service

Incorporates RequiredFieldValidators

Highly customizable UI and behavior

© PROGRAM UTVIKLING.no WebExpress - page - 162


Using the Login Control

<html>
<body>
<form runat="server">
<asp:Login RunAt="server" />
</form>
</body>
</html>

© PROGRAM UTVIKLING.no WebExpress - page - 163


Customizing the Login Control

<asp:Login ID="LoginControl" RunAt="server"


CreateUserText="Create new account"
CreateUserUrl="CreateUser.aspx"
DisplayRememberMe="false"
PasswordRecoveryText="Forgotten your password?"
PasswordRecoveryUrl="RecoverPassword.aspx"
SubmitButtonText="Do It!"
TitleText="Please Log In"
/>

© PROGRAM UTVIKLING.no WebExpress - page - 164


Login Control Events

Login Control Events:

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

© PROGRAM UTVIKLING.no WebExpress - page - 165


Validating Credential Formats

<asp:Login ID="LoginControl" RunAt="server"


OnLoggingIn="OnValidateCredentials" ... />
.. . .
<script language="C#" runat="server">
void OnValidateCredentials (object sender, CancelEventArgs e)
{
if (!Regex.IsMatch (LoginControl.UserName, "[a-zA-Z0-9]{6,}") ||
!Regex.IsMatch (LoginControl.Password, "[a-zA-Z0-9]{8,}"))
{
LoginControl.InstructionText = "User names and passwords " +
"must contain letters and numbers only and must be at " +
"least 6 and 8 characters long, respectively";
e.Cancel = true;
}
}
</script>

© PROGRAM UTVIKLING.no WebExpress - page - 166


The Membership Class

Provides static methods for performing key membership tasks


Creating and deleting users
Retrieving information about users
Generating random passwords
Validating logins

© PROGRAM UTVIKLING.no WebExpress - page - 167


Creating New Users

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:
}
}

© PROGRAM UTVIKLING.no WebExpress - page - 168


Validating Logins

if (Membership.ValidateUser (UserName.Text, Password.Text))


FormsAuthentication.RedirectFromLoginPage (UserName.Text,
RememberMe.Checked);

© PROGRAM UTVIKLING.no WebExpress - page - 169


Membership Schema

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

© PROGRAM UTVIKLING.no WebExpress - page - 170


The MembershipUser Class

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

protected void Page_Load( object sender, EventArgs e)


{
MembershipUser user= Membership.GetUser();
if (user != null)
statusLabel.Text = "Hello " + user.UserName +
", you are registered with email= " + user.Email;
else
statusLabel.Text = "Unkown user";
}

© PROGRAM UTVIKLING.no WebExpress - page - 171


The Roles Class

Gateway to the Role Management API

Provides static methods for performing key role management tasks


Creating and deleting roles
Adding users to roles
Removing users from roles and more

if (Roles.Enabled)
{
Roles.IsUserInRole("Developer");
statusLabel.Text += " - Welcome to the developer community";
}

© PROGRAM UTVIKLING.no WebExpress - page - 172


Enabling the Role Manager

Role management is disabled by default

Enable it via Web.config:


Enable it through the Web Site Administration Tool

<configuration>
<system.web>
<roleManager enabled="true" />
</system.web>
</configuration>

© PROGRAM UTVIKLING.no WebExpress - page - 173


Using Roles class

Creating a new Role

if (!Roles.RoleExists ("Developers"))
{
Roles.CreateRole ("Developers");
}

Adding a user to a Role

string name = Membership.GetUser ().Username;


Roles.AddUserToRole (name, "Developers");

© PROGRAM UTVIKLING.no WebExpress - page - 174


Web Services

Web Services is a new way of performing remote method calls


Expose methods over the Internet
Allow any client to use the service facilities
Platform and browser independent
Universally understood data format, uses
HTTP or RPC (Remote Procedure Calls)
Simple Object Access Protocol (SOAP)

Loosely coupled messaging system


Self-describing text-based communication

Similar communication to any device


Can be accessed simply by specifying the URL

© PROGRAM UTVIKLING.no WebExpress - page - 175


Protocols

Web Service
Open
Internet
Protocols A programmable service accessible
via standard Web protocols

Universal Description Discovery and UDDI & DISCO


Integration (UDDI) initiative
Web services are defined in terms of the
formats and ordering of messages
WSDL(SDL)

Web service consumers can send and SOAP


receive messages using XML
All these capabilities are built using open XML, XSD
Internet protocols HTTP, SMTP

© PROGRAM UTVIKLING.no WebExpress - page - 176


Web Service Execution

Your Web
Service
Passed to
Calls Assemblies

SOAP Request
asmx
File
ASP
Engine
MyApp.exe
Instantiate

SOAP Response XML based


Response
Web Service
Client
Server

© PROGRAM UTVIKLING.no WebExpress - page - 177


A Simple Web Service
<%@ WebService Language="c#" Class="MyDate" %>
using System;
Place the file using System.Web.Services;
public class MyDate : WebService
Date.asmx in a {
virtual directory [WebMethod]
public string Now()
{
return "Time is: " + DateTime.Now.ToString();
}
}

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

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


<string xmlns="http://tempuri.org/">Time is: 10.11.2005 13:37:51
</string>

© PROGRAM UTVIKLING.no WebExpress - page - 178


Creating a Web Service

When we create an Web Service in our site


A WebService.asmx file is generated
Referring to the code behind

<%@ WebService Language="c#" Codebehind="~/App_Code/WebService.cs"


Class="WebService" %>

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";
}
}

© PROGRAM UTVIKLING.no WebExpress - page - 179


Adding a Method

To add a method to our web services, define a public method in


WebService.cs and give it WebMethod attributes
[WebMethod]
public double add(double d1, double d2)
{
return d1+d2;
}

Compile and run the project and observe it in the web browser

© PROGRAM UTVIKLING.no WebExpress - page - 180


Trying the New Web Service

With the web browser pointing at your Service.asmx file


Click on the link add and fill in the form
Click on the button Invoke to send an http request
Will generate an http response as shown

The response to pressing Invoke

© PROGRAM UTVIKLING.no WebExpress - page - 181


WSDL - Service Description.

Web Service Description Language (WSDL) describes the services


Uses an XML format, describing
The services (methods)
The parameter types etc.
Allows dynamic discovery of web services at runtime

The operations and messages are described in an abstract way


When bound to a concrete network protocol and message format, they
define an endpoint
WSDL is extensible and makes it possible to describe endpoints and
their messages regardless of the message formats or network
protocols used to communicate

The WSDL description can be seen in the browser by clicking on


Service Description or by pointing the browser to the address
http://localhost/Simple/SeaTemp.asmx?WSDL

© PROGRAM UTVIKLING.no WebExpress - page - 182


A WSDL Proxy

To implement a Web Service client, we need a proxy class


A proxy class lets us call our Now method from an ordinary C# program
We don t need to worry about how to connect to the server or how
to pass and return parameters to and from the server method
The proxy will take care of the call details for us
The proxy class is seen as normal C# class from our client code

The program wsdl.exe may be used to generate a proxy class:

C:\course\C#>wsdl /l:cs /n:DateNameSpace /out:MyDate.cs


http://localhost/Test/date.asmx?WSDL
Microsoft (R) Web Services Description Language Utility
. . .
Writing file 'MyDate.cs'.

C:\course\C#>

© PROGRAM UTVIKLING.no WebExpress - page - 183


A Simple Client Calling Now()

A simple console program could now be used to call the service


using System;
using TestingWS.localhost;

class NowWrapper
{
static void Main(string[] args)
{
MyDate date= new MyDate();
Console.WriteLine(date.Now());
}
}

Time is: 12.12.2005 11:22:17


The output:
Press any key to continue

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

© PROGRAM UTVIKLING.no WebExpress - page - 184


SOAP Example in HTTP
POST /Accounts/Henrik.asmx HTTP/1.1
Host: www.webservicebank.com HTTP Request
Content-Length: nnnn
Content-Type: text/xml; charset="utf-8"
SOAP Message
SOAPAction: "Some-URI"

<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>

© PROGRAM UTVIKLING.no WebExpress - page - 185


Web Application

A Web service
Makes the internet XML
Web Web
accessible from an Service Service
application Internet

XML
Web
Application

© PROGRAM UTVIKLING.no WebExpress - page - 186


Consuming Web Services

Integrating web services in an application using Visual Studio


1) Make a client application that will use the web service
2) Make a proxy class that knows how to communicate with the web
service
Gives our code the illusion that we have a local copy of the
service

1) Make a client application project in Visual Studio


Can be any type of application, for instance a console application

2) Add the Web Reference to the project


VisualStudio inspects the description of the service (wsdl) )
Generates the proxy class in the namespace
YourClientNameSpace.localhost

© PROGRAM UTVIKLING.no WebExpress - page - 187


A Simple Service

Below is an example of a client code


Accesses the Add web service through the proxy generated by VS

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);
}
}
}

© PROGRAM UTVIKLING.no WebExpress - page - 188


Testing a Real Weather Forecast Web Service

Search for Web Services can be done at:


http://www.webservicex.net
Search for Forecast, and the following reference will appear
http://www.regex.com.au/weather/RegexWeatherService.wsdl
In Visual Studio, add Web References to the .wsdl file
Will automatically generate the proxy or wrapper classes you need
Use it:
static void Main(string[] args)
{
RegexWeatherService service= new RegexWeatherService();
WeatherForecast forecast= service.getForecast("Sydney");
Console.WriteLine("Weather forecast for {0}, issued={1}",
forecast.city,forecast.dateIssued);
Console.WriteLine("Temperature to morrow, min={0} max={1}",
forecast.tomorrow.minTemp, forecast.tomorrow.maxTemp);
}

Weather forecast for Sydney, issued=3:42pm on Wednesday 13th of March 2005


Temperature to morrow, min=17 max=24

© PROGRAM UTVIKLING.no WebExpress - page - 189


Tank you for listening !

more courses on:


www.ProgramUtvikling.no

© PROGRAM UTVIKLING.no WebExpress - page - 190

You might also like