Tải bản đầy đủ (.pdf) (133 trang)

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

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (5.85 MB, 133 trang )

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
Simpo PDF Merge and Split Unregistered Version -
756

CHAPTER 22 asP.NEt adVaNCEd FEatuREs
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" %>

<script runat="server">
</script>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server">
</asp:Content>


This file is quite a bit different from a typical .aspx page. First, there is none of the default HTML code,
script tags, and DOCTYPE declarations. Second, note the addition of the MasterPageFile attribute in the
Page directive. This new attribute makes the association to the master page that will be used for this content
page. In this case, it is the MasterPage.master file created earlier.
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
Simpo PDF Merge and Split Unregistered Version -
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" %>

<script runat="server">
Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Label1.Text = "Hello " & TextBox1.Text
End Sub
</script>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<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" />
<br />
<br />
<asp:Label ID="Label1" Runat="server"></asp:Label>
</b>
</asp:Content>
<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
Simpo PDF Merge and Split Unregistered Version -
758

CHAPTER 22 asP.NEt adVaNCEd FEatuREs
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 Magazines
This 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=" >
<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>
Simpo PDF Merge and Split Unregistered Version -
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 .sitemap
file it finds in the project; nothing is required on your part to make this happen. The SiteMapPath’s smart
Navigation

759
Simpo PDF Merge and Split Unregistered Version -
760

CHAPTER 22 asP.NEt adVaNCEd FEatuREs
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 SiteMapPath
control. 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 SiteMapDataSource
control on the page:
Simpo PDF Merge and Split Unregistered Version -
<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
Simpo PDF Merge and Split Unregistered Version -
762

CHAPTER 22 asP.NEt adVaNCEd FEatuREs
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
WindowsTo kenRoleProvider
XmlSiteMapProvider
SqlProfileProvider
RSAProtectedConfigurationProvider
WmiWebEventProvider
TraceWebEventProvider
SqlWebEventProvider
TemplatedMailWebEventProvider
SimpleMailWebEventProvider
EventLogWebEventProvider
SqlSessionStateStore
OutOfProcSessionStateStore
InProcSessionStateStore
ASP.NET
Role
WebEvents

WebParts
Configuration
Membership
SiteMapSessionState
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.
Simpo PDF Merge and Split Unregistered Version -
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
-? Displays a list of available option commands.
-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 connec-
tion string itself.
-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.
-A p Adds support for working with profiles.
_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
<lena me>

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
Simpo PDF Merge and Split Unregistered Version -
764

CHAPTER 22 asP.NEt adVaNCEd FEatuREs
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).
Simpo PDF Merge and Split Unregistered Version -
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
Simpo PDF Merge and Split Unregistered Version -
766

CHAPTER 22 asP.NEt adVaNCEd FEatuREs
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>
<clear />
<add name="LocalSqlServer"
connectionString="Data Source=localhost\sqlexpress;Database=aspnetdb;
Integrated Security=SSPI" />
</connectionStrings>

</configuration>


Notice the <clear> element. This is required as the machine.config file already has an entry named
LocalSqlServer. This entry must be cleared first, so we can add the new entry with the proper connection string.
Just like the default connection string, the built-in providers have their default settings defined in the
machine.config file. In most cases the defaults are suitable, and you do not need to do any application
specific configuration. However, if you want to customize the way individual providers work, you can
override their default settings in the web.config file. For instance, if you are using the membership
provider, and you want a minimum password length of 12 characters and login to fail after three invalid
password attempts, then you would add the following:
<configuration>
<system.web>

<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, "
connectionStringName="LocalSqlServer"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="true"
applicationName="/"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="3"
minRequiredPasswordLength="12"
minRequiredNonalphanumericCharacters="1"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""/>
</providers>
</membership>

</system.web>
</configuration>
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.
Simpo PDF Merge and Split Unregistered Version -
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
Simpo PDF Merge and Split Unregistered Version -
768

CHAPTER 22 asP.NEt adVaNCEd FEatuREs
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
Simpo PDF Merge and Split Unregistered Version -
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.
FIGURE 2220
FIGURE 2221
FIGURE 2222
Click the Finish button to exit the wizard. You should be redirected back to the Security tab. The last

step is to add at least one of the users you created to the Manager role. Click the Manage users link, and
then click the Edit roles link for one or more of the users and add them to the Manager role as shown in
Figure 22-22.
The contents added to the
web.config file in the root folder include the following:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<authorization>
<allow roles="Manager" />
Membership and Role Management

769
Simpo PDF Merge and Split Unregistered Version -
770

CHAPTER 22 asP.NEt adVaNCEd FEatuREs
<deny users="?" />
</authorization>
<roleManager enabled="true" />
<authentication mode="Forms" />
</system.web>
</configuration>
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
on forms authentication.
Note that there is a second
web.config in the Secret folder. This defines the security for the folder and the

pages inside:
<configuration>
<system.web>
<authorization>
<allow roles="Manager" />
<deny users="*" />
</authorization>
</system.web>
</configuration>
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.
Simpo PDF Merge and Split Unregistered Version -
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
as shown here:
<?xml version="1.0"?>
<configuration>
<system.web>
<profile>
<properties>
<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:
<%@ Page Language="VB" %>

<script runat="server">

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

If Not IsPostBack Then
' Web Application projects
'Dim prof = HttpContext.Current.Profile
'TextBox1.Text = prof.GetPropertyValue("FirstName")
'TextBox2.Text = prof.GetPropertyValue("LastName")

' 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
Simpo PDF Merge and Split Unregistered Version -
772

CHAPTER 22 asP.NEt adVaNCEd FEatuREs
'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
End Sub
</script>

<html xmlns=" >
<head id="Head1" runat="server">
<title>Welcome Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:LoginName ID="LoginName1" runat="server" />
<br /><br />
First name:<br />
<asp:TextBox ID="TextBox1" Runat="server"></asp:TextBox>

<br />
Last name:<br />
<asp:TextBox ID="TextBox2" Runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" Runat="server" Text="Submit Information"
OnClick="Button1_Click" />
<br />
<br />
<asp:Label ID="Label1" Runat="server"></asp:Label>
</div>
</form>
</body>
</html>
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.
Simpo PDF Merge and Split Unregistered Version -
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
End User’s Internet
Browser (e.g. IE7)
End User’s Client Computer
Response
FIGURE 2224

Windows Server
ASP.NET
Processing Engine
Request
Response
Asynchronous
Response
Asynchronous
Request
End User's Internet
Browser (e.g. IE7)
ASP.NET AJAX Library
End User's Client Computer
FIGURE 2225
Microsoft Ajax Implementation
There are actually two parts to Microsoft Ajax: a client-side JavaScript library and a set of server controls.
Simpo PDF Merge and Split Unregistered Version -
774

CHAPTER 22 asP.NEt adVaNCEd FEatuREs
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

Simpo PDF Merge and Split Unregistered Version -
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.
FIGURE 2229
The code for the service implementation (Service.NorthwindService) is shown below. You’ll need to add
the LINQ to SQL model shown in Figure 22-29 before adding this code.
Public Class CustomerDto
Property CustomerID As String
Property CompanyName As String
Property ContactName As String
Property ContactTitle As String

Property OrderCount As Integer
End Class

Simpo PDF Merge and Split Unregistered Version -
776

CHAPTER 22 asP.NEt adVaNCEd FEatuREs
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:=" _
<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 ObjectDataSource

control to communicate with the Web service to get data, and uses standard data binding to populate the
DropDownList and GridView controls:
Simpo PDF Merge and Split Unregistered Version -
Microsoft Ajax (ASP.NET AJAX)

777
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Demo01-NoAjax.aspx.vb"
Inherits="Client.Demo01_NoAjax" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
" />
<html xmlns=" >
<head id="Head1" runat="server">
<title>No Ajax</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
SelectMethod="CountryNames" TypeName="Client.NorthwindService">
</asp:ObjectDataSource>
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="ObjectDataSource1" AutoPostBack="True">
</asp:DropDownList>
<br /><br />

<asp:ObjectDataSource ID="ObjectDataSource2" runat="server"
SelectMethod="GetCustomersByCountry"
TypeName="Client.NorthwindService">
<SelectParameters>

<asp:ControlParameter ControlID="DropDownList1"
Name="country"
PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataSourceID="ObjectDataSource2">
<Columns>
<asp:BoundField DataField="CustomerID"
HeaderText="Customer ID"
SortExpression="CustomerID" />
<asp:BoundField DataField="CompanyName"
HeaderText="Company Name"
SortExpression="CompanyName" />
<asp:BoundField DataField="ContactName"
HeaderText="Contact Name"
SortExpression="ContactName" />
<asp:BoundField DataField="ContactTitle"
HeaderText="Contact Title"
SortExpression="ContactTitle" />
<asp:BoundField DataField="OrderCount"
HeaderText="Order Count"
SortExpression="OrderCount" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>

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).
Simpo PDF Merge and Split Unregistered Version -
778

CHAPTER 22 asP.NEt adVaNCEd FEatuREs
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
Simpo PDF Merge and Split Unregistered Version -
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">
</asp:ScriptManager>

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
SelectMethod="CountryNames" TypeName="Client.NorthwindService">
</asp:ObjectDataSource>
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="ObjectDataSource1" AutoPostBack="True">
</asp:DropDownList>
<br /><br />

<asp:ObjectDataSource ID="ObjectDataSource2" runat="server"
SelectMethod="GetCustomersByCountry"
TypeName="Client.NorthwindService">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1"
Name="country"
PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataSourceID="ObjectDataSource2">
<Columns>

<asp:BoundField DataField="CustomerID" HeaderText="Customer ID"
SortExpression="CustomerID" />
<asp:BoundField DataField="CompanyName" HeaderText="Company Name"
SortExpression="CompanyName" />
<asp:BoundField DataField="ContactName" HeaderText="Contact Name"
SortExpression="ContactName" />
<asp:BoundField DataField="ContactTitle" HeaderText="Contact Title"
SortExpression="ContactTitle" />
<asp:BoundField DataField="OrderCount" HeaderText="Order Count"
SortExpression="OrderCount" />
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DropDownList1"
EventName="SelectedIndexChanged" />
</Triggers>
</asp:UpdatePanel>
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).
Simpo PDF Merge and Split Unregistered Version -

×