private static void GenerateCodeDomTree(WsdlImporter wsdlImporter, ServiceContractGenerator contractGenerator) { Collection<ContractDescription> contracts = wsdlImporter.ImportAllContracts(); Collection<Binding> bindings = wsdlImporter.ImportAllBindings(); ServiceEndpointCollection endpoints = wsdlImporter.ImportAllEndpoints(); if (wsdlImporter.Errors.Any(e => !e.IsWarning)) { throw new CodeGenerationException(wsdlImporter.Errors); } foreach (ContractDescription contract in contracts) { //TODO:Alex:Make the naming scheme customisable. contract.Name = "I" + contract.Name.Replace("Interface", string.Empty); contractGenerator.GenerateServiceContractType(contract); } foreach (Binding binding in bindings) { string bindingSectionName, configurationName; contractGenerator.GenerateBinding(binding, out bindingSectionName, out configurationName); } foreach (ServiceEndpoint endpoint in endpoints) { ChannelEndpointElement channelElement; contractGenerator.GenerateServiceEndpoint(endpoint, out channelElement); } }
static void GenerateVBCodeForService(Uri metadataAddress, string outputFile) { MetadataExchangeClient mexClient = new MetadataExchangeClient(metadataAddress, MetadataExchangeClientMode.HttpGet); mexClient.ResolveMetadataReferences = true; MetadataSet metaDocs = mexClient.GetMetadata(); WsdlImporter importer = new WsdlImporter(metaDocs); ServiceContractGenerator generator = new ServiceContractGenerator(); System.Collections.ObjectModel.Collection<ContractDescription> contracts = importer.ImportAllContracts(); foreach (ContractDescription contract in contracts) { generator.GenerateServiceContractType(contract); } if (generator.Errors.Count != 0) throw new ApplicationException("There were errors during code compilation."); // Write the code dom. System.CodeDom.Compiler.CodeGeneratorOptions options = new System.CodeDom.Compiler.CodeGeneratorOptions(); options.BracingStyle = "C"; System.CodeDom.Compiler.CodeDomProvider codeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("VB"); System.CodeDom.Compiler.IndentedTextWriter textWriter = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(outputFile)); codeDomProvider.GenerateCodeFromCompileUnit(generator.TargetCompileUnit, textWriter, options); textWriter.Close(); }
protected override CodeCompileUnit GenerateCode(EndPointSetting wsdl) { if (wsdl == null || string.IsNullOrEmpty(wsdl.Uri)) throw new ApplicationException("WSDL Uri in endpoint section of the configuration is empty."); var wsdlContent = TryGetContent(wsdl.Uri); if (string.IsNullOrEmpty(wsdlContent)) throw new ApplicationException("Could not get content from WSDL at " + wsdl.Uri); var codeCompileUnit = new CodeCompileUnit(); try { var importer = CreateImporter(wsdl); var generator = new ServiceContractGenerator(codeCompileUnit); var ns = ProxyGeneratorSettings.Options.Services.Namespace; generator.Options = ServiceContractGenerationOptions.AsynchronousMethods | ServiceContractGenerationOptions.ChannelInterface | ServiceContractGenerationOptions.ClientClass | ServiceContractGenerationOptions.EventBasedAsynchronousMethods; // Data contract options importer.State.Remove(typeof(XsdDataContractExporter)); var contractImporter = new XsdDataContractImporter(); contractImporter.Options = new ImportOptions { EnableDataBinding = true }; contractImporter.Options.Namespaces.Add("*", ns); importer.State.Add(typeof(XsdDataContractImporter), contractImporter); var contracts = importer.ImportAllContracts(); var endpoints = importer.ImportAllEndpoints(); var codeNamespace = new CodeNamespace(ns); codeCompileUnit.Namespaces.Add(codeNamespace); foreach(ContractDescription contract in contracts) { generator.GenerateServiceContractType(contract); } if(generator.Errors.HasWarnings()) { Logger.WarnFormat("There was warnings when importing WSDL file at {0}. Warning message is: {1}.", wsdl.Uri, generator.Errors.GetWarnings()); } // Call SL fixups var slfix = new WcfSilverlightCodeGenerationExtension(); slfix.ClientGenerated(generator); } catch (Exception ex) { string message = "The wsdl with path:" + wsdl.Uri + " could not be processed.Error during the CodeCompileUnit generation."; throw new ApplicationException(message, ex); } return codeCompileUnit; }
public ServiceClientProxyCompileResult CompileProxy(ServiceMetadataInformation serviceMetadataInfo) { string tempConfigFileName = CreateTempConfigFile(); CodeCompileUnit codeCompileUnit = serviceMetadataInfo.CodeCompileUnit; ServiceContractGenerator contractGenerator = new ServiceContractGenerator(codeCompileUnit, CreateConfig(new FileInfo(tempConfigFileName))); contractGenerator.Options |= ServiceContractGenerationOptions.ClientClass; for (int i = 0; i < serviceMetadataInfo.Contracts.Count; i++) { ContractDescription contract = serviceMetadataInfo.Contracts[i]; contractGenerator.GenerateServiceContractType(contract); } bool success = true; Collection<MetadataConversionError> contractGenErrors = contractGenerator.Errors; if (contractGenErrors != null) { foreach (MetadataConversionError error in contractGenErrors) { if (!error.IsWarning) { success = false; break; } } } if (!success) { //TODO: Throw exception } CodeDomProvider codeDomProvider = serviceMetadataInfo.CodeDomProvider; string proxyCode = CreateProxyCode(codeDomProvider, codeCompileUnit); CompilerParameters compilerParameters = new CompilerParameters(); AddAssemblyReference(typeof(ServiceContractAttribute).Assembly, compilerParameters.ReferencedAssemblies); AddAssemblyReference(typeof(System.Web.Services.Description.ServiceDescription).Assembly, compilerParameters.ReferencedAssemblies); AddAssemblyReference(typeof(DataContractAttribute).Assembly, compilerParameters.ReferencedAssemblies); AddAssemblyReference(typeof(XmlElement).Assembly, compilerParameters.ReferencedAssemblies); AddAssemblyReference(typeof(Uri).Assembly, compilerParameters.ReferencedAssemblies); AddAssemblyReference(typeof(DataSet).Assembly, compilerParameters.ReferencedAssemblies); CompilerResults results = codeDomProvider.CompileAssemblyFromSource(compilerParameters, proxyCode); CompilerErrorCollection compileErrors = results.Errors; Assembly compiledAssembly = Assembly.LoadFile(results.PathToAssembly); return new ServiceClientProxyCompileResult(serviceMetadataInfo, compiledAssembly, GenerateConfig(contractGenerator, serviceMetadataInfo.Endpoints, tempConfigFileName)); }
public CodeCompileUnit GenerateCodeFromImportedContracts(WsdlImporter importer) { var generator = new ServiceContractGenerator(); var contracts = importer.ImportAllContracts(); foreach (var contract in contracts) { generator.GenerateServiceContractType(contract); } if (generator.Errors.Count != 0) throw new Exception("There were errors during code compilation."); var targetCompileUnit = generator.TargetCompileUnit; return targetCompileUnit; }
protected override CodeCompileUnit GenerateCode(EndPointSetting wsdl) { if (wsdl == null || string.IsNullOrEmpty(wsdl.Uri)) throw new ApplicationException("WSDL Uri in endpoint section of the configuration is empty."); var wsdlContent = TryGetContent(wsdl.Uri); if (string.IsNullOrEmpty(wsdlContent)) throw new ApplicationException("Could not get content from WSDL at " + wsdl.Uri); var codeCompileUnit = new CodeCompileUnit(); try { var importer = CreateImporter(wsdl); var generator = new ServiceContractGenerator(codeCompileUnit); var contracts = importer.ImportAllContracts(); var endpoints = importer.ImportAllEndpoints(); var codeNamespace = new CodeNamespace(ProxyGeneratorSettings.Options.Services.Namespace); codeCompileUnit.Namespaces.Add(codeNamespace); foreach(ContractDescription contract in contracts) { generator.GenerateServiceContractType(contract); } if(generator.Errors.HasWarnings()) { Logger.WarnFormat("There was warnings when importing WSDL file at {0}. Warning message is: {1}.", wsdl.Uri, generator.Errors.GetWarnings()); } } catch (Exception ex) { string message = "The wsdl with path:" + wsdl.Uri + " could not be processed.Error during the CodeCompileUnit generation."; throw new ApplicationException(message, ex); } return codeCompileUnit; }
/// <summary> /// 根据元数据发布地址生成代理类 /// </summary> /// <param name="address">元数据地址</param> /// <param name="mode">交换元数据方式</param> /// <param name="outPutProxyFile">代理文件路径</param> /// <param name="outPutConfigFile">配置文件路径</param> private static void GenerateWCfProxyAndConfig(string address, Entities.MetadataExchangeClientMode mode, string outPutProxyFile, string outPutConfigFile) { var mexClient = new MetadataExchangeClient(new Uri(address), (System.ServiceModel.Description.MetadataExchangeClientMode) mode); var metadataSet = mexClient.GetMetadata(); var importer = new WsdlImporter(metadataSet); var codeCompileUnit = new CodeCompileUnit(); var config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = outPutConfigFile }, ConfigurationUserLevel.None); var generator = new ServiceContractGenerator(codeCompileUnit, config); foreach (var endpoint in importer.ImportAllEndpoints()) { generator.GenerateServiceContractType(endpoint.Contract); ChannelEndpointElement element; generator.GenerateServiceEndpoint(endpoint, out element); } generator.Configuration.Save(); var provider = CodeDomProvider.CreateProvider("CSharp"); using (var sw = new StreamWriter(outPutProxyFile)) { var textWriter = new IndentedTextWriter(sw); var options = new CodeGeneratorOptions(); provider.GenerateCodeFromCompileUnit(codeCompileUnit, textWriter, options); } }
/// <summary> /// Generates the basic CodeNamespace using .NET Fx code generation API. /// </summary> private void CreateBasicCodeDomTree() { TweakWsdlImporter(); Collection<ContractDescription> contracts = wsdlImporter.ImportAllContracts(); Collection<Binding> bindings = wsdlImporter.ImportAllBindings(); ServiceEndpointCollection endpoints = wsdlImporter.ImportAllEndpoints(); if (wsdlImporter.Errors.Any(e => !e.IsWarning)) { throw new ClientServiceGenerationException(wsdlImporter.Errors); } ServiceContractGenerator scg = new ServiceContractGenerator(compileUnit, Configuration); TweakServiceContractGenerator(scg); foreach (ContractDescription contract in contracts) { contract.Name = "I" + contract.Name.Replace("Interface", string.Empty); CodeTypeReference ctr = scg.GenerateServiceContractType(contract); } foreach (Binding binding in bindings) { string bindingSectionName, configurationName; scg.GenerateBinding(binding, out bindingSectionName, out configurationName); } foreach (ServiceEndpoint endpoint in endpoints) { ChannelEndpointElement channelElement; scg.GenerateServiceEndpoint(endpoint, out channelElement); } }
void Run (string [] args) { co.ProcessArgs (args); if (co.RemainingArguments.Length == 0) { co.DoHelp (); return; } if (!co.NoLogo) co.ShowBanner (); CodeCompileUnit ccu = new CodeCompileUnit (); CodeNamespace cns = new CodeNamespace (co.Namespace); ccu.Namespaces.Add (cns); generator = new ServiceContractGenerator (ccu); generator.Options = GetGenerationOption (); generator.Options |=ServiceContractGenerationOptions.ChannelInterface; code_provider = GetCodeProvider (); MetadataSet metadata = null; // For now only assemblyPath is supported. foreach (string arg in co.RemainingArguments) { Uri uri = null; if (Uri.TryCreate (arg, UriKind.Absolute, out uri)) { metadata = ResolveWithDisco (arg); if (metadata == null) metadata = ResolveWithWSMex (arg); continue; } FileInfo fi = new FileInfo (arg); if (!fi.Exists) switch (fi.Extension) { case ".exe": case ".dll": GenerateContractType (fi.FullName); break; default: throw new NotSupportedException ("Not supported file extension: " + fi.Extension); } } if (metadata == null) return; List<IWsdlImportExtension> list = new List<IWsdlImportExtension> (); list.Add (new TransportBindingElementImporter ()); //list.Add (new DataContractSerializerMessageContractImporter ()); list.Add (new XmlSerializerMessageContractImporter ()); //WsdlImporter importer = new WsdlImporter (metadata, null, list); WsdlImporter importer = new WsdlImporter (metadata); //ServiceEndpointCollection endpoints = importer.ImportAllEndpoints (); Console.WriteLine ("Generating files.."); /*foreach (ServiceEndpoint se in endpoints) generator.GenerateServiceContractType (se.Contract);*/ Collection<ContractDescription> contracts = importer.ImportAllContracts (); foreach (ContractDescription cd in contracts) generator.GenerateServiceContractType (cd); /*if (cns.Types.Count == 0) { Console.Error.WriteLine ("Argument assemblies have no types."); Environment.Exit (1); }*/ //FIXME: Generate .config Console.WriteLine (GetOutputFilename ()); using (TextWriter w = File.CreateText (GetOutputFilename ())) { code_provider.GenerateCodeFromCompileUnit (ccu, w, null); } }
static void GenerateVBCodeForService(EndpointAddress metadataAddress, string outputFile) { MetadataExchangeClient mexClient = new MetadataExchangeClient(metadataAddress); mexClient.ResolveMetadataReferences = true; MetadataSet metaDocs = mexClient.GetMetadata(); WsdlImporter importer = new WsdlImporter(metaDocs); ServiceContractGenerator generator = new ServiceContractGenerator(); // Uncomment the following code if you are going to do your work programmatically rather than add // the WsdlDocumentationImporters through a configuration file. /* // The following code inserts the custom WSDL programmatically adding the custom WsdlImporter without // removing the other importers already in the collection. System.Collections.Generic.IEnumerable<IWsdlImportExtension> exts = importer.WsdlExtensions; System.Collections.Generic.List<IWsdlImportExtension> newExts = new System.Collections.Generic.List<IWsdlImportExtension>(); foreach (IWsdlImportExtension ext in exts) newExts.Add(ext); newExts.Add(new WsdlDocumentationImporter()); importer = new WsdlImporter(newExts.ToArray(), metaDocs.MetadataSections); */ System.Collections.ObjectModel.Collection<ContractDescription> contracts = importer.ImportAllContracts(); foreach (ContractDescription contract in contracts) { generator.GenerateServiceContractType(contract); } if (generator.Errors.Count != 0) throw new ApplicationException("There were errors during code compilation."); // Write the code dom. System.CodeDom.Compiler.CodeGeneratorOptions options = new System.CodeDom.Compiler.CodeGeneratorOptions(); options.BracingStyle = "C"; System.CodeDom.Compiler.CodeDomProvider codeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("VB"); System.CodeDom.Compiler.IndentedTextWriter textWriter = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(outputFile)); codeDomProvider.GenerateCodeFromCompileUnit(generator.TargetCompileUnit, textWriter, options); textWriter.Close(); }
static void Generate(string url, TextWriter writer) { var cr = new ContractReference(); cr.Url = url; var protocol = new DiscoveryClientProtocol(); var wc = new WebClient(); using (var stream = wc.OpenRead(cr.Url)) protocol.Documents.Add(cr.Url, cr.ReadDocument(stream)); var mset = ToMetadataSet(protocol); var importer = new WsdlImporter(mset); var xsdImporter = new XsdDataContractImporter(); var options = new ImportOptions(); options.ReferencedCollectionTypes.Add(typeof(LinkedList<>)); xsdImporter.Options = options; importer.State.Add(typeof(XsdDataContractImporter), xsdImporter); Collection<ContractDescription> contracts = importer.ImportAllContracts(); CodeCompileUnit ccu = new CodeCompileUnit(); CodeNamespace cns = new CodeNamespace("TestNamespace"); ccu.Namespaces.Add(cns); var generator = new ServiceContractGenerator(ccu); foreach (var cd in contracts) generator.GenerateServiceContractType(cd); var provider = new CSharpCodeProvider(); provider.GenerateCodeFromCompileUnit(ccu, writer, null); }
protected override string CreateProxyFile (DotNetProject dotNetProject, FilePath basePath, string proxyNamespace, string referenceName) { var ccu = new CodeCompileUnit (); var cns = new CodeNamespace (proxyNamespace); ccu.Namespaces.Add (cns); bool targetMoonlight = dotNetProject.TargetFramework.Id.Identifier == ("Silverlight"); bool targetMonoTouch = dotNetProject.TargetFramework.Id.Identifier == ("MonoTouch"); bool targetMonoDroid = dotNetProject.TargetFramework.Id.Identifier == ("MonoDroid"); bool targetCoreClr = targetMoonlight || targetMonoDroid || targetMonoTouch; bool generateSyncMethods = targetMonoDroid | targetMonoTouch; var generator = new ServiceContractGenerator (ccu); generator.Options = ServiceContractGenerationOptions.ChannelInterface | ServiceContractGenerationOptions.ClientClass; if (refGroup.ClientOptions.GenerateAsynchronousMethods || targetCoreClr) generator.Options |= ServiceContractGenerationOptions.AsynchronousMethods; if (refGroup.ClientOptions.GenerateEventBasedAsynchronousMethods) generator.Options |= ServiceContractGenerationOptions.EventBasedAsynchronousMethods; #if NET_4_5 if (refGroup.ClientOptions.GenerateTaskBasedAsynchronousMethod) generator.Options |= ServiceContractGenerationOptions.TaskBasedAsynchronousMethod; #endif if (refGroup.ClientOptions.GenerateInternalTypes) generator.Options |= ServiceContractGenerationOptions.InternalTypes; if (refGroup.ClientOptions.GenerateMessageContracts) generator.Options |= ServiceContractGenerationOptions.TypedMessages; // if (targetMoonlight || targetMonoTouch) // generator.Options |= ServiceContractGenerationOptions.EventBasedAsynchronousMethods; MetadataSet mset; mset = protocol != null ? ToMetadataSet (protocol) : metadata; CodeDomProvider code_provider = GetProvider (dotNetProject); var list = new List<IWsdlImportExtension> (); list.Add (new TransportBindingElementImporter ()); list.Add (new XmlSerializerMessageContractImporter ()); var importer = new WsdlImporter (mset); try { ConfigureImporter (importer); } catch { } Collection<ContractDescription> contracts = importer.ImportAllContracts (); foreach (ContractDescription cd in contracts) { cd.Namespace = proxyNamespace; if (targetCoreClr) { var moonctx = new MoonlightChannelBaseContext (); cd.Behaviors.Add (new MoonlightChannelBaseContractExtension (moonctx, generateSyncMethods)); foreach (var od in cd.Operations) od.Behaviors.Add (new MoonlightChannelBaseOperationExtension (moonctx, generateSyncMethods)); generator.GenerateServiceContractType (cd); moonctx.Fixup (); } else generator.GenerateServiceContractType (cd); } string fileSpec = Path.Combine (basePath, referenceName + "." + code_provider.FileExtension); using (TextWriter w = File.CreateText (fileSpec)) { code_provider.GenerateCodeFromCompileUnit (ccu, w, null); } return fileSpec; }
public static void GenerateProxyAssembly(string url, string guid, bool fromUi = false) { TestSuite suite = TestPackage.Suites.Find(s => s.Guid == guid); if (suite == null && fromUi) { suite = new TestSuite() { ServiceUrl = url, BaseUrl = url, Wsdl = url + "?wsdl", Guid = guid }; TestPackage.Suites.Add(suite); url = suite.Wsdl; } StreamReader lResponseStream = GetHttpWebResponse(url); XmlTextReader xmlreader = new XmlTextReader(lResponseStream); //read the downloaded WSDL file ServiceDescription desc = ServiceDescription.Read(xmlreader); MetadataSection section = MetadataSection.CreateFromServiceDescription(desc); MetadataSet metaDocs = new MetadataSet(new[] { section }); WsdlImporter wsdlimporter = new WsdlImporter(metaDocs); //Add any imported files foreach (XmlSchema wsdlSchema in desc.Types.Schemas) { foreach (XmlSchemaObject externalSchema in wsdlSchema.Includes) { var import = externalSchema as XmlSchemaImport; if (import != null) { if (suite != null) { Uri baseUri = new Uri(suite.BaseUrl); if (string.IsNullOrEmpty(import.SchemaLocation)) continue; Uri schemaUri = new Uri(baseUri, import.SchemaLocation); StreamReader sr = GetHttpWebResponse(schemaUri.ToString()); XmlSchema schema = XmlSchema.Read(sr, null); wsdlimporter.XmlSchemas.Add(schema); } } } } //Additional check in case some services do not generate end points using generator for (int w = 0; w < wsdlimporter.WsdlDocuments.Count; w++) { for (int se = 0; se < wsdlimporter.WsdlDocuments[w].Services.Count; se++) { for (int po = 0; po < wsdlimporter.WsdlDocuments[w].Services[se].Ports.Count; po++) { // ReSharper disable once ForCanBeConvertedToForeach for (int ext = 0; ext < wsdlimporter.WsdlDocuments[w].Services[se].Ports[po].Extensions.Count; ext++) { switch (wsdlimporter.WsdlDocuments[w].Services[se].Ports[po].Extensions[ext].GetType().Name) { //BasicHttpBinding case "SoapAddressBinding": _endPointUrls.Add(((wsdlimporter.WsdlDocuments[w].Services[se].Ports[po])).Binding.Name, ((SoapAddressBinding)(wsdlimporter.WsdlDocuments[w].Services[se].Ports[po].Extensions[ext])).Location); if (suite != null && !suite.EndPoints.ContainsKey( ((wsdlimporter.WsdlDocuments[w].Services[se].Ports[po])).Binding.Name)) { suite.EndPoints.Add( ((wsdlimporter.WsdlDocuments[w].Services[se].Ports[po])).Binding.Name, ((SoapAddressBinding) (wsdlimporter.WsdlDocuments[w].Services[se].Ports[po].Extensions[ext])) .Location); suite.EndPointType.Add(((wsdlimporter.WsdlDocuments[w].Services[se].Ports[po])).Binding.Name, "BasicHttpBinding"); } break; //WSHttpBinding case "Soap12AddressBinding": _endPointUrls.Add(((wsdlimporter.WsdlDocuments[w].Services[se].Ports[po])).Binding.Name, ((SoapAddressBinding)(wsdlimporter.WsdlDocuments[w].Services[se].Ports[po].Extensions[ext])).Location); if (suite != null && !suite.EndPoints.ContainsKey( ((wsdlimporter.WsdlDocuments[w].Services[se].Ports[po])).Binding.Name)) { if (((SoapAddressBinding) (wsdlimporter.WsdlDocuments[w].Services[se].Ports[po].Extensions[ext])) .Location.ToLower().StartsWith("net.tcp")) { suite.EndPoints.Add( ((wsdlimporter.WsdlDocuments[w].Services[se].Ports[po])).Binding.Name, ((SoapAddressBinding) (wsdlimporter.WsdlDocuments[w].Services[se].Ports[po].Extensions[ext ])) .Location); suite.EndPointType.Add( ((wsdlimporter.WsdlDocuments[w].Services[se].Ports[po])).Binding.Name, "NetTcpBinding"); } else { suite.EndPoints.Add( ((wsdlimporter.WsdlDocuments[w].Services[se].Ports[po])).Binding.Name, ((SoapAddressBinding) (wsdlimporter.WsdlDocuments[w].Services[se].Ports[po].Extensions[ext ])) .Location); suite.EndPointType.Add( ((wsdlimporter.WsdlDocuments[w].Services[se].Ports[po])).Binding.Name, "WSHttpBinding"); } } break; case "XmlElement": break; } } } } } foreach (Import import in wsdlimporter.WsdlDocuments[0].Imports) { GenerateProxyAssembly(import.Location, guid); return; } XsdDataContractImporter xsd = new XsdDataContractImporter { Options = new ImportOptions { ImportXmlType = true, GenerateSerializable = true } }; xsd.Options.ReferencedTypes.Add(typeof(KeyValuePair<string, string>)); xsd.Options.ReferencedTypes.Add(typeof(List<KeyValuePair<string, string>>)); wsdlimporter.State.Add(typeof(XsdDataContractImporter), xsd); Collection<ContractDescription> contracts = wsdlimporter.ImportAllContracts(); ServiceEndpointCollection allEndpoints = wsdlimporter.ImportAllEndpoints(); // Generate type information for each contract. ServiceContractGenerator serviceContractGenerator = new ServiceContractGenerator(); foreach (var contract in contracts) { serviceContractGenerator.GenerateServiceContractType(contract); // Keep a list of each contract's endpoints. if (suite != null) { if (suite.EndpointsForContracts == null) suite.EndpointsForContracts = new Dictionary<string, List<EndpointsForContractsClass>>(); suite.EndpointsForContracts[contract.Name] = allEndpoints.Where(ep => ep.Contract.Name == contract.Name) .Select(ep => new EndpointsForContractsClass() { Uri = ep.Address.Uri.ToString(), Binding = ep.Binding }).ToList(); } } if (serviceContractGenerator.Errors.Count != 0) throw new Exception("There were errors during code compilation."); //Initialize the CODE DOM tree in which we will import the ServiceDescriptionImporter CodeNamespace nm = new CodeNamespace(); CodeCompileUnit unit = new CodeCompileUnit(); unit.Namespaces.Add(nm); CodeDomProvider compiler = CodeDomProvider.CreateProvider("C#"); // include the assembly references needed to compile var references = new[] { "System.Web.Services.dll", "System.Xml.dll", "System.ServiceModel.dll", "System.configuration.dll", "System.Runtime.Serialization.dll" }; var parameters = new CompilerParameters(references) { GenerateInMemory = true }; var results = compiler.CompileAssemblyFromDom(parameters, serviceContractGenerator.TargetCompileUnit); if (results.Errors.Cast<CompilerError>().Any()) { throw new Exception("Compilation Error Creating Assembly"); } // all done.... if (_assembly.ContainsKey(guid)) _assembly[guid] = results.CompiledAssembly; else _assembly.Add(guid, results.CompiledAssembly); if (_serviceInterface.ContainsKey(guid)) _serviceInterface[guid] = _assembly[guid].GetTypes()[0]; else _serviceInterface.Add(guid, _assembly[guid].GetTypes()[0]); }
protected override string CreateProxyFile (DotNetProject dotNetProject, FilePath basePath, string proxyNamespace, string referenceName) { CodeCompileUnit ccu = new CodeCompileUnit (); CodeNamespace cns = new CodeNamespace (proxyNamespace); ccu.Namespaces.Add (cns); bool targetMoonlight = dotNetProject.TargetFramework.Id.StartsWith ("SL"); bool targetMonoTouch = dotNetProject.TargetFramework.Id.StartsWith ("IPhone"); ServiceContractGenerator generator = new ServiceContractGenerator (ccu); generator.Options = ServiceContractGenerationOptions.ChannelInterface | ServiceContractGenerationOptions.ClientClass; if (refGroup.ClientOptions.GenerateAsynchronousMethods) generator.Options |= ServiceContractGenerationOptions.AsynchronousMethods; if (refGroup.ClientOptions.GenerateInternalTypes) generator.Options |= ServiceContractGenerationOptions.InternalTypes; if (refGroup.ClientOptions.GenerateMessageContracts) generator.Options |= ServiceContractGenerationOptions.TypedMessages; // if (targetMoonlight || targetMonoTouch) // generator.Options |= ServiceContractGenerationOptions.EventBasedAsynchronousMethods; MetadataSet mset; if (protocol != null) mset = ToMetadataSet (protocol); else mset = metadata; CodeDomProvider code_provider = GetProvider (dotNetProject); List<IWsdlImportExtension> list = new List<IWsdlImportExtension> (); list.Add (new TransportBindingElementImporter ()); list.Add (new XmlSerializerMessageContractImporter ()); WsdlImporter importer = new WsdlImporter (mset); Collection<ContractDescription> contracts = importer.ImportAllContracts (); foreach (ContractDescription cd in contracts) { cd.Namespace = proxyNamespace; if (targetMoonlight || targetMonoTouch) { var moonctx = new MoonlightChannelBaseContext (); cd.Behaviors.Add (new MoonlightChannelBaseContractExtension (moonctx, targetMonoTouch)); foreach (var od in cd.Operations) od.Behaviors.Add (new MoonlightChannelBaseOperationExtension (moonctx, targetMonoTouch)); generator.GenerateServiceContractType (cd); moonctx.Fixup (); } else generator.GenerateServiceContractType (cd); } string fileSpec = Path.Combine (basePath, referenceName + "." + code_provider.FileExtension); using (TextWriter w = File.CreateText (fileSpec)) { code_provider.GenerateCodeFromCompileUnit (ccu, w, null); } return fileSpec; }
protected void btnFetchRequests_Click(object sender, EventArgs e) { txtRequest.Text = string.Empty; txtResponse.Text = string.Empty; string wsdlUrl = txtUrl.Text; if (wsdlUrl != null && wsdlUrl != string.Empty && wsdlUrl.IndexOf("wsdl") != -1)// && ValidateRequestURL()) { lblWarning.Visible = false; try { WSHttpBinding binding = new WSHttpBinding(SecurityMode.None); binding.MaxReceivedMessageSize = 2147483647; MetadataExchangeClient metClient = new MetadataExchangeClient(binding); metClient.ResolveMetadataReferences = true; MetadataSet metSet = metClient.GetMetadata(new Uri(wsdlUrl), MetadataExchangeClientMode.HttpGet); WsdlImporter wsdlImporter = new WsdlImporter(metSet); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); ServiceContractGenerator generator = new ServiceContractGenerator(codeCompileUnit); Collection<ContractDescription> contracts = wsdlImporter.ImportAllContracts(); ServiceEndpointCollection endpoints = wsdlImporter.ImportAllEndpoints(); List<string> opsList = new List<string>(); string serviceName = string.Empty; string nameSpace = string.Empty; foreach (ContractDescription contract in contracts) { foreach (OperationDescription op in contract.Operations) { opsList.Add(op.Name); } generator.GenerateServiceContractType(contract); serviceName = contract.Name; nameSpace = contract.Namespace; break; } ddlOperations.DataSource = opsList; ddlOperations.DataBind(); ddlOperations.Visible = true; lblOperations.Visible = true; ViewState.Add("ServiceName", serviceName); ViewState.Add("Namespace", nameSpace); CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp"); StringWriter ws = new StringWriter(); provider1.GenerateCodeFromCompileUnit(codeCompileUnit, ws, new CodeGeneratorOptions()); string serverRoot = System.Configuration.ConfigurationManager.AppSettings["ServerRoot"]; string[] assemblyNames = new string[] { "System.Configuration.dll", "System.Xml.dll", Server.MapPath( serverRoot + "bin/") + "System.Runtime.Serialization.dll", "System.dll", "System.Web.Services.dll", "System.Data.dll", Server.MapPath( serverRoot + "bin/") + "System.ServiceModel.dll" }; CompilerParameters options = new CompilerParameters(assemblyNames); options.WarningLevel = 0; options.GenerateInMemory = true; string sourceCode = ws.ToString(); CompilerResults results = provider1.CompileAssemblyFromSource(options, sourceCode); if (!results.Errors.HasErrors) { Assembly compiledAssembly = results.CompiledAssembly; Type objClientType = compiledAssembly.GetType(serviceName); foreach (MethodInfo minfo in objClientType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)) { StringBuilder sb = new StringBuilder(); if (nameSpace != null && nameSpace != string.Empty) { sb.Append("<" + minfo.Name + " xmlns=\"" + nameSpace + "\">"); } else { sb.Append("<" + minfo.Name + ">"); } ParameterInfo[] paramInfos = minfo.GetParameters(); if (paramInfos != null && paramInfos.Length > 0) { foreach (ParameterInfo param in paramInfos) { ConstructorInfo cons = param.ParameterType.GetConstructor(new Type[] { }); if (cons != null) { if (param.ParameterType.IsSerializable) { sb.Append("<" + param.Name + ">"); object obj = cons.Invoke(new object[] { }); LoadPropertyMembers(obj, sb, compiledAssembly); sb.Append("</" + param.Name + ">"); } else { object obj = cons.Invoke(new object[] { }); LoadPropertyMembers(obj, sb, compiledAssembly); } } else { if (param.ParameterType.IsEnum) { sb.Append("<" + param.Name + ">"); object obj = Activator.CreateInstance(compiledAssembly.GetType(param.ParameterType.FullName)); sb.Append(obj.ToString()); sb.Append("</" + param.Name + ">"); } else if (param.ParameterType.IsValueType) { sb.Append("<" + param.Name + ">"); switch (param.ParameterType.Name) { case "Int16": case "Int32": case "Int64": case "Double": case "Decimal": sb.Append("0"); break; case "Boolean": sb.Append("false"); break; case "DateTime": sb.Append(DateTime.Now.ToString("yyyy-MM-dd")); break; } sb.Append("</" + param.Name + ">"); } else if (param.ParameterType.IsArray) { sb.Append("<" + param.Name + ">"); string propName = param.ParameterType.Name; propName = propName.Replace("[]", string.Empty); sb.Append("<" + propName + ">"); sb.Append("</" + propName + ">"); sb.Append("</" + param.Name + ">"); } else { sb.Append("<" + param.Name + ">"); sb.Append("</" + param.Name + ">"); } } } } sb.Append("</" + minfo.Name + ">"); string data = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"><soap:Body>"; data += sb.ToString(); data += "</soap:Body></soap:Envelope>"; ViewState.Add(minfo.Name + "Request", data); } txtRequest.Text = IndentXMLString(ViewState[ddlOperations.SelectedValue + "Request"].ToString()); ws.Flush(); ws.Close(); } else { lblWarning.Text = "There was an error in loading XML requests from the assembly." + "\n" + "You can still provide XML request by copy and pasting it in the Request textbox."; lblWarning.Visible = true; //ViewState.Clear(); } } catch (Exception ex) { lblWarning.Text = "Following error occured. " + ex.Message; lblWarning.Visible = true; ViewState.Clear(); return; } } else { lblWarning.Text = "Service URL is either empty or incorrect. Please provide a URL with \"wsdl\" extension. Example: http://servicename.com/service.svc?wsdl"; lblWarning.Visible = true; lblWarning.ForeColor = System.Drawing.Color.Red; txtRequest.Text = string.Empty; txtResponse.Text = string.Empty; ddlOperations.Items.Clear(); } }
public static CodeCompileUnit Import (MetadataSet metadata, ImportOptions options) { var importer = new WsdlImporter (metadata); var xsdImporter = new XsdDataContractImporter (); xsdImporter.Options = options; importer.State.Add (typeof(XsdDataContractImporter), xsdImporter); var contracts = importer.ImportAllContracts (); CodeCompileUnit ccu = new CodeCompileUnit (); var generator = new ServiceContractGenerator (ccu); if (contracts.Count != 1) throw new InvalidOperationException (string.Format ( "Metadata import failed: found {0} contracts.", contracts.Count)); var contract = contracts.First (); generator.GenerateServiceContractType (contract); return ccu; }
public AppDMoviesWSAutoDiscovery(string webserviceBindingUri, string interfaceContractName) { // 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(webserviceBindingUri); // For MEX endpoints use a MEX address and a mexMode of .MetadataExchange MetadataExchangeClientMode mexMode = MetadataExchangeClientMode.HttpGet; string contractName = interfaceContractName; //string creditcard, string expiry, string cvv // 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 ICommunicationObject) Type[] mytypes = results.CompiledAssembly.GetTypes(); Type clientProxyType = mytypes.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(); // Create an instance of the proxy // Pass the endpoint's binding and address as parameters // to the ctor proxyinstance = results.CompiledAssembly.CreateInstance( clientProxyType.Name, false, System.Reflection.BindingFlags.CreateInstance, null, new object[] { se.Binding, se.Address }, CultureInfo.CurrentCulture, null); } }
/// <summary> /// Generates the code. /// </summary> /// <param name="serviceDescription">The service description.</param> /// <returns>WebServiceClientCodeDto.</returns> /// <exception cref="VeyronException">Service endpoints not found.</exception> public WebServiceClientCodeDto GenerateCode(WebServiceDescription serviceDescription) { var result = new WebServiceClientCodeDto { ServiceId = serviceDescription.Id, ServiceGuid = serviceDescription.Guid }; using (var codeProvider = new CSharpCodeProvider()) { var metadataSections = new List<MetadataSection>(); metadataSections.AddRange(serviceDescription.XmlSchemas.Select(MetadataSection.CreateFromSchema)); metadataSections.AddRange(serviceDescription.ServiceDescriptions.Select(MetadataSection.CreateFromServiceDescription)); var @namespace = string.Format("sp_{0}", serviceDescription.Guid.ToString().Replace('-', '_')); var codeUnit = new CodeCompileUnit(); var importer = new WsdlImporter(new MetadataSet(metadataSections)); AddStateForXmlSerializerImport(importer, codeUnit, codeProvider, @namespace); AddStateForFaultSerializerImport(importer); RemoveDataContractSerializerExtension(importer); var endpoints = importer.ImportAllEndpoints(); if (endpoints.Count == 0) { if (importer.Errors.Any(e => !e.IsWarning)) throw new AggregateException("Service description import failed.", importer.Errors.Select(e => new Exception(e.Message))); throw new VeyronException("Service endpoints not found."); } var endpoint = endpoints[0]; var configDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Directory.CreateDirectory(configDirectory); var configPath = Path.Combine(configDirectory, "endpoints.config"); File.WriteAllText(configPath, EmptyConfiguration, Encoding.UTF8); var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = configPath }; var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); var contractGenerator = new ServiceContractGenerator(codeUnit, config); contractGenerator.NamespaceMappings.Add("*", @namespace); contractGenerator.Options = ServiceContractGenerationOptions.ClientClass | ServiceContractGenerationOptions.TypedMessages; contractGenerator.GenerateServiceContractType(endpoint.Contract); ChannelEndpointElement endpointElement; contractGenerator.GenerateServiceEndpoint(endpoint, out endpointElement); config.Save(); result.EndpointsConfiguration = File.ReadAllText(configPath); Directory.Delete(configDirectory, true); using (var stringWriter = new StringWriter()) { var options = new CodeGeneratorOptions { BracingStyle = "C" }; codeProvider.GenerateCodeFromCompileUnit(codeUnit, stringWriter, options); stringWriter.Flush(); result.Code = stringWriter.ToString(); return result; } } }
public void ImportMethodWithDateTime () { var ms = GetMetadataSetFromWsdl ("Test/Resources/DateTime.wsdl"); var imp = new WsdlImporter (ms); var cg = new ServiceContractGenerator (); var cd = imp.ImportAllContracts () [0]; cg.GenerateServiceContractType (cd); var sw = new StringWriter (); new CSharpCodeProvider ().GenerateCodeFromCompileUnit ( cg.TargetCompileUnit, sw, null); // sort of hacky test Assert.IsTrue (sw.ToString ().IndexOf ("System.DateTime GetDate") > 0, "#1"); }
/// <summary> /// Generate Proxy Code and (if available) configuration /// </summary> /// <param name="contractGenerator">The contract generator to use</param> /// <param name="targetCompileUnit">Compile unit into which we should generate the client code</param> /// <param name="proxyNamespace">CLR namespace into which we should generate the client code</param> /// <param name="configurationNamespace">Namespace to use in configuration</param> /// <param name="contractCollection">The contracts for which we should generate code and optionally config</param> /// <param name="bindingCollection">The bindings we should generate config for</param> /// <param name="serviceEndpointList">The endpoints we should generate config for</param> /// <param name="proxyGenerationErrors">A list of errors encountered while generating the client</param> /// <param name="serviceEndpointToChannelEndpointElementMap">Map from service endpoint to the configuration element for the endpoint</param> /// <param name="proxyGeneratedContractTypes">The generated contract types</param> protected static void GenerateProxy(WsdlImporter importer, ServiceContractGenerator contractGenerator, CodeCompileUnit targetCompileUnit, string proxyNamespace, string configurationNamespace, IEnumerable<ContractDescription> contractCollection, IEnumerable<System.ServiceModel.Channels.Binding> bindingCollection, List<ServiceEndpoint> serviceEndpointList, IList<ProxyGenerationError> proxyGenerationErrors, out Dictionary<ServiceEndpoint, ChannelEndpointElement> serviceEndpointToChannelEndpointElementMap, out List<GeneratedContractType> proxyGeneratedContractTypes) { // Parameter checking if (serviceEndpointList == null) throw new ArgumentNullException("serviceEndpointList"); if (bindingCollection == null) throw new ArgumentNullException("bindingCollection"); if (contractCollection == null) throw new ArgumentNullException("contractCollection"); if (proxyGenerationErrors == null) throw new ArgumentNullException("proxyGenerationErrors"); proxyGeneratedContractTypes = new List<GeneratedContractType>(); serviceEndpointToChannelEndpointElementMap = new Dictionary<ServiceEndpoint, ChannelEndpointElement>(); try { HttpBindingExtension httpBindingEx = importer.WsdlImportExtensions.Find<HttpBindingExtension>(); foreach (ContractDescription contract in contractCollection) { if (httpBindingEx == null || !httpBindingEx.IsHttpBindingContract(contract) || serviceEndpointList.Any(endpoint => endpoint.Contract == contract)) { CodeTypeReference typeReference = contractGenerator.GenerateServiceContractType(contract); if (typeReference != null) { // keep the (targetNamespace, portType) -> CLR type map table... string baseType = typeReference.BaseType; GeneratedContractType generatedType = new GeneratedContractType(contract.Namespace, contract.Name, baseType, baseType); proxyGeneratedContractTypes.Add(generatedType); } } } // We should only import the Binding & Endpoints if there is a configuration storage... if (contractGenerator.Configuration != null) { foreach (ServiceEndpoint endpoint in serviceEndpointList) { ChannelEndpointElement endpointElement = null; contractGenerator.GenerateServiceEndpoint(endpoint, out endpointElement); serviceEndpointToChannelEndpointElementMap[endpoint] = endpointElement; } foreach (System.ServiceModel.Channels.Binding bindingDescription in bindingCollection) { string bindingSectionName = null; string bindingConfigurationName = null; // Generate binding will change the state of the contractGenerator... contractGenerator.GenerateBinding(bindingDescription, out bindingSectionName, out bindingConfigurationName); } } PatchConfigurationName(proxyNamespace, configurationNamespace, proxyGeneratedContractTypes, serviceEndpointToChannelEndpointElementMap.Values, targetCompileUnit); } finally { foreach (MetadataConversionError error in contractGenerator.Errors) { proxyGenerationErrors.Add(new ProxyGenerationError(error)); } } }
/// <summary> /// compile our wsdl file /// </summary> /// <param name="astrWebServiceURI"></param> /// <param name="astrUsername"></param> /// <param name="astrPassword"></param> /// <param name="astrMethod"></param> /// <returns></returns> private compiledAssembly generateCompiledAssembly(string astrWebServiceURI, string astrUsername, string astrPassword, string astrMethod) { CompilerResults result = null; // Define the WSDL Get address, contract name and parameters, with this we can extract WSDL details any time //Uri address = new Uri("http://ifbenp.indfish.co.nz:16201/mws-ws/services/Vessel?wsdl"); //("http://localhost:64508/Service1.svc?wsdl"); Uri address = new Uri(astrWebServiceURI); // For HttpGet endpoints use a Service WSDL address a mexMode of .HttpGet and for MEX endpoints use a MEX address and a mexMode of .MetadataExchange MetadataExchangeClientMode mexMode = MetadataExchangeClientMode.HttpGet; // Get the metadata file from the service. MetadataExchangeClient metadataExchangeClient = new MetadataExchangeClient(address, mexMode); metadataExchangeClient.ResolveMetadataReferences = true; //One can also provide credentials if service needs that by the help following two lines. ICredentials networkCredential = new NetworkCredential(astrUsername, astrPassword, ""); metadataExchangeClient.HttpCredentials = networkCredential; //Gets the meta data information of the service. MetadataSet metadataSet = metadataExchangeClient.GetMetadata(); // Import all contracts and endpoints. WsdlImporter wsdlImporter = new WsdlImporter(metadataSet); //Import all contracts. Collection<ContractDescription> contracts = wsdlImporter.ImportAllContracts(); //Import all end points. ServiceEndpointCollection allEndpoints = wsdlImporter.ImportAllEndpoints(); // Generate type information for each contract. ServiceContractGenerator serviceContractGenerator = new ServiceContractGenerator(); //Dictinary has been defined to keep all the contract endpoints present, contract name is key of the dictionary item. var endpointsForContracts = new Dictionary<string, IEnumerable<ServiceEndpoint>>(); string contractName = null; foreach (ContractDescription contract in contracts) { serviceContractGenerator.GenerateServiceContractType(contract); // Keep a list of each contract's endpoints. endpointsForContracts[contract.Name] = allEndpoints.Where(ep => ep.Contract.Name == contract.Name).ToList(); contractName = contract.Name; } // Generate a code file for the contracts. CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions(); codeGeneratorOptions.BracingStyle = "C"; // Create Compiler instance of a specified language. CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("C#"); // Adding WCF-related assemblies references as copiler parameters, so as to do the compilation of particular service contract. CompilerParameters compilerParameters = new CompilerParameters(new string[] { "System.dll", "System.ServiceModel.dll", "System.Runtime.Serialization.dll" }); compilerParameters.GenerateInMemory = true; //Gets the compiled assembly. result = codeDomProvider.CompileAssemblyFromDom(compilerParameters, serviceContractGenerator.TargetCompileUnit); object proxyInstance = null; if (result.Errors.Count <= 0) { // Find the proxy type that was generated for the specified contract (identified by a class that implements the contract and ICommunicationbject - this is contract //implemented by all the communication oriented objects). Type proxyType = result.CompiledAssembly.GetTypes().First(t => t.IsClass && t.GetInterface(contractName) != null && t.GetInterface(typeof(ICommunicationObject).Name) != null); // Now we get the first service endpoint for the particular contract. ServiceEndpoint serviceEndpoint = endpointsForContracts[contractName].First(); BasicHttpBinding newBinding = new BasicHttpBinding(); newBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly; newBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; newBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None; newBinding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Default; newBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName; serviceEndpoint.Binding = newBinding; // Create an instance of the proxy by passing the endpoint binding and address as parameters. proxyInstance = result.CompiledAssembly.CreateInstance(proxyType.Name, false, System.Reflection.BindingFlags.CreateInstance, null, new object[] { serviceEndpoint.Binding, serviceEndpoint.Address }, CultureInfo.CurrentCulture, null); PropertyInfo clientCredentials = proxyType.GetProperty("ClientCredentials"); if(null != clientCredentials) { ClientCredentials credentials = new ClientCredentials(); credentials.UserName.UserName = astrUsername; credentials.UserName.Password = astrPassword; object objCredentials = clientCredentials.GetValue(proxyInstance); credentials = objCredentials as ClientCredentials; if (null != credentials) { credentials.UserName.Password = astrPassword; credentials.UserName.UserName = astrUsername; } } } compiledAssembly finalResults = new compiledAssembly() { compilerResults = result, instantiatedObject = proxyInstance }; return (finalResults); }