XML WebService Full Instance detailed parsing

Source: Internet
Author: User
Tags format execution functions interface query reference tostring wsdl
Web|xml

First of all, we must understand what is webservice. Conceptually, it may be more complicated, but we can have a macroscopic understanding: WebService is an external interface with functions that can be invoked by external clients (note: There are also functions that are not callable by the customer). If we are the service side, we wrote a webservice and gave it to the customer (and we gave them the call rules), and the customer was in a relatively transparent state when getting information from the server. That is, the customer does not understand (and does not need) its process, they only get data.

The data passed by WebService can only be serialized data, typically XML data, where we discuss only the transfer of XML data.

With some initial understanding of XML webservice, we will cut to the point, that is, to use a specific WebService case to explain the specific webservice usage, with concrete examples to explain a concept I think how it is more than simple reasoning can make people easy to understand it.

Here, we will take a simple distributed courseware search system as an example to explain. Use VS2003 for the compilation environment, C # for the language, and SqlServcer2000 for the database. (This example is inspired by an article from an online friend who thinks it can represent the characteristics of webservice, and that's what the idea is.)

First, make clear what we are going to do. We need a customer interface, that is, a site, we call it servicegathersite, what form it does not matter, even it does not need a database itself, it is only to provide users with a query interface, the real service, Ordinary users are not exposed to. Then, here we need several services to provide the site, we can call them the resource station, for simplicity, suppose there are two resource stations, called WEBSITEA,WEBSITEB, they can be not published, but only to enrich the query data exist. And finally is something that we need to focus on---resource station to servicegathersite. Two resource stations, there are two services, we call Siteaservice and Sitebservice. Two services have no relationship, and the internal methods are completely unrelated. , just need to tell servicegathersite how the method is used, meaning that the service only provides a query interface, how the returned data is processed, and whether the service itself is allocated by the site that uses the service.

Having written so much, it is a brief introduction to the concept of XML webservice and the structure of our example, the next article, we will begin to truly enter the design phase of the code.

The previous article introduces some of the basic features of webservice and the structure of our example, and this article will start with the specific code writing work.

This topic is mainly about WebService, so here our code is mainly related to webservice, and other works, such as: Servicegathersite,websitea, will be briefly introduced.

In VS2003, developing a webservice is not difficult, first, we create a new WebService project (file-> new-> Project->c#->web Service Application)

To finish this project, we will see a file called Service1.asmx, which is the standard file for WebService, it also has the concept of UI, but we are generally not concerned, so we look at its CS code file. If you haven't done anything yet, You will see an annotated HelloWorld of WebMethod, remove the annotation, and in the running, you can get the simplest WebService run instance. Click "HelloWorld" to execute its method. Obviously, What this function means to us is only a macroscopic understanding of the way the Web service is written.

Next, we will begin to introduce the writing of WebService. In the code file, if we write a function and want this function to be an externally callable interface function, we have to add a line of code to the function [WebMethod (description=) Description of the function. )], if your function does not have this declaration, it will not be referenced by the user. such as:

[WebMethod (description= "easiest way")]
public string HelloWorld ()
{
Return to "Hello World";
}
This function is an externally callable interface function that is equivalent to an API for the user. If a user invokes the HelloWorld () method after quoting the service, he will get the return value of "HelloWorld".
See here, we are not found that, in fact, WebService is not so mysterious, it is only an interface, for us, the focus is still the writing of interface functions. Below, I will give the interface function we need for our example.
[WebMethod (description= "query to get the courseware information needed")]
Public XmlDataDocument Getsiteadata (string assignname)
{
XmlDataDocument xd=new XmlDataDocument (); //
DataSet ds=new DataSet ();
Cstoreproc cp=new Cstoreproc ("searchassign");
Cp. Addparin ("@keywords", sqldbtype.varchar,30,assignname);
Cp. Addparout ("@res", SqlDbType.Int);
if (CP. Selectproc ())///If executed successfully, stored procedure
{
Cp.mydata.enforceconstraints=false; Do not check for strict formatting
if ((int) CP. Getreturnvalue ("@res") ==-1)
{
String Xml= "";
Xd. Loadxml (XML);
return XD;
}
Xd=new XmlDataDocument (Cp.mydata);
XmlNode Root1=xd. DocumentElement;
XmlNodeList roots=root1. selectnodes ("list");
foreach (XmlNode roota in Roots)//Add site name tag to all elements
{
XmlElement link=xd. CreateElement ("SiteName");
link.innertext=configurationsettings.appsettings["SiteName"]. ToString ();
Roota. AppendChild (Link);
}
return XD;
}
else return null;
}

This is an interface function to get information about the resource site. Most of the code inside, I think for a certain asp.net base of friends, should be a look at the understanding, here only to explain the next cstoreproc, this is my encapsulated a stored procedure class, the main function is to perform various types of stored procedures.

A careful friend may find that the return type of this function appears to be more specific and is an XML document. As we have said before, WebService can only transmit serialized data, XML clearly satisfies the conditions, but not serialized data like hash tables is not transmitted, XML is most widely used, And considering Cross-platform applications, here we only sample the transfer of XML data.

Next to the article, let's briefly explain the Getsiteadata (string assignname) function.

function is simple, but to return the query results, the data format is XmlDataDocument. When the query fails (no matching query results), we construct an XML that returns an empty record. Otherwise, we will generate a XmlDataDocument after the query dataset , and then, because of the project's need, I added a loop to add the nodes that are not in the dataset, the name of the site. After that, we have completed an XML data document that conforms to our desired format and we return it.

OK, so here's the WebService method function (here's a Web service method, later), and then our task is how to call it. First compile the WebService project, assuming that our service is for resource site A, We may as well call it servicea. Run the asmx file separately, execute the Getsiteadata (string assignname) method, and you will be prompted to enter the parameters, you enter the content to search for, point to confirm, will return you an XML data, and on IE display, That's what you're searching for, pull.

Here on the work of ServiceA, in our project, it is a resource site a provides services, meaning that it queries the data will be all from site A, and site a resources added in this project also has a special project to achieve.

Okay, let's get back to business. Here I introduce vs call WebService method, in fact, other platform invocation method is very similar. First we introduce the Web reference method, which I strongly recommend to use when debugging, very convenient. Right-click the reference, point to add a Web reference, Enter your webservice address, such as: http://localhost/aspxproject/webservicesolution/sitebservice/service1.asmx, you must Make sure that the WebService you enter is present. Then reference can be made, note: The Web reference name is used as the namespace of the webservice you join. For example, you enter: SiteA, the instantiation of the service will be like this: Sitea.service1 servicea=new Sitea.service1 ();(Service1 is the class name of the service).

Having done this, the call to the service seems to have become so simple that we have implemented a remote instantiation, and the next remote call is just as easy. The following is the binding code of the Resource Collection station Servicegathersite (only collect information of site a)

Binding Data
public void Binddata ()
{
Servicea=new Sitea.service1 ();
DataSet ds=new DataSet ();
XmlNode XmlNode1;
XmlDataDocument xd=new XmlDataDocument ();
StringBuilder xmlString1;
Xmlnode1=servicea.getsiteadata (Strsearch);
if (xmlnode1==null)//--stored procedure execution failed
Return
Xmlstring1=new StringBuilder (Xmlnode1.outerxml);
if (xmlstring1.tostring (). Equals (""))
return;
Xd. Loadxml (Xmlstring1.tostring ());
Ds. READXML (New XmlNodeReader (XD));
Datagrid1.datasource=ds. tables["List"]. DefaultView;
Datagrid1.databind ();
}

This code gives the solution of XML conversion to DataSet, although this is not necessary, but after all, in the ASP.net, the dataset occupies a heavy role, everyone knows. Other friends please see first (hehe, the master on the exemption), In the next article there will be some explanations for it and solutions for multiple service distribution calls, wrote three, found that there seems to be some friends to see, then I will shortcoming continue to write down well, we have any comments also want to put forward, under the understanding of the existence of bias is also inevitable, hope understanding:

Next to the article, let's briefly explain the following binding function. First instantiate the ServiceA, which is not different from the instantiation of the general class. The next step is to use XmlNode1 to accept the return value of the function, and then to construct the XML and convert it into a dataset, which is a common method, and it's best to write down this method if it's a friend you just contacted.

Next, give the code that calls two services asynchronously

Binding Data
public void Binddata ()
{
IAsyncResult ar1;
IAsyncResult ar2;
Servicea=new Sitea.service1 ();
Serviceb=new Siteb.service1 ();
DataSet ds=new DataSet ();
XmlNode Xmlnode1,xmlnode2;
XmlDataDocument xd=new XmlDataDocument ();
StringBuilder xmlstring1,xmlstring2;
--Simple asynchronous invocation
Ar1=servicea.begingetsiteadata (Strsearch,null,null);
Ar2=serviceb.begingetsiteadata (Strsearch,null,null);
Xmlnode1=servicea.endgetsiteadata (AR1);
Xmlnode2=serviceb.endgetsiteadata (AR2);
//----------
if (xmlnode1==null&&xmlnode2==null)//--stored procedure execution failed
Return
Xmlstring1=new StringBuilder (Xmlnode1.outerxml);
Xmlstring2=new StringBuilder (Xmlnode2.outerxml);
Xmlstring1=makenewxmlstring (XMLSTRING1,XMLSTRING2); Generate a new XML
if (xmlstring1.tostring (). Equals (""))
return;
Xd. Loadxml (Xmlstring1.tostring ());
Ds. READXML (New XmlNodeReader (XD));
Datagrid1.datasource=ds. tables["List"]. DefaultView;
Datagrid1.databind ();
}
Generate new XML
Public StringBuilder makenewxmlstring (StringBuilder str1,stringbuilder str2)
{
Str1=str1. Replace ("", "");
Str2=str2. Replace ("", "");
Str1. Append (str2. ToString ());
return str1;
}

There are two places to be aware of, one is XML construction, and the implementation of asynchronous invocation, please readers, understand

The following is a way to refer to WebService through a DLL, and I'll just introduce the process.

First, in IE enter the address of the service, such as: Http://www.xxx.com/service.asmx

Then write the input http://www.xxx.com/service.asmx?wsdl

When opened, Save as xxx.wsdl

Then compile with the VS command prompt: Wsdl/namespace:sitea servicea.wsdl

Generate proxy classes with namespaces as SiteA

Finally Csc/out:servicea.dll/t:library Service1.cs, where Service1.cs is the proxy class file

The last reference DLL is OK.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.