Dynamic Call WebService

Source: Internet
Author: User
Tags wsdl

WebService content

Using Microsoft.csharp;
Using System;
Using System.CodeDom;
Using System.CodeDom.Compiler;
Using System.IO;
Using System.Linq;
Using System.Net;
Using System.Reflection;
Using System.Text;
Using System.Web;
Using System.Web.Services.Description;

<summary>
Summary description of Callwebservice
</summary>
public class Callwebservice
{
Public Callwebservice ()
{
//
TODO: Add constructor logic here
//
}
#region Invokewebservice
< summary>
Dynamically invoking Web Services
</summary>
< param name= "url" >wsdl service address (WebService HTTP address) </param>
< param name= "methodname" > method Name of WebService to invoke </param>
< param name= "args" > Parameters </param>
< returns></returns>
<example>
<code>
How to use
String url = "Http://90.10.1.51/Service.asmx";
string[] args = new string[1];
Args[0] = "P000001";
Object result = Callwebservice.invokewebservice (URL, "Pdaservice", null);
</code>
</example>
public static object Invokewebservice (string URL, String methodname, object[] args)
{
Return invokewebservice (URL, null, methodname, args);
}
< summary>
Dynamically invoking Web Services
</summary>
< param name= "url" >wsdl service address (WebService HTTP address) </param>
< param name= "ClassName" > The class name of the WebService to invoke (excluding namespace prefixes) </param>
< param name= "methodname" > method Name of WebService to invoke </param>
< param name= "args" > Parameters </param>
< returns></returns>
public static object Invokewebservice (string url, string classname, String methodname, object[] args)
{
The namespace of the WebService to invoke (not known can be viewed through Class View)
String @namespace = "Pdaweb";
if ((classname = = null) | | (ClassName = = ""))
{
classname = getwsclassname (URL);
}
Try
{
First, download WSDL information using WebClient, Get Service Description Language (WSDL)
Provides a public method for sending data to and receiving data from a resource identified by a URI
WebClient WC = new WebClient ();
Stream stream = WC. OpenRead (URL + "?) WSDL ");
/* The following table describes the WebClient method for downloading data from a resource. Corresponds to the WebClient method that is uploaded to the resource.
* OpenRead Resources return data as Stream, corresponding to Openwrite ()
* OpenReadAsync returns data from a resource without blocking the calling thread
* Downloaddata downloads data from a resource and returns a Byte array.
* DownloadDataAsync downloads data from a resource and returns a Byte array without blocking the calling thread.
* DownloadFile download data from the resource to a local file.
* DownloadFileAsync downloads data from a resource to a local file without blocking the calling thread.
* Downloadstring Downloads A string from the resource and returns a string.
* DownloadStringAsync Download a String from a resource without blocking the calling thread
*/
Create and format a WSDL document.
The ServiceDescription class corresponds to the root element definitions of the WSDL file.
ServiceDescription sd = Servicedescription.read (stream);
Create a client proxy proxy class.
The ServiceDescriptionImporter class makes it easy to import the information contained in the WSDL description into the System.CodeDom.CodeCompileUnit object
ServiceDescriptionImporter SDI = new ServiceDescriptionImporter ();
Sdi. ProtocolName = "Soap"; Specifies the Access protocol.
Sdi. Style = servicedescriptionimportstyle.client; Generates a client agent.
Sdi. CodeGenerationOptions = Codegenerationoptions.generateproperties | Codegenerationoptions.generatenewasync;
Add a WSDL document.
Sdi. Addservicedescription (SD, "", "");
Use the CodeDom to compile the client proxy class.
Adds a namespace to the proxy class, which defaults to global space.
CodeNamespace cn = new CodeNamespace (@namespace);
Second, generate the client proxy class code
The/*codecompileunit contains several collections: you can store
* The collection of CodeNamespace objects for the CodeDOM source code drawing, the collection of assemblies referenced by the project,
* and a collection of properties for the project assembly.
*/
CodeCompileUnit CCU = new CodeCompileUnit ();
Add the new namespace to the compile unit.
Ccu. Namespaces.add (CN);
Imports the specified Servicedescriptions value and generates the code as specified by the Style property.
ADD the new namespace import for the System namespace
Sdi. Import (CN, CCU);
CSharpCodeProvider ICC = new CSharpCodeProvider ();
Third, set the compilation parameters
CompilerParameters cplist = new CompilerParameters ();
Cplist. GenerateExecutable = false;
Cplist. GenerateInMemory = true;
Cplist. Referencedassemblies.add ("System.dll");
Cplist. Referencedassemblies.add ("System.XML.dll");
Cplist. Referencedassemblies.add ("System.Web.Services.dll");
Cplist. Referencedassemblies.add ("System.Data.dll");

CompilerParameters parameter = new CompilerParameters ();
Parameter. GenerateExecutable = false;
Parameter. outputassembly = "Test.dll"; You can specify any file name that you want.
Parameter. Referencedassemblies.add ("System.dll");
Parameter. Referencedassemblies.add ("System.XML.dll");
Parameter. Referencedassemblies.add ("System.Web.Services.dll");
Parameter. Referencedassemblies.add ("System.Data.dll");
Iv. Compiling proxy classes
CompilerResults cr = Icc.compileassemblyfromdom (cplist, CCU);
if (true = = Cr. Errors.haserrors)
{
StringBuilder sb = new StringBuilder ();
foreach (CompilerError ce in CR. Errors)
{
Sb. Append (CE. ToString ());
Sb. Append (Environment.NewLine);
}
throw new Exception (sb.) ToString ());
}
Build the proxy instance and call the method
Assembly Assembly = cr.compiledassembly;
If you have previously added a namespace to the proxy class, you need to add the namespace to the type before it.
Type t = assembly. GetType (@namespace + "." + ClassName, True, true);
Contains a specific method to create an object type locally or remotely, or to obtain a reference to an existing remote object
Object obj = activator.createinstance (t);
Discovers the properties of a method (Attribute) and provides access to the method's metadata.
MethodInfo mi = t.getmethod (methodname);
Return MI. Invoke (obj, args);
/*
PropertyInfo PropertyInfo = type. GetProperty (PropertyName);
return propertyinfo.getvalue (obj, null);
*/
}
catch (Exception ex)
{
throw new Exception (ex. Innerexception.message, New Exception (ex. Innerexception.stacktrace));
}
}
<summary>
Get the WebService class name
</summary>
<param name= "Wsurl" ></param>
<returns></returns>
private static string Getwsclassname (String wsurl)
{
string[] parts = wsurl.split ('/');
string[] pps = parts[parts. LENGTH-1]. Split ('. ');
return pps[0];
}
#endregion
}

Invoke page Content

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Web.UI;
Using System.Web.UI.WebControls;

public partial class _default:system.web.ui.page
{
protected void Page_Load (object sender, EventArgs e)
{
Try
{
String url = "Http://90.10.1.51/Service.asmx";
string[] args = new string[1];
Args[0] = "P000001";
Object result = Callwebservice.invokewebservice (URL, "Pdaservice", null);
Response.Write (Result. ToString ());
}
catch (Exception ex)
{
Response.Write (ex. Message.tostring ());
}
}
}

Dynamic Call WebService

Related Article

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.