If you browse the Wrox United site, you can see several examples of user controls, and one, the Newscontrol, is visible on the front page.. And there are a couple more user controls in t
Trang 1You’ll see how you can manipulate all of these controls in the same way as you might expect to whenusing a single file.
Try It Out Creating a Code-Behind File
1. Open VWD and create a new web site called TestCodeBehind in the Chapter directory(C:\BegASPNET2\Chapters\Begin\Chapter10)
2. Go to Solution Explorer and click the plus symbol (+) next to Default.aspxto expand the tree
to reveal the file Default.aspx.cs(refer to Figure 10-1)
3. Go back to the Default.aspxfile and add two Labelcontrols, a TextBoxcontrol, and aButtoncontrol, as shown in Figure 10-2
Figure 10-2
Again, Default.aspxis the only file that has the code-behind file automatically created for you If you create another Web Form, you must make sure to check the Place Code in a Separate File option, which is unchecked by default.
353
Trang 2Adjust the source HTML to read as follows:
<asp:Label ID=”Label1” runat=”server” Text=”What is the answer to the meaning oflife, the universe and everything?:”></asp:Label>
<asp:Label ID=”Label2” runat=”server” Text=””></asp:Label>
4. Go back to Design View and double-click anywhere on the background of Default.aspxotherthan on the controls Doing so will open up into the code-behind file, shown in Figure 10-3
Figure 10-3
5. Add the following code to the Page_Loadevent handler:
if (Page.IsPostBack){
if (TextBox1.Text == “42”) Label2.Text = “So you read Douglas Adams as well ”;
else{
Trang 3Label2.Text = “No, I’m not sure that’s it”;
}}
6. Click the green arrow to run it You may get a textbox asking whether or not to add a newWeb.config file or run without debugging Click the former
7. Enter a value or lengthier sentence into the text box, as shown in Figure 10-4.
Figure 10-4
How It Works
It all seems very simple — instead of putting your code within <script>tags, you place it within a arate page, connected by the Pagedirective tag Indeed, if you check at the top of the Source View forDefault.aspx, you can see that the following was already created:
sep-<%@Page CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
This refers to the code-behind file Default.aspx.cs There the following code is run when thePage_Loadevent is called (when the page is viewed) This is just the normal kind of code talked about
in Chapter 9:
if (Page.IsPostBack){
if (TextBox1.Text == “42”) Label2.Text = “So you read Douglas Adams as well ”;
else{Label2.Text = “No, I’m not sure that’s it”;
}}
It says if the page has been posted back (submitted), check the contents of the TextBoxcontrol If itequals 42, then you have your correct answer, and you set the Label2control’s Textproperty accord-ingly If the contents of the TextBoxcontrol do not equal 42, you display a different answer (“No, I’mnot sure that’s it”)
However, there is a bit more going on beneath the covers, namely the method by which your code iscompiled
355
Trang 4Compilation in ASP.NET 2.0
Compilation is another one of those subjects that this book doesn’t go into in depth, because you don’tneed to know too much about it However, you should be aware of its presence When you submit yourWeb Form to the server, your Web Form and ASP.NET pages first have to be translated into a language
the server can understand This is known as compilation You can see how this process works in NET 2.0
in Figure 10-5
Figure 10-5
The compiler changes your code into something known as intermediate code, or Microsoft Intermediate
Language (MSIL) This language is something that is independent of any PC it is run on The NET CLR(Common Language Runtime) is able to take this intermediate code and change it into executable codethat it can run and provide output for The output is then sent back to the user as a response (There’sactually a bit more to this process, as you’ll see in Chapter 14.)
During the process of compilation, your pages are approved syntactically, so if you’ve made any typossuch as the following, they will be spotted at compile time:
if (Paige.IsPostBack)
Your code can be compiled in two ways:
❑ Pre-Runtime Compilation:The “normal” way (or the “old way,” — the default way in ASP.NET1.1) Code-behind files are compiled into an assembly and stored in the \bindirectory WebForms and aspx pages are compiled when needed
Disk
Compiler
Intermediate CodeResponse
.NET CLRRuntime
Trang 5❑ Full Runtime Compilation:Code-behind files and any other associated code can now be placed
in the App_Codefolder ASP.NET 2.0 will then create and maintain references to the assemblythat is generated from these files at runtime
The App_Code Folder
If you create an App_Codefolder in your project, any code you place in that project will automatically becompiled when you run the project It’s a far more robust solution than the old \binfolder used byASP.NET 1.x, and for that reason you should use it for any code other than code-behind The reason youshould not use it for code-behind is that it is easier in VWD to keep your code files attached to the pagethey are related to; otherwise viewing them could be a pain
So not only can you organize your code and in which pages it is placed, but ASP.NET 2.0 dictates a different structure for ordering where those pages are placed
Data Layers
You’ve looked at how code and content can be successfully separated, but there is a third dimension toour discussions, namely that of the data Throughout this book, we’ve paused to reflect briefly on vari-ous aspects of the history of the Internet and the Web, while trying to keep you away from a huge lec-ture on the entire subject However, another quick history lecture is in order here to help you understandthe purpose of the next ASP.NET 2.0 feature
Two-Tier Applications
Rather than rewinding too far back, let’s jump in halfway When HTML started getting beyond the versities, it became necessary to provide something more than just static text and images One of the firstways in which web pages were made dynamic was to enable them to access a database The browserwas one tier, and the database was the second tier In this scenario, the browser dealt with rules aboutthe business or application and user interface
uni-The data retrieval and manipulation was performed by another separate database application, such asSQL Server or Microsoft Access It would handle the data storage and retrieval device for the applica-
tion These two-tier applications were also commonly know as server applications A typical
client-server application is depicted in Figure 10-6
The term business rules is used to encompass any part of the application logic that
isn’t the user interface or the database If the application isn’t being used for a
busi-ness, then the term application logic might be more applicable, although they mean
the same thing.
There is actually a third option called deployment pre-compilation, which is for full compilation of your project prior to deployment You’ll learn a little more about this
in Chapter 16.
357
Trang 6Figure 10-6
The other popular variation on the two-tier application saw the business rules (application logic) being
executed on the database system Such applications would commonly use stored procedures to manipulate
the database (or in some cases triggers) A stored procedure is a query that is stored on the database Itcan be called by the client application and then run on the server It would contain rules about the busi-ness as well For example, if you had a league table on Wrox United that awarded three points for a winand one point for a draw, then in the database query, it would somehow have to record that when oneside scores more goals than another side, it is worth three points This is a business rule It doesn’t mat-ter to the database how many points you add on to the win; however, your league table would fail towork properly if you added two or five points for a win
Three-Tier Applications
The big difference with three-tier applications is that business rules are no longer located on either theclient or the database They are stored and run on a system in between the client and the server Theadvantage of this is that the business rules server can ensure that all of the business processing is donecorrectly There is now a third layer interface, business rules and data The introduction of the data tier isillustrated in Figure 10-7
Figure 10-7
In a three-tier application, the client never accesses the data storage system directly You can makechanges to the business rules and this would mean you could change any part of the system withouthaving to alter the other two parts As the three different sections of the application communicate viainterfaces, and as long as the interface between the code and application front-end remains the same,the internal workings of each part can be changed without affecting the rest of the application The
DataSource
REQUEST
RESPONSE
Trang 7advantages of doing this are similar to those for keeping code and content separate Typically, a database
is managed by a database administrator (DBA), and it might even be managed by a separate company.The web developer as jack-of-all-trades would previously have been required to know the intimateworkings of the database, when really they shouldn’t be interfering there at all So this brings you to theend of your little excursion, because you can now look at a new feature in ASP.NET 2.0 that allows you
to separate your applications more simply into three tiers
What’s New in ASP.NET 2.0
In ASP.NET 2.0, you are no longer restricted to binding only to data controls You can also bind to rate business controls via the ObjectDataSourcecontrol
sepa-Using the ObjectDataSource Control
The new ASP.NET ObjectDataSourcecontrol enables you to declaratively bind data controls such asthe GridView, DataList, and DropDownListcontrols to a separate business control or a data compo-nent Previously, you could only bind the controls directly to a database This new development enablesthe separation of your business rules from your content and your data
ObjectDataSourceis a more difficult control to explain than a GridViewor DropDownListcontrol, sorather than wasting excessive verbiage, it’s quicker to show you exactly what the ObjectDataSourcecontrol does in an example You’re actually going to do two examples to show it in action In the firstexample, you’ll see how to create a data component to return a list of players from the Players table ThisTry It Out is split into two sections: the first section where you create the ObjectDataSourceitself andthe second where you bind the ObjectDataSourcecontrol to a GridViewcontrol The resulting outputwill be completely non-editable In the second example, you’ll use the Try It Out to create a data compo-nent that can not only read from the Wrox United database but also write data to it You’ll create andbind the data component in this same example that will make it quite lengthy
The data component that you create in both examples will consist of an XSD schema file (.xsd) This filedescribes the data you require and defines which methods will be used to read and write data Thisdoesn’t require any code or knowledge of XML schemas because when you run the application, the xsdfile is compiled for you and performs all of the tasks needed
Start by creating the data component for the read-only example
Try It Out Creating the Data Component
1. Open Visual Web Developer and select Open Web Site From the C:\BegASPNet2\Chapters\Begin\Chapter10folder, select ObjectDataSourceand click OK
2. In Solution Explorer, right-click the name of your web site, select Add ASP.NET Folder, andselect App_Code
3. Right-click the App_Codefolder and select Add New Item from the list
4. From the Visual Studio installed templates, click DataSet
5. Rename the DataSet ods.xsd and click Add.
6. VWD starts the TableAdapter Configuration Wizard (Be patient here, because this one reallydoes take a while to kick in.) When the wizard finally arrives, select ConnectionString (Web.config) from the drop-down list (see Figure 10-8) and click Next
359
Trang 8Figure 10-8
7. Next you get a page where you can choose to use SQL statements or stored procedures Selectthe Use SQL statements radio button (as shown in Figure 10-9) and click Next
Figure 10-9
Trang 98. On the next wizard screen, you can define the SQL statement Type the following SQL statementinto the “What data should be loaded into the table” area of the dialog box:
SELECT PlayerID, FirstName, LastName, Position, DateJoined, DateLeft FROM Players
9. After entering the SQL statement, click Next You can now define which methods the nent will expose Uncheck the Fill a DataTable check box and make sure that the Return a
compo-DataTable check box is checked (see Figure 10-10) In the Method name box, type GetPlayers.
This method is used later to retrieve the data Uncheck the final check box
Figure 10-10
10. Click Finish In Figure 10-11, you can see the data component in the designer It shows both thedata you selected and the method you created
Figure 10-11
11. Save the data component and close the component designer.
12. Select Build➪Build Web Site to compile the component (Note that this won’t produce anythingviewable.)
361
Trang 10How It Works
The data component is now usable as a data source within a Web Form You’ve used the wizard to createthe component for you, to select the fields from the database, and also to name the method by which youwant to be able to call this component
Thenext step is to bind to this component To do this, you can create and configure an
ObjectDataSourcecontrol You can then add controls, such as the GridViewcontrol, to the page andbind them to the data source control
Try It Out Binding to the ObjectDataSource Control
1. Open the Default.aspxfrom Solution Explorer and switch to Design View
2. Open the Toolbox and from the Data section drag an ObjectDataSourcecontrol onto the page
3. Select the Toolbox again, and from the Data section drag a GridViewcontrol onto the page
4. Click the black arrow in the top-right corner of the ObjectDataSourcecontrol The CommonTasks box appears with the words “Configure Data Source.” Click this
5. In the dialog box that appears, there is a single drop-down list asking you to choose your business object (see Figure 10-12) There should only be one, the odsTableAdapters
PlayersTableAdapter Select it and click Next
Figure 10-12
6. On the next screen (shown in Figure 10-13), under the Select tab in the Choose a method down box, the GetPlayers(), returns PlayersDataTablemethod is displayed Select itand click Finish (the other methods are automatically picked for you)
Trang 11drop-Figure 10-13
7. Click the black arrow on the top-right corner of the GridViewcontrol and from the Choose DataSource list that appears, select ObjectDataSource1 The Grid will update in Design View
8. Open the Properties window and check that the DataKeyNamesproperty is set to PlayerID
9. Run the application, and you will see Figure 10-14 in your browser
Trang 12How It Works
You started by creating an instance of an ObjectDataSourcecontrol To give it its functionality, youattached it to the GetPlayers()method that was specified in the data component The GetPlayers()method was created in the previous Try It Out This method returns the results of the SQL statement,available as a DataTableobject The DataTableobject is an object that the GridView(and indeed alldata controls) can bind to If you go back and look at the source that has been created, you can see thesource for the two controls you added to your form
The Wrox United ObjectDataSource
This data so far has been static So as mentioned previously, in this next Try It Out, you go one furtherand use the ObjectDataSourcecontrol to be able to edit and update your squad’s details In the Adminsection of the Wrox United site, there is a page called EditSquad.aspx, which is used to change theplayers’ details However, it uses the SqlDataSourcecontrol for the details This can be replaced with
an ObjectDataSourcecontrol It has insert, update, select, and delete methods that map neatly to themethods in a simple class
Trang 13Try It Out The Wrox United ObjectDataSource
1. Open the Wrox United application from the chapter samples (C:\BegASPNET2\Chapters\Begin\Chapter10\WroxUnited) in Visual Web Developer
2. Right-click the App_Codefolder and select Add New Item from the list
3. From the Visual Studio installed templates, click DataSet
4. Rename the DataSet wroxunited.xsd and click Add.
5. VWD starts the TableAdapter Configuration Wizard (As before, be patient here.) When the wizard finally arrives, select wroxunited (Web.config) and click Next
6. When you get the page where you can choose to use SQL statements or stored procedures.select the Use SQL statements radio button and click Next
7. On the next wizard screen, you can define the SQL statement Type the following SQL statementinto the “What data should be loaded into the table” area of the dialog box:
SELECT PlayerID, FirstName, LastName, Position, PictureURL, DateJoined, DateLeftFROM Players
WHERE PlayerID = @PlayerID
8. After entering the SQL statement, click Next You can now define which methods the nent will expose Uncheck the Fill a DataTable check box and make sure that Return a DataTable
compo-check box is compo-checked In the Method name box, type GetPlayers This method is used later to
retrieve the data Make sure the final check box, “Create methods to send update directly to thedatabase,” is checked
9. Click Next and then click Finish Save the data component, and close the component designer.
10. Select Build➪Build Web Site to compile the component.
11. Open the Admin folder of WroxUnited and open the EditSquad.aspxfile
12. In Design View, scroll down, select the second SqlDataSourcecontrol, DetailsDataSource(shown in Figure 10-15), and delete it
13. From the Data Section of the Toolbox, drag an ObjectDataSourcecontrol where theSqlDataSourceused to be
14. Click the black arrow at the top right of the ObjectDataSourcecontrol, and from the CommonTasks menu, select Configure Data Source
15. In the opening dialog box, select wroxunitedTableAdapters.PlayersTableAdapterandclick Next
16. In the Select tab, select the GetPlayers(Int32 PlayerID), returns PlayersDataTablemethod from the drop-down list box and click Next
17. In the Define Parameters dialog box, select Control from the Parameter Source drop-down listbox Select GridView1in Control view The parameters on the left of the dialog box will nowshow GridView.SelectedValue Click Finish
365
Trang 14Figure 10-15
18. Right-click the ObjectDataSourcecontrol in Design View and select Properties
19. In the Properties window, change the (ID)property so that it reads “DetailsDataSource”
20. Open EditSquad.aspx.csand amend the code in the procedure parameters to read as follows
in the three subs:
protected void DetailsDataSource_Updated(object sender ,
Trang 1521. Save and close the file.
22. Run the application, log in as an administrator (dave\dave@123), and navigate to the
EditSquad.aspxpage It works in the same way as before except that you are now using anObjectDataSourcecontrol
How It Works
You haven’t changed much between this and the previous example You built a data component, andyou then added an ObjectDataSourcecontrol into the EditSquad.aspxpage You added methods forthe Update, Insert, and Delete methods via the wizard The code that provided your functionality in theclasses was already in existence — all you had to do was change the references from the SqlDataSourcecontrol to the ObjectDataSourcecontrol Then you ran it, and the WroxUnited application was able touse the ObjectDataSourceinstead
User Controls
Your final problem is that of making your code easy to reuse, and this is addressed by user controls.
Again, these existed in ASP.NET 1.x, but this is something that also has been improved upon in ASP.NET2.0 So what are user controls? Well in a nutshell, user controls are reusable Web Forms They’ve beenthrough several name changes and evolutions from scriptlets to pagelets, before arriving at user con-trols They can be thought of as mini-scripts, mini-pages, or pages within your pages, but however youchoose to think of them, the key is that they can be called up as many times as you need them
If you browse the Wrox United site, you can see several examples of user controls, and one, the Newscontrol, is visible on the front page In fact, if you look at the front page (shown in Figure 10-16), it is amultitude of components garnered from different sources
The Newscontrol is a user control, the Logincontrol is an ASP.NET control, the shopping cart is a link to
a user control, and the menu is derived from the site master, which itself is an ASP.NET control So theentire site front page and design is reusable If you click the Shopping Cart link, you will see the seconduser control, shown in Figure 10-17
And there are a couple more user controls in the administrative section of the site too, but you get theidea that these controls can be used in multiple pages, or called from different places, and rather thanhaving to cut and paste the code individually each time, you can just call on this one section of code overand over again One question you might have is how do they differ from the normal ASP.NET servercontrols, such as the TextBoxcontrol or the Logincontrol that you looked at earlier?
Very little is the answer The main difference is that you have to provide the code behind the controlyourself, whereas ASP.NET server controls come fully functional out of the box You can add properties
to user controls and set them as attributes, just like you would with a normal ASP.NET server control
367
Trang 16Figure 10-16
So why isn’t everything an ASP.NET server control? Well, ASP.NET 2.0 ships with a multitude of trols designed for the most common scenarios and situations ASP.NET 2.0 adds greatly to the number ofserver controls For example, in ASP.NET 1.1 if you wanted a Logincontrol, you had to stitch together ausername text box, a password text box, a button, and a label for messages within a panel, so you had tocreate this as a user control In version 2.0, the Logincontrol comes as a server control However, it justisn’t possible to anticipate everything that a user might want or need Therefore, it makes sense to havethe flexibility to create your own
con-If you view the source code in Internet Explorer for the home page (Default.aspx) in WroxUnited.net,you’ll see no indication that a user control has been used — it’s all HTML elements and some occasionalscript, which is just as it should be If you were using a Flash plug-in or a Java applet, you would seesome indication with an <object>tag or on older browsers, possibly an <embed>tag So there’s noworry about extra download time being taken either
Login Control (ASP.NET)
Trang 17Figure 10-17
If you look at the actual page that is sent to the server, you can see the user control is included with twosimple lines of code that highlighted here (this source code page is available for download at
www.wrox.com):
<%@ Page Language=”C#” Trace=”false” MasterPageFile=”~/site.master”
AutoEventWireup=”true” codefile=”Default.aspx.cs” Inherits=”_Default” %>
<%@ Register TagPrefix=”uc1” TagName=”News” Src=”News.ascx” %>
<asp:Content ID=”Content1” ContentPlaceHolderID=”mainContent” Runat=”server”>
<h2>Welcome to the Wrox United Web site.</h2>
<p>We’re a great football team No really, we are Don’t take any notice
of our past performance We’re just unlucky.</p>
<uc1:news id=”News1” runat=”server” ItemsToShow=”3”></uc1:news>
</asp:Content>
This page starts giving you some clues as to how user controls work
User Control Structure
User controls are stored in separate files with a separate ascx extension Any time you see this extension,you know that you are dealing with a user control To create a user control, you need to add a @Registerdirective to the top of your Web Form identifying where you can find your user control:
<%@Register TagPrefix=”WroxUnited” TagName=”MyControl” %>
369
Trang 18You need to add a new tag specifying where the control will go on your page It consists of the
TagPrefix, followed by a colon, followed by the TagName, an ID, and the now familiar runat=serverattribute:
<WroxUnited:MyControl id=”mycontrol1” runat=”server”>
</WroxUnited:MyControl>
Lastly, you need to specify the user control itself in a separate ascx file Unlike Web Forms, you don’tneed to specify extra <html>and <body>tags, because the contents of this control will be added to thebody of the containing main page In fact, all you need to have is the controls that you want to include.For example, you could include the controls from the code-behind example used earlier in the chapter:
<asp:Label ID=”Label1” runat=”server” Text=”What is the answer to the meaning
of life, the universe and everything?:”></asp:Label>
<asp:TextBox ID=”TextBox1” runat=”server”></asp:TextBox>
<br /><br />
<asp:Button ID=”Button1” runat=”server” Text=”Submit” />
<br />
<asp:Label ID=”Label2” runat=”server” Text=””></asp:Label>
Of course, user controls can have code-behind files as well, just like Web Forms:
public void Page_Load( object sender, System.EventArgs e)
{
if (Page.IsPostBack){
if (TextBox1.Text == “42”) Label2.Text = “So you read Douglas Adams as well ”;
else{Label2.Text = “No, I’m not sure that’s it”;
}}
This control can then be bolted into your web pages wherever you specify the @Registerdirective andadd a tag for the control
A Simple User Control
In the next Try It Out, you’re going to start by creating a trivial “Hello World”-style user control to getyou used to the idea of including them in your pages This code does no more than encapsulate thecode-behind from the first example you created in the chapter as a user control You’ll see how you canplace the user control in one web page, and then in a second web page
Try It Out Creating a Simple User Control
1. Open VWD and create a new ASP.NET web site called SimpleUserControl in the chapter
direc-tory (C:\BegASPNET\Chapters\Begin\Chapter10)
2. In Solution Explorer, right-click the web site and select Add New Item Select Web User Control,
enter the name SimpleUserControl.ascx, and check the Place Code in Separate File option, as
shown in Figure 10-18
Trang 20You can cut and paste the relevant code from the first Try It Out in this chapter into Source View
if you still have it at hand:
<asp:Label ID=”Label1” runat=”server” Text=”What is the answer to the meaning oflife, the universe and everything?:”></asp:Label>
<asp:TextBox ID=”TextBox1” runat=”server”></asp:TextBox>
<br /><br />
<asp:Button ID=”Button1” runat=”server” Text=”Submit” />
<br />
<asp:Label ID=”Label2” runat=”server” Text=””></asp:Label>
4. Double-click the page again and this time, add the following code-behind to
SimpleUserControl.ascx.cs:public partial class SimpleUserControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e){
if (Page.IsPostBack){
if (TextBox1.Text == “42”) Label2.Text = “So you read Douglas Adams as well ”;
else{Label2.Text = “No, I’m not sure that’s it”;
}} }}
5. Next you need to add this control to a page From Solution Explorer, drag
SimpleControlUser.ascxinto Design View for Default.aspx(see Figure 10-20)
6. Click the green arrow to run Default.aspx It works in exactly as it did in the first Try It Out ofthis chapter, as evidenced in Figure 10-21
7. Go to Solution Explorer and right-click the project Select Add New Item and add a new Web
Form to the page called secondpage.aspx.
8. Go to Design View and drag SimpleUserControl.ascxinto this page Next, go to SolutionExplorer and right-click secondpage.aspxand select Set As Start Page
Trang 22There’s nothing to stop you from copying this tag and pasting it again and again in the page, although itmight make your page a little illogical, with several versions of the user control Note that this examplegot you to cut and paste the old code from the code-behind page This was quite deliberate because thiswas the old way of transferring replicated code Each time you wanted to transfer the code, you wouldcut and paste it manually Not only is cutting and pasting more labor-intensive, but it is also far moreprone to mistakes, because if you altered the code in one page, it would need to be altered in all of therest With user controls, any changes you need to make can just be made to the ascx file and the ascx.csfile themselves, and then every time the user control is called, it automatically uses the new code.
Trang 23The Wrox United News User Control
You’re now going to move onto a more complex user control, and one that is used on the Wrox Unitedweb site You’re going to re-create the Newscontrol that you find on the main Wrox United site This con-trol scans the News table, selects the most up-to-date stories, and displays them on the front page, withthe most recent being displayed first
Before you launch into the coding, it’s worth saying a little bit about why we chose to make this a usercontrol, while other bits and pieces we chose not to ANewscontrol is something that is going to be com-mon on many web sites (although technically speaking, user controls shouldn’t be used across severalapplications — as you will see at the end of this chapter — because there is something better served forthat purpose) It is also something that will quite likely be called upon at several places throughout theapplication (although you only call upon it once within the Wrox United application), and the principlewill remain the same throughout — it will display a list of articles in order, with the most recent first Ofcourse, not all things you will design on this site will be suitable for reuse and for creating as user con-trols, but the Newscontrol is a content delivery mechanism and content is the driving force behind mostweb sites In the following Try It Out, you create your own Newsuser control and drop it into your ownblank page
Try It Out Using the News Control
1. Open Visual Web Developer and select Open Web Site From the Chapter10 folder (C:\BegASPNET\Chapters\Begin\Chapter10), select WroxUnitedNewsControland click OK
2. Go to Visual Web Developer and right-click the top item in Solution Explorer Select Add New
Item and select Web User Control Type NewsUserControl.ascx in the Name text box Make
sure the Place Code in Separate File check box is selected, as shown in Figure 10-23
Figure 10-23
3. Go to Design View and drag a SqlDataSourcecontrol from the Data section of the Toolboxmenu Don’t, however, click to configure the Data Source from the Common Tasks box thatappears
375
Trang 244. From the Data section of the Toolbox menu, add a Repeatercontrol below the SqlDataSourceand select SqlDataSource1to be the Repeater’s Data Source (see Figure 10-24).
Figure 10-24
5. Add the template to the HTML With the Repeatercontrol, you have to switch to Source View
to add the template Switch to Source View and add the following code:
<asp:Repeater ID=”Repeater1” Runat=”server” DataSourceID=”SqlDataSource1”>
This contains the connection string information that you will need for this example
7. Go to the code-behind file and add the following code for an ItemsToShowproperty, whichgoverns how many items are shown on the screen at the same time:
Trang 25public partial class NewsUserControl : System.Web.UI.UserControl{
private int _itemsToShow = 5;
public int ItemsToShow {
get{return _itemsToShow;
}set{_itemsToShow = value;
}}
8. Add the following code directly underneath the code you previously added:
private void Page_PreRender(object sender, System.EventArgs e){
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;
}
9. Go to Solution Explorer and create a new Web Form called NewsDisplay.aspx Go to Design
View and drag your NewsUserControl.ascxinto the Web Form
10. 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
377
Trang 2611. Go back to Source View and add an ItemsToShowattribute, 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.cssfile fromthe templates folder in the directory into the aspx file to apply the style sheet
Figure 10-26
How It Works
You have a Newscontrol that not only can you drop in any page (it is used on the front page of the WroxUnited site), but also enables you to configure the number of items shown via a single attribute The fol-lowing code has been created in the user control, a SqlDataSourcecontrol that queries the news tabletogether with a Repeatercontrol that displays each of the news items:
<%@ Control Language=”C#” AutoEventWireup=”false” codefile=”News.ascx.cs”
Trang 27It’s the behind that provides the main functionality Once again, the relationship between the behind and the main control is shown You added an ItemsToShowproperty to the code-behind andexposed 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;
code-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 Theproperty enables you to both get and set the separate values
The code that occurs in the Pre_Renderevent enables you to display the contents of the control This issimilar to the Page_Loadevent, except it occurs just before the controls on a page are rendered Becauseyou want to display these at the last possible moment, you place two statements here The first one pro-vides a SQL statement that selects the top news items ordered by date, and restricted by the _itemsToShowvariable 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
Assemblies and Custom Ser ver Controls
.NET also provides the capability to pre-compile code components into a central location that can beaccessed 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
Trang 28inside the component itself at runtime (in other words, the component isn’t compiled at the same time asthe main application, but rather has to be done beforehand) .NET assemblies can use any of the NET-compliant languages, and the assemblies are compiled into dll files These dll files are then placedwithin the App_Codefolder, 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 vides such controls as TextBox, Label, CheckBox, and radio button controls to aid in the development
pro-of user interfaces Although the vast majority pro-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 timeswhen you might need to create controls that extend the user interface still further Custom controls arecontrols that generate a visible user interface If you consider that when ASP.NET was created, theASP.NET server controls are actually just custom controls that someone at Microsoft has already createdfor 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 customcontrols can be used with any application Hence they are pre-compiled into assembly files, makingthem more portable They also inherit from the System.Web.UI.Controlnamespace rather than thenamespace specific to the application Typical examples of custom controls include TreeViewcontrolsand 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 waydevelopers can learn their trade well is by learning the best practices This chapter has been all aboutcomponentization and code reuse You have looked at four strategies for these The first was the use ofcode-behind The main reason for using code-behind is to separate the web page’s design, style, anduser interface from the main structure and the code of the web site The second was using the
ObjectDataSourcecontrol to create a separate business layer and data layer in your application Thiswas 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 deployedacross different applications Finally, you looked a user controls and how the use of user controls pro-motes code-reuse
Although this chapter delved a lot into theory, it also taught you the way you should code and the niques you should employ Good applications are ones that contain as little code as possible, that don’trepeat the same code and ultimately run quicker, have fewer bugs and are easier to maintain, and arepossibly even easier for the end-user to use The next chapter examines another new feature in ASP.NET2.0, that of profiles and roles
Trang 291. Create a new web site and a new page called CodeBehind.aspx with a single label, but makingsure 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’tdisplay if there is no news image present for that article
381
Trang 31Roles and Profiles
In Chapter 4, you learned how ASP.NET handles simple user accounts, how access to a site can becontrolled on a user-by-user basis, and how to group users into roles and control access to a sitethrough the use of roles Using the ASP.NET Web Site Administration Tool, you have the ability todefine user accounts, administer roles, and set security permissions all in one central location Thischapter 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 amember of, all using code
Additionally, because you should now feel comfortable working with NET code, this chaptertakes you on a tour of user profiles The user profiles that you can create in ASP.NET can storeadditional information on a user-account-by-user-account basis; for example, a user’s favoritefootball team or favorite color You’ll recall that, in Chapter 5, the concepts of styling controls andpages using central themes were discussed; in this chapter, one of the items you’ll be adding touser 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 siteThis chapter revisits Wrox United and introduces the Fan Club page to the site In this page, you’lllearn how to display different content depending on which role a user is a member of, and how toupdate a user’s profile You’ll also make use of the powerful LoginViewcontrol, which simplifiesthe process of displaying different content dependent on role membership
Trang 32The 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 differenttypes 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 Certainuser accounts in a network may be members of a different group — for example, your system adminis-trators may be members of the Domain Administrators group, enabling them to administer the users inthe company domain Figure 11-1 displays the groups available to a fairly basic Windows XP installa-tion; 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 anexample of an account on the same machine
Figure 11-2
Trang 33Notice that the user displayed here is a member of both the Power Users and Remote Desktop Usersgroups This means that the user (called Chris) can log in via a Remote Desktop session (if remote con-nections 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 administratorwanted to grant a specific permission to all the members of the development team at the office where Iwork, he could either assign those permissions to each one of the 12 user accounts individually, or hecould add us all to a “Developers” role, and grant that one permission to the role It’s a simple and logi-cal way to work, and you will almost always have to consider which roles a user is a member of whenyou develop an application
One of the most important roles you will come across is that of the Administrator An Administrator canpretty much do anything to an application or a system For this reason, you can rejoice in the ability tolog 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 poten-tially dangerous from a security perspective Code running with full privileges can modify a system tothe point where the system is completely destroyed — you don’t want to end up deleting the entire con-tents 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 onlythose permissions that are required by the application The default settings in ASP.NET mean that thecode that runs ASP.NET web applications will have a limited set of privileges by default, and IIS6 (theweb server provided with Windows Server 2003) is locked down tight when you first install it, so youhave to actually enable ASP.NET when you install it just to run ASP.NET web applications That doesn’tmean that you can sit back and keep running as an administrator the whole time — try logging in as auser 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 els of access to the site Each user account that is defined has a different level of access, whether it’s as asite administrator or a fan club member Time to recap a little on what you achieved in Chapter 4 If youopen up the Wrox United application source in VWD and select Website➪ASP.NET Configuration, you’llsee 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
lev-These screenshots were taken from the user configuration stored in the C:\BegASPNET2\Chapters\Begin\Chapter11version 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 thatthere are seven different users: ChrisH, ChrisU, Dan, Dave, Jim, John, and Lou Because users can bemembers of more than one role, and roles can have more than one member, that’s quite a few possiblecombinations Clicking the Manage link shown next to each role in Figure 11-3 displays all members of arole Figure 11-4 displays the list of FanClubMembers
385
Trang 34Figure 11-3
Figure 11-4
Trang 35You can continue to explore each of the user accounts and roles to see who is a member of each group, soyou 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 theAdmin 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 linksavailable 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 WroxUnited 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 willsee 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: FanClubMatchReport.aspxand FanClubPictures.aspx
At the moment, the pages are looking a bit empty, so it’s time to start adding some code
3. Open FanClub.aspxin Visual Web Developer and switch to Design View
4. Drag a LoginViewcontrol 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 bership before they can access the fan club pages
mem-❑ Administrator/Manager/Owner/Reporter:All logged-in users who are not members ofthe Fan Club will be told to contact the administrator of the site to gain access to the fanclub
❑ FanClubMembers:Members of the Fan Club will be able to change their passwordsand to update their profiles (you add this part later in the chapter)
387
Trang 36Figure 11-5
Trang 376. In the Common Tasks box of the LoginViewcontrol (the flyout highlighted in Figure 11-6), clickthe Edit RoleGroups link In the dialog box that appears (shown in Figure 11-7), you can enterthe details for the two custom role groups Click the Add button to add a new group, and then
click the ellipsis next to the Roles property on the right and enter FanClubMember in the dialog
box that appears
Figure 11-7
7. Repeat the process and enter Administrator, Owner, Manager, and Reporter, each on separate
lines in the pop-up, as depicted in Figure 11-8
Figure 11-8
8 Click OK to close the dialogs and you’ll be returned to the Design View for the page
9. Back in the Common Tasks box of the LoginViewcontrol (refer to Figure 11-6), select theAnonymousTemplate from the View drop-down and enter just a few words of text in the body
of the control (see Figure 11-9)
389
Trang 38Figure 11-9
When you return to Source View, you will now see the following code:
<%@ Page Language=”C#” MasterPageFile=”~/site.master” AutoEventWireup=”false”CodeFile=”FanClub.aspx.cs” Inherits=”FanClub” Title=”Fan Club” %>
<asp:Content ID=”Content1” ContentPlaceHolderID=”mainContent” Runat=”Server”>
<asp:LoginView ID=”FCLoginView” runat=”server”>