Adding web reference dynamically C# - c#

My code is this:
internal class WsProxy
{
[SecurityPermissionAttribute(SecurityAction.Demand, Unrestricted = true)]
internal static object CallWebService(string webServiceAsmxUrl, string userName, string password, string serviceName, string methodName, object[] args)
{
System.Net.WebClient client = new System.Net.WebClient();
if (userName.Length > 0)
{
client.Credentials = new NetworkCredential(userName, password);
}
// Connect To the web service
System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");
// Now 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 = "Soap"; // 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 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);
if (warning == 0) // If zero then we are good to go
{
// Generate the proxy code
CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");
// Compile the assembly proxy with the appropriate references
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);
// Check For Errors
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.");
}
// Finally, Invoke the web service method
object wsvcClass = results.CompiledAssembly.CreateInstance("nmspace");//nmspace
MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
return mi.Invoke(wsvcClass, args);
}
else
{
return null;
}
}
And here is how I call it:
object[] arg = new object[5];
WsProxy.CallWebService(#"myurl/somename.asmx", "NameService", "TheMethod", arg);
But every time, wsvcClass is null.
I tried changing
object wsvcClass = results.CompiledAssembly.CreateInstance("nmspace");
to
object wsvcClass = results.CompiledAssembly.CreateInstance("nmspace."+serviceName);
and it doesn't work.
Everyone says that the code works like charm, but I can't get it to work. Why?
UPDATE:
Here is what I do when I add the reference dynamically:
Namespace.MyService defect = new Namespace.MyService();
defect.Name = "someName";
And here is how I try to do it via code:
object wsvcClass = results.CompiledAssembly.CreateInstance("Namespace." + "MyService");
MethodInfo mi = wsvcClass.GetType().GetMethod("Namespace." + "MyService");
return mi.Invoke(null, new object[] { "someName" });
mi is null and I know there's something wrong on the last line too. It just looks stupid to me.

have you tried
object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
"nmspace" is wrong as this is the name of your variable, which holds a CodeNamespace with no name.

Related

How to call a web service dynamically without add service reference over SSL

I'm developing a client that call a web service without add service reference. The method receives as a parameter an XML.
static void Main(string[] args)
{
string xmlAux = string.Empty;
string link = "https://test.xxx.com/xxx/xxx.asmx";
string arg1 = #"<tuca> <hd> <t_doc>10</t_doc> <id_user>xxx</id_user> <pwd>xxx</pwd> <id_pais>xxx</id_pais> </hd> <parametros> <par tipo=""tipo_sujeto"">fisico</par> <par tipo=""calificacion"">xxx</par> <par tipo=""CEDULA DE IDENTIDAD"">xxx</par> </parametros> </tuca>";
object[] arguments = { arg1 };
var ws = CallWebService(link, "xxx", "Reporte", arguments);
if (ws != null)
{
xmlAux = ws.ToString();
}
}
[System.Security.Permissions.SecurityPermissionAttribute(System.Security.Permissions.SecurityAction.Demand, Unrestricted = true)]
internal 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");
// Now read the WSDL file describing a service.
var description = System.Web.Services.Description.ServiceDescription.Read(stream);
///// LOAD THE DOM /////////
// Initialize a service description importer.
var importer = new System.Web.Services.Description.ServiceDescriptionImporter();
importer.ProtocolName = "Soap12"; // Use SOAP 1.2.
importer.AddServiceDescription(description, null, null);
// Generate a proxy client.
importer.Style = System.Web.Services.Description.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.
var nmspace = new System.CodeDom.CodeNamespace();
var unit1 = new System.CodeDom.CodeCompileUnit();
unit1.Namespaces.Add(nmspace);
// Import the service into the Code-DOM tree. This creates proxy code that uses the service.
var warning = importer.Import(nmspace, unit1);
if (warning == 0) // If zero then we are good to go
{
// Generate the proxy code
var provider1 = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp");
// Compile the assembly proxy with the appropriate references
string[] assemblyReferences = new string[5] { "System.dll", "System.Web.Services.dll", "System.Web.dll", "System.Xml.dll", "System.Data.dll" };
var parms = new System.CodeDom.Compiler.CompilerParameters(assemblyReferences);
var results = provider1.CompileAssemblyFromDom(parms, unit1);
// Check For Errors
if (results.Errors.Count > 0)
{
foreach (System.CodeDom.Compiler.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.");
}
// Finally, Invoke the web service method
object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
var mi = wsvcClass.GetType().GetMethod(methodName);
return mi.Invoke(wsvcClass, args);
}
else
{
return null;
}
}
In the line:
return mi.Invoke(wsvcClass, args)
throws exception:
InnerException: {"The underlying connection was closed: An unexpected error occurred on a receive."}
Message: Exception has been thrown by the target of an invocation.
I solved it with this post:
Invoking a Web Service dynamically using System.Net and SOAP
http://www.c-sharpcorner.com/uploadfile/f9935e/invoking-a-web-service-dynamically-using-system-net-and-soap/

How to implement TLS-ALPN in .NET C# for a HTTP/2 server

does anyone know, how I can implement the TLS-ALPN in .NET?
I've implemented a basic HTTP/2 server, but without TLS encryption.
I searched in google, but I only found resources for C, Java or other languages, but nothing for .NET (C#)
According to HttpTwo project on Github it is not possible currently because of a bug.
Update: It's not supported in .NET. You can vote for it here: https://visualstudio.uservoice.com/forums/121579-visual-studio-2015/suggestions/6264363-add-support-for-alpn-to-system-net-security-sslstr
quote:
The HTTP/2 RFC states that secure connections must use ALPN to
negotiate the protocol. Unfortunately, .NET's SslStream has no ability
to specify application protocols as part of the TLS authentication, so
it can't support ALPN. There's an issue tracking this on
dotnetfix however it seems like this isn't going to happen very
soon (especially on mono and .NET 4.x).
It actually is possible. With some reflection you can inject any extension in client or server hello.
Here's some code to give you an idea:
// Refer IANA on ApplicationProtocols: https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml#alpn-protocol-ids
public static void FixALPN(params string[] protocols) {
if (Interlocked.Increment(ref cntFixALPN) > 1)
{
throw new Exception("FixALPN should be called only ONCE, put it in your Main or use a static constructor.");
return;
}
// get the needed (internal) System types
string tpname = typeof(System.Net.HttpListener).AssemblyQualifiedName;
Type tpiface = Type.GetType(tpname.Replace("HttpListener", "SSPIInterface"));
Type tpgsspi = Type.GetType(tpname.Replace("HttpListener", "GlobalSSPI"));
Type tpsdc = Type.GetType(tpname.Replace("HttpListener", "SafeDeleteContext"));
Type tpsecbuf = Type.GetType(tpname.Replace("HttpListener", "SecurityBuffer"));
// create ALPN buffer
ConstructorInfo ci = (from x in tpsecbuf.GetConstructors() where x.GetParameters().Length == 4 select x).First();
var secbufempty = ci.Invoke(new object[] { new byte[0], 0, 0, 0 });
byte[] btsalpn = GetALPNBuffer(protocols);
var secbufalpn = ci.Invoke(new object[] { btsalpn, 0, btsalpn.Length, 18 });
// grab the object to replace...
FieldInfo fi = tpgsspi.GetField("SSPISecureChannel", BindingFlags.NonPublic | BindingFlags.Static);
var secchan = fi.GetValue(null);
// ...and the method(s) we'll use in our intercepted call(s)
MethodInfo miSDC_ISC = tpsdc.GetMethod("InitializeSecurityContext", BindingFlags.NonPublic | BindingFlags.Static);
MethodInfo miSDC_ASC = tpsdc.GetMethod("AcceptSecurityContext", BindingFlags.NonPublic | BindingFlags.Static);
// fake the internal interface
var result = new InterfaceImplementer(tpiface, (mcm) => {
MethodInfo mi = (MethodInfo)mcm.MethodBase;
object[] args = mcm.Args;
object ret = null;
if (mi.Name == "InitializeSecurityContext") // For Client Mode
{
if (args[5] == null) // empty input, new connection
{
dynamic[] secbufs = (dynamic[])Activator.CreateInstance(miSDC_ASC.GetParameters()[6].ParameterType, new object[] { 1 });
secbufs[0] = secbufalpn;
object[] sdcargs = new object[] { 0, args[0], args[1], args[2], args[3], args[4],
null,
secbufs,
args[6], args[7]
};
ret = miSDC_ISC.Invoke(null, sdcargs);
args[0] = sdcargs[1];
args[1] = sdcargs[2];
args[7] = sdcargs[9];
}
else
{
ret = mi.Invoke(secchan, args);
}
}
else if (mi.Name == "AcceptSecurityContext") // For Server Mode
{
dynamic[] secbufs = (dynamic[])Activator.CreateInstance(miSDC_ASC.GetParameters()[6].ParameterType, new object[] { 3 });
secbufs[0] = args[2];
secbufs[1] = secbufempty;
secbufs[2] = secbufalpn;
object[] sdcargs = new object[] { 0, args[0], args[1], args[3], args[4],
null,
secbufs,
args[5], args[6]
};
ret = miSDC_ASC.Invoke(null, sdcargs);
args[0] = sdcargs[1];
args[1] = sdcargs[2];
args[6] = sdcargs[8];
}
else
ret = mi.Invoke(secchan, args);
return new ReturnMessage(ret, args, args.Length, mcm.LogicalCallContext, mcm);
}).GetTransparentProxy();
// and set it, done
fi.SetValue(null, result);
}
.NET Core 2.1.2 includes the necessary changes to SslStream required to support ALPN. It isn't documented yet, but the pull request that adds it is here

Consuming wsdl url by passing method name and parameters and getting response 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)
{
try
{
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();
codeunit.Namespaces.Add(codenamespace);
//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[] {
"System.dll",
"System.Web.Services.dll",
"System.Web.dll",
"System.Xml.dll",
"System.Data.dll"
};
//--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============");
System.Diagnostics.Debug.WriteLine(oops.ErrorText);
}
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);
}
else
{
return null;
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}
In the above code while importing:
ServiceDescriptionImportWarnings warning = importer.Import(codenamespace, codeunit);
warning should come 0 then only it would go inside the if statement. But I'm getting CodeNotGenerated
I'm not able to figure out what the problem is. Can anyone please explain?

Calling a WCF service with certificate from a client application without having the contract interface

My particular problem is something like this:
I am able to invoke WCF service dynamically, but i need to provide certificate.
We don't want to use app.config.
Major issue is that WCF service is a 3rd party url.
Actually, i am getting an exception while invoke instance that certificate is not provided.
My code is something like this:
try
{
// Define the metadata address, contract name, operation name,
// and parameters.
// You can choose between MEX endpoint and HTTP GET by
// changing the address and enum value.
Uri mexAddress = new Uri("http://Some3rdPartyURL.svc?wsdl");//Some 3rd party url
// For MEX endpoints use a MEX address and a
// mexMode of .MetadataExchange
MetadataExchangeClientMode mexMode = MetadataExchangeClientMode.HttpGet;
string contractName = "IService";//"";//3rd party service name
string operationName = "SendMethod";//3rd party method name
object[] args = new object[] { "", "", "0" };//3rd party required parameters
//object[] operationParameters = new object[] { /*1, 2*/args };
// Get the metadata file from the service.
MetadataExchangeClient mexClient =
new MetadataExchangeClient(mexAddress, mexMode);
mexClient.ResolveMetadataReferences = true;
MetadataSet metaSet = mexClient.GetMetadata();
// Import all contracts and endpoints
WsdlImporter importer = new WsdlImporter(metaSet);
Collection<ContractDescription> contracts =
importer.ImportAllContracts();
ServiceEndpointCollection allEndpoints = importer.ImportAllEndpoints();
// Generate type information for each contract
ServiceContractGenerator generator = new ServiceContractGenerator();
var endpointsForContracts = new Dictionary<string, IEnumerable<ServiceEndpoint>>();
foreach (ContractDescription contract in contracts)
{
generator.GenerateServiceContractType(contract);
// Keep a list of each contract's endpoints
endpointsForContracts[contract.Name] = allEndpoints.Where(
se => se.Contract.Name == contract.Name).ToList();
}
if (generator.Errors.Count != 0)
throw new Exception("There were errors during code compilation.");
// Generate a code file for the contracts
CodeGeneratorOptions options = new CodeGeneratorOptions();
options.BracingStyle = "C";
CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("C#");
// Compile the code file to an in-memory assembly
// Don't forget to add all WCF-related assemblies as references
CompilerParameters compilerParameters = new CompilerParameters(
new string[] {
"System.dll", "System.ServiceModel.dll",
"System.Runtime.Serialization.dll"});
compilerParameters.GenerateInMemory = true;
CompilerResults results = codeDomProvider.CompileAssemblyFromDom(
compilerParameters, generator.TargetCompileUnit);
if (results.Errors.Count > 0)
{
throw new Exception("There were errors during generated code compilation");
}
else
{
// Find the proxy type that was generated for the specified contract
// (identified by a class that implements
// the contract and ICommunicationbject)
Type clientProxyType = results.CompiledAssembly.GetTypes().First(
t => t.IsClass &&
t.GetInterface(contractName) != null &&
t.GetInterface(typeof(ICommunicationObject).Name) != null);
// Get the first service endpoint for the contract
ServiceEndpoint se = endpointsForContracts[contractName].First();
//se = endpointsForContracts[contractName].First();
WSHttpBinding wsBinding = this.fillWsHttpBinding();
string encodeValue = "MIIFazCCBFO****"; // here we should use the encoded certificate value generated by svcutil.exe.
X509Certificate2Collection supportingCertificates = new X509Certificate2Collection();
supportingCertificates.Import(Convert.FromBase64String(encodeValue));
X509Certificate2 primaryCertificate = supportingCertificates[0];
supportingCertificates.RemoveAt(0);
EndpointIdentity.CreateX509CertificateIdentity(primaryCertificate, supportingCertificates);
EndpointIdentity identity = EndpointIdentity.CreateX509CertificateIdentity(primaryCertificate);
var endpoint = new EndpointAddress(mexAddress, identity);
se.Binding = wsBinding;
se.Address = endpoint;
// Create an instance of the proxy
// Pass the endpoint's binding and address as parameters
// to the ctor
object instance = results.CompiledAssembly.CreateInstance(
clientProxyType.Name,
false,
System.Reflection.BindingFlags.CreateInstance | BindingFlags.Public | BindingFlags.Instance,
null,
new object[] { se.Binding, se.Address }, CultureInfo.CurrentCulture, null);
var methodInfo = instance.GetType().GetMethod(operationName);
var methodParams = methodInfo.GetParameters();
int count = args.Count();
object[] args2 = new object[count];
int i = 0;
foreach (var service1 in methodParams)
{
args2[i] = Convert.ChangeType(args[i], Type.GetType("System." + service1.ParameterType.Name));
i += 1;
}
Object retVal = instance.GetType().GetMethod(operationName).Invoke(instance, args2);/*Getting Error that certificate not provided???*/
}
}
catch (Exception ex)
{
string error = ex.ToString();
MessageBox.Show("Error Invoking Method: " + ex.Message);
}
private WSHttpBinding fillWsHttpBinding()
{
WSHttpBinding wsBinding = new WSHttpBinding();
wsBinding.CloseTimeout = new TimeSpan(0, 1, 0);
wsBinding.OpenTimeout = new TimeSpan(0, 10, 0);
wsBinding.ReceiveTimeout = new TimeSpan(0, 10, 0);
wsBinding.SendTimeout = new TimeSpan(0, 5, 30);
wsBinding.BypassProxyOnLocal = false;
wsBinding.TransactionFlow = false;
wsBinding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
wsBinding.MaxBufferPoolSize = 524288L;
wsBinding.MaxReceivedMessageSize = 10485760L;
wsBinding.MessageEncoding = WSMessageEncoding.Text;
wsBinding.TextEncoding = Encoding.UTF8;
wsBinding.UseDefaultWebProxy = true;
wsBinding.AllowCookies = false;
wsBinding.ReaderQuotas.MaxDepth = 32;
wsBinding.ReaderQuotas.MaxStringContentLength = 8192;
wsBinding.ReaderQuotas.MaxArrayLength = 10485760;
wsBinding.ReaderQuotas.MaxNameTableCharCount = 16384;
wsBinding.ReliableSession.Ordered = true;
wsBinding.ReliableSession.InactivityTimeout = TimeSpan.FromMinutes(10);
wsBinding.ReliableSession.Enabled = false;
wsBinding.Security.Mode = SecurityMode.Message;
wsBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
wsBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
wsBinding.Security.Transport.Realm = "";
wsBinding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
wsBinding.Security.Message.NegotiateServiceCredential = true;
wsBinding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Basic256;
return wsBinding;
}
Where you are setting the certificate on the EndpointIdentity causes it to be used to validate the service's identity. You haven't set the client's credentials using instance.ClientCredentials.ClientCertificate.SetCertificate(...). You'll have to get the ClientCredentials from the ClientBase<> using reflection. See http://msdn.microsoft.com/en-us/library/ms732391%28v=vs.110%29.aspx.
var credentialProperty = instance.GetType().GetProperty("ClientCredentials");
var credentials = (ClientCredentials)credentialProperty.GetValue(instance, null);
credentials.ClientCertificate.SetCertficate(...);
You've also got two calls to EndpointIdentity.CreateX509CertificateIdentity, ignoring the output of one of them.

How to Invoke a WCF Service Dynamically using C# Winforms?

I have a WCF Service and i want to invoke this at run time ...
if i do the same code and instead of WCF(.svc) if i call (.asmx) i can able to get through and getting results... but here WCF gets failed
private void button1_Click(object sender, EventArgs e)
{
string WebserviceUrl = "http://localhost:90/service1/service1.svc";
string serviceName = Service1;
string methodName = GetData;
string[] arArguments = new string[2];
arArguments[0] = 2 ;
string sData =CallWebService(WebserviceUrl, serviceName, methodName, arArguments);
if (!string.IsNullOrEmpty(sData))
MessageBox.Show(sData + "\tData Available");
else
MessageBox.Show(sData + "\tData not Available");
}
[SecurityPermissionAttribute(SecurityAction.Demand, Unrestricted = true)]
private string CallWebService(string WebserviceUrl, string serviceName, string methodName, string[] arArguments)
{
System.Net.WebClient client = new System.Net.WebClient();
System.IO.Stream stream = client.OpenRead(WebserviceUrl + "?wsdl");
ServiceDescription description = ServiceDescription.Read(stream);
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap12";
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) // If Successfull
{
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) // Error Part
{
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);
MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
return mi.Name;
}
else
{
return null;
}
}
how to achieve this .....

Categories