Saturday, January 2, 2010

How to Create a Webservice Proxy Class in Run Time & Execute a Method?

Aim :

      How invocation of web services Without use add/Web reference.

      We know the WSDL URL , Method name and Parameters we can access the Webservice without adding Proxy class & Web Reference.

Steps
      
  •       Read the WSDL Stream from the URL
      Uri uri = new Uri(URL);

      
      WebRequest webRequest = WebRequest.Create(uri);
     
      Stream requestStream = webRequest.GetResponse().GetResponseStream(); 
  •       Read the Service name from the WSDL by using
       ServiceDescription oServiceDescription = ServiceDescription.Read(requestStream);

       String sServiceName = oServiceDescription.Services[0].Name;

The ServiceDescriptionImporter class allows we to easily import the information contained in a WSDL description into a System.CodeDom.CodeCompileUnit object.

       ServiceDescriptionImporter servImport = new ServiceDescriptionImporter();
       servImport.AddServiceDescription(oServiceDescription, String.Empty, String.Empty);
       servImport.ProtocolName = "Soap";
       servImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;

       CodeNamespace nameSpace = new CodeNamespace();

       CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
       codeCompileUnit.Namespaces.Add(nameSpace);
CodeCompileUnit contains a collection that can store CodeNamespace objects containing CodeDOM source code graphs, along with a collection of assemblies referenced by the project, and a collection of attributes for the project assembly.

  •        Now we can import the WSDL into CodeDom
        ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit);
  •       Then we Generate the code from CodeCompileUnit.Namespaces Class
       StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture);
       Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider();
       prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions());
  •       Compile the assembly with the appropriate references
       String[] assemblyReferences = new String[2] { "System.Web.Services.dll", "System.Xml.dll" };
       CompilerParameters param = new CompilerParameters(assemblyReferences);
       param.GenerateExecutable = false;
       param.GenerateInMemory = true;
       param.TreatWarningsAsErrors = false;
       param.WarningLevel = 4;

      CompilerResults results = new CompilerResults(new TempFileCollection());
      results = prov.CompileAssemblyFromDom(param, codeCompileUnit);
     Assembly assembly = results.CompiledAssembly; 
  
  •      Read all the methos & Parameters  from the Compiled assembly ( Run time proxy instance).
methodInfo = service.GetMethods();
foreach (MethodInfo oInfo in methodInfo)
{
      if (String.Compare(oInfo.Name, sMathod, true) == 0)
     {
           //Invoke Method
          Object[] oParam = new Object[oInPutParam.Length];
          for (int iCnt = 0; iCnt < oInPutParam.Length; iCnt++)
         {
              oParam[iCnt] = Convert.ChangeType(oInPutParam[iCnt], oInfo.GetParameters()[iCnt].ParameterType);
          }
     
          Object obj = Activator.CreateInstance(service);
         response = oInfo.Invoke(obj, oParam);
         break;
     }
}

Complete Code Block

private String ServiceInvocation(String URL, String sMathod, Object[] oInPutParam)

{
   MethodInfo[] methodInfo = null;
   Type service = null;
   Object response = null;
   try
   {
           Uri uri = new Uri(URL);
           WebRequest webRequest = WebRequest.Create(uri);
           Stream requestStream = webRequest.GetResponse().GetResponseStream();

            ServiceDescription oServiceDescription = ServiceDescription.Read(requestStream);
            String sServiceName = oServiceDescription.Services[0].Name;

            ServiceDescriptionImporter servImport = new ServiceDescriptionImporter();
            servImport.AddServiceDescription(oServiceDescription, String.Empty, String.Empty);
            servImport.ProtocolName = "Soap";
            servImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;

           CodeNamespace nameSpace = new CodeNamespace();
          CodeCompileUnit codeCompileUnit = new CodeCompileUnit();
          codeCompileUnit.Namespaces.Add(nameSpace);

         // Set Warnings
         ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit);

        if (warnings == 0)
      {

              StringWriter stringWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture);
             Microsoft.CSharp.CSharpCodeProvider prov = new Microsoft.CSharp.CSharpCodeProvider();
             prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions());

             // Compile the assembly with the appropriate references
            String[] assemblyReferences = new string[2] { "System.Web.Services.dll", "System.Xml.dll" };
            CompilerParameters param = new CompilerParameters(assemblyReferences);
            param.GenerateExecutable = false;
            param.GenerateInMemory = true;
            param.TreatWarningsAsErrors = false;
            param.WarningLevel = 4;

            CompilerResults results = new CompilerResults(new TempFileCollection());
            results = prov.CompileAssemblyFromDom(param, codeCompileUnit);
           Assembly assembly = results.CompiledAssembly;
           service = assembly.GetType(sServiceName);

           methodInfo = service.GetMethods();
           foreach (MethodInfo oInfo in methodInfo)
         {
                 if (String.Compare(oInfo.Name, sMathod, true) == 0)
                {
                        //Invoke Method
                        Object[] oParam = new Object[oInPutParam.Length];
                        for (int iCnt = 0; iCnt < oInPutParam.Length; iCnt++)
                        {
                                oParam[iCnt] = Convert.ChangeType(oInPutParam[iCnt], oInfo.GetParameters()[iCnt].ParameterType);
                         }
                        Object obj = Activator.CreateInstance(service);
                        response = oInfo.Invoke(obj, oParam);
                       break;
                }
      }
}

else
      throw new Exception(warnings.ToString());
   return Convert.ToString(response);
  }
  catch
  {
       throw;
   }
}


Thank You

No comments: