Dll to Upload Xml to Web Service

Creating a Web Service

There are 2 different coding techniques with which 1 can construct a web service: inline lawmaking and code-behind.

Web Service with Inline Code

Creating a single-file web service is quite simple. All that's required is to create a new file, add an @ WebService directive and a class containing the implementation for the methods yous want to betrayal, and decorate the methods to exist exposed with the WebMethod attribute. The @ WebService directive supports the following attributes:

Class

Specifies the proper name of the class containing the implementation of the web service. This attribute is necessary to allow the ASP.Net runtime to locate the compiled class at runtime.

CodeBehind

Specifies the proper name of a code-behind file that contains the class that implements the web service. This attribute is used past Visual Studio .NET when edifice the project containing the code-behind class.

Debug

Specifies whether the web service should be compiled with debug symbols.

Language

Specifies the linguistic communication used for lawmaking written inline in the .asmx file.

To demonstrate the cosmos of a web service, look at Example 4-1, which implements a simple "Quote of the 24-hour interval" spider web service.

Case iv-1. Quote of the day application (Qotd.asmx)

<%@ WebService Language="VB" Course="Qotd" %> Imports System Imports System.Data Imports Organization.Spider web Imports Arrangement.Web.Services    Public Form Qotd       <WebMethod(  )> _    Public Role GetQotd(  ) As Cord       Dim QuoteDS As New DataSet(  )       Dim Context As HttpContext = HttpContext.Current(  )       Dim QuoteXML As String = Context.Server.MapPath("qotd.xml")       Dim QuoteCount Equally Integer       Dim QuoteToReturn Every bit Integer       Dim Randomizer As New Random(  )          QuoteDS.ReadXml(QuoteXML)       QuoteCount = QuoteDS.Tables(0).Rows.Count       QuoteToReturn = Randomizer.Side by side(0, QuoteCount)       Return QuoteDS.Tables(0).Rows(QuoteToReturn)(0) & _          "<br /><br />" & QuoteDS.Tables(0).Rows(QuoteToReturn)(1)    Cease Function    End Course

The WebService directive in Example 4-1 specifies Visual Basic .NET as the language used in the web service and specifies that the web service'due south implementation is contained in a form named Qotd. The next iv lines import several namespaces to save the endeavour of typing in the namespace name each time a member is used in the code.

Adjacent comes the class definition for the Qotd form. This class contains a unmarried function, GetQotd , which returns a string containing a quote and the name of its author, separated past ii HTML line breaks. Note that this definition assumes that the consumer of the web service will display the results as HTML. In a later example, we'll provide a more than flexible implementation.

Within the method, you create an ADO.Cyberspace dataset (encounter Affiliate 7 for more data on ADO.Cyberspace) and utilise the ReadXml method of the DataSet class to read in the stored quotes from a simple XML file. The contents of this file are shown in Example 4-2. Once the data is loaded into the dataset, you bank check the Count belongings to determine how many records exist and then employ an instance of the Random class to return a random number from 0 to the tape count. This number is and so used to remember the outset and second values (which also happen to be the but values) of the desired row, equally shown in the post-obit snippet, and return information technology to the caller of the method:

Render QuoteDS.Tables(0).Rows(QuoteToReturn)(0) & _          "<br /><br />" & QuoteDS.Tables(0).Rows(QuoteToReturn)(ane)

Annotation that since collections in .NET are zero-based, Tables(0) refers to the showtime table in the Tables collection of the dataset (in this case, the only table). Y'all tin access the value of a detail field in a particular row in a specific table by using the post-obit syntax:

MyVariable = MyDataset.Tables(              tableindex            ).Rows(              rowindex            )(              fieldindex            )

Example 4-2. Qotd.xml

<Quotes>    <Quote>       <QuoteText>Never give in--never, never, never, never, in nothing great  or small, big or picayune, never give in except to convictions of accolade and  good sense. Never yield to force; never yield to the manifestly overwhelming  might of the enemy.</QuoteText>       <QuoteAuthor>Winston Churchill</QuoteAuthor>    </Quote>    <Quote>       <QuoteText>Nosotros shall fight on the beaches. Nosotros shall fight on the landing  grounds. We shall fight in the fields, and in the streets, nosotros shall fight in  the hills. We shall never give up!</QuoteText>       <QuoteAuthor>Winston Churchill</QuoteAuthor>    </Quote>     <Quote>       <QuoteText>An appeaser is one who feeds a crocodile-hoping it will eat  him concluding.</QuoteText>       <QuoteAuthor>Winston Churchill</QuoteAuthor>    </Quote>     <Quote>       <QuoteText>Nosotros shape our buildings: thereafter they shape us.</QuoteText>       <QuoteAuthor>Winston Churchill</QuoteAuthor>    </Quote>    <Quote>       <QuoteText>Scientific discipline without faith is lame, religion without science  is blind.</QuoteText>       <QuoteAuthor>Albert Einstein</QuoteAuthor>    </Quote>     <Quote>       <QuoteText>Every bit far equally the laws of mathematics refer to reality, they are  non sure, and as far equally they are sure, they do non refer to reality.</QuoteText>       <QuoteAuthor>Albert Einstein</QuoteAuthor>    </Quote>     <Quote>       <QuoteText>If A equals success, then the formula is A equals X plus Y  plus Z. X is work. Y is play. Z is keep your rima oris shut.</QuoteText>       <QuoteAuthor>Albert Einstein</QuoteAuthor>    </Quote>     <Quote>       <QuoteText>When a man sits with a pretty daughter for an hour, information technology seems  similar a infinitesimal. But allow him sit on a hot stove for a infinitesimal-and it'south longer  than any hour. That'south relativity.</QuoteText>       <QuoteAuthor>Albert Einstein</QuoteAuthor>    </Quote>  </Quotes>

Once you've added the code in Case four-1 to a file, saved information technology with the .asmx extension, and created a file called Qotd.xml with the text in Instance four-2 in the aforementioned virtual directory, you tin can open the .asmx file in a browser to test the implementation. The issue should be like to Figure 4-iii.

Browsing a web service

Effigy four-3. Browsing a web service

The principal documentation page displayed in Figure 4-3 is generated automatically by the ASP.NET runtime whenever a web service (.asmx file) is chosen from a browser rather than past a Lather asking. You should note three things virtually the page in Figure 4-iii:

  • The link to the service description. Accessing this link displays the WSDL contract (meet Figure 4-iv), which describes the methods exposed by the web service (in much the aforementioned fashion every bit an IDL file describes a COM object). This contract is also used past .Net clients to generate proxy classes for consuming the web service. This topic is discussed in more particular later in the affiliate.

  • The link that provides access to a documentation page for the GetQotd method, which is shown in Figure iv-5. If the web service exposed multiple methods, the master documentation page would provide a link for each.

  • The main documentation page as well displays a recommendation about the default namespace for the web service. This recommendation refers to the XML namespace, which if not specified, defaults to http://tempuri.org and should not be dislocated with the .NET namespaces. A subsequently example demonstrates how to set the default namespace to a unique URL.

Service description for Qotd.asmx

Effigy 4-four. Service clarification for Qotd.asmx

As shown in Figure iv-5, the documentation page for the GetQotd method provides an Invoke push button that allows you to test the web service method and that provides documentation on creating SOAP, HTTP Go, and HTTP Mail requests for the selected method. In this instance, HTTP Become and Mail are not shown.

GetQotd documentation

Figure 4-5. GetQotd documentation

If you click the Invoke push button, a new browser window should open, displaying XML text similar to the following snippet. (Notation that the quotation and author may vary, since they are selected randomly.)

<?xml version="1.0" encoding="utf-eight" ?>  <string xmlns="http://tempuri.org/">We shape our buildings: thereafter    they shape us.<br><br>Winston Churchill</cord>

Because the GetQotd method returns a string containing HTML formatting (the <br /> tags), it volition automatically brandish the quote and author on separate lines if shown in a browser. But what if a consumer of the web service wants to apply a dissimilar format to the quote than the author?

With this implementation, they're out of luck, unless they are willing to parse out the 2 parts and use the formatting individually that manner. To accost this result, await at a modified version of the Qotd spider web service that uses a lawmaking-behind grade for its implementation.

Web Service Using Code-Behind

The following snippet is all that's required for the .asmx file for our code-behind version of the Qotd web service (Qotd_cb.asmx):

<%@ WebService Language="VB" Grade="aspnetian.Qotd_cb" %>

Note that instead of providing the course name, Qotd_cb, we've as well added a namespace name, "aspnetian," to reduce the likelihood of naming conflicts. Example 4-iii, which contains the lawmaking-backside class that implements the web service, defines this namespace.

Case four-3. Qotd_cb.vb

Imports System Imports System.Data Imports Arrangement.Web Imports Organisation.Web.Services    Namespace aspnetian    <WebService(Namespace:="http://www.aspnetian.com/webservices/")> _ Public Class Qotd_cb    Inherits WebService       <WebMethod(  )> _    Public Function GetQotd(  ) As String       Dim QuoteDS As New DataSet(  )       Dim QuoteXML As String = Server.MapPath("qotd.xml")       Dim QuoteCount As Integer       Dim QuoteNumber Every bit Integer       Dim Randomizer As New Random(  )          QuoteDS.ReadXml(QuoteXML)       QuoteCount = QuoteDS.Tables(0).Rows.Count       QuoteNumber = Randomizer.Next(0, QuoteCount)       Return QuoteDS.Tables(0).Rows(QuoteNumber)(0) & "<br /><br />" _           & QuoteDS.Tables(0).Rows(QuoteNumber)(i)    End Office       <WebMethod(  )> _    Public Function GetQuoteNumber(  ) As Integer       Dim QuoteDS As New DataSet(  )       Dim QuoteXML As Cord = Server.MapPath("qotd.xml")       Dim QuoteCount As Integer       Dim Randomizer Equally New Random(  )          QuoteDS.ReadXml(QuoteXML)       QuoteCount = QuoteDS.Tables(0).Rows.Count       Return Randomizer.Adjacent(0, QuoteCount)    End Function       <WebMethod(  )> _    Public Function GetQuote(QuoteNumber As Integer) As Cord       Dim QuoteDS As New DataSet(  )       Dim QuoteXML Equally Cord = Server.MapPath("qotd.xml")       Dim QuoteCount As Integer       Dim QuoteToReturn Every bit String          QuoteDS.ReadXml(QuoteXML)       QuoteToReturn = QuoteDS.Tables(0).Rows(QuoteNumber)(0)        Render QuoteToReturn    End Function       <WebMethod(  )> _    Public Role GetAuthor(QuoteNumber As Integer) As String       Dim QuoteDS As New DataSet(  )       Dim QuoteXML As Cord = Server.MapPath("qotd.xml")       Dim QuoteCount As Integer       Dim AuthorToReturn Equally String          QuoteDS.ReadXml(QuoteXML)       AuthorToReturn = QuoteDS.Tables(0).Rows(QuoteNumber)(i)        Return AuthorToReturn    End Function    End Form    End Namespace

In addition to wrapping the class declaration in a namespace declaration, this instance adds a new aspect, WebService, and several new methods. The WebService aspect is added at the class level then nosotros tin can specify the default namespace (XML namespace) for the web service. This namespace needs to be a value unique to your web service. In the example, the namespace is http://www.aspnetian.com/webservices/ ; for your ain spider web services, you should use your own unique value. You may want to substitute a URL that you control, as doing so will assure you that web services created past others will not use the same value.

The added methods are GetQuoteNumber, GetQuote, and GetAuthor. These methods demonstrate that fifty-fifty though spider web service requests are sent as XML text, the input and output parameters of web service methods are withal strongly typed. These methods address the potential formatting outcome discussed previously by allowing clients to retrieve a quote and its author separately in society to adapt different formatting for each. To ensure that the matching author for the quote is retrieved, the customer would first call GetQuoteNumber to retrieve a randomly generated quote number, and and then phone call GetQuote and/or GetAuthor, passing in the received quote number. This provides the customer more flexibility, but does not require the web service to go on track of which quote number was sent to a given client.

An important difference between the single-file web service and the lawmaking-behind implementation is that for the code-behind version, you lot must compile the code-behind class into an assembly manually and place it in the bin directory earlier the web service will work. Annotation that this stride is automatic when you build a web service project in Visual Studio .NET. If yous're writing lawmaking by hand, this step tin be accomplished past using a DOS batch file containing the commands shown in the post-obit snippet:

vbc /t:library /r:System.Web.dll /r:Organisation.dll /r:Arrangement.Web.Services.dll  /r:Organisation.Xml.dll /r:Arrangement.Data.dll /out:bin\qotd_cb.dll qotd_cb.vb    break

Notation that all command-line options for the vbc.exe compiler should be role of a single control. The interruption command allows you to see any warnings or errors generated during compilation before the command window is closed.

Inheriting from WebService

In Example iv-1, the Current belongings of the HttpContext class is used to become a reference to the Context object for the electric current request. Getting this reference is necessary to admission to the Server intrinsic object so that we can call its MapPath method to get the local path to the XML file used to store the quotes. However, every bit you add together more methods that use the XML file, yous cease upwardly with redundant calls to HttpContext.Current.

For ameliorate readability and maintainability, yous can eliminate these calls by having the web service class inherit from Organization.Web.Services.WebService. Inheriting from WebService automatically provides access to the Server, Session, and Application intrinsic objects, besides as to the HttpContext case for the current request and the User object representing the authenticated user. In the case of Example 4-3, inheriting from WebService eliminates the calls to HttpContext.Current entirely.

Tip

Web services that inherit from the WebService class take access to the ASP.Cyberspace Session object. Notwithstanding, you should carefully consider whether your application will do good from storing state data in the Session collection before using it -- particularly if your application may demand to calibration to more one web server. ASP.NET at present provides out-of-procedure Session state options that can be used in web farm situations. Unfortunately, because these solutions require, at best, an out-of-procedure telephone call (and at worst, a cross-machine call), using them results in a pregnant functioning penalty. Regardless of your decision, you should ever load-exam your application to ensure that information technology volition meet your performance and scalability needs.

Figure four-6 shows the main documentation page for the lawmaking-behind version of the Qotd web service. Annotation that the main documentation folio contains links for each new method exposed by the web service. Also note that the page no longer displays the namespace warning/recommendation, since we set up the default namespace in this version.

Browsing Qotd_cb.asmx

Figure 4-6. Browsing Qotd_cb.asmx

You've written a web service and you tested it past opening the .asmx file in a browser and invoking the methods. What's next? Unless your web service will exist consumed only by yourself or by someone with whom you have regular communication, you lot demand to publish or advertise your web service in some way. Potential clients also demand to locate your web service to use it.

Publishing a spider web service tin be achieved in either of two ways: through a discovery certificate or by registering the web service with a UDDI directory.

Discovery Documents

A discovery document is a file with the extension .disco that contains references to the WDSL contracts for spider web services you desire to publish, references to documentation for your web services, and/or references to other discovery documents.

Publishing and Locating Web Services

Yous can publish a discovery document on your web server and provide clients with a link to or a URL for the discovery document. Clients can then apply the disco.exe .NET command-line utility to generate WSDL contracts locally for creating proxy classes to communicate with the spider web service. Example 4-four shows the format of a discovery certificate for the Qotd spider web service.

Example 4-4. Qotd.disco

<?xml version="1.0"?> <discovery xmlns="http://schemas.xmlsoap.org/disco/">    <contractRef        ref="http://localhost/aspnetian/Chapter_4/Qotd.asmx?wsdl"        docRef="http://localhost/aspnetian/Chapter_4/Qotd.asmx"        xmlns="http://schemas.xmlsoap.org/disco/scl/" />    <contractRef        ref="http://localhost/aspnetian/Chapter_4/Qotd_cb.asmx?wsdl"        docRef="http://localhost/aspnetian/Chapter_4/Qotd_cb.asmx"        xmlns="http://schemas.xmlsoap.org/disco/scl/" /> </discovery>

One time clients know the location of the discovery file, they tin can use the disco.exe control-line utility to create local WSDL files for all of their web services, as shown in the following lawmaking snippet:

disco http://localhost/aspnetian/Chapter_4/Qotd.disco

This line creates local WSDL files for both the Qotd and Qotd_cb web services.

UDDI

The other method used for publishing and locating web services is UDDI. Withal in the procedure of maturing, UDDI works on the principle of providing multiple replicated directories in which public web services are registered. The UDDI spider web site (http://www.uddi.com) contains a listing of the participating directory sites from which clients or providers of web services can cull. Providers of web services requite relevant information, such equally the blazon of web service, an advisable category (such as Construction or Financial and Insurance.), and most importantly, the URL for the application's WSDL file. Potential clients can search the UDDI directory for web services that match their needs and then locate and consume them via their WSDL contract.

kentwidep1956.blogspot.com

Source: https://www.oreilly.com/library/view/aspnet-in-a/0596001169/ch04s03.html

Related Posts

0 Response to "Dll to Upload Xml to Web Service"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel