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); } }
public static void GenerateConfig(MetadataSet metadata, Configuration config) { WsdlImporter importer = new WsdlImporter (metadata); var endpoints = importer.ImportAllEndpoints (); var generator = new ServiceContractGenerator (config); generator.Options = ServiceContractGenerationOptions.None; foreach (var endpoint in endpoints) { ChannelEndpointElement channelElement; generator.GenerateServiceEndpoint (endpoint, out channelElement); } }
/// <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)); } } }
private static string GenerateConfig(ServiceContractGenerator contractGenerator, IReadOnlyList<ServiceEndpoint> endpoints, string configFilePath) { for (int i = 0; i < endpoints.Count; i++) { ServiceEndpoint current = endpoints[i]; ChannelEndpointElement channelEndpointElement; contractGenerator.GenerateServiceEndpoint(current, out channelEndpointElement); } Configuration configuration = contractGenerator.Configuration; configuration.NamespaceDeclared = false; configuration.Save(); return File.ReadAllText(configFilePath); }
private void GenerateConfig( ServiceContractGenerator contractGenerator, ServiceEndpointCollection endpoints) { List<string> addedEndpoints = new List<string>(); foreach (ServiceEndpoint endpoint in endpoints) { // filter by endpoint address so we generate only the endpoint // that matches the endpoint names in ImportedEndpointNames if (!addedEndpoints.Contains(endpoint.Name) && (options.ImportedEndpointNames.Count == 0 || options.ImportedEndpointNames.Contains(endpoint.Name))) { // generate service endpoint ChannelEndpointElement channelElement; contractGenerator.GenerateServiceEndpoint(endpoint, out channelElement); this.generatedChannelElements.Add(channelElement); // generate the binding string bindingSectionName; string configurationName; contractGenerator.GenerateBinding(endpoint.Binding, out bindingSectionName, out configurationName); ThrowOnMetadataConversionErrors(contractGenerator.Errors); addedEndpoints.Add(endpoint.Name); } } // Save changes if specified. if (!string.IsNullOrEmpty(options.OutputConfigurationFile)) { configuration.Save(ConfigurationSaveMode.Modified); } }
/// <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); } }
/// <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 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; } } }