The topics described here concentrates fully on pure .Net Framework, describing actual meaning of some programming concepts, FCL and best practices. However you will be using these concepts in all . Net framework compatible languages like Microsoft visual basic .net (VB.Net) or C# .Net (csharp.Net) to build a web application (Asp.Net) or Desktop applications (winforms .net) or Web/Windows services





This blog has moved!

You will be automatically redirected to the new address. If that does not occur, visit
http://Codemine.net
and update your bookmarks.

Thursday, June 3, 2010

Dynamic Webservice Invoke

Recently in one of the projects which i am working i came into such a situation in which i need to read a number of web service URL’s, then dynamically call a particular method in it. First i thought of going with reflection alone but further analysis led me to more in depths of reflection which includes a bit of dynamic compilation thereby to create a “webproxy” like stuff at runtime. Thus we can get the actual metadata of the target type using which we can invoke the required method. Here we might need the type definition of the method and return parameter too (if any).



Luckily i just had a common return type which i don’t have to worry too much about. Now that we decided to go with dynamic compilation in .Net Clr and reflection we need to start with a ServiceDescription class to which we can assign a stream which will in turn read the required data from a WSDL URL, a ServiceDescriptionImporter class to import it. Now we need to add the necessary references and do the compilation as required.

Below is just the main part of the code for dynamic compilation in C#


ServiceDescription description = ServiceDescription.Read(stream);
ServiceDescriptionImporter imp = new ServiceDescriptionImporter();
imp.ProtocolName = "Soap"; // Use SOAP
imp.AddServiceDescription(description, null, null);

CodeNamespace namspace = new CodeNamespace();
CodeCompileUnit unt = new CodeCompileUnit();
unt.Namespaces.Add(namspace);
ServiceDescriptionImportWarnings warning = imp.Import(namspace, unt);
if (warning == 0)
{
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
string[] assemblyReferences = new string[2] { "System.Web.Services.dll", "System.Xml.dll" };
CompilerParameters parms = new CompilerParameters(assemblyReferences);
CompilerResults results = provider.CompileAssemblyFromDom(parms, unt);
object o = results.CompiledAssembly.CreateInstance("MyService");
Type t = o.GetType();


And now we can dynamically invoke webservice method with the following code


t.InvokeMember("MyParam", System.Reflection.BindingFlags.InvokeMethod, null, o, null);

}

0 comments: