net development

138
.Net Development Prepared by : Dave Parkinson www.webdesigninfo.co.uk (February 2012)

Upload: daveparky

Post on 06-May-2015

8.102 views

Category:

Education


7 download

DESCRIPTION

ASP.NET 4 Development using Access Databases

TRANSCRIPT

Page 1: Net Development

.Net Development

Prepared by : Dave Parkinson

www.webdesigninfo.co.uk

(February 2012)

Page 2: Net Development

.NET DEVELOPMENT Page 2

.NET DEVELOPMENT CONTENTS

Chapter 1 : Introduction to the Visual Studio 2010 and the .NET Framework.....................5

1.1 Introduction to .NET.......................................................................................................................5

Chapter 2 : Visual Studio 2010 & C#.......................................................................................7

2.1 Introduction......................................................................................................................................7

2.2 What is C#?.......................................................................................................................................7

2.3 A Quick Overview of C# Syntax.....................................................................................................82.3.1 Variables and Operators...............................................................................................................................82.3.2 Decision Making and Flow Control.............................................................................................................92.3.3 Member Functions......................................................................................................................................102.3.4 Classes and Objects....................................................................................................................................102.3.5 Event Handling...........................................................................................................................................11

2.4 Using Visual Studio........................................................................................................................122.4.1 Exercise 1 - Starting a Project (A Windows Application)........................................................................122.4.2 Exception Handling....................................................................................................................................16

Chapter 3 : Designing Web Sites with Visual Studio 2010....................................................17

3.1 Introduction....................................................................................................................................17

3.2 Testing your Web Application......................................................................................................17

3.3 HTML and CSS..............................................................................................................................173.3.1 Applying Cascading Style Sheets to an HTML document........................................................................183.3.2 CSS Rules...................................................................................................................................................183.3.3 Element Layout and Positioning................................................................................................................203.3.4 Working with CSS in Visual Studio..........................................................................................................21

3.4 Web Site Layout.............................................................................................................................233.4.1 Working with Master Pages.......................................................................................................................243.4.2 Exercise 3 – Creating a Web Site using Visual Studio 2010.....................................................................25

Chapter 4 : Web Applications and ASP.NET.........................................................................33

4.1 Introduction....................................................................................................................................33

4.2 Features in ASP.NET.....................................................................................................................344.2.1 ASP.NET Controls.....................................................................................................................................354.2.2 Web services integration............................................................................................................................364.2.3 Handling Post Back....................................................................................................................................364.2.4 Moving Between Pages..............................................................................................................................37

4.4 Useful ASP.NET Tutorial Web Sites...........................................................................................37

Chapter 5 : Using Visual Studio & ASP.NET........................................................................38

5.1 Introduction....................................................................................................................................385.1.1 Structure of a Web Form Page...................................................................................................................385.1.2 Adding Server Controls.............................................................................................................................385.1.3 Handling Events.........................................................................................................................................38

5.2 Web Page Exercise 1 – Creating an ASP.NET Web Calculator................................................40

5.3 Web Page Exercise 2 – Creating an ASP.NET Web Lottery Number Generator...................43

Chapter 6 : Validation Web Form Pages................................................................................44

6.1 Introduction....................................................................................................................................446.1.1 Overview of the Validation Controls.........................................................................................................44

Dave Parkinson

Page 3: Net Development

.NET DEVELOPMENT Page 3

6.1.2 Post Backs and Form Validation................................................................................................................456.1.3 JavaScript and the Validation Controls......................................................................................................45

6.2 Using Validation Controls.............................................................................................................466.2.1 Checking for Required Fields....................................................................................................................466.2.2 Validating a Range of Expressions............................................................................................................466.2.3 Web Page Exercise 3 - Using a RequiredFieldValidator Control..............................................................476.2.4 Comparing Values......................................................................................................................................486.2.5 Performing Data Type Checks...................................................................................................................486.2.6 Regular Expression Validation...................................................................................................................496.2.7 Displaying a Summary of Validation Errors..............................................................................................496.2.8 Web Page Exercise 4 – Validating a Web Form........................................................................................50

Chapter 7 : Maintaining State on your Web Site...................................................................51

7.1 Introduction....................................................................................................................................51

7.2 Using View State.............................................................................................................................517.2.1 Disabling View State..................................................................................................................................527.2.2 Adding Custom Information to View State................................................................................................527.2.3 Protecting View State.................................................................................................................................53

7.3 Using Cookies.................................................................................................................................537.3.1 Reading Cookies........................................................................................................................................547.3.2 Writing Cookies.........................................................................................................................................54

7.4 Using Session State.........................................................................................................................55

7.5 Using Application State.................................................................................................................56

7.6 Web Page Exercise 5 – Using Cookies and Session Variables...................................................56

Chapter 8 : Databases.............................................................................................................58

8.1 Introduction....................................................................................................................................58

8.2 Review of Databases and SQL......................................................................................................598.2.1 Relational Databases..................................................................................................................................598.2.2 Structured Query Language.......................................................................................................................60

8.3 Web Page Exercise 6 - Reading Data from an Access Database...............................................63

8.4 Using Datasets to connect to a Database......................................................................................678.4.1 Connecting to a Database using Typed Data Sets......................................................................................68

8.5 Other Data-Bound Controls..........................................................................................................748.5.1 Exercise 8 – Using List View and other Data-Bound Controls.................................................................75

8.6 Searching through a Database Table using Typed Data Sets....................................................758.6.1 Web Page Exercise 9 – Searching through a Database Table....................................................................76

Chapter 9 – Configuring your Web Application....................................................................81

9.1 Introduction....................................................................................................................................81

9.2 Web Forms Authentication...........................................................................................................829.2.1 Web Exercise 10 – Password Protecting an area of your Web Site...........................................................849.2.2 Storing Usernames and Passwords in the Web.Config File.......................................................................889.2.3 Storing Usernames and Passwords in a Database......................................................................................89

Chapter 10 : Other Useful ASP.NET v3.5 Features..............................................................90

10.1 RSS Feeds – Exercise 11..............................................................................................................90

10.2 Uploading and Displaying Pictures on your Web Site – Exercise 12......................................92

10.3 Calendar Control – Exercise 13..................................................................................................95

Dave Parkinson

Page 4: Net Development

.NET DEVELOPMENT Page 4

10.4 Retrieving Web Pages – Exercise 14..........................................................................................96

10.5 Form to Email – Exercise 15.......................................................................................................97

Chapter 11 : ASP.NET and AJAX.........................................................................................99

11.1 Introduction..................................................................................................................................99

11.2 ASP.NET AJAX...........................................................................................................................9911.2.1 Using AJAX Server Controls – Exercise 16..........................................................................................10011.2.2 ASP.NET AJAX Control Toolkit– Exercise 17.....................................................................................101

Dave Parkinson

Page 5: Net Development

.NET DEVELOPMENT Page 5

Chapter 1 : Introduction to the Visual Studio 2010 and the .NET Framework

1.1 Introduction to .NET

Microsoft introduced the .NET concept as a way of integrating the development and delivery of windows applications, web applications and web services. .NET provides a common set of components and services that can be used to develop and run applications.

.NET contains a huge number of pre-defined components and services that are available to the application developer. This set of components and services is called the .NET Framework. The .NET Framework contains more than 6000 classes that can be used in your application. This means that most of the common actions like interacting with files and interacting with databases have predefined classes that you can use.

Previously, programmers developed programs in a language specific development environment. For example, A Visual C++ program was written in the Visual C++ development environment and a Visual Basic program was written in the Visual Basic programming environment. It was difficult to develop applications that had programs written in a variety of languages.From a programmer’s perspective, .NET provides a single Integrated Development Environment that allows programs written in a variety of different languages to be easily combined in the same application. This was achieved by using a Common Language Runtime. All languages supported by .NET compile to a standard language called Microsoft Intermediate Language (MSIL). MSIL is then converted by the Common Language Runtime into native code that runs on your PC.The use of the CLR means that .NET is theoretically independent of the hardware platform. Because applications in .NET compile to MSIL and are run through the CLR, the applications will run on any platform that has the CLR installed. This means that .NET applications will run on PC, Mac, Sun or any other platform, provided that the CLR is installed.

Another feature of the ‘.NET’ framework is that it allows software developers to use a common set of unified classes regardless of the programming language.

All languages that are supported by the CLR use the same data types. This means that it is much easier for programs written in different languages to pass variables. Within Visual Studio .NET, Microsoft provides Visual Basic, Visual C++ and C# (C sharp). However, Microsoft have produced a Common Language Specification to allow other Companies to produce language compilers that are compatible with .NET.

Hence if you decide to develop in Visual Basic, C# or C++ the programming elements will appear the same as will the development environment (including drag and drop creation of user interfaces and auto code generation). All the target code will be deliverable in a single directory (called an assembly) making for easy deployment from CD Rom or the Web.

Types of application you will develop in this module (and the .NET Services module) include:-

Dave Parkinson

Page 6: Net Development

.NET DEVELOPMENT Page 6

Windows Applications – these are client side applications. An exciting feature of .NET is that such applications can be quickly delivered for the web on a ‘no-touch’ basis. The user can surf to a web page and the windows application is automatically loaded and run on the client machine. Called ‘smart client applications’ they provide the rich features of traditional windows applications whilst also the convenience (i.e. you don’t need to install them) of ‘thin client’ browser based applications such as Java Applets.

Web Applications – these are server side applications consisting of one or more Web Forms. Unlike ‘old’ ASP or PHP technology they are compiled rather than interpreted. They are based on Microsoft’s ASP.NET technology. The new .NET framework lets you develop these applications in much the same way as Windows Applications using drag and drop user interface creation and similar code generation. The first version of ASP.NET offered several important advantages over previous Web development models. ASP.NET 4.0 improves upon that foundation by adding support for several new and exciting features in the areas of developer productivity, administration and management, extensibility, and performance. We will be using ASP.NET 4.0.

XML Web Services – these are special web based applications that provide a distributed computing solution across the internet.

Throughout this course we will be using Microsoft’s Visual Studio.NET 2010 to develop Windows Applications, Web Application and Web Services.

Dave Parkinson

Page 7: Net Development

.NET DEVELOPMENT Page 7

Chapter 2 : Visual Studio 2010 & C#

2.1 Introduction

When developing in .NET you will be using object oriented programming. Object oriented programming is now the paradigm for nearly all software development. When previously a programmer would have to develop programs from the ground up; instead these days they need only manage and use a number of objects that perform the required tasks.

Objects are created (i.e. instantiated) from classes; a class being a template that can be used directly or extended (i.e. inherited) and modified to suit the programmer’s specific needs. The beauty of modern programming is that classes are usually prewritten and arranged in hierarchically ordered packages (i.e. namespaces) for programmers to use as needed.

2.2 What is C#?

In this module we will use C#.NET. C# (pronounced C sharp) which is Microsoft’s attempt to redefine C++ for optimised use with a Virtual Machine (in this case Microsoft’s Common Language Runtime). In this respect it is very similar to Java, probably being a result of the fall out between Sun and Microsoft after Microsoft tried to unilaterally tweak the Java specification.

Here’s a really dumb question - ‘why we learning another language?’.

The syntax of C# will already be very familiar to C, C++,PHP and Java programmers. The few changes, additions and omissions actually make C# one of most intuitive and tidy OOP languages to use.

All .NET compliant programming languages (e.g. C#.NET, VB.NET, Java.NET, C++.NET, etc) are defined according to a common type system. In other words they

Use the same set of primitive variable types.

Use the same object oriented programming constructs (e.g. classes, objects, namespaces, events, inheritance and interfaces).

Compile to the same byte code, hence different classes can be written in different languages yet linked seamlessly.

Give identical access to same precompiled classes, with the same methods using the same input arguments and return types, all hierarchically ordered in the same namespaces.

Dave Parkinson

Page 8: Net Development

.NET DEVELOPMENT Page 8

Hence when using .NET, regardless of the language we choose, you create programming solutions in a very similar way. In reality it does not matter whether we choose to use C# or Visual Basic to write our applications. However Microsoft have developed C# specifically for web development and it makes sense to learn a language which is likely to become the de-facto standard for web development in the Microsoft environment.

2.3 A Quick Overview of C# Syntax

C# is very similar to C++ , Java and PHP scripting language in terms of its syntax. Note that all C# statements end in a ‘;’ and C# is case sensitive.

2.3.1 Variables and Operators

The simplest programming entity is the primitive variable. C# provides the usual primitive variable types notably:-

int, long & short for integer variables float & double for real number variableschar and unsigned char for byte values (0 to 255)bool for variables that can either be true or false

Although strings can be created as arrays of characters with for example

char mystring[100];

Microsoft provides a string class who’s objects are far easier declare and use.

string mystring;

Declaring variables is straight forward. For Example:-

int x, y, z;

float PI;

string mystring;

Declaring arrays of variables in C# is especially tidy…

float [] prime_numbers = new float[10];

double [,] matrix = new double[3,3];

You initialise variables with the assignment operator ( = ), though ensure floats use an ‘f’ suffix when assigning values with decimal points.

For example:-

Dave Parkinson

Page 9: Net Development

.NET DEVELOPMENT Page 9

x=10;

PI=3.1414f;

myString="hello world";

prime_numbers[0]=1.0f;prime_numbers[1]=2.0f;prime_numbers[2]=3.0f;

matrix[2,0]=0;

You can subsequently add, subtract, multiply and divide variables with arithmetic operators ( + - * / ). For example:-

z=x+y;

Average=(a+b+c)/3;

And recast if needed. For example:-

myInt=(int)myFloat;

2.3.2 Decision Making and Flow Control

Like C++, Visual Basic and Java, C# supports all the common decision making and flow control statements (if statements, do loops, while loops, for loops etc). You test variable values and perform appropriate tasks using conditional operators

== for equals, >, <, >=,<=, && for And, || for OR.

For example:-

float x=0, y=0;if(x==10)

y=20;elsey=3;

if(message == "hello" && happy == true) {

reply = "hello to you too";}else {

reply = "be that way";}

or loop until a condition is met…

while(i < 10)

Dave Parkinson

Page 10: Net Development

.NET DEVELOPMENT Page 10

{sum = sum + prime_numbers[i];i = i + 1;

}

for(i = 0; i<9;i=i+1) {

val = prime_numbers[i];sum = sum + val;

}

2.3.3 Member Functions

To avoid excessive amounts of code it is often desirable to group regularly used statements into member functions (often called methods). Functions take input variables (often called arguments or parameters), and can output a result variable called the return value.

Functions are firstly defined. For example…

float MyAdd(float a, float b) {

float c;c=a+b;return c;

}

In the above example we use a ‘void’ type to indicate no value is returned.

Calling functions is again straight forward. For example…

c = MyAdd(a, b);

2.3.4 Classes and Objects

Given that we have variables that hold data and the functions that process this data, it is often desirable to encapsulate all data and functionality an object. Such objects being instantiated from type definitions called classes.

Dave Parkinson

Page 11: Net Development

.NET DEVELOPMENT Page 11

Later we will look at defining our own classes, for now consider a class called MyCalculator.

Typically we would instantiate an object from the class using the ‘new’ keyword.

MyCalculator myCalcObj=new MyCalculator();

We could then use the object to access data and methods associated with the class. For example…

result=myCalcObj.Add(1,2);

Calls the method Add passing values 1 and 2 and receiving the result 3.

Some classes however can be used directly, for example the standard Math class gives you direct access to member functions such as Cos, Sin, Log10, etc. For example…

result=Math.Sin(angle);

Later you’ll notice C# source files will begin with statements such as..

using System;using System.Drawing;using System.Collections;using System.ComponentModel;using System.Windows.Forms;using System.Data;

these are simply making visible to your code collections of standard class definitions called ‘namespaces’ in much the same way as ‘import’ statements in java or ‘header files’ in C++.

2.3.5 Event Handling

Rather than just running a serial sequence of tasks; modern object orientated applications are event driven, i.e. they respond to events such as button clicks, mouse dragging, keyboards being pressed, timers going off, etc as and when they occur.

Dave Parkinson

Page 12: Net Development

.NET DEVELOPMENT Page 12

Objects such as buttons, timers, etc can generate events (e.g. when a button is clicked) and hence objects containing methods with suitable arguments can be delegated to handle these events. Such methods are called event handlers because they perform appropriate tasks in response to events.

When writing programs in Visual Studio much of your coding will involve filling event handler methods for objects that comprise your application.

Further information on C# can be found in the C# programmers reference section of the Help files on Visual Studio 2010.

2.4 Using Visual Studio

Microsoft Visual Studio 2010 is an Integrated Development Environment (IDE) where you can write, compile, build, run and debug computer programs. The IDE allows you to write in a variety of languages (C#, Visual Basic, C++ etc) for a variety of purposes (Windows Applications, Web Applications, Web Services, etc) in a visually intuitive way where much of the difficult code generation is done automatically. This application also provides excellent inline help including programming tutorials and references.

To start Visual Studio.NET from windows

Start->All Programs->Microsoft Visual Studio 2010->Microsoft Visual Studio 2010

Upon starting Visual Studio you are presented with a Start page detailing previous projects and providing a gateway to offline and online help.

2.4.1 Exercise 1 - Starting a Project (A Windows Application)

A project bundles into a single directory all the files you use to develop your computer program including source code, resources and IDE settings. From the IDE main menu select…

File->New->Project

The resultant dialog box allows you to select Project Types from a variety of Templates and assign a name and directory to your project.

Dave Parkinson

Page 13: Net Development

.NET DEVELOPMENT Page 13

e.g. Select Visual C# , Windows Forms Application ... Name: Conversion Location: F:\Netdevelopment on a directory Netdevelopment on your pen disc… hence click [OK]

Upon starting the project you are presented with a …

Design Area – where you will create the user interface for your application and write your source code.

Properties Window – where you assign individual properties to individual visual elements. For example think of say a button as an object that has encapsulated within it member variables that describe it; such as its caption, font, size, colour, etc. From the properties window you can select one object from a list of current objects and hence set it’s member variables.

Solution Explorer – where you can view the constituent files and references (i.e. linked libraries, etc) that make up your project. A solution is in effect a project (or group of projects).

Toolbox – where you can select from a variety of objects to add to your application.

Output Pane – where the IDE sends messages to you (e.g. compile time errors, etc)

Dave Parkinson

Page 14: Net Development

.NET DEVELOPMENT Page 14

Having created your project

1. From the Properties Window select the Form1 object and hence change the value it’s member variable Text from ‘Form1’ to ‘Miles to Kilometres’.

2. Experiment with other form properties i.e. change the form’s background colour.

You are now ready to design your application

From the Toolbox drag and drop a Label onto the Form1 window.From the Toolbox drag and drop a TextBox onto the Form1 window.From the Toolbox drag and drop a Button onto the Form1 window.

Dave Parkinson

Page 15: Net Development

.NET DEVELOPMENT Page 15

You can view the source code that has been generated by right clicking on Form1.cs in the solution explorer and selecting the option View->Code.

By double clicking the Button in the From1 design view the event handler code is automatically generated, i.e.

private void button1_Click(object sender, System.EventArgs e){

}

And so becomes a method of the Form1 class.

As yet the event handler for the Button1 doesn’t do anything. You will need to add some code to the method Button1_Click( …) to handle the event.

Next, add to the Button1_Click( …) event handler method code to take input from the text box, convert it to a double value hence calculate a new value and set the label.

So the class looks like…

public partial class Form1 : Form { public Form1() { InitializeComponent(); }

private void button1_Click(object sender, EventArgs e) { double m, k; // variables for miles and kilometres string myString; // declare a string

myString = textBox1.Text; // get text from textbox m = System.Convert.ToDouble(myString); // convert to double k = m * 1.609; // calculate miles to kilometres label1.Text = System.Convert.ToString(k); // set label to Km

} }

Note the program declares doubles for miles and kilometres and a string that will come in handy

sets myString to the input from the textBox1 object’s Text member.

converts myString to a numerical value using the class System.Convert

hence uses this value to convert from miles to kilometres

hence the sets the Text member of the label1 object to display the result.

Note you can also convert numbers to strings just by adding them to a pre-existing string.

Dave Parkinson

Page 16: Net Development

.NET DEVELOPMENT Page 16

The final program looks like:

2.4.2 Exception Handling

An important feature of OOP programming is exception handling. There are occasions where the executing program can generate an error and hence quit or even crash. Being able to catch such errors (i.e. exceptions) and take appropriate actions makes for stable applications.For instance if the user of the above ‘Miles To Kilometres’ application enters a word instead of a number an exception is generated.The keywords to test and handle such an exception are ‘try’ and ‘catch’For example

private void button1_Click(object sender, System.EventArgs e){

bool error_flag=false;string myString="";

try {

myString = textBox1.Text;m=System.Convert.ToDouble(myString);

}catch{

label1.Text = "Input Error";error_flag = true;

}if(error_flag==false) {

k = m * 1.609; label1.Text = System.Convert.ToString(k);

}}

Change your program as shown above using try and catch to add error recovery to your conversion application.

Dave Parkinson

Page 17: Net Development

.NET DEVELOPMENT Page 17

Chapter 3 : Designing Web Sites with Visual Studio 2010

3.1 Introduction

Visual Studio 2010 enables you to build Web pages with standard elements such as hypertext links, tables, forms etc. You can create web pages either in design view, which allows you to drag and drop elements onto the screen from the toolbox, or in source view, which allows you to add HTML code directly. You can easily switch between these two modes of operation by clicking the Design or Source tabs at the bottom of the editor window. When designing a web page you can preview the page in a web browser by right clicking the .aspx file (or .html file) in the solution explorer window. You can either view in the internal browser or select Browse With and chose one of the browsers installed on your machine. Alternatively you can press debug on the main toolbar. This will display your web page in your default browser.

3.2 Testing your Web Application

With Visual Studio 2010 you no longer need to install and use IIS to host and test your web sites and web applications. When you start to develop a new web site Visual Studio gives you four choices on where to host the site

1. File System Web Site – This is the default location. and allows you to host your web site on any folder on a hard drive (or pen drive) in your PC. This is the method we will be using throughout this course.

2. Local IIS Web Site – This allows you to host a websites within the local IIS root folder on your hard disc.

3. Remote Web Site – this allows you to create web applications that reside on remote servers as long as those servers support FrontPage 2000 Server Extensions.

4. FTP Web Site – this allows you to create and maintain web sites on an FTP server

3.3 HTML and CSS

HTML has served as the primary way of defining the content blocks of your webs site and is the easiest way to define the layout of your web site. HTML includes a variety of layout tags you can use (tables, lists etc) that enable you to create highly complex layouts for your web page. In order to add styling to your web pages with HTML you needed to add HTML cases formatted tags (e.g. font, color etc). This resulted in a mess of ‘spaghetti’ HTML and no clear separation between the structure and the content of your web pages.

The introduction of CSS to the web development and design world brought it back to a clean and elegant solution to styling web pages. CSS meant a style could be defined in a single location for the entire web site, and simply referenced on the elements requiring the

Dave Parkinson

Page 18: Net Development

.NET DEVELOPMENT Page 18

style. Using CSS brought back the logical separation between web page content and the styles used to display it.

3.3.1 Applying Cascading Style Sheets to an HTML document

There are three mechanisms by which styles can be applied to a HTML document.

1. the style can be defined within the HTML tag 2. styles can be defined in the <head> section and applied to the whole document3. styles can be defined in external files called stylesheets These can then be used in any

document by including the stylesheet

The third technique is the most flexible as it means any changes applied to the stylesheet will automatically be applied to total website allowing major formatting changes to be made with little effort.

All three methods of defining styles can be used within the same website. The term cascading style sheets (CSS) is simply a set of precedence rules that avoid conflict in style definitions. This means that style definitions in the <head> section override definitions in an external stylesheet, and style definitions in the HTML tag override all others.

3.3.2 CSS Rules

A CSS rule is made of two parts, the Selector and the Properties e.g.

p{

font-family: Arial;font-size: 12pt;color: Red

}

In the example above p is the selector and all the items within the brackets are the properties.

The selector is the portion of the rule that dictates how the web browser should select the elements to apply the style to. CSS includes a variety of types of selectors, each of which defines a different element selection technique. For example:

Universal SelectorsThe universal selector indicates that the style should apply to any element in the web page.

*{

font-family: Arial;}

Dave Parkinson

Page 19: Net Development

.NET DEVELOPMENT Page 19

This selector would change the font of any element that supports the font property to Arial.

Type SelectorsThe type selector allows you to create a style that applies to a specific type of HTML element.

p{

font-family: Arial;}

This selector would change the font of all <p> tags in the web page to Arial.

Class SelectorsClass selectors are a special type of CSS selector that allows you to apply a style to any element with a specific class name. The class name is defined in HTML using the class attribute, which is present on almost every element. Class selectors are identified by prefixing them with a single full stop (.)

.title{

font-family: Arial;font-weight: bold;

}

This CSS rule would be applied to any element whose class attribute matched the rule name e.g.

<div class=”title”>My Web Page</div>

ID SelectorsID selectors are another special type of CSS selector that allows you to create styles that target element with specific ID values. ID selectors are identified by prefixing them with a hash mark (#)

#title{

font-family: Arial;font-weight: bold;

}

This CSS rule would be applied to any element whose class attribute matched the rule name e.g.

<div class=”title”>My Web Page</div>

This selector is most widely used with layers, since layers are always defined with a unique ID.

Dave Parkinson

Page 20: Net Development

.NET DEVELOPMENT Page 20

3.3.3 Element Layout and Positioning

CSS is useful not only for styling elements in a page, but also positioning elements as well. CSS gives a much more flexible positioning system than HTML. CSS bases the positioning of elements in a web page on something called the box model. Once an elements box behaviour has been determined, it can be positioned using several different techniques.

The box module defines how every element in HTML is treated by the browser as a rectangular box. The box comprises different parts, including margins, padding, borders, and content.

All the separate elements that make up the box can influence its position within the web page, and unless otherwise specifies, each is given a default value of zero.

HTML provides you with two different types of boxes, the block box and the inline box. Block boxes are typically represented by tags such as <p>, <div> or <table>. For block boxes, the containing block is used to determine the position of its child blocks. Additionally, block boxes can contain either inline or block boxes, but not both. The second box type is the inline box. Inline boxes are typically represented by tags such as B, I and SPAN as well as actual text and content. Their contents is distributed in lines, normally flowing left-to-right, top-to-bottom.

CSS provides you with four primary positioning mechanisms: Normal (static), Absolute, Relative and Fixed. Each type offers a different behaviour you can use to lay out the elements in your page. The type of behaviour property is set by the position property. Each element can have its own position property set, allowing you to use multiple positioning schemes within a page.

Static PositioningUsing normal (static) positioning, blocks items flow vertically and inline items flow horizontally, left to right (a static element ignores any top, bottom, left, or right declarations). This is the default positioning behaviour.

Dave Parkinson

Page 21: Net Development

.NET DEVELOPMENT Page 21

Relative PositioningUsing relative positioning, elements are initially positioned using Static layout. The surrounding boxes are positioned and then the box is moved based on its offset properties (top, bottom, left and right). An element with position: relative moves an element relative to its normal position, so "left:20" adds 20 pixels to the element's LEFT position.

Absolute PositioningAbsolute positioning works much like relative positioning, except instead of an element calculating its offset position based on its position in the normal positioning scheme, the offsets are calculated based on the position of its closest absolutely positioned ancestor. If no ancestor exists then it is based on the browser window itself. As with relative blocks you can use the elements tag label to position the element on the page .

Fixed PositioningAn element with position: fixed is positioned at the specified coordinates relative to the browser window. The element's position is specified with the "left", "top", "right", and "bottom" properties. The element remains at that position regardless of scrolling.

Another option for controlling the position of elements using CSS is to use the float property. This property allows you to float an element to the left or right side of a block. The floating block is positioned vertically as it would normally be in a normal position, but horizontally shifted as far left or right as possible.

3.3.4 Working with CSS in Visual Studio

Visual Studio offers a variety of tools to make working with CSS easier. To create a new style you can select the new style option from the Format menu. This opens the following dialog box:

Dave Parkinson

Page 22: Net Development

.NET DEVELOPMENT Page 22

Once you have created styles for your web site Visual Studio provides three tool windows you can use to manage style sheets, apply styles to elements and inspect the style properties applied to an element. All three windows are available from the View menu.

Manage Styles Tool Window

This shows all the styles currently applied to your page. The style is previewed at the bottom of the window.

Apply Styles Tool Window

This window lets you apply styles to various elements on your web pages.

Dave Parkinson

Page 23: Net Development

.NET DEVELOPMENT Page 23

CSS Properties Tool Window

This tool shows you all the properties that have been applied to the currently selected element. You can also use the tool to edit the style properties.

3.4 Web Site Layout

A typical web page is made up of a collection of components. For example:

Some of the components like the branding, the navigation, sidebar and footer are constant from page to page. Other components like the content are specific to a particular page.

Dave Parkinson

branding

navigation

contentsidebar

footer

Page 24: Net Development

.NET DEVELOPMENT Page 24

The various elements on the page can be laid out using CSS, with the separate components being contained within <div> tags and the styles associated within each component being defined a an external style sheet. The skeletal markup for a typical page would be as follows:

<!—doctype--><html><head> <title><!--page title--></title>

<!--fetch stylesheets--></head><body>

<div id=”branding”> <!--display brand--></div><div id=”navigation”> <!--display navigation--></div><div id=”sidebar”> <!--display sidebar--></div><div id=”content”> <!--display content--></div><div id=”footer”> <!--display footer--></div>

</body></html>

3.4.1 Working with Master Pages

Master Pages, a new feature of Microsoft ASP.NET, enables you to apply the same page layout to multiple content pages in a Web application. Master Pages provide you with an easy method of creating a consistent look and feel for a Web site. The pages in most Web applications have standard elements, such as logos, navigation menus, and copyright notices. You can place all of these elements within a single Master Page. If you base the content pages in your application on this Master Page, then all of the content pages will automatically include the same standard elements. When you create a master page, you can define portions of the page that the content page can replace with its own content. These portions are defined using an ASP.NET control; the ContentPlaceHolder control. A master page can contain any number of ContentPlaceHolder controls (or none at all.) On the content page, the content from the ContentPlaceHolder controls appears inside of Content controls. By default, the content pages Content controls are empty so that you can provide your own content.

The above diagram shows a master page and an associated content page as they appear in Visual Studio 2010. You can see the ContentPlaceHolder control in the master page and the corresponding Content control in the content page. Notice that the master pages

Dave Parkinson

Page 25: Net Development

.NET DEVELOPMENT Page 25

content that is outside of the ContentPlaceHolder is visible but greyed out in the content page. Only the content inside of the ContentPlaceHolder can be accessed via the content page. All other content that comes from the master page is unchangeable.

3.4.2 Exercise 3 – Creating a Web Site using Visual Studio 2010

This exercise shows you how to create a web site using Visual Studio. We will be using this web site to access all the other exercises produced in this module. Open Visual Studio 2010 and select File – New Web Site. Browse to the D:drive or your pen drive and create an ASP.NET Empty Web Site called ‘mysurname’ (e.g. parkinson). Note you cannot use your f: drive as you cannot run the built-in ASP.NET web server over a network.

The web location should be set to File System and the Language to C#. Your website will be opened by Visual Studio as shown below:

Dave Parkinson

Page 26: Net Development

.NET DEVELOPMENT Page 26

Download the file 960template.zip from Blackboard and unzip it onto your pen drive. Copy the contents of the 960template directory (see below) into the directory containing your Visual Studio Project.

Your web site should now contain the following files:

This template uses the 960gs CSS framework to design the site structure. The MasterPage.master file defines the general look and feel of all the site's pages. To add additional pages just edit the MasterPage.master file to add the extra links and then add a new web page.

Dave Parkinson

Page 27: Net Development

.NET DEVELOPMENT Page 27

In order to test our website press the debug button on the menu bar. The first time you do this it will open a dialog box as shown below:

Click the OK button (we will discuss the web.config file later in the course). Your web page should be displayed in the default browser as shown below.

The home page explains how use the template. It includes a link to the free, open source CSS template, 960gs CSS Framework, which has been used to design the site. Click on this link to find more information on the framework.

The biggest problem with CSS development is the number of different browsers which are out there and being used. Each browser implements CSS slightly differently (some more differently than others). This causes huge headaches for any web developer trying to get a consistent layout across different browsers, browser versions and platforms. A way of fixing this problem is to use a framework.

One of these frameworks is called 960 Grid System, and is a fixed width framework. This is a very simple framework that allows the developer to very quickly implement wire-frame designs and then embellish their content with their own styles. The width of a page using 960 Grid System is 960px, and this can be split into either 12 or 16 grids (each 60px or 40px per grid respectively with a 20px gap between the grids).The biggest problem with CSS development is the number of different

Dave Parkinson

Page 28: Net Development

.NET DEVELOPMENT Page 28

The web site contains the following files and directories. CSS Directory

The subdirectory css (within the main css directory) contains all the files for the 960gs CSS Framework. It should not be edited.

The style.css file contains all the styles for your site. #title, #menu, #footer { background-color: #00584a; color: #fff;}

#menu a { color: #fff; text-decoration: none; background-color: #008a7f; display: block; padding: 3px;}

#menu li { list-style: none; margin: 2px;}

#menu { height: 300px;}

#footer { text-align: center;}

You need to edit this file to add new styles and to change to look of your site.

Images Directory

This directory is used to store all the images on your site.

Dave Parkinson

Page 29: Net Development

.NET DEVELOPMENT Page 29

MasterPage.master

The master page contains the following HTML code:

<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>Dave Parkinson's ASP.NET Web Site</title> <asp:ContentPlaceHolder id="head" runat="server"> </asp:ContentPlaceHolder> <link href="css/css/reset.css" media="screen" rel="stylesheet" type="text/css" > <link href="css/css/960.css" media="screen" rel="stylesheet" type="text/css" > <link href="css/css/text.css" media="screen" rel="stylesheet" type="text/css" > <link href="css/style.css" media="screen" rel="stylesheet" type="text/css" ></head><body> <form id="form1" runat="server"> <div id="container" class="container_16"> <div id="title" class="grid_16"> <img src="images/salford_university.gif" alt="Salford University" /> </div> <div id="menu" class="grid_3"> <ul> <li><a href="index.aspx">Home</a></li> <li><a href="read.aspx">Page 1</a></li> <li><a href="#">Page 2</a></li> <li><a href="#">Page 3</a></li> <li><a href="#">Page 4</a></li> <li><a href="#">Page 5</a></li> <li><a href="#">Page 6</a></li> <li><a href="#">Page 7</a></li> <li><a href="#">Page 8</a></li> </ul> </div> <div id="content" class="grid_13"> <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder> </div>

<div id="footer" class="grid_16"> <p>Footer here</p> </div> </div> </form></body></html>

Dave Parkinson

Page 30: Net Development

.NET DEVELOPMENT Page 30

The master page references all the style sheets (.css files) used in the construction of the page.

It divides the web page into four sections:

id = ‘title’This section sets up the header to contain the Salford University logo. This header will appear on every page of the website that uses this Master Page.

id = ‘menu’This section sets up the menu bar to provide the links to all the pages on the website. This menu will appear on every page of the website that uses this Master Page.

id = ‘content’This section contains a content placeholder. This enables this area to be changed for each individual web page.

id = ‘footer’This section sets up the footer. This footer will appear on every page of the website that uses this Master Page.

Dave Parkinson

Page 31: Net Development

.NET DEVELOPMENT Page 31

Index.aspx

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="index" Title="Dave Parkinson's ASP.NET Web Site" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"></asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <span class="header">This is Dave Parkinsons ASP.NET v4 Web Site</span><p class="header">&nbsp;<img alt="Dave Parkinson's Picture" src="images/dave_parkinson.jpg"/></p><p>This site is designed using the <a href="http://www.960.gs">960gs CSS framework</a>.</p><p><a href="http://www.rickogden.com/tutorials/960gs/">Click here for a tutorial.</a></p><p>This template uses the 960gs CSS framework to design the site structure. The MasterPage.master file defines the general look and feel of all the site&#39;s pages. To add additional pages just edit the MasterPage.master file to add the extra links and then add a new web page.</p></asp:Content>

The index page initially includes the master page content. You are only allowed to edit the information between the two content placeholders (Content ID=”Content2”). The html content on this page displays the following information.

If you wish to add another page to your website then you do as follows:

Click File - New, File.

Dave Parkinson

Page 32: Net Development

.NET DEVELOPMENT Page 32

Choose Web Form from the Add New Item dialog as shown below

Ensure that the boxes for: Place code in a separate file and Select master page are both selected and name the page (e.g. page1.aspx). Select Add.

A new dialog box will appear prompting you to Select a Master Page. Choose MasterPage.master and select OK.

A new .aspx page will be produced with the header, menu and footer the same as all the other web pages. The content area will be blank waiting for you to add your own content.

If we wish to change our master page in the future any changes made will automatically be applied to all the other web pages using the master page.

Dave Parkinson

Page 33: Net Development

.NET DEVELOPMENT Page 33

Dave Parkinson

Page 34: Net Development

.NET DEVELOPMENT Page 34

Chapter 4 : Web Applications and ASP.NET

4.1 Introduction

Web Applications are server side applications consisting of one or more Web Forms. Microsoft’s previous technology for generating Web Applications was Active Server Pages (now often referred to as ASP Classic)

ASP.NET is a complete overhaul of traditional Active Server Pages. Therefore, it offers a very different methodology for building Web applications. ASP.NET is much more powerful, offering developers a more efficient way to build Web applications.

Fundamental Changes from ASP :-

Classic ASP was built on top of the Windows operating system and IIS. It was always a separate entity, and therefore its functionality was limited. ASP.NET, on the other hand, is an integral part of the operating system under the .NET Framework. It shares many of the same objects that traditional applications would use, and all .NET objects are available for ASP.NET’s use.

ASP made it very clear that client and server were two separate entities. Once ASP was finished with its work on the server, it passed the HTML to the client and forgot about it. ASP.NET ties together the client and the server through clever use of server-side and client-side code, all invisible to the developer. Web development is now much more like traditional application development than the disconnected request/response model that ASP development typified.

Furthermore, ASP.NET code is compiled, whereas classic ASP used interpreted scripting languages. Using compiled code means an automatic boost in performance over ASP applications.

Session state was a very important concept in classic ASP. It's the ability to automatically determine if a sequence of requests is coming from the same client, mainly through the use of cookies. This session management made it easy to keep track of users and their actions. Easy-to-build shopping carts and data scrolling were born. However, as Web sites began moving to server farms (collections of servers all handling the same Web site) developers began to see the limitation of ASP-based session management. Namely, sessions weren't transferable across servers. Session management has become much easier and more powerful with ASP.NET. ASP.NET addresses this issue by providing built-in session support that's scalable across Web farms. It also provides reliability that can even survive server crashes, and it can work with browsers that don't support cookies.

In addition, ASP.NET is now completely object-oriented.

ASP and other traditional dynamic Web page technologies are very different from ASP.NET because they're built using interpreted languages, such as VBScript and JavaScript, whereas ASP.NET is built using compiled languages (such as Visual Basic and C#). Using interpreted languages produces Web pages in which the program code and

Dave Parkinson

Page 35: Net Development

.NET DEVELOPMENT Page 35

content code are joined. Compiled languages, on the other hand, keep program code and HTML separate.

To understand this difference, first you've got to make sure you've got a solid grasp of how traditional technologies like ASP work. Dynamic Web pages that are built using traditional technologies, ASP or PHP, usually contain a few lines of code followed by a few lines of HTML, followed by still more lines of code.

When code is intermingled with the content in this way. the Web server is forced to do what is called context switching. For each line in the page, the server must interpret whether it's code or content. Then it must compile and run the line if it's code, or output the line to the client's browser if it's content.

If you think code interspersed with HTML content is difficult for the server to deal with, consider the developer who has to write the code. This form of compilation forces developers to write code that's not easily structured and is difficult to reuse.

In contrast, with ASP.NET, developers produce program code that's kept separate from the content on the page. When code is separated in this way, a number of advantages emerge:

The Web server knows exactly which portion is the code and which is the content, so it can compile the code in its entirety once, rather than one line at a time, significantly reducing execution time.

The designer doesn't have to look at all the developer's code while laying out the page.

The developer won't accidentally alter the design when writing the code.

Development and design tools like Visual Studio, Expression Web and Dreamweaver can better serve their users by focusing on the two components of a dynamic page, program code and HTML, separately.

A final advantage of ASP.NET pages is the fact that you can even place the code in a separate file called a code-behind file. By relocating program code to the code-behind files, your Web page can comprise only content. This full separation of HTML and program code makes it easier to reuse both program code and the HTML.

4.2 Features in ASP.NET

Besides the complete change in separation between code and content and the resulting way in which the code is compiled, ASPNET has some significant new features that aren't a part of standard ASP or other traditional Web development environments.

4.2.1 ASP.NET Controls

Dave Parkinson

Page 36: Net Development

.NET DEVELOPMENT Page 36

Server Controls - ASP.NET server controls comprise programmable, pre-packaged server-side program code written to perform dynamic functions.These server controls are referenced by tags using a special syntax, <asp:tagname...>, and are then placed within your Web pages, where they execute. When subsequently executed by ASP.NET, these tags are converted into HTML and content to be rendered by the user's browser. For example, a simple control "asp:label” represents a server control that displays text using HTML <span...> tags.Server controls vary in the functionality they provide. Standard ASP.NET server controls such as "asp:button" and "asp:textbox" are designed to be used in place of their more traditional counterparts (the HTML <input> form elements of type button and text). They look the same in Visual Studio’s Design view and will appear the same in the browser. However, although they look the same in Design view, the markup is vastly different. Using server controls in place of the traditional HTML controls lets you take advantage of ASP.NET features, such as being able to dynamically set the control's attributes at run time.

Validation Controls - Validation controls are used to validate the data that an end user enters, or possibly fails to enter, into form elements. For example, a validation control can be used to make a field in an entry form a required field. In addition to requiring form fields to be filled, validation controls in ASP.NET can be used to validate the user's input against a range of values or to compare two values.

List Controls - ASP.NET list controls are used to iterate, process, and display dynamic data. To associate a list control with data, we bind (link) dynamic data, such as database query results, to a list control. Performing the binding operation automatically populates a List control with data from a data source such as an array or a database.

Data Controls - Data access in ASP.NET can be accomplished completely declaratively (no code) using the new data-bound and data source controls. There are data source controls to represent different data backends such as SQL database, Access database, and XML, and there are data-bound controls for displaying your data, such as gridview, detailsview, listview and formview.

Rich Controls – These are complex components that can be placed directly into an ASP.NET Web page. Examples of rich controls include the Calendar and Ad Rotator controls, which display a calendar and a rotating advertisement respectively.

Navigation Controls - The navigation controls provide a common user interface for navigating between pages in your site, such as treeview, menu, and sitemappath.

Login Controls - The new login controls provide the building blocks to add authentication and authorization to your site, such as login forms, create user forms, password retrieval, and a custom user interface for logged in users or roles.

Web Part Controls - Web parts are a new family of controls that enable you to add rich, personalized content and layout to your site, as well as the ability to edit that content and layout directly from your application pages.

Dave Parkinson

Page 37: Net Development

.NET DEVELOPMENT Page 37

Master Pages - This feature provides the ability to define common structure and interface elements for your site, such as a page header, footer, or navigation bar, in a common location called a "master page", to be shared by many pages in your site.

Themes and Skins - The themes and skins features in ASP.NET allows for easy customization of your site's look-and-feel. You can define style information in a common location called a "theme", and apply that style information globally to pages or controls in your site.

Integrated AJAX Support – ASP.NET now contains AJAX support as part of the .NET Framework 4.0.

4.2.2 Web services integration

Another new feature of ASP.NET is the complete integration of Web services. A Web service is, in a sense, a small program available over the Internet to which you can call functions and get results.

For example, the Postal Office might write a Web service that provides a list of all post codes. From within your Web page, you could call this Web service to get the list of post codes and add that data to a drop-down list box. Visitors to your Web site would then be able to select from that list. If the Postal Office updated the list, your page would automatically be updated as well, since the information isn't being stored locally.

Web services work by transferring data encoded in XML over a transportation technology, such as HTTP.

4.2.3 Handling Post Back

One of the biggest differences between ASP and ASP.NET is that in ASP.NET a Web Form must post back to itself rather than post to a different page.

Historically, developers posted to a different page by setting the form's action attribute.Posting to a separate page used to be a good idea because it made for a cleaner separation of code from HTML. Now, because ASP.NET handles events in the same Web Form in which they're raised, the form must post back to the same page. Even if you set the action attribute of the form to a different page, the Web server finds the runat="server" attribute setting and overrides your action value.

On of the major advantages in posting back to the same page is that ASP.NET maintains a hidden variable called _VIEWSTATE which holds all the values on your form. This means that when you process a form using post back you do have to worry about maintaining the state of any data entered on a form, ASP.NET will do this for you.

Dave Parkinson

Page 38: Net Development

.NET DEVELOPMENT Page 38

4.2.4 Moving Between Pages

So how do you help your visitors navigate to other pages on your site if you're always posting back to the same Web Form? The answer is the Response.Redirect command.First, handle the post back in your Web Form. Then give the Response.Redirect command the URL of the next page you want the visitor to go to, like this:

Response.Redirect("NextPage.aspx");

To increase performance there's a second, optional parameter you can add to the command. It determines whether the server should halt processing the current page and transfer immediately or whether it should finish the page first. The Boolean value of true halts processing and transfers immediately. That would look like this:

Response.Redirect("NextPage.aspx", true);

Transferring to a new page is when we really have to start worrying about maintaining state. The reason is that we won't have that handy __VIEWSTATE hidden form element doing the work for us. It's not available when transferring between pages using the Response.Redirect command. Any values that need to be passed to another web page should use Session Variables.

4.4 Useful ASP.NET Tutorial Web Sites

Microsoft ASP.NET 4.0 Videos and Tutorialshttp://www.asp.net/learn/

Dave Parkinson

Page 39: Net Development

.NET DEVELOPMENT Page 39

Chapter 5 : Using Visual Studio & ASP.NET

5.1 Introduction

Interactive ASP.NET Web Sites can be designed using Visual Studio using Web Form Pages. Although Visual Studio Web Form pages can contain dynamic content, the foundation of the page is still standard HTML. On top of the HTML we can also add server controls and application logic. When you add a server control to the page, the control is executed on your Web server and generates content that is sent to a Web browser.

5.1.1 Structure of a Web Form Page

A Web Form Page consists of two files. The presentation page (e.g. exercise1.aspx) contains all the user interface elements of the web page, such as HTML tags and web server controls. This file ends in the extension .aspx, and it is the page that you request when you open the file in your browser.

A web form also uses a second file, called the code-behind file, which contains all the application logic for your page. The code-behind file has the same name as the presentation page but has the extension .cs (e.g.exercise1.cs)

When you create a Web Form Page, you typically need to work with the page using three different images. Whilst designing the visual elements of the page you use either Design View or HTML view in the Designer. While developing the application logic for a web page you use the Code Editor.

5.1.2 Adding Server Controls

Unlike standard HTML pages, Web Form Pages can contain Web server controls. Web server controls represent the user interface elements in a page. Unlike normal HTML tags, server controls have properties, methods, and events that you can access within your code.You can find all of the Web Forms controls in the Toolbox.

ASP.NET introduced a number of Web Form Controls. These Web Form controls are divided into a number of groups (standard, data, validation, navigation, login, Ajax etc.) and all accessible from the toolbox. We will be using many of these controls over the course of this module.

5.1.3 Handling Events

Controls in a Web Form Page can raise events. For example, when you click a button, the Button control raises a Click event. Or, when you select a new list item in a ListBox control, the control raises a SelectedlndexChanged event.

Dave Parkinson

Page 40: Net Development

.NET DEVELOPMENT Page 40

A Web Form Page itself can raise events. For example, you can use page events to perform certain actions whenever the page is requested by a browser.

Handling Control EventsIf you want to perform some action whenever an event is raised by a control, you need to add an event handler to your code. An event handler is a method or subroutine that executes when a certain event is raised.

There are two ways you can add event handlers to your code. First, you can double-click a control on the Designer surface. Double-clicking a control will automatically switch you to the Code Editor and add an event handler for the control's default event.

If you need to add an event handler for something other than a control's default event, you'll need to select the control from the drop list in the properties window. Next, click the icon at the top of the Properties windows labelled events (the lightning bolt). Clicking the events button will display a list of all the events associated with control. You can double-click any of the events listed in the properties window to add an event handler for that event.

Handling Page EventsA Web Form Page itself has several events that you can handle in your code. The most important of these is the Page_Load event. The Page_Load method is executed every time someone requests the Web Form Page.The IsPostBack PropertyCode located in the Page_Load subroutine executes each and every time a page is requested. Because controls automatically retain their values between post backs to the server you typically do not need to assign values to the controls each and every time the page is requested. You can detect whether a page is being requested for the first time by using the IsPostBack property. If it’s value is True then the page has been resubmitted back to server more than once. To test this property under the Page_Load event:

Dave Parkinson

Page 41: Net Development

.NET DEVELOPMENT Page 41

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

// Put user code to initialize the page hereif(!IsPostBack)

Label1.Text=Time();}

When the page is first opened the time will be displayed. On future postbacks it will not be updated.

5.2 Web Page Exercise 1 – Creating an ASP.NET Web Calculator

Add a new form to your existing ASP.NET web application (named ‘mysurname’) by right clicking on the main directory in the Solution Explorer.

Name the new Web Form exercise1.aspx and select the master page when requested.

On the web form add Label boxes, Text boxes, a Button and a RadioButtonList as shown below to design your calculator :-

Dave Parkinson

Page 42: Net Development

.NET DEVELOPMENT Page 42

RadioButtonList’s are used to force the user to make a single selection from a range of options. To use a RadioButtonList in your program follow the steps below:

1. Place a RadioButtonList Web Form object on the main dialog window.

2. Click on the selection arrow to display the RadioButtonList Tasks as shown below

3. Click Edit Items to open the ‘ListItem Collection Editor’ shown below. Hence create radio buttons for ‘Add’, ‘Subtract’, ‘Multiply’, ‘Divide’.

In the Calculate button handler test the RadioButtonList.SelectedItem.Value property to check for +,-,*,/ and perform the calculations accordingly.

As we discussed earlier it is good practice to encapsulate all data and functionality into an object. Given that for this application we have variables that hold data and the functions that process this data. It is desirable to encapsulate the data and functionality in an object. Such objects being instantiated from type definitions called classes.

To use classes the first step is to add an App_Code folder. To do this, simply right click the solution and choose Add ASP.NET Folder. Name the folder App_Code. After the folder is in place, right click the folder and select Add New Item. Choose Class from the Add New Item dialog as shown below:

Dave Parkinson

Page 43: Net Development

.NET DEVELOPMENT Page 43

Name the new file Calculator.cs

Open the Calculator.cs file and add the following function to add two numbers together.

public class Calculator{

public double Add(double a, double b){

return (a + b);}

}

Return to your Exercise 1 design view and double click on the command button to open the code view. Add the following code to the button click object. Note that the IntelliSence capability knows all about the objects in your class.

double a = 0, b = 0, c = 0;Calculator MyCalc = new Calculator();a = System.Convert.ToDouble(TextBox1.Text);b = System.Convert.ToDouble(TextBox2.Text);if (RadioButtonList1.SelectedItem.Value == "add")

{ Label2.Text = "+"; Label4.Text = MyCalc.Add(a,b).ToString(); }

Add further functionality in your class and in your web page to enable subtract, multiply and divide. Test your completed application. Make sure that you use try and catch to test for invalid input into your calculator.

Don’t forget to edit your MasterPage.master file to add the link to exercise1.aspx

Dave Parkinson

Page 44: Net Development

.NET DEVELOPMENT Page 44

5.3 Web Page Exercise 2 – Creating an ASP.NET Web Lottery Number Generator

Add a new form to your existing ASP.NET web application. Name the new Web Form exercise2.aspx.

On the web form add Label boxes and Buttons as shown below to design your lottery number generator :-

HINT - To generate random numbers between 1 and 6 use the following code:-

Random RandomClass = new Random();Num1 = RandomClass.Next(1,7)Num2 = RandomClass.Next(1,7)

When you press the Generate button the six different lottery numbers should be placed in the label boxes.

When you can generate 6 different numbers try and set the individual numbers to match the lottery colours e.g. 0-9 is white, 10-19 is blue, 20-29 is pink, 30-39 is green, 40-49 is yellow. HINT – use System.Drawing.Color. to set the label background colour

When you press the Sort button the numbers should be sorted in numerical order. HINT – use the help files to investigate how to sort data.

Dave Parkinson

Page 45: Net Development

.NET DEVELOPMENT Page 45

Chapter 6 : Validation Web Form Pages

6.1 Introduction

If you want to collect information from the users of your application, you'll most likely need to implement some type of form validation. For example, you'll need a way to make certain form fields required and prevent users from entering the wrong type of information into them.

Fortunately, Visual Studio .NET makes it easy to validate form data. You can add a variety of Validation controls to your Web Form Page to prevent the wrong type of data from being submitted.

6.1.1 Overview of the Validation Controls

There are five standard Validation Web controls that you can add to a Web Form Page to validate form data:

CompareValidator - Enables you to validate the data in a form field against a fixed value or other form field

CustomValidator - Enables you to validate the data in a form field by using a custom subroutine

RangeValidator - Enables you to validate the data in a form field against a minimum and maximum value

RegularExpressionvalidator - Enables you to validate the data in a form field against a regular expression

RequiredFieldValidator - Enables you to validate the data in a form field by checking whether the form field contains a value

All of the Validation controls support three properties-

ControlToValidate property

Text property

IsValid property

The ControlToValidate property contains the name of the form control that you want to validate. For example, suppose that you want to create a text box in a Web Form Page named txtPassword and you don't want a user to be able to submit the form without entering a value for the TextBox control. In that case, you would add a RequiredFieldValidator control to the page and assign the value txtPassword to the RequiredFieldValidator control's controlToValidate property.

Dave Parkinson

Page 46: Net Development

.NET DEVELOPMENT Page 46

The second property that all Validation controls share is the Text property. You assign the error message that you want the Validation control to display to the Text property. For example, you might assign the value You must enter a password! to the Text property of a RequiredFieldValidator control. Whatever error message you assign to the Text property appears at the same location as the Validation control on a page.

Finally, all Validation controls have an IsValid property. The IsValid property has the value True when the control indicated by the controlToValidate property passes the validation test. Otherwise, this property has the value False. You can use this property to determine the nature of the particular validation errors contained in a Web Form Page.

6.1.2 Post Backs and Form Validation

If you have worked with HTML forms in the past, you are probably used to creating forms that post to a new page. To take advantage of Validation controls in a Web Form Page, however, you cannot post the form information to a new page. Instead, you must post the Web Form Page back to the same page on the Web server.

For example, suppose that you want to add two Web Form Pages to a project, a page named Register.aspx and a page named ThankYou.aspx. The Register.aspx page contains a registration form and the ThankYou.aspx page contains a thank you message for registering.

The user submits it, and receives a thank you message. However, you can't take advantage of Validation controls in the Register.aspx page when you post a form to a new page.

Instead, the Register.aspx page should post back to itself. This way, you can display error messages with any Validation controls that you have added to the form. When there are no validation errors in the Register.aspx page, you can explicitly redirect the user to the ThankYou.aspx page.

By default, Web Form Pages automatically post back to themselves. However, you must explicitly add the code to the Web Form to redirect the user to a new page when there are no validation errors in the page.

6.1.3 JavaScript and the Validation Controls

When you use the Validation controls with Microsoft Internet Explorer 4.0 or later, the Validation controls will automatically use client-side ]avaScript. This means that the Validation controls can immediately display error messages on the browser while the user is in the process of completing a form. If there are any validation errors in a page, the client-side ]avaScript will prevent the user from submitting the form back to the server.

If you are not using Microsoft Internet Explorer 4.0 or later, you can still use the Validation controls. The Validation controls will “fall back" to performing validation on the server after the form is submitted to the Web server. Validation error messages won't

Dave Parkinson

Page 47: Net Development

.NET DEVELOPMENT Page 47

be displayed immediately, but they will appear after the page is posted back to the Web server.

6.2 Using Validation Controls

All the Validation controls can be found under the Validation tab in the Toolbox. Because these controls are Web controls, you can add them only to Web Form Pages and not to other types of pages, such as HTML pages.

In the following sections, you'll learn how to take advantage of each of the Validation controls to perform common form validation tasks.

6.2.1 Checking for Required Fields

You can use the RequiredFieldValidator control to automatically display an error message when you submit a form with an empty form field. For example, you can use the RequiredFieldValidator control with a login form to prevent users from submitting the form when values have not been entered for the username and password form fields.

The RequiredFieldValidator has two important properties that you need to set:

Control ToValidate - The form field to validate

Text - The error message to display

6.2.2 Validating a Range of Expressions

You can use the RangeValidator control to specify a minimum and maximum value for a TextBox control. You can use this control to check for a range of integers, currency amounts, dates, strings, or doubles.

The RangeValidator control has five important properties:

ControlToValidate - The form field to validate

MinimumValue - The minimum valid value in the range of values

MaximumValue - The maximum valid value in the range of values

Text - The error message to display

Type - The type of comparison to perform (possible values are String, Integer, Double, Date, Currency)

For example, suppose that you want to add an Age text box to a Web Form Page. In that case, you might want to prevent a user from entering an age less than 2 or more than 100.

Dave Parkinson

Page 48: Net Development

.NET DEVELOPMENT Page 48

If you don't enter a value into the text box and submit the form, the RangeValidator control will not display an error message. If you want to require a value for a control, you must add both a RangeValidator and RequiredFieldValidator control to the Web Form Page.

6.2.3 Web Page Exercise 3 - Using a RequiredFieldValidator Control

1. In your project create a new Web Form Page named exercise3.aspx.

2. Add an HTML Label to the Web Form Page and assign it the text Username.

3. Add a Web Form TextBox control to the Web Form Page.

4. Add a RequiredFieldValidator control to the Web Form. Assign the following two properties to the control:

Property ValueText Required!ControlToValidate TextBox1

5. Add a Button control to the Web Form Page.

Next, you need to add the code that executes when you click the Button control

1. Add a Button1_Click () method to the Web Form Page by double-clicking the Button control on the Designer surface.

2. Enter the following code for the Button1_Click() method:

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

if (Page.Isvalid) Response.Redirect( “success.aspx” );

}

Finally, you need to add the success page to your project and compile the pages:

1. Add a new Web Form Page to your project named success.aspx

2. Add an HTML Label to the success.aspx page and enter the text Thank you for completing the form into the label. Add a link to return to your site home page.

3. Test your program.

Add a RangeValidator to your web form. Check that the data entered is a number between 3 and 9.

6.2.4 Comparing Values

Dave Parkinson

Page 49: Net Development

.NET DEVELOPMENT Page 49

You can use the CompareValidator to compare the value of one control to another control or to compare the value of one control to a fixed value. The CompareValidator has six important properties:

ControlToValidate - The form field to validate

ControlToCompare - The form field to perform the comparison against

Operator - The operator used for the comparison (possible values are Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, and DataTypeCheck)

Text - The error message to display

Type - The type of comparison to perform (possible values are String, Integer, Double, Date, Currency)

ValueToCompare - The fixed value to compare

For example, suppose that you are building a Web application to schedule meetings. The form might contain a field for entering the starting time of the meeting and a second field for entering the ending time of the meeting. You could use the CompareValidator to ensure that the time entered into the second field occurs after the time entered into the first field.

Or, suppose that you have only one form field for entering a meeting date. In that case, you might want to check that the date entered into the field occurs after the current date and time.

Like the RangeValidator, if you don't enter a value into the text box and submit the form, the CompareValidator control will not display an error message. If you want to require a value for a control, you must add both a CompareValidator and RequiredFieldValidator control to the Web Form Page.

6.2.5 Performing Data Type Checks

One common validation task involves checking whether the right type of data was entered into a form field. For example, you do not want users entering the text "apple" into a form field labelled Birth Date.

You can use the CompareValidator to perform data type checks by assigning the value DataTypeCheck to the CompareValidator control's Operator property.The CompareValidator is very picky about the format of acceptable dates. You are allowed to enter dates by using a short date format, such as 12/25/1966. Other date formats, such as December 12, 1966, will fail.

6.2.6 Regular Expression Validation

Dave Parkinson

Page 50: Net Development

.NET DEVELOPMENT Page 50

You can use the RegularExpressionValidator to check whether the value of a form field matches a specified pattern. For example, you can use this Validation control to validate Social Security numbers, postal codes, phone numbers, and email addresses.

The RegularExpressionValidator has three important properties:

ControlToValidate - The form field to validate

Text - The error message to display

ValidationExpression - The regular expression pattern to match

You can supply any regular expression pattern that you want for the ValidationExpression property. Alternatively, you can use one of the predefined regular expression patterns supplied with Visual Studio .NET. If you add a RegularExpressionvalidator control to a page and click the ellipses next to the Validation Expression property, the Regular Expression Editor dialog box appears.

Like the other Validation controls, if you don't enter a value into the text box and submit the form, the RegularExpressionValidator control will not display an error message. If you want to require a value for a control, you must add both a RegularExpressionValidator and RequiredFieldValidator control to the Web Form Page.

6.2.7 Displaying a Summary of Validation Errors

If you are creating a long form that uses several Validation controls, it might be difficult for someone completing the form to see all the validation error messages, For example, if the form has 50 form fields and there is a single validation error that appears next to the 48th form field, the person completing the form may never see it.

You can display a summary of all the validation error messages for a Web Form Page in a single location by using the ValidationSummary control

To take advantage of the ValidationSummary control, you need to provide a value for the ErrorMessage property for each Validation control on a page. The ErrorMessage property contains the error that the ValidationSummary control displays when there is an error.

It is important to not confuse a Validation control's Text property with its ErrorMessage property. The message assigned to the Text property appears at the same location on the Web Form Page as the Validation control. On the other hand, the message assigned to the ErrorMessage property is displayed as part of the summary displayed by the ValidationSummary control.

Typically, you'll want to supply a different error message for the Text and ErrorMessage properties. For example, for the text property, you might assign the message "First name is required!" for the ErrorMessage property.

6.2.8 Web Page Exercise 4 – Validating a Web Form

Dave Parkinson

Page 51: Net Development

.NET DEVELOPMENT Page 51

1. In your project create a new Web Form Page named exercise4.aspx.

2. Add various Labels, TextBoxes, and validation controls to the Web Form Page to check for the validity of the following:-

First Name SurnameAddress PostcodePhoneEmailAge (must be between 18 and 70)

Add a Button control to the Web Form Page to take you to the success.aspx page if all data is entered correctly.

Add a Summary of Validation errors to the Web Page as shown below:

Dave Parkinson

Page 52: Net Development

.NET DEVELOPMENT Page 52

Chapter 7 : Maintaining State on your Web Site

7.1 Introduction

Within the client-server model, when a client wants to view a particular HTML or ASP.NET page he first requests the page and then once the page is found it is returned to him. At this point the conversation between the client and the server is over. The web server does not keep information on what clients it has spoken to recently, or what requests were made. For this reason Web sites are often referred to as stateless (an application is said to have state if it persists information for each user).

Variables within a Web Form Page do not retain their values between requests. Requesting a Web Form Page is similar to starting and stopping an application. After the page is finished being processed, you must start all over again with a blank slate.

If you need to maintain the value of a information required across multiple page requests, you need to do something special. There are various methods of maintaining the state of information within your web site. These are:-

View State to retain the state of variables for a particular page

Cookies to retain information from page to page

Session State to retain the state of variables for a particular user

Application State to retain the state of variables for all users

7.2 Using View State

View State enables you to preserve the state of a page when posting the page back to itself. It's important to understand that View State does not work when posting from one page to another. You can only take advantage of View State when performing postbacks.

Every Web Form control automatically preserves the values of all of its properties through View State. For example, if you type an item in a textbox and perform a postback the value in the textbox will be retained.

View State also applies to the items displayed in a GridView or DetailsView. A GridView or DetailsView automatically retains the values of all of its rows in View State.

View State works by taking advantage of a hidden form field that is automatically added to every Web Form Page. You can see this hidden form field if you select View Source when displaying a Web Form Page in a browser. Immediately before a page is rendered, the values of the properties of all controls in a page are converted into a string. When the page is rendered, this string is assigned to the hidden _VIEWSTATE form field. When the

Dave Parkinson

Page 53: Net Development

.NET DEVELOPMENT Page 53

page is posted back to the server, the string is parsed and all the values are reassigned to the properties of the controls in the page.

7.2.1 Disabling View State

View State can be both a blessing and a curse. View State enables you to magically retain the state of all the controls on a page. However, the hidden VIEWSTATE form field can become very large, which can slow down the rendering of a page.

You don't always need to take advantage of View State. If you don't need to preserve the state of controls across post backs, you don't need to use View State.

You can disable View State for any control by assigning the value False to its EnableViewState property. You should always disable View State for controls such as the Repeater, DataList, and DataGrid controls when you are simply displaying data.

You also can disable View State for all the controls in a page by using the DOCUMENT EnableViewState property. To disable View State for a page, select DOCUMENT in the Properties window and assign the value False to the EnableViewState property.

7.2.2 Adding Custom Information to View State

You can add your own data to View State by taking advantage of the ViewState collection. Any data that you add to the ViewState collection will be added to the _VIEWSTATE hidden form field and will be preserved across postbacks.

For example, the following statement adds the string "Hello World" to the ViewState collection:

ViewState[“myItem”] = “Hello World”;

After an item has been added to the ViewState collection, you can retrieve the item by passing the name of the item to the collection:

Response.Write (ViewState['myItem']);

You can add almost any object to the ViewState collection, including strings, integers ArrayLists, and even DataSets. The only requirement is that the object must be serializable.

However, remember that anything you add to View State must be added to the _VIEWSTATE hidden form field, Consequently, adding a DataSet to View State can significantly impact the rendering time for a page.

Dave Parkinson

Page 54: Net Development

.NET DEVELOPMENT Page 54

7.2.3 Protecting View State

By default, View State is not encrypted. In theory, anyone requesting a page can copy the page to their local hard drive, modify the value of the hidden _VIEWSTATE form field, and submit the modified page back to the server.

For example, if you are storing a shopping cart in View State, someone could modify the price of all the products in the shopping cart and submit the modified page. A great way for users to give themselves massive discounts!

You can protect the integrity of View State by adding a Message Authentication Code (MAC) to the hidden _VIEWSTATE form field. After the View State MAC is enabled, an exception is thrown if someone tampers with the View State.

You can enable the View State MAC for a particular Web Form Page by selecting DOCUMENT in the Properties window and assigning the value True to the EnableViewStateMAC property. You can enable the View State MAC for an application or directory by adding the following tag to the System.Web section of the Web.Config file:

<pages enableViewStateMac='true' />

The View State MAC is disabled by default. Enabling the View State MAC adds some extra work to the processing of the page, so it has an impact on performance. If you don't need it, don't enable it.

Enabling the View State MAC does not result in the View State being encrypted. If you want to encrypt the contents of View State, you need to enable the View State MAC and perform an additional step. You need to add the following tag to the System.Web section of the Web.Config file:

<machinekey validation=”3DES” />

This tag causes all View State to be encrypted using the Triple Data Encryption Standard. Again, this has an impact on performance, so don't enable it unless you need it.

7.3 Using Cookies

A web site does not have to be stateless, it can use cookies to persist information over lengthy periods of time.

Cookies are small bits of information, such as strings and numeric values, stored on a clients computer for a specified period of time. When cookies are created on the clients computer, the developer needs to specify when they expire. After a cookie expires it will automatically remove itself from the clients computer.

When a web site writes a cookie to a clients computer, only that web site can later read the cookie’s value. It is the browsers responsibility to keep track of which web site created the cookie, and only allow cookies to be read by the proper web sites.

Dave Parkinson

Page 55: Net Development

.NET DEVELOPMENT Page 55

It is important to note that all modern browsers provide users with an option not to accept cookies on their computers; however they do accept cookies by default.

If you wanted to store multiple items of information you could use several different cookies. However it more sensible to create a logical structure for your cookies using keys. Each cookie can optionally have a set of keys. Each key can be used to save an item of information. For example, if you wanted to use cookies to save information about visitors it would be sensible to create a single cookie named UserInformation and a set of keys for holding the users name, the last time he accessed your web pages, etc.

Most browsers support cookies of up to 4096 bytes. Because of this small limit, cookies are best used to store small amounts of data. Browsers also impose limitations on how many cookies your site can store on the user's computer. Most browsers allow only 20 cookies per site; if you try to store more, the oldest cookies are discarded. Some browsers also put an absolute limit, usually 300, on the number of cookies they will accept from all sites combined.

7.3.1 Reading Cookies

Cookies are stored and read using HTTP headers (when a client requests a web page from a server, it not only sends the URL of the web page requested but also some additional information. This information consists of useful facts about the client e.g. what browser he is using, what operating system, and the cookies present on the client. This information is called the HTTP headers).

Cookies can be read using the Request object as follows :-

Request.Cookies(“cookiename”)(“keyname”);

Each cookie can have zero to many keys. If a cookie or its keys do not exist on a clients computer (i.e. if they have never been written, or the client has turned off cookies in his browser), then the Request object will return an empty string.

7.3.2 Writing Cookies

Cookies can be written to the clients computer through the HTP headers using the Response object as follows :-

Response.Cookies[“cookiename”] [“keyname”] = data;

Cookies can contain any single data type (e.g. strings, numbers, dates, currencies, and Boolean values), but cannot store arrays or objects.

If we wanted to create a cookie called UserInformation on the clients computer to keep track of a visitors name and the last time he visited the web site then we would use the following ASP code :-

Response.Cookies[“UserInformation”] [“Name”] = “Dave”;Response.Cookies[“UserInformation”] [“LastVisit”] = DateTime.Now.ToString();

Dave Parkinson

Page 56: Net Development

.NET DEVELOPMENT Page 56

When a cookie expires it deletes itself from the clients computer. When creating cookies, you can specify when the cookie should expire using the Expires property. If you do not specify this value, then the cookie is set to expire when the user closes his browser. If you want to maintain state for the duration of the users visit to your site then the default value is ideal. However, cookies are often used to persist state over days, weeks or years. To accommodate for this lengthy a period the Expires property must be set. For example :-

Response.Cookies[“UserInformation”].Expires = DateTime.Now.AddDays(7);

would set the cookie to expire in one weeks time.

7.4 Using Session State

Session State enables you to preserve the values of variables across page requests for a particular user. Session State is typically used for storing shopping carts, user preferences, or user security information, such as usernames and passwords.

Items that you add to Session State are stored in the Web Server's memory. You can add almost any type of object to Session State, including strings, integers, ArrayLists, DataSets, and DataTables. The only requirement is that the object be serializable.

Each variable stored in the Session object is referred to as a session variable and can be created as follows :-

Session[sessionVariableName] = value;

For example :-

Session[“WelcomeMessage”]= “Hello world”;

To read the value of your Session variable in another ASP.NET page on you site you do the following :-

SomeVariable = Session[sessionVariableName];

Because each users Session is created and stored in the Web servers memory, it is important to have this memory freed up when the visitor leaves your site. Due to the nature of the client server model you cannot determine when a visitor leaves your site. However you can keep track of the last time a specific user accessed your site. If a specific user has not accessed your site for a particular amount of time the Session is freed from the Web servers memory. This amount of time can be set as follows (in this example 5 minutes) :-

Session.Timeout = 5;

By default the session timeout is set to 20 minutes. If you want to abandon the users Session explicitly (e.g. by providing a LogOut button) then you use the following :-

Session.Abandon;

Dave Parkinson

Page 57: Net Development

.NET DEVELOPMENT Page 57

You should be careful not to put to many variables into the Session object. All visitors to your site will create a set of Session variables each occupying their own area of Web server memory. If your site is very busy, with a lot of concurrent users, this will result in large amounts of Web server memory being used and this will severely affect the performance of your site. As Session Variables use a cookie to store the session ID (and hence identify the owner of the session), then cookies must be turned on for Session Variable to work.

7.5 Using Application State

Application State variables enables you to preserve the values of variables across page requests for the entire web site. Items that you add to Application State are stored in the Web Server's memory. Each variable stored in the Application object is referred to as a application variable and can be created as follows :-

Application[applicationVariableName] = value;

For example :-

Application[“WelcomeMessage”]= “Hello world”;

To read the value of your Application variable in another ASP.NET page on you site you do the following :-

SomeVariable = Application[applicationVariableName];

Because only one instance of the Application object exists for the entire web site, it should only be used to store information that is specific to the entire webs site.

Because only one application object is shared among all users of your web site you must take care when updating application variables to ensure two users don’t try to access the same variable at the same time. You do this by locking the application object as follows.

Application.Lock;Application[“WelcomeMessage”]= “Hello world”;Application.UnLock;

7.6 Web Page Exercise 5 – Using Cookies and Session Variables

Add a new form to your existing ASP.NET web application. Name the new Web Form exercise5.aspx. Add another new form to your existing ASP.NET web application. Name the new Web Form sessiontest.aspx.

On the web form exercise5.aspx add Label boxes Text boxes and Buttons as shown below to design your Web Page:

Dave Parkinson

Page 58: Net Development

.NET DEVELOPMENT Page 58

Add code to the command button which reads the information from the textbox and passes it to a new page via a session variable and via a cookie.Hint: to force the web site to go to another page rather than post back use Response.Redirect("sessiontest.aspx").

Another cookie should be added to pass the current date and time to the new page. Code should be added to set the session timeout and change the cookie expiration date.

The form sessiontest.aspx should display the information passed to it as shown below:

Dave Parkinson

Page 59: Net Development

.NET DEVELOPMENT Page 59

Chapter 8 : Databases

8.1 Introduction

Nearly every dynamic web application performs some kind of data access, and fortunately ASP.NET 4.0 makes this incredibly easy to do. ASP.NET 4.0 enables a solution for data access binding which requires no code at all for the most common data scenarios, such as:

Selecting and displaying data Sorting, Paging and Caching Data Updating, Inserting and Deleting Data

Data Source ControlsData source controls allow connection to a backend data store, for example a database, XML file, or XML Web Service. Data source controls also enable rich capabilities over data (such as sorting, paging, filtering, updating, deleting, and inserting); that data-bound controls can automatically use. ASP.NET includes the following data source controls

Name Description

SqlDataSource Enables binding to a SQL database represented by an ADO.NET provider, such as Microsoft™ SQL Server, OLEDB, ODBC, or Oracle.

AccessDataSource Enables binding to a Microsoft™ Access (Jet) database.

XmlDataSource Enables binding to an XML file or document.

Data-bound ControlsData-bound Web server controls are controls that can be bound to a data source control to make it easy to display and modify data in your Web application. Data-bound Web server controls are composite controls that combine other ASP.NET Web controls, such as Label and TextBox controls, into a single layout. These controls can optionally take advantage of data source capabilities such as sorting, paging, filtering, updating, deleting, and inserting. ASP.NET 4.0 includes several data bound controls for displaying data e.g.

Name Description

GridView Renders data in a grid format. This control is an evolution of the DataGrid control, and can automatically take advantage of data source capabilities.

DetailsView Renders a single data item in a table of label/value pairs. This control can also automatically take advantage of data source capabilities.

ListView The ListView control displays data from a data source in a format that you define using templates. The ListView control implicitly supports edit, insert, and delete operations, as well as sorting and paging functionality.

Dave Parkinson

Page 60: Net Development

.NET DEVELOPMENT Page 60

8.2 Review of Databases and SQL

Databases hold items of information and the relationships between such items. There are a variety of database management systems available for creating and viewing databases, for example Microsoft Access, Microsoft Sequel Server, Oracle, FoxPro, MySQL etc. ASP.NET will typically be used with either Microsoft Sequel Server databases or Access databases

8.2.1 Relational Databases

Relational Databases typically consist of:-

Tables of information each containing rows of data records

Linkages between different records within tables via primary keys and foreign keys

A data record is an individual entry into the database; for example details about a student, a book, a product, a member of a fan club, etc.

A record is hence divided into fields that hold the required data. For example a student’s record would hold [rollnumber, firstname, surname, course, level, address].

For a relational database one field should serve as a unique ID for that record (e.g. rollnumber) this can hence be specified as the primary key.

A data record can also refer to the keys of records in other tables (e.g. Supervisor’s Employee Number) as foreign keys.

Types of relationships between data are

One to one

One to many

Many to many (not recommended)

Dave Parkinson

Page 61: Net Development

.NET DEVELOPMENT Page 61

8.2.2 Structured Query Language

Structured Query Language, or SQL (pronounced sequel), is an efficient language used by developers to retrieve, add, delete, or modify information in a relational database.Nearly all modem databases communicate via this standard language, so it's essential that you learn the basics of SQL.

The SELECT StatementThe SELECT statement is probably the most common SQL statement. Its basic purpose is to grab a set of data from a database table. The syntax for the SELECT statement is as follows:

SELECT selectlist FROM tablename [WHERE searchCondition] [ORDER BY orderbyExpression [ASC | DESC ]]

The structure follows basic English. selectlist is generally a comma-delimited list of the columns you want to return. For example, Name ,First_Name would return the values in these two columns. Additionally, an asterisk (*) can be used to return all of the columns from a particular table. tablename is the name of the table to grab the data from. An example of a simple SELECT statement to load all the data from the table in the database created earlier into a recordset is:

SELECT * FROM addresses

Note that you shouldn't use SELECT * because often it returns more information than you need. This can result in decreased performance. Instead, explicitly specify the columns you need to return. This will take a bit longer when coding, but your code will enjoy performance benefits. For example if we only wanted to return the data in the Name and First Name columns we should use :

SELECT Name, First_Name FROM addresses

SELECT statements always return all the rows in your database (unless qualified with a WHERE clause).

You can use the WHERE clause to specify additional criteria for the returned data. A WHERE clause can generally be any logical statement, similar to an if statement in regular programming languages. For example:-

SELECT * FROM addresses WHERE FirstName='Chris'

SELECT * FROM addresses WHERE First_Name='Chris' AND Name='Smith'

The first statement returns only records where the First_Name field value is "Chris". The second statement returns only the records where First_Name field value is "Chris" and the Name field is equal to "Smith".To use wildcards for your SQL WHERE clause criteria, you can use the LIKE keyword followed by wildcard operators. The LIKE keyword accepts the following operators.

Dave Parkinson

Page 62: Net Development

.NET DEVELOPMENT Page 62

* A string of zero or more characters

_ Exactly one character

[ ] A specific character in the given set

For example :-

1. SELECT * FROM addresses WHERE First_Name LIKE '*s*'

2. SELECT * FROM addresses WHERE First_Name LIKE '_hris'

3. SELECT * FROM addresses WHERE First_Name LIKE '[abcd]hris'

The SQL statement on line 1 returns any rows where the First_Name contains an s somewhere in the value. The * operator works the same in SQL as it does in Windows, meaning zero or more characters.

The SQL statement on line 2 returns any records where the first name contains anyone letter, followed by the string "bris".

The SQL statement on line 3 returns any records where the first name contains a string that begins with any of the letters a, b, c, or d, followed by the string "bris".

The ORDER BY clause specifies the order in which the data is returned, such as alphabetical order. Without this clause, there's no way to know in what order the database will return records. Even though they may have been entered alphabetically during data entry, that doesn't mean the records will be returned the same way. The ORDER BY clause lets you specify which columns to order the data by, and how. If used with columns containing string characters, it converts those characters into their ASCII equivalents and sorts based on those numbers. For example :-

SELECT * FROM addresses ORDER BY First_Name ASC

This statement returns all records sorted alphabetically by first name. Likewise, specifying DESC sort order instead of ASC returns reverse-alphabetic order. You can specify multiple columns delimited by commas in the ORDER BY clause as well, each with its own sort order. SQL will use the additional columns if the first one contains any duplicate data. For example, the following statement would order the data by name unless two names were identical when it would order by first name.

SELECT * FROM addresses ORDER BY Name, First_Name ASC

You can also use SELECT statements to return data from more than one table at once. This is done with a comma-delimited list of table names for the tablename argument.

The INSERT StatementAnother common SQL statement is the INSERT statement, which is used to insert new rows into a database table. Its basic syntax is as follows:

INSERT [INTO] tablename [column list]

Dave Parkinson

Page 63: Net Development

.NET DEVELOPMENT Page 63

VALUES (DEFAULT | NULL | expression)

This statement is similar in syntax to SELECT. For example :-

INSERT INTO addresses (First_Name, Name, Address, Phone)VALUES ('Chris','Payne','135 Ash Street','8006596598')

This statement inserts a new row with the field values specified in the VALUES clause. The data type you supply in VALUES must match the data type in the corresponding column or you will receive an error. Also, if you specify a column, you must specify a value or you'll get another error.

The UPDATE StatementThe UPDATE statement updates existing rows in a database table. You can specify a WHERE Clause with this statement to update only a subset of the values in a database table. The syntax is as follows:

UPDATE tablename SET column name = (DEFAULT | NULL | expression)[WHERE searchCondition]

If you leave off the WHERE clause, the specified column(s) are updated in every row in the database. Be very careful with this statement, because it's easy to ruin your data! An example of the use of the UPDATE statement is :-

UPDATE addressesSET Address = '136 Ash Street' WHERE First_Name = 'Chris' AND Name = 'Payne'

This statement changes the Address record where the First_Name is "Chris" and the Name is "Payne”. You can specify only the columns you need in the column name list, and the WHERE clause is exactly the same as the SELECT statement.

The DELETE StatementThe DELETE statement deletes rows from a database. The syntax is :

DELETE FROM tablename [WHERE searchCondition]

The DELETE statement is very simple. The only thing to remember is the WHERE clause, which is very important. If you don't specify this clause, the DELETE statement will delete all the rows in the entire table, normally a disastrous occurrence. Again, the WHERE clause is exactly the same as for the SELECT statement. For example, the following deletes only records with the first name "Chris":

DELETE FROM addresses WHERE First_Name = 'Chris'

Dave Parkinson

Page 64: Net Development

.NET DEVELOPMENT Page 64

8.3 Web Page Exercise 6 - Reading Data from an Access Database

1. Create an Access database (test.accdb) using Access 2010 with a table called people containing the fields shown below, using the lastname as the primary key.

Populate the database as shown below:

Save the database in the App_Data folder within your website directory.

2. Within your Visual Studio Project create a new web form exercise 6.aspx

Open Server Explorer within Visual Studio. And then right click on Data Connections and select Add connection. This brings up the dialog box:

Dave Parkinson

Page 65: Net Development

.NET DEVELOPMENT Page 65

To connect to an Access database select Change data source and select Microsoft Access Database File

Click OK, then browse to select your Access database:

You can only add new tables and fields to an Access database using the Access application. You can however edit the table data by selecting the table and right clicking to select Retrieve Data.

Dave Parkinson

Page 66: Net Development

.NET DEVELOPMENT Page 66

3. From the Data section of the Toolbox drag a GridView object onto your web page:-

The GridView control allows for tabular data display and editing. The following features are available in the GridView control.

Binding to data source controls, such as AccessDataSource. Built-in sorting capabilities. Built-in updating and deleting capabilities. Built-in paging capabilities. Built-in row selection capabilities. Programmatic access to the GridView object model to dynamically set properties,

handle events, and so on. Multiple key fields. Multiple data fields for the hyperlink columns. Customisable appearance through themes and styles.

Click the smart tag to open GridView Tasks and select <new data source>

Select the Access database from within the App_Data directory and the wizard will bring you to the Configure Data Source dialog.

Dave Parkinson

Page 67: Net Development

.NET DEVELOPMENT Page 67

Select your Access database (test.accdb).The next step is to configure the SQL Select statement to retrieve your required data.

You can specify columns from a table or view, or you can specify a custom SQL statement or name a stored procedure. For this example select all four columns as shown above. Try using the ORDER BY option to organise your data alphabetically by lastname. You can also use the WHERE option to select certain sections of your database.

Clicking the Next button lets you test your query and see the results. If you are satisfied click Finish

4. Test your ProgramThe output from your program should look like:-

Dave Parkinson

Page 68: Net Development

.NET DEVELOPMENT Page 68

Experiment with Auto Format within the GridView Tasks. Also try changing the properties of the GridView control (i.e. font etc.). Test the options to Enable Paging, Enable Sorting and Enable Selection.

Using this method of connection, if we wish to add editing functions to this table (i.e. modify, add and delete entries) then we have to write our own functions to provide these facilities. Another option is to use datasets which have pre-written functions to provided these facilities as part of the .Net Framework.

8.4 Using Datasets to connect to a Database

ADO.NET assumes a model for data access in which you open a connection, get data or perform an operation, and then close the connection. ADO.NET provides two basic strategies for how you work with this model.

One model is to perform operations directly against the database. As we saw in the previous example you use a data command object that includes an SQL statement or a reference to a stored procedure. You can then open a connection, execute the command to perform the operation, and then close the connection. If the command returns a result set, that is, if the command performs a Select statement, you can load the data directly into a DataGrid, or you can fetch the data using a data reader, which acts like a highly efficient read-only cursor. The data reader can then act as a source for data binding.

An alternative strategy is store data in a dataset, which is an in-memory cache of records you can work with while disconnected from the data source. To use a dataset, you create an instance of it and then use a data adapter to fill it from the data source. You then work with the data in the dataset, for example, by binding controls to dataset members.

This model for data access in Visual Studio .NET applications allows you to store data in datasets and use a data adapter to read and write data in the database. The advantages of the dataset model are:

Dave Parkinson

Page 69: Net Development

.NET DEVELOPMENT Page 69

Working with multiple tables   A dataset can contain multiple tables of results, which it maintains as discrete objects. You can work with the tables individually or navigate between them as parent-child tables.

Manipulating data from multiple sources   The tables in a dataset can represent data from many different sources (for example, from different databases, from XML files, spreadsheets, and so on, all in the same dataset). Once the data is in the dataset, you can manipulate it and relate it in a homogeneous format as if it had come from a single source.

Data exchange with other applications   A dataset provides a powerful way to exchange with other components of your application and with other applications. Datasets include extensive support for features such as serializing data as XML and reading and writing XML Schemas.

Data binding   If you are working with forms, it is usually easier to bind controls to data in a dataset than it is to programmatically load data values into the control after executing a command.

Maintaining records for reuse   A dataset allows you to work with the same records repeatedly without requerying the database. Using dataset facilities, you can filter and sort records, and you can use the dataset as a source of data if you are paging.

Ease of programming   When you work with a dataset, you can generate a class file that represents its structure as objects (for example, a Customers table in the dataset can be accessed as the dataset.Customers object). This makes it easier, clearer, and less error-prone to program with, and is supported by Visual Studio tools such as IntelliSense, the Data Adapter Configuration wizard, and so on.

Datasets store data in a disconnected cache. The structure of a dataset is similar to that of a relational database; it exposes a hierarchical object model of tables, rows, and columns. In addition, it contains constraints and relationships defined for the dataset.

8.4.1 Connecting to a Database using Typed Data Sets

In the previous example when we wish to display a database we first load it into a GridView. We often wish to access the data within this GridView to search and check particular values within it. Using the methods explained to date we can easily display and contents of data from a database. However the data fetched by the Data Source is not easily made available for more complex data manipulation (i.e. we cannot edit the data or move data to and from the database into variables). In order to gain more control when accessing a database we need to use a typed data set. Typed data sets are a form of strongly typed business objects that fetch data from a database and expose it via a set of methods. This enables the programmer to directly gain control of data obtained from the database. The typed dataset (as opposed to an untyped dataset) allows us to access the rows and columns by their actual names.

In order to connect to our database via a dataset we take the following steps:

1. Add a Web Form Page to your project named exercise7.aspx.

2. Create a typed data set by adding a new item to the App_Code folder by selecting the DataSet option from the Add New Item Dialog. Name the DataSet people.xsd

Dave Parkinson

Page 70: Net Development

.NET DEVELOPMENT Page 70

Select Add. This opens the following screen. Right click on the screen and select Add – TableAdapter as shown below:

The TableAdapter Configuration wizard opens and allow you to select the data source. Chose the connection string to the test.mdb database in the App_Data directory (held in the web.config file).

Dave Parkinson

Page 71: Net Development

.NET DEVELOPMENT Page 71

Select that the TableAdapter should use SQL statements to access the database

and then use the Query Builder to select every item from the people table.

In the advanced options select the Generate Insert, Update and Delete statements. After the query and advanced options are set, you can configure the methods that will be generated.

Press OK, the Next.

Dave Parkinson

Page 72: Net Development

.NET DEVELOPMENT Page 72

Select the options as shown above. This creates a method for filling a DataTable Fill( ) and a method for returning a DataTable GetData( ). The GetData method will return a DataTable object with the contents of the database selected via the SQL statement set up earlier. The final option allows the creation of insert, update and delete methods. When the configuration wizard has finished, the data set is shown in the design window.

VERY IMPORTANT - Save your dataset. You can now use the data set directly in code.

3. Drag a GridView onto the page (exercise7.aspx) and choose a new data source type. When asked for the where the data is from choose an Object and leave the ID as ObjectDataSource1.

Dave Parkinson

Page 73: Net Development

.NET DEVELOPMENT Page 73

You will then be asked to choose a Business Object. Select peopleTableAdapters.peopleTableAdapter as shown below.

Leave the Define Data methods as shown below then select Finish.

Dave Parkinson

Page 74: Net Development

.NET DEVELOPMENT Page 74

Run the program and check you can view the database.

4. Adding an Editing Facility Visual Studio allows you to add various facilities to the GridView without writing any code. Click the smart tag on the grid and try the new checkboxes (Editing, Deleting) to test the effects on your web site.

5. Adding an Insert FacilityFrom the Data section of the Toolbox drag a DetailsView object onto your web page directly below the GridView.

The DetailsView control is used to display a single record from a data source in a table, where each field of the record is displayed in a row of the table. It can be used in combination with a GridView control for master-detail scenarios.

The DetailsView control supports the following features: Binding to data source controls, such as AccessDataSource. Built-in inserting capabilities. Built-in updating and deleting capabilities. Built-in paging capabilities. Programmatic access to the DetailsView object model to dynamically set

properties, handle events, and so on. Customisable appearance through themes and styles.

Dave Parkinson

Page 75: Net Development

.NET DEVELOPMENT Page 75

Choice the same Data Source as set for the GridView (ObjectDataSource1) and Enable Inserting.Within the properties view set the Default Mode to Insert

Test your program. It should appear as shown below:

8.5 Other Data-Bound Controls

List ViewThe List View data-bound control is a very powerful object gives much more control over the layout of your data from an Data Source. It includes a series of different templates that you can configure to suit your needs. It includes 11 different control templates along with the capability of designing your own template. These templates range from simple data views to templates offering support for editing, inserting, deleting and paging.

Dave Parkinson

Page 76: Net Development

.NET DEVELOPMENT Page 76

DropDownListThis control enables the user to populate a drop down list directly from a data source.

ListBoxThis control enables the user to populate a list box directly from a data source.

RadioButtonListThis control enables the user to populate a Radio Button list directly from a data source.

CheckBoxListThis control enables the user to populate a check box list directly from a data source.

8.5.1 Exercise 8 – Using List View and other Data-Bound Controls

1. In your project create a new Web Form Page named exercise8.aspx.

2. Add a list view to your web page and link it to the people table in your Access Database via the same dataset we used in exercise 7.

3. Experiment with the various templates to display the data on your page. For Example:

4. Try adding a DropDownList, ListBox, RadioButtonList and CheckBoxList to your page and experiment with their settings.

8.6 Searching through a Database Table using Typed Data Sets

When we wish to display a database we first load it into a GridView. We often wish to access the data within this GridView to search and check particular values within it.

Using some of the methods explained to date we can easily display the contents of data from a database. However the data fetched by the Data Source is not easily made available for more complex data manipulation (i.e. we cannot move data to and from the database

Dave Parkinson

Page 77: Net Development

.NET DEVELOPMENT Page 77

into variables). In order to gain more control when accessing a database we need to use a typed data set. Typed data sets are a form of strongly typed business objects that fetch data from a database and expose it via a set of methods. This enables the programmer to directly gain control of data obtained from the database.

8.6.1 Web Page Exercise 9 – Searching through a Database Table

The following exercise shows how we can search through a database containing the following fields:-

and check to find a match between the number in a textbox (inputted by the user of the program) and the numbers in the columns in the database. If a match is found the person ‘owning’ that number is displayed on the screen.

1. Add a new table called numbers to your existing database test.accdb as shown above. Add fields ‘name’, ‘number1’, ‘number2’, ‘number3’ to your table. The name field datatype should be set to ‘text’ and the number fields datatype set to ‘number’. Set the name field as the primary key.

2. Add a Web Form Page to your project named exercise9.aspx.

3. Create a typed data set by adding a new item to the App_Code folder by selecting the DataSet option from the Add New Item Dialog. Name the DataSet numbers.xsdAdd a TableAdapter as we did previously. The TableAdapter Configuration wizard opens and allow you to select the data source. Chose the connection string to the test.accdb database in the App_Data directory (held in the web.config file).

Select that the TableAdapter should use SQL statements to access the databaseand then use the Query Builder to select every item from the numbers table.

Dave Parkinson

Page 78: Net Development

.NET DEVELOPMENT Page 78

In the advanced options select the Generate Insert, Update and Delete statements. After the query and advanced options are set, you can configure the methods that will be generated.

Accept the options given. When the configuration wizard has finished, the data set is shown in the design window.

Save your dataset. You can now use the data set directly in code.

Dave Parkinson

Page 79: Net Development

.NET DEVELOPMENT Page 79

4. Drag a GridView onto the page (exercise9.aspx) and choose a new data source type. When asked for the where the data is from choose an Object and leave the ID as ObjectDataSource1.

You will then be asked to choose a Business Object. Select your numbersTableAdapter as shown below.

Leave the Define Data methods as shown then select Finish.

Run the program and check you can view the database.

5. You can now access the data from the data set. You can create a numbersDataTable to represent the table, and then access the data from individual rows. For example if we wish to check as before that a particular number (set in a TextBox) is set in the numbers1 field in the data table then we do so using the following code:

numbersTableAdapters.numbersTableAdapter num = new numbersTableAdapters.numbersTableAdapter();numbers.numbersDataTable numtable = num.GetData();Label1.Text = "";

foreach (DataRow row in numtable.Rows) if (TextBox1.Text == System.Convert.ToString(row["number1"])) { Label1.Text = " Mr " + System.Convert.ToString(row["name"]) + ", your number matches "; }

Dave Parkinson

Page 80: Net Development

.NET DEVELOPMENT Page 80

In order to use this method of reading from a dataset we need to add a new Namespace to our program. Add the following under the existing Namespace declarations:

using System.Data;

Add a Textbox below the gridview and the add a Button as shown below. Add the code shown above to the Button. The code creates a new data table called numtable and fills it with the contents selected from the database. The foreach statement tests each row within the data table to see if the data in the TextBox matches the contents of the number1 field on the row in question. Test your program.

Try and extend your program to test for all three numbers matching.

6. You can extend the program still further by providing a means of editing the data table by reading the contents of a particular data cell into a TextBox and then changing the contents and writing them back to the data table and hence the database.

Add a text box and two command buttons (labelled Read and Write) to your web page. In order to identify the row within the GridView we wish to edit you need to enable selection within your GridView. This allows you to identify the row selected from within your code.

On the read button add the following code:

numbersTableAdapters.numbersTableAdapter num = new numbersTableAdapters.numbersTableAdapter();numbers.numbersDataTable numtable = num.GetData();int i = GridView1.SelectedIndex;TextBox2.Text=System.Convert.ToString(numtable.Rows[i]["number1"]);

On the write button add the following code:

numbersTableAdapters.numbersTableAdapter num = new numbersTableAdapters.numbersTableAdapter();numbers.numbersDataTable numtable = num.GetData();

Dave Parkinson

Page 81: Net Development

.NET DEVELOPMENT Page 81

int i = GridView1.SelectedIndex;numtable.Rows[i]["number1"]= System.Convert.ToInt16(TextBox2.Text);num.Update(numtable);GridView1.DataBind();

The finished program is shown below. Test your program.

Dave Parkinson

Page 82: Net Development

.NET DEVELOPMENT Page 82

Chapter 9 – Configuring your Web Application

9.1 Introduction

One of the goals of the .NET Framework is to eliminate the need to use the Windows registry to store application configuration settings. This is good news because dependence on the Windows registry results in a number of problems:

Storing configuration information in the Windows registry makes it difficult to move an application from one server to another. In particular, it makes it difficult to move an application from a development server to a production server because every registry setting must be moved from one server to the other.

The Windows registry can become corrupted, causing your application to fail.

You must use special utilities to edit the Windows registry, which makes it difficult to perform quick modifications.

The .NET Framework replaces the Windows registry with the Machine.Config and Web.Config files. These files are plain text files in XML format. You can edit them with any text editor, including Notepad.

The Machine.Config file contains configuration settings that apply to every .NET application on a server. It's the master configuration file. You can find this file at \WINNT\Microsoft.NET\ Framework\ Version\CONFIG.

Typically, you do not modify the Machine.Config file. Instead, you override configuration settings in the Machine.Config file within a lower-level Web.Config file. The Web.Config file doesn't contain any additional sections that are not included in the Machine.Config file.

You can place a Web.Config file in a number of different locations. The location of the Web.Config file determines the scope of its configuration settings. For example:

wwwroot - If you place a Web.Config file in the root directory of a Web site, it applies to all Web applications contained within the Web site.

directory - If you place a Web.Config file in a particular directory, it applies to all files in that directory and all files located in directories below that directory.

The Machine.Config and Web.Config files work hierarchically. The Machine.Config file is huge. However, if you want to override a configuration setting in a Web.Config file, you don't need to copy the whole Machine.Config into the Web.Config file. You can copy only those settings that you want to override.

Dave Parkinson

Page 83: Net Development

.NET DEVELOPMENT Page 83

9.2 Web Forms Authentication

Most web applications include password protected areas. For example, if you are building an online store, you need to allow users to register before they buy a product. Or you may want protect some pages in your web site so that only administrators can access a page.The .NET Framework includes three built-in methods of authenticating users:

Windows Authentication

Forms Authentication

NET Passport Authentication

All these authentication methods follow a similar model, if you understand how to configure one, you can configure the other two.

Windows Authentication uses Windows accounts, and Microsoft .NET Passport Authentication uses Microsoft Passport user accounts (the same user accounts that are used by such Microsoft services as HotMail and MSN).

We will concentrate on Forms Authentication because this is the type of authentication that you are most likely to set up for a Web application. Forms Authentication, unlike the other two authentication models, enables you to store usernames and passwords in a custom data store, such as a database table or XML file.

Before discussing the topic of Forms Authentication, we need to understand how Microsoft distinguishes between the following two terms:

Authentication - The process of identifying a user

Authorisation - The process of determining the resources a user is allowed to access

Forms Authentication handles authentication by creating a browser cookie that identifies a user. It handles authorisation by enabling you to create a configuration file that lists the resources a user is allowed to access.

When you configure Forms Authentication, you need to create two Web.Config files (or a single Web.Config file with two sections). You need to create a Web.Config file that indicates the type of authentication you want to perform, and a Web.Config file that authorizes access to different users or roles.

A minimal authentication Web.Config file looks as follows:

<configuration> <system.web>

<authentication mode=”Forms” /> </system.web> </configuration>This file simply enables Forms Authentication for an application as opposed to Windows or Passport Authentication. The default authentication method, as specified in the

Dave Parkinson

Page 84: Net Development

.NET DEVELOPMENT Page 84

Machine.Config file, is Windows Authentication. This configuration file overrides the default setting.

The <authentication> section must be placed in the root Web.Config file for an application. You can enable only one method of authentication for an application. For example, one application cannot use both Forms Authentication and Passport Authentication.

An authentication Web.Config file doesn't do anything interesting by itself. To password protect pages, you need to add another Web.Config file that contains an <authorization> section. A minimal authorization Web.Config file looks like the following:

<configuration> <system.web>

<authorization> <deny users=”?” />

</authorization> </system.web> </configuration>

This Web.Config file prevents anonymous (unauthenticated) users from accessing any pages in the current directory or any subdirectory. If an anonymous user attempts to access a page, the user is automatically redirected to a page named Login.aspx.

By default, unauthorized users are redirected to the application root Login.aspx page. You can supply an alternative path for the Login page by modifying the loginUrl attribute in the authentication Web.Config file as follows:

<configuration> <system. web>

<authentication mode=”Forms”> <forms loginUrl=”mylogin.aspx” />

</authentication></system.web> </configuration>

Forms Authentication only applies to resources mapped into the .NET Framework. By default, it does not apply to HTML or classic ASP.

The <authentication> section accepts two different elements: <deny> and <allow>. The <deny> element can be used to deny access to a list of users or roles. The <allow> element enables access.

You can specify users or roles by name. You can also use two special symbols: ? and *. The question mark (?) represents all anonymous users. The asterisk (*) represents all users, regardless of whether they are authenticated.

Consider, for example, the following Web.Config file:

<configuration> <system.web>

Dave Parkinson

Page 85: Net Development

.NET DEVELOPMENT Page 85

<authorization> <allow users=”Jane” /><deny users=”*”/>

</authorization> </system. web> </configuration>

This authorization Web.Config file denies access to all the pages in a directory to all users except Jane. The <authorization> section uses a first match algorithm. The order of the <allow> and <deny> elements here is important. If you reversed the order, all users, including Jane, would be denied access.

You can add multiple authorization Web.Config files to a single application. For example, you can prevent anonymous users from accessing pages in certain folders and not others. You can also password protect an entire application by adding an <authorization> section to the root Web.Config file.

You should keep in mind that the Web.Config file works by inheritance. Unless you override an authentication section in a lower-level Web.Config file, authentication settings will apply to all the files in a folder and all of its subfolders.

9.2.1 Web Exercise 10 – Password Protecting an area of your Web Site

In this exercise, we will walk through each of the steps required to enable Forms Authentication. We will password-protect all the pages in a directory named SecretFile so that only users who log in can view the pages.

The first step is to enable Forms Authentication for your web site by modifying the Web.Config file located in the root directory of your application.

1. Double-click the root Web.Config file in the Solution Explorer window.

2. Find the section in the Web.Config file that says :

<system.web><compilation debug="true" targetFramework="4.0"/>

</system.web>

3. Change it to the following:

<system.web><compilation debug="true" targetFramework="4.0"/><authentication mode="Forms" />

</system.web>

4. Click the Save button to save the modified Web.Config file.

This Web.Config file enables Forms Authentication for your entire application.

Dave Parkinson

Page 86: Net Development

.NET DEVELOPMENT Page 86

Making these modifications does not password protect any pages. However, it is a necessary step before you can password protect a page.

Next, we need to create the Web Form Page that we want to password protect.

1. Add a new folder to your application named SecretFiles by right-clicking your application name in the Solution Explorer Window and selecting Add, New Folder.

2. Edit your master page to add a link to a page we will be creating later in this directory

<li><a href="SecretFiles/secret.aspx">Exercise 10</a></li>

3. As the web page we will be creating is in a different directory to our other pages, the current master page will not work (the links will point to the wrong place). To fix this we need to create a new master page. Make a copy of the existing master page and rename it MasterPage1.master. Modify the body section of this new master page as follows:

<body> <form id="form1" runat="server"> <div id="container" class="container_16"> <div id="title" class="grid_16"> <img src="../images/salford_university.gif" alt="Salford University" /> </div> <div id="menu" class="grid_3"> <ul> <li><a href="../index.aspx">Home</a></li> <li><a href="../exercise1.aspx">Exercise 1</a></li> <li><a href="../exercise2.aspx">Exercise 2</a></li> <li><a href="../exercise3.aspx">Exercise 3</a></li> <li><a href="../exercise4.aspx">Exercise 4</a></li> <li><a href="../exercise5.aspx">Exercise 5</a></li> <li><a href="../exercise6.aspx">Exercise 6</a></li> <li><a href="../exercise7.aspx">Exercise 7</a></li> <li><a href="../exercise8.aspx">Exercise 8</a></li> <li><a href="../exercise9.aspx">Exercise 9</a></li> <li><a href="secret.aspx">Exercise 10</a></li> </ul> </div> <div id="content" class="grid_13"> <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder> </div>

<div id="footer" class="grid_16"> <p>Footer here</p> </div> </div> </form></body>

4. Add a new Web Form Page to the SecretFiles folder by right-clicking SecretFiles in the Solution Explorer window and selecting Add, Add Web Form. Make sure you select the

Dave Parkinson

Page 87: Net Development

.NET DEVELOPMENT Page 87

new master page, MasterPage1.master. Provide the name Secret.aspx for the new Web Form Page and click Open.

5. Drag a Label onto the Secret.aspx page.

6. Enter the text This Content is Secret! in the label.

Finally, to password protect the files in the SecretFiles folder, we must add a second Web.Config file to the SecretFiles folder. This second Web.Config file contains an <authentication> section that prevents anonymous users from accessing the folder.

1. Right-click the SecretFiles folder in the Solution Explorer window and select Add, Add New Item. When the Add New Item dialog box appears, select Web Configuration File in the Templates panel and click Open.

2. Your new Web.Config file should contain the following:

<?xml version="1.0"?><configuration> <system.web>

</system.web></configuration

3. Add the following configuration settings within the system.web tags:

<system.web> <authorization>

<deny users=”?” /></authorization>

</system.web>

4. Click Save.

After you complete this last set of steps, all of the files in the SecretFiles folder are password protected. If you select the Secret.aspx page in the Solution Explorer window and test the application, you'll receive a 404 “resource cannot be found” error. You have been automatically redirected to a page named Login.aspx that doesn't exist. Now we will create the Login.aspx page.

If a user attempts to access a password protected page, he is automatically redirected to a page named Login.aspx. Our login page will allow a user to log in only when the user enters the username Administrator and the password Secret.

Perform the following steps to add the necessary controls to the Login.aspx page:

1. Add a new Web Form Page to the root folder of your project named Login.aspx,

2. Add Labels, TextBox controls and a Button to your page as shown below (set the TextMode property for the second TextBox to be Password):

Dave Parkinson

Page 88: Net Development

.NET DEVELOPMENT Page 88

Enter the following code for the Log in handler:

if (TextBox1.Text == "Administrator" && TextBox2.Text == "Secret")System.Web.Security.FormsAuthentication.RedirectFromLoginPage(TextBox1.Text,false);

elseLabel3.Text = "Invalid Username/Password";

Leave Secret.aspx as your start page and test your application. You will automatically be redirected to your Login.aspx page. If you enter Administrator and Secret, you will be automatically redirected back to the Secret.aspx page (the username and password are case sensitive).

The Button1_Click handler first checks whether the Username and Password TextBox controls contain the values Administrator and Secret. If the values match, the RedirectFromLoginPage ( ) method is called.

The RedirectFromLoginPage ( ) method does two things. First, it issues an Authentication Ticket to the user's browser. The Authentication Ticket is an encrypted cookie that identifies the user. It also automatically redirects the user back to the original page that the user requested by secretly calling the Response.Redirect ( ) method.

The RedirectFromLoginPage( ) method accepts two parameters. The first parameter represents a username. The username can be any string, including an email address.The second parameter indicates whether a persistent cookie should be created. When the second parameter has the value true, the user does not have to log in the next time the user visits the Web site. The Authentication cookie is saved persistently on the user's browser.

Note :The RedirectFromLoginPage ( ) method redirects the user to the original page the user requested. There is a special situation, however, when the user requests the Login.aspx page directly. In that situation, there is no page to which the user can be redirected, so the user is redirected to the Default.aspx page.

After a user has logged in, you can retrieve the user's username by using the User.Identity.Name property (a property of the Page class). This is useful when you want to customize pages for particular users.

Modify your Secret.aspx page to display the username of the person logging on.

You can also add a Sign Out link to the pages in your application by taking advantage ofthe FormsAuthentication.SignOut( ) method. This method removes the Authentication Ticket cookie from the user's browser.

Add a logout button to your web page, and add the following code to the button

Dave Parkinson

Page 89: Net Development

.NET DEVELOPMENT Page 89

System.Web.Security.FormsAuthentication.SignOut();Response.Redirect(“../Login.aspx?ReturnUrl=” + Server.UrlEncode(Request.Path ));

Your web page should appear as follows:

Test your web page. When the Secret.aspx page opens, a Sign Out link appears. If you click the Sign Out link, you are redirected to the Login.aspx page. Furthermore, if you attempt to go directly back to the Secret.aspx page after signing out, you are redirected to the Login.aspx page.

The second line of code in the Buttonl_Click handler performs the redirection.Notice that a query string parameter named ReturnUrl is passed back to the Login.aspx page. The FormsAuthentication. RedirectFromLoginPage ( ) method uses this query string parameter when redirecting a user who has successfully logged in.

9.2.2 Storing Usernames and Passwords in the Web.Config File

In the Login.aspx page that we built in the previous section, we checked whether the user entered the usemame Administrator and the password Secret. Our application isn't particularly useful because only one person can ever log in. We can, however, store a list of usernames and passwords in the Web.Config file.

Storing usernames and passwords in the Web.Config file is valuable when you need to maintain a limited number of usernames and passwords. For example, if your Web application contains a private section for administrators of the application, you can password protect the section and store a list of valid administrators in the Web.Config file.

1. Modify the application root Web.Config file that we created in the previous exercise.

<system.web> <authentication mode="Forms">

<forms><credentials passwordFormat="Clear"> <user name="Dave" password="Secret" /> <user name="Jane" password="Secret" /> <user name="Fred" password="Secret" /></credentials>

</forms></authentication>

</system.web>

Dave Parkinson

Page 90: Net Development

.NET DEVELOPMENT Page 90

2. Right-click the Login.aspx page in the Solution Explorer window and select Code from the View menu. Modify the Buttonl_Click handler as follows:

if(System.Web.Security.FormsAuthentication.Authenticate(TextBox1.Text,TextBox2.Text)) System.Web.Security.FormsAuthentication.RedirectFromLoginPage(TextBox1.Text,false);

else Label3.Text = "Invalid Username/Password";

3. Test your web application.

After you complete these steps, you can view the Secret.aspx page only if you enter one of the username and password combinations contained in the application Web.Config file. We modified the Login.aspx page to use the Authenticate ( ) method to check usernames and passwords. The Authenticate ( ) method simply performs a match against usernames and passwords in the Web.Config file.

9.2.3 Storing Usernames and Passwords in a Database

1. Add a new table called passwords to the Access database. Add fields ‘username’, ‘password’ to your table. The fields datatypes should be set to ‘text’. Set the username field as the primary key.

2. Create a new web page, logindb.aspx.

3. Change the root directory web.config to point to this page as the default login. Also change the secret.aspx file to redirect back to the new logindb.aspx page on a logout

4. Using the same design as in the previous login page write code that will check that the username and passwords entered match passwords in the database table before authenticating.

HINTCreate a DataSet (called password.xsd) to connect to the database and then access the data in the same manner as in Exercise 9. Within a foreach loop read the values of username and password from the table, check these against the contents of the textboxes, and authenticate the user if a match is found as we did previously.

Dave Parkinson

Page 91: Net Development

.NET DEVELOPMENT Page 91

Chapter 10 : Other Useful ASP.NET v3.5 Features

10.1 RSS Feeds – Exercise 11

A popular facility on websites is the ability to display current data from an RSS feed. This enables some of the content on your site to be changed, and up to date, every time a user visits your site. What is RSS? RSS (originally stood for Rich Site Summary but since version 2.0 is now called Really Simple Syndication) is a format for delivering regularly changing web content. Many news-related sites, weblogs and other online publishers syndicate their content as an RSS Feed to whoever wants it. RSS solves a problem for people who regularly use the web. It allows you to easily stay informed by retrieving the latest content from the sites you are interested in. You save time by not needing to visit each site individually. You ensure your privacy, by not needing to join each site's email newsletter. The number of sites offering RSS feeds is growing rapidly and includes big names like Yahoo, BBC etc.

An RSS feed is in XML format and will generally contain a number of different elements. These are:-

<title> The title of the RSS element<link> A URL link to the full webpage for this item<description> A description of the item<pubDate> The publication date and time of the item<guid> The ID or item number

A typical RSS feed consists of a number of items, one of which is shown below:

<item> <title>Star City</title> <link>http://liftoff.msfc.nasa.gov/news/2003/news-starcity.asp</link>

<description>How do Americans get ready to work with Russians aboard the International Space Station? They take a crash course in culture, language and protocol at Russia's Star City.</description>

<pubDate>Tue, 03 Jun 2003 09:39:21 GMT</pubDate> <guid>http://liftoff.msfc.nasa.gov/2003/06/03.html#item573</guid> </item>

In order to display RSS information on our website we can use a list view with an XML data source attached to it as described below:

Open a new web form and call it exercise11.

Add a DataList to the web page and select a new data source and configure it as an Xml File. This will open up the following dialog box:

Dave Parkinson

Page 92: Net Development

.NET DEVELOPMENT Page 92

Set the Data file to point to the BBC weather feed: http://newsrss.bbc.co.uk/weather/forecast/9/Next3DaysRSS.xml

Set the XPath expression as follows:rss/channel/item[position()<=3]

The Data file defines the URL information for the particular RSS feed. The XPath defines the content. You can optionally add the item [position()<=3] to limit the number of items in the feed, in this case three.

Set the Auto Format option for the DataList to Classic

An Item Template should be added to the DataList as follows:

<asp:DataList ID="DataList1" runat="server" DataSourceID="XmlDataSource1" CellPadding="4" ForeColor="#333333"> <AlternatingItemStyle BackColor="White" /> <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <ItemStyle BackColor="#EFF3FB" /> <SelectedItemStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /> <ItemTemplate> <%#XPath("title")%><br/><br/> </ItemTemplate> </asp:DataList>

Note that the item template is set to return the title element only.Try adding the description element to the template to obtain more detailed weather information.

Add a second feed to your web page using the BBC sports feed and selecting football;

Set the Data file to point to the BBC weather feed: http://newsrss.bbc.co.uk/rss/sportonline_uk_edition/football/rss.xml

Dave Parkinson

Page 93: Net Development

.NET DEVELOPMENT Page 93

Set the XPath expression as follows:rss/channel/item[position()<=4]

Once again display the feed in a DataList. Add an item template to define the information you wish to show as shown below:

<ItemTemplate><b><a href="<%#XPath("link")%>"><%#XPath("title")%></a></b><br />

<%#XPath ("description")%><br /> <%#XPath("pubDate")%><br />

</ItemTemplate>

This Item template shows a URL link to the detailed web page providing the RSS link. It also shows a description of the item and the publication date and time.

The final web page is shown below:

10.2 Uploading and Displaying Pictures on your Web Site – Exercise 12

In order to display a picture on a web site we must upload the picture to a known location on the web server (in this case we will load it onto the base directory), and we must know the name of the file to display (this can be stored in a table within your Access database).

1. Add a new table called pictures to the Access database as shown below. Add fields ‘picture’, ‘title’ to your table. The fields datatypes should be set to ‘text’. Set the title field as the primary key.

Dave Parkinson

Page 94: Net Development

.NET DEVELOPMENT Page 94

2. Add a new Web Form and name it Exercise 12. The FileUpLoad control enables you to upload a file to the server. It displays a text box control and a browse button that allow users to select a file to upload to the server. The FileUpload control does not automatically save a file to the server after the user selects the file to upload. You must explicitly provide a control or mechanism to allow the user to submit the specified file. For example, you can provide a button that the user clicks to upload the file. The code that you write to save the specified file should call the SaveAs method, which saves the contents of a file to a specified path on the server

Add a FileUpLoad control, a label and a text box (to take the picture title to be uploaded to your database) to your web page and add a DataList control as shown below:

Modify the existing code on the button click as follows:

if (FileUpload1.HasFile) { String sPath = MapPath(FileUpload1.FileName); FileUpload1.PostedFile.SaveAs(sPath); Label2.Text = "Received " + FileUpload1.FileName + ", Content Type

" + FileUpload1.PostedFile.ContentType + ", Length " + FileUpload1.PostedFile.ContentLength;

string mysql;

Dave Parkinson

Page 95: Net Development

.NET DEVELOPMENT Page 95

mysql = "insert into pictures (picture,title) values ('" + FileUpload1.FileName + "','" + TextBox1.Text + "')";

AccessDataSource1.SelectCommand = mysql; DataList1.DataBind(); Response.Redirect("exercise12.aspx"); }else { Label2.Text = "Image was not uploaded"; }

The DataList should be configured to select the pictures table and should select all the fields in the table i.e. SELECT [picture], [title] FROM [pictures] ORDER BY [title]

As we did in the RSS feed exercise, you need to modify the Item Template in the DataList within the .aspx code (in source view). Change the existing template as follows:

<ItemTemplate> <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("picture") %>' /> <asp:Label ID="titleLabel" runat="server" Text='<%# Eval("title") %>' /> <br /> <br /> </ItemTemplate>

This code will upload the selected file into the root directory of the website and also add the name of the file and the title of the picture (from the TextBox) into the database. It will then display the contents of your pictures database table on your website.Test your website:

Dave Parkinson

Page 96: Net Development

.NET DEVELOPMENT Page 96

10.3 Calendar Control – Exercise 13

The Calendar control displays a month calendar from which users can select dates. You can make appointment-style calendars by adding content in the OnDayRender event. Two of the arguments for OnDayRender are the Day that is being rendered and its Cell object. Custom text can be added to the cell for a particular day by adding it as a LiteralControl to the Cell object's Controls collection, as shown in the following example.

1. Add a new web page, exercise13.aspx

2. Add a calender object to the web page. Select the calendar object on screen and then enable the Calender1_DayRender events handler item and the Calender1_SelectionChanged events handler item as shown below.

Add the code:

public partial class exercise13 : System.Web.UI.Page{

String[][] holidays; protected void Page_Load(object sender, EventArgs e) { holidays = new String[100][];

for (int n = 0; n < 100; n++) holidays[n] = new String[32];

holidays[1][1] = "New Year's Day"; holidays[2][14] = "Valentine's Day"; holidays[2][15] = "My Birthday"; holidays[11][5] = "Bonfire Night"; holidays[12][25] = "Christmas Day"; }

protected void Calendar1_SelectionChanged(object sender, EventArgs e) {

Label2.Text = "You selected " + Calendar1.SelectedDate.ToShortDateString();

}

protected void Calendar1_DayRender(object sender, DayRenderEventArgs e) { CalendarDay d = ((DayRenderEventArgs)e).Day; TableCell c = ((DayRenderEventArgs)e).Cell;

Dave Parkinson

Page 97: Net Development

.NET DEVELOPMENT Page 97

if (d.IsOtherMonth) { c.Controls.Clear(); } else { string Hol = holidays[d.Date.Month][d.Date.Day]; if (Hol != string.Empty) c.Controls.Add(new LiteralControl("<br>" + Hol)); }

}}

3. Test the calendar facility.

10.4 Retrieving Web Pages – Exercise 14

Although not a common requirement you may want to access other resources on the Internet, for example web pages. To do this Asp.Net provides a range of classes in the System.Net namespace. The code below shows how to fetch a web page (specified in the pageURL variable) from another site and load it into a string.

You need to add the following using statements to the top of your code:

using System.Net;using System.IO;

Then add the code:

string sourceString; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(pageURL);

Dave Parkinson

Page 98: Net Development

.NET DEVELOPMENT Page 98

HttpWebResponse result = (HttpWebResponse)req.GetResponse(); StreamReader reader = null; if (result.StatusCode == HttpStatusCode.OK) { reader = new StreamReader(result.GetResponseStream()); sourceString = reader.ReadToEnd(); } else { sourceString = "Failed request"; } reader.Close(); result.Close();

Create a new web page, exercise14.aspx and test the web page scraping facility.

10.5 Form to Email – Exercise 15

A popular facility on websites is the ability to present a form to the user and then sent the information gathered as an email. You can only run the following code if your website is resident on the Crystal Tech Server.

The form above has three text boxes:TextBox1 contains the recipient’s email address

Dave Parkinson

Page 99: Net Development

.NET DEVELOPMENT Page 99

TextBox2 contains the email message subjectTextBox3 contains the message itself

The email system uses the SmtpClient class. You need to add the following using statement to the top of your code:

using System.Net.Mail;

The following code should be attached to the Send Email button:

MailMessage message = new MailMessage("[email protected]",TextBox1.Text);message.Subject = TextBox2.Text;message.Body=TextBox3.Text;SmtpClient client=new SmtpClient("mail.csesalford.com");client.Send(message);

The code above will send an email to the address in TextBox1 from [email protected]

Crystal Tech do not allow mail to be send from an email address which is not part of the Crystal Tech site. I have generated a valid email address ([email protected]) which can be used for the ‘mail from’ address.

Note that this code will only work if your website is resident on the Crystal Tech Server.

Dave Parkinson

Page 100: Net Development

.NET DEVELOPMENT Page 100

Chapter 11 : ASP.NET and AJAX

11.1 Introduction

Ajax (asynchronous JavaScript and XML), or AJAX, is a group of interrelated web development techniques used for creating interactive web applications or rich Internet applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behaviour of the existing page. Data is retrieved using the XMLHttp object.

Advantages In many cases, the pages on a website consist of much content that is common

between them. Using traditional methods, that content would have to be reloaded on every request. However, using Ajax, a web application can request only the content that needs to be updated, thus drastically reducing bandwidth usage and load time.

The use of asynchronous requests allows the client's Web browser UI to be more interactive and to respond quickly to inputs, and sections of pages can also be reloaded individually. Users may perceive the application to be faster or more responsive, even if the application has not changed on the server side.

The use of Ajax can reduce connections to the server, since scripts and style sheets only have to be requested once.

Disadvantages Dynamically created pages do not register themselves with the browser's history

engine, so clicking the browser's "back" button would not return the user to an earlier state of the Ajax-enabled page, but would instead return them to the last page visited before it.

Dynamic web page updates also make it difficult for a user to bookmark a particular state of the application.

Because most web crawlers do not execute JavaScript code, web applications should provide an alternative means of accessing the content that would normally be retrieved with Ajax, to allow search engines to index it.

Any user whose browser does not support Ajax or JavaScript, or simply has JavaScript disabled, will not be able to use its functionality. Similarly, devices such as mobile phones, PDAs, and screen readers may not have support for JavaScript or the XMLHttpRequest object. Also, screen readers that are able to use Ajax may still not be able to properly read the dynamically generated content.

11.2 ASP.NET AJAX

ASP.NET AJAX consists of client-script libraries and of server components that are integrated to provide a robust development framework. In addition to ASP.NET AJAX, you can use the ASP.NET AJAX Control Toolkit and the features in the ASP.NET AJAX Futures releases, which are both community supported.

ASP.NET AJAX server controls consist of server and client code that integrate to produce AJAX-like behaviour. The following list describes the most frequently used

Dave Parkinson

Page 101: Net Development

.NET DEVELOPMENT Page 101

ASP.NET AJAX server controls. These server controls are included in Visual Studio 2010 under the AJAX Extensions Tab.

ScriptManagerManages script resources for client components, partial-page rendering, localization, globalization, and custom user scripts. The ScriptManager control is required in order to use the UpdatePanel, UpdateProgress, and Timer controls.

UpdatePanelEnables you to refresh selected parts of the page, instead of refreshing the whole page by using a synchronous postback.

UpdateProgressProvides status information about partial-page updates in UpdatePanel controls.

TimerPerforms postbacks at defined intervals. You can use the Timer control to post the whole page, or use it together with the UpdatePanel control to perform partial-page updates at a defined interval.

ASP.NET AJAX   client-script libraries consist of JavaScript (.js) files that provide features for object-oriented development. Client side controls are provided by the ASP.NET AJAX Control Toolkit, which is a collection of samples and components that show you some of the experiences you can create with rich client ASP.NET AJAX controls and extenders. The Control Toolkit provides samples and a powerful SDK to make it simple to create and reuse custom controls and extenders.

11.2.1 Using AJAX Server Controls – Exercise 16

In order to use the AJAX facilities you have to add a Script Manager Server to your page. We also need to add a Update Panel to the page to act as a container for our AJAX enabled controls.

Create a new web page and name it exercise16.aspx

From under the AJAX Extensions within the Toolbox, add a Script Manager to your new page. Add an Update Panel to the page and within it add labels, a textbox and a button to recreate a similar exercise to exercise 1.

Add code to report the information typed in the text box to a label as shown below.

Dave Parkinson

Page 102: Net Development

.NET DEVELOPMENT Page 102

Only the area within the Update Panel gets actioned when the button is pressed. The rest of the page is not refreshed. We can prove this by adding a label below the update panel and add code on the page load to show the current date and time. In addition we can also display the date on time within the update panel as shown below.

The date and time should only update within the Update Panel when the button is clicked.

11.2.2 ASP.NET AJAX Control Toolkit– Exercise 17

Since the ASP.NET Control Toolkit is not part of the default install for Visual Studio 2010 you have to set up the controls yourself.

The Ajax Control Toolkit contains a rich set of controls that you can use to build highly responsive and interactive Ajax-enabled ASP.NET Web Forms applications. Follow the steps below to download and start using the Ajax Control Toolkit with Visual Studio.

You can download the latest version of the Ajax Control Toolkit from http://ajaxcontroltoolkit.codeplex.com/

Click the Downloads tab at the CodePlex site to see the list of available Ajax Control Toolkit downloads. You should choose the binary version of the Ajax Control Toolkit for .NET 4.

Download the Binary version and not the Source version of the Ajax Control Toolkit. You should download the Source version of the Ajax Control Toolkit only when you are interested in extending the Ajax Control Toolkit.

Click on Downloads and select the option AjaxControlToolkit.Binary.NET4.zip Run the .zip file and extract the toolkit to a directory of your choice.

Dave Parkinson

Page 103: Net Development

.NET DEVELOPMENT Page 103

The next step is to add the Ajax Control Toolkit to the Visual Studio Toolbox. Follow these steps:

1. Launch Visual Studio and open your ASP.NET website.

2. Create a new Toolbox tab by right-clicking the Toolbox and selecting Add Tab. Name the new tab Ajax Control Toolkit.

3. Right-click beneath the new tab and select the menu option Choose Items... Click the Browse button and browse to the folder where you extracted the Ajax Control Toolkit. Pick the AjaxControlToolkit.dll and click the OK button to close the Choose Toolbox Items dialog.

The Control Toolkit Items dialog changes to include the controls contained in this DLL as shown below. Click OK and the new controls will be added to your Visual Studio Toolbox.

You will find that in excess of 40 new controls and extenders have been added.

The majority of the new controls are extenders. Extenders are controls that add to the capability of existing ASP.NET Controls by adding additional JavaScript on the client as well as some server side communications (e.g. Animation Extender, Calendar Extender etc ). There are also some controls that are AJAX controls in their own right (e.g. Accordion Control, Password Strength Control etc.).

Dave Parkinson

Page 104: Net Development

.NET DEVELOPMENT Page 104

Note that as the AJAX Control Toolkit is a Community project is being added to on a frequent basis. You should revisit the CodePlex site regularly to take advantage of any new offerings.

Visit the tutorials page to learn how to use the Ajax Control Toolkit controls.

http://www.asp.net/ajaxlibrary/act_tutorials.ashx

To get a full listing of each control go the following website:

http://asp.net/AJAX/AjaxControlToolkit/Samples/

This web site provides full details of each control, with documentation, examples and videos showing how the control may be used.

Add a new page, exercise 17 to your web site and experiment with these AJAX controls. Don’t forget to first add a Script Manager and if required, ensure controls are be placed within a Update Panel if you want to prevent the entire page refreshing.

Dave Parkinson