- •Contents at a Glance
- •Table of Contents
- •Acknowledgments
- •Introduction
- •Who This Book Is For
- •Finding Your Best Starting Point in This Book
- •Conventions and Features in This Book
- •Conventions
- •Other Features
- •System Requirements
- •Code Samples
- •Installing the Code Samples
- •Using the Code Samples
- •Support for This Book
- •Questions and Comments
- •Beginning Programming with the Visual Studio 2008 Environment
- •Writing Your First Program
- •Using Namespaces
- •Creating a Graphical Application
- •Chapter 1 Quick Reference
- •Understanding Statements
- •Identifying Keywords
- •Using Variables
- •Naming Variables
- •Declaring Variables
- •Working with Primitive Data Types
- •Displaying Primitive Data Type Values
- •Using Arithmetic Operators
- •Operators and Types
- •Examining Arithmetic Operators
- •Controlling Precedence
- •Using Associativity to Evaluate Expressions
- •Associativity and the Assignment Operator
- •Incrementing and Decrementing Variables
- •Declaring Implicitly Typed Local Variables
- •Chapter 2 Quick Reference
- •Declaring Methods
- •Specifying the Method Declaration Syntax
- •Writing return Statements
- •Calling Methods
- •Specifying the Method Call Syntax
- •Applying Scope
- •Overloading Methods
- •Writing Methods
- •Chapter 3 Quick Reference
- •Declaring Boolean Variables
- •Using Boolean Operators
- •Understanding Equality and Relational Operators
- •Understanding Conditional Logical Operators
- •Summarizing Operator Precedence and Associativity
- •Using if Statements to Make Decisions
- •Understanding if Statement Syntax
- •Using Blocks to Group Statements
- •Cascading if Statements
- •Using switch Statements
- •Understanding switch Statement Syntax
- •Following the switch Statement Rules
- •Chapter 4 Quick Reference
- •Using Compound Assignment Operators
- •Writing while Statements
- •Writing for Statements
- •Understanding for Statement Scope
- •Writing do Statements
- •Chapter 5 Quick Reference
- •Coping with Errors
- •Trying Code and Catching Exceptions
- •Handling an Exception
- •Using Multiple catch Handlers
- •Catching Multiple Exceptions
- •Using Checked and Unchecked Integer Arithmetic
- •Writing Checked Statements
- •Writing Checked Expressions
- •Throwing Exceptions
- •Chapter 6 Quick Reference
- •The Purpose of Encapsulation
- •Controlling Accessibility
- •Working with Constructors
- •Overloading Constructors
- •Understanding static Methods and Data
- •Creating a Shared Field
- •Creating a static Field by Using the const Keyword
- •Chapter 7 Quick Reference
- •Copying Value Type Variables and Classes
- •Understanding Null Values and Nullable Types
- •Using Nullable Types
- •Understanding the Properties of Nullable Types
- •Using ref and out Parameters
- •Creating ref Parameters
- •Creating out Parameters
- •How Computer Memory Is Organized
- •Using the Stack and the Heap
- •The System.Object Class
- •Boxing
- •Unboxing
- •Casting Data Safely
- •The is Operator
- •The as Operator
- •Chapter 8 Quick Reference
- •Working with Enumerations
- •Declaring an Enumeration
- •Using an Enumeration
- •Choosing Enumeration Literal Values
- •Choosing an Enumeration’s Underlying Type
- •Working with Structures
- •Declaring a Structure
- •Understanding Structure and Class Differences
- •Declaring Structure Variables
- •Understanding Structure Initialization
- •Copying Structure Variables
- •Chapter 9 Quick Reference
- •What Is an Array?
- •Declaring Array Variables
- •Creating an Array Instance
- •Initializing Array Variables
- •Creating an Implicitly Typed Array
- •Accessing an Individual Array Element
- •Iterating Through an Array
- •Copying Arrays
- •What Are Collection Classes?
- •The ArrayList Collection Class
- •The Queue Collection Class
- •The Stack Collection Class
- •The Hashtable Collection Class
- •The SortedList Collection Class
- •Using Collection Initializers
- •Comparing Arrays and Collections
- •Using Collection Classes to Play Cards
- •Chapter 10 Quick Reference
- •Using Array Arguments
- •Declaring a params Array
- •Using params object[ ]
- •Using a params Array
- •Chapter 11 Quick Reference
- •What Is Inheritance?
- •Using Inheritance
- •Base Classes and Derived Classes
- •Calling Base Class Constructors
- •Assigning Classes
- •Declaring new Methods
- •Declaring Virtual Methods
- •Declaring override Methods
- •Understanding protected Access
- •Understanding Extension Methods
- •Chapter 12 Quick Reference
- •Understanding Interfaces
- •Interface Syntax
- •Interface Restrictions
- •Implementing an Interface
- •Referencing a Class Through Its Interface
- •Working with Multiple Interfaces
- •Abstract Classes
- •Abstract Methods
- •Sealed Classes
- •Sealed Methods
- •Implementing an Extensible Framework
- •Summarizing Keyword Combinations
- •Chapter 13 Quick Reference
- •The Life and Times of an Object
- •Writing Destructors
- •Why Use the Garbage Collector?
- •How Does the Garbage Collector Work?
- •Recommendations
- •Resource Management
- •Disposal Methods
- •Exception-Safe Disposal
- •The using Statement
- •Calling the Dispose Method from a Destructor
- •Making Code Exception-Safe
- •Chapter 14 Quick Reference
- •Implementing Encapsulation by Using Methods
- •What Are Properties?
- •Using Properties
- •Read-Only Properties
- •Write-Only Properties
- •Property Accessibility
- •Understanding the Property Restrictions
- •Declaring Interface Properties
- •Using Properties in a Windows Application
- •Generating Automatic Properties
- •Initializing Objects by Using Properties
- •Chapter 15 Quick Reference
- •What Is an Indexer?
- •An Example That Doesn’t Use Indexers
- •The Same Example Using Indexers
- •Understanding Indexer Accessors
- •Comparing Indexers and Arrays
- •Indexers in Interfaces
- •Using Indexers in a Windows Application
- •Chapter 16 Quick Reference
- •Declaring and Using Delegates
- •The Automated Factory Scenario
- •Implementing the Factory Without Using Delegates
- •Implementing the Factory by Using a Delegate
- •Using Delegates
- •Lambda Expressions and Delegates
- •Creating a Method Adapter
- •Using a Lambda Expression as an Adapter
- •The Form of Lambda Expressions
- •Declaring an Event
- •Subscribing to an Event
- •Unsubscribing from an Event
- •Raising an Event
- •Understanding WPF User Interface Events
- •Using Events
- •Chapter 17 Quick Reference
- •The Problem with objects
- •The Generics Solution
- •Generics vs. Generalized Classes
- •Generics and Constraints
- •Creating a Generic Class
- •The Theory of Binary Trees
- •Building a Binary Tree Class by Using Generics
- •Creating a Generic Method
- •Chapter 18 Quick Reference
- •Enumerating the Elements in a Collection
- •Manually Implementing an Enumerator
- •Implementing the IEnumerable Interface
- •Implementing an Enumerator by Using an Iterator
- •A Simple Iterator
- •Chapter 19 Quick Reference
- •What Is Language Integrated Query (LINQ)?
- •Using LINQ in a C# Application
- •Selecting Data
- •Filtering Data
- •Ordering, Grouping, and Aggregating Data
- •Joining Data
- •Using Query Operators
- •Querying Data in Tree<TItem> Objects
- •LINQ and Deferred Evaluation
- •Chapter 20 Quick Reference
- •Understanding Operators
- •Operator Constraints
- •Overloaded Operators
- •Creating Symmetric Operators
- •Understanding Compound Assignment
- •Declaring Increment and Decrement Operators
- •Implementing an Operator
- •Understanding Conversion Operators
- •Providing Built-In Conversions
- •Creating Symmetric Operators, Revisited
- •Adding an Implicit Conversion Operator
- •Chapter 21 Quick Reference
- •Creating a WPF Application
- •Creating a Windows Presentation Foundation Application
- •Adding Controls to the Form
- •Using WPF Controls
- •Changing Properties Dynamically
- •Handling Events in a WPF Form
- •Processing Events in Windows Forms
- •Chapter 22 Quick Reference
- •Menu Guidelines and Style
- •Menus and Menu Events
- •Creating a Menu
- •Handling Menu Events
- •Shortcut Menus
- •Creating Shortcut Menus
- •Windows Common Dialog Boxes
- •Using the SaveFileDialog Class
- •Chapter 23 Quick Reference
- •Validating Data
- •Strategies for Validating User Input
- •An Example—Customer Information Maintenance
- •Performing Validation by Using Data Binding
- •Changing the Point at Which Validation Occurs
- •Chapter 24 Quick Reference
- •Querying a Database by Using ADO.NET
- •The Northwind Database
- •Creating the Database
- •Using ADO.NET to Query Order Information
- •Querying a Database by Using DLINQ
- •Creating and Running a DLINQ Query
- •Deferred and Immediate Fetching
- •Joining Tables and Creating Relationships
- •Deferred and Immediate Fetching Revisited
- •Using DLINQ to Query Order Information
- •Chapter 25 Quick Reference
- •Using Data Binding with DLINQ
- •Using DLINQ to Modify Data
- •Updating Existing Data
- •Adding and Deleting Data
- •Chapter 26 Quick Reference
- •Understanding the Internet as an Infrastructure
- •Understanding Web Server Requests and Responses
- •Managing State
- •Understanding ASP.NET
- •Creating Web Applications with ASP.NET
- •Building an ASP.NET Application
- •Understanding Server Controls
- •Creating and Using a Theme
- •Chapter 27 Quick Reference
- •Comparing Server and Client Validations
- •Validating Data at the Web Server
- •Validating Data in the Web Browser
- •Implementing Client Validation
- •Chapter 28 Quick Reference
- •Managing Security
- •Understanding Forms-Based Security
- •Implementing Forms-Based Security
- •Querying and Displaying Data
- •Understanding the Web Forms GridView Control
- •Displaying Customer and Order History Information
- •Paging Data
- •Editing Data
- •Updating Rows Through a GridView Control
- •Navigating Between Forms
- •Chapter 29 Quick Reference
- •What Is a Web Service?
- •The Role of SOAP
- •What Is the Web Services Description Language?
- •Nonfunctional Requirements of Web Services
- •The Role of Windows Communication Foundation
- •Building a Web Service
- •Creating the ProductsService Web Service
- •Web Services, Clients, and Proxies
- •Talking SOAP: The Easy Way
- •Consuming the ProductsService Web Service
- •Chapter 30 Quick Reference
Chapter 27 Introducing ASP.NET |
575 |
Understanding Server Controls
The Web forms controls you added to the form are collectively known as Server controls. Server controls are similar to the standard HTML items that you can use on an ordinary Web page except that they are more programmable. Most Server controls expose event handlers, methods, and properties that code running on the server can execute and modify dynamically at run time. In the following exercises, you will learn more about programming Server controls.
Examine a Server control
1.In the Design View window displaying EmployeeForm.aspx, click the Source button.
2.Examine the HTML code for the form. Look at the definition of the first Label control in more detail (the following code has been laid out to make it easier to read):
<asp:Label ID=”Label1” runat=”server” Font-Bold=”True” Font-Names=”Arial Black” Font-Size=”X-Large” Height=”36px”
Text=”Litware, Inc. Software Developers” Width=”630px” Style=”position: absolute; left: 96px; top: 24px”></asp:Label>
There are a couple of things to observe. First, look at the type the control is, asp:Label.
All Web forms controls live in the asp namespace because this is the way they are defined by Microsoft. The second noteworthy item is the runat=”server” attribute. This
attribute indicates that the control can be accessed by code running on the Web server. This code can query and change the values of any of the properties of this control (for example, change its text).
HTML Controls
ASP.NET also supports HTML controls. If you expand the HTML category in the Toolbox, you are presented with a list of controls. These are the controls that Microsoft supplied with the original ASP model. They are provided so that you can port existing ASP pages into ASP.NET more easily. However, if you are building a Web application from scratch, you should use the Standard Web Forms controls instead.
HTML controls also have a runat attribute so that you can specify where event handling code should be executed for these controls. Unlike Web forms controls, the default location for HTML controls to execute code is in the browser rather than on the server— assuming that the user’s browser supports this functionality.
576 Part VI Building Web Applications
The EmployeeForm.aspx page requires you to add the following functionality:
Populate the PositionRole drop-down list when the user selects a position (Worker, Boss, Vice President, President).
Save the information entered when the user clicks the Save button.
Clear the form when the user clicks the Clear button.
You will implement this functionality by writing event handlers.
Note The methods you will add in the following exercise use hard-coded values for the various roles and the jobs that they can perform. In a professional application, you should store this type of information in a database and use a technology such as ADO.NET or DLINQ to retrieve the various roles and their associated jobs from the database. You will see how to use DLINQ with an ASP.NET Web application in Chapter 29.
Handle Server control events
1.In Solution Explorer, expand the file EmployeeForm.aspx.
The file EmployeeForm.aspx.cs will appear. This is the file that will actually contain the C# code for the event handlers that you write. This file is known as a code-behind file. You can separate the C# code from the display logic for a Web application by us-
ing this feature of ASP.NET. (You can actually write C# code and event handlers in the EmployeeForm.aspx file by using the Source View window, but this approach is not recommended.)
2.In the Code and Text Editor window displaying the source view for EmployeeForm.aspx, examine the first line of the file. It contains the following text:
<%@ Page Language=”C#” ... CodeFile=”EmployeeForm.aspx.cs ... %>
The CodeFile directive specifies the file containing the program code for the Web form and the language in which it is written, in this case, C#. The other supported languages include Microsoft Visual Basic and JScript.
3.In Solution Explorer, double-click the EmployeeForm.aspx.cs file.
The file appears in the Code and Text Editor window. At the top of the file, there is a set of using statements. Note that this file makes heavy use of the System.Web namespace
and its subnamespaces—this is where the ASP.NET classes reside. Also, notice that the code itself is in a class called _Default that descends from System.Web.UI.Page; this is
the class from which all Web forms descend. Currently, it contains a single empty method called Page_Load. This method runs when the page is displayed. You can write code in this method to initialize any data required by the form.
Chapter 27 Introducing ASP.NET |
577 |
4. Add a method called initPositionRole to the _Default class after the Page_Load method:
private void initPositionRole()
{
}
You will invoke this method to initialize the positionRole drop-down list to its default set of values.
5. Add the following statements shown in bold type to the initPositionRole method:
private void initPositionRole()
{
positionRole.Items.Clear(); positionRole.Enabled = true; positionRole.Items.Add(“Analyst”); positionRole.Items.Add(“Designer”); positionRole.Items.Add(“Developer”);
}
The first statement clears the items from the drop-down list box. The second statement activates the list box. (You will write some code shortly that disables it under certain circumstances.) The remaining statements add the three roles that are applicable to workers.
6. Add the statements shown here in bold type to the Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
initPositionRole();
}
}
This block of code causes the positionRole drop-down list to be populated when the form appears in the user’s browser. However, it is important to understand that the Page_Load method runs every time the Web server sends the form to the user’s browser. For example, when the user clicks a button the form can be sent back to the Web server for processing; the Web server then responds by sending the form back to the browser for displaying when the processing has completed. You don’t want the initialization to be performed every time the page appears because it is a waste of process-
ing and can lead to performance problems if you are building a commercial Web site. You can determine whether the Page_Load method is running because this is the first time the page is being displayed by querying the IsPostBack property of the Web page. This property returns false the first time the page is displayed and true if the page is
being redisplayed because the user has clicked a control. In the code you added, you call the initPositionRole method only when the form is first displayed.
578 |
Part VI Building Web Applications |
7.Switch to the EmployeeForm.aspx file, and click the Design button. Select the Worker radio button. In the Properties window toolbar, click the Events toolbar button. (This button has a little lightning icon.) Double-click the CheckedChanged event. This event
occurs when the user clicks the radio button and its value changes. Visual Studio 2008 generates the method workerButton_CheckedChanged to handle this event.
Note The Properties window of an ASP.NET Web application provides additional features not currently available when you build a WPF application. These features include being able to list the events available for a control and specify an event handler. When you create a WPF application, this functionality is available only when you edit the Extensible Application Markup Language (XAML) code for a control.
8.In the Code and Text Editor window, add the statement shown here in bold type to the workerButton_CheckedChanged event method:
protected void workerButton_CheckedChanged(object sender, EventArgs e)
{
initPositionRole();
}
Remember that the default values for the positionRole drop-down list are those for a worker, so the same method can be reused to initialize the list.
9.Switch to the Design View window displaying the EmployeeForm.aspx form. Select the Boss radio button, and use the Properties window to create an event method called bossButton_CheckedChanged for the CheckedChanged event. When the form is displayed in the Code and Text Editor window, type the following statements in the
BossCheckedChanged method:
protected void bossButton_CheckedChanged(object sender, EventArgs e)
{
positionRole.Items.Clear(); positionRole.Enabled = true; positionRole.Items.Add(“General Manager”); positionRole.Items.Add(“Project Manager”);
}
These are the roles that a manager can fulfill.
10.Return to the Design View window displaying the EmployeeForm.aspx form, and create an event handler for the CheckedChanged event for the Vice President radio button. In the Code and Text Editor window, add the following statements shown in bold type to the vpButton_CheckedChanged event method:
protected void vpButton_CheckedChanged(object sender, EventArgs e)
{
positionRole.Items.Clear(); positionRole.Enabled = true;
Chapter 27 Introducing ASP.NET |
579 |
positionRole.Items.Add(“VP Sales”); positionRole.Items.Add(“VP Marketing”); positionRole.Items.Add(“VP Production”); positionRole.Items.Add(“VP Human Resources”);
}
11.Switch to the Design View window displaying the EmployeeForm.aspx form, and create an event handler for the CheckedChanged event for the President radio button. Add the code shown here in bold type to the presidentButton_CheckedChanged event method:
protected void presidentButton_CheckedChanged(object sender, EventArgs e)
{
positionRole.Items.Clear(); positionRole.Enabled = false;
}
Roles do not apply to the president of the company, so the drop-down list is cleared and disabled.
12.Return to the Design View window displaying the EmployeeForm.aspx form, and create an event handler for the Click event of the Save button. The method would usually save
the information to a database, but to keep this application simple, the method will just echo some of the data in the InfoLabel control instead. Add the following statements shown in bold type to the saveButton_Click method:
protected void saveButton_Click(object sender, EventArgs e)
{
String position = “”;
if (workerButton.Checked) position = “Worker”;
if (bossButton.Checked) position = “Manager”;
if (vpButton.Checked)
position = “Vice President”; if (presidentButton.Checked)
position = “President”;
infoLabel.Text = “Employee: ” + firstName.Text + “ ” + lastName.Text + “    Id: ” + employeeID.Text + “    Position: ” + position;
}
The   character is a nonbreaking space in HTML; ordinary white-space characters after the first white-space character will usually be ignored by the browser.
13.Using the same technique, create an event method for the Click event of the Clear button. Add the following block of code shown in bold type to this method:
protected void clearButton_Click(object sender, EventArgs e)
{
firstName.Text = “”; lastName.Text = “”;
580 |
Part VI Building Web Applications |
employeeID.Text = “”; workerButton.Checked = true; bossButton.Checked = false; vpButton.Checked = false; presidentButton.Checked = false; initPositionRole(); infoLabel.Text = “”;
}
This code clears the information entered by the user and then resets the role to Worker (the default value).
Note Although only one radio button in a group can have its Checked property set to true, it is necessary to set the Checked property of the remaining radio buttons to false to
ensure that the correct button is displayed as being selected when ASP.NET refreshes the form in the user’s Web browser.
Test the Web form again
1.On the Debug menu, click Start Debugging to run the Web form again.
2.When the Web form appears in Internet Explorer, type an employee’s name, enter an ID number (make them up), and then click the Role drop-down list.
The list of roles for a worker is displayed.
3.Change the position of your fictitious employee to Vice President, and then click the Role drop-down list box.
Notice that the list has not changed and still displays the roles for a worker. The list hasn’t changed because the CheckedChanged event for the Vice President radio button has not been raised.
4.Close Internet Explorer, and return to Visual Studio 2008.
5.Display the EmployeeForm.aspx Web form in the Design View window, and then select the worker-Button radio button. In the Properties window, set the AutoPostBack property to True.
Tip If the Properties window is still displaying the list of events for the radio button, click the Properties button next to the Events button on the Properties window toolbar.
Chapter 27 Introducing ASP.NET |
581 |
When the user clicks this radio button, the form will be sent back to the server for processing, the CheckedChanged event will fire, and the form can be updated to display the roles for this radio button. By default, the AutoPostBack property is set to False to
avoid unnecessary network traffic.
6.Set the AutoPostBack property to True for the other radio buttons: bossButton, vpButton, and presidentButton.
7.Run the Web form again.
This time you will find that when you click the radio buttons, there is a slight flicker while the form is submitted to the server, the event handler runs, the drop-down list is populated, and the form is displayed again.
8.On the Internet Explorer toolbar, click the Page drop-down list, and then click View Source to display the source of the HTML page being displayed in the browser.
Note If the Internet Explorer Security message box appears, click Allow so that you can view the source file for the page.
Notepad starts and displays the HTML source for the page. Notice that there is no mention of any “asp:” Server controls in this file and no C# code. Instead, the Server controls and their contents have been converted to the equivalent HTML controls (and some JavaScript). This is one of the basic features of the Server controls—you access them programmatically like ordinary .NET Framework objects, with methods, properties, and events. When they are rendered by the Web server, they are converted to HTML so that you can display the form in any HTML-compliant browser.
9.When you have finished examining the file, close Notepad.
10.On the Web form, click Save.
The InfoLabel control displays the details of the new employee. If you examine the source, you will see that the HTML for the InfoLabel control (rendered as an HTML span with an ID of “InfoLabel”) contains this text.
11.Click Clear.
The form resets to its default values.
12.Close Internet Explorer, and return to Visual Studio 2008.
