Lập trình ứng dụng nâng cao (phần 9) potx - Pdf 17

382
|
Chapter 17: Programming ASP.NET Applications
Web Forms implement a programming model in which web pages are dynamically
generated on a web server for delivery to a browser over the Internet. With Web
Forms, you create an ASPX page with more or less static content consisting of
HTML and web controls, as well as AJAX and Silverlight, and you write C# code to
add additional dynamic content. The C# code runs on the server for the standard
ASPX event handlers and on the client for the Silverlight event handlers (JavaScript is
used for standard AJAX event handlers), and the data produced is integrated with
the declared objects on your page to create an HTML page that is sent to the
browser.
You should pick up the following three critical points from the preceding paragraph
and keep them in mind for this entire chapter:
• Web pages can have both HTML and web controls (described later).
• Processing may be done on the server or on the client, in managed code or in
unmanaged code, or via a combination.
• Typical ASP.NET controls produce standard HTML for the browser.
Web Forms divide the user interface into two parts: the visual part or user interface
(UI), and the logic that lies behind it. This is called code separation; and it is a good
thing.
From version 2.0 of ASP.NET, Visual Studio takes advantage of par-
tial classes, allowing the code-separation page to be far simpler than it
was in version 1.x. Because the code-separation and declarative pages
are part of the same class, there is no longer a need to have protected
variables to reference the controls of the page, and the designer can
hide its initialization code in a separate file.
The UI page for ASP.NET pages is stored in a file with the extension .aspx. When
you run the form, the server generates HTML sent to the client browser. This code
uses the rich Web Forms types found in the
System.Web and System.Web.UI

void and take two parameters. The
first parameter represents the object raising the event. The second, called the event
argument, contains information specific to the event, if any. For most events, the
event argument is of type
EventArgs, which doesn’t expose any properties. For some
controls, the event argument might be of a type derived from
EventArgs that can
expose properties specific to that event type.
In web applications, most events are typically handled on the server and, therefore,
require a round trip. ASP.NET supports only a limited set of events, such as button
clicks and text changes. These are events that the user might expect to cause a signif-
icant change, as opposed to Windows events (such as mouse-over) that might
happen many times during a single user-driven task.
Postback versus nonpostback events
Postback events are those that cause the form to be posted back to the server imme-
diately. These include click-type events, such as the button
Click event. In contrast,
many events (typically change events) are considered nonpostback in that the form
isn’t posted back to the server immediately. Instead, the control caches these events
until the next time a postback event occurs.
You can force controls with nonpostback events to behave in a post-
back manner by setting their
AutoPostBack property to true.
384
|
Chapter 17: Programming ASP.NET Applications
State
A web application’s state is the current value of all the controls and variables for the
current user in the current session. The Web is inherently a “stateless” environment.
This means that every post to the server loses the state from previous posts, unless

the
LoadViewState( ) method. This allows ASP.NET to manage the state of your
control across page loads so that each control isn’t reset to its default state each
time the page is posted.
Process Postback Data
During this phase, the data sent to the server in the posting is processed. If any
of this data results in a requirement to update the
ViewState, that update is per-
formed via the
LoadPostData( ) method.
Creating a Web Form
|
385
Load
CreateChildControls( ) is called, if necessary, to create and initialize server
controls in the control tree. State is restored, and the form controls contain
client-side data. You can modify the load phase by handling the
Load event with
the
OnLoad( ) method.
Send Postback Change Modifications
If there are any state changes between the current state and the previous state,
change events are raised via the
RaisePostDataChangedEvent( ) method.
Handle Postback Events
The client-side event that caused the postback is handled.
PreRender
This is your last chance to modify the output prior to rendering, using the
OnPreRender( ) method.
Save State

Chapter 17: Programming ASP.NET Applications
Although Visual Studio no longer uses projects for web applications, it
does keep solution files to allow you to quickly return to a web site or
desktop application you’ve been developing. The solution files are
kept in a directory you can designate through the Tools
➝ Options
window, as shown in Figure 17-2.
Code-Behind Files
Let’s take a closer look at the .aspx and code-behind files that Visual Studio creates.
Start by renaming Default.aspx to HelloWeb.aspx. To do this, close Default.aspx and
then right-click its name in the Solution Explorer. Choose Rename, and enter the
name
HelloWeb.aspx. That renames the file, but not the class. To rename the class,
right-click the .aspx page, choose View Code in the code page, and then rename the
class
HelloWeb_aspx. You’ll see a small line next to the name. Click it, and you’ll open
the smart tag that allows you to rename the class. Click “Rename ‘_Default’ to
‘HelloWeb_aspx’” and Visual Studio ensures that every occurrence of
Default_aspx
is replaced with its real name, as shown in Figure 17-3.
Within the HTML view of HelloWeb.aspx, you see that a form has been specified in
the body of the page using the standard HTML form tag:
<form id="form1" runat="server">
Figure 17-1. Creating your new web application
Creating a Web Form
|
387
Web Forms assume that you need at least one form to manage the user interaction,
and it creates one when you open a project. The attribute
runat="server" is the key

between them (in this case, C#). The
= sign immediately following the opening tag
causes ASP.NET to display the value, just like a call to
Response.Write( ). You could
just as easily write the line as:
Hello World! It is now
<% Response.Write(DateTime.Now.ToString( )); %>
Run the page by pressing F5.
Adding Controls
You can add server-side controls to a Web Form in three ways: by writing HTML into
the HTML page, by dragging controls from the toolbox to the Design page, or by
programmatically adding them at runtime. For example, suppose you want to use
buttons to let the user choose one of three shippers provided in the Northwind data-
base. You can write the following HTML into the
<form> element in the HTML
window:
<asp:RadioButton GroupName="Shipper" id="Speedy"
text = "Speedy Express" Checked="True" runat="server">
</asp:RadioButton>
<asp:RadioButton GroupName="Shipper" id="United"
text = "United Package" runat="server">
Enabling Debugging
When you press F5, you begin the debugger. It’s likely that Visual Studio will notice
that debugging is not enabled in the Web.config file for this application, and the
Debugging Not Enabled dialog box will appear, as shown in Figure 17-4.
The default in this dialog box is to modify (and, if needed, create) the Web.config file.
Go ahead and click OK to enable debugging for your application.
Creating a Web Form
|
389

|
Chapter 17: Programming ASP.NET Applications
Figure 17-5. List item collection
Figure 17-6. Using properties and styles
Data Binding
|
391
The tag indications (provided automatically at the bottom of the window) show us
our location in the document; specifically, inside a ListItem, within the
ListBox
which is inside a div which itself is inside form1. Very nice.
Server Controls
Web Forms offer two types of server-side controls. The first is server-side HTML
controls. These are HTML controls that you tag with the attribute
runat=Server.
The alternative to marking HTML controls as server-side controls is to use ASP.NET
Server Controls, also called ASP controls or web controls. ASP controls have been
designed to augment and replace the standard HTML controls. ASP controls pro-
vide a more consistent object model and more consistently named attributes. For
example, with HTML controls, there are myriad ways to handle input:
<input type="radio">
<input type="checkbox">
<input type="button">
<input type="text">
<textarea>
Each behaves differently and takes different attributes. The ASP controls try to nor-
malize the set of controls, using attributes consistently throughout the ASP control
object model. Here are the ASP controls that correspond to the preceding HTML
server-side controls:
<asp:RadioButton>

Form DisplayShippers.aspx.
From the toolbox, drag a
RadioButtonList onto the new form, either onto the design
pane, or within the
<div> in the Source view.
If you don’t see the radio buttons on the left of your work space, try
clicking on View
➝ Toolbox to open the toolbox, and then clicking on
the Standard tab of the toolbox. Right-click on any control in the tool-
box, and choose Sort Items Alphabetically.
In the Design pane, click on the new control’s smart tag. Then, select Choose Data
Source. The Choose a Data Source dialog opens, as shown in Figure 17-7.
Figure 17-7. Choose a Data Source dialog
Data Binding
|
393
Drop down the “Select a data source” menu and choose <New Data Source>. You
are then prompted to choose a data source from the datatypes on your machine.
Select Database, assign it an ID, and click OK. The Configure Data Source dialog
box opens, as shown in Figure 17-8.
Choose an existing connection, or in this case, choose New Connection to configure
a new data source, and the Add Connection dialog opens.
Fill in the fields: choose your server name, how you want to log in to the server (if in
doubt, choose Windows Authentication), and the name of the database (for this
example, Northwind). Be sure to click Test Connection to test the connection. When
everything is working, click OK, as shown in Figure 17-9.
After you click OK, the connection properties will be filled in for the Configure Data
Source dialog. Review them, and if they are OK, click Next. On the next wizard
page, name your connection (e.g.,
NorthWindConnectionString) if you want to save it

Choose View
➝ Source, and you’ll see that what is being sent to the browser is sim-
ple HTML, as shown in Example 17-1.
Figure 17-10. Configuring the Select statement
396
|
Chapter 17: Programming ASP.NET Applications
Figure 17-11. Testing the query
Figure 17-12. Binding radio buttons to the data source
Data Binding
|
397
Figure 17-13. The Radio Button list with the data control
Example 17-1. HTML Source view
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " />xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns=" /><head><title>
Display Shippers
</title>
<style type="text/css">
.RadioButtonStyle
{
font-family: Verdana;
font-size: medium;
font-weight: normal;
font-style: normal;
border: medium groove #FF0000;
}
</style>
398
|

name="RadioButtonList1" value="2" />
<label for="RadioButtonList1_1">United Package</label></td>
</tr>
<tr>
<td><input id="RadioButtonList1_2" type="radio"
name="RadioButtonList1" value="3" />
<label for="RadioButtonList1_2">Federal Shipping</label></td>
</tr>
</table>
</div>
<div>
<input type="hidden" name="_ _EVENTVALIDATION" id="_ _EVENTVALIDATION"
value="/wEWBQLIyMfLBQL444i9AQL544i9AQL644i9AQL3jKLTDcEXOHLsO/LFFixl7k4g2taGl6Qy" />
</div></form>
</body>
</html>
Example 17-1. HTML Source view (continued)
Data Binding
|
399
Adding Controls and Events
By adding just a few more controls, you can create a complete form with which users
can interact. You will do this by adding a more appropriate greeting (“Welcome to
NorthWind”), a text box to accept the name of the user, two new buttons (Order
and Cancel), and text that provides feedback to the user. Figure 17-14 shows the fin-
ished form.
This form won’t win any awards for design, but its use will illustrate a number of key
points about Web Forms.
I’ve never known a developer who didn’t think he could design a per-
fectly fine UI. At the same time, I never knew one who actually could.

<body>
<form id="form1" runat="server">
<table style="width: 300px; height: 33px">
<tr>
<td colspan="2" style="height: 20px">Welcome to NorthWind</td>
</tr>
<tr>
<td>Your name:</td>
<td><asp:TextBox ID="txtName" Runat=server></asp:TextBox></td>
</tr>
<tr>
<td>Shipper:</td>
<td>
<asp:RadioButtonList ID="rblShippers" runat="server"
DataSourceID="SqlDataSource1" DataTextField="CompanyName"
DataValueField="ShipperID">
</asp:RadioButtonList>
</td>
</tr>
<tr>
<td><asp:Button ID="btnOrder" Runat=server Text="Order"
onclick="btnOrder_Click" /></td>
<td><asp:Button ID="btnCancel" Runat=server Text="Cancel" /></td>
</tr>
<tr>
<td colspan="2"><asp:Label id="lblMsg" runat=server></asp:Label></td>
</tr>
</table>
Data Binding
|

}
This sets the RadioButtonList’s first radio button to Selected. The problem with this
solution is subtle. If you run the application, you’ll see that the first button is
selected, but if you choose the second (or third) button and click OK, you’ll find that
the first button is reset. You can’t seem to choose any but the first selection. This is
because each time the page is loaded, the
OnLoad event is run, and in that event han-
dler you are (re-)setting the selected index.
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [ShipperID], [CompanyName] FROM [Shippers]">
</asp:SqlDataSource>
</form>
</body>
</html>
Example 17-2. The .aspx file (continued)
402
|
Chapter 17: Programming ASP.NET Applications
The fact is that you only want to set this button the first time the page is selected, not
when it is posted back to the browser as a result of the OK button being clicked.
To solve this, wrap the setting in an
if statement that tests whether the page has
been posted back:
protected override void OnLoad(EventArgs e)
{
if (!IsPostBack)
{
rblShippers.SelectedIndex = 0;
}

}
404
Chapter 18
CHAPTER 18
Programming WPF Applications 18
Microsoft currently offers two ways to create desktop applications: Windows Forms
(the technology in use since .NET 1.0) and Windows Presentation Foundation, or
WPF (new to .NET 3.5).
It is useful to see that regardless of the technology involved, the C# is very much the
same, so I will cover WPF in this chapter and Windows Forms in the next.
In this chapter, I’ll show you how to create a relatively straightforward (though non-
trivial) WPF application with C# event handlers. In the next chapter, I’ll show you
another nontrivial application, written in Windows Forms, and again, we’ll use C#
to implement the event handlers.
Everything about the two applications will be different, except for the C#; the lan-
guage remains unchanged whether you are writing WPF, Windows Forms, ASP.
NET, or Silverlight.
WPF in a Very Small Nutshell
It isn’t possible or reasonable to teach all of WPF in a single chapter,
and I won’t try. For a more reasonable introduction, please see Pro-
gramming .NET 3.5 by myself and Alex Horovitz (O’Reilly), and for a
complete and comprehensive review of WPF please see the truly won-
derful Programming WPF by Ian Griffiths and Chris Sells (O’Reilly),
which may be one of the best technical books I’ve ever read.
WPF is written, in large part, using a declarative language: XAML (pronounced
zamel, to rhyme with camel). XAML stands for eXtensible Application Markup Lan-
guage, which is a dialect of the industry-standard XML and thus is easily read and
manipulated by tools such as Visual Studio.
WPF in a Very Small Nutshell
|

dler, and we’ll reach into the control and place the president’s name into the title bar
of the control.
Figure 18-1 shows the result of scrolling to the 16th president and clicking on the
image. Note that the name of the president is displayed in the title bar, and that the
image of President Lincoln is both larger and brighter than the surrounding images.
406
|
Chapter 18: Programming WPF Applications
Building the Application
To create this application, open Visual Studio 2008, and select Create ➝ Project. In
the New Project dialog select .NET Framework 3.5, and choose Visual C# in the
Project Types window and WPF Application in the Templates window. Select a
location for your program and give your program a name (I’ll be naming mine Presi-
dential Browser), as shown in Figure 18-2.
Visual Studio will create a starter application with a window, inside of which it will
place an empty grid. It will present you with a split window, with the designer on
top, and the XAML on the bottom. We can work with this (we’re easy).
Because we know that we want two items in our grid—the text block that says
“United States Presidents” and our sideways listbox of photographs—we can make a
start at a layout.
Grids and Stack Panels
Two of the layout objects WPF provides are stack panels and grids (not to be con-
fused with data grids!). A stack panel lets you stack a set of objects one on top of (or
next to) another set of objects. That turns out to be very useful.
At times, you’d like to set up a stack that is both horizontal and vertical—essentially
a table, which is what a grid is for. A grid has columns and rows, both counting from
zero.
We’ll create a simple grid of two rows and one column, and inside each row, we’ll
place a stack panel. The top stack panel will hold the text, and the bottom stack
panel will hold the listbox that will, in turn, hold the photos. (Don’t panic! We’ll


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status