Assembly Language: Step-by-Step - part 9 pps

80 290 0
Assembly Language: Step-by-Step - part 9 pps

Đ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

Reading an XML Document into the DataSet Reading XML data into a DataSet can be done by simply using the ReadXml method of the DataSet. This method has several overloads, but one of the over- loads allows a filename to be passed into the method. The filename must be a physical path, which means that when the XML document is on the Web server, the Server.MapPath method can be used with a relative virtual address to obtain the physical path. The following code shows an example of reading an XML file into the DataSet and then displaying the data in a DataGrid: Private Sub Button13_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Button13.Click Dim ds As New DataSet(“MyCompany”) ds.ReadXml(“C:\EmployeeList.XML”) DataGrid1.DataSource = ds.Tables(“Employee”) DataBind() End Sub The browser output is shown in Figure 9.12. This code reads the Employ- eeList.XML file into the DataSet. The DataSet parses the repeating rows into tables. The end result is that two tables are created: the Employee table and the Address table. The DataSet does well at identifying the XML data, but all of the data types are strings and many of the data types, such as dates and numbers, produce the desired results. This can be corrected by supplying an XML schema. An XSL schema can be supplied as a separate file, or it can be embedded into the XML file. For the EmployeeList.XML file, an XML schema might look like the following: <?XML version=”1.0” standalone=”yes”?> <xs:schema id=”EmployeeList” xmlns=”” xmlns:xs=”http://www.w3.org/2001/XMLSchema” xmlns:msdata=”urn:schemas-microsoft-com:XML-msdata”> <xs:element name=”EmployeeList” msdata:IsDataSet=”true”> <xs:complexType> <xs:choice maxOccurs=”unbounded”> <xs:element name=”Employee” id=”EmpID”> <xs:complexType> <xs:sequence> <xs:element name=”HireDate” type=”xs:dateTime” minOccurs=”0” msdata:Ordinal=”0” /> <xs:element name=”Address” minOccurs=”0” maxOccurs=”unbounded”> 368 Chapter 9 k 430234 Ch09.qxd 7/1/03 9:02 AM Page 368 <xs:complexType> <xs:sequence> <xs:element name=”Street1” type=”xs:string” minOccurs=”0” /> <xs:element name=”Street2” type=”xs:string” minOccurs=”0” /> <xs:element name=”City” type=”xs:string” minOccurs=”0” /> <xs:element name=”State” type=”xs:string” minOccurs=”0” /> <xs:element name=”ZipCode” type=”xs:string” minOccurs=”0” /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name=”EmpID” type=”xs:integer” use=”required” /> <xs:attribute name=”LastName” type=”xs:string” /> <xs:attribute name=”FirstName” type=”xs:string” /> <xs:attribute name=”Salary” type=”xs:decimal” /> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> Using this schema, the DataSet knows that the HireDate is indeed a date field, the EmpID is an integer, and the Salary is a decimal. The DataSet has a WriteXmlSchema method that can save the derived schema to a file. This produces a baseline schema that can modified and loaded back into the DataSet using the ReadXmlSchema. Figure 9.12 The EmployeeList is read into memory and bound to the DataGrid. Working with XML Data 369 k 430234 Ch09.qxd 7/1/03 9:02 AM Page 369 Writing an XML Document from the DataSet A DataSet can be saved to an XML file using the WriteXml method, regardless of its original source. One option that is available is the ability to change the output type of each column when writing the data. For example, the HireDate can be an element or an attribute. The following code changes all columns of all tables to attributes and then writes the XML with an embedded schema to a file called EList.XML: Private Sub Button14_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Button14.Click Dim ds As New DataSet(“MyCompany”) ds.ReadXmlSchema(“c:\el.xsd”) ds.ReadXml(“C:\EmployeeList.XML”) Dim t As DataTable For Each t In ds.Tables Dim c As DataColumn For Each c In t.Columns c.ColumnMapping = MappingType.Attribute Next Next ds.WriteXml(“c:\EList.XML”, XmlWriteMode.WriteSchema) End Sub The code changes all columns by changing the ColumnMapping properties of all Columns of all Tables to MappingType.Attribute. The options for the MappingType are Attribute, Element, Hidden, or SimpleContent. Another change that can be made to the XML output is nesting of parent and child tables. The relation has a Nested property that can be set to control the nesting. The following code sets the Nested property to false for all relation- ships in the DataSet: Dim r As DataRelation For Each r In ds.Relations r.Nested = False Next When the columns are all changed to attributes and the nesting is set to false, the XML output looks like the following: 370 Chapter 9 k 430234 Ch09.qxd 7/1/03 9:02 AM Page 370 <?XML version=”1.0” standalone=”yes”?> <EmployeeList> <Employee HireDate=”2003-01-01T00:00:00.0000000-05:00” EmpID=”1” LastName=”GaryLast” FirstName=”Gary” Salary=”50000” Employee_Id=”0” /> <Employee HireDate=”2003-01-02T00:00:00.0000000-05:00” EmpID=”2” LastName=”RandyLast” FirstName=”Randy” Salary=”40000” Employee_Id=”1” /> <Address Street1=”123 MyStreet” Street2=”” City=”MyCity” State=”My” ZipCode=”12345” Employee_Id=”0” /> <Address Street1=”234 MyStreet” Street2=”” City=”MyCity” State=”My” ZipCode=”23456” Employee_Id=”1” /> </EmployeeList> The Employee_ID is a column that was dynamically added in order to main- tain the relationship between the Employee table and the Address table. Last, the name that is passed into the DataSet’s constructor is the name of the DataSet, and also the name of the root element for the XML output. Using the XmlDataDocument with a DataSet There may be times when is it more desirable to work with data in an XML fashion instead of table rows and columns. This can be done by creating an XmlDataDocument and passing a DataSet into the class constructor. In the fol- lowing example, the Suppliers table is read from the Northwind database, and then an XmlDataDocument is created from the DataSet. Finally, a resultant table is created, containing the SupplierID, CompanyName, and Contact- Name, as shown in Figure 9.13. Figure 9.13 Creating an HTML table by navigating the XmlDataDocument. Working with XML Data 371 k 430234 Ch09.qxd 7/1/03 9:02 AM Page 371 Private Sub Button15_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Button15.Click ‘Connection Dim cn As New SqlConnection() Dim cnstr As String cnstr = “server=.;integrated security=yes;database=northwind” cn.ConnectionString = cnstr ‘Command Dim cmd As New SqlCommand() cmd.CommandText = _ “Select SupplierID, CompanyName, ContactName from Suppliers” cmd.Connection = cn Dim da As New SqlDataAdapter(cmd) Dim ds As New DataSet(“NW”) da.Fill(ds, “Suppliers”) Dim x As New XmlDataDocument(ds) Dim nav As XPathNavigator = x.CreateNavigator() Dim node As XPathNodeIterator node = nav.Select(“//Suppliers”) Response.Write(“<table border=’1’>”) Do While node.MoveNext() Response.Write(“<tr>”) Dim nav2 As XPathNavigator nav2 = node.Current Response.Write(“<td>”) nav2.MoveToFirstChild() ‘ID Response.Write(nav2.Value & “ “) Response.Write(“</td>”) Response.Write(“<td>”) nav2.MoveToNext() Response.Write(nav2.Value & “ “) Response.Write(“</td>”) Response.Write(“<td>”) nav2.MoveToNext() Response.Write(nav2.Value & “<br>”) Response.Write(“</td>”) Response.Write(“</tr>”) Loop Response.Write(“</table>”) End Sub This code builds a simple table containing the SupplierID, CompanyName, and ContactName, using an XPathNavigator. 372 Chapter 9 k 430234 Ch09.qxd 7/1/03 9:02 AM Page 372 Validating XML Documents Having the ability to define the structure of an XML document and then vali- date the XML document against its defined structure is an important element of being able to exchange documents between disparate systems. The .NET Framework offers the ability to perform validation against a document type definition (DTD) or schema. This section explores XML document validation using the XmlValidatingReader class. XmlValidatingReader The XmlValidatingReader class performs forward-only validation of a stream of XML. The XmlValidatingReader constructor can be passed to an XmlReader, a string, or a stream. This class has a ValidationType property that can be set to Auto, DTD, None, Schema, or XDR. If the setting is set to None, this class becomes an XmlTextReader. In the next example, the file in Listing 9.1 is validated using the following code: Private Sub Button16_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Button16.Click Dim vr As New XmlValidatingReader( _ New XmlTextReader(“C:\xmltest.XML”)) vr.ValidationType = ValidationType.DTD Dim xd As New XmlDocument() xd.Load(vr) Response.Write(“Valid Document!<br>”) vr.Close() End Sub This code simply opens the XML file with an XmlTextReader, and the reader is used as the input to the XmlValidatingReader. Since this code has an embed- ded DTD, the document is validated. In the next test, the input file has been modified. <?XML version=”1.0” encoding=”utf-8”?> <!DOCTYPE myRoot [ <!ELEMENT myRoot ANY> <!ELEMENT myChild ANY> <!ELEMENT myGrandChild EMPTY> <!ATTLIST myChild ChildID ID #REQUIRED > Working with XML Data 373 k 430234 Ch09.qxd 7/1/03 9:02 AM Page 373 ]> <myRoot> <myChild ChildID=”ref-1”> <myGrandChild/> <myGrandChild>Hi</myGrandChild> <myGrandChild/> </myChild> <myChild ChildID=”ref-2”> <myGrandChild/> <myGrandChild/> <myGrandChild/> </myChild> <myChild ChildID=”ref-3”> <myGrandChild/> <myGrandChild/> <myGrandChild/> </myChild> <myChild ChildID=”ref-4”> <myGrandChild/> <myGrandChild/> <myGrandChild/> </myChild> </myRoot> The DTD states that the myGrandChild element must be empty, but one of the myGrandChild elements of myChild ref-1 has a myGrandChild element containing the word Hi. This causes an error, as shown in Figure 9.14. Attempts to read from the XmlValidatingRead should always occur within a Try/Catch block to catch possible validation exceptions. Figure 9.14 The error that is generated when an invalid document is validated using the XmlValidatingReader. 374 Chapter 9 k 430234 Ch09.qxd 7/1/03 9:02 AM Page 374 Lab 9.1: Working with XML Data You have a requirement to be able to save a customer’s orders, along with the order details, to an XML file. The XML file must have only three levels of elements. The first level is the root element, which is called Customers, and has attributes for the CustomerID, CompanyName, and Contact- Name. The second level is the Orders element, which contains an Orders element for each order that the customer has. The third level contains Order_Details elements, which contain an element for each item in the order. The XML document essentially contains an element for each row of each table, and all column data must be presented as XML attributes. In this lab, you modify the DataGrid from the previous lab, to add a Save Orders button to the DataGrid; this button writes the current customer’s orders to an XML file. Retrieving the Data In this section, you modify the Bindtable method to retrieve the cus- tomers, orders and order details for all customers, and store the results in a Session variable. DataRelations also is created to join these tables together, and the ColumnMapping must be set to be an attribute for every column in the DataSet. 1. Start this lab by opening the OrderEntrySolution from Lab 8.1. 2. Right-click the OrderEntrySolution in the Solution Explorer, and click Check Out. This checks out the complete solution. 3. Open the CustomerList.aspx.vb code-behind page. 4. In the Bindtable method, modify the code to check for the existence of a Session variable named Customers. If it exists, assign the Ses- sion variable to a DataSet. 5. If the Session variable does not exist, populate a new DataSet with Customers, Orders, and Order Details from the Northwind SQL database. Add relations between the Customers and Orders tables, and between the Orders and Order Details tables. 6. Add a loop, which enumerates all tables and all columns of the DataSet, setting the ColumnMapping to Attribute. 7. Store the DataSet in the Customers Session variable. Your code should look like the following: Public Sub Bindtable() Dim ds As DataSet If Session(“Customers”) Is Nothing Then Dim cnstr As String Working with XML Data 375 k 430234 Ch09.qxd 7/1/03 9:02 AM Page 375 cnstr = “server=.;integrated security=yes;” _ & “database=northwind” Dim cn As New SqlConnection(cnstr) Dim sql As String = _ sql = “Select CustomerID, CompanyName, ContactName “ _ & “ from customers” Dim da As New SqlDataAdapter(sql, cn) ds = New DataSet(“NW”) ‘Fill Customers da.Fill(ds, “Customers”) ds.Tables(“Customers”).PrimaryKey = _ New DataColumn() _ {ds.Tables(“Customers”).Columns(“CustomerID”)} ‘Fill Orders sql = “Select * from Orders” da.SelectCommand.CommandText = sql da.Fill(ds, “Orders”) ds.Tables(“Orders”).PrimaryKey = _ New DataColumn() _ {ds.Tables(“Orders”).Columns(“OrderID”)} ‘Fill Order Details sql = “Select * from [Order Details]” da.SelectCommand.CommandText = sql da.Fill(ds, “Order_Details”) ds.Tables(“Order_Details”).PrimaryKey = _ New DataColumn() _ {ds.Tables(“Order_Details”).Columns(“OrderID”), _ ds.Tables(“Order_Details”).Columns(“ProductID”)} ‘Create Customers to Orders Relation ds.Relations.Add( _ “CustomersOrders”, _ ds.Tables(“Customers”).Columns(“CustomerID”), _ ds.Tables(“Orders”).Columns(“CustomerID”), _ True) ds.Relations(“CustomersOrders”).Nested = True ‘Create Orders to Order Details Relation ds.Relations.Add( _ “OrdersOrderDetails”, _ ds.Tables(“Orders”).Columns(“OrderID”), _ ds.Tables(“Order_Details”).Columns(“OrderID”), _ True) ds.Relations(“OrdersOrderDetails”).Nested = True ‘Change all columns to attributes Dim t As DataTable For Each t In ds.Tables Dim c As DataColumn For Each c In t.Columns c.ColumnMapping = MappingType.Attribute Next Next Session(“Customers”) = ds Else 376 Chapter 9 k 430234 Ch09.qxd 7/1/03 9:02 AM Page 376 ds = CType(Session(“Customers”), DataSet) End If dgCustomers.DataSource = ds.Tables(“Customers”) dgCustomers.DataKeyField = “CustomerID” DataBind() End Sub Preparing the Data Grid The DataGrid needs to be updated to have a Save button beside each cus- tomer. The Save button is used to initiate the storing of customer data in an XML file. 1. In the Init event method of the DataGrid, add code to create a button column. 2. Set the properties of the button. Be sure that the CommandName is called Save. This is used in the ItemCommand method, in order to find out which button was pressed. 3. Your code should look like the following: Private Sub dgCustomers_Init( _ ByVal sender As Object, _ ByVal e As System.EventArgs) _ Handles dgCustomers.Init Dim colButton As New ButtonColumn() With colButton .ButtonType = ButtonColumnType.PushButton .CommandName = “Save” .ItemStyle.Width = New Unit(100, UnitType.Pixel) .ItemStyle.HorizontalAlign = HorizontalAlign.Center .HeaderStyle.HorizontalAlign = HorizontalAlign.Center .HeaderText = “Save Orders<br>as XML” .Text = “Save” End With dgCustomers.Columns.Add(colButton) End Sub Save Customer’s Orders to XML File In this section, you add code to the ItemCommand method of the Data- Grid. This code retrieves the customer primary key of the selected cus- tomer. The code then uses an XmlDataDocument to get data from the DataSet and write the data to the XML file. 1. Add an if statement to the ItemCommand, which checks to see if the Command is Save. All additional code is placed inside the if statement. 2. Add code to retrieve the DataSet from the Session variable. 3. Declare a variable called XML as a XmlDataDocument. Check to see if a Session variable called CustomersXml exists. If so, assign the Working with XML Data 377 k 430234 Ch09.qxd 7/1/03 9:02 AM Page 377 [...]... application 1 Right-click the Customer project in the Solution Explorer Click Set As StartUp Project 2 Right-click the CustomerList.aspx page Click Set As Start Page 3 Run the application The result should look like that shown in Figure 9. 15 Figure 9. 15 The CustomerList page filled with Customers 4 Click the Save button for CustomerID ANTON The browser output is shown in Figure 9. 16 Notice that there... represents ANTON, followed by the orders and order items Figure 9. 16 The browser output of CustomerID = ANTON 5 Check you work back into Visual SourceSafe 3 79 380 Chapter 9 Summary ■ ■ XML documents can be accessed using the Document Object Model (DOM) Level 1 and Level 2 ■ ■ The XPathNavigator uses a cursor model and XPath queries to provide read-only, random access to the data ■ ■ The XmlValidatingReader... As String s1options = String.Format( _ “s1 - CanRead:{0} CanSeek:{1} CanWrite:{2}”, _ s1.CanRead, _ s1.CanSeek, _ s1.CanWrite) Response.Write(s1options) Dim b As Byte() b = System.Text.Encoding.Unicode.GetBytes(“Hello World”) s1.Write(b, 0, b.Length) s1.Close() End Sub 3 89 390 Chapter 10 The browser displays the following information about the stream: s1 - CanRead:True CanSeek:True CanWrite:True... Figure 10.3 Browser output when writing and reading a file 391 392 Chapter 10 Private Sub Button2_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click Dim s1 As New FileStream( _ “c:\test.txt”, _ FileMode.OpenOrCreate, _ FileAccess.Read, FileShare.Read) Dim s1options As String s1options = String.Format( _ “s1 - CanRead:{0} CanSeek:{1} CanWrite:{2}”, _ s1.CanRead,... Stream.Null Dim s1options As String s1options = String.Format( _ “s1 - CanRead:{0} CanSeek:{1} CanWrite:{2}”, _ s1.CanRead, _ s1.CanSeek, _ s1.CanWrite) Response.Write(s1options) Dim b As Byte() b = System.Text.Encoding.Unicode.GetBytes(“Hello World”) s1.Write(b, 0, b.Length) s1.Seek(0, SeekOrigin.Begin) Dim strOutput As String = “” 393 394 Chapter 10 Dim bInput(10) As Byte Dim count As Integer = bInput.Length... e As System.EventArgs) _ Handles Button3.Click Dim s1 As New MemoryStream() Dim s1options As String s1options = String.Format( _ “s1 - CanRead:{0} CanSeek:{1} CanWrite:{2}”, _ s1.CanRead, _ s1.CanSeek, _ s1.CanWrite) Response.Write(s1options) Dim b As Byte() 395 396 Chapter 10 b = System.Text.Encoding.Unicode.GetBytes(“Hello World”) s1.Write(b, 0, b.Length) s1.Seek(0, SeekOrigin.Begin) Dim strOutput... DecNet, and InternetNetwork (IP) Examples of the ProtocolType are SPX, TCP, and UDP 397 398 Chapter 10 Get URL from User Get IPAddress from URL Create IPEndPoint with IP and Port Create Get Request Create Socket Connect Socket to EndPoint Send Get Request Receive Response from Stream Response to User Figure 10.7 A high-level view of the progam flow when working with the NetworkStream to retrieve the... order to communicate over the network 399 400 Chapter 10 Figure 10.8 An example of using the NetworkStream to read a Web page CryptoStream The CryptoStream class provides the ability to move and process data from one stream to another This stream does not have an endpoint This class inherits all the methods in the Stream class and has additional cryptographic-centric properties and methods CryptoStream... network endpoint This class inherits all the methods in the Stream class and has additional network-centric properties and methods NetworkStreams can be used to access a Web site, as well as to communicate between local computers It takes a little bit more code to set up the NetworkStream Figure 10.7 shows a high-level view of the program flow when using the NetworkStream to retrieve the default Web page... FileMode.Create) Dim s1options As String s1options = String.Format( _ “s1 - CanRead:{0} CanSeek:{1} CanWrite:{2}”, _ s1.CanRead, _ s1.CanSeek, _ s1.CanWrite) Response.Write(s1options) Dim b As Byte() b = System.Text.Encoding.Unicode.GetBytes(“Hello World”) s1.Write(b, 0, b.Length) Dim strOutput As String = “” Dim bInput (9) As Byte Dim count As Integer = bInput.Length Do While (count > 0) count . following: 370 Chapter 9 k 430234 Ch 09. qxd 7/1/03 9: 02 AM Page 370 <?XML version=”1.0” standalone=”yes”?> <EmployeeList> <Employee HireDate=”200 3-0 1-0 1T00:00:00.000000 0-0 5:00” EmpID=”1”. using the ReadXmlSchema. Figure 9. 12 The EmployeeList is read into memory and bound to the DataGrid. Working with XML Data 3 69 k 430234 Ch 09. qxd 7/1/03 9: 02 AM Page 3 69 Writing an XML Document from. CompanyName, and Contact- Name, as shown in Figure 9. 13. Figure 9. 13 Creating an HTML table by navigating the XmlDataDocument. Working with XML Data 371 k 430234 Ch 09. qxd 7/1/03 9: 02 AM Page 371 Private

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

Từ khóa liên quan

Mục lục

  • Chapter 9 Working with XML Data

    • Working with XML Documents

      • DataSets and XML

        • Reading an XML Document into the DataSet

        • Writing an XML Document from the DataSet

        • Using the XmlDataDocument with a DataSet

        • Validating XML Documents

          • XmlValidatingReader

          • Lab 9.1: Working with XML Data

          • Summary

          • Chapter 10 Streams, File Access, and Serialization

            • Classroom Q & A

            • Stream Classes

              • Stream

              • FileStream

                • FileStream Constructor

                • FileStream Examples

                • Null Stream

                • MemoryStream

                  • MemoryStream Constructor

                  • MemoryStream Examples

                  • NetworkStream

                    • NetworkStream Constructor

                    • NetworkStream Example

                    • CryptoStream

                      • CryptoStream Constructor

                      • CryptoStream Encryption Example

                      • CryptoStream Decryption Example

                      • BufferedStream

                        • BufferedStream Constructor

                        • BufferedStream Example

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

Tài liệu liên quan