1. Trang chủ
  2. » Công Nghệ Thông Tin

Professional ASP.NET 2.0 XML phần 10 pptx

54 280 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 54
Dung lượng 1,63 MB

Nội dung

For the ShoppingAssistant Web site, the CommonMaster.master page provides the standard heading and left navigation for all the pages. The code of the CommonMaster.master is shown in Listing 15-7. Listing 15-7: CommonMaster.master Page for Consistent Look and Feel <%@ Master Language=”C#” %> <html xmlns=”http://www.w3.org/1999/xhtml” > <head runat=”server”> <title>Common Master Page</title> </head> <body> <form id=”form1” runat=”server”> <div> <asp:Table BorderStyle=Double id=”tblTop” runat=”server” Width=”100%” Height=”105px” ForeColor=”Black”> <asp:TableRow> <asp:TableCell> <img src=”Images/wrox_logo.gif”> </asp:TableCell> <asp:TableCell> <font size=30>Shopping Assistant</font> </asp:TableCell> </asp:TableRow> <asp:TableFooterRow> <asp:TableCell ColumnSpan=”2”><br /></asp:TableCell> </asp:TableFooterRow> </asp:Table> <asp:Table BorderStyle=Double id=”bodyTable” runat=”server” Width=”100%” Height=”100%” ForeColor=”Black”> <asp:TableRow VerticalAlign=Top> <asp:TableCell> <asp:Table BackColor=LightSteelBlue runat=”server” Height=”100%” Width=”135px” ID=”leftTable”> <asp:TableRow Height=”75”> <asp:TableCell VerticalAlign=Top> <asp:HyperLink Font-Bold=true NavigateUrl=”~/CategoriesListing.aspx” runat=”server” ID=”categoriesListingLink” Text=”Categories Listing”> </asp:HyperLink> <br/><br/><br/> What Is a Master Page? As you learned in a previous chapter, ASP.NET 2.0 introduced a new concept known as Master Pages, in which a common base master file is created to provide a consis- tent layout for all the pages in a Web site. Master Pages allow you to isolate the look and feel and standard behavior for all the pages in your application to a centralized Master Page. In that page, you add placeholders (known as ContentPlaceHolder) for the content (or child pages) to add their custom content. When users request a content page, the output of the content pages is merged with the output of the Master Page, resulting in an output that combines the layout of the Master Page with the output of the content page. 514 Chapter 15 18_596772 ch15.qxd 12/13/05 11:18 PM Page 514 <asp:HyperLink Font-Bold=true NavigateUrl=”~/CreateUser.aspx” runat=”server” ID=”createNewLink” Text=”Create New User”> </asp:HyperLink><br/><br/><br/> <asp:HyperLink Font-Bold=true NavigateUrl=”~/Login.aspx” runat=”server” ID=”loginLink” Text=”Login”> </asp:HyperLink><br/><br/><br/> <asp:HyperLink Font-Bold=true NavigateUrl=”~/Logout.aspx” runat=”server” ID=”logoutLink” Text=”Logout”> </asp:HyperLink><br/><br/><br/> </asp:TableCell> </asp:TableRow> </asp:Table> </asp:TableCell> <asp:TableCell HorizontalAlign=Left> <asp:contentplaceholder id=”BodyContent” runat=”server”> </asp:contentplaceholder> </asp:TableCell> </asp:TableRow> </asp:Table> </div> </form> </body> </html> The Master Page contains a header that displays the Wrox logo and the name of the Web site. It also con- tains a left navigation bar that facilitates easy navigation of the pages in the ShoppingAssistant Web site. Inside the Master Page, there is a ContentPlaceHolder control that allows the content pages (also know as child or inherited pages) to substitute their content. Login Process In the ShoppingAssistant Web site, the user must be logged in to browse through the different pages of the site. To this end, create a new ASP.NET page named Login.aspx that allows the user to log into the site. The login page authenticates the user’s username and password against the Membership store provided by ASP.NET. Before looking at the code of the Login.aspx page, it is useful to briefly examine the underlying authentication technology used by the ShoppingAssistant. How Master Pages Work? The Master Page defines content areas using the ContentPlaceHolder control, and the content pages place their content in the areas identified by the ContentPlaceHolder control in the Master Page. Pages that use a Master Page to define the layout can place content only in the areas defined by the ContentPlaceHolder, thus enabling a consistent site design. Master Pages are saved with the file extension .master and they contain the Master directive at the top of the page instead of the Page directive that is used by the traditional ASP.NET pages. In addition to hosting all the contents that are required for defining the stan- dard look and feel of the application, the Master Pages also contain all the top-level HTML elements for a page, such as <html>, <head>, and <form>. The Master Pages also contain one or more content placeholders that are used to define regions that will be rendered through the content pages. 515 Building a ShoppingAssistant Using XML Web Services 18_596772 ch15.qxd 12/13/05 11:18 PM Page 515 The login feature of the Web site is implemented using forms-based authentication mechanism. The forms-based authentication technology depends on cookies to store the authentication information for the currently logged in user. After the user is authenticated, cookies are used to store and maintain ses- sion information enabling the users to identify themselves to the Web site. To enable forms-based authentication for the ShoppingAssistant Web site, add the following entry in the web.config file directly under the <system.web> element. <authentication mode=”Forms”> <forms name=”.ASPXSHOPPINGASSISTANT” loginUrl=”Login.aspx” protection=”All” timeout=”30” path=”/”> </forms> </authentication> The loginUrl attribute in the <forms> element specifies the name of the login page that you want the users to be redirected to, any time they access a page or resource that does not allow anonymous access. For every Web form that you want to secure using the forms-based authentication mechanism, you need to add an entry to the web.config file. For example, to set the restrictions of authenticated user access for a page called CategoriesListing.aspx, set the following entry directly under the <configuration> element of the web.config file. <location path=”CategoriesListing.aspx”> <system.web> <authorization> <deny users=”?” /> </authorization> </system.web> </location> When a user attempts to access the CategoriesListing.aspx page, the ASP.NET forms-based security system will automatically redirect the user to the Login.aspx page, and will continue to prevent them from accessing it until they have successfully validated their user name and password credentials to the ShoppingAssistant application. Similarly you protect the ProductsListing.aspx and ProductDetail.aspx pages also using similar entries in the web.config file. Now that you have a general understanding of the forms-based authentication, you are ready to exam- ine the Login.aspx page. The Login.aspx page is implemented in Listing 15-8. Listing 15-8: Login Page Using <asp:Login> Server Control <%@ Page Language=”C#” MasterPageFile=”~/CommonMaster.master” Title=”Login” %> <asp:Content ID=”Content1” ContentPlaceHolderID=”BodyContent” Runat=”Server”> <asp:login ID=”Login1” runat=”server” createuserurl=”CreateUser.aspx” DestinationPageUrl=”~/CategoriesListing.aspx” createusertext=”Create a New Account” /> </asp:Content> If you have ever implemented forms authentication by hand, you will appreciate the <asp:Login> con- trol. In the past, an equivalent implementation to perform a database lookup would have required a cou- ple of hundred lines of more code. The Login control shown in Listing 15-8 not only provides you with the interface, but also provides the underlying validation by leveraging the default membership provider. When you submit your username and password by using the Login control, your credentials are automatically validated by the configured membership provider. 516 Chapter 15 18_596772 ch15.qxd 12/13/05 11:18 PM Page 516 In the login page, try logging in with an invalid username or password, and notice that an appropriate default error message appears. It is all handled automatically for you. Figure 15-4 shows the output of the Login.aspx page. Figure 15-4 Security Features in ASP.NET 2.0 New security features are an important improvement in ASP.NET 2.0. These features include membership services that manage a database of user accounts, hashed pass- words, a role manager for managing role membership for users, and new security- related server-side controls that make implementing forms authentication much easier. ASP.NET 2.0 also offers a provider model that gives you complete control over the implementation of the Membership and Role services and cookieless forms authentication. In addition to the extensible provider model, ASP.NET 2.0 also provides a suite of server controls that interact with the membership and role stores. The Login control provides a daunting list of properties. The vast majority of these properties simply enable you to control different aspects of the appearance of the login interface. For example, you can use the FailureText property to control the content of the text that is displayed when a login attempt fails. Additionally, you can use the CreateUserUrl and PasswordRecoveryUrl properties to create links to a registration page and pass- word recovery page. 517 Building a ShoppingAssistant Using XML Web Services 18_596772 ch15.qxd 12/13/05 11:18 PM Page 517 Before using the login feature, you need to register some users with the membership service to get started, so the first page you will be writing is one that allows you to add users. For this purpose, create a new page named CreateUser.aspx. If the user does not have a valid account, they can get to the CreateUser.aspx page using the Create New Account hyperlink on the Login.aspx page or by click- ing the Create New User hyperlink in the left navigation. Performing any of these operations directs the user to the CreateUser.aspx page, whose implementation is shown in Listing 15-9. Listing 15-9: Creating New User using <asp:CreateUserWizard> Server Control <%@ Page Language=”C#” MasterPageFile=”~/CommonMaster.master” Title=”Create User” %> <asp:Content ID=”Content1” ContentPlaceHolderID=”BodyContent” Runat=”Server”> <asp:CreateUserWizard ID=”CreateUserWizard1” runat=”server” continuedestinationpageurl=”CategoriesListing.aspx” /> </asp:Content> Listing 15-9 produces the output shown in Figure 15-5. Figure 15-5 After you create an account using the page shown in Figure 15-5, if you click the Continue button, you will be redirected to the CategoriesListing.aspx page. This is because of the value set in the ContinueDestinationPageUrl attribute of the <asp:CreateUserWizard> control. After you are finished adding users, take a close look at your virtual directory. You should see a new subdirectory called “ App_Data” that has a SQL Server 2005 Express database named ASPNETDB.MDF inside. This is where the membership and role services store their data by default, but you can also over- ride the default storage mechanism to use SQL Server database or your own custom data repository. 518 Chapter 15 18_596772 ch15.qxd 12/13/05 11:18 PM Page 518 Logout Process All you need to do to log out of the site is to click the Logout hyperlink on the left navigation. When you click that link, the user is redirected to the Logout.aspx page shown in Listing 15-10. Listing 15-10: Implementation of Logout Functionality <%@ Page Language=”C#” MasterPageFile=”~/CommonMaster.master” Title=”Logout” %> <%@ Import Namespace=”System.Web.Security” %> <script runat=”server”> void Page_Load(object sender, EventArgs e) { FormsAuthentication.SignOut(); Response.Redirect(“Login.aspx”); } </script> <asp:Content ID=”Content1” ContentPlaceHolderID=”BodyContent” Runat=”Server”> </asp:Content> The CreateUserWizard control enables you to create a standard user registration page. Simply by adding the following tag to a page, you can enable new users to register at your Web site. <asp:CreateUserWizard ID=”CreateUserWizard1” Runat=”server” /> The CreateUserWizard control is powerful in that you can configure the control to send email messages by assigning values to the control’s MailDefinition property. The MailDefinition property represents an instance of the MailDefinition class that contains all of the properties required for defining an email message. For exam- ple, the following CreateUserWizard control will send the contents of the Registration.txt file as the body of the registration email message whenever someone completes the registration wizard. <asp:CreateUserWizard ID=”CreateUserWizard1” Runat=”server”> <MailDefinition BodyFileName=”~/Registration.txt” From=”YourName@YourDomain.com” Subject=”Thanks for registering”> </MailDefinition> </asp:CreateUserWizard> The CreateUserWizard control’s email functionality also can be useful in more complicated registration scenarios in which you need to validate a user’s email address before you provide the user with access to your Web application. If you enable the CreateUserWizard control’s AutoGeneratePassword property, the con- trol will randomly generate a password for a user. By taking advantage of the CreateUserWizard control’s email functionality, you can automatically send the randomly generated password to the user. If the user subsequently authenticates against your Web application using the sent password, you know that the user must have supplied a valid email address. 519 Building a ShoppingAssistant Using XML Web Services 18_596772 ch15.qxd 12/13/05 11:18 PM Page 519 As Listing 15-10 shows, the logout implementation requires just one line of code. You simply call the SignOut() method of the System.Web.Security.FormsAuthentication class. That will clear all the cookies (used for authentication purposes) in the client machine. Then you simply redirect the users to the Login.aspx page. Categories Listing Process All the categories present in the site are displayed through the CategoriesListing.aspx page. In the categories listing page, you use an <asp:GridView> Web control to display the categories. You bind the GridView control directly to the List<Category> returned by the Web service in the Page_Load event. To add the Web reference, right-click on the project in the Solution explorer and select Add Web Reference in the context menu. In the Add Web Reference dialog box, enter the path of the .asmx file of the Web service. When you add a Web reference of a Web service to your project, Visual Studio 2005 automatically generates a proxy class that not only interfaces with the Web service but also provides a local representation of the Web service. Listing 15-11 illustrates the code of the CategoriesListing.aspx page. Listing 15-11: Categories Listing Page that Uses CategoriesService <%@ Page Language=”C#” MasterPageFile=”~/CommonMaster.master” Title=”Categories Listing” %> <%@ Import Namespace=”CategoriesProxy” %> <script runat=”server”> void Page_Load(object sender, EventArgs e) { CategoriesProxy.CategoriesService obj = new CategoriesProxy.CategoriesService(); gridCategories.DataSource = obj.GetCategories(); gridCategories.DataBind(); } </script> <asp:Content ID=”Content1” ContentPlaceHolderID=”BodyContent” Runat=”Server”> <asp:GridView id=”gridCategories” style=”Z-INDEX: 101; LEFT: 162px; POSITION: absolute; TOP: 147px” runat=”server” Height=”321px” width=”529px” BorderColor=”Black” cellpadding=”4” Font-Names=”Verdana” Font-Size=”8pt” AutoGenerateColumns=”False” ShowFooter=”True”> <FooterStyle ForeColor=”Control” BackColor=”ActiveCaptionText”></FooterStyle> <HeaderStyle BackColor=”Gray”></HeaderStyle> <RowStyle BackColor=”Control”></RowStyle> <Columns> <asp:BoundField DataField=”CategoryName” HeaderText=”Category Name”/> <asp:HyperLinkField Text=”Show all products” DataNavigateUrlFields=”CategoryID” DataNavigateUrlFormatString=”ProductsListing.aspx?CategoryID={0}” HeaderText=”All products in the Category”></asp:HyperLinkField> </Columns> </asp:GridView> </asp:Content> 520 Chapter 15 18_596772 ch15.qxd 12/13/05 11:18 PM Page 520 The GetCategories() method of the CategoriesService returns an array of Category objects that is directly bound to the GridView control. When called from browser, the Categories listing page looks like the output shown in Figure 15-6. Figure 15-6 Products Listing Process As the name suggests, the ProductListing.aspx page shows the list of products available on the site and the list of products shown is based on the category the user has selected in the categories listing page. The Page_Load event handler contains the code to invoke the ProductsService Web service, retrieve data from it, and then display its contents into a GridView control. The code of the ProductsListing.aspx page is shown in Listing 15-12. Listing 15-12: Products Listing Page That Uses ProductsService <%@ Page Language=”C#” MasterPageFile=”~/CommonMaster.master” Title=”Products Listing” %> <%@ Import Namespace=”ProductsProxy” %> <script runat=”server”> void Page_Load(object sender, EventArgs e) { /* Synchronous Web Service Call approach */ ProductsProxy.ProductsService obj = new ProductsProxy.ProductsService(); int categoryID = Convert.ToInt32(Request.QueryString[“CategoryID”]); //Bind the Web service return value to Products GridView 521 Building a ShoppingAssistant Using XML Web Services 18_596772 ch15.qxd 12/13/05 11:18 PM Page 521 gridProducts.DataSource = obj.GetProductsByCategoryID(categoryID); gridProducts.DataBind(); } </script> <asp:Content ID=”Content1” ContentPlaceHolderID=”BodyContent” Runat=”Server”> <asp:GridView id=”gridProducts” style=”Z-INDEX: 101; LEFT: 162px; POSITION: absolute; TOP: 147px” runat=”server” Height=”321px” width=”529px” BorderColor=”Black” cellpadding=”4” Font-Names=”Verdana” Font-Size=”8pt” AutoGenerateColumns=”False” ShowFooter=”True”> <FooterStyle ForeColor=”Control” BackColor=”ActiveCaptionText”/> <HeaderStyle BackColor=”Gray”></HeaderStyle> <RowStyle BackColor=”Control”></RowStyle> <Columns> <asp:BoundField DataField=”ModelNo” HeaderText=”ModelNumber”/> <asp:BoundField DataField=”ModelName” HeaderText=”ModelName”/> <asp:BoundField DataField=”Description” HeaderText=”Description”/> <asp:BoundField DataField=”Price” HeaderText=”Price”/> <asp:HyperLinkField Text=”Product Details” DataNavigateUrlFields=”ProductID” DataNavigateUrlFormatString=”productdetails.aspx?ProductID={0}” HeaderText=”Show Details”/> </Columns> </asp:GridView> </asp:Content> In the Page_Load event, you retrieve the CategoryID passed in the query string and supply it as a parameter when invoking the Web service method GetProductsByCategoryID(). Navigating to the page in the browser results in the output as similar to Figure 15-7. Figure 15-7 522 Chapter 15 18_596772 ch15.qxd 12/13/05 11:18 PM Page 522 Figure 15-7 displays the products that belong to the category that was selected in the categories listing page. Product Details Listing Process When the user selects a particular product from the list of products, the user is taken to the product details page where details about the product are shown. For showing the product details, you will create a Web page named ProductDetails.aspx that encapsulates all the code required for retrieving the details of the product from the Web service. The code of the ProductDetails.aspx page is shown in Listing 15-13. Listing 15-13: Product Details Page That Uses ProductsService <%@ Page Language=”C#” MasterPageFile=”~/CommonMaster.master” Title=”Product Details” %> <%@ Import Namespace=”ProductsProxy” %> <script runat=”server”> void Page_Load(object sender, EventArgs e) { /* Synchronous Web Service Call approach */ ProductsProxy.ProductsService obj = new ProductsProxy.ProductsService(); int productID = Convert.ToInt32(Request.QueryString[“ProductID”]); formProductDetails.DataSource = obj.GetProductDetails(productID); formProductDetails.DataBind(); } </script> <asp:Content ID=”Content1” ContentPlaceHolderID=”BodyContent” Runat=”Server”> <table width=”95%” cellpadding=”0” cellspacing=”0” border=”0”> <tr> <td> <asp:FormView ID=”formProductDetails” runat=”server”> <HeaderTemplate> <tr> <td height=”40” align=”center” colspan=”2”> <asp:Label runat=”server” Font-Bold=”true” ForeColor=”Brown” ID=”heading”>Product Details</asp:Label> </td> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td height=”60” width=”30%” bgcolor=”buttonface”> <asp:label Font-Bold=true Text=”Model Number : “ runat=”server” ID=”lblModelNumber” /> <br> </td> <td height=”60” bgcolor=”buttonface”> <asp:label Text=’<%#Eval(“ModelNo”)%>’ runat=”server” ID=”lblModelNumberValue” /> <br> </td> </tr> <tr> <td height=”60” width=”30%” bgcolor=”buttonface”> <asp:label Font-Bold=true Text=”Model Name : “ runat=”server” 523 Building a ShoppingAssistant Using XML Web Services 18_596772 ch15.qxd 12/13/05 11:18 PM Page 523 [...]... XML output from a DataSet, 228–230 NET Framework, 42, 56 overview, 214 ReadXml method, 214 string from a DataSet, getting XML as, 227–228 transforming DataSet to XML, 222–230 XML data type columns and, 303–316 XmlDataDocument class, 235–241 XmlReadMode enumeration, 215 XmlWriteMode enumeration, 222 XPathNavigator class and XmlData Document relationship between, 242–243 advanced operations, 207–209... sheet, 190–192 sorting an XML file using a style sheet, 182–183 statically applying a style sheet, 180–186 system-property function, 179 unparsed-identity-uri function, 179 used to transform XML data, 49–50 user-defined functions, 193–197 variables, 185–186 XmlDataDocument class, 187 XmlDocument class, 187 XmlPathDocument class, 187 XmlReader class, 187 XmlResolver class, 208–209 XmlWriter class, 187 xsl:apply-imports... 218–219 InferXmlSchema method, 222 overview, 218 ReadXmlSchema method, 221–222 supplied schemas, 219–222 typed DataSets, 230–235 writing, 230 DataSource controls, 38 DataTable DataReader, 245 methods, 243 overview, 243 ReadXml method, 243 ReadXmlSchema method, 243 serializing, 244 WriteXml method, 243 WriteXmlSchema method, 243 547 Index DataTable datatypes datatypes, 16 declaring namespaces, 10 11 decompression... 135–136 events raised by XmlDocument class, handling, 157–158 node data, changing, 157 nodes, creating and appending, 149–151 nodes, deleting, 157 overview, 131–132 processing, 132 programmatically creating XML documents, 149–158 programming with, 134 tree, XML document loaded into DOM, 132–134 validating XmlDocument object, 171 validation, 110 111 XmlDocument class, 136–148 XmlDocumentFragment class,... Call the CreateXmlDocument() method passing in the values of the local variables CreateXMLDocument(browser, requestType, authenticated, categoryID, productID); The CreateXmlDocument() method creates an XML file in a specific directory using the WriteXXX() methods of the XmlWriter object The name of the XML file is generated by the call to the NewGuid() method of Guid class A typical XML file created... CategoriesListing.aspx page in that it also relies on a local XML file named Products .xml for the data displayed through the FormView control formProductDetails The place where it is different is where it creates the XML file using a method named CreateXmlDocument() The CreateXmlDocument() method is invoked at the end of the Page_Load event Before calling the CreateXmlDocument() method, you store the parameters related... GetProductsCompleted(object sender, GetProductsCompletedEventArgs args) 528 Building a ShoppingAssistant Using XML Web Services { string xmlFilePath = @”C:\Projects\Wrox\Products .xml ; Product[] productArray = args.Result; XmlSerializer serializer = new XmlSerializer(typeof(Product[])); TextWriter writer = new StreamWriter(xmlFilePath); //Serialize the Product array and close the TextWriter serializer.Serialize(writer,... database SaveReportInfo(e.FullPath); } private void SaveReportInfo(string path) { try { XmlReader reader = XmlReader.Create(path); XmlDocument document = new XmlDocument(); document.Load(reader); XmlNode reportInfoNode = document.DocumentElement; ReportInfo report = new ReportInfo(); //Get all the values from the XML document into the ReportInfo object report.Browser = reportInfoNode.ChildNodes.Item(0).InnerText;... Serialize the contents of the Category array into an XML file named Categories .xml through Serialize() method of the XmlSerializer object serializer.Serialize(writer, categoryArray); Similarly the GetProductsCompleted() method retrieves the results of the Web service call and serializes that result into an XML file named Products .xml 529 Chapter 15 NET Framework 2.0 provides a new event-based asynchronous programming... Data Store void Page_Load(object sender, EventArgs e) { /* Asynchronous Web Service Call through the XML file generated by the Windows Service */ string xmlFilePath = @”C:\Projects\Wrox\Categories .xml ; XmlSerializer serializer = new XmlSerializer(typeof(Category[])); TextReader reader = new StreamReader(xmlFilePath); //Deserialize the Category and close the TextReader gridCategories.DataSource = (Category[])serializer.Deserialize(reader); . = new Timer(timerDelegate, autoEvent, 0, 100 00) ; To the constructor, you also supply the start and frequency of the timer event as arguments as 0 and 100 00, respectively. This will result in the. ColumnSpan= 2 ><br />< /asp: TableCell> < /asp: TableFooterRow> < /asp: Table> < ;asp: Table BorderStyle=Double id=”bodyTable” runat=”server” Width=” 100 %” Height=” 100 %” ForeColor=”Black”>. DataNavigateUrlFormatString=”ProductsListing.aspx?CategoryID= {0} ” HeaderText=”All products in the Category”>< /asp: HyperLinkField> </Columns> < /asp: GridView> < /asp: Content> 5 20 Chapter 15 18_5967 72 ch15.qxd 12/ 13 /05

Ngày đăng: 12/08/2014, 23:22