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

Beginning ASP.NET 2.0 With CSharp (2006) [eng]

.pdf
Скачиваний:
86
Добавлен:
16.08.2013
Размер:
20.33 Mб
Скачать

Chapter 10

11.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>

12.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.

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 enables 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 news items:

<%@ Control Language=”C#” AutoEventWireup=”false” codefile=”News.ascx.cs” 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>

378

Componentization

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

private int _itemsToShow = 5; public int ItemsToShow

{

get

{

return _itemsToShow;

}

set

{

_itemsToShow = value;

}

}

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

The code that occurs in the Pre_Render event enables you to display the contents of the control. 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 _items ToShow variable that you created at the top of the class:

string sel = string.Format(“SELECT Top {0} * FROM [News] WHERE DateToShow <= ‘{1}’ ORDER BY DateToShow DESC”, _itemsToShow, DateTime.Now.ToString(“yyyy/MM/dd”));

//Make sure above is all on one line. SqlDataSource1.SelectCommand = sel;

The second statement 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 a News control, 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

379

Chapter 10

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 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 dialog boxes 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, because 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.

Although this chapter delved a lot into theory, it also taught 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 are 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.

380

Componentization

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 codebehind 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.

381

11

Roles and Profiles

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, 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 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 domainbased 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

384

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 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 C:\BegASPNET2\Chapters\ Begin\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. 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.

385

Chapter 11

Figure 11-3

Figure 11-4

386

Roles and Profiles

You can continue to explore each of the user accounts and roles to see who is a member of each group, so you can discover the following (among other things):

ChrisH, ChrisU, Dave, and John are reporters.

Dave is a member of all groups; hence he’s the “super user” (who can access all areas of the site, which is great for testing).

Lou is only a member of the Fan Club; hence she is the only true fan of the team.

Dan’s the team’s manager and Jim’s the owner.

After digging through the site configuration, in the Access Rules section, you’ll also recall that the Admin section of the site was restricted so that only site administrators could enter that part of the site. Additionally, the Fan Club was restricted so that only members could see the fan club–specific links available in the fan club section.

In the next example, you get to use this configuration and try it out for yourself. The Fan Club for Wrox United is a good place to start.

In the following Try It Out, you build the skeleton for the Fan Club page and see how different users will see a different version of the page, depending on whether they are logged in, and, if the user has logged in, the current user’s identity.

Try It Out

The Wrox United Fan Club

1.Open up the chapter version (in C:\BegASPNET2\Chapters\Begin\Chapter11\WroxUnited) of the Wrox United application and run the site by pressing Ctrl+F5.

2.Log in to the site as Lou, using the password lou@123. There is a link to the Fan Club (FanClub

.aspx) in the menu on the left (shown in Figure 11-5), and to the two subpages: FanClubMatch Report.aspx and FanClubPictures.aspx.

At the moment, the pages are looking a bit empty, so it’s time to start adding some code.

3.Open FanClub.aspx in Visual Web Developer and switch to Design View.

4.Drag a LoginView control onto the page, as shown in Figure 11-6.

5.Rename the control FCLoginView.

You’re going to create three different views on this page:

AnonymousTemplate: Anonymous visitors will be asked to purchase a Fan Club membership before they can access the fan club pages.

Administrator/Manager/Owner/Reporter: All logged-in users who are not members of the Fan Club will be told to contact the administrator of the site to gain access to the fan club.

FanClubMembers: Members of the Fan Club will be able to change their passwords and to update their profiles (you add this part later in the chapter).

387