Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 82 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
82
Dung lượng
613,96 KB
Nội dung
552 Chapter 10 • ASP.NET using System.Diagnostics; You will need to add these two namespaces to the file to provide data access functionality: using System.Data; using System.Data.SqlClient; namespace simpleCart.components { public class dataaccess { Set the connection string to connect to the SQL data store: private string connection = "Persist Security Info=False; User ID=[user name]; password=[password]; Initial Catalog=shopDb;Data Source=[server name]"; Create the method getAllBooks; this method will connect to the database and call the stored procedure GetAllBooks: public DataSet getAllBooks() { SqlConnection conn = new SqlConnection ( this.connection ) ; conn.Open ( ) ; Create the command object to reference the stored procedure: SqlCommand cmd = new SqlCommand ( "GetAllBooks" , conn ) ; cmd.CommandType = CommandType.StoredProcedure; Here you will use the SQL data adapter so that you can retrieve the data returned by getAllBooks and store it in a DataSet: SqlDataAdapter da = new SqlDataAdapter (cmd) ; DataSet ds = new DataSet ( ) ; da.Fill ( ds , "Books" ) ; www.syngress.com ASP.NET • Chapter 10 553 Next, close the connection to the database and return the resulting DataSet: conn.Close(); return ds; } } } In this section, you created the component that you will use to retrieve the data from the database in a dataset. In the next section, you will create the com- ponent that will function as the shopping cart. Creating XmlShoppingCart.cs This component is a wrapper component for XML. It provides add, remove, view, and clear functionality.The only catch is that items added to the cart must be XmlNodes from Catalog or must adhere to the same document structure.You can find this file in its entirety on the CD (see XmlShoppingCart.cs in the com- ponents folder of the application): using System; Add support for XML by including the XML namespace: using System.Xml; namespace simpleCart.components { Define the shopping cart class: public class xmlShoppingCart { private XmlDocument myCart; private string elementType; This initializes the cart. On page_ load, the cart can be initialized with an existing xmlCart string.This enables client caching of the cart: public void initCart(string dataSource, string elementType) { this.elementType = elementType; myCart = new XmlDocument(); www.syngress.com 554 Chapter 10 • ASP.NET if( dataSource != null ) { myCart.LoadXml(dataSource); } else { //load default cart root myCart.LoadXml("<shopcart-items></shopcart-items>"); } } This method handles adding an item to the cart by importing the node from the catalog XML data: public string addItem2Cart( XmlDocument item ) { try { XmlNode newItem = myCart.ImportNode(item.DocumentElement.FirstChild, true); myCart.DocumentElement.AppendChild(newItem); return "Success"; } catch(Exception e) { return e.ToString(); } } This method removes an item from the cart based on its ID value using the removeChild method of the XML DOM object: public string removeItemFromCart(string idvalue, string attributename ) { // example: XmlNode curnode = //myCart.SelectSingleNode("//Books[isbn='0012-456-789x']"); string XPathQuery = "//" + this.elementType + "[" + www.syngress.com ASP.NET • Chapter 10 555 attributename + "='" + idvalue + "']"; XmlNode curnode = myCart.SelectSingleNode(XPathQuery); try { myCart.DocumentElement.RemoveChild( curnode ); return "Success"; } catch(Exception e) { return e.ToString(); } } This method empties the cart by removing all the child nodes: public void clearCart() { XmlElement root = myCart.DocumentElement; root.RemoveAll(); //removes all child nodes } This method returns the current contents of the cart as an XML DOM object: public XmlDocument getCartDescription() { return myCart; } This method returns the current contents of the cart as an XML formatted string: public string getCartDescriptionString() { return myCart.OuterXml; } } } www.syngress.com 556 Chapter 10 • ASP.NET So far, you have built the component that gets the data from the database and the component that handles the cart operations. Next, you will create the object that handles displaying the catalog incrementally: catalog.cs. Creating catalog.cs This is the largest and most complex of the components. On initialize, it loads and stores a DataSet object. Catalog adds a new table to the DataSet, which con- tains metadata. Catalog is able to return the data as XmlDocuments by range.You can find this file in its entirety on the CD (see catalog.cs in the Components folder of the application). This class makes extensive use of DataSet operations.You will look at creating DataRows, DataTables, DataViews, and DataSets.You will also look at creating new DataSets based on the results of filtering your primary dataset: using System; You will need to add the Data namespace in order to make use of the DataSet and its related object: using System.Data; namespace simpleCart.components { /// <summary> /// bookCatalog acts as cached datasource. /// Enables retrieval of data in data ranges /// </summary> Here you begin creating the catalog object: public class bookCatalog { private DataSet dsAllBooks; /// <summary> /// Initalizes bookCatalog by reading in a dataset /// </summary> /// <param name="ds"></param> www.syngress.com ASP.NET • Chapter 10 557 First, load all the data returned by SQL into your Catalog object, this will enable you to filter the data and return the appropriate subset: public void initCatalog(DataSet ds ) { dsAllBooks = ds; int recordCount = dsAllBooks.Tables[0].Rows.Count; try { dsAllBooks.Tables.Add( createSummaryTable(0, recordCount-1, recordCount) ); } catch(Exception e) { string temp = e.ToString(); //this fails when attempting to add the table twice } } /// <summary> /// Creates a table that is added to the DataSet. /// This table contains some metadata /// about the dataset returned. /// </summary> /// <param name="startPos"></param> /// <param name="range"></param> /// <param name="RecordCount"></param> /// <returns>Returns a DataTable containing Metadata</returns> This method takes metadata about the entire dataset and adds it to a new DataTable: dtSummary.This DataTable is used by other methods of this object/class: private DataTable createSummaryTable(int startPos, int range, int RecordCount) { www.syngress.com 558 Chapter 10 • ASP.NET Create the new table: DataTable dtSummary = new DataTable("Summary"); DataRow drSummary; Add new columns to the table: dtSummary.Columns.Add( new DataColumn("RecordCount", typeof(int))); dtSummary.Columns.Add( new DataColumn("FirstItemIndex", typeof(int))); dtSummary.Columns.Add( new DataColumn("LastItemIndex", typeof(int))); Create a new row and add the data to its columns: drSummary = dtSummary.NewRow(); drSummary["RecordCount"] = RecordCount; drSummary["FirstItemIndex"] = startPos; drSummary["LastItemIndex"] = startPos + range; Add the new row to the new table: dtSummary.Rows.Add( drSummary ); Return the new table containing the supplied data: return dtSummary; } /// <summary> /// This Method returns the input DataSet /// </summary> /// <returns>DataSet containing: DataTable books</returns> public DataSet catalog() { return dsAllBooks; } /// <summary> /// Specialized interface to catalogRangeByCategory. www.syngress.com ASP.NET • Chapter 10 559 /// This Method returns all the data for only the given book /// </summary> /// <param name="book_isbn"></param> /// <returns>DataSet containing: DataTable books ///& DataTable "Summary"</returns> public DataSet catalogItemDetails( string book_isbn ) { return catalogRangeByCategory( -1, -1, book_isbn); } /// <summary> /// Specialized interface to catalogRangeByCategory. /// This Method returns all the books within the given range /// </summary> /// <param name="startPos"></param> /// <param name="range"></param> /// <returns></returns> public DataSet catalogRange(int startPos, int range) { return catalogRangeByCategory( startPos, range, null); } This function filters the data by creating a new DataView. The resulting data is added to a new table; these new tables along with a new summary table are added to a new DataSet.This new DataSet is returned to the caller: protected DataSet catalogRangeByCategory(int startPos, int range, string book_isbn) { DataSet dsBookRange; DataTable dtBooks; DataTable dtTemp; string strExpr; string strSort; DataRow[] foundRows; int endPos; www.syngress.com 560 Chapter 10 • ASP.NET int RecordCount; DataViewRowState recState; Create a local copy of the table Books: dtTemp = dsAllBooks.Tables["Books"]; Copy the table structure of table Books into a new DataTable object: dtBooks = dtTemp.Clone();//create Empty Books Table Create the appropriate data filter: if( book_isbn != null) { //return a single item strExpr = "isbn='" + book_isbn + "'"; } else { strExpr = ""; } strSort ="title"; recState = DataViewRowState.CurrentRows; Filter the data storing the results in an array: foundRows = dtTemp.Select(strExpr, strSort, recState); Grab the appropriate range of the selected data: RecordCount = foundRows.Length; if( (startPos == -1) && (range == -1)) { startPos = 0; range = RecordCount; } if( (startPos + range) > RecordCount) { endPos = RecordCount; } www.syngress.com ASP.NET • Chapter 10 561 else { endPos = startPos + range; } Fill the new DataTable with the selected data subset: for(int i = startPos; i < endPos; i ++) { dtBooks.ImportRow( (DataRow)foundRows[i] ); } Create a new DataSet and add the newly filled DataTable: dsBookRange = new DataSet(); dsBookRange.Tables.Add(dtBooks ); Add a summary table to the new DataSet: // add a summary table to the dataset dsBookRange.Tables.Add( createSummaryTable( startPos, range, RecordCount) ); Return the newly created DataSet: return dsBookRange; } } } If you look closely at the method catalogRangeByCategory, you will get a glimmer of how powerful DataSets are.The DataSet is the successor to the ADO 2.6 Recordset object; it can actually store the entire structure of a multitable rela- tional database and all its data.You can perform query and filter operations on it almost like a real relational database. It is also one of a few data types that can be sent to and from Web Services. When the data source doesn’t change often and is used primarily as read- only, it makes sense to cache the data in a DataSet at the application level.What does that mean? The Application_Start method within the Global.asax file is exe- cuted when the first user accesses the site; the application does not end until roughly 20 minutes after no user accesses the site.This scenario is depicted in www.syngress.com [...]... ASP.NET Web Service called soapExamples: Go to File | New | Project, choose the entry ASP.NET Web Service under the Visual C# Projects folder, keep the default Location, and enter soapExamples as the Name of the project (see Figure 11.4).This will set up a new virtual directory of the same name (see Figure 11.5) Figure 11.4 Setting Up a New ASP.NET Web Service www.syngress.com 583 584 Chapter 11 • Web. .. Global.asax file across a Web farm of servers Working with Web Forms Web Forms (ASPX pages) are the replacement for ASP pages in ASP.NET All controls and UI functionality will be placed within Web Forms Web Forms inherit all the methods and properties of the Page class, which belongs to the System .Web. UI namespace You can add three main sets of controls to your Web Form: HTML server controls ,Web server controls,... %SystemRoot%\Microsoft.NET\Framework\v1.0.2914\, which handles NET-specific Web requests (see Figure 11.7) Figure 11.7 Mapping NET File Extensions www.syngress.com 585 586 Chapter 11 • Web Services 2 The IIS directory is converted to a FrontPage Server Extensions Web, allowing for Visual Studio.NET design support 3 Under the IIS virtual directory, a variety of standard FrontPage directories are created (see Figure 11 .8) ... simpleService : System .Web. Services.WebService { public simpleService() { Continued www.syngress.com Web Services • Chapter 11 Figure 11.3 Continued } protected override void Dispose( bool disposing ) { } [System .Web. Services.WebMethod] public string echo(string input) { return input; } } } Let’s now open up the Visual Studio.NET integrated development environment and create the echo Web Service from scratch,... NET Framework as viable solutions architecture ASP.NET will take Web development and Web applications programming to a new level, providing a robust and scalable multideveloper platform Solutions Fast Track Introducing the ASP.NET Architecture ASP.NET architecture enables rapid prototyping of cross-platform scalable applications A Web client requests a Web Form (ASPX) resource that is delivered through... class simpleService needs to inherit from System .Web. Services.WebService ■ Your method echo needs to be decorated with the System .Web. Services.WebMethod attribute See Figure 11.3 for your first fully functioning Web Service Note that the complete code for the echo Web method is in the directory soapExamples/ on the CD accompanying this book Figure 11.3 Echo Web Method (simpleService.asmx.cs) namespace soapExamples... Global.asax Empty by default Sample Web Service file, pointing to C# class file Service1.asmx.cs, created automatically by Visual Studio.NET Sample C# Web Service class file, created automatically by Visual Studio.NET Sample Web Service resource file to store localization information for Service1.asmx Empty by default Created automatically by Visual Studio.NET Service1.asmx Service1.asmx.cs Service1.asmx.resx 6... detail the various Web Services standards introduced in the previous section: SOAP, the wire transport protocol,WSDL to describe Web Services, DISCO to discover, and UDDI to publish Web Services.You will also write your very first Web Service using the tools provided by Microsoft Visual Studio.NET By the end of this section, you will have enough knowledge to go ahead and create your own Web Services.The... Ready4Checkout.Text = "false"; } } www.syngress.com ASP.NET • Chapter 10 Summary In this chapter, you have worked with the ASP.NET architecture ,Web Forms, DataSets, and DataConnections with ADO.NET.You have worked with many of the ASP.NET UI controls, including: Button, TextBox, CheckBox, RadioButton, Label, and Xml.You have worked through examples using the ASP.NET validation controls, including the asp:RegularExpressionValidator... this project soapExamples.csproj.webinfo XML file containing Web- related project-level settings, such as the URL to start this application soapExamples.vsdisco XML file containing DISCO dynamic discovery information for this Web Service AssemblyInfo.cs C# class defining assembly metadata, such as version number information Web. Config XML file containing configuration for the Web Service, such as security, . "false"; } } www.syngress.com ASP .NET • Chapter 10 571 Summary In this chapter, you have worked with the ASP .NET architecture ,Web Forms, DataSets, and DataConnections with ADO .NET. You have worked with many of the ASP .NET. real-world examples, you can see the potential of ASP .NET and the .NET Framework as viable solutions architecture. ASP .NET will take Web development and Web applications programming to a new level, providing. Fast Track Introducing the ASP .NET Architecture ; ASP .NET architecture enables rapid prototyping of cross-platform scalable applications. ; A Web client requests a Web Form (ASPX) resource that