1. Trang chủ
  2. » Công Nghệ Thông Tin

Professional Visual Basic 2010 and .neT 4 phần 7 pot

133 312 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 133
Dung lượng 5,85 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The settings used to create the content page in the sample project are shown in Figure 22-4.. Select the MasterPage.master page and click OK.The page created should have one Content cont

Trang 1

creating the content Page

Now that you have a master page you can start creating content pages associated with it To create a content page, right-click on the solution in the Solution Explorer and select Add New Item Select the Web Form template, and check the Select master page check box The settings used to create the content page in the sample project are shown in Figure 22-4 Clicking the Add button brings up a dialog that enables you to select a master page to associate with this new file, as shown in Figure 22-5

figure 22-4

figure 22-5

Master Pages ❘ 755

Trang 2

In this case you should only have a single master page available in the dialog, though it is possible to have as many master pages as you wish in a single project Select the MasterPage.master page and click OK.The page created should have one Content control for each of the ContentPlaceHolder controls in the selected master page:

<%@ Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" %>

There isn’t much to show while in the Source view of Visual Studio when looking at a content page; the real power of master pages can be seen when you work with the page in the designer by switching to the Design

or Split view (see Figure 22-6)

figure 22-6

This view shows you the entire template and the two content areas that can contain server controls All the grayed-out areas are off-limits and do not allow for any changes from the content page, whereas the available areas allow you to deal with any type of content you wish For instance, not only can you place

Trang 3

raw text in these content areas, you can also add anything that you would normally place into a typical aspx page The page in the sample application includes a simple form as shown below If you’re following along you can use the Design or Source view to build a similar user interface If you want to build an identical interface you will need to get the wrox.jpg file from the sample code included with the book and put it in a folder named Images in your project.

<%@ Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" %>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">

<b>Enter in your name:<br />

<asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox>

<asp:Button ID="Button1" Runat="server" Text="Submit" OnClick="Button1_Click" />

<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">

<asp:Image ID="Image1" Runat="server" ImageUrl="~/Images/wrox.jpg" />

</asp:Content>

Code snippet from Default.aspx

Just as with typical aspx pages, you can create any event handlers you may need for your content page This particular example uses a button-click event for when the end user submits the form Running this example produces the results shown in Figure 22-7

figure 22-7

Master Pages ❘ 757

Trang 4

Providing default content in your master Page

Earlier, you saw how to use a basic ContentPlaceHolder control In addition to using it as shown, you can also create ContentPlaceHolder controls that contain default content:

<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">

Here is some default content!

</asp:ContentPlaceHolder>

For default content, you can again use whatever you want, including any other ASP.NET server controls

A content page that uses a master page containing one of these ContentPlaceHolder controls can then either override the default content — by just specifying other content (which overrides the original content declared in the master page) — or keep the default content contained in the control

naVigaTion

Developers rarely build single-page Web applications Instead, applications are usually made up of multiple pages that are related to each other in some fashion Some applications have a workflow through which end users can work from page to page, while other applications have a navigation structure that allows for free roaming throughout the pages Sometimes the navigation structure of a site becomes complex, and managing this complexity can be rather cumbersome

ASP.NET includes a way to manage the navigational structure of your Web applications by defining it

in an XML file and then binding the XML data to server controls focused on navigation You maintain your navigational structure in a single file, and the data-binding mechanism ensures that any changes are instantaneously reflected throughout your application

The sample projects included with the book contain a Web site project named Navigation You can open this project and follow along with the existing code or you can build your own project as we go

The first step in working with the ASP.NET navigation system is to create a sitemap file, the XML file that will contain the complete site structure For instance, suppose you want the following navigation:

Home Books Magazines U.S Magazines European MagazinesThis site structure has three levels to it, with multiple items in the lowest level You can reflect this in the web.sitemap file as follows:

<?xml version="1.0" encoding="utf-8" ?>

<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >

<siteMapNode url="default.aspx" title="Home"

description="The site homepage">

<siteMapNode url="books.aspx" title="Books"

description="Books from our catalog" />

<siteMapNode url="magazines.aspx" title="Magazines"

description="Magazines from our catalog">

<siteMapNode url="magazines_us.aspx" title="U.S Magazines"

description="Magazines from the U.S." />

<siteMapNode url="magazines_eur.aspx" title="European Magazines"

description="Magazines from Europe" />

</siteMapNode>

</siteMapNode>

</siteMap>

Code snippet from Web.sitemap

To create a sitemap file in Visual Studio, go to the Add New Item dialog and select the Site Map option You can place the preceding content in this file To move a level down in the hierarchy, nest <siteMapNode>

Trang 5

elements within other <siteMapNode> elements A <siteMapNode> element can contain several different attributes, as defined in Table 22-1.

TaBle 22-1: siteMapNode Element Attributes

aTTriBuTe descriPTion

Title Provides a textual description of the link The String value used here is the text used

for the link Description This attribute not only reminds you what the link is for, it is also used for the ToolTip

attribute on the link The ToolTip attribute is the yellow box that appears next to the link when the user hovers the cursor over the link for a couple of seconds

Url Describes where the file is located in the solution If the file is in the root directory, then

simply use the filename, such as default.aspx If the file is located in a subfolder, then be sure to include the folders in the String value used for this attribute, e g , MySubFolder/MyFile.aspx

Roles If ASP NET security trimming is enabled, you can use the Roles attribute to define which

roles are allowed to view and click the provided link in the navigation

figure 22-8

using the sitemapPath server control

One of the available server controls that can bind to a site map is the SiteMapPath control This control

provides a popular structure found on many Internet websites Sometimes called breadcrumb navigation,

this feature is simple to implement in ASP.NET

To see an example of this control at work, we’ll need a page that would be at the bottom of the site map

structure Within the project that contains your site map file, create a Web Form named magazines_us.aspx

(this page name is included in the site map file) and drag and drop a SiteMapPath control from the Navigation section of the Toolbox onto it This control’s markup looks as follows:

<asp:SiteMapPath ID="SiteMapPath1" runat="server"></asp:SiteMapPath>

What else do you need to do to get this control to work? Nothing Simply build and run the page to see the results shown in Figure 22-8

The SiteMapPath control defines the end user’s place in the application’s site structure It shows the current page the user is on (U.S Magazines), as well as the two pages above it in the hierarchy

The SiteMapPath control requires no DataSource control, as it automatically binds itself to any sitemapfile it finds in the project; nothing is required on your part to make this happen The SiteMapPath’s smart

navigation ❘ 759

Trang 6

tag enables you to customize the control’s appearance too, so you can produce other results, as shown

in Figure 22-9

figure 22-9

The code for this version of the SiteMapPath control is as follows:

<asp:SiteMapPath ID="SiteMapPath1" runat="server" Font-Names="Verdana"

Font-Size="0.8em" PathSeparator=" : " >

<CurrentNodeStyle ForeColor="#333333" />

<NodeStyle Font-Bold="True" ForeColor="#284E98" />

<PathSeparatorStyle Font-Bold="True" ForeColor="#507CD1" />

<RootNodeStyle Font-Bold="True" ForeColor="#507CD1" />

</asp:SiteMapPath>

Code snippet from magazines_us.aspx

This example illustrates that a lot of style elements and attributes can be used with the SiteMapPathcontrol Many options at your disposal enable you to create breadcrumb navigation that is unique

menu server control

Another navigation control enables end users of your application to navigate throughout the pages based upon information stored within the web.sitemap file The Menu server control produces a compact

navigation system that pops up sub-options when the user hovers the mouse over an option The result of the Menu server control when bound to the site map is shown in Figure 22-10

figure 22-10

To see this, examine the Web Form named magazines_eur.aspx It has both a Menu and a SiteMapDataSourcecontrol on the page:

Trang 7

<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />

<asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1">

</asp:Menu>

Code snippet from magazines_eur.aspx

The SiteMapDataSource control automatically works with the application’s web.sitemap file and the Menu control to bind to the SiteMapDataSource (just like a GridView can bind to a SqlDataSource) Like many of the other visual controls in ASP.NET, you can easily modify the appearance of the Menu control

by clicking the Auto Format link in the control’s smart tag Choosing Classic produces the result shown in Figure 22-11

figure 22-11

As with the other controls, a lot of sub-elements contribute to the changed look of the control’s style:

<asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1"

BackColor="#B5C7DE" DynamicHorizontalOffset="2" Font-Names="Verdana"

Font-Size="0.8em" ForeColor="#284E98" StaticSubMenuIndent="10px">

<DynamicHoverStyle BackColor="#284E98" ForeColor="White" />

<DynamicMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />

<DynamicMenuStyle BackColor="#B5C7DE" />

<DynamicSelectedStyle BackColor="#507CD1" />

<StaticHoverStyle BackColor="#284E98" ForeColor="White" />

<StaticMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />

<StaticSelectedStyle BackColor="#507CD1" />

</asp:Menu>

Code snippet from magazines_eur.aspx

WorKing WiTh The asP.neT ProVider model

Ever since the beginning days of ASP.NET, users wanted to be able to store sessions by means other than the three traditional storage modes: InProc, StateServer, and SQLServer One such request was for a new storage mode that could store sessions in an Oracle database This might seem like a logical thing to add, but if the team added a storage mode for Oracle they would soon get requests to add additional modes for other databases and data storage methods For this reason, instead of building storage modes for specific

scenarios, the ASP.NET team made the system extensible by designing a plugable provider model that

enables anyone to add new modes as needed

In addition to session state, there are several other features included in ASP.NET that require state storage of some kind In addition, instead of recording state in a fragile mode (the way sessions are stored

by default), many of these features require their state to be stored in more concrete data stores such as databases or XML files This also enables a longer-lived state for the users visiting an application — something else that is required by these new systems

Working with the asP.neT Provider Model ❘ 761

Trang 8

The features found in ASP.NET today that require advanced state management include the following:Membership

➤Role management

➤Site navigation

➤Personalization

➤Health-monitoring Web events

➤Web parts personalization

➤Configuration file protection

➤For each of the features one or more providers are available by default to define the way the state of that system is recorded Figure 22-12 illustrates these providers

DPAPIProtectedConfigurationProvider

SqlPersonalizationProvider

SqlMembershipProvider ActiveDirectoryMembershipProvider

AuthorizationRoleMembershipProvider

SqlRoleProvider WindowsTokenRoleProvider

XmlSiteMapProvider

SqlProfileProvider

RSAProtectedConfigurationProvider

WmiWebEventProvider TraceWebEventProvider SqlWebEventProvider TemplatedMailWebEventProvider

SimpleMailWebEventProvider

EventLogWebEventProvider

SqlSessionStateStore OutOfProcSessionStateStore InProcSessionStateStore

ASP.NET Role WebEvents

WebParts Configuration Membership

SiteMap SessionState

Profile

figure 22-12

The next section describes how to set up SQL Server to work with several of the providers presented in this chapter You can use SQL Server 7.0, 2000, 2005, or 2008 for the back-end data store for many of the providers presented (although not all of them)

creating an application services database

The instructions in this section and the next assume you have a SQL Server 2005 or 2008 Express instance named SqlExpress If you have differently named instances available, you will need to modify the connection strings shown accordingly If you do not have SQL Server at all, the easiest way to get the Express version is to use Microsoft’s Web Platform Installer (www.microsoft.com/web/downloads/platform.aspx)

There are two mechanisms you can use to create an application services database Let Visual Studio or another NET framework tool do it for you, or do it yourself

Trang 9

The first option is only available when you have configured your application to use a local (or user instance) database for application services Unfortunately the tools are inconsistent, sometimes the database will be created automatically, and sometimes you will need to create it We’ll see two examples where the database

is created automatically in this chapter: by Visual Studio when we add profile properties to an application, and by the Web Site Administration Tool when we configure membership and role information

To create the database explicitly, you can use a tool named aspnet_regsql.exe that comes with the NET Framework This tool can create the necessary tables, roles, stored procedures, and other items needed

by the providers To access this tool, open the Visual Studio 2010 command prompt by selecting Start ➪ All Programs ➪ Microsoft Visual Studio 2010 ➪ Visual Studio Tools ➪ Visual Studio Command Prompt (2010) Make sure you run the command prompt as administrator You will likely need the additional privilege to be able to create the application services database With the command prompt open, you can access aspnet_regsql.exe, which can be run as a command-line tool or a GUI interface

The asP.neT sQl server setup Wizard Command-line Tool

The command-line version gives developers optimal control over how the database is created Working from the command line using this tool is not difficult, so don’t be intimidated by it

At the command prompt, type aspnet_regsql.exe -? to get a list of all the command-line options at your

disposal for working with this tool

Table 22-2 describes some of the available options for setting up your SQL Server instance to work with the ASP.NET application services

TaBle 22-2: Frequently Used Setup Wizard Command-Line Options

command oPTion descriPTion

-W Uses the Wizard mode This is the default if no other parameters are used

-S <server> Specifies the SQL Server instance to work with -U <login> Specifies the username for logging in to SQL Server If you use this, then you also use

the -P command

-P <password> Specifies the password to use for logging in to SQL Server If you use this, then you also

use the -U command -E Provides instructions for using the current Windows credentials for authentication -C Specifies the connection string for connecting to SQL Server If you use this, then you

don’t need to use the -U and -P commands because they are specified in the tion string itself

connec A all Adds support for all the available SQL Server operations provided by ASP NET, including

membership, role management, profiles, site counters, and page/control personalization

_R all Removes support for all the available SQL Server operations that have been previously

installed These include membership, role management, profiles, site counters, and page/control personalization

-R p Removes support for the profile capability from SQL Server

-d <database> Specifies the database name to use with the application services If you don’t specify a

database name, then aspnetdb is used -sqlexportonly

<filename>

Instead of modifying an instance of a SQL Server database, use this command in conjunction with the other commands to generate a SQL script that adds or removes the features speci-fied This command creates the scripts in a file that has the name specified in the command

Working with the asP.neT Provider Model ❘ 763

Trang 10

figure 22-13

figure 22-14

One advantage of using the command-line tool, rather than the GUI-based version of the ASP.NET SQL Server Setup Wizard, is that you can install in the database just the features you’re interested in working with, instead of installing everything (as the GUI-based version does) For instance, if you want only the membership system to interact with SQL Server — not any of the other systems (such as role management and personalization) — then you can configure the setup so that only the tables, roles, stored procedures, and other items required by the membership system are established in the database

The asP.neT sQl server setup Wizard GUi Tool

To access the GUI version, type the following at the Visual Studio command prompt:

aspnet_regsql.exe

At this point, the ASP.NET SQL Server Setup Wizard welcome screen appears, as shown in Figure 22-13.Clicking the Next button gives you a new screen that offers two options: one to configure SQL Server for application services and the other to remove existing tables used by the application services (see Figure 22-14)

Trang 11

From here, choose Configure SQL Server for application services and click Next The third screen (see Figure 22-15) asks for the login credentials to SQL Server and the name of the database to perform the operations The Database option is <default> — meaning the wizard creates a database called aspnetdb If you want to add application services to an existing database you can select it from the drop-down at the bottom on the page.

figure 22-15

figure 22-16

After you have made your server and database selections, click Next The screen shown in Figure 22-16 asks you to confirm your settings If everything looks correct, click the Next button — otherwise, click Previous and correct your settings

When this is complete, you get a notification that everything was set up correctly

Working with the asP.neT Provider Model ❘ 765

Trang 12

Connecting the Built-in Providers to a Database

The built-in providers that require storage will look in the web.config file for a connection string entry named LocalSqlServer to determine how they should connect to the database If this entry does not exist

in web.config, they will use the default entry from machine.config which indicates a local database should be used Here is an example connection string that is configured to use the database created by the wizard in the last section:

<configuration>

<connectionStrings>

<configuration>

<system.web>

<membership>

memBershiP and role managemenT

ASP.NET contains a built-in membership and role management system that can be initiated either through code or through the ASP.NET Web Site Administration Tool This is an ideal system for authenticating users

to access a page or even your entire site This management system not only provides a new API suite for managing users, but also provides you with some server controls that interact with this API

Trang 13

The sample code contains a Web site project called Membership that we will use as an example for this

section It’s based on the Empty Web site project template After the project was created, a couple of pages were added to help demonstrate the security features of the Membership provider If you want to build your

own project, you’ll need to create a folder called Secret and then create a page in this folder called Payroll aspx Also, create a Default.aspx page in the root folder Add a line of text (something like “This is the

payroll page”) to both the payroll and default pages

As mentioned previously, the membership and role-management providers access their data by finding

a connection string named LocalSqlServer The Web Site Administration Tool uses these providers so the connection string must be properly configured before using the tool Also recall that if you do not have an entry for LocalSqlServer in the web.config file, the tool will create and use a local database in your application for storage The sample application included with this book uses a local database that was automatically created when membership was configured It is named aspnetdb.mdb and it is located in the App_Data folder.Let’s walk through the process of using the ASP.NET Web Site Administration Tool to set up security and user roles You can launch this tool through a button in the Solution Explorer or by selecting ASP.NET Configuration under Website (Web site projects) or Project (Web application projects) in the main menu When the tool opens, click the Security tab and then click the link to start the Security Setup Wizard as shown in Figure 22-17

figure 22-17

You’ll be greeted with the Welcome page for the wizard This page describes how the wizard will help you set up security for your site Clicking the Next button will take you to the page where you can choose which authentication you will use

The options presented ask whether your application will be available on the public Internet or hosted on

an intranet These options are misleading because you can use either of them regardless of where the site is being hosted What the wizard is really asking is what kind of authentication you wish to use If you select Internet, then your website will be enabled with forms authentication If you select local network, then your site will be configured to work with Windows Integrated Authentication For our example, select the Internet option as shown in Figure 22-18

Membership and role Management ❘ 767

Trang 14

Working through the wizard, you are also asked whether you are going to work with role management Enable role management by checking the appropriate check box and add a role named Manager After this step, you can begin to enter users into the system Fill out information for each user you want in the system,

as shown in Figure 22-19 The database used in the sample application has three users: Rob Windsor, Bill Sheldon, and Billy Hollis The password is the same for all users: pass@word1

figure 22-18

figure 22-19

Trang 15

The next step is to create the access rules for your site You can pick specific folders and apply the rules for the folder Click the Membership folder on the left and then add an access rule to deny anonymous users

to the folder (see Figure 22-20) Now click the Secret folder and add two access rules, one to allow people

in the Manager role and one to deny all users (see Figure 22-21) The order is important, as the rules are applied in the order in which they appear in the web.config file(s) If the order of the rules were reversed, users in the Manager role would be denied access to the Secret folder

The contents added to the web.config file in the root folder include the following:

Trang 16

Code snippet from web.config

This shows all the settings that were added by the wizard The <authorization> section allows for users who are in the role of Manager, and denies all anonymous users (defined with a question mark) The

<roleManager> element turns on the role management system, while the <authentication> element turns

Code snippet from Secret\web.config

Now, add a page called Login.aspx This page will be used when users need to enter their credentials

On the login page place a Login server control This is one of the many server controls that are designed

to work with the Membership and Role providers Each one requires little or no configuration because they are aware of the methods and properties of the providers to which they are connected For example, the Login control natively knows how to ask the Membership provider to validate credentials entered

by a user

Now run the application trying to access the Default.aspx page You will start out as an anonymous user Because anonymous users have been denied access to all pages in the site, you will be redirected to the Login.aspx page so you can enter your credentials, as shown in Figure 22-23

figure 22-23

Entering the credentials for any of the users you created earlier should get you to the Default.aspx page However, only the credentials for users in the Manager role will be sufficient to allow you to navigate to the Payroll.aspx page

Trang 17

Profile ProPerTies

Many Web applications have features that allow for personalization of some kind This might be as simple

as greeting a user by name, or it might deal with more advanced issues such as content placement Whatever the case, personalization techniques have always been tricky Developers have used anything from cookies, sessions, or database entries to control the personalization that users can perform on their pages

ASP.NET includes a personalization system that is easy to use It is as simple as making entries in the web.config file to get the personalization system started Like the membership and role management systems, the personalization system uses the provider model so it can be customized to suit your needs.Continuing with the Membership project created in the last section, we’ll create two profile properties, FirstName and LastName, both of type String To get started, alter the web.config file in the root folder

<add name="FirstName" type="System.String" />

<add name="LastName" type="System.String" />

</properties>

</profile>

</system.web>

</configuration>

Code snippet from web.config

When you are using a Web site project, which makes use of dynamic compilation, ASP.NET will create a class in the background with strongly typed properties matching those you just defined When you are using

a Web application project you have to get and set the properties using methods of the Profile property of the current HttpContext

Update the Default.aspx page by adding the controls and code required to allow the user to enter a first name and last name, and then save these values to the corresponding Profile properties In addition, add controls and code required to show the values of the Profile properties when the page loads and when their values are updated You should end up with something similar to this:

' Web Site projects TextBox1.Text = Profile.FirstName TextBox2.Text = Profile.LastName End If

PopulateLabel() End Sub

Protected Sub Button1_Click(ByVal sender As Object, _ ByVal e As System.EventArgs)

' Web Application projects 'Dim prof = HttpContext.Current.Profile

Profile Properties ❘ 771

Trang 18

'prof.SetPropertyValue("FirstName", TextBox1.Text) 'prof.SetPropertyValue("LastName", TextBox2.Text)

' Web Site projects Profile.FirstName = TextBox1.Text Profile.LastName = TextBox2.Text PopulateLabel()

End Sub Private Sub PopulateLabel ' Web Application projects 'Dim prof = HttpContext.Current.Profile 'Label1.Text = "First name: " & prof.GetPropertyValue("FirstName") & _ '"<br/>Last name: " & prof.GetPropertyValue("LastName")

' Web Site projects Label1.Text = "First name: " & Profile.FirstName & _ "<br/>Last name: " & Profile.LastName

Code snippet from Default.aspx

When this page is posted back to itself, the values entered into the two text boxes are placed into the personalization engine and associated with this particular user through the Profile object Once stored in the personalization engine, they are then available to you on any page within the application through the use of the same Profile object

microsofT aJax (asP.neT aJax)

In Web development, Ajax (asynchronous JavaScript and XML) is a term that signifies the capability

to build rich, interactive applications These applications contain client-side code that responds to user interactions by making asynchronous Web service calls via the XMLHttpRequest object and then updating areas of the page using the Document Object Model (DOM) Because the Web service calls are made asynchronously, the page remains responsive to the user throughout the process

Trang 19

Microsoft ajax (asP.neT aJaX) ❘ 773

The creation and inclusion of the XMLHttpRequest object in JavaScript and the fact that most upper-level browsers support it led to the creation of the Ajax model Ajax applications, although they have been around for a few years, gained popularity after Google released a number of notable, Ajax-enabled applications such

as Google Maps and Google Suggest These applications clearly demonstrated the value of Ajax

Shortly thereafter, Microsoft released a beta for a new toolkit that enabled developers to incorporate Ajax

features in their Web applications This toolkit has had several names — initially it was code-named Atlas,

at release it was renamed to ASP.NET AJAX, and with the release of NET 4 Beta 2 it has been renamed again to Microsoft Ajax Whatever the name, this toolkit abstracts away the low-level coding previously required, making it extremely simple to start using Ajax features in your applications today

understanding the need for ajax

To understand what Ajax is doing to your Web application, it would be instructive to first take a look at

what a Web page does when it does not use Ajax Figure 22-24 shows a typical request and response activity

for a Web application

In this case, end user interactions cause a full page postback The Web server processes the request, ASP.NET generates the updated page (including ViewState), and the full page is sent to the end user’s browser where it is rendered During this process the page is unresponsive to additional user interactions and the user generally experiences a “flicker” as the page is being updated

Conversely, an Ajax-enabled Web page includes JavaScript that takes care of issuing the calls to the Web server It does this when it is possible to send a request and get a response for just part of the page and using script; the client library only updates the parts of the page that have changed due to the request With only part of the page being processed, the end user experiences what some people term “fluidity” in the page, which makes the page seem more responsive Less code is required to update just a portion of a page, and it produces the responsiveness the end user expects Figure 22-25 shows a diagram of how this works

Windows Server

ASP.NET Processing Engine

Request

Response

AsynchronousResponse

AsynchronousRequest

End User's InternetBrowser (e.g IE7)ASP.NET AJAX LibraryEnd User's Client Computer

figure 22-25microsoft ajax implementation

There are actually two parts to Microsoft Ajax: a client-side JavaScript library and a set of server controls

Trang 20

The Microsoft Ajax Library is a set of JavaScript files that expose an object-oriented interface that is designed to be familiar to those who have used the NET Framework (see Figure 22-26) Even though many of the namespaces, types, and calling conventions are similar to those found in NET, the client-side library has no dependency on the NET Framework Thus, it can be used in Web pages of any kind: ASPX, HTML, PHP, JSP and so on This fact was the primary motivation for removing ASP.NET from the name

of the toolkit The toolkit is also designed with browser compatibility in mind; anything you build using the library should work consistently across recent versions of the popular browsers

Controls and Components Client Script Library

Client Application Services Browser Integration

Component Model and UI Framework Base Class Library Script Core Browser Compatibility

HTML, Script, ASP.NET AJAX Markup Service Proxies

figure 22-26

The server-side framework is mostly made up of a set of server controls that appear in the AJAX Extensions tab of the Toolbox (see Figure 22-27) The most commonly used controls are the ScriptManager and the UpdatePanel(you’ll see both of these later) In addition, the server-side framework adds extensions to WCF and ASMX Web services that enable the automatic creation of JavaScript proxies and automatic marshalling of objects back and forth between JavaScript objects (JSON) and the NET objects, significantly easing the process of calling services from client-side code Figure 22-28 illustrates the server-side framework provided by Microsoft Ajax

figure 22-27

ASP.NET AJAX Server Controls App Services Bridge ASP.NET AJAX Server Extensions

Page Framework Server Controls

ASP.NET AJAX ASP.NET Pages Web Services

Application Services ASP.NET

figure 22-28

Trang 21

Microsoft ajax (asP.neT aJaX) ❘ 775

updatePanel control vs client-side service calls

Like many things in the NET arena, Microsoft gives you options for adding Ajax behavior to your applications Using the UpdatePanel control enables you to continue to develop with server controls and the Web Forms model It has a small learning curve and is great when working with existing applications, but it is somewhat limited in functionality The alternative is to move to a more architecturally pure Ajax implementation whereby you use client-side JavaScript to make Web service calls and update pages using the DOM or using the new DataView control and client templates Because this changes the development process for many, it has a steeper learning curve; but it offers greater flexibility in implementation

introducing the sample Project

For this example you will build an application similar to something you built earlier You will have a page that displays customers from the Northwind database, filtered by country The big difference will

be the introduction of a Web service that sits between the user interface code and the data model You will start with an application that does not make use of Microsoft Ajax and then update it first to use the UpdatePanel control and then to use client-side service calls and client templates

The solution will contain two projects, a Class Library project named Service that will have the data model and the implementation of the service operations, and a Web application project named Client that will expose the Web service and the pages with which end users interact The data model and the solution structure are shown in Figure 22-29

Trang 22

Public Class NorthwindService Public Function GetCountryNames() As String() Dim dc As New NorthwindDataContext Dim query = From cust In dc.Customers Select cust.Country Distinct Order By Country

Return query.ToArray() End Function

Public Function GetCustomersByCountry(ByVal country As String) _

As CustomerDto() Dim dc As New NorthwindDataContext Dim query = From cust In dc.Customers Where cust.Country = country Select New CustomerDto With { .CustomerID = cust.CustomerID, .CompanyName = cust.CompanyName, .ContactName = cust.ContactName, .ContactTitle = cust.ContactTitle, .OrderCount = cust.Orders.Count }

Return query.ToArray() End Function

End Class

Code snippet from Service\NortwindService.vb

The code for the Web service (Client.NorthwindService) is shown next (note that it just delegates calls to the service implementation class):

Imports System.Web.Services Imports System.Web.Services.Protocols Imports System.ComponentModel

<System.Web.Script.Services.ScriptService()> _

<System.Web.Services.WebService(Namespace:="http://mycompany.com/Northwind")> _

<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _

<ToolboxItem(False)> _ Public Class NorthwindService Inherits System.Web.Services.WebService

<WebMethod()> _ Public Function CountryNames() As String() Dim svc As New Service.NorthwindService() Return svc.GetCountryNames()

End Function <WebMethod()> _ Public Function GetCustomersByCountry(ByVal country As String) _

As Service.CustomerDto() Dim svc As New Service.NorthwindService() Return svc.GetCustomersByCountry(country) End Function

End Class

Code snippet from Client\NorthwindService.asmx.vb

Finally, the markup for the page (Client.Demo01-NoAjax) is shown here It uses the ObjectDataSourcecontrol to communicate with the Web service to get data, and uses standard data binding to populate the DropDownList and GridView controls:

Trang 23

Microsoft ajax (asP.neT aJaX) ❘ 777

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Demo01-NoAjax.aspx.vb"

Code snippet from Client\Demo01-NoAjax.aspx

Figure 22-30 shows the Demo01-NoAjax.aspx page running What can’t be captured in an image is that there

is a full-page postback each time the user selects a new country However, you can see the communication with the server when a new country is selected using a tracing tool like Fiddler (www.fiddlertool.com) Figure 22-31 shows the request in the upper pane (1,590 bytes) and the response in the lower pane (4,374 bytes)

Trang 24

adding the updatePanel control

One of the drawbacks to the current implementation is that the markup for the drop-down list containing the countries is sent with every response even though the list of countries rarely changes When a country is selected from the list, all you really need to update is the grid containing the customer data

The previously mentioned UpdatePanel control enables you to do this quite easily The UpdatePanel,

along with the rest of the Microsoft Ajax framework, allows for partial-page rendering In other words,

you can indicate a section of a page that you want to be updated when a user interaction occurs, leaving the

figure 22-30

figure 22-31

Trang 25

Microsoft ajax (asP.neT aJaX) ❘ 779

remainder of the page unchanged An added benefit is that this process will be done asynchronously, so the page remains responsive while the update is in progress To achieve this goal, you need to use the properties

of the UpdatePanel to indicate which events of which controls will trigger an asynchronous postback

instead of a regular full-page postback

In our example, we want to wrap the GridView control in an UpdatePanel and indicate that a SelectedIndexChanged event on the DropDownList control should cause an asynchronous postback

To do this, add a ScriptManager control to the top of the page, and then update the part of the page (or create a modified copy) that includes the markup for the GridView to look like this from the Demo02-UpdatePanel.aspx page:

<asp:ScriptManager ID="ScriptManager1" runat="server">

Code snippet from Client\Demo02-UpdatePanel.aspx

Figure 22-32 shows the page running In this case, when a new country is selected the page is asynchronously posted back to the server and the page-lifecycle runs, but only the markup for the grid is sent to the client Looking at the trace in Figure 22-33, you can see that the request is virtually the same as before (1,668 bytes) but the response is significantly smaller (2,625 bytes)

Trang 26

figure 22-32

figure 22-33

using client-side service calls and client Templates

As you’ve seen, refactoring the page to add Ajax-like behavior with the UpdatePanel is fairly easy and doesn’t require a significant change in the way you develop pages You also get the benefit of reduced traffic,

as only the markup for the area of the page that is contained in the UpdatePanel is sent in the response.Unfortunately, there are some drawbacks The main drawback is that the full page life cycle is running for each request This means that markup for the entire page is being generated on the server even though some

of it is going to be discarded because it is outside the UpdatePanel The second drawback is the size of the

Trang 27

Microsoft ajax (asP.neT aJaX) ❘ 781

request and response Even though we reduced it significantly from the full-page postback, we can do much, much better (as you will see shortly)

Let’s modify the application to use a purer Ajax implementation in which we are calling Web services from the client-side JavaScript This is done in Demo03-Ajax.aspx in the sample application

The first thing we need to do is ensure that the Web service we are going to call is able to generate a JavaScript proxy If you are using ASMX Web Services, all that is required is the addition of the System.Web.Script.Services.ScriptService attribute to your service type If you look back at the sample code, our service type (NorthwindService.asmx.vb) already has that attribute so we are good to go

If we were using a WCF service, we would need an endpoint that used the webHttpBinding and had the enableWebScript element in its endpoint behavior

Next, we need to add a service reference and a couple of script references to the ScriptManager Since we’ll be calling our service from the client-side, we need to ensure that the JavaScript proxy is added to our page; the service reference will take care of this The script references ensure that the page has access

to the required client-side libraries Traditionally, the client-side libraries have been deployed as embedded resources in the System.Web.Extensions assembly With the release of NET 4 Beta 2, Microsoft decided

to take the Microsoft Ajax Library out of band, allowing the library to be updated more frequently than the NET Framework The most recent version of the Microsoft Ajax Library can be downloaded from CodePlex (http://ajax.codeplex.com)

For the sample application, the ASP.NET Ajax Library 0911 Beta was downloaded and the JavaScript files were added to the Client project in a folder named Scripts

<asp:ScriptManager ID="ScriptManager1" runat="server">

Code snippet from Client\Demo03-Ajax.aspx

If you know your application will have reliable access to the Internet, you have the option of using the Microsoft Ajax Content Delivery Network (CDN) This allows your application to load the required JavaScript files directly from the Microsoft site instead of having to include them with each project An additional benefit is that the ScriptManager control is aware of the CDN so all you need to do is set one property and the ScriptManager automatically ensures that the required JavaScript files are included with each response

<asp:ScriptManager EnableCdn="true" ID="ScriptManager1" runat="server">

we will use the client template features to enable client-side data binding This allows us to define a template for the table body that includes placeholders for properties of the objects that will be bound to the template For simple binding, the name of the property is surrounded in double curly braces (e.g., {{ CustomerID }}); however, more complex binding scenarios are supported using a syntax similar to that used in WPF (e.g., {binding RequiredDate, convert=dateConverter}) In a moment you will create a DataView control and attach it to the tbody element The DataView will act like the server-side DataSource controls we used

Trang 28

earlier It will be the object that receives the data and populates the target element via the data-binding mechanism.

The last important point to note is the class attribute on the tbody element It needs to have the value

“sys-template” for the data binding to work:

<table id="customersTable" cellspacing="0" border="1">

Code snippet from Client\Demo03-Ajax.aspx

Finally, we need to add the JavaScript code to populate the table we just created Let’s start with what happens when the page loads Just as we have a Page_Load event hander on the server side, we can create

a pageLoad function in JavaScript and the framework will call it for us when the client-side elements have been initialized

When the page loads, we want to create the DataView that will be used to populate the body of the table; then we want to populate the table; and finally we want to hook up an event handler so that when the user selects a different country, the table is refreshed When we create the DataView we will pass a string parameter that uses CSS selector syntax to identify the element to attach to In this case, that element is the table body To show the customers we will call a custom showCustomers function, which we’ll add shortly

To add the event handler to the DropDownList, we will use the $addhandler shortcut method, indicating that when the change event happens we want to call the showCustomers function:

var custView;

function pageLoad() { custView = Sys.create.dataView("#customersBody");

showCustomers();

$addHandler($get("DropDownList1"), "change", showCustomers);

}

Code snippet from Client\Demo03-Ajax.aspx

The code to show the customers is fairly simple First, we get the name of the country the user has selected from the DropDownList Then we call the Web service to get the customers for the selected country This

is done asynchronously, so the Web service call takes two parameters: the country and the name of the

function we want to call when the service operation is complete (this is generally known as the callback

function) When the service operation returns, the callback function will be passed the data representing the

Trang 29

Microsoft ajax (asP.neT aJaX) ❘ 783

customers as a JavaScript array All we need to do to update the table is to give the DataView the array; it will take care of the data binding and rendering:

function showCustomers() { var country = $get("DropDownList1").value;

Client.NorthwindService.GetCustomersByCountry(country, showCustomersComplete);

} function showCustomersComplete(data) { custView.set_data(data);

}

Code snippet from Client\Demo03-Ajax.aspx

Our page is now complete and ready for testing The complete code and markup is shown here:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Demo03-Ajax.aspx.vb"

var custView;

function pageLoad() { custView = Sys.create.dataView("#customersBody");

showCustomers();

$addHandler($get("DropDownList1"), "change", showCustomers);

} function showCustomers() { var country = $get("DropDownList1").value;

Client.NorthwindService.GetCustomersByCountry(

country, showCustomersComplete);

} function showCustomersComplete(data) { custView.set_data(data);

} </script>

Trang 30

Code snippet from Client\Demo03-Ajax.aspx

Figure 22-34 shows the page running Looking at the trace in Figure 22-35, you can see that the request is

a simple JavaScript object that represents the country selected (20 bytes); and the response is a JavaScript array that represents the customer data from the selected country (538 bytes) That’s an 87% savings in network traffic when compared to the example using the UpdatePanel

figure 22-34

Trang 31

This chapter and the previous chapter offered a whirlwind tour of ASP.NET and some of the features that you can provide in the projects you develop ASP.NET is highly focused on the area of developer productivity, and it works very hard at providing you access to functionality expected in websites today

A nice aspect of most of the features presented is that you can either utilize the wizards that are built into the underlying technology or skip these wizards and employ the technologies by editing markup Either way is fine Another useful aspect of the technologies introduced is that they all enable a huge amount of customization You can alter the behavior and output of these technologies to achieve exactly what you need

If you want to dig deeper into ASP.NET, be sure to take a look at Professional ASP.NET 4 (Evjen et al.,

Wiley, 2010)

figure 22-35

summary ❘ 785

Trang 33

asP.neT MVC

WhaT you Will learn in This chaPTer

The Model - View - Controller (MVC) Pattern

➤ The goals of ASP NET MVC

➤ How the MVC pattern has been applied to ASP NET MVC

➤ Working with controllers and actions

➤ Using scaff olding to help generate views

➤ Validation in ASP NET MVC 2

➤ ASP.NET MVC is a Web framework that was originally released in March 2009 as an alternative

to ASP.NET Web Forms It was designed to limit abstractions and give developers a great deal of control over the creation of pages in an application Specifi cally, ASP.NET MVC was designed to do the following:

Provide complete control over HTML markup — With Web Forms, the fi nal markup is mostly

determined by the server controls on a page

Have intuitive website URLs — With Web Forms, the URL is determined by the location and

name of the fi le being addressed

Have a clear separation of concerns — The Web Forms programming model encourages

developers to put business logic and database access code in the code - behind for a page

Be testable by default — Several aspects of the Web Forms model make it diffi cult to write unit

tests for user interface layer logic

It ’ s important to repeat that ASP.NET MVC is an alternative to Web Forms, not its replacement MVC will suit the style of some developers, and seem a step backward for others Many have used the analogy of manual versus automatic transmission Manual (MVC) gives you complete control but requires more effort; automatic (Web Forms) may be slightly less effi cient but it does the work for you Ultimately, the choice of framework is yours Choose the one that best suits your development style

As this book is being written, ASP.NET MVC 2 is in Beta and is projected to be complete with the release of Visual Studio 2010 The contents of this chapter are based on the version of ASP.NET MVC 2 included with the Beta 2 versions of Visual Studio 2010 and NET 4

Trang 34

model-VieW-conTroller and asP.neT

The Model-View-Controller pattern was conceived in the late 1970s by Trygve Reenskaug, a Norwegian computer scientist It provides a powerful and elegant means of separating concerns within an application, and it applies extremely well to Web development

The pattern separates an application into three components:

Model — The business objects in the application

View — The user interface

Controller — Classes that handle user requests and manage application logic and flow

In the ASP.NET implementation of the pattern, requests are routed to controller classes that generally apply application logic (authorization, for example), interact with the model to retrieve or update data, determine the data that needs to be rendered in the response, and then pass control to a view to format the data and render the final markup to the user

Another important aspect of the implementation of ASP.NET MVC is the use of convention over configuration

As we build an application in the next section, you will see that conventions are used to determine the names and locations of files in a project or to determine which class or file to load at runtime You are not forced to follow these conventions, but doing so allows for a consistent experience across ASP.NET MVC applications

Building an asP.neT mVc aPPlicaTion

ASP.NET MVC is a new addition to the ASP.NET family and is likely new to most of you reading this book Following the premise that the most effective way to learn a new framework is to use it, we will spend the remainder of this chapter building an ASP.NET MVC 2 application

creating the Project

Open Visual Studio and create a new ASP.NET MVC 2 Web Application named MvcDemo You will

immediately be asked if you want to create an associated unit test project (see Figure 23-1) Because

testability is one of the core tenets of ASP.NET MVC it makes sense that the project template would encourage you to do so Keep the default test project name and click OK to create the projects

If you look at the MVC project in the Solution Explorer (see Figure 23-2),

you’ll see that several files and folders have been created by default Three

of the folders should jump out at you immediately: Models, Views, and

Controllers These folders map to the three components of the pattern on

which this style of application is based

Trang 35

If you run the application, you will see that a few pages (including the master page) are included as part of the project template (see Figure 23 - 3) While not exactly the same, the site will be similar in look and feel to one created when you use the non - empty Web Forms project templates

figure 23-3

Currently, there are no out - of - the - box Web site project templates for ASP.NET MVC.

controllers and actions

In traditional Web application frameworks, requests are mapped to fi les containing markup for pages In ASP.NET MVC, requests are mapped to methods on classes The classes are the previously mentioned controller classes, and the methods are known as actions Action methods are responsible for receiving user input, retrieving or saving data to the model, and passing control to the appropriate view The view will typically return the markup for a page but it could also return other content types such as a binary fi le

or JSON formatted data Typical actions will handle requests to list, add, edit, or delete entities from the model

Let ’ s examine these concepts further by creating

a new controller In the Solution Explorer, right click on the Controllers folder and select Add ➪ Controller By convention, the names of controller classes should end with “ Controller ” The Add Controller dialog even encourages the use of this convention, as shown in Figure 23 - 4 Set the name

-to SimpleController and click the Add but-ton

The class that ’ s created will inherit from the base Controller class ( System.Web.Mvc.Controller ) and will have the shell for a default action method named Index : Public Class SimpleController

Inherits System.Web.Mvc.Controller

'

figure 23-4

Building an asP.neT MVC application ❘ 789

Trang 36

' GET: /Simple/

Function Index() As ActionResult Return View()

End Function End ClassThe Index action method is about as simple as it gets When a request comes in for this action it just passes control to a view without any application logic or data access Because the action method has not specified which view to show, convention states that ASP.NET MVC should look for a file matching the pattern /Views/{Controller}/{Action}.aspx In the case of the Index action, that would be /Views/Simple/Index.aspx, which does not exist at this point

The comment above the method is not required but

it is something you’ll typically see in code generated

by Visual Studio It indicates that this action will be

accessed via an HTTP GET request to /Simple This

illustrates another convention The default routing

rules used by MVC expect something in the form

of /{Controller}/{Action} If the action is not

specified, then ASP.NET MVC will default to

calling the Index action method, so a request

to /Simple or /Simple/Index will be routed to

the Index action You will learn about routing

and how to add or modify routing rules later in

this chapter

Because the view for the Index action does not exist,

let’s create it We could do this rather easily by hand,

but there’s no need to; Visual Studio will create it for

us In the Code Editor, right-click anywhere in the

code for the Index method and select the Add View

option in the context menu In the Add View dialog,

leave the default values as they are (see Figure 23-5)

and click the Add button You should be presented

with a new content page that looks something like the

Note two things about the page: It was created in the proper folder by default (that is, \Views\Simple) and

it inherits from System.Web.Mvc.ViewPage instead of System.Web.UI.Page At this point you should be able to run the application Once it is loaded in the browser, navigate to /Simple and you’ll see a page like the one shown in Figure 23-6

figure 23-5

Trang 37

figure 23-6

Now we’ll look at an example in which data is passed from the action method to the view Back in the SimpleController class, add a new action method called SayHello that takes a string parameter called name When a request is made, ASP.NET will match parameters on the query string to parameters of the method The action method can pass the value of the parameter to the view by adding it to the built-in ViewDatacollection

' ' GET: /Simple/SayHello?name=Rob

Function SayHello(ByVal name As String) As ActionResult ViewData("Name") = name

Return View() End Function

Code snippet from \Controllers\SimpleController.vb

Create the view by right-clicking anywhere in the code for the SayHello function, selecting Add View in the context menu, and clicking the Add button In the content page that’s created, modify the value of the <h2> element to output the value of the name parameter stored in the ViewData:

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

Trang 38

adding the model

In MVC, the model typically refers to the business or domain objects These are classes that represent the data

in the application, along with the corresponding business rules and validation For our sample application we will use LINQ to SQL to create a simple domain model over data from the Northwind database

If you don’t have the Northwind database available, get the one included in the sample code for the book and add it to the App_Data folder of your project In the Models folder, create a new LINQ to SQL model

called Northwind.dbml and add the Categories and Products table to it as shown in Figure 23-8 Saving the

model will create the NorthwindDataContext and the domain objects for categories and products

figure 23-8

figure 23-7

We could stop here and have our controllers access the data model directly, but doing so will reduce testability and lead to duplication of queries across the application To avoid these issues, we will create a class that encapsulates access to the data model

Trang 39

In the Models folder, create a new class called NorthwindRepository In it create three methods: one that returns all categories, one that returns all products, and one that returns products in a specific category In all three of the methods, sort the results by the name of the product or category.

Public Class NorthwindRepository Private _context As New NorthwindDataContext()

Public Function GetCategories() As IQueryable(Of Category) Dim query = From cat In _context.Categories

Order By cat.CategoryName Select cat

Return query End Function Public Function GetProducts() As IQueryable(Of Product) Dim query = From prod In _context.Products

Order By prod.ProductName Select prod

Return query End Function Public Function GetProductsForCategory(ByVal categoryName As String) _

As IQueryable(Of Product) Dim query = From prod In _context.Products Where prod.Category.CategoryName = categoryName Order By prod.ProductName

Select prod Return query

End Function End Class

Code snippet from \Models\NorthwindRepository.vb

Views

Now that we have a model, we can create some controllers, actions, and views that are more like those you would create in a traditional business application To start off, we will look at views that display data from the database; later in the chapter we add views that let us modify the data

Create a new controller called ProductsController The Index action should be modified to get the list of categories and return a view that will display them:

Public Class ProductsController Inherits System.Web.Mvc.Controller

Private _repository As New NorthwindRepository()

' ' GET: /Products/

Function Index() As ActionResult Dim categories = _repository.GetCategories().ToList() Return View(categories)

End Function End Class

Code snippet from \Controllers\ProductsController.vb

Notice that instead of passing the list of categories to the view using the ViewData collection (which would

be weakly typed), we pass them as the first parameter to the View method This enables us to create a strongly typed view, one that is aware that it is rendering category objects Bring up the Add View dialog as before, but this time check the Create a Strongly-Typed View check box and select MvcDemo.Category

Building an asP.neT MVC application ❘ 793

Trang 40

from the View data class drop-down For now we’ll keep the default value of Empty in the View content drop-down You’ll see the effect of using the other values in this drop-down later in the chapter.

In the resulting view page, you show the category names in an unordered list:

<%@ Page Title="" Language="VB" MasterPageFile="~/Views/Shared/Site.Master"

Inherits="System.Web.Mvc.ViewPage(Of IEnumerable(Of MvcDemo.Category))" %>

<% For Each category In Model %>

<li><%: category.CategoryName %></li>

If you run the application and navigate to /Products, you should see a page similar to the one shown in Figure 23-9

figure 23-9

Ngày đăng: 12/08/2014, 23:23

TỪ KHÓA LIÊN QUAN