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

Professional ASP.NET 2.0 XML phần 6 pps

60 263 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 60
Dung lượng 1,3 MB

Nội dung

“CAST(BirthDate AS char(12)) AS BirthDate from “ + “HumanResources.Employee Where EmployeeID =” + employeeID.ToString(), sqlConnection); //Set the SqlCommand object properties command.CommandType = CommandType.Text; adapter.SelectCommand = command; //Fill the Dataset with the return value from the stored procedure adapter.Fill(employeeDataset,”Employees” ); XmlDocument xmlDoc = new XmlDocument(); return employeeDataset.GetXml(); } } catch (Exception ex) { throw ex; } } public void Page_Load(object sender, EventArgs e) { if (!Request.Browser.SupportsCallback) throw new ApplicationException(“This browser doesn’t support “ + “Client callbacks.”); string src = Page.ClientScript.GetCallbackEventReference(this, “arg”, “DisplayResultsCallback”, “ctx”, “DisplayErrorCallback”, false); string mainSrc = @”function GetEmployeeDetailsUsingPostback(arg, ctx){ “ + src + “; }”; Page.ClientScript.RegisterClientScriptBlock(this.GetType(), “GetEmployeeDetailsUsingPostback”, mainSrc, true); } </script> <html> <head> <title>Retrieving XML Dynamically using ASP.NET 2.0 Script Callback</title> <script language=”javascript”> function GetEmployeeDetails() { var n = document.forms[0].txtEmployeeID.value; GetEmployeeDetailsUsingPostback(n, “txtNumber”); } function DisplayResultsCallback( result, context ) { var strXML,objXMLNode,objXMLDoc,objEmployee,strHTML; objXMLDoc = new ActiveXObject(“Microsoft.XMLDOM”); //Load the returned XML string into XMLDOM Object objXMLDoc.loadXML(result); //Get reference to the Employees Node objEmployee = objXMLDoc.selectSingleNode(“EmployeesRoot”). selectSingleNode(“Employees”); 274 Chapter 9 12_596772 ch09.qxd 12/13/05 11:15 PM Page 274 //Check if a valid employee reference is returned from the server strHTML = “<font color=’#0000FF’>”; if (objEmployee != null) { //Dynamically generate HTML and append the contents strHTML += “<br><br>Employee ID :<b>” + objEmployee.selectSingleNode(“EmployeeID”).text + “</b><br><br>”; strHTML += “Title:<b>” + objEmployee.selectSingleNode(“Title”).text + “</b><br><br>”; strHTML += “Hire Date :<b>” + objEmployee.selectSingleNode(“HireDate”).text + “</b><br><br>”; strHTML += “Gender:<b>” + objEmployee.selectSingleNode(“Gender”).text + “</b><br><br>”; strHTML += “Birth Date:<b>” + objEmployee.selectSingleNode(“BirthDate”).text + “</b><br><br>”; } else { strHTML += “<br><br><b>Employee not found</b>”; } strHTML += “</font>” //Assign the dynamically generated HTML into the div tag divContents.innerHTML = strHTML; } function DisplayErrorCallback( error, context ) { alert(“Employee Query Failed. “ + error); } </script> </head> <body> <form id=”Form1” runat=”server”> <font color=”#800080”><H1>Employee Details</H1></font> <br><br> <P align=”left”> <font color=”#800080”><b>Enter the Employee ID:</b> </font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <INPUT id=”txtEmployeeID” name=”txtEmployeeID” style=”LEFT: 149px; TOP: 72px”> <INPUT id=”btnGetEmployee” type=”button” value=”Get Employee Details” name=”btnGetEmployee” onclick=”GetEmployeeDetails()”> </P> <P></P> <div id=”divContents”> </div> <P></P> </form> </body> </html> 275 XML Data Display 12_596772 ch09.qxd 12/13/05 11:15 PM Page 275 To understand the code better, consider the code listing as being made up of three different parts. ❑ Implementing the server-side event for callback ❑ Generating the client-side script for callback ❑ Implementing client callback method Start by looking at the server-side event for callback. Implementing the Server-Side Event for Callback At the top of page, you import the required namespaces by using the Import directive. After that we use the implements directive to implement the ICallbackEventHandler interface. This interface has a method named RaiseCallbackEvent that must be implemented to make the callback work. <%@ implements interface=”System.Web.UI.ICallbackEventHandler” %> The signature of the RaiseCallbackEvent method is as follows. void ICallbackEventHandler.RaiseCallbackEvent(string eventArgs) As you can see from the above, the RaiseCallbackEvent method takes an argument of type string. If you need to pass values to the server-side method, you should use this string argument. Inside the RaiseCallbackEvent method, you store the supplied event argument in a local private variable for future use. void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument) { _callbackArg = eventArgument; } After that, you override the GetCallbackResult() method as shown below. string ICallbackEventHandler.GetCallbackResult() { int value = Int32.Parse(_callbackArg); return GetEmployeeDetails(value); } The GetCallbackResult() method is the one that is responsible for returning the output of the server- side execution to the client. Inside the GetCallbackResult() method, you first convert the supplied employee ID into an integer type and then invoke a function named GetEmployeeDetails passing in the employee ID as an argument. int value = Int32.Parse(eventArgs); return GetEmployeeDetails(value); As the name suggests, the GetEmployeeDetails() method retrieves the details of the employee and returns that information in the form of an XML string. This method starts by retrieving the connection string from the web.config file by using the following line of code. 276 Chapter 9 12_596772 ch09.qxd 12/13/05 11:15 PM Page 276 string connString = WebConfigurationManager. ConnectionStrings[“adventureWorks”].ConnectionString; The above line of code retrieves the connection string from the connectionStrings section of the web.config file. The connection string is stored in the web.config as follows. <connectionStrings> <add name=”adventureWorks” connectionString=”server=localhost;Integrated Security=true; database=AdventureWorks”/> </connectionStrings> Once the connection string is retrieved, you then create an instance of the SqlConnection object passing in the connection string as an argument. Then you create instances of DataSet, SqlDataAdapter, and SqlCommand objects passing in the appropriate parameters to their constructors. Then you execute the sql query by invoking the Fill() method of the SqlDataAdapter object. Once the query is executed and the results available in the DataSet object, you then invoke the GetXml() method of the DataSet object to return the XML representation of the DataSet to the caller. The GetCallbackResult() method receives the output xml string and simply returns it back to the caller. Generating the Client-Side Script for Callback This section will look at the Page_Load event of the page. In the beginning of the Page_Load event, you check to see if the browser supports callback by examining the SupportsCallback property of the HttpBrowserCapabilities object. if (!Request.Browser.SupportsCallback) throw new ApplicationException Then you invoke the Page.ClientScript.GetCallbackEventReference() method to implement the callback in client-side. You can use this method to generate client-side code, which is required to ini- tiate the asynchronous call to server. string src = Page.ClientScript.GetCallbackEventReference(this, “arg”, “DisplayResultsCallback”, “ctx”, “DisplayErrorCallback”, false); The arguments passed to the GetCallbackEventReference method are as follows: ❑ this —Control that implements ICallbackEventHandler(Current Page) ❑ arg —String to be passed to server-side as argument ❑ DisplayResultsCallback —Name of the client-side function that will receive the result from server-side event ❑ ctx —String to be passed from one client-side function to other client-side function through context parameter ❑ DisplayErrorCallback —Name of the client-side function that will be called if there is any error during the execution of the code ❑ false —Indicates that the server-side function to be invoked asynchronously 277 XML Data Display 12_596772 ch09.qxd 12/13/05 11:15 PM Page 277 When you execute this page from the browser and view the HTML source code, you will see that the following callback code is generated due to the above GetCallbackEventReference method call. WebForm_DoCallback(‘__Page’, arg, DisplayResultsCallback, ctx,DisplayErrorCallback, false) WebForm_DoCallback is a JavaScript function that in turn invokes the XmlHttp class methods to actu- ally perform the callback. Then you embed the callback code inside a function by concatenating the call- back generated code with a JavaScript function named GetEmployeeDetailsUsingPostback using the following line of code. string mainSrc = @”function “ + “GetEmployeeDetailsUsingPostback(arg, ctx)” + “{ “ + src + “; }”; Finally you register the client script block through the Page.ClientScript.RegisterClientScriptBlock() method call. Note that in ASP.NET 2.0, the Page.RegisterClientScriptBlock and Page.RegisterStartupScript methods are obsolete. That’s why you had to take the help of Page.ClientScript to render client-side script to client browser. Page.ClientScript property returns an object of type ClientScriptManager type, which is used for managing client scripts. Implementing Client Callback Method In the client side, you have a method named GetEmployeeDetails, which is invoked when the Get Employee Details command button is clicked. function GetEmployeeDetails() { var n = document.forms[0].txtEmployeeID.value; GetEmployeeDetailsUsingPostback(n, “txtNumber”); } From within the GetEmployeeDetails() method, you invoke a method named GetEmployeeDetailsUsingPostback() and pass in the required parameters. Note that the definition of the GetEmployeeDetailsUsingPostback() method is added in the Page_Load event in the server side (through the RegisterClientScriptBlock method call). Once the server-side function is exe- cuted, the callback manager automatically calls the DisplayResultsCallback() method. The code of the DisplayResultsCallback() method is shown below. In this example, because the value returned from the server-side page is an XML string, you load the returned XML into an XML- DOM parser and then parse its contents. objXMLDoc = new ActiveXObject(“Microsoft.XMLDOM”); //Load the returned XML string into XMLDOM Object objXMLDoc.loadXML(strXML); Then you get reference to the Employees node by invoking the selectSingleNode method of the MSXML DOM object. objEmployee = objXMLDoc.selectSingleNode(“EmployeesRoot”). selectSingleNode(“Employees”); 278 Chapter 9 12_596772 ch09.qxd 12/13/05 11:15 PM Page 278 If a valid Employees element is returned from the function call, you display its contents. You display this information in a div tag by setting the innerHTML property of the div element to the dynamically constructed HTML. if (objEmployee != null) { //Dynamically generate HTML and append the contents strHTML += “<br><br>Employee ID :<b>” + objEmployee.selectSingleNode(“EmployeeID”).text + “</b><br><br>”; strHTML += “Title:<b>” + objEmployee.selectSingleNode(“Title”).text + “</b><br><br>”; strHTML += “Hire Date :<b>” + objEmployee.selectSingleNode(“HireDate”).text + “</b><br><br>”; strHTML += “Gender:<b>” + objEmployee.selectSingleNode(“Gender”).text + “</b><br><br>”; strHTML += “Birth Date:<b>” + objEmployee.selectSingleNode(“BirthDate”).text + “</b><br><br>”; } When you browse to Listing 9-18 using the browser and search for an employee with employee ID of 1, the page will display the employee attributes such as title, hire date, gender, and birth date. Figure 9-10 When you click on the Get Employee Details button in Figure 9-10, you will notice that the employee information is retrieved from the server and displayed in the browser; all without refreshing the page. 279 XML Data Display 12_596772 ch09.qxd 12/13/05 11:15 PM Page 279 ASP.NET Atlas Technology In the previous section, you have seen how to utilize the script callback feature to dynamically retrieve XML data from the client-side. Having introduced the script callback feature with ASP.NET2.0, the ASP.NET team immediately realized the need for a richer development framework for building interactive dynamic Web applications. To this end, the ASP.NET team has released the early community preview edition of a new technology named Atlas that provides a rich server-side and client-side libraries. Through this library, Atlas enables you to create rich Web applications that harness the power of the server and the browser. Moreover Atlas accomplishes all of this without the traditional need to post-back to the server. Atlas Architecture Figure 9-11 shows the architecture of Atlas in terms of the different client and server components and their interactions. Figure 9-11 ASP.NET Atlas framework provides a suite of ASP.NET Server Controls, Web services, and JavaScript libraries. These simplify and enhance application creation by provid- ing in-built controls and components that can be used in traditional JavaScript script and event or through ASP.NET Atlas script. Atlas script is a new construct that allows simple declarative definition of client-side controls, components, behaviors, and data binding that are tied to markup elements in the page. 280 Chapter 9 12_596772 ch09.qxd 12/13/05 11:15 PM Page 280 As you can see from the above picture, Atlas doesn’t change or modify any core ASP.NET, .NET Framework or other binaries on your system. One of Atlas’s goals has been to make it really easy for developers to leverage the rich browser features without having to install a whole bunch of software components. You can download the early preview edition of Atlas from the following link. http://msdn.microsoft.com/asp.net/future/atlastemplate/default.aspx Installing Atlas is very simple. You can download the msi from the above link. After completing the install, if you open up the Visual Studio 2005 New Project dialog box, you will see a new template for Atlas. If you don’t want to run the install and you simply want to leverage the core functionalities, you can do that as well. All you need to do is to copy the assembly Microsoft.Web.Atlas.dll binary into your projects’ \bin directory and copy the Atlas\ScriptLibrary directory of .js files into your pro- ject. The advantage of the msi installation is that it creates the ASP.NET Atlas Web Project template that you can use to create new Web sites. Atlas is designed to be cross-browser. This first technology preview adds Ajax support to IE, FireFox and Safari browser clients. Our plan is to test and further expand browser support even more with subse- quent builds. Note that all styling for Atlas-based controls are done purely through CSS. Retrieving Data from a Web Service Using Atlas Now that you have had an understanding of the features of Atlas, it is time to look at an example. The code example shown in Listing 9-19 demonstrates the code of the Web service that simply returns the employee details as an array of Employee objects. Note that the Web service is just a standard .asmx file and does not contain any Atlas specific code. Listing 9-19: Data Service that returns Employee Details <%@ WebService Language=”C#” Class=”EmployeeService” %> using System; using System.Collections; using System.Collections.Generic; using System.Web.Services; public class EmployeeService : System.Web.Services.WebService { [WebMethod] Key Features of Atlas Through a set of common UI building blocks, Atlas enables increased productivity by reducing the number of lines of code you need to write Atlas allows you to create code that is easier to author, debug, and maintain by pro- viding a clean separation of content, style, behavior, and code Atlas is well integrated with design and development tools Atlas works with ASP.NET pages and server controls thereby providing access to ASP.NET hosted Web services and components Atlas works everywhere providing a cross-browser standards-based implementation 281 XML Data Display 12_596772 ch09.qxd 12/13/05 11:15 PM Page 281 public Employee[] GetAddresses() { List<Employee> data = new List<Employee>(); data.Add(new Employee(0, “Thiru”)); data.Add(new Employee(1, “Thamiya”)); data.Add(new Employee(2, “Prabhu”)); return data.ToArray(); } } The Employee declaration is very simple and it just contains two properties: ID and Name. Listing 9-20 shows the implementation of the Employee class. Listing 9-20: Declaration of Employee Class using System; public class Employee { int _id; string _name; public Employee(){} public Employee(int id, string name) { _id = id; _name = name; } public int ID { set{_id = value;} get{return _id; } } public string Name { set{name = value; } get{return _name;} } } Now that the Web service is implemented, the next step is to invoke the Web service from an Atlas enabled Web page. Listing 9-21 shows the complete code of the Web page. Listing 9-21: Using Atlas to Invoke a Remote Web Service <%@ Page Language=”C#” %> <html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”> <head> <title>Address Viewer</title> <atlas:ScriptManager ID=”ScriptManager1” runat=”server” /> <script src=”EmployeeService.asmx/js” type=”text/javascript”></script> <script language=”javascript” type=”text/javascript”> 282 Chapter 9 12_596772 ch09.qxd 12/13/05 11:15 PM Page 282 function btnAddress_onclick() { EmployeeService.GetAddresses(onSearchComplete); } function onSearchComplete(results) { var searchResults = document.getElementById(“searchResults”); searchResults.control.set_data(results); } </script> </head> <body> <form id=”form1” runat=”server”> <div id=”header”>Get Addresses: <input id=”btnAddress” type=”button” value=”Get” onclick=”btnAddress_onclick();” /> </div> <div id=”content”> <div class=”left”> <atlas:ListView id=”searchResults” runat=”server” ItemTemplateControlID=”row”> <LayoutTemplate> <ul id=”Ul1” runat=”server”> <li id=”row” runat=”server”> <atlas:Label id=”id” runat=”server”> <Bindings> <atlas:Binding DataPath=”ID” Property=”text” /> </Bindings> </atlas:Label> <atlas:Label ID=”name” runat=”server”> <Bindings> <atlas:Binding DataPath=”Name” Property=”text” /> </Bindings> </atlas:Label> </li> </ul> </LayoutTemplate> </atlas:ListView> </div> </div> </form> </body> </html> There are two important declarations in the above page: One is the reference to the Atlas script manager and the second one points to the EmployeeService.asmx with the /js flag specified at the end. <atlas:ScriptManager ID=”ScriptManager1” runat=”server” /> <script src=”EmployeeService.asmx/js” type=”text/javascript”></script> 283 XML Data Display 12_596772 ch09.qxd 12/13/05 11:15 PM Page 283 [...]... calling the EndExecuteXmlReader() method passing in the IAsyncResult object as an argument XmlReader reader = command.EndExecuteXmlReader(asyncResult); 2 96 SQL Server 2005 XML Integration Next you load the returned XmlReader into an XmlDocument object and display the output XmlDocument doc = new XmlDocument(); //Load the XmlReader to an XmlDocument object doc.Load(reader); output.Text = XML : “ + Server.HtmlEncode(doc.OuterXml);... DatabaseLogID, XmlEvent FROM “ + “ DatabaseLog WHERE DatabaseLogID = “ + ID.ToString() + “ FOR XML AUTO, ROOT(‘DatabaseLogs’), ELEMENTS”; XmlReader reader = command.ExecuteXmlReader(); XmlDocument doc = new XmlDocument(); //Load the XmlReader to an XmlDocument object doc.Load(reader); builder.Append(“Complete XML :” + Server.HtmlEncode(doc.OuterXml) + “”); //Retrieve the DatabaseLogID and XmlEvent... statement creates a primary XML index called idx _xml_ data on the XML column xml_ data of the table Employee: CREATE PRIMARY XML INDEX idx _xml_ data on Employee (xml_ data) Secondary XML Indexes After the primary XML index has been created, you may want to create secondary XML indexes to speed up different classes of queries within your workload There are three types of secondary XML indexes named PATH, PROPERTY,... also create a table with more than one XML or relational columns with or without a primary key Typed XML Columns If you have XML schemas in an XML schema collection describing your XML data, you can associate the XML schema collection with the XML column to yield typed XML The XML schemas are used to validate the data, perform more precise type checks than untyped XML during compilation of query and data... XML TYPE is assigned to an XML data type variable @var Then the variable is used in the insert statement DECLARE @var xml SET @var = (SELECT xml_ data FROM Employee FOR XML AUTO,TYPE) Insert the value of the variable into a new table named EmployeeOutput CREATE TABLE EmployeeOutput (xml_ data xml) INSERT INTO EmployeeOutput (xml_ data) VALUES (@var) 301 Chapter 10 XML Data Type Methods Although the XML. .. DatabaseLogID, XmlEvent FROM “ + “ DatabaseLog WHERE DatabaseLogID = “ + ID.ToString() + “ FOR XML AUTO, ROOT(‘DatabaseLogs’), ELEMENTS”; Now you execute the actual query by calling the ExecuteXmlReader() method on the SqlCommand object XmlReader reader = command.ExecuteXmlReader(); You then load the XmlReader object onto an XmlDocument for further processing XmlDocument doc = new XmlDocument(); //Load the XmlReader... processing XML Schema Collections Support for typed XML columns is enabled by using XML schema collections in SQL Server XML schema collections are defined like any other SQL Server object, and they are stored in SQL Server An XML schema collection is created using CREATE XML SCHEMA COLLECTION T-SQL statement by providing one or more XML schemas More XML schema components can be added to an existing XML schema,... ‘C:\Data\Employee .xml , SINGLE_BLOB) AS xml_ value) AS R (xml_ value) The third option is to utilize the output of the FOR XML with the TYPE directive as an input to the insert command With SQL Server 2005 FOR XML has been enhanced with a TYPE directive to generate the result as an XML data type instance The resulting XML can be assigned to an XML column, variable, or parameter In the following statement, the XML instance... return assignable values, the result of a FOR XML query can be assigned to an XML variable, or inserted into an XML column /* Assign the output of FOR XML to a variable */ DECLARE @Employee XML; SET @Employee = (SELECT * FROM HumanResources.Employee FOR XML AUTO, TYPE) CREATE TABLE Employee_New (EmployeeID int, XmlData XML) /* Assign the output of FOR XML to a column*/ INSERT INTO Employee_New SELECT... DatabaseLogID, XmlEvent “ + “FROM DatabaseLog WHERE DatabaseLogID = “ + ID.ToString() + “ FOR XML AUTO, ROOT(‘DatabaseLogs’), ELEMENTS”; IAsyncResult asyncResult = command.BeginExecuteXmlReader(); //Do some other processing here asyncResult.AsyncWaitHandle.WaitOne(); 295 Chapter 10 XmlReader reader = command.EndExecuteXmlReader(asyncResult); XmlDocument doc = new XmlDocument(); //Load the XmlReader to an XmlDocument . rich Web applications 28 5 XML Data Display 12_ 5 967 72 ch09.qxd 12/ 13 /05 11:15 PM Page 28 5 12_ 5 967 72 ch09.qxd 12/ 13 /05 11:15 PM Page 28 6 SQL Server 20 05 XML Integration XML has become the standard. XML Features in SQL Server 20 05 ❑ XQuery and the support provided by SQL Server 20 05 ❑ FOR XML clause and the new features ❑ How to execute FOR XML queries from ADO .NET 13_5 967 72 ch 10. qxd 12/ 13 /05 . Server 20 05 New XML Features in SQL Server 20 05 SQL Server 20 00 enables you to store XML on the server by storing the XML text in a BLOB field, so you can’t work with or reference the XML on

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

TỪ KHÓA LIÊN QUAN