Cotinuing to my post on Dynamic webservice invoke in C#, Here is the full C#.Net source code for gererating a web proxy by just providing the required WSDL URL as input. The source code targets .Net 2.0 Runtime. This code is making use of Reflection and dynamic runtime compilation features in C#.
Public object[] GeneratewebserviceProxy(string WSDL)
{
WebRequest webRequest = WebRequest.Create(WSDL);
System.IO.Stream requestStream = webRequest.GetResponse().GetResponseStream();
ServiceDescription description = ServiceDescription.Read(requestStream);
string sdName = description.Services[0].Name;
// here i had just one type and one method, so trying to extract the method name..
string Method_Name = description.Messages[0].Name.Replace("Request","");
Method_Name = Method_Name.Replace("Response","");
// Initialize a service description importer.
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap";
importer.AddServiceDescription(description, null, null);
// Initialize a Code-DOM tree into which we will import the service.
CodeNamespace nmspace = new CodeNamespace();
CodeCompileUnit unit1 = new CodeCompileUnit();
unit1.Namespaces.Add(nmspace);
// Import the service into the Code-DOM tree. This creates proxy code
// that uses the service.
ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);
object[] objRet = null;;
if (warning == 0)
{
// Generate and print the proxy code in C#.
CodeDomProvider provider1 = new CSharpCodeProvider();
// Compile the assembly with the appropriate references
string[] assemblyReferences = new string[2] { "System.Web.Services.dll", "System.Xml.dll" };
CompilerParameters parms = new CompilerParameters(assemblyReferences);
CompilerResults results = provider1.CreateCompiler().CompileAssemblyFromDom(parms, unit1);
//Invoke the web service method
object o = results.CompiledAssembly.CreateInstance(sdName);
Type t = o.GetType();
MethodInfo m = t.GetMethod("Invoke", BindingFlags.NonPublic | BindingFlags.Instance);
object[] webmethod_param = {RequiredParam_ifany};
object[] objParams = {Method_Name, webmethod_param};
objRet = (object[])m.Invoke(o, objParams);
if (objRet.Length >0)
{
objRet = (object[])objRet[0];
}
}
return objRet;
}
Hope you enjoyed the post. Let me know your comments....
Was this post helpful to you ? !!.. Then please like this in any of the social media below !.
Let it be useful for others too..