Your SlideShare is downloading. ×

Web based Software Development

9,832
views

Published on

ASP.NET 4 Development using Microsoft SQL Databases

ASP.NET 4 Development using Microsoft SQL Databases

Published in: Education, Technology, Business

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
9,832
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
126
Comments
0
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 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 DevelopmentThis 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 languagesDave 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 Developers Notebook" OReilly 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" OReilly 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 2007Dave 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 0470187573Dave Parkinson
  • 5. WEB BASED SOFTWARE DEVELOPMENT Page 5WEB BASED SOFTWARE DEVELOPMENT CONTENTSChapter 1 : Introduction to the Visual Studio 2010 and the .NET Framework ..................... 81.1 Introduction to the Client Server Model....................................................................................... 81.2 Server-Side Scripts verses Client-Side Scripts ............................................................................. 91.3 External Web Pages with CrystalTech ....................................................................................... 101.2 Introduction to .NET .................................................................................................................... 10Chapter 2 : Visual Studio 2010 & C# ..................................................................................... 132.1 Introduction ................................................................................................................................... 132.2 What is C#? ................................................................................................................................... 132.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 ......................................................................................................................................... 172.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 ........................................................................................... 23Chapter 3 : Designing Web Sites with Visual Studio 2010 ................................................... 243.1 Introduction ................................................................................................................................... 243.2 Testing your Web Application ..................................................................................................... 243.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 ......................................................................................................... 283.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 .................................................................... 32Chapter 4 : Web Applications and ASP.NET ........................................................................ 404.1 Introduction ................................................................................................................................... 404.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 ............................................................................................................................ 444.4 Useful ASP.NET Tutorial Web Sites .......................................................................................... 44Chapter 5 : Using Visual Studio & ASP.NET ....................................................................... 455.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 ....................................................................................................................................... 455.2 Web Page Exercise 1 – Creating an ASP.NET Web Calculator ............................................... 47Dave Parkinson
  • 6. WEB BASED SOFTWARE DEVELOPMENT Page 65.3 Web Page Exercise 2 – Creating an ASP.NET Web Lottery Number Generator .................. 50Chapter 6 : Validation Web Form Pages ............................................................................... 516.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 .................................................................................................... 526.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 ...................................................................................... 57Chapter 7 : Maintaining State on your Web Site................................................................... 587.1 Introduction ................................................................................................................................... 587.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 ............................................................................................................................... 607.3 Using Cookies ................................................................................................................................ 60 7.3.1 Reading Cookies ....................................................................................................................................... 61 7.3.2 Writing Cookies ....................................................................................................................................... 617.4 Using Session State ........................................................................................................................ 627.5 Using Application State ................................................................................................................ 637.6 Web Page Exercise 5 – Using Cookies and Session Variables .................................................. 63Chapter 8 : Databases ............................................................................................................. 658.1 Introduction ................................................................................................................................... 658.2 Review of Databases and SQL ..................................................................................................... 66 8.2.1 Relational Databases ................................................................................................................................ 66 8.2.2 Structured Query Language ...................................................................................................................... 678.3 Web Page Exercise 6 - Reading Data from a Microsoft SQL Server Database ...................... 708.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 .................................................................. 838.5 Other Data-Bound Controls......................................................................................................... 85 8.5.1 Exercise 8 – Using List View and other Data-Bound Controls ................................................................ 868.6 Searching through a Database Table using Typed Data Sets ................................................... 86 8.6.1 Web Page Exercise 9 – Searching through a Database Table................................................................... 86Chapter 9 – Configuring your Web Application .................................................................... 929.1 Introduction ................................................................................................................................... 929.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 ................................................................................... 100Dave Parkinson
  • 7. WEB BASED SOFTWARE DEVELOPMENT Page 7Chapter 10 : Other Useful ASP.NET Features ................................................................... 10110.1 RSS Feeds – Exercise 11 ........................................................................................................... 10113.2 Uploading and Displaying Pictures on your Web Site – Exercise 12 ................................... 10310.3 Calendar Control – Exercise 13 ............................................................................................... 10610.4 Retrieving Web Pages – Exercise 14 ....................................................................................... 10710.5 Form to Email – Exercise 15 .................................................................................................... 108Chapter 11 : Deploying your WebSite on the CrystalTech Web Server.............................. 11011.1 Introduction ............................................................................................................................... 110Chapter 12 : ASP.NET 3.5 and AJAX ................................................................................. 11112.1 Introduction ............................................................................................................................... 11112.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 ................................................................................... 113Chapter 13 : Web Services .................................................................................................... 11613.1 Introduction ............................................................................................................................... 11613.2 A Brief History of Developing Distributed Applications ....................................................... 11713.3 Investigating Web Services ...................................................................................................... 11813.4 Money Calculator - Exercise 16 ............................................................................................... 119Dave Parkinson
  • 8. WEB BASED SOFTWARE DEVELOPMENT Page 8 Chapter 1 : Introduction to the Visual Studio 2010 and the .NET Framework1.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 dynamicDave 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 inDave 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 WindowsDave 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 20103.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 server3.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 theDave 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 273.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 elements 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 elements 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 pagesDave 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 sites 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 differentDave 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 Parkinsons 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 Parkinsons 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 Parkinsons Picture" src="images/dave_parkinson.jpg"/></p><p>This site is designed using the <a href="http://www.960.gs">960gs CSSframework</a>.</p><p><a href="http://www.rickogden.com/tutorials/960gs/">Click here for atutorial.</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;spages. To add additional pages just edit the MasterPage.master file to add the extralinks 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 belowDave 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.NET4.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. Its 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 werent 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 thats scalable across Web farms. It also provides reliability that can even survive server crashes, and it can work with browsers that dont 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 theyre 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 andDave 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 youve got to make sure youve 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 its code or content. Then it must compile and run the line if its code, or output the line to the clients browser if its 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 thats not easily structured and is difficult to reuse. In contrast, with ASP.NET, developers produce program code thats 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 doesnt have to look at all the developers code while laying out the page. The developer wont 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 arent a part of standard ASP or other traditional Web development environments.Dave Parkinson
  • 42. WEB BASED SOFTWARE DEVELOPMENT Page 424.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 users 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 controls 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 users 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 sites 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 isnt 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 forms 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 theyre 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 444.2.4 Moving Between Pages So how do you help your visitors navigate to other pages on your site if youre 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 theres 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 wont have that handy __VIEWSTATE hidden form element doing the work for us. Its 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.NET5.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 controls default event. If you need to add an event handler for something other than a controls default event, youll 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.aspxDave Parkinson
  • 50. WEB BASED SOFTWARE DEVELOPMENT Page 505.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 Pages6.1 Introduction If you want to collect information from the users of your application, youll most likely need to implement some type of form validation. For example, youll 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 dont want a user to be able to submit the form without entering a value for the TextBox control. In that case, you would add aDave Parkinson
  • 52. WEB BASED SOFTWARE DEVELOPMENT Page 52 RequiredFieldValidator control to the page and assign the value txtPassword to the RequiredFieldValidator controls controlToValidate property. 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 cant 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 onDave Parkinson
  • 53. WEB BASED SOFTWARE DEVELOPMENT Page 53 the server after the form is submitted to the Web server. Validation error messages wont 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, youll 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 display6.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)Dave Parkinson
  • 54. WEB BASED SOFTWARE DEVELOPMENT Page 54 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. If you dont 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 Value Text 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.Dave Parkinson
  • 55. WEB BASED SOFTWARE DEVELOPMENT Page 556.2.4 Comparing Values 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 dont 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 controls 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.Dave Parkinson
  • 56. WEB BASED SOFTWARE DEVELOPMENT Page 566.2.6 Regular Expression Validation 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 dont 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 controls 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, youll 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.Dave Parkinson
  • 57. WEB BASED SOFTWARE DEVELOPMENT Page 576.2.8 Web Page Exercise 4 – Validating a Web Form 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 Surname Address Postcode Phone Email Age (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
  • 58. WEB BASED SOFTWARE DEVELOPMENT Page 58 Chapter 7 : Maintaining State on your Web Site7.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 users7.2 Using View State View State enables you to preserve the state of a page when posting the page back to itself. Its 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 theDave Parkinson
  • 59. WEB BASED SOFTWARE DEVELOPMENT Page 59 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 dont always need to take advantage of View State. If you dont need to preserve the state of controls across post backs, you dont 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
  • 60. WEB BASED SOFTWARE DEVELOPMENT Page 607.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 dont need it, dont 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 dont 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
  • 61. WEB BASED SOFTWARE DEVELOPMENT Page 61 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 users 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
  • 62. WEB BASED SOFTWARE DEVELOPMENT Page 62 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 Servers 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
  • 63. WEB BASED SOFTWARE DEVELOPMENT Page 63 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 Servers 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
  • 64. WEB BASED SOFTWARE DEVELOPMENT Page 64 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
  • 65. WEB BASED SOFTWARE DEVELOPMENT Page 65 Chapter 8 : Databases8.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 Controls Data 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 Controls Data-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
  • 66. WEB BASED SOFTWARE DEVELOPMENT Page 668.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 databases8.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
  • 67. WEB BASED SOFTWARE DEVELOPMENT Page 678.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 its essential that you learn the basics of SQL. The SELECT Statement The 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 shouldnt 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. * A string of zero or more charactersDave Parkinson
  • 68. WEB BASED SOFTWARE DEVELOPMENT Page 68 _ 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, theres no way to know in what order the database will return records. Even though they may have been entered alphabetically during data entry, that doesnt 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 Statement Another 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] VALUES (DEFAULT | NULL | expression)Dave Parkinson
  • 69. WEB BASED SOFTWARE DEVELOPMENT Page 69 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 youll get another error. The UPDATE Statement The 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 its easy to ruin your data! An example of the use of the UPDATE statement is :- UPDATE addresses SET 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 Statement The 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 dont 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 = ChrisDave Parkinson
  • 70. WEB BASED SOFTWARE DEVELOPMENT Page 708.3 Web Page Exercise 6 - Reading Data from a Microsoft SQL Server Database 1. A sequel server database has been set up on the Crystal Tech server specifically for the use of this module. To connect to a database using Visual Studio first open Server Explorer. Select connect to database and you will open a dialog box as shown below (the Data Source box should be set to Microsoft SQL Server): To connect to the CrystalTech SQL Server database fill in the dialog box as shown above with the following information. Server Name: SQLB32.webcontrolcenter.com User name: wbsd Password: “as provided by Dave Parkinson” Database name: cse Once connected to an SQL Server database you can add a new table by right clicking on the database and selecting create table. You can edit the table data by selecting the table and right clicking to select show table data. When you create tables in this database you must suffix them with your surname. For example: parkinson_mytableDave Parkinson
  • 71. WEB BASED SOFTWARE DEVELOPMENT Page 71 Note that you will be sharing this database with other students so do not edit or delete any table that you do not own. Any table not named in the above manner will be deleted. Expand the view of the database within Server Explorer then right click on tables and select Add New Table. Create the required column names and data types as shown below. Select lastname as the primary key. Right click on the header and save the table as mysurname_people (e.g. parkinson_people) Right click on the new table in server explorer and select Show Table Data. Populate the database as shown below: 2. Within your Visual Studio Project create a new web form exercise 6.aspx (make sure you select your master page) From the Data section of the Toolbox drag a GridView object onto your web page:-Dave Parkinson
  • 72. WEB BASED SOFTWARE DEVELOPMENT Page 72 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 SQL DataSource. 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 an SQL Database and press enter, the wizard will bring you to the Configure Data Source dialog.Dave Parkinson
  • 73. WEB BASED SOFTWARE DEVELOPMENT Page 73 Select your SQL Server database (sqlb32.wbsd.wbsd) and on the next screen save the connection string. 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.Dave Parkinson
  • 74. WEB BASED SOFTWARE DEVELOPMENT Page 74 Clicking the Next button lets you test your query and see the results. If you are satisfied click Finish 4. Test your Program The output from your program should look like:- 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 createDave Parkinson
  • 75. WEB BASED SOFTWARE DEVELOPMENT Page 75 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: 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 Exercise 7 - 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.Dave Parkinson
  • 76. WEB BASED SOFTWARE DEVELOPMENT Page 76 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 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 wdsd database (held in the web.config file).Dave Parkinson
  • 77. WEB BASED SOFTWARE DEVELOPMENT Page 77 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.Dave Parkinson
  • 78. WEB BASED SOFTWARE 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. Press OK, then Next. 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.Dave Parkinson
  • 79. WEB BASED SOFTWARE DEVELOPMENT Page 79 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. 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. Run the program and check you can view the database.Dave Parkinson
  • 80. WEB BASED SOFTWARE DEVELOPMENT Page 80 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 Facility From 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 SqlDataSource. 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. Choice the same Data Source as set for the GridView (ObjectDataSource1) and Enable Inserting.Dave Parkinson
  • 81. WEB BASED SOFTWARE DEVELOPMENT Page 81 Within the properties view set the Default Mode to Insert Test your program. It should appear as shown below:8.4.2 Using Stored Parameters within Sequel Server When we accessed the database in the previous exercises it was stated that you can retrieve data from a database by either using a custom SQL statement or name a stored procedure. We used a custom SQL statement but there are circumstances where it is better to used stored procedures. What are stored procedures ? Normally, you would call a database with a query like: Select column1, column2 From Table1 To make this into a stored procedure, you simple execute this code:Dave Parkinson
  • 82. WEB BASED SOFTWARE DEVELOPMENT Page 82 CREATE PROCEDURE parkinson_myStoredProcedure AS Select column1, column2 From Table1 RETURN The stored procedure is normally held within the database thus making it quicker to action. Now all you have to do to get the recordset returned to you is execute the stored procedure. You can simply call it by name like this: parkinson_myStoredProcedure The stored procedure can be added to the database using Server Explorer from within Visual Studio in the same way we created tables within the SQL Server database. For example: When you create procedures in this database you must suffix them with your surname. For example: parkinson_myproceedure This method is fundamentally the same as using SQL statements directly. However it becomes more useful when you call a Stored Procedure with parameters. Lets say that we want to expand on our previous query and add a WHERE clause. So we would have: Select column1, column2 From Table1 Where column1 = 0 We could hard code the Where column1 = 0 into the previous stored procedure, but it would be a lot more powerful if the number that 0 represents could be passed in as an input parameter? That way it wouldnt have to be 0, it could be 1, 2, 3, 4, etc. and you wouldnt have to change the stored procedure. CREATE PROCEDURE myStoredProcedure @myInput int AS Select column1, column2 From Table1 Where column1 = @myInput RETURNDave Parkinson
  • 83. WEB BASED SOFTWARE DEVELOPMENT Page 83 You can have as many parameters as you want, or none at all. Parameters are set when the stored procedure is called, and the stored procedure receives it into a variable. @myInput is a variable. All variables in a stored procedure have a @ symbol preceding it. A name preceded with @@ are global variables. Other than that, you can name a variable anything you want. When you declare a variable, you must specify its datatype. We can now call the stored procedure with a parameter: myStoredProcedure 0 If you want more than one parameter, you separate them with commas in both the stored procedure and the procedure call. Like so: CREATE PROCEDURE myStoredProcedure @myInput int, @myString varchar(100), @myFloat AS ..... RETURN And you would call it like this: myStoredProcedure 0, This is my string, 3.45 Note: The varchar datatype is used to hold strings. You must specify the length of the string when you declare it. In this case, the variable is assigned to allow for 100 characters to be held in it.8.4.3 Using Visual Studio and Stored Parameters in Sequel Server Add a search facility to your web form. Add a button, textbox and GridView to your form. The search facility allows you to type in the surname of the person you are looking for and should return the phone number into a second GridView placed on your form. You should use a stored procedure rather than a custom SQL statement. 1. Create a stored procedure (named yoursurname_selectphone). It should contain the following: CREATE PROCEDURE parkinson_selectphone @surname varchar(20) AS Select phone from parkinson_people Where lastname=@surname RETURN 2. Add a new data source to the grid view (select a new SQL Database). Choose the wbsd database connection string, and then when asked to configure the select statement choose a Stored Procedure:Dave Parkinson
  • 84. WEB BASED SOFTWARE DEVELOPMENT Page 84 Select your stored procedure: Select the parameter source as being a Control and select the ControlID as TextBox1 Test your Program:Dave Parkinson
  • 85. WEB BASED SOFTWARE DEVELOPMENT Page 858.5 Other Data-Bound Controls List View The 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. DropDownList This control enables the user to populate a drop down list directly from a data source. ListBox This control enables the user to populate a list box directly from a data source. RadioButtonList This control enables the user to populate a Radio Button list directly from a data source. CheckBoxList This control enables the user to populate a check box list directly from a data source.Dave Parkinson
  • 86. WEB BASED SOFTWARE DEVELOPMENT Page 868.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 MS SQL 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 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 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:-Dave Parkinson
  • 87. WEB BASED SOFTWARE DEVELOPMENT Page 87 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 yourname_numbers to the SQL Server database as shown above. Add fields „name‟, „number1‟, „number2‟, „number3‟ to your table. The name field datatype should be set to „varchar(50)‟ and the number fields datatype set to „int‟. 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.xsd Add 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 wbds. Select that the TableAdapter should use SQL statements to access the database and then use the Query Builder to select every item from the numbers table.Dave Parkinson
  • 88. WEB BASED SOFTWARE DEVELOPMENT Page 88 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. 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.Dave Parkinson
  • 89. WEB BASED SOFTWARE DEVELOPMENT Page 89 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 "; } 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:Dave Parkinson
  • 90. WEB BASED SOFTWARE DEVELOPMENT Page 90 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(); int i = GridView1.SelectedIndex; numtable.Rows[i]["number1"]= System.Convert.ToInt16(TextBox2.Text); num.Update(numtable); GridView1.DataBind();Dave Parkinson
  • 91. WEB BASED SOFTWARE DEVELOPMENT Page 91 The finished program is shown below. Test your program.Dave Parkinson
  • 92. WEB BASED SOFTWARE DEVELOPMENT Page 92 Chapter 9 – Configuring your Web Application9.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. Its the master configuration file. You can find this file at WINNTMicrosoft.NET Framework VersionCONFIG. 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 doesnt 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 dont 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
  • 93. WEB BASED SOFTWARE DEVELOPMENT Page 939.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>Dave Parkinson
  • 94. WEB BASED SOFTWARE DEVELOPMENT Page 94 This file simply enables Forms Authentication for an application as opposed to Windows or Passport Authentication. The default authentication method, as specified in the 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 doesnt 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:Dave Parkinson
  • 95. WEB BASED SOFTWARE DEVELOPMENT Page 95 <configuration> <system.web> <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.Dave Parkinson
  • 96. WEB BASED SOFTWARE DEVELOPMENT Page 96 This Web.Config file enables Forms Authentication for your entire application. 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 theDave Parkinson
  • 97. WEB BASED SOFTWARE DEVELOPMENT Page 97 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, youll receive a 404 “resource cannot be found” error. You have been automatically redirected to a page named Login.aspx that doesnt 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
  • 98. WEB BASED SOFTWARE DEVELOPMENT Page 98 Enter the following code for the Log in handler: if (TextBox1.Text == "Administrator" && TextBox2.Text == "Secret") System.Web.Security.FormsAuthentication.RedirectFromLoginPage(TextBox1.Text,false); else Label3.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 users 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 users 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 users 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 of the FormsAuthentication.SignOut( ) method. This method removes the Authentication Ticket cookie from the users browser. Add a logout button to your web page, and add the following code to the buttonDave Parkinson
  • 99. WEB BASED SOFTWARE DEVELOPMENT Page 99 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 isnt 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
  • 100. WEB BASED SOFTWARE DEVELOPMENT Page 100 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 yournamewd10_passwords to the SQL Server database as shown below. Add fields „username‟, „password‟ to your table. The fields datatypes should be set to „varchar(50)‟. 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. HINT Create a DataSet 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
  • 101. WEB BASED SOFTWARE DEVELOPMENT Page 101 Chapter 10 : Other Useful ASP.NET Features10.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 sites 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 Russias 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
  • 102. WEB BASED SOFTWARE DEVELOPMENT Page 102 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.xmlDave Parkinson
  • 103. WEB BASED SOFTWARE DEVELOPMENT Page 103 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:13.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 SQL Server database. 1. Add a new table called yourname_pictures to the SQL Server database as shown below. Add fields „picture‟, „title‟ to your table. The fields datatypes should be set to „varchar(50)‟. Set the title field as the primary key.Dave Parkinson
  • 104. WEB BASED SOFTWARE DEVELOPMENT Page 104 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
  • 105. WEB BASED SOFTWARE DEVELOPMENT Page 105 mysql = "insert into yourname_pictures (picture,title) values (" + FileUpload1.FileName + "," + TextBox1.Text + ")"; SqlDataSource1.SelectCommand = mysql; DataList1.DataBind(); Response.Redirect("exercise12.aspx"); } else { Label2.Text = "Image was not uploaded"; } The DataList should be configured to select the yourname_pictures table and should select all the fields in the table i.e. SELECT [picture], [title] FROM [yourname_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 (form the TextBox) into the database. It will then display the contents of your pictures database table on your website. Test your website:Dave Parkinson
  • 106. WEB BASED SOFTWARE DEVELOPMENT Page 10610.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 objects 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 Years Day"; holidays[2][14] = "Valentines 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
  • 107. WEB BASED SOFTWARE DEVELOPMENT Page 107 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
  • 108. WEB BASED SOFTWARE DEVELOPMENT Page 108 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 addressDave Parkinson
  • 109. WEB BASED SOFTWARE DEVELOPMENT Page 109 TextBox2 contains the email message subject TextBox3 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("donotreply@csesalford.com",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 donotreply@csesalford.com 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 (donotreply@csesalford.com) 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
  • 110. WEB BASED SOFTWARE DEVELOPMENT Page 110 Chapter 11 : Deploying your WebSite on the CrystalTech Web Server11.1 Introduction In order for you to put your asp.net web site on CrystalTech you must first be allocated web space (this must be set up by Dave Parkinson). The web space will be a directory within the www.csesalford.com web site. The sub directory will be „yoursurnamewd10’ and it will be protected by password. To upload your site, within Visual Studio select Website – Copy Web site. This opens the dialog box: Complete the connection information as shown: Server: ftp.csesalford.com Username: “yoursurnamewd10” Password: “as provided by Dave Parkinson” This will open a copy facility as shown below allowing you to upload your files to the web server. You should upload all the files and directories within your Visual Studio Project directly to your web space. You can view your web site at the address:- www.csesalford.com/yoursurnamewd10Dave Parkinson
  • 111. WEB BASED SOFTWARE DEVELOPMENT Page 111 Chapter 12 : ASP.NET 3.5 and AJAX12.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 clients 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 browsers history engine, so clicking the browsers "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.12.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.Dave Parkinson
  • 112. WEB BASED SOFTWARE DEVELOPMENT Page 112 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 ASP.NET AJAX server controls. These server controls are included in Visual Studio 2010 under the AJAX Extensions Tab. ScriptManager Manages 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. UpdatePanel Enables you to refresh selected parts of the page, instead of refreshing the whole page by using a synchronous postback. UpdateProgress Provides status information about partial-page updates in UpdatePanel controls. Timer Performs 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.12.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
  • 113. WEB BASED SOFTWARE DEVELOPMENT Page 113 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.12.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.zipDave Parkinson
  • 114. WEB BASED SOFTWARE DEVELOPMENT Page 114 Run the .zip file and extract the toolkit to a directory of your choice. The next step is to add the Ajax Control Toolkit to the Visual Studio Toolbox. Follow these steps: 1. Launch Visual Studio and create a new ASP.NET Web Forms project or website. Open Default.aspx in the Visual Studio editor. 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
  • 115. WEB BASED SOFTWARE DEVELOPMENT Page 115 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
  • 116. WEB BASED SOFTWARE DEVELOPMENT Page 116 Chapter 13 : Web Services13.1 Introduction The „world wide web‟ has grown rapidly beyond its original role of presenting text and images into a fully interactive medium for data access, online transactions and distributed applications. For instance consider what happens when you buy a product from an online store. What seems at first simple a client / server interaction is actually more complicated. For example the store‟s server will need to check with a warehouse server to see if the item is in stock, if it isn‟t then an appropriate supplier‟s server will be contacted. Subsequently a delivery company‟s server needs to be contacted to get the product to the customer and the store and customer‟s banks need to exchange money. Each server involved may itself need to contact on other servers automatically to cross reference or update information. For instance the supplier will need to liaise with other suppliers, delivery services and other banks. A key problem with automatically processing information across a whole range of different servers at different locations around the world, is trying to get all these computers to talk to each other - regardless of the range of different operating systems running on different hardware. If we can solve this problem, then any web site has the potential to be the front end to larger distributed applications whose constituent parts run across a heterogeneous network of computers. A Web Service is an application component accessible over open protocols In other words web services are components that share information across the web in a standard way regardless of the hardware and software differences involved.Dave Parkinson
  • 117. WEB BASED SOFTWARE DEVELOPMENT Page 11713.2 A Brief History of Developing Distributed Applications Originally most software development was procedure based hence distributed applications running across a network used remote procedure calls (RPC). Typically both client and server computers each needed to run an extra execution layer (i.e. middleware) to handle connection and hence data exchanges via a mutually recognised protocol (e.g. SUN-RCP or DCE-RCP). With the advent of object orientated computing client machines wanted access to server based objects. The Common Object Request Broker Architecture (CORBA) was a standard developed by a consortium of companies (the Object Management Group) to enable the use of objects over networks. Central to CORBA are Object Request Brokers (ORBs) which provide the necessary middleware (i.e. glue or plumbing) between computer applications. If a computer wishes to use or provide objects, than his or her system must have an ORB product installed. The client doesn‟t need to know anything about which servers are on the network, instead the various ORBS deal with connecting and passing of data to and from the appropriate servers. ORBS communicate with each other via the standard binary protocol IIOP (Internet Inter-ORB Protocol). Although CORBA has been implemented for a wide variety of different systems there are often incompatibilities between different implementations. A similar approach is offered by Microsoft‟s Distributed Component Object Model (DCOM). Although an open standard it has only really been used for distributed computing between Microsoft Windows based clients and servers. Yet another option is Sun‟s EJB (Enterprise JavaBeans) that uses a protocol called RMI to allow Java based applications to use remote objects. A key problem with all the above middleware solutions is poor interoperability between them. For example CORBA based objects can‟t communicate with DCOM objects which can‟t communicate with EBJ objects. If a business acquires a new partner their respective computers may not be able to talk to each other without some kind of expensive bridging solution. Another problem is how different computers restrict access. If a computer has a firewall installed it may well block communication on ports used by CORBA, DCOM, etc, (much like a bouncer may only allow people into a club through one door). A strict firewall may only allow communication via port 80, i.e. the port reserved for HTTP (HyperText Transfer Protocol) based communication. HTTP is the protocol Web Browsers use to communicate with Web Servers.Dave Parkinson
  • 118. WEB BASED SOFTWARE DEVELOPMENT Page 118 The ideal solution would be to have a universally recognised standard technology to link applications running on different platforms utilising the universal standard and firewall friendly protocol HTTP. XML Web Services are based on this ideal solution having been specified by the W3Consortium and hence implemented by member companies such as Sun, IBM and Microsoft. XML web services are based on a new protocol called SOAP (Simple Object Access Protocol), which rides piggy back on HTTP. SOAP is based on the universal text based standard for organising information, XML (Extensible Markup Language). In this module we will see the importance of SOAP in offering a highly interoperable and extensible means of using and exposing objects for use across the internet.13.3 Investigating Web Services In this exercise you will investigate the types of web services available Open Internet Explorer hence type the URL: www.webservicex.net This web site gives a listing of many web services that are in the public domain. On the menu Currency Convertor Web Service Click on the Conversion Rate link within the demo to open up a HTML front end allowing you to test the web service facilities.Dave Parkinson
  • 119. WEB BASED SOFTWARE DEVELOPMENT Page 119 Try and find conversion rates between various countries. The following URLs list wide variety of web services accessible to web developers. http://www.xmethods.com http://www.webservicelist.com Explore some of the web services available. Some you will be able to test via a HTTP based form. Most will give access to a Web Service Description Language File (WSDL).13.4 Money Calculator - Exercise 16 This exercise shows you how add a web service to your web site Add a new web page and name it exercise16. On the web page create the following: Before we can write the program we must first incorporate into our program a currency conversion web service from the www.webservicex.net web site.Dave Parkinson
  • 120. WEB BASED SOFTWARE DEVELOPMENT Page 120 To have access to our remote web service we need Visual Studio.NET to have a reference to it. From main menu select… Website ->Add Web Reference This will give the „Add Web Reference‟ dialog box shown. In the Address field enter the URL for the web service … http://www.webservicex.net/CurrencyConvertor.asmx?wsdl Upon selecting Go, Visual Studio will download this Web Service Description Language File.Dave Parkinson
  • 121. WEB BASED SOFTWARE DEVELOPMENT Page 121 When downloading is complete click „[Add Reference]‟ to create a proxy class (i.e. a local representation of the web service). You can view this new class via the menu option View -> Solution Explorer. Hence from this class you can create objects – hence use the web service in your own applications. For example… Add to top of your c# code using net.webservicex.www; this simply makes visible the namespace where of web service class reside. Hence in the event handler of the calculate button (when currency convert is selected) you can declare and instantiate an object called „ws‟ using the class „CurrencyExchangeService‟. CurrencyConvertor ws = new CurrencyConvertor(); This will give you access to the method „ConversionRate( )‟ which takes as input two currencies and returns a double value representing the exchange rate. For example to convert between Pounds (GBP) and US dollars (USD)… double rate; rate = ws.ConversionRate(Currency.GBP, Currency.USD); Other currency values can be found on the web site describing the web service. Write the code on the convert button to allow you to take the number entered in the TextBox and convert it from UK pounds to a value in US Dollars. The result should be written to the label box.Dave Parkinson
  • 122. WEB BASED SOFTWARE DEVELOPMENT Page 122 Your final program should appear as follows: You can use two „DropDownLists‟ as a way to let the user choose currencies as shown (to get the text value from a drop down list use DropDownList1.SelectedItem.Text) Try adding other web services to your web page.Dave Parkinson

×