1. Web Based Software
Development
Prepared by : Dave Parkinson
www.webdesigninfo.co.uk
(September 2011)
2. WEB BASED SOFTWARE DEVELOPMENT Page 2
Web Based Software Development
This full module runs for 2 weeks ~ 3 hours lecture / practical per week.
UNIVERSITY OF SALFORD FORM MS
MODULE SPECIFICATION
Module Title: CRN: University module
Web-Based Software Development 25365 code:
G430 M0055
Level: Credit ECTS Length (in Semester(s) in
M Value: Value: Semesters): which to be
30 15 2 offered:
1&2
Existing/new Title of Module being replaced (if any): With effect from:
module: Academic year
Existing 2007-2008
Originating School: Module Co-ordinator(s):
School of Computing, Lee Griffiths
Science and Engineering
Programme(s) in which to be offered:
MSc Databases and Web-Based Systems (MST/DW/F)
MSc Learning Technologies (MST/LN/F)
Pre-requisites (between levels): Co-requisites (within a level):
Indicative learning Percentage taught by School(s) other than originating
hours: School:
300 (contact hours: 72)
Aims of Module:
This module aims to build on previous knowledge of software development to provide a
systematic understanding of up-to-date issues, techniques and technologies for developing
robust, usable and scalable web-accessible data-driven applications that conform to
interoperable standards. Both the hardware and software aspects of network-based service
delivery on an enterprise scale will be covered.
Intended Learning Outcomes:
Upon successful completion of the module, students will be able to:
Knowledge and Understanding
show an in-depth understanding of web-based presentation technologies and
techniques, including practical experience of dialogue design techniques, usability
and accessibility engineering and prototyping;
Dave Parkinson
3. WEB BASED SOFTWARE DEVELOPMENT Page 3
demonstrate an in-depth understanding of enterprise infrastructures, including a
practical understanding of currently used client-side and server-side languages and
proprietary server technologies; and
discuss current research in the area.
On completion, students will have the following professional or transferable skills:
Professional Skills
Design, develop and test an enterprise level Internet-based system
Transferable/Key Skills and other attributes
Take part in discussions and make presentations.
Application of Number, Collect and record data and Present findings
Module mark calculation: Method A
Assessment components (in chronological order of submission/examination date)
Duration Word count (if Component
Type of assessment Weighting% (if exam) essay/dissertation): pass required
Coursework 100
Learning and teaching strategies:
There will be 48 hours of lectures; 24 hours of tutorials; and 228 hours of independent
study and assessed coursework. This makes a total of 300 hours total learning experience.
In order to provide a practical demonstration of their learning, students will use an
appropriate development platform to:
1. design, build and test an advanced data-driven Web-Based solution; and
2. design and implement multimedia interaction.
In the module assessment, students will apply the software development lifecycle to an
ongoing project. At regular stages throughout the project, students will have an opportunity
to review and reflect on progress. Marks for the work will be derived from: the software
deliverable; the application of appropriate theories, technologies and good practice; and
documentation reflecting on the work done and the processes involved.
Syllabus outline:
Interface Design and analysis methodologies
Usability Engineering and System prototyping
Client/Server scripting and presentation languages
Dave Parkinson
4. WEB BASED SOFTWARE DEVELOPMENT Page 4
Software architectures
Server technology (IIS, Apache, Microsoft SQL Server, MySql, Streaming media)
Development platform (Microsoft ASP.NET)
Developing for mobile platforms
Transaction and error logging
Internet security
Web Services including SOAP, XML and WSDL
AJAX
Web Application Performance
Macromedia Flash and ActionScript
Current Research
Indicative texts and/or other learning materials/resources:
Deitel, H.M. and Deitel, P.J. "Visual C#: How to Program" 2nd edition; Prentice Hall
2005; ISBN 0131525239
Lee, W.M. "ASP.NET 2.0 A Developer's Notebook" O'Reilly 2005; ISBN 0596008120
Kerman, P. "Teach Yourself Macromedia Flash 8 in 24 Hours" 3rd edition; SAMS 2005;
ISBN 0672327546
Lott, J. et al "ActionScript 3.0 Cookbook" O'Reilly 2006; ISBN 0596526954
Nielsen, J. and Loranger, H. "Prioritizing Web Usability" New Riders 2006; ISBN
0321350316
Preece, J. et al "Interaction Design: Beyond Human Computer Interaction" 2nd edition;
Wiley 2007; ISBN 0470018666
Preece, J. et al "Human-Computer Interaction" Addison-Wesley 1994; ISBN
0201627698
www.w3.org
The following journal is relevant to research in this field:
"Behaviour and Information Technology" Taylor and Francis; ISSN 0144-929X
Lecture notes and related materials can be found at vle.salford.ac.uk
Date of completion of this version of Module Specification: Wed 4 Jul 2007
Dave Parkinson‟s Book Recommendations:
“Build Your Own Website The Right Way Using HTML & CSS"
Ian J. Lloyd; £13.85; ISBN 0-9752402-9-3
“Professional ASP.NET 3.5 in C# and VB"
Evjen, B., Hanselman, S. and Rader; £18.84; SBN 0470187573
Dave Parkinson
5. WEB BASED SOFTWARE DEVELOPMENT Page 5
WEB BASED SOFTWARE DEVELOPMENT CONTENTS
Chapter 1 : Introduction to the Visual Studio 2010 and the .NET Framework ..................... 8
1.1 Introduction to the Client Server Model....................................................................................... 8
1.2 Server-Side Scripts verses Client-Side Scripts ............................................................................. 9
1.3 External Web Pages with CrystalTech ....................................................................................... 10
1.2 Introduction to .NET .................................................................................................................... 10
Chapter 2 : Visual Studio 2010 & C# ..................................................................................... 13
2.1 Introduction ................................................................................................................................... 13
2.2 What is C#? ................................................................................................................................... 13
2.3 A Quick Overview of C# Syntax .................................................................................................. 14
2.3.1 Variables and Operators ........................................................................................................................... 14
2.3.2 Decision Making and Flow Control ......................................................................................................... 15
2.3.3 Member Functions .................................................................................................................................... 16
2.3.4 Classes and Objects .................................................................................................................................. 16
2.3.5 Event Handling ......................................................................................................................................... 17
2.4 Using Visual Studio ....................................................................................................................... 18
2.4.1 Exercise 1 - Starting a Project (A Windows Application) ....................................................................... 18
2.4.2 Exception Handling .................................................................................................................................. 22
2.4.3 Exercise 2 – Creating a Windows Calculator ........................................................................................... 23
Chapter 3 : Designing Web Sites with Visual Studio 2010 ................................................... 24
3.1 Introduction ................................................................................................................................... 24
3.2 Testing your Web Application ..................................................................................................... 24
3.3 HTML and CSS............................................................................................................................. 24
3.3.1 Applying Cascading Style Sheets to an HTML document ....................................................................... 25
3.3.2 CSS Rules ................................................................................................................................................. 25
3.3.3 Element Layout and Positioning ............................................................................................................... 27
3.3.4 Working with CSS in Visual Studio ......................................................................................................... 28
3.4 Web Site Layout ............................................................................................................................ 30
3.4.1 Working with Master Pages ..................................................................................................................... 31
3.4.2 Exercise 3 – Creating a Web Site using Visual Studio 2010 .................................................................... 32
Chapter 4 : Web Applications and ASP.NET ........................................................................ 40
4.1 Introduction ................................................................................................................................... 40
4.2 Features in ASP.NET.................................................................................................................... 41
4.2.1 ASP.NET Controls ................................................................................................................................... 42
4.2.2 Web services integration .......................................................................................................................... 43
4.2.3 Handling Post Back .................................................................................................................................. 43
4.2.4 Moving Between Pages ............................................................................................................................ 44
4.4 Useful ASP.NET Tutorial Web Sites .......................................................................................... 44
Chapter 5 : Using Visual Studio & ASP.NET ....................................................................... 45
5.1 Introduction ................................................................................................................................... 45
5.1.1 Structure of a Web Form Page ................................................................................................................. 45
5.1.2 Adding Server Controls ........................................................................................................................... 45
5.1.3 Handling Events ....................................................................................................................................... 45
5.2 Web Page Exercise 1 – Creating an ASP.NET Web Calculator ............................................... 47
Dave Parkinson
6. WEB BASED SOFTWARE DEVELOPMENT Page 6
5.3 Web Page Exercise 2 – Creating an ASP.NET Web Lottery Number Generator .................. 50
Chapter 6 : Validation Web Form Pages ............................................................................... 51
6.1 Introduction ................................................................................................................................... 51
6.1.1 Overview of the Validation Controls ........................................................................................................ 51
6.1.2 Post Backs and Form Validation .............................................................................................................. 52
6.1.3 JavaScript and the Validation Controls .................................................................................................... 52
6.2 Using Validation Controls ............................................................................................................ 53
6.2.1 Checking for Required Fields ................................................................................................................... 53
6.2.2 Validating a Range of Expressions ........................................................................................................... 53
6.2.3 Web Page Exercise 3 - Using a RequiredFieldValidator Control ............................................................. 54
6.2.4 Comparing Values .................................................................................................................................... 55
6.2.5 Performing Data Type Checks ................................................................................................................. 55
6.2.6 Regular Expression Validation ................................................................................................................. 56
6.2.7 Displaying a Summary of Validation Errors ............................................................................................ 56
6.2.8 Web Page Exercise 4 – Validating a Web Form ...................................................................................... 57
Chapter 7 : Maintaining State on your Web Site................................................................... 58
7.1 Introduction ................................................................................................................................... 58
7.2 Using View State ........................................................................................................................... 58
7.2.1 Disabling View State ................................................................................................................................ 59
7.2.2 Adding Custom Information to View State .............................................................................................. 59
7.2.3 Protecting View State ............................................................................................................................... 60
7.3 Using Cookies ................................................................................................................................ 60
7.3.1 Reading Cookies ....................................................................................................................................... 61
7.3.2 Writing Cookies ....................................................................................................................................... 61
7.4 Using Session State ........................................................................................................................ 62
7.5 Using Application State ................................................................................................................ 63
7.6 Web Page Exercise 5 – Using Cookies and Session Variables .................................................. 63
Chapter 8 : Databases ............................................................................................................. 65
8.1 Introduction ................................................................................................................................... 65
8.2 Review of Databases and SQL ..................................................................................................... 66
8.2.1 Relational Databases ................................................................................................................................ 66
8.2.2 Structured Query Language ...................................................................................................................... 67
8.3 Web Page Exercise 6 - Reading Data from a Microsoft SQL Server Database ...................... 70
8.4 Using Datasets to connect to a Database ..................................................................................... 74
8.4.1 Exercise 7 - Connecting to a Database using Typed Data Sets ................................................................ 75
8.4.2 Using Stored Parameters within Sequel Server ........................................................................................ 81
8.4.3 Using Visual Studio and Stored Parameters in Sequel Server .................................................................. 83
8.5 Other Data-Bound Controls......................................................................................................... 85
8.5.1 Exercise 8 – Using List View and other Data-Bound Controls ................................................................ 86
8.6 Searching through a Database Table using Typed Data Sets ................................................... 86
8.6.1 Web Page Exercise 9 – Searching through a Database Table................................................................... 86
Chapter 9 – Configuring your Web Application .................................................................... 92
9.1 Introduction ................................................................................................................................... 92
9.2 Web Forms Authentication .......................................................................................................... 93
9.2.1 Web Exercise 10 – Password Protecting an area of your Web Site .......................................................... 95
9.2.2 Storing Usernames and Passwords in the Web.Config File ..................................................................... 99
9.2.3 Storing Usernames and Passwords in a Database ................................................................................... 100
Dave Parkinson
7. WEB BASED SOFTWARE DEVELOPMENT Page 7
Chapter 10 : Other Useful ASP.NET Features ................................................................... 101
10.1 RSS Feeds – Exercise 11 ........................................................................................................... 101
13.2 Uploading and Displaying Pictures on your Web Site – Exercise 12 ................................... 103
10.3 Calendar Control – Exercise 13 ............................................................................................... 106
10.4 Retrieving Web Pages – Exercise 14 ....................................................................................... 107
10.5 Form to Email – Exercise 15 .................................................................................................... 108
Chapter 11 : Deploying your WebSite on the CrystalTech Web Server.............................. 110
11.1 Introduction ............................................................................................................................... 110
Chapter 12 : ASP.NET 3.5 and AJAX ................................................................................. 111
12.1 Introduction ............................................................................................................................... 111
12.2 ASP.NET AJAX ........................................................................................................................ 111
12.2.1 Using AJAX Server Controls – Exercise 16 ......................................................................................... 112
12.2.2 ASP.NET AJAX Control Toolkit– Exercise 17 ................................................................................... 113
Chapter 13 : Web Services .................................................................................................... 116
13.1 Introduction ............................................................................................................................... 116
13.2 A Brief History of Developing Distributed Applications ....................................................... 117
13.3 Investigating Web Services ...................................................................................................... 118
13.4 Money Calculator - Exercise 16 ............................................................................................... 119
Dave Parkinson
8. WEB BASED SOFTWARE DEVELOPMENT Page 8
Chapter 1 : Introduction to the Visual Studio 2010 and the .NET Framework
1.1 Introduction to the Client Server Model
The internet runs on a client server model. In a client server model, two computers work
together to perform a task. A client computer requests some needed information from a
server computer. The server returns this information, and the client acts on it. With the
internet the server is a particular web server.
The client on the internet, is a web browser. When you visit a static web page through a
web browser, the following steps occur :-
The client requests a web
page from the server
Client Server
The server returns the
web page from the client
1. The client (the web browser) locates the web server specified by the first part of
the URL (e.g. www.webdesigninfo.co.uk).
2. The client then requests the static web page specified by the second part of the
URL (e.g. /index.htm).
3. The web server sends the contents of that particular file to the client in HTML
format.
4. The client receives the HTML sent by the server and renders it for you, the user.
In this transaction, the web server acts passively (i.e. it only sends the data requested back
to the client, no data processing takes place). To allow for dynamic web pages the web
server must take a more active role.
Active Server Pages are Microsoft‟s solution to creating server side based dynamic web
pages. The latest version of Active Server Pages from Microsoft is ASP.NET which
provides an event driven environment for creating interactive web pages.
UNIX and LINUX servers support PHP as their scripting language for creating interactive
web sites.
Dave Parkinson
9. WEB BASED SOFTWARE DEVELOPMENT Page 9
When a web browser requests a dynamic web page (e.g. an ASP page, or a PHP page, the
following steps occur :-
Client requests ASP file Server locates the
ASP file on the
hard disc and
Client Server processes it,
removing all ASP
script and replacing
it with HTML text
Server returns HTML
text to client
1. The client (the web browser) locates the web server specified by the first part of
the URL (e.g. www.webdesigninfo.co.uk).
2. The client then requests the ASP web page specified by the second part of the URL
(e.g. /index.asp).
3. The web server reads the ASP file and processes the code.
4. After the ASP page has been completely processed by the web server, the output is
sent in HTML format to the client.
5. The client receives the HTML sent by the server and renders it for you, the user.
The client cannot tell the difference between a dynamic web page and a static web page
because, in both cases, it receives just HTML. When the web server processes an ASP
page, or a PHP page, all the programmatic code is interpreted on the server, none of it is
sent to the client.
1.2 Server-Side Scripts verses Client-Side Scripts
When using server side programming it is vitally important to understand that server side
programming code exists on the server only. Server side programming code is processed
completely on the server. The client cannot access this server side programming code.
Another form of creating interactivity on your web site is to use client side scripting
(client-side scripting is programmatic code that runs in your browser).
Client-side scripting code is simply HTML code and is denoted by the <SCRIPT> HTML
tag. Client-side scripting is usually written using the JavaScript programming language, as
this is supported by all the major browsers.
You can have client-side scripting code in a dynamic page because client-side scripting is
part of the HTML code as far as the web server is concerned. When developing dynamic
Dave Parkinson
10. WEB BASED SOFTWARE DEVELOPMENT Page 10
web pages, however, it is important to remember that client-side scripting and server side
programming code are two different things and cannot interact with each other.
1.3 External Web Pages with CrystalTech
As part of the course you will be given your own personal web space on the Crystal Tech
Server (www.crystaltech.com) . Note you can only run ASP or PHP code on a web server.
The website will be accessed via the following:
www.csesalford.com/yoursurname
(e.g. www.csesalford.com/parkinson)
Once you have created your web site you will need to upload the files created on your
local computer to your web server using the FTP connection tools within Microsoft Visual
Studio.
1.2 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
Dave Parkinson
11. WEB BASED SOFTWARE DEVELOPMENT Page 11
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:-
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
Dave Parkinson
12. WEB BASED SOFTWARE DEVELOPMENT Page 12
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 3.5 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
13. WEB BASED SOFTWARE DEVELOPMENT Page 13
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
14. WEB BASED SOFTWARE DEVELOPMENT Page 14
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 variables
char 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
15. WEB BASED SOFTWARE DEVELOPMENT Page 15
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;
else
y=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
16. WEB BASED SOFTWARE DEVELOPMENT Page 16
{
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
17. WEB BASED SOFTWARE DEVELOPMENT Page 17
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
18. WEB BASED SOFTWARE DEVELOPMENT Page 18
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 2008.
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
19. WEB BASED SOFTWARE DEVELOPMENT Page 19
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 its 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
20. WEB BASED SOFTWARE DEVELOPMENT Page 20
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
21. WEB BASED SOFTWARE DEVELOPMENT Page 21
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
22. WEB BASED SOFTWARE DEVELOPMENT Page 22
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);
}
}
Dave Parkinson
23. WEB BASED SOFTWARE DEVELOPMENT Page 23
Change your program as shown above using try and catch to add error recovery to your
conversion application.
2.4.3 Exercise 2 – Creating a Windows Calculator
Create a new C# Windows Application project called Calculator. On the windows form
add label boxes, text boxes, buttons and radio buttons as shown below to design your
calculator.
Radio buttons are used to force the user to make a single selection from a range of options.
Radio buttons are placed in a group and only one radio button from that group may be
selected.
To use radio buttons in your program follow the steps below:
1. Place a group box on the main dialog window. Select its properties and make the
group box visible then change or delete the caption as required.
2. Place one or more radio buttons within the group box. Change the text values to + , - ,
* , / . Set the checked property to be true on the first radio button only.
3. Within your code test the value of each radio buttons checked property.
The finished calculator should look like :-
Add try and catch statements to your code to make it error resilient.
Dave Parkinson
24. WEB BASED SOFTWARE DEVELOPMENT Page 24
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
25. WEB BASED SOFTWARE DEVELOPMENT Page 25
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 document
3. 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 Selectors
The universal selector indicates that the style should apply to any element in the web page.
*
{
font-family: Arial;
}
Dave Parkinson
26. WEB BASED SOFTWARE DEVELOPMENT Page 26
This selector would change the font of any element that supports the font property to
Arial.
Type Selectors
The 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 Selectors
Class 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 Selectors
ID 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
27. WEB BASED SOFTWARE DEVELOPMENT Page 27
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 Positioning
Using 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
28. WEB BASED SOFTWARE DEVELOPMENT Page 28
Relative Positioning
Using 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 Positioning
Absolute 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 Positioning
An 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
29. WEB BASED SOFTWARE DEVELOPMENT Page 29
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
30. WEB BASED SOFTWARE DEVELOPMENT Page 30
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:
branding
navigation
sidebar content
footer
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
31. WEB BASED SOFTWARE DEVELOPMENT Page 31
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
32. WEB BASED SOFTWARE DEVELOPMENT Page 32
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
33. WEB BASED SOFTWARE DEVELOPMENT Page 33
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
34. WEB BASED SOFTWARE DEVELOPMENT Page 34
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
35. WEB BASED SOFTWARE DEVELOPMENT Page 35
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
36. WEB BASED SOFTWARE DEVELOPMENT Page 36
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>
The master page references all the style sheets (.css files) used in the construction of the
page.
Dave Parkinson
37. WEB BASED SOFTWARE DEVELOPMENT Page 37
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
38. WEB BASED SOFTWARE DEVELOPMENT Page 38
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">
<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'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.
Choose Web Form from the Add New Item dialog as shown below
Dave Parkinson
39. WEB BASED SOFTWARE DEVELOPMENT Page 39
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
40. WEB BASED SOFTWARE DEVELOPMENT Page 40
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
41. WEB BASED SOFTWARE DEVELOPMENT Page 41
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.
Dave Parkinson
42. WEB BASED SOFTWARE DEVELOPMENT Page 42
4.2.1 ASP.NET Controls
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
43. WEB BASED SOFTWARE DEVELOPMENT Page 43
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
44. WEB BASED SOFTWARE DEVELOPMENT Page 44
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 Tutorials
http://www.asp.net/learn/
Dave Parkinson
45. WEB BASED SOFTWARE DEVELOPMENT Page 45
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
46. WEB BASED SOFTWARE DEVELOPMENT Page 46
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 Events
If 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 Events
A 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 Property
Code 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
47. WEB BASED SOFTWARE DEVELOPMENT Page 47
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if(!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
48. WEB BASED SOFTWARE DEVELOPMENT Page 48
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
49. WEB BASED SOFTWARE DEVELOPMENT Page 49
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
50. WEB BASED SOFTWARE DEVELOPMENT Page 50
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
51. WEB BASED SOFTWARE DEVELOPMENT Page 51
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
Dave Parkinson