Beginning ASP.NET 1.1 with Visual C# .NET 2003 phần 6 ppt

90 279 0
Beginning ASP.NET 1.1 with Visual C# .NET 2003 phần 6 ppt

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

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

Thông tin tài liệu

{ Session["SelectedCss"] = "WroxUnited.css"; } else { Session["SelectedCss"] = Request.Cookies["PreferredCss"].Value; } } } That's quite a lot of Ifs! Don't worry – we will come to this in just a moment. However, before you can run the code, you need to include some stylesheets or nothing will be displayed! You will also need to make some minor adjustments to some of the code on the page, notably to the Calendar control's DayRender event handler, to make the page look a bit nicer when the stylesheet is applied. 6. First, change the DayRender event handler as follows (remove the original style settings and replace them with a single class statement): public void EventCalendar_DayRender(object sender, DayRenderEventArgs e) { if (((Hashtable)Cache["DateList"])[e.Day.Date] != null) { e.Cell.CssClass = "selecteddate"; // e.Cell.Style.Add("font-weight", "bold"); // e.Cell.Style.Add("font-size", "larger"); // e.Cell.Style.Add("border", "3 dotted darkred"); // e.Cell.Style.Add("background", "#f0f0f0"); // The following line will exist in your code if you completed the // exercises at the end of the last chapter e.Day.IsSelectable = true; } else { // This line of code is part of the solution to one of the exercises at // the end of chapter 10 e.Day.IsSelectable = false; e.Cell.CssClass = "normaldate"; // e.Cell.Style.Add("font-weight", "lighter") // e.Cell.Style.Add("color", "DimGray") } } 7. Change the code for the calendar in the HTML view: <asp:Calendar id="EventCalendar" runat="server" OnSelectionChanged="EventCalendar_SelectionChanged" OnDayRender="EventCalendar_DayRender" CssClass="calendar"> <DayStyle cssclass="normaldate"></DayStyle> <OtherMonthDayStyle cssclass="othermonthdate"></OtherMonthDayStyle> 423 Users and Applications </asp:Calendar> 8. Now create a new blank stylesheet, and call it WroxUnited.css, as shown in Figure 11-18: Figure 11-18 9. In this new stylesheet, enter the following code: BODY { { background-image:url(images/background.gif); color:"#000000"; font-family: georgia; } a { color:"#8b0000"; font-weight:bold; } .selecteddate{ font-weight: bold; font-size: larger; border: 3 dotted darkred; background:#f0f0f0; } .normaldate{ font-weight:lighter; color:dimgray; } .calendar a{ text-decoration:none; font-size: 10pt; } 424 Chapter 11 .othermonthdate{ font-weight:lighter; color:#d3d3d3; } 10. Save this as WroxUnited.css in the WroxUnited folder. Then, change the following lines and save the file with a different name, WroxUnited2.css: BODY { background-image:url(images/awaybackground.gif); color:"#ffffff"; font-family: georgia; } a { color:"yellow"; font-weight:bold; } .calendar a{ text-decoration:none; } .selecteddate { font-weight: bold; font-size: larger; border: 3 dotted white; background:#c0c0c0; } .normaldate { font-weight:lighter; color:#d3d3d3; } .othermonthdate { font-weight:lighter; color:dimgray; } 11. Finally, you need to get hold of the two background images that are used in the two stylesheets, background.gif and awaybackground.gif. Both are available for download from the Wrox site. They are extremely small images, so they will not take long to download. 12. It's about time to run the page and try it out for yourself! The first style you'll see is the Home style page, as shown in Figure 11-19, the away kit that is shown in Figure 11-20, is fairly different, as you’ll no doubt notice! 425 Users and Applications Figure 11-19: Figure 11-20 426 Chapter 11 13. If you check the Remember Preference box before clicking Apply, the style you are applying will be remembered for you in a cookie. Next time you open the site, this stylesheet will be the default. How It Works This example rolled together two different techniques, sessions and cookies, and gave a unified look and feel that you can apply to all the pages in this site. The first thing done was to use the contents of the Session object to provide a filename for the <Link > tag in the head section of the ASP.NET page: <html> <head> <link id="css" href='<%= (string)Session["SelectedCss"] %>' type="text/css" rel="stylesheet" /> </head> You'll recall that the <%= %> syntax is used to access ASP.NET objects from the HTML side of the page. This technique is certainly adequate for this example, and is a simple way to get to the contents of the Session object. The next step was to add some controls to the page to select and apply the stylesheet to the page: <hr /><br/><br/> <p> Choose a theme: <br/> <asp:DropDownList id="ddlTheme" runat="server"> <asp:ListItem Value="WroxUnited.css" Selected="true"> Home Kit</asp:ListItem> <asp:ListItem Value="WroxUnited2.css">Away Kit</asp:ListItem> </asp:DropDownList> <asp:Button id="btnApplyTheme" onclick="btnApplyTheme_Click" runat="server" Text="Apply"></asp:Button> <br /> <asp:CheckBox id="chkRememberStylePref" runat="server" Text="Remember preference"></asp:CheckBox> </p> We set the details of the drop down list manually, assigning each item a Text property and a Value property. The Text property (the bit between the tags) is the text that displays in the control. The value is the underlying code value for the selected item, and we use this value to update the session. Clicking the Apply button will fire the Click event of the button, taking you neatly to the event handler for this event: void btnApplyTheme_Click(object sender, EventArgs e) { Session["SelectedCss"] = ddlTheme.SelectedItem.Value; Set the value of the session to be the value of the currently selected drop down list item (not the displayed text). This value is the filename for the stylesheet. 427 Users and Applications if (chkRememberStylePref.Checked) { HttpCookie CssCookie = new HttpCookie("PreferredCss"); CssCookie.Value = ddlTheme.SelectedItem.Value; CssCookie.Expires = DateTime.Now.AddSeconds(20); Response.Cookies.Add(CssCookie); } } If the ChkRememberStylePref checkbox is checked when the button is clicked, a cookie is added to the user's machine, specifying their preference for subsequent visits to the site. Again, we set a short expiry time for this cookie so that you can see it working and also see what happens when it expires. You can set this to be whatever time interval you prefer. OK, so you have a session and a cookie – the next stage is to read those values in when the page is loaded: public void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Session["SelectedCss"] == null) { If the Session does not yet exist, we set a default value for the selected stylesheet using the value in the cookie if one exists on the client machine, or set it to a specific value if there is no cookie present: if (Request.Cookies["PreferredCss"] == null) { Session["SelectedCss"] = "WroxUnited.css"; } else { Session["SelectedCss"] = Request.Cookies["PreferredCss"].Value; } } } Now that we have applied the stylesheet, we need to manually alter the styling of the Calendar control (if you skip this step, you'll notice that the calendar doesn't follow the stylesheet like the rest of the page): public void EventCalendar_DayRender(object sender, DayRenderEventArgs e) { if (((Hashtable)Cache["DateList"])[e.Day.Date] != null) { e.Cell.CssClass = "selecteddate"; e.Day.IsSelectable = true; } else { e.Day.IsSelectable = false; e.Cell.CssClass = "normaldate"; 428 Chapter 11 } } <DayStyle cssclass="normaldate"></DayStyle> <OtherMonthDayStyle cssclass="othermonthdate"></OtherMonthDayStyle> Finally, we declare some stylesheet information. Let's run through the values of just a couple of these definitions: BODY { background-image:url(images/background.gif); color:"#000000"; font-family: georgia; } The BODY tag controls the way the bulk of the page is rendered, including any background coloring or styling, as well as the font color and style. The .selecteddate style is the style added in the DayRender() event handler for the calendar: .selecteddate{ font-weight: bold; font-size: larger; border: 3 dotted darkred; background:#f0f0f0; } Notice how the styles here are similar to the styles used in the code for the DayRender() event handler previously? Well, that's the joy of stylesheets! You've now centralized this code so that you only have to alter it in one place. Summary We covered quite a bit of ground in this chapter. We used cookies, sessions, and applications and cached data for enhancing performance. We also had some fun with interactive examples in this chapter that demonstrated these concepts. The important points covered in this chapter are: ❑ Cookies are a neat way to store small pieces of identifying data, but cannot be relied upon (users may have them disabled in their browser preferences). ❑ Sessions are an extremely powerful way to store data that exists for as long as a user is connected to the site, and you can use them to store data for online shopping examples. ❑ Application-scope objects are accessible by any page in an application and are a great way to centralize objects that need to be shared. ❑ Caching data is crucial to improving application performance, but it's also similar to storing data in the Application object. However, the Cache object has some neat features such as 429 Users and Applications linking to a dependency, and you can control when items in the cache expire and react to the events raised when those items expire. The next chapter will look at encapsulating commonly used page elements into reusable sections known as user controls. You'll also learn how the code-behind technique can be used to cleanly separate HTML code from C# code. Exercises 1. Add the text, Current Topic, and a label control to the Chat.aspx page above the main chat box that contains the text of the current topic (stored in the Application object). Add some default topic text to the Global.asax file, and also another box and button to the page, allowing you to change the current topic. 2. Add the session initialization code from the Stylesheet example to your Global.asax file. 3. Add a link to the Merchandise.aspx page from the front page of the site, then apply the stylesheet used in the Default.aspx page to all the other pages in the site. You will need to add the <link > tag to the <head > section of each page, and you will need to ensure that the session initialization code is correctly configured in the Global.asax file from the previous exercises. 430 Chapter 11 12 Reusable Code for ASP.NET So far, most of the ASP.NET pages we've built were quite specialized and self-contained. We've put a lot of functionality into each page, but only retained the benefits of our hard work from one page to another by copying the entire contents into a new ASPX page. This isn't an ideal way to write functionality-rich Web sites, particularly if you're on a salary and expected to deliver results before the next millennium! We'll now look at writing reusable code for ASP.NET. Note that we're not just talking about objects here (although, yet again, objects play a crucial role in the reusability story), but about code components – totally independent files that encapsulate groups of useful functionality. This chapter will look at two specific ways of using components in ASP.NET: ❑ User control: A Web form that is encapsulated in a reusable server control ❑ Code-behind: Used for separating HTML user interface design (color, aesthetics, and so on) from page code First, let's take a careful look at what is meant by components and consider the various advantages they offer. Encapsulation As discussed in Chapter 7, an object essentially is a software construct that bundles together data and functionality. You can define interfaces to use the functionality that an object contains, for example, by creating methods and properties that can be accessed programmatically. By hiding everything that doesn't concern task-specific usage of an object, implementation details are hidden from the consumer, which makes it a lot easier to robustly plug an object together with other objects. This makes it far easier for large teams of developers to build complex applications that don't fall prey to lots of low-level weaknesses. [...]... page A user control is saved with a ascx file extension, and can be called from any of the ASP.NET pages in our application by using just two lines of code The main principle of user controls is that you essentially cut out a portion of code from your 4 36 Reusable Code for ASP NET ASP.NET page and paste it into a user control, where it will work just fine as long as the ASP.NET page knows where to find... 12-1 The first ASP.NET page creates a new object of type Class1 that resides within the Component1 component The second ASP.NET page creates two new objects – one of type Class1 and one of type Class2 Class2 also resides within Component1 All code written so far has been held in specific ASPX pages So, what's the point in having all this reusable code if it can only be reached from within a single... assemblies – don't worry if you haven't got any experience with the other languages, as we'll stick with C# for the rest of this book In Visual Studio NET, Web Forms applications are always created with a code-behind file, rather than placing code on the same page In addition, code-behind files in Visual Studio NET are named the same as the ASPX page, with 451 Chapter 12 an additional cs or vb on the end... this is a purely C# NET file and not an ASP.NET page using System; using System.Web.UI; using System.Web.UI.WebControls; This first block of code lays the foundation for the code-behind file These three lines of code import namespaces from the NET Class Library These namespaces are used to access all of the functionality of ASP.NET pages Actually, these are loaded by default into any ASP.NET page, though... the first line in our ASP.NET page mentioned Wrox.MyCodeBehind Well, this is what the ASP.NET page is looking for – the MyCodeBehind class in the Wrox namespace namespace Wrox { public class MyCodeBehind : Page { The second part of this line indicates that the MyCodeBehind class is inheriting functionality from the ASP.NET Page object This means, "Take the Page class, combine it with the one defined... working with information input via a form to connecting to a database and working with data Throughout the book, you've been encouraged to keep your code separated into distinct blocks – the dynamically generated content (ASP.NET code) and presentation (HTML and various controls) – so that it's easy to change the look of your page without affecting what it does Web Matrix simplifies this process with. .. design-focused code from the ASP.NET code blocks, and then reuse bits of that code, it would be much easier to update a single piece of code to change functionality – every page that used it would be automatically updated This style of work would make everyone happy – Web designers get to play with color and layout as much as they like, and the ASP.NET developers can fine-tune their code without affecting the... single file This statement is essential when working with code-behind on an ASP.NET page public TextBox Name; public Label Message; 455 Chapter 12 These lines are simply variable declarations and mimic the names of the controls on the ASP.NET page You need to use this technique for any code-behind file – all controls on a page that you want interacting with the code-behind file need to have a corresponding... of our ASP.NET pages When IIS detects a request for a page with a aspx extension, it uses this component to process the page and communicate with the NET Framework DLLs are classified as system files and are hidden by default They can only be seen in Windows Explorer if the 'Show hidden files and folders' option in your Folder Options is set The DLLs talked about in these examples are COM DLLs .NET DLLs... technique can be used to encapsulate a lot of logic to deal with user input, thereby separating the jobs of the designer and the programmer, which is one of the goals of ASP.NET Code behind can be used on any ASPX page with a block on it The code portion of the page can be cleanly moved out to the code-behind file If you use or intend to use Visual Studio NET, you will notice that this is the default . definitions. Figure 12 -1 considers a quick example: Figure 12 -1 The first ASP. NET page creates a new object of type Class1 that resides within the Component1 component. The second ASP. NET page creates. fairly different, as you’ll no doubt notice! 425 Users and Applications Figure 11 -19 : Figure 11 -20 4 26 Chapter 11 13 . If you check the Remember Preference box before clicking Apply, the style. configured in the Global.asax file from the previous exercises. 430 Chapter 11 12 Reusable Code for ASP. NET So far, most of the ASP. NET pages we've built were quite specialized and self-contained.

Ngày đăng: 13/08/2014, 04:21

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan