Skip to content

Instantly share code, notes, and snippets.

@phatty
Created June 5, 2014 04:15
Show Gist options
  • Save phatty/f897d5ed08f42b540394 to your computer and use it in GitHub Desktop.
Save phatty/f897d5ed08f42b540394 to your computer and use it in GitHub Desktop.
public static class WcfGen
{
private static string contractName;
private static string operationName;
private static Type clientProxyType;
private static CodeDomProvider codeDomProvider;
private static CompilerResults results;
private static Uri mexAddress;
private static Dictionary<string, IEnumerable<ServiceEndpoint>> endpointsForContracts = new Dictionary<string, IEnumerable<ServiceEndpoint>>();
public static void RegisterService ( string URL , string contractName )
{
WcfGen.contractName = contractName;
WcfGen.operationName = operationName;
mexAddress = new Uri(URL);
MetadataExchangeClient mexClient = new MetadataExchangeClient(mexAddress, MetadataExchangeClientMode.HttpGet);
mexClient.ResolveMetadataReferences = true;
MetadataSet metaSet = mexClient.GetMetadata();
WsdlImporter importer = new WsdlImporter(metaSet);
Collection<ContractDescription> contracts =
importer.ImportAllContracts();
ServiceEndpointCollection allEndpoints = importer.ImportAllEndpoints();
ServiceContractGenerator generator = new ServiceContractGenerator();
foreach (ContractDescription contract in contracts)
{
generator.GenerateServiceContractType(contract);
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.");
}
CodeGeneratorOptions options = new CodeGeneratorOptions();
options.BracingStyle = "C";
CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("C#");
CompilerParameters compilerParameters = new CompilerParameters(
new string[] {
"System.dll", "System.ServiceModel.dll",
"System.Runtime.Serialization.dll" });
compilerParameters.GenerateInMemory = true;
results = codeDomProvider.CompileAssemblyFromDom(compilerParameters, generator.TargetCompileUnit);
if (results.Errors.Count > 0)
{
throw new Exception("There were errors during generated code compilation");
}
else
{
clientProxyType
= results.CompiledAssembly.GetTypes().First(
t => t.IsClass &&
t.GetInterface(contractName) != null &&
t.GetInterface(typeof(ICommunicationObject).Name) != null);
}
}
public static object CallService (string contractName,string operationName)
{
ServiceEndpoint se = endpointsForContracts[contractName].First();
object instance = results.CompiledAssembly.CreateInstance(
clientProxyType.Name,
false,
System.Reflection.BindingFlags.CreateInstance,
null,
new object[] { se.Binding, se.Address },
CultureInfo.CurrentCulture, null);
object retVal = instance.GetType().GetMethod(operationName).Invoke(instance, null);
return retVal ;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment