mcts 70-562 Microsoft .NET Framework 3.5, ASP.NET Application Development phần 6 pot

108 234 0
mcts 70-562 Microsoft .NET Framework 3.5, ASP.NET Application Development phần 6 pot

Đ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

System.Text.Encoding.UTF8) With xmlWriter Formatting = Formatting.Indented Indentation = WriteStartDocument() WriteComment("XmlTextWriter Test Date: " & _ DateTime.Now.ToShortDateString()) WriteStartElement("EmployeeList") 'New Employee WriteStartElement("Employee") WriteAttributeString("EmpID", "1") WriteAttributeString("LastName", "JoeLast") WriteAttributeString("FirstName", "Joe") WriteAttributeString("Salary", XmlConvert.ToString(50000)) WriteElementString("HireDate", _ XmlConvert.ToString(#1/1/2003#, _ XmlDateTimeSerializationMode.Unspecified)) WriteStartElement("Address") WriteElementString("Street1", "123 MyStreet") WriteElementString("Street2", "") WriteElementString("City", "MyCity") WriteElementString("State", "OH") WriteElementString("ZipCode", "12345") 'Address WriteEndElement() 'Employee WriteEndElement() 'New Employee WriteStartElement("Employee") WriteAttributeString("EmpID", "2") WriteAttributeString("LastName", "MaryLast") WriteAttributeString("FirstName", "Mary") WriteAttributeString("Salary", XmlConvert.ToString(40000)) WriteElementString("HireDate", _ XmlConvert.ToString(#1/2/2003#, _ XmlDateTimeSerializationMode.Unspecified)) Lesson 3: Working with XML Data CHAPTER 511 .WriteStartElement("Address") WriteElementString("Street1", "234 MyStreet") WriteElementString("Street2", "") WriteElementString("City", "MyCity") WriteElementString("State", "OH") WriteElementString("ZipCode", "23456") 'Address WriteEndElement() 'Employee WriteEndElement() 'EmployeeList WriteEndElement() Close() End With Response.Redirect("EmployeeList.xml") End Sub //C# protected void Button10_Click(object sender, EventArgs e) { XmlTextWriter xmlWriter = new XmlTextWriter(MapPath("EmployeeList.xml"), System.Text.Encoding.UTF8); xmlWriter.Formatting = Formatting.Indented; xmlWriter.Indentation = 5; xmlWriter.WriteStartDocument(); xmlWriter.WriteComment("XmlTextWriter Test Date: " + DateTime.Now.ToShortDateString()); xmlWriter.WriteStartElement("EmployeeList"); //New Employee xmlWriter.WriteStartElement("Employee"); xmlWriter.WriteAttributeString("EmpID", "1"); xmlWriter.WriteAttributeString("LastName", "JoeLast"); xmlWriter.WriteAttributeString("FirstName", "Joe"); xmlWriter.WriteAttributeString("Salary", XmlConvert.ToString(50000)); xmlWriter.WriteElementString("HireDate", XmlConvert.ToString(DateTime.Parse("1/1/2003"), XmlDateTimeSerializationMode.Unspecified)); 12 CHAPTER Using ADO.NET, XML, and LINQ with ASP.NET xmlWriter.WriteStartElement("Address"); xmlWriter.WriteElementString("Street1", "123 MyStreet"); xmlWriter.WriteElementString("Street2", ""); xmlWriter.WriteElementString("City", "MyCity"); xmlWriter.WriteElementString("State", "OH"); xmlWriter.WriteElementString("ZipCode", "12345"); //Address xmlWriter.WriteEndElement(); //Employee xmlWriter.WriteEndElement(); //New Employee xmlWriter.WriteStartElement("Employee"); xmlWriter.WriteAttributeString("EmpID", "2"); xmlWriter.WriteAttributeString("LastName", "MaryLast"); xmlWriter.WriteAttributeString("FirstName", "Mary"); xmlWriter.WriteAttributeString("Salary", XmlConvert.ToString(40000)); xmlWriter.WriteElementString("HireDate", XmlConvert.ToString(DateTime.Parse("1/2/2003"), XmlDateTimeSerializationMode.Unspecified)); xmlWriter.WriteStartElement("Address"); xmlWriter.WriteElementString("Street1", "234 MyStreet"); xmlWriter.WriteElementString("Street2", ""); xmlWriter.WriteElementString("City", "MyCity"); xmlWriter.WriteElementString("State", "OH"); xmlWriter.WriteElementString("ZipCode", "23456"); //Address xmlWriter.WriteEndElement(); //Employee xmlWriter.WriteEndElement(); //EmployeeList xmlWriter.WriteEndElement(); xmlWriter.Close(); Response.Redirect("EmployeeList.xml"); } This code starts by opening the file as part of the constructor for the XmlTextWriter The constructor also expects an encoding type Because an argument is required, passing Nothing causes the encoding type to be UTF-8, which is the same as the value that is explicitly being passed The following is the EmployeeList.xml file that is created: Lesson 3: Working with XML Data CHAPTER 513 2003-01-01T00:00:00 123 MyStreet MyCity OH 12345 2003-01-02T00:00:00 234 MyStreet MyCity OH 23456 There are many statements that are doing nothing more than writing to the xmlWriter Typing time is saved in the Visual Basic code by the use of the With xmlWriter statement, which allows a simple dot to be typed to represent the xmlWriter object The XmlTextWriter handles the formatting of the document by setting the Formatting and Indentation properties The WriteStartDocument method writes the XML declaration to the file The WriteComment method writes a comment to the file When writing elements, you can use either the WriteStartElement method or the Write­ ElementString method The WriteStartElement method only writes the starting element but keeps track of the nesting level and adds new elements inside this element The element is completed when a call is made to the WriteEndElement method The WriteElementString method simply writes a closed element to the file The WriteAttribute method takes a name and value pair and writes the attribute into the current open element When writing is complete, the Close method must be called to avoid losing data The file is then saved 14 CHAPTER Using ADO.NET, XML, and LINQ with ASP.NET Reading a File Using the XmlTextReader The XmlTextReader is used to read an XML file node by node The reader provides forwardonly, noncaching access to an XML data stream The reader is ideal for use when there is a possibility that the information that is desired is near the top of the XML file and the file is large If random access is required, use the XPathNavigator class or the XmlDocument class The following code reads the XML file that was created in the previous example and displays information about each node: 'VB Protected Sub Button11_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Button11.Click lbl = GetLabel(275, 20) Dim xmlReader As New _ XmlTextReader(MapPath("EmployeeList.xml")) Do While xmlReader.Read() Select Case xmlReader.NodeType Case XmlNodeType.XmlDeclaration, _ XmlNodeType.Element, _ XmlNodeType.Comment Dim s As String s = String.Format("{0}: {1} = {2}", _ xmlReader.NodeType, _ xmlReader.Name, _ xmlReader.Value) lbl.Text += s Case XmlNodeType.Text Dim s As String s = String.Format(" - Value: {0}", _ xmlReader.Value) lbl.Text += s End Select If xmlReader.HasAttributes Then Do While xmlReader.MoveToNextAttribute() Dim s As String s = String.Format(" - Attribute: {0} = {1}", _ xmlReader.Name, xmlReader.Value) lbl.Text += s Loop End If Loop xmlReader.Close() End Sub Lesson 3: Working with XML Data CHAPTER 515 This code opens the EmployeeList file, and then performs a simple loop, reading one element at a time until finished For each node that is read, a check is made on the NodeType, and the node information is printed When a node is read, its corresponding attributes are read as well A check is made to see if the node has attributes, and they are displayed Modifying an XML Document Once the XmlDocument object is loaded, you can easily add and remove nodes When removing a node, you simply need to locate the node and delete it from its parent When adding a node, you need to create the node, search for the appropriate location into which to insert the node, and insert the node The following code deletes an existing node and adds a new node: 'VB Protected Sub Button12_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Button12.Click lbl = GetLabel(275, 20) 'Declare and load new XmlDocument Dim xmlDoc As New XmlDocument() xmlDoc.Load(MapPath("XmlSample.xml")) 'delete a node Dim node As XmlNode node = xmlDoc.SelectSingleNode("//myChild[@ChildID='ref-3']") node.ParentNode.RemoveChild(node) 'create a node and add it Dim newElement as XmlElement = _ xmlDoc.CreateElement("myNewElement") node = xmlDoc.SelectSingleNode("//myChild[@ChildID='ref-1']") node.ParentNode.InsertAfter(newElement, node) xmlDoc.Save(MapPath("XmlSampleModified.xml")) Response.Redirect("XmlSampleModified.xml") End Sub //C# protected void Button12_Click(object sender, EventArgs e) { lbl = GetLabel(275, 20); //Declare and load new XmlDocument XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(MapPath("XmlSample.xml")); Lesson 3: Working with XML Data CHAPTER 517 //delete a node XmlNode node; node = xmlDoc.SelectSingleNode("//myChild[@ChildID='ref-3']"); node.ParentNode.RemoveChild(node); //create a node and add it XmlElement newElement = xmlDoc.CreateElement("myNewElement"); node = xmlDoc.SelectSingleNode("//myChild[@ChildID='ref-1']"); node.ParentNode.InsertAfter(newElement, node); xmlDoc.Save(MapPath("XmlSampleModified.xml")); Response.Redirect("XmlSampleModified.xml"); } To delete a node, use the SelectSingleNode method to locate the node to delete After the node is located, the node can be removed from its parent by using the ParentNode property’s RemoveChild method To add a node, execute the CreateElement method on the XmlDocument object Next, the insert location is searched and the ParentNode property’s InsertAfter method is used to insert the new node Validating XML Documents An important element to exchanging documents between disparate systems is the ability to define the structure of an XML document and then validate the XML document against its defined structure The NET Framework offers the ability to perform validation against a DTD or schema Earlier versions of the NET Framework used the XmlValidatingReader object to perform validation, but this object is now obsolete Instead, this section explores XML document validation using the XmlReader class The XmlReader class performs forward-only reading and validation of a stream of XML The XmlReader class contains a Create method that can be passed as a string or a stream, as well as an XmlReaderSettings object To perform validation, the XmlReaderSettings object must be created and its properties set to perform validation In the next example, the files XmlSample.xml and XmlBadSample.xml are validated using the following code: 'VB Protected Sub Button13_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Button13.Click lbl = GetLabel(275, 20) If ValidateDocument(MapPath("XmlSample.xml")) Then lbl.Text += "Valid Document" Else lbl.Text += "Invalid Document" End If End Sub 18 CHAPTER Using ADO.NET, XML, and LINQ with ASP.NET Protected Sub Button14_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Button14.Click lbl = GetLabel(275, 20) If ValidateDocument(MapPath("XmlBadSample.xml")) Then lbl.Text += "Valid Document" Else lbl.Text += "Invalid Document" End If End Sub Public Function ValidateDocument(ByVal fileName As String) _ As Boolean Dim xmlSet As New XmlReaderSettings() xmlSet.ValidationType = ValidationType.DTD xmlSet.ProhibitDtd = False Dim vr As XmlReader = XmlReader.Create( _ fileName, xmlSet) Dim xd As New XmlDocument() Try xd.Load(vr) Return True Catch ex As Exception lbl.Text += ex.Message + "" Return False Finally vr.Close() End Try End Function //C# protected void Button13_Click(object sender, EventArgs e) { lbl = GetLabel(275, 20); if (ValidateDocument(MapPath("XmlSample.xml"))) { lbl.Text += "Valid Document"; } else { lbl.Text += "Invalid Document"; } } protected void Button14_Click(object sender, EventArgs e) { Lesson 3: Working with XML Data CHAPTER 519 lbl = GetLabel(275, 20); if (ValidateDocument(MapPath("XmlBadSample.xml"))) { lbl.Text += "Valid Document"; } else { lbl.Text += "Invalid Document"; } } private bool ValidateDocument(string fileName) { XmlReaderSettings xmlSet = new XmlReaderSettings(); xmlSet.ValidationType = ValidationType.DTD; xmlSet.ProhibitDtd = false; XmlReader vr = XmlReader.Create(fileName, xmlSet); XmlDocument xd = new XmlDocument(); try { xd.Load(vr); return true; } catch (Exception ex) { lbl.Text += ex.Message + ""; return false; } finally { vr.Close(); } } The XmlBadSample.xml file is as follows: XML File: XmlBadSample.xml ]> 20 CHAPTER Using ADO.NET, XML, and LINQ with ASP.NET Create a Master-Detail Solution Using the Data-Bound Server Controls For this task, you should complete Practice practice Create a new Web site that uses a domain familiar to you, such as customers and orders, owners and vehicles, employees and sick days, or albums and songs Add a Web page that is configurable as a master-detail page to provide access to related data n take a practice test The practice tests on this book’s companion CD offer many options For example, you can test yourself on just the content covered in this chapter, or you can test yourself on all the 70-562 certification exam content You can set up the test so it closely simulates the experience of taking a certification exam, or you can set it up in study mode so you can look at the correct answers and explanations after you answer each question MORE INFO practice tests For details about all the practice test options available, see the “How to Use the Practice Tests” section in this book’s Introduction 604 CHAPTER Working with Data Source and Data-Bound Controls CHAPTER Writing and Working with Services D evelopers are using services to make better use of legacy code across applications Web services enable system integration, business process workflow across boundaries, business logic reuse, and more There are two primary ways to create services in ASP.NET You can create Web services based on the ASP.NET (.asmx) model This is a familiar ASP.NET programming experience for services that are meant to be exclusively bound to Hypertext Transfer Protocol (HTTP) and hosted by Microsoft Internet Information Services (IIS) and ASP.NET You can also use Microsoft Windows Communication Foundation (WCF) to create Web services This model allows developers to write services that can be configured to work with a variety of hosts, protocols, and clients Of course, this includes hosting in IIS and communicating through HTTP This chapter first covers the ASP.NET Extensible Markup Language (XML) Web service model This includes building, hosting, and consuming Web services with Microsoft Visual Studio and ASP.NET The first lesson in the chapter introduces ASP.NET developers to working with WCF-based services This second lesson covers creating WCF services to be hosted inside IIS and ASP.NET It also walks through calling WCF services from an ASP.NET Web page Exam objectives in this chapter: n Working with Data and Services n n Call a Windows Communication Foundation (WCF) service or a Web service from an ASP.NET Web page Working with ASP.NET AJAX and Client-Side Scripting n Consume services from client scripts Lessons in this chapter: n Creating and Consuming XML Web Services  607 n Creating and Consuming WCF Services  628 CHAPTER 605 Before You Begin To complete the lessons in this chapter, you should be familiar with developing applications with Visual Studio using Visual Basic or C# In addition, you should be comfortable with all of the following: n n A basic understanding of Hypertext Markup Language (HTML) and client-side scripting with the JavaScript language n How to create a new Web site n 06 The Visual Studio 2008 Integrated Development Environment (IDE) The basics of the JavaScript programming language and Dynamic HTML (DHTML) CHAPTER Writing and Working with Services Lesson 1: Creating and Consuming XML Web Services Web services have become the common programming model for implementing interoperability between systems that have little or no real connectivity Prior to Web services, connecting applications in meaningful ways was a difficult challenge This challenge was exacerbated by having to cross application domains, servers, networks, data structures, security boundaries, and the like However, with the prominence of the Internet, Web services have become a common model for accessing data, performing distributed transactions, and exposing business process workflow The Internet and its supported standards around HTTP and XML make Web services possible However, having to program directly against HTTP, XML, and Simple Object Access Protocol (SOAP) is a challenging (and time-consuming) proposition Thankfully, ASP.NET provides a model for building and consuming XML Web services With it, you can define a Web service as code (an asmx file and related class) ASP.NET will then wrap this code as a Web service object This object will know how to expose your Web service This includes deserializing SOAP requests, executing your NET Framework code, and serializing your response to be sent back to the requesting client as a SOAP message Additionally, ASP.NET provides a simple client model for consuming Web services A proxy object is generated for you when you reference a Web service You can then program against this proxy object as if you were calling in-process code The proxy object takes care of serialization, SOAP messaging, and the related processes Figure 9-1 provides a high-level overview of the XML Web service model in ASP.NET Network Boundary Web Server (Client Application) Web Browser (user client) Web Server (Web Service) SOAP Request HTTP Request aspx page (and code-behind) Web Service Proxy Object Web Service Web Server Object SOAP Response asmx file (and code-behind) Figure 9-1  The XML Web service model in ASP.NET Lesson 1: Creating and Consuming XML Web Services CHAPTER 607 This lesson starts by covering the basics of an XML Web service This includes defining Web service projects and the Web services themselves You then see how to consume XML Web services with ASP.NET After this lesson, you will be able to: n Understand how ASP.NET uses Internet standards to allow you to build XML Web services n Create XML Web services n Consume XML Web services inside an ASP.NET page n Call an XML Web service from client-side script Estimated lesson time: 45 minutes REAL WORLD Mike Snell I have really seen Web services take off over the last few years This technology had been making big promises, but few were making big bets on it Now, organiza- tions are using Web services to expose and consume all kinds of legacy data that was difficult to get at previously I have seen projects that expose billing data, customer data, reporting information, business workflow, and much more In addition, software vendors have added services as part of their base offering It used to be commonplace to provide an application programming interface (API) with your application Now, this includes a base set of services that the application uses and that you can use to extend the application Some great examples include Microsoft Office SharePoint Server and Microsoft Team Foundation Server Thankfully, Web services is one technology that has really lived up to its original promise Creating an ASP.NET Web Service An ASP.NET XML Web service is a class you write that inherits from the class System.Web Services.WebService This class provides a wrapper for your service code In this way, you are free to write a Web service in pretty much the same way you would write any other class and method The WebService class and ASP.NET take care of the rest Figure 9-2 shows the objects leveraged by most ASP.NET Web services 608 CHAPTER Writing and Working with Services figure 9-2 Classes related to creating ASP.NET Web services Each of these classes controls how your Web service works and how ASP.NET and the compiler view your service code You can inherit from the WebService class to get access to standard ASP.NET features The attribute classes allow you to mark parts of your code as related to XML Web services Items marked for use as Web services are identified by ASP.NET It then knows how to deserialize requests for your service, call your service, and serialize the response It also handles working with SOAP, XML, Web Services Description Language (WSDL), and the related Web service standards You will see how each of these classes is used for creating Web services in the coming sections NOTE Web service design cOnsideratiOns When you write a class that contains a Web service, it is important to remember that this class’s calls will be across a network and across application domains Calls to XML Web service calls are sent as messages through HTTP These messages must be packaged (serialized) and unpackaged (deserialized) for transport in both directions These types of calls, although powerful, can be expensive in terms of processing time Therefore, you want to make the most of these calls For this reason, you should define your methods to a large amount of work and then return processing You not want, on the other hand, Web services that maintain state on the server and require a lot of smaller calls to access and set class data These calls should be saved for working with in-process objects only Lesson 1: Creating and Consuming XML Web Services CHAPTER 609 ASP.NET Web Service Projects Web services in ASP.NET are defined by an asmx file This file can be added directly to an existing Web site This is useful if you intend for your Web site to expose Web services in addition to Web pages Of course, you can also create a simple Web site and use it for only asmx Web service files Another scenario is to create a Web service project through the Add New Project dialog box Here, you select the ASP.NET Web service application This generates a separate project for your Web service application This project has a structure similar to a Web site This includes a folder for App_Data, a Web.config file, and related elements It is important to note that in both scenarios, your Web service is hosted within ASP.NET and therefore has access to its features (session state, security model, configuration, and so on) Like a Web page, Web services are exposed through Uniform Resource Locators (URLs) This means your domain name followed by a page name, as in http://MyDomain/MyService asmx The page for an XML Web service is defined by the asmx file This file is nothing more than a simple text file that is used as a pointer to the code of your Web service You add an asmx file to your site for each Web service you wish to expose In this case, think of a Web service like a class that only exposes methods Therefore, each Web service can expose multiple methods As an example, suppose you wish to write an XML Web service that exposes methods related to working with the author data in Microsoft’s sample database called Pubs You might start by creating an asmx file called Authors.asmx This file would contain an @ WebService directive that points to the actual code for the Web service The following is an example: 'VB //C# This markup is similar to what you would see for a Web page However, there is no additional markup included inside a Web service Instead, the Web service is defined entirely in code The WebServiceAttribute Class Creating an asmx file and exposing public methods marked as WebMethod (see later) is sufficient for defining Web services in ASP.NET However, there are a number of other classes that can be used to provide additional functionality One such class is the WebServiceAttribute class (recall that attribute classes can be used with or without the Attribute suffix) This class can be used to provide information about your Web service This information is used by clients that wish to reference the Web service 10 CHAPTER Writing and Working with Services You can provide both a namespace and a description of your Web service by applying the WebService attribute and parameters to your class The description parameter is simply text you write to identify the high-level intent of your Web service The namespace parameter sets the namespace of your Web service This should be a domain name under your control Visual Studio uses the tempuri.org namespace as filler until you define your actual namespace As an example, imagine again that you are creating a Web service centered on exposing author information You would define your class inside the code-behind file for the asmx file You could then add the WebService attribute to the class, as shown here: 'VB _ Public Class Authors //C# [WebService(Description = "Services related to published authors", Namespace = "http://tempuri.org/")] public class Authors The WebService Class The WebService class represents a base class for creating XML Web services in ASP.NET This class is similar to the Page class for Web pages It provides access to ASP.NET objects like Application and Session It is important to note that this class is optional: You not need to inherit from this class to create XML Web services Instead, you use this class as a base class only when you wish to access and use the features of an ASP.NET application You might, for example, need to leverage session state between service calls You could so easily by first inheriting from this class and then accessing the session object as if you were coding an ASP.NET Web page The following code shows the authors example Web service Here, the Authors class inherits directly from the WebService base class 'VB _ Public Class Authors Inherits System.Web.Services.WebService //C# [WebService(Description = "Services related to published authors", Namespace = "http://tempuri.org/")] public class Authors : System.Web.Services.WebService Lesson 1: Creating and Consuming XML Web Services CHAPTER 611 The WebMethodAttribute Class Your Web service exposes Web methods Each of these methods provides some sort of functionality encapsulated by the Web service Your class can identify these methods through the use of the WebMethod attribute You apply this attribute to any public method in your Web service class you wish to expose as part of your service You can assign the WebMethod attribute to a class without setting any of the parameters of the WebMethod class This simply identifies your method as a Web service method However, the WebMethod attribute class also has a number of constructors used for various groups of parameter values The parameters include the following: n enableSessionState  This parameter is used to indicate whether the given method should be able to work with session state You set this value to false to disable the use of session state for the given Web method n transactionOption  This parameter is used to indicate if your Web method supports transactions The parameter is of the type System.EnterpriseServices.TransactionOption Web services are stateless HTTP calls Therefore, you can only use an XML Web service as the root of a transaction This means the TransactionOptions that indicate a root transaction are equivalent (Required, RequiresNew) All other transaction options indicate no transaction support for the given service (Disabled, NotSupported, Supported) n cacheDuration  This parameter is used to define the number of seconds for which the response should be cached by the server This is useful if your service has a high volume of access and the data is relatively static In this case, you can cache results between calls to increase performance n bufferResponse  This parameter is used to indicate whether the Web service response should be buffered back to the client Consider the author example Imagine you have a public method called GetAuthorTitles that returns a list of titles based on the ID of a given author Because this data only changes when an author publishes a new book, it is also a good candidate for caching The following shows the WebMethod attribute applied to this method Here, the cacheDuration parameter is set to minutes (300 seconds) 'VB _ Public Function GetAuthorTitles(ByVal authorId As String) As DataTable End Function //C# [WebMethod(CacheDuration=300)] public DataTable GetAuthorTitles(string authorId) { } 12 CHAPTER Writing and Working with Services Web Services and Data TYpes Notice that the previous example method, GetAuthorTitles, returns a DataTable object This is possible as the object supports serialization It can serialize itself into XML Provided the calling client is also NET, it can pick this XML up and deserialize it back into a strongly typed DataTable In this case, ASP.NET does this for you without you having to really think about it You might also wish to provide instances of your own classes as return values of your functions or as parameters You can so by creating the object inside the Web service application In this case, the compiler will take care of making the objects you expose serializable These objects simply need a default constructor that does not accept parameters You can also use the Serializable attribute class to tag class outside your Web service This ensures any public members of the class can be serialized by ASP.NET Consuming an ASP.NET Web Service You can consume an ASP.NET Web service in any application capable of making an HTTP call This means most NET application types can call Web services, including console applications, Windows-based applications, and ASP.NET This section focuses on calling an XML Web service from an ASP.NET application Referencing a Web Service To get started, you need to have access to a published Web service This Web service can be published on a server or can be another project in your same solution Either way, as long as it is a valid Web service, you will be able to subscribe to it The first step is setting a Web reference from your Web site to the given service You this by right-clicking your project file and choosing Set Web Reference This opens the Add Web Reference dialog box Here, you define the URL of your service, select the given service (.asmx file), and set a name for the reference This name will be used by the generated proxy class to define the namespace for accessing your service Figure 9-3 shows an example of connecting to the Authors.asmx service Once you have set the reference, Visual Studio and ASP.NET work to generate a Proxy class for working with the service This allows you to write code against the service as if the service was just another class in your application This proxy class does all the work of communicating to and from the Web service, serializing and deserializing data, and more Lesson 1: Creating and Consuming XML Web Services CHAPTER 613 Figure 9-3  The Add Web Reference dialog box As an example, the Authors.asmx file has two Web methods: GetAuthor and GetAuthorTitles The first returns an instance of the Author class as embedded in the service class The second returns a DataTable To work with the Author class (of which the Web application knows nothing), Visual Studio generates this type from the WSDL of the Web service and puts it inside the proxy’s namespace Figure 9-4 shows an example of the contents inside the proxy namespace for the Author.asmx Web service reference Figure 9-4  A Web service proxy for the Authors service 14 CHAPTER Writing and Working with Services NOTE WsdL.eXe Visual Studio includes the command-line tool WSDL.exe You can use this tool to create a proxy class from an existing Web service You specify the language of the proxy class and a URL to the Web service The tool will use this information to generate a proxy class file Calling a Web Service You call the Web service through the proxy This is as simple as writing code to call a method For example, the following code shows how you call the GetAuthor method from the Authors asmx Web service discussed previously: 'VB Dim pubs As New PubsServices.Authors() Dim auth As PubsServices.Author = pubs.GetAuthor("213-46-8915") Label1.Text = auth.FirstName + " " + auth.LastName //C# PubServices.Authors pubs = new PubServices.Authors(); PubServices.Author auth = pubs.GetAuthor(); Label1.Text = auth.FirstName + " " + auth.LastName; Note that in the preceding example code, only the call to GetAuthor actually hits the Web service The object creation and property gets are simply calls to the proxy object and are thus in-process calls You can also bind to the Web service call Remember, the Web service is exposed through a local proxy object Therefore, you can use object data binding to bind to the given Web service (via the proxy) As an example, recall the GetAuthorTitles Web service This service is accessed via a proxy object method of the same name You can set this method as the SelectMethod of an object data source as shown in the following code You can then bind the results to a GridView control SelectMethod="GetAuthorTitles" Lesson 1: Creating and Consuming XML Web Services CHAPTER 615 Public Function GetCelsius(ByVal temperature As Single) As Single Return (5 / 9) * (temperature - 32) End Function End Class //C# [System.Web.Script.Services.ScriptService] [WebService(Namespace = "http://tempuri.org/")] public class TempConversion : System.Web.Services.WebService { [WebMethod] public float GetCelsius(float temperature) { return (5 / 9) * (temperature - 32); } } Next, you need to make sure the HTTP handler ScriptHandlerFactory is registered with your site inside the Web.config file The following shows an example: You now need to create a client Web page Remember, this Web page must be in the same domain as the Web service Inside the Web page markup, you add a ScriptManager control This control should be set to reference the actual Web service (.asmx file) The following shows an example of this markup: The next step would be to add JavaScript functionality to call the Web service, passing the user’s input In addition, you need to write a simple callback function that takes the results and displays them to the user The following code demonstrates this The user input is inside the TextBoxTemp and the results are shown using LabelResults function GetCelsius() { var val = document.getElementById("TextBoxTemp"); Lesson 1: Creating and Consuming XML Web Services CHAPTER 617 TempConversion.GetCelsius(val.value, FinishCallback); } function FinishCallback(result) { var results = document.getElementById("LabelResults"); results.innerHTML = result; } Finally, you need to add the remaining markup to the page This simply consists of the user input information The following shows an example: Enter Fahrenheit Temperature:   Notice that in this markup, the GetCelsius JavaScript method defined earlier is called when the user clicks the Calculate button This triggers the Web service The results are returned to the FinishCallback JavaScript method and then displayed in the Label control Figure 9-5 shows the call in action Figure 9-5  The Web service call from a Web browser 18 CHAPTER Writing and Working with Services ... make up LINQ to XML Table 7 -6 presents the classes shown in Figure 7-19 and provides a description of each 22 CHAPTER Using ADO.NET, XML, and LINQ with ASP.NET Table 7 -6? ?? The LINQ to XML Classes... 534 CHAPTER Using ADO.NET, XML, and LINQ with ASP.NET before you begin To complete the lessons in this chapter, you should be familiar with developing applications with Microsoft Visual Studio... 15 //C# XElement employees = 26 CHAPTER Using ADO.NET, XML, and LINQ with ASP.NET new XElement("Employees", new XElement("Employee", new XElement("id",

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

Từ khóa liên quan

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

  • Đang cập nhật ...

Tài liệu liên quan