Thursday, September 23, 2010

Call webservice without adding web reference

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

//Added for samplecode
using System.CodeDom.Compiler;
using System.Security.Permissions;
using System.Web.Services.Description;
using System.Reflection;
using System.CodeDom;
using System.Diagnostics;

namespace DynamicSoap

public static class DynamicWebService

public static Object CallWebService(string webServiceAsmxUrl,
string serviceName, string methodName, object[] args)

System.Net.WebClient client = new System.Net.WebClient();

//-Connect To the web service
System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");

//Read the WSDL file describing a service.
ServiceDescription description = ServiceDescription.Read(stream);

//Load the DOM

//--Initialize a service description importer.
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap12"; //Use SOAP 1.2.
importer.AddServiceDescription(description, null, null);

//--Generate a proxy client.

importer.Style = ServiceDescriptionImportStyle.Client;
//--Generate properties to represent primitive values.

importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;

//Initialize a Code-DOM tree into which we will import the service.
CodeNamespace codenamespace = new CodeNamespace();
CodeCompileUnit codeunit = new CodeCompileUnit();

//Import the service into the Code-DOM tree.
//This creates proxy code that uses the service.

ServiceDescriptionImportWarnings warning = importer.Import(codenamespace, codeunit);

if (warning == 0)

//--Generate the proxy code
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

//--Compile the assembly proxy with the
// appropriate references
string[] assemblyReferences = new string[] {

//--Add parameters
CompilerParameters parms = new CompilerParameters(assemblyReferences);
parms.GenerateInMemory = true; //(Thanks for this line nikolas)
CompilerResults results = provider.CompileAssemblyFromDom(parms, codeunit);

//--Check For Errors
if (results.Errors.Count > 0)

foreach (CompilerError oops in results.Errors)
System.Diagnostics.Debug.WriteLine("========Compiler error============");
throw new Exception("Compile Error Occured calling WebService.");

//--Finally, Invoke the web service method
Object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
return mi.Invoke(wsvcClass, args);

return null;
catch (Exception ex)
throw ex;

Reference link :-

No comments: