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 .....
Related
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/
I m using the following code to invoke SOAP method dynamically. It works when the input for the service is ONE(1). When I increase the input to Two it returns error.
Out of idea why this happens.
I referred to this link to built this..
http://www.codeproject.com/Articles/18950/Dynamic-Discovery-and-Invocation-of-Web-Services
My SOAP Service:
[WebMethod]
public string UpdateMapString(string status, string astationid)
{
return string.Format("Update Completed");
}
This is my C# Code Calling the SOAP service.
The main Function:
private MethodInfo[] methodInfo;
private ParameterInfo[] param;
private Type service;
private Type[] paramTypes;
public List<Type> myproperty = new List<Type>();
private string MethodName = "";
public List<string> treews = new List<string>();
public List<string> treeParameters = new List<string>();
public static void Main(string[] args)
{
Program a = new Program();
a.DynamicInvocation();
a.selectMethod();
a.invoke();
Console.ReadLine();
}
To Call Service:
public void DynamicInvocation()
{
try
{
Uri uri = new Uri("http://localhost:50167/Service.asmx?WSDL");
WebRequest webRequest = WebRequest.Create(uri);
System.IO.Stream requestStream = webRequest.GetResponse().GetResponseStream();
// Get a WSDL file describing a service
ServiceDescription sd = ServiceDescription.Read(requestStream);
string sdName = sd.Services[0].Name;
// Add in tree view
// treeWsdl.Nodes.Add(sdName);
treews.Add(sdName);
Console.WriteLine("Service Name: " + sdName);
// messageTextBox.Text += "Generating Proxy \r\n";
// progressBar1.PerformStep();
// Initialize a service description servImport
ServiceDescriptionImporter servImport = new ServiceDescriptionImporter();
servImport.AddServiceDescription(sd, String.Empty, String.Empty);
servImport.ProtocolName = "Soap";
servImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;
// messageTextBox.Text += "Generating assembly \r\n";
// progressBar1.PerformStep();
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());
// messageTextBox.Text += "Compiling assembly \r\n";
// progressBar1.PerformStep();
// 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(sdName);
methodInfo = service.GetMethods();
foreach (MethodInfo t in methodInfo)
{
if (t.Name == "Discover")
break;
Console.WriteLine(t.Name);
}
}
// messageTextBox.Text += warnings;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
// messageTextBox.Text += "\r\n" + ex.Message + "\r\n\r\n" + ex.ToString(); ;
// progressBar1.Value = 70;
}
}
To get the Method:
public void selectMethod()
{
treeParameters.Add(treews[0]);
MethodName = methodInfo[0].Name;
param = methodInfo[0].GetParameters();
/// myProperty.add = param[e.Node.Index].ParameterType;
myproperty.Add(param[0].ParameterType);
// Console.WriteLine("This is param: " + param[0].ToString());
// myProperty = new properties(param.Length);
// Get the Parameters Type
paramTypes = new Type[param.Length];
for (int i = 0; i < paramTypes.Length; i++)
{
paramTypes[i] = param[i].ParameterType;
}
foreach (ParameterInfo temp in param)
{
treeParameters.Add(temp.ParameterType.Name + " " + temp.Name);
}
}
To Invoke Service (error in this function)
public void invoke()
{
Console.WriteLine("Invoke:");
object[] param1 = new object[param.Length];
try
{
for (int i = 0; i < param.Length; i++)
{
//param1[i] = Convert.ChangeType(myProperty.MyValue[i], myProperty.TypeParameter[i]);
// Console.WriteLine(myproperty[i].ToString());
param1[i] = Convert.ChangeType("10", typeof(string));
}
foreach (MethodInfo t in methodInfo)
{
//Console.WriteLine("Tname: " + t.Name.ToString());
if (t.Name == MethodName)
{
//Invoke Method
Object obj = Activator.CreateInstance(service);
//*****************error at this line
Object response = t.Invoke(obj, param1);
//*****************error at this line
// Console.WriteLine(t.Name);
Console.WriteLine(response.ToString());
break;
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
//MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
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.
I'm trying to compile some unsafe code from an application using Codedom, but everytime I get an error saying I must use "/unsafe." I've googled the issue and added:
Parameters.CompilerOptions = "/unsafe";
To my codedom code. Are there any simple solutions for this?
Edit: if it wasn't already clear, my solution didn't work.
Edit: Here is the class.
public static bool Compile(string EXE_Name, string Source)
{
var Compiler = new CSharpCodeProvider();
var Parameters = new CompilerParameters
{
CompilerOptions = "/unsafe"
};
CompilerResults cResults = default(CompilerResults);
Parameters.GenerateExecutable = true;
Parameters.OutputAssembly = EXE_Name;
Parameters.ReferencedAssemblies.Add(typeof(System.Xml.Linq.Extensions).Assembly.Location);
Parameters.ReferencedAssemblies.Add("System.dll");
Parameters.ReferencedAssemblies.Add("System.Core.dll");
Parameters.ReferencedAssemblies.Add("System.Data.dll");
Parameters.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll");
Parameters.ReferencedAssemblies.Add("System.Deployment.dll");
Parameters.ReferencedAssemblies.Add("System.Windows.Forms.dll");
Parameters.ReferencedAssemblies.Add("System.Drawing.dll");
Parameters.ReferencedAssemblies.Add("System.Xml.dll");
Parameters.CompilerOptions = " /target:winexe";
Parameters.TreatWarningsAsErrors = false;
cResults = Compiler.CompileAssemblyFromSource(Parameters, Source);
if (cResults.Errors.Count > 0)
{
foreach (CompilerError CompilerError_loopVariable in cResults.Errors)
{
CompilerError error = CompilerError_loopVariable;
MessageBox.Show("Error: " + error.ErrorText, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return false;
}
else if (cResults.Errors.Count == 0)
{
return true;
}
return true;
}
It works for me - perhaps you weren't setting the parameters correctly?
using System.CodeDom.Compiler;
using Microsoft.CSharp;
class Test
{
public static void Main(string[] args)
{
var compiler = new CSharpCodeProvider();
var parameters = new CompilerParameters {
CompilerOptions = "/unsafe"
};
var source = "unsafe struct Foo {}";
var result = compiler.CompileAssemblyFromSource(parameters, source);
// No errors are shown with the above options set
foreach (var error in result.Errors)
{
Console.WriteLine(error);
}
}
}
var Parameters = new CompilerParameters
{
CompilerOptions = "/unsafe"
};
and later:
Parameters.CompilerOptions = " /target:winexe";
You just replace "/unsafe" with " /target:winexe". Use:
Parameters.CompilerOptions += " /target:winexe";
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.