Net Development

8,575 views

Published on

ASP.NET 4 Development using Access Databases

Published in: Education, Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
8,575
On SlideShare
0
From Embeds
0
Number of Embeds
121
Actions
Shares
0
Downloads
88
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Net Development

  1. 1. .Net DevelopmentPrepared by : Dave Parkinson www.webdesigninfo.co.uk (February 2012)
  2. 2. .NET DEVELOPMENT Page 2 .NET DEVELOPMENT CONTENTSChapter 1 : Introduction to the Visual Studio 2010 and the .NET Framework ..................... 51.1 Introduction to .NET ...................................................................................................................... 5Chapter 2 : Visual Studio 2010 & C# ....................................................................................... 72.1 Introduction ..................................................................................................................................... 72.2 What is C#? ..................................................................................................................................... 72.3 A Quick Overview of C# Syntax .................................................................................................... 8 2.3.1 Variables and Operators ............................................................................................................................. 8 2.3.2 Decision Making and Flow Control ........................................................................................................... 9 2.3.3 Member Functions .................................................................................................................................... 10 2.3.4 Classes and Objects .................................................................................................................................. 10 2.3.5 Event Handling ......................................................................................................................................... 112.4 Using Visual Studio ....................................................................................................................... 12 2.4.1 Exercise 1 - Starting a Project (A Windows Application) ....................................................................... 12 2.4.2 Exception Handling .................................................................................................................................. 16Chapter 3 : Designing Web Sites with Visual Studio 2010 ................................................... 173.1 Introduction ................................................................................................................................... 173.2 Testing your Web Application ..................................................................................................... 173.3 HTML and CSS............................................................................................................................. 17 3.3.1 Applying Cascading Style Sheets to an HTML document ....................................................................... 18 3.3.2 CSS Rules ................................................................................................................................................. 18 3.3.3 Element Layout and Positioning ............................................................................................................... 20 3.3.4 Working with CSS in Visual Studio ......................................................................................................... 213.4 Web Site Layout ............................................................................................................................ 23 3.4.1 Working with Master Pages ..................................................................................................................... 24 3.4.2 Exercise 3 – Creating a Web Site using Visual Studio 2010 .................................................................... 25Chapter 4 : Web Applications and ASP.NET ........................................................................ 334.1 Introduction ................................................................................................................................... 334.2 Features in ASP.NET.................................................................................................................... 34 4.2.1 ASP.NET Controls ................................................................................................................................... 35 4.2.2 Web services integration .......................................................................................................................... 36 4.2.3 Handling Post Back .................................................................................................................................. 36 4.2.4 Moving Between Pages ............................................................................................................................ 374.4 Useful ASP.NET Tutorial Web Sites .......................................................................................... 37Chapter 5 : Using Visual Studio & ASP.NET ....................................................................... 385.1 Introduction ................................................................................................................................... 38 5.1.1 Structure of a Web Form Page ................................................................................................................. 38 5.1.2 Adding Server Controls ........................................................................................................................... 38 5.1.3 Handling Events ....................................................................................................................................... 385.2 Web Page Exercise 1 – Creating an ASP.NET Web Calculator ............................................... 405.3 Web Page Exercise 2 – Creating an ASP.NET Web Lottery Number Generator .................. 43Chapter 6 : Validation Web Form Pages ............................................................................... 446.1 Introduction ................................................................................................................................... 44 6.1.1 Overview of the Validation Controls ........................................................................................................ 44Dave Parkinson
  3. 3. .NET DEVELOPMENT Page 3 6.1.2 Post Backs and Form Validation .............................................................................................................. 45 6.1.3 JavaScript and the Validation Controls .................................................................................................... 456.2 Using Validation Controls ............................................................................................................ 46 6.2.1 Checking for Required Fields ................................................................................................................... 46 6.2.2 Validating a Range of Expressions ........................................................................................................... 46 6.2.3 Web Page Exercise 3 - Using a RequiredFieldValidator Control ............................................................. 47 6.2.4 Comparing Values .................................................................................................................................... 48 6.2.5 Performing Data Type Checks ................................................................................................................. 48 6.2.6 Regular Expression Validation ................................................................................................................. 49 6.2.7 Displaying a Summary of Validation Errors ............................................................................................ 49 6.2.8 Web Page Exercise 4 – Validating a Web Form ...................................................................................... 50Chapter 7 : Maintaining State on your Web Site................................................................... 517.1 Introduction ................................................................................................................................... 517.2 Using View State ........................................................................................................................... 51 7.2.1 Disabling View State ................................................................................................................................ 52 7.2.2 Adding Custom Information to View State .............................................................................................. 52 7.2.3 Protecting View State ............................................................................................................................... 537.3 Using Cookies ................................................................................................................................ 53 7.3.1 Reading Cookies ....................................................................................................................................... 54 7.3.2 Writing Cookies ....................................................................................................................................... 547.4 Using Session State ........................................................................................................................ 557.5 Using Application State ................................................................................................................ 567.6 Web Page Exercise 5 – Using Cookies and Session Variables .................................................. 56Chapter 8 : Databases ............................................................................................................. 588.1 Introduction ................................................................................................................................... 588.2 Review of Databases and SQL ..................................................................................................... 59 8.2.1 Relational Databases ................................................................................................................................ 59 8.2.2 Structured Query Language ...................................................................................................................... 608.3 Web Page Exercise 6 - Reading Data from an Access Database ............................................... 638.4 Using Datasets to connect to a Database ..................................................................................... 67 8.4.1 Connecting to a Database using Typed Data Sets .................................................................................... 688.5 Other Data-Bound Controls......................................................................................................... 74 8.5.1 Exercise 8 – Using List View and other Data-Bound Controls ................................................................ 758.6 Searching through a Database Table using Typed Data Sets ................................................... 75 8.6.1 Web Page Exercise 9 – Searching through a Database Table................................................................... 76Chapter 9 – Configuring your Web Application .................................................................... 819.1 Introduction ................................................................................................................................... 819.2 Web Forms Authentication .......................................................................................................... 82 9.2.1 Web Exercise 10 – Password Protecting an area of your Web Site .......................................................... 84 9.2.2 Storing Usernames and Passwords in the Web.Config File ..................................................................... 88 9.2.3 Storing Usernames and Passwords in a Database ..................................................................................... 89Chapter 10 : Other Useful ASP.NET v3.5 Features.............................................................. 9010.1 RSS Feeds – Exercise 11 ............................................................................................................. 9010.2 Uploading and Displaying Pictures on your Web Site – Exercise 12 ..................................... 9210.3 Calendar Control – Exercise 13 ................................................................................................. 95Dave Parkinson
  4. 4. .NET DEVELOPMENT Page 410.4 Retrieving Web Pages – Exercise 14 ......................................................................................... 9610.5 Form to Email – Exercise 15 ...................................................................................................... 97Chapter 11 : ASP.NET and AJAX ........................................................................................ 9911.1 Introduction ................................................................................................................................. 9911.2 ASP.NET AJAX .......................................................................................................................... 99 11.2.1 Using AJAX Server Controls – Exercise 16 ......................................................................................... 100 11.2.2 ASP.NET AJAX Control Toolkit– Exercise 17 ................................................................................... 101Dave Parkinson
  5. 5. .NET DEVELOPMENT Page 5 Chapter 1 : Introduction to the Visual Studio 2010 and the .NET Framework1.1 Introduction to .NET Microsoft introduced the .NET concept as a way of integrating the development and delivery of windows applications, web applications and web services. .NET provides a common set of components and services that can be used to develop and run applications. .NET contains a huge number of pre-defined components and services that are available to the application developer. This set of components and services is called the .NET Framework. The .NET Framework contains more than 6000 classes that can be used in your application. This means that most of the common actions like interacting with files and interacting with databases have predefined classes that you can use. Previously, programmers developed programs in a language specific development environment. For example, A Visual C++ program was written in the Visual C++ development environment and a Visual Basic program was written in the Visual Basic programming environment. It was difficult to develop applications that had programs written in a variety of languages. From a programmer‟s perspective, .NET provides a single Integrated Development Environment that allows programs written in a variety of different languages to be easily combined in the same application. This was achieved by using a Common Language Runtime. All languages supported by .NET compile to a standard language called Microsoft Intermediate Language (MSIL). MSIL is then converted by the Common Language Runtime into native code that runs on your PC. The use of the CLR means that .NET is theoretically independent of the hardware platform. Because applications in .NET compile to MSIL and are run through the CLR, the applications will run on any platform that has the CLR installed. This means that .NET applications will run on PC, Mac, Sun or any other platform, provided that the CLR is installed. Another feature of the „.NET‟ framework is that it allows software developers to use a common set of unified classes regardless of the programming language. All languages that are supported by the CLR use the same data types. This means that it is much easier for programs written in different languages to pass variables. Within Visual Studio .NET, Microsoft provides Visual Basic, Visual C++ and C# (C sharp). However, Microsoft have produced a Common Language Specification to allow other Companies to produce language compilers that are compatible with .NET. Hence if you decide to develop in Visual Basic, C# or C++ the programming elements will appear the same as will the development environment (including drag and drop creation of user interfaces and auto code generation). All the target code will be deliverable in a single directory (called an assembly) making for easy deployment from CD Rom or the Web. Types of application you will develop in this module (and the .NET Services module) include:-Dave Parkinson
  6. 6. .NET DEVELOPMENT Page 6 Windows Applications – these are client side applications. An exciting feature of .NET is that such applications can be quickly delivered for the web on a „no-touch‟ basis. The user can surf to a web page and the windows application is automatically loaded and run on the client machine. Called „smart client applications‟ they provide the rich features of traditional windows applications whilst also the convenience (i.e. you don‟t need to install them) of „thin client‟ browser based applications such as Java Applets. Web Applications – these are server side applications consisting of one or more Web Forms. Unlike „old‟ ASP or PHP technology they are compiled rather than interpreted. They are based on Microsoft‟s ASP.NET technology. The new .NET framework lets you develop these applications in much the same way as Windows Applications using drag and drop user interface creation and similar code generation. The first version of ASP.NET offered several important advantages over previous Web development models. ASP.NET 4.0 improves upon that foundation by adding support for several new and exciting features in the areas of developer productivity, administration and management, extensibility, and performance. We will be using ASP.NET 4.0. XML Web Services – these are special web based applications that provide a distributed computing solution across the internet. Throughout this course we will be using Microsoft‟s Visual Studio.NET 2010 to develop Windows Applications, Web Application and Web Services.Dave Parkinson
  7. 7. .NET DEVELOPMENT Page 7 Chapter 2 : Visual Studio 2010 & C#2.1 Introduction When developing in .NET you will be using object oriented programming. Object oriented programming is now the paradigm for nearly all software development. When previously a programmer would have to develop programs from the ground up; instead these days they need only manage and use a number of objects that perform the required tasks. Objects are created (i.e. instantiated) from classes; a class being a template that can be used directly or extended (i.e. inherited) and modified to suit the programmer‟s specific needs. The beauty of modern programming is that classes are usually prewritten and arranged in hierarchically ordered packages (i.e. namespaces) for programmers to use as needed.2.2 What is C#? In this module we will use C#.NET. C# (pronounced C sharp) which is Microsoft‟s attempt to redefine C++ for optimised use with a Virtual Machine (in this case Microsoft‟s Common Language Runtime). In this respect it is very similar to Java, probably being a result of the fall out between Sun and Microsoft after Microsoft tried to unilaterally tweak the Java specification. Here‟s a really dumb question - „why we learning another language?‟. The syntax of C# will already be very familiar to C, C++,PHP and Java programmers. The few changes, additions and omissions actually make C# one of most intuitive and tidy OOP languages to use. All .NET compliant programming languages (e.g. C#.NET, VB.NET, Java.NET, C++.NET, etc) are defined according to a common type system. In other words they Use the same set of primitive variable types. Use the same object oriented programming constructs (e.g. classes, objects, namespaces, events, inheritance and interfaces). Compile to the same byte code, hence different classes can be written in different languages yet linked seamlessly. Give identical access to same precompiled classes, with the same methods using the same input arguments and return types, all hierarchically ordered in the same namespaces.Dave Parkinson
  8. 8. .NET DEVELOPMENT Page 8 Hence when using .NET, regardless of the language we choose, you create programming solutions in a very similar way. In reality it does not matter whether we choose to use C# or Visual Basic to write our applications. However Microsoft have developed C# specifically for web development and it makes sense to learn a language which is likely to become the de-facto standard for web development in the Microsoft environment.2.3 A Quick Overview of C# Syntax C# is very similar to C++ , Java and PHP scripting language in terms of its syntax. Note that all C# statements end in a „;‟ and C# is case sensitive.2.3.1 Variables and Operators The simplest programming entity is the primitive variable. C# provides the usual primitive variable types notably:- int, long & short for integer variables float & double for real number 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
  9. 9. .NET DEVELOPMENT Page 9 x=10; PI=3.1414f; myString="hello world"; prime_numbers[0]=1.0f; prime_numbers[1]=2.0f; prime_numbers[2]=3.0f; matrix[2,0]=0; You can subsequently add, subtract, multiply and divide variables with arithmetic operators ( + - * / ). For example:- z=x+y; Average=(a+b+c)/3; And recast if needed. For example:- myInt=(int)myFloat;2.3.2 Decision Making and Flow Control Like C++, Visual Basic and Java, C# supports all the common decision making and flow control statements (if statements, do loops, while loops, for loops etc). You test variable values and perform appropriate tasks using conditional operators == for equals, >, <, >=,<=, && for And, || for OR. For example:- float x=0, y=0; if(x==10) y=20; 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
  10. 10. .NET DEVELOPMENT Page 10 { sum = sum + prime_numbers[i]; i = i + 1; } for(i = 0; i<9;i=i+1) { val = prime_numbers[i]; sum = sum + val; }2.3.3 Member Functions To avoid excessive amounts of code it is often desirable to group regularly used statements into member functions (often called methods). Functions take input variables (often called arguments or parameters), and can output a result variable called the return value. Functions are firstly defined. For example… float MyAdd(float a, float b) { float c; c=a+b; return c; } In the above example we use a „void‟ type to indicate no value is returned. Calling functions is again straight forward. For example… c = MyAdd(a, b);2.3.4 Classes and Objects Given that we have variables that hold data and the functions that process this data, it is often desirable to encapsulate all data and functionality an object. Such objects being instantiated from type definitions called classes.Dave Parkinson
  11. 11. .NET DEVELOPMENT Page 11 Later we will look at defining our own classes, for now consider a class called MyCalculator. Typically we would instantiate an object from the class using the „new‟ keyword. MyCalculator myCalcObj=new MyCalculator(); We could then use the object to access data and methods associated with the class. For example… result=myCalcObj.Add(1,2); Calls the method Add passing values 1 and 2 and receiving the result 3. Some classes however can be used directly, for example the standard Math class gives you direct access to member functions such as Cos, Sin, Log10, etc. For example… result=Math.Sin(angle); Later you‟ll notice C# source files will begin with statements such as.. using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; these are simply making visible to your code collections of standard class definitions called „namespaces‟ in much the same way as „import‟ statements in java or „header files‟ in C++.2.3.5 Event Handling Rather than just running a serial sequence of tasks; modern object orientated applications are event driven, i.e. they respond to events such as button clicks, mouse dragging, keyboards being pressed, timers going off, etc as and when they occur.Dave Parkinson
  12. 12. .NET DEVELOPMENT Page 12 Objects such as buttons, timers, etc can generate events (e.g. when a button is clicked) and hence objects containing methods with suitable arguments can be delegated to handle these events. Such methods are called event handlers because they perform appropriate tasks in response to events. When writing programs in Visual Studio much of your coding will involve filling event handler methods for objects that comprise your application. Further information on C# can be found in the C# programmers reference section of the Help files on Visual Studio 2010.2.4 Using Visual Studio Microsoft Visual Studio 2010 is an Integrated Development Environment (IDE) where you can write, compile, build, run and debug computer programs. The IDE allows you to write in a variety of languages (C#, Visual Basic, C++ etc) for a variety of purposes (Windows Applications, Web Applications, Web Services, etc) in a visually intuitive way where much of the difficult code generation is done automatically. This application also provides excellent inline help including programming tutorials and references. To start Visual Studio.NET from windows Start->All Programs->Microsoft Visual Studio 2010->Microsoft Visual Studio 2010 Upon starting Visual Studio you are presented with a Start page detailing previous projects and providing a gateway to offline and online help.2.4.1 Exercise 1 - Starting a Project (A Windows Application) A project bundles into a single directory all the files you use to develop your computer program including source code, resources and IDE settings. From the IDE main menu select… File->New->Project The resultant dialog box allows you to select Project Types from a variety of Templates and assign a name and directory to your project.Dave Parkinson
  13. 13. .NET DEVELOPMENT Page 13 e.g. Select Visual C# , Windows Forms Application ... Name: Conversion Location: F:Netdevelopment on a directory Netdevelopment on your pen disc … hence click [OK] Upon starting the project you are presented with a … Design Area – where you will create the user interface for your application and write your source code. Properties Window – where you assign individual properties to individual visual elements. For example think of say a button as an object that has encapsulated within it member variables that describe it; such as its caption, font, size, colour, etc. From the properties window you can select one object from a list of current objects and hence set it‟s member variables. Solution Explorer – where you can view the constituent files and references (i.e. linked libraries, etc) that make up your project. A solution is in effect a project (or group of projects). Toolbox – where you can select from a variety of objects to add to your application. Output Pane – where the IDE sends messages to you (e.g. compile time errors, etc)Dave Parkinson
  14. 14. .NET DEVELOPMENT Page 14 Having created your project 1. From the Properties Window select the Form1 object and hence change the value it‟s member variable Text from „Form1‟ to „Miles to Kilometres‟. 2. Experiment with other form properties i.e. change the form‟s background colour. You are now ready to design your application From the Toolbox drag and drop a Label onto the Form1 window. From the Toolbox drag and drop a TextBox onto the Form1 window. From the Toolbox drag and drop a Button onto the Form1 window.Dave Parkinson
  15. 15. .NET DEVELOPMENT Page 15 You can view the source code that has been generated by right clicking on Form1.cs in the solution explorer and selecting the option View->Code. By double clicking the Button in the From1 design view the event handler code is automatically generated, i.e. private void button1_Click(object sender, System.EventArgs e) { } And so becomes a method of the Form1 class. As yet the event handler for the Button1 doesn‟t do anything. You will need to add some code to the method Button1_Click( …) to handle the event. Next, add to the Button1_Click( …) event handler method code to take input from the text box, convert it to a double value hence calculate a new value and set the label. So the class looks like… public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { double m, k; // variables for miles and kilometres string myString; // declare a string myString = textBox1.Text; // get text from textbox m = System.Convert.ToDouble(myString); // convert to double k = m * 1.609; // calculate miles to kilometres label1.Text = System.Convert.ToString(k); // set label to Km } } Note the program declares doubles for miles and kilometres and a string that will come in handy sets myString to the input from the textBox1 object‟s Text member. converts myString to a numerical value using the class System.Convert hence uses this value to convert from miles to kilometres hence the sets the Text member of the label1 object to display the result. Note you can also convert numbers to strings just by adding them to a pre-existing string.Dave Parkinson
  16. 16. .NET DEVELOPMENT Page 16 The final program looks like:2.4.2 Exception Handling An important feature of OOP programming is exception handling. There are occasions where the executing program can generate an error and hence quit or even crash. Being able to catch such errors (i.e. exceptions) and take appropriate actions makes for stable applications. For instance if the user of the above „Miles To Kilometres‟ application enters a word instead of a number an exception is generated. The keywords to test and handle such an exception are „try‟ and „catch‟ For example private void button1_Click(object sender, System.EventArgs e) { bool error_flag=false; string myString=""; try { myString = textBox1.Text; m=System.Convert.ToDouble(myString); } catch { label1.Text = "Input Error"; error_flag = true; } if(error_flag==false) { k = m * 1.609; label1.Text = System.Convert.ToString(k); } } Change your program as shown above using try and catch to add error recovery to your conversion application.Dave Parkinson
  17. 17. .NET DEVELOPMENT Page 17 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
  18. 18. .NET DEVELOPMENT Page 18 style. Using CSS brought back the logical separation between web page content and the styles used to display it.3.3.1 Applying Cascading Style Sheets to an HTML document There are three mechanisms by which styles can be applied to a HTML document. 1. the style can be defined within the HTML tag 2. styles can be defined in the <head> section and applied to the whole 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
  19. 19. .NET DEVELOPMENT Page 19 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
  20. 20. .NET DEVELOPMENT Page 203.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
  21. 21. .NET DEVELOPMENT Page 21 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
  22. 22. .NET DEVELOPMENT Page 22 Once you have created styles for your web site Visual Studio provides three tool windows you can use to manage style sheets, apply styles to elements and inspect the style properties applied to an element. All three windows are available from the View menu. Manage Styles Tool Window This shows all the styles currently applied to your page. The style is previewed at the bottom of the window. Apply Styles Tool Window This window lets you apply styles to various elements on your web pages.Dave Parkinson
  23. 23. .NET DEVELOPMENT Page 23 CSS Properties Tool Window This tool shows you all the properties that have been applied to the currently selected element. You can also use the tool to edit the style properties.3.4 Web Site Layout A typical web page is made up of a collection of components. For example: 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
  24. 24. .NET DEVELOPMENT Page 24 The various elements on the page can be laid out using CSS, with the separate components being contained within <div> tags and the styles associated within each component being defined a an external style sheet. The skeletal markup for a typical page would be as follows: <!—doctype--> <html> <head> <title><!--page title--></title> <!--fetch stylesheets--> </head> <body> <div id=”branding”> <!--display brand--></div> <div id=”navigation”> <!--display navigation--></div> <div id=”sidebar”> <!--display sidebar--></div> <div id=”content”> <!--display content--></div> <div id=”footer”> <!--display footer--></div> </body> </html>3.4.1 Working with Master Pages Master Pages, a new feature of Microsoft ASP.NET, enables you to apply the same page layout to multiple content pages in a Web application. Master Pages provide you with an easy method of creating a consistent look and feel for a Web site. The pages in most Web applications have standard elements, such as logos, navigation menus, and copyright notices. You can place all of these elements within a single Master Page. If you base the content pages in your application on this Master Page, then all of the content pages will automatically include the same standard elements. When you create a master page, you can define portions of the page that the content page can replace with its own content. These portions are defined using an ASP.NET control; the ContentPlaceHolder control. A master page can contain any number of ContentPlaceHolder controls (or none at all.) On the content page, the content from the ContentPlaceHolder controls appears inside of Content controls. By default, the content pages Content controls are empty so that you can provide your own content. The above diagram shows a master page and an associated content page as they appear in Visual Studio 2010. You can see the ContentPlaceHolder control in the master page and the corresponding Content control in the content page. Notice that the master pagesDave Parkinson
  25. 25. .NET DEVELOPMENT Page 25 content that is outside of the ContentPlaceHolder is visible but greyed out in the content page. Only the content inside of the ContentPlaceHolder can be accessed via the content page. All other content that comes from the master page is unchangeable.3.4.2 Exercise 3 – Creating a Web Site using Visual Studio 2010 This exercise shows you how to create a web site using Visual Studio. We will be using this web site to access all the other exercises produced in this module. Open Visual Studio 2010 and select File – New Web Site. Browse to the D:drive or your pen drive and create an ASP.NET Empty Web Site called „mysurname‟ (e.g. parkinson). Note you cannot use your f: drive as you cannot run the built-in ASP.NET web server over a network. The web location should be set to File System and the Language to C#. Your website will be opened by Visual Studio as shown below:Dave Parkinson
  26. 26. .NET DEVELOPMENT Page 26 Download the file 960template.zip from Blackboard and unzip it onto your pen drive. Copy the contents of the 960template directory (see below) into the directory containing your Visual Studio Project. Your web site should now contain the following files: This template uses the 960gs CSS framework to design the site structure. The MasterPage.master file defines the general look and feel of all the 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
  27. 27. .NET DEVELOPMENT Page 27 In order to test our website press the debug button on the menu bar. The first time you do this it will open a dialog box as shown below: Click the OK button (we will discuss the web.config file later in the course). Your web page should be displayed in the default browser as shown below. The home page explains how use the template. It includes a link to the free, open source CSS template, 960gs CSS Framework, which has been used to design the site. Click on this link to find more information on the framework. The biggest problem with CSS development is the number of different browsers which are out there and being used. Each browser implements CSS slightly differently (some more differently than others). This causes huge headaches for any web developer trying to get a consistent layout across different browsers, browser versions and platforms. A way of fixing this problem is to use a framework. One of these frameworks is called 960 Grid System, and is a fixed width framework. This is a very simple framework that allows the developer to very quickly implement wire- frame designs and then embellish their content with their own styles. The width of a page using 960 Grid System is 960px, and this can be split into either 12 or 16 grids (each 60px or 40px per grid respectively with a 20px gap between the grids).The biggest problem with CSS development is the number of differentDave Parkinson
  28. 28. .NET DEVELOPMENT Page 28 The web site contains the following files and directories. CSS Directory The subdirectory css (within the main css directory) contains all the files for the 960gs CSS Framework. It should not be edited. The style.css file contains all the styles for your site. #title, #menu, #footer { background-color: #00584a; color: #fff; } #menu a { color: #fff; text-decoration: none; background-color: #008a7f; display: block; padding: 3px; } #menu li { list-style: none; margin: 2px; } #menu { height: 300px; } #footer { text-align: center; } You need to edit this file to add new styles and to change to look of your site. Images Directory This directory is used to store all the images on your site.Dave Parkinson
  29. 29. .NET DEVELOPMENT Page 29 MasterPage.master The master page contains the following HTML code:<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs"Inherits="MasterPage" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>Dave 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
  30. 30. .NET DEVELOPMENT Page 30 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
  31. 31. .NET DEVELOPMENT Page 31 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'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
  32. 32. .NET DEVELOPMENT Page 32 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
  33. 33. .NET DEVELOPMENT Page 33 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
  34. 34. .NET DEVELOPMENT Page 34 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
  35. 35. .NET DEVELOPMENT Page 354.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
  36. 36. .NET DEVELOPMENT Page 36 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
  37. 37. .NET DEVELOPMENT Page 374.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
  38. 38. .NET DEVELOPMENT Page 38 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
  39. 39. .NET DEVELOPMENT Page 39 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
  40. 40. .NET DEVELOPMENT Page 40 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
  41. 41. .NET DEVELOPMENT Page 41 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
  42. 42. .NET DEVELOPMENT Page 42 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
  43. 43. .NET DEVELOPMENT Page 435.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
  44. 44. .NET DEVELOPMENT Page 44 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
  45. 45. .NET DEVELOPMENT Page 45 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
  46. 46. .NET DEVELOPMENT Page 46 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
  47. 47. .NET DEVELOPMENT Page 47 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
  48. 48. .NET DEVELOPMENT Page 486.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
  49. 49. .NET DEVELOPMENT Page 496.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
  50. 50. .NET DEVELOPMENT Page 506.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

×