Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning ASP.NET 2

.0.pdf
Скачиваний:
23
Добавлен:
17.08.2013
Размер:
24.67 Mб
Скачать

Componentization

Figure 10-24

6.Next we need to add the namespace. Go to the code-behind file NewsUserControl.ascx.vb and add a reference to the System.Data namespace at the top of the file:

Imports System.Data

7.Now we’ll add the code. Still in the code-behind file add the following code for an ItemsToShow property, which governs how many items are shown on the screen at the same time:

Partial Class NewsControl

Inherits System.Web.UI.UserControl Private _itemsToShow As Integer = 5 Public Property ItemsToShow() As Integer

Get

Return _itemsToShow End Get

Set(ByVal value As Integer) _itemsToShow = value

End Set End Property

8.Select (Page Events) from the left-hand drop-down box.

9.Select the Pre_Render method from the top of the screen in the right drop-down list box, and add the following code to it:

Private Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender

379

Chapter 10

Dim sel As String = String.Format(“SELECT Top {0} * FROM [News] WHERE “ & _ “ DateToShow <= ‘{1}’ ORDER BY DateToShow DESC”, _itemsToShow, _

DateTime.Now.ToString(“yyyy/MM/dd”))

SqlDataSource1.SelectCommand = sel

End Sub

10.Now go to Solution Explorer and create a new Web Form called NewsDisplay.aspx. Go to Design View and drag your NewsUserControl.ascx into the Web Form.

11.Run it — it’s fairly raw without any styles, but you will see five news items, as shown in Figure 10-25.

Figure 10-25

12.Go back to Source View and add an ItemsToShow attribute, and set it to 2:

<div>

<uc1:NewsUserControl id=”NewsUserControl1” runat=”server” ItemsToShow=”2”>

</uc1:NewsUserControl>

</div>

13.Save the page and run it again, and you will see the output shown in Figure 10-26. If you want to improve the “rough and ready” look of this control, as we have, drag the site.css file from the templates folder in the directory into the aspx file to apply the style sheet.

380

Componentization

Figure 10-26

How It Works

You have a News control that not only can you drop in any page (it is used on the front page of the Wrox United site), but also allows you to configure the number of items shown via a single attribute. The following code has been created in the user control, a SqlDataSource control that queries the news table together with a Repeater control that displays each of the individual news items:

<%@ Control Language=”VB” AutoEventWireup=”false” codefile=”News.ascx.vb” Inherits=”NewsControl” %>

<asp:SqlDataSource id=”SqlDataSource1” Runat=”server” ConnectionString=”<%$ ConnectionStrings:WroxUnited %>”>

</asp:SqlDataSource>

<asp:Repeater ID=”Repeater1” Runat=”server” DataSourceID=”SqlDataSource1” <ItemTemplate>

<div class=”newsItem”>

<span class=”newsDate”><%#Eval(“DateToShow”, “{0:dd MMM yyyy}”)%> </span>

<span class=”newsTitle”><%#Eval(“Title”)%></span> </div>

<span class=”newsContent”> <%#Eval(“Description”) %>

</span>

</ItemTemplate>

</asp:Repeater>

It’s the code-behind that provides the main functionality, though. Once again the relationship between the code-behind and the main control is shown. You added an ItemsToShow property to the codebehind and exposed it as a public property. This has the effect of creating an attribute that you can set via the Web Form:

Private _itemsToShow As Integer = 5

Public Property ItemsToShow() As Integer

Get

381

Chapter 10

Return _itemsToShow

End Get

Set(ByVal value As Integer)

_itemsToShow = value End Set

End Property

You set the default to 5, so if the attribute isn’t set you automatically display five items instead. The property allows you to both get and set the separate values.

What allows you to display the contents of the control is the code that occurs in the Pre_Render event. This is similar to the Page_Load event, except it occurs just before the controls on a page are rendered. Because you want to display these at the last possible moment, you place two statements here. The first one provides a SQL statement that selects the top news items ordered by date, and restricted

by the _itemsToShow variable that you created at the top of the class:

Dim sel As String = String.Format(“SELECT Top {0} * FROM [News] WHERE “ & _ “ DateToShow <= ‘{1}’ ORDER BY DateToShow DESC”, _itemsToShow,

DateTime.Now.ToString(“yyyy/MM/dd”))

SqlDataSource1.SelectCommand = sel

The second sets this SQL to the SelectCommand property of your data source, and this restricts the number of items shown by your user control.

Composite Controls

You’ve looked at how user controls are nested inside pages, but it doesn’t stop there. You can nest user controls inside user controls. These are known as composite controls. If you consider a scenario where you require a group of user controls, such as, say, a News control and a Login control, and a Fixture viewer control. Rather than having to place references to these controls separately each time, you could place them in a single user control and use that control instead. This further enhances the code-reuse within the application.

Assemblies and Custom Ser ver Controls

.NET also provides the capability to pre-compile code components into a central location that can be accessed from anywhere within the site. These components, like user controls, can contain one or more classes; however, the crucial difference is that ASP.NET uses the compiled assemblies rather than the code inside the component itself at runtime (in other words, the component isn’t compiled at the same time as the main application, but rather has to be done beforehand). .NET assemblies can use any of the .NETcompliant languages, and the assemblies are compiled into .dll files. These .dll files are then placed within the App_Code folder, and can be used by ASP.NET as part of the program.

Custom server controls are a specific version of assemblies. You have already seen how ASP.NET provides such controls as TextBox, Label, CheckBox, and radio button controls to aid in the development of user interfaces. Although the vast majority of server controls should cover you for most situations, and also the fact that in ASP.NET 2.0, there is an even wider range of server controls, there are still times when you

382

Componentization

might need to create controls that extend the user interface still further. Custom controls are controls that generate a visible user interface. If you consider that when ASP.NET was created, the ASP.NET server controls are actually just custom controls that someone at Microsoft has already created for you and distributed with ASP.NET 2.0. A main difference between user controls and custom controls is that user controls are intended to be confined to the application they were created for, whereas custom controls can be used with any application. Hence they are pre-compiled into assembly files, making them more portable. They also inherit from the System.Web.UI.Control namespace rather than the namespace specific to the application. Typical examples of custom controls include TreeView controls and custom file open dialogs for a particular file type.

The creation of custom controls is something you have to worry about less now, given the vast amount of controls provided with ASP.NET 2.0, and for that reason they are not covered in this book.

For in-depth discussion of custom controls, consult Professional ASP.NET 2.0 by Bill Evjen, et al, from Wrox Press.

Summar y

This chapter has taken a slightly more theory-heavy slant than previous chapters. I make no apologies for this; the only way developers can learn their trade well is by learning the best practices. This chapter has been all about componentization and code reuse. You have looked at four strategies for these. The first was the use of code-behind. The main reason for using code-behind is to separate the web page’s design, style, and user interface from the main structure and the code of the web site. The second

was using the ObjectDataSource control to create a separate business layer and data layer in your application. This was the next step, separating your application into an interface, a business rules layer, and a data layer. Third was the idea of centralizing all of our data access code into one component that could be deployed across different applications. Finally, you looked a user controls and how the use of user controls promotes code-reuse.

While this chapter has delved a lot into theory, it has been teaching you the way you should code and the techniques you should employ. Good applications are ones that contain as little code as possible, that don’t repeat the same code and ultimately run quicker, have fewer bugs and are easier to maintain,

and possibly even easier for the end-user to use. The next chapter examines another new feature in ASP.NET 2.0, that of profiles and roles.

Exercises

1.Create a new web site and a new page called CodeBehind.aspx with a single label, but making sure that you don’t check the box marked Placed Code in a Separate File. Now create a code-behind file manually for that page that displays the content of the label.

2.How would you go about adding an image to accompany each news item? Note that it shouldn’t display if there is no news image present for that article.

383

11

Roles and Profiles

Back in Chapter 4, you learned how ASP.NET handles simple user accounts, how access to a site can be controlled on a user-by-user basis, and how to group users into roles and control access to a site through the use of roles. Using the ASP.NET Web Site Administration Tool, you have the ability to define user accounts, administer roles, and set security permissions all in one central location. This chapter revisits the concept of roles and looks at how accounts and roles are used in Wrox United. You also learn how to control program logic and flow based on which roles the current user is a member of, all using code.

Additionally, because you should now feel comfortable working with .NET code, this chapter takes you on a tour of user profiles. The user profiles that you can create in ASP.NET can store additional information on a user-account-by-user-account basis; for example, a user’s favorite football team or favorite color. You’ll recall that, back in Chapter 5, the concepts of styling controls and pages using central themes were discussed; in this chapter, one of the items you’ll be adding to user profiles is the preferred theme to use for a specific web site.

In this chapter, you learn how to:

Manage site accessibility on a role-by-role basis in code

Use roles effectively in a site, using the Wrox United site as an example

Employ user profiles to store additional information about a user

Work with profiles in code to store and apply favorite themes to a site

This chapter revisits Wrox United and introduces the Fan Club page to the site. In this page, you’ll learn how to display different content depending on which role a user is a member of, and how to update a user’s profile. You’ll also make use of the powerful LoginView control, which simplifies the process of displaying different content dependent on role membership.

Chapter 11

The Impor tance of Roles

A role is a key concept to understand when you do any work on a system that involves working with user accounts. In any organization, user accounts are likely to be assigned to roles that relate to the type of user account. For example, if you look at the local user accounts set up on your PC, you will find lists of different types of groups; for example, users, power users, and administrators. In a simple Windows domain-based network, you may find that all corporate users are members of the Domain Users role. Certain user accounts in a network may be members of a different group — for example, your system administrators may be members of the Domain Administrators group, enabling them to administer the users in the company domain. Figure 11-1 displays the groups available to a fairly basic Windows XP installation; each user account can be a member of zero or more groups.

Figure 11-1

Because each user account can be a member of more than one group, if required, Figure 11-2 shows an example of an account on the same machine.

Figure 11-2

386

Roles and Profiles

Notice that the user displayed here is a member of both the Power Users and Remote Desktop Users groups. This means that the user (called Chris) can log in via a Remote Desktop session (if remote connections are allowed), and can perform most day-to-day administration tasks, with some restrictions, required on the computer.

The ability to group users together into related roles simplifies the process of administration. If my administrator wanted to grant a specific permission to all the members of the development team at the office where I work, he could either assign those permissions to each one of the 12 user accounts individually, or he could add us all to a “Developers” role, and grant that one permission to the role. It’s a simple and logical way to work, and you will almost always have to consider which roles a user is a member of when you develop an application.

One of the most important roles you will come across is that of the Administrator. An Administrator can pretty much do anything to an application or a system. For this reason, you can rejoice in the ability to log in as an Administrator to fix a problem that can only be fixed with a specific set of permissions. However, you need to be very aware of permissions when you develop applications because it’s potentially dangerous from a security perspective. Code running with full privileges can modify a system to the point where the system is completely destroyed — you don’t want to end up deleting the entire contents of your Windows directory, or formatting your hard drive accidentally.

The best practice to adopt is that of lowest-privilege; start with a low-privilege user account and add only those permissions that are required by the application. The default settings in ASP.NET mean that the code that runs ASP.NET web applications will have a limited set of privileges by default, and IIS6 (the web server provided with Windows Server 2003) is locked down tight when you first install it, so you have to actually enable ASP.NET when you install it just to run ASP.NET web applications. That doesn’t mean that you can sit back and keep running as an administrator the whole time — try logging in as a user who is only a member of Power Users, or, better still, the Users group, and test your code regularly. Never assume that an application is working without having tested it as a completely different user.

Introducing Roles in Wrox United

In the full Wrox United application, you’ll recall that roles have been configured to enable different levels of access to the site. Each user account that is defined has a different level of access, whether it’s as a site administrator or a fan club member. Time to recap a little on what you achieved in Chapter 4 — if you open up the Wrox United application source in VWD and select Website ASP.NET Configuration, you’ll see the list of current users, the list of roles, and you can explore each user account to see their roles. Figure 11-3 shows the list of roles defined in the preconfigured Wrox United application.

These screenshots were taken from the user configuration stored in the Chapter11 version of the site, though the configuration is the same in the full version of the site.

So, that’s a total of five different roles. If you look at the users defined in the application, you’ll find that there are seven different users: ChrisH, ChrisU, Dan, Dave, Jim, John, and Lou. Now, because users can be members of more than one role, and roles can have more than one member, that’s quite a few possible combinations. Clicking the Manage link shown next to each role in Figure 11-3 displays all members of a role. Figure 11-4 displays the list of FanClubMembers.

387

Chapter 11

Figure 11-3

Figure 11-4

388