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

Professional ASP.NET 1.0 Special Edition- P19 potx

40 208 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 40
Dung lượng 1,14 MB

Nội dung

'create connection and command to access database Dim objConnect As New OleDbConnection(strConnect) Dim objCommand As New OleDbCommand(strSQL, objConnect) 'declare the variables we'll need Dim objReader As OleDbDataReader Dim strValues As String = "" Dim intIndex As Integer Try 'get a DataReader containing the specified row data objConnect.Open() objReader = objCommand.ExecuteReader() 'put values from row into a string to return If objReader.Read() Then For intIndex = 0 To objReader.FieldCount - 1 strValues += objReader.GetValue(intIndex) & ", " Next End If 'close connection and return result objConnect.Close() GetUnderlyingValues = Left(strValues, Len(strValues) - 2) Catch objError As Exception GetUnderlyingValues = "*Error*" End Try End Function Summary This chapter has been devoted entirely to the often-thorny problems we encounter when updating a relational data source such as a SQL database from within our applications. While the techniques have focused on using the .NET data access classes with a relational database, bear in mind that the connection between our code and the data store is via standard methods such as OLE-DB and ODBC. This means that, as new managed providers become available, we can use the same techniques to work with other data stores such as mail servers, active directory, indexing services, etc. The chapter began with a look at the techniques we often use to perform single operations against a data store - such as inserting a user's name and e-mail address into a database, or deleting rows in response to a user's input. We demonstrated how to do this with both SQL statements and with stored procedures. We also looked at how we can use transactions to provide better data integrity. We used both database transactions and .NET connection-based transactions. However, the main focus of the chapter was on how we use the new DataSet object to store and then update data in a disconnected environment. We saw how we can use the Update method of the DataAdapter to push updates into a data store automatically, and how we can carry out the task ourselves in a staged and more controllable manner. We finished up with a look at a major issue in all multi-user environments - concurrent data updates. We saw how we can work round the problem using our own custom methods, and how the .NET data access classes provide other techniques that make it much easier than the data access technologies we used in previous versions of ASP. Overall, the topics we examined were:  Updating data sources with a Command object  Using transactions when updating data sources  Updating data sources from a DataSet object  A detailed look inside the DataAdapter.Update method  Managing concurrent updates to a data source This chapter completes our look at how we can work with relational data within .NET using the new data-access classes that the framework provides. However, the ceaseless advance of XML into our daily data-handling lives requires us to be competent in handling this new type of data format, as well as being proficient in handling relational data. And, to help us out, the .NET classes provide useful integration between relational and XML data. In the next chapter we'll explore this topic, and see other ways that we can access and manipulate XML. XML Data Management in .NET The previous three chapters have largely been concerned with working with relational data in ASP.NET. Even though XML is gradually spreading into most areas of computing, databases such as Microsoft SQL Server, Oracle, DB2, and Sybase still form the backbone of most commercial environments. However, to conclude our study of data management techniques within ASP.NET, we'll devote this chapter to looking in more detail at how we can work with XML documents. Unlike the previous situation with ASP 3.0 and earlier, we don't need to use add-ons such as an XML parser or other specialist components to be able to work with XML formatted data. All the tools we need are built into the .NET Framework as a set of useful and extensible classes. We can use these to read, write, and edit XML in its native format, and convert from relational data to XML and back again. So, in this chapter, we'll look at:  Accessing relational data as XML and vice versa  Synchronization between an XML document and the DataSet object  Validating XML documents using a schema  Creating and editing XML documents in a range of different ways  Some alternatives available when transforming XML using style sheets We spent some time in Chapter 8 exploring the whole object model for XML under .NET, and the way this changes how we work with X ML . We also demonstrated many of th e more simp le te chniqu es . Here, we'll di ve straight in wit h a de tailed look at the major topic of the interchangeability of XML and relational data. Obtaining the Sample Files All the examples used in this chapter are available for you to run on your own server. The download file can be obtained from http://www.wrox.com/Books/Book_Details.asp?isbn=1861007035, and it includes SQL scripts and instructions for creating the database that the examples use. You can also run some of the examples online at http://www.daveandal.com/profaspnet/. The main menu page ( default.htm) contains links to all the sample files. The fifth link, "Advanced Relational Data Management in .NET " leads to another menu page (in the data05 folder) that contains links to all the examples for this chapter: XML and the DataSet Object Despite the ubiquitous presence of relational databases as the powerhouses of most commercial environments today, the use of XML as a data format is growing steadily. The ease of transmission and storage of XML as a text document (or within a database table as text), and its inherent cross-platform nature make it ideal for many situations. In fact, within the .NET Framework, XML is actually the foundation for all data storage and serialization. There are no more MIME-encoded Recordset objects or COM objects that hold data in their own specific formats. A good example is the DataSet object we've been using throughout the previous chapters. We've viewed it as a container for one or more data tables (rather like some wrapper around multiple Recordset objects). This is a reasonable approach when we need to access the data using relational techniques. However, the DataSet can persist its contents as a disk file, or into another object such as a Stream. The format of the data at this point is XML. The XML-based Methods of the DataSet The DataSet object exposes the following methods for working with an XML representation of the data it contains or will contain: GetXml Returns a string containing the XML representation of the data stored in the DataSet. No schema information is output. GetXmlSchema Returns just the schema for an XML representation of the data stored in the DataSet. InferXmlSchema Uses a schema that is referenced by a TextReader, XmlReader, or Stream object, or in a specified disk file, to infer the structure for the data in a DataSet. ReadXml Reads XML data (including a schema if present) into the DataSet from a TextReader, XmlReader, or Stream object, or from a specified disk file. ReadXmlSchema Reads an XML schema (only) into the DataSet from a TextReader, XmlReader, or Stream object, or from a specified disk file. WriteXml Writes the contents of the DataSet object to an XML document via a TextWriter, XmlWriter, or Stream object, or directly to a specified disk file. May include a schema - see the notes following the next example. WriteXmlSchema Writes a schema describing the contents of the DataSet object to a TextWriter, XmlWriter, or Stream object, or directly to a specified disk file. In general, when extracting XML from a DataSet (unless you actually need a string representation of the data) the GetXml and GetXmlSchema methods should be avoided. It's much more efficient to create a Stream or disk file directly, or take advantage of a TextWriter or XmlWriter when using the WriteXml and WriteXmlSchema methods. We'll demonstrate these two methods, and the ReadXml and ReadXmlSchema methods, in the next two examples. Some of the example files in this chapter require Write access to the server's wwwroot folder and subfolders below this. You will get an " Access Denied" message for these examples when running under the default configuration of ASP.NET. See the section "Setting Up the Samples" in Chapter 8 for details of how to configure the relevant permissions. Writing Data from a DataSet to an XML File Our first example demonstrates the way we can write data from a DataSet directly to a disk file as an XML document. As we're filling the DataSet from a relational database, we need to include the relevant .NET namespaces in our page, and we also include the custom user control that returns the correct connection string for our machine: <%@Import Namespace="System.Data" %> <%@Import Namespace="System.Data.OleDb" %> <%@ Register TagPrefix="wrox" TagName="connect" Src=" \global\connect-strings.ascx" %> <%' insert connection string script %> <wrox:connect id="ctlConnectStrings" runat="server" /> The way we're filling the DataSet is identical to the techniques and code we used in the previous chapters, and so we won't be describing it in detail again here. For more information, refer back to Chapter 8, Introducing .NET Data Management. The page contains three <div> elements where we output information and results: <div>Connection string: <span id="outConnect" runat="server" /></div> <div>SELECT command: <span id="outSelect" runat="server" /></div> <div id="outMessage" runat="server" /> Filling the DataSet In the Page_Load event, we fill our DataSet using a SQL statement that joins two tables: Sub Page_Load() Dim strConnect As String strConnect = ctlConnectStrings.OLEDBConnectionString outConnect.innerText = strConnect Dim strSelect As String strSelect = "SELECT BookList.*, BookAuthors.FirstName, " _ & "BookAuthors.LastName FROM BookList INNER JOIN " _ & "BookAuthors ON BookList.ISBN = BookAuthors.ISBN " _ & "WHERE BookList.ISBN LIKE '18610033%'" outSelect.innerText = strSelect Dim objDataSet As New DataSet Try Dim objConnect As New OleDbConnection(strConnect) Dim objDataAdapter As New OleDbDataAdapter(strSelect, objConnect) objDataAdapter.Fill(objDataSet, "Books") Catch objError As Exception outError.innerHTML = "Error while accessing data.<br />" _ & objError.Message & "<br />" & objError.Source Exit Sub End Try Now that we have a DataSet containing our data, we can write it out to a disk file as XML. The next screenshot shows the results of running this page ' Writing Data from a DataSet to an XML File' (write-data-as-xml.aspx): You can see that the page includes two hyperlinks to the files we've created - the XML data itself and the XSD schema that defines the structure of the XML document. The code to create these two files is shown below. Creating the XML Data and Schema Files All we have to do is create the appropriate virtual path and name for the two files, and then call the WriteXml and WriteXmlSchema methods. We do this within a Try Catch construct to trap any errors that might arise while writing the files - for example if ASP.NET does not have the relevant permission or if the path does not exist. If all goes well, we display the confirmation messages and hyperlinks to the new files: Try 'use the path to the current virtual application Dim strVirtualPath As String = Request.ApplicationPath _ & "/XML-from-DataSet.xml" Dim strVSchemaPath As String = Request.ApplicationPath _ & "/Schema-from-DataSet.xsd" 'write data and schema from DataSet to documents on disk 'must use the Physical path to the file not the Virtual path objDataSet.WriteXml(Request.MapPath(strVirtualPath)) outMessage.innerHTML = "Written file: <a href=" & Chr(34) _ & strVirtualPath & Chr(34) & ">" _ & strVirtualPath & "</a><br />" objDataSet.WriteXmlSchema(Request.MapPath(strVSchemaPath)) outMessage.innerHTML += "Written file: <a href=" & Chr(34) _ & strVSchemaPath & Chr(34) & ">" _ & strVSchemaPath & "</a></b>" Catch objError As Exception 'display error details outMessage.innerHTML = "Error while writing disk file.<br />" _ & objError.Message & "<br />" & objError.Source Exit Sub ' and stop execution End Try Notice that we have to provide a physical path to the XML document files, not the virtual path. The Resulting XML Document If you click the hyperlinks in the page, you can view the XML document and schema we've created. The XML document is [...]... statement: It's kind of hard to see what the structure of the XML is from the screenshot, but if we break out one of the elements you can see the structure quite clearly: There are a couple of things to note This is not an XML document, as there is no document type declaration or root element All we get back is a... useful to developers already, and it's extremely fast and efficient To support it in NET simply entailed including an option to return an object that could hold XML document fragments The answer is a special version of the "execute" methods available in the Command object we use for relational data access, but which returns an XmlReader object instead of a DataReader object (like we used in the relational . server. The download file can be obtained from http://www.wrox.com/Books/Book_Details .asp? isbn =18 6 10 0 703 5, and it includes SQL scripts and instructions for creating the database that the examples. management techniques within ASP. NET, we'll devote this chapter to looking in more detail at how we can work with XML documents. Unlike the previous situation with ASP 3 .0 and earlier, we don't. "BookAuthors ON BookList.ISBN = BookAuthors.ISBN " _ & "WHERE BookList.ISBN LIKE &apos ;18 6 10 033%'" outSelect.innerText = strSelect Dim objDataSet As New DataSet Try

Ngày đăng: 03/07/2014, 07:20