c# - dynamically call rest web service

[SecurityPermissionAttribute(SecurityAction.Demand, Unrestricted = true)]

        public static object callWebService(string webServiceAsmxUrl, string serviceName, string methodName, object[] args)
        {
            System.Net.WebClient client = new System.Net.WebClient();
            System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl);
            ServiceDescription description = ServiceDescription.Read(stream);
            ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
            importer.ProtocolName = "Soap";
            importer.AddServiceDescription(description, null, null);
            importer.Style = ServiceDescriptionImportStyle.Client;
            importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
            CodeNamespace nmspace = new CodeNamespace();
            CodeCompileUnit unit1 = new CodeCompileUnit();
            unit1.Namespaces.Add(nmspace);
            ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);
            if (warning == 0)
            {
                CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");
                string[] assemblyReferences = new string[5] { "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll" };
                CompilerParameters parms = new CompilerParameters(assemblyReferences);
                CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1);
                if (results.Errors.Count > 0)
                {
                    foreach (CompilerError oops in results.Errors)
                    {
                        System.Diagnostics.Debug.WriteLine("========Compiler error============");
                        System.Diagnostics.Debug.WriteLine(oops.ErrorText);
                    }
                    throw new System.Exception("Compile Error Occured calling webservice. Check Debug ouput window.");
                }
               
                object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
                ((System.Web.Services.Protocols.WebClientProtocol)wsvcClass).Timeout = 60000;
                MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
                var webserviceOutput = mi.Invoke(wsvcClass, args);             
                return webserviceOutput;
            }
            else
            {
                return null;
            }

Comments