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(); }
public ServiceContractGenerationContext ( ServiceContractGenerator serviceContractGenerator, ContractDescription contract, CodeTypeDeclaration contractType) : this (serviceContractGenerator, contract, contractType, null) { }
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); } }
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 OperationContractGenerationContext ( ServiceContractGenerator serviceContractGenerator, ServiceContractGenerationContext contract, OperationDescription operation, CodeTypeDeclaration declaringType, CodeMemberMethod method) : this (serviceContractGenerator, contract, operation, declaringType, method, null, null) { }
public ServiceContractGenerationContext ( ServiceContractGenerator serviceContractGenerator, ContractDescription contract, CodeTypeDeclaration contractType, CodeTypeDeclaration duplexCallbackType) { generator = serviceContractGenerator; this.contract = contract; contract_type = contractType; duplex_callback_type = duplexCallbackType; }
public OperationContractGenerationContext(ServiceContractGenerator serviceContractGenerator, ServiceContractGenerationContext contract, OperationDescription operation, CodeTypeDeclaration declaringType, CodeMemberMethod syncMethod, CodeMemberMethod taskMethod) : this(serviceContractGenerator, contract, operation, declaringType) { if (syncMethod == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("syncMethod")); if (taskMethod == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("taskMethod")); this.syncMethod = syncMethod; this.taskMethod = taskMethod; }
public ServiceContractGenerationContext(ServiceContractGenerator serviceContractGenerator, ContractDescription contract, CodeTypeDeclaration contractType) { if (serviceContractGenerator == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serviceContractGenerator")); if (contract == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("contract")); if (contractType == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("contractType")); this.serviceContractGenerator = serviceContractGenerator; this.contract = contract; this.contractType = contractType; }
OperationContractGenerationContext(ServiceContractGenerator serviceContractGenerator, ServiceContractGenerationContext contract, OperationDescription operation, CodeTypeDeclaration declaringType) { if (serviceContractGenerator == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serviceContractGenerator")); if (contract == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("contract")); if (declaringType == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("declaringType")); this.serviceContractGenerator = serviceContractGenerator; this.contract = contract; this.operation = operation; this.declaringType = declaringType; }
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); } }
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; }
public OperationContractGenerationContext ( ServiceContractGenerator serviceContractGenerator, ServiceContractGenerationContext contract, OperationDescription operation, CodeTypeDeclaration declaringType, CodeMemberMethod method, CodeMemberMethod beginMethod, CodeMemberMethod endMethod) { generator = serviceContractGenerator; this.contract = contract; this.operation = operation; declaring_type = declaringType; this.method = method; this.begin_method = beginMethod; this.end_method = endMethod; }
/// <summary> /// Builds a new instance. /// </summary> /// <param name="codeGeneratorContext">The code generator context.</param> /// <returns> /// A new <see cref="ServiceContractGenerator"/> instance. /// </returns> public ServiceContractGenerator Build(ICodeGeneratorContext codeGeneratorContext) { CodeGeneratorOptions codeGeneratorOptions = codeGeneratorContext.CodeGeneratorOptions; CodeCompileUnit codeCompileUnit = codeGeneratorContext.CodeCompileUnit; Configuration configuration = InitializeConfiguration(); ServiceContractGenerator contractGenerator = new ServiceContractGenerator(codeCompileUnit, configuration) { Options = generationOptionsBuilder.Build(codeGeneratorOptions) }; foreach (KeyValuePair<string, string> mapping in codeGeneratorOptions.NamespaceMappings) { contractGenerator.NamespaceMappings.Add(mapping.Key, mapping.Value); } return contractGenerator; }
void Run (string [] args) { co.ProcessArgs (args); if (co.RemainingArguments.Length == 0) co.DoHelp (); 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 (); code_provider = GetCodeProvider (); // For now only assemblyPath is supported. foreach (string arg in co.RemainingArguments) { FileInfo fi = new FileInfo (arg); if (!fi.Exists) throw new ArgumentException (String.Format ("File {0} not found.", fi.Name)); switch (fi.Extension) { case ".exe": case ".dll": GenerateContractType (fi.FullName); break; default: throw new NotSupportedException ("Not supported file extension: " + fi.Extension); } } if (cns.Types.Count == 0) { Console.Error.WriteLine ("Argument assemblies have no types."); Environment.Exit (1); } using (TextWriter w = File.CreateText (GetOutputFilename ())) { code_provider.GenerateCodeFromCompileUnit (ccu, w, null); } }
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; }
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; }
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(); }
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); } }
private void TweakServiceContractGenerator(ServiceContractGenerator scg) { // Do we have to genrate the async code? if (options.GenerateAsyncCode) { scg.Options |= ServiceContractGenerationOptions.AsynchronousMethods; } // Are we generating the service end code? if (options.GenerateService) { // Then turn off the channel interface and client class generation. scg.Options &= ~(ServiceContractGenerationOptions.ClientClass | ServiceContractGenerationOptions.ChannelInterface); } // Map all XML namespaces to default CLR namespace specified for the generated code. // This generates fully qualified type names in the method signatures. // And that is not compatible with some of the tweaks we do to the code later // with the decorators. Therefore switching back to namespace less code generation. // scg.NamespaceMappings.Add("*", options.ClrNamespace); }
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); } }
internal ContextInitializer(ServiceContractGenerator parent, ServiceContractGenerator.CodeTypeFactory typeFactory) { this.parent = parent; this.typeFactory = typeFactory; this.asyncMethods = parent.OptionsInternal.IsSet(ServiceContractGenerationOptions.AsynchronousMethods); }
public ServiceContractGenerationContext(ServiceContractGenerator serviceContractGenerator, ContractDescription contract, System.CodeDom.CodeTypeDeclaration contractType) { }
private void SetContractGeneratorOptions(ContractGenerationOptions options, ServiceContractGenerator contractGenerator) { if (options.GenerateAsyncMethods) { contractGenerator.Options |= ServiceContractGenerationOptions.AsynchronousMethods; } else { contractGenerator.Options &= ~ServiceContractGenerationOptions.AsynchronousMethods; } if (options.GenerateInternalTypes) { contractGenerator.Options |= ServiceContractGenerationOptions.InternalTypes; } else { contractGenerator.Options &= ~ServiceContractGenerationOptions.InternalTypes; } if (options.GenerateTypedMessages) { contractGenerator.Options |= ServiceContractGenerationOptions.TypedMessages; } else { contractGenerator.Options &= ~ServiceContractGenerationOptions.TypedMessages; } if (options.GenerateChannelInterface) { contractGenerator.Options |= ServiceContractGenerationOptions.ChannelInterface; } else { contractGenerator.Options &= ~ServiceContractGenerationOptions.ChannelInterface; } if (options.GenerateClientClass) { contractGenerator.Options |= ServiceContractGenerationOptions.ClientClass; } else { contractGenerator.Options &= ~ServiceContractGenerationOptions.ClientClass; } }
private void AddReferencedTypesAndKnownContracts( ContractGenerationOptions options, WsdlImporter wsdlImporter, ServiceContractGenerator contractGenerator) { foreach (Type type in options.ReferencedTypes) { if (type.IsDefined(typeof(ServiceContractAttribute), false)) { try { ContractDescription contractDescription = ContractDescription.GetContract(type); XmlQualifiedName xmlName = new XmlQualifiedName(contractDescription.Name, contractDescription.Namespace); wsdlImporter.KnownContracts.Add(xmlName, contractDescription); contractGenerator.ReferencedTypes.Add(contractDescription, type); continue; } catch (Exception exception) { throw new TypeLoadException( string.Format(CultureInfo.CurrentCulture, Properties.Resources.ErrUnableToLoadReferenceType, type.AssemblyQualifiedName), exception); } } } }
/// <summary> /// Instantiate and configure a ServiceContractGenerator to be used for code and config /// generation. /// </summary> /// <param name="proxyOptions"> /// Options set in the SvcMap file to control the code/config generation. /// </param> /// <param name="wsdlImporter"> /// The WsdlImporter that is to be used to import the metadata for this service reference. /// </param> /// <param name="targetCompileUnit"> /// Compile unit into which we will generate the client code /// </param> /// <param name="proxyNamespace"> /// The CLR namespace into which we will generate the client code. /// </param> /// <param name="targetConfiguration"> /// Optional configuration into which we will generate the endpoints/bindings corresponding /// to this service reference. May be Null/Nothing, in which case we will not generate config. /// </param> /// <param name="typeLoader"> /// Type loader that can be used to find reference assemblies and/or resolve shared service and /// data contract types. /// </param> /// <param name="targetFrameworkVersion"> /// The target framework version number. The higher 16 bits contains the major version number, and low 16 bits contains minor version number. /// </param> /// <param name="importErrors"> /// The list into which we will add any errors while importing the metadata. /// </param> /// <returns></returns> protected static ServiceContractGenerator CreateContractGenerator(ClientOptions proxyOptions, WsdlImporter wsdlImporter, CodeCompileUnit targetCompileUnit, string proxyNamespace, System.Configuration.Configuration targetConfiguration, IContractGeneratorReferenceTypeLoader typeLoader, int targetFrameworkVersion, IList<ProxyGenerationError> importErrors) { ServiceContractGenerator contractGenerator = new ServiceContractGenerator(targetCompileUnit, targetConfiguration); // We want to generate all types into the proxy namespace CLR namespace. We indicate // this by adding a namespace mapping from all XML namespaces ("*") to the namespace // the caller told us to generate the client code in. contractGenerator.NamespaceMappings.Add("*", proxyNamespace); if (proxyOptions.GenerateInternalTypes) { contractGenerator.Options |= ServiceContractGenerationOptions.InternalTypes; } else { contractGenerator.Options &= ~ServiceContractGenerationOptions.InternalTypes; } // Make sure at most one of the async options will be set: AsynchronousMethods | TaskBasedAsynchronousMethod. contractGenerator.Options &= ~ServiceContractGenerationOptions.AsynchronousMethods & ~ServiceContractGenerationOptions.EventBasedAsynchronousMethods & ~ServiceContractGenerationOptions.TaskBasedAsynchronousMethod; if (proxyOptions.GenerateTaskBasedAsynchronousMethod) { contractGenerator.Options |= ServiceContractGenerationOptions.TaskBasedAsynchronousMethod; } else if (proxyOptions.GenerateAsynchronousMethods) { contractGenerator.Options |= ServiceContractGenerationOptions.AsynchronousMethods; if (targetFrameworkVersion >= FRAMEWORK_VERSION_35) { contractGenerator.Options |= ServiceContractGenerationOptions.EventBasedAsynchronousMethods; } } if (proxyOptions.GenerateMessageContracts) { contractGenerator.Options |= ServiceContractGenerationOptions.TypedMessages; } else { contractGenerator.Options &= ~ServiceContractGenerationOptions.TypedMessages; } // If we have a type loader, we tell the contract generator and wsdl importer about // all shared types and assemblies that we've specified in the proxy options... if (typeLoader != null) { foreach (ContractMapping mapping in proxyOptions.ServiceContractMappingList) { try { Type sharedType = typeLoader.LoadType(mapping.TypeName); // verify that the type is shareable - if not, we generate an error... if (!IsTypeShareable(sharedType)) { importErrors.Add( new ProxyGenerationError( ProxyGenerationError.GeneratorState.GenerateCode, String.Empty, new FormatException(String.Format(CultureInfo.CurrentCulture, WCFModelStrings.ReferenceGroup_SharedTypeMustBePublic, mapping.TypeName))) ); continue; } // Get a contract description corresponding to the type we wanted to share ContractDescription contract = ContractDescription.GetContract(sharedType); if (!String.Equals(mapping.Name, contract.Name, StringComparison.Ordinal) || !String.Equals(mapping.TargetNamespace, contract.Namespace, StringComparison.Ordinal)) { // mismatch importErrors.Add( new ProxyGenerationError( ProxyGenerationError.GeneratorState.GenerateCode, String.Empty, new FormatException(String.Format(CultureInfo.CurrentCulture, WCFModelStrings.ReferenceGroup_ServiceContractMappingMissMatch, mapping.TypeName, contract.Namespace, contract.Name, mapping.TargetNamespace, mapping.Name))) ); } XmlQualifiedName qname = new XmlQualifiedName(contract.Name, contract.Namespace); wsdlImporter.KnownContracts.Add(qname, contract); contractGenerator.ReferencedTypes.Add(contract, sharedType); } catch (Exception ex) { importErrors.Add(new ProxyGenerationError( ProxyGenerationError.GeneratorState.GenerateCode, String.Empty, ex)); } } } foreach (NamespaceMapping namespaceMapping in proxyOptions.NamespaceMappingList) { contractGenerator.NamespaceMappings.Add(namespaceMapping.TargetNamespace, namespaceMapping.ClrNamespace); } return contractGenerator; }
private ServiceContractGenerator CreateServiceContractGenerator(ContractGenerationOptions options, System.Configuration.Configuration inputConfiguration, CodeCompileUnit codeCompileUnit) { ServiceContractGenerator generator = new ServiceContractGenerator(codeCompileUnit, inputConfiguration); SetContractGeneratorOptions(options, generator); foreach (KeyValuePair<string, string> pair in options.NamespaceMappings) { generator.NamespaceMappings.Add(pair.Key, pair.Value); } return generator; }
public OperationContractGenerationContext(ServiceContractGenerator serviceContractGenerator, ServiceContractGenerationContext contract, OperationDescription operation, System.CodeDom.CodeTypeDeclaration declaringType, System.CodeDom.CodeMemberMethod syncMethod, System.CodeDom.CodeMemberMethod beginMethod, System.CodeDom.CodeMemberMethod endMethod) { }
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); }
public ServiceContractGenerationContext(ServiceContractGenerator serviceContractGenerator, ContractDescription contract, CodeTypeDeclaration contractType, CodeTypeDeclaration duplexCallbackType) : this(serviceContractGenerator, contract, contractType) { this.duplexCallbackType = duplexCallbackType; }
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]); }
public CodeTypeFactory(ServiceContractGenerator parent, bool internalTypes) { this.parent = parent; this.internalTypes = internalTypes; }
/// <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)); } } }
public ServiceContractGenerationContext(ServiceContractGenerator serviceContractGenerator, ContractDescription contract, CodeTypeDeclaration contractType, CodeTypeDeclaration duplexCallbackType) : this(serviceContractGenerator, contract, contractType) { _duplexCallbackType = duplexCallbackType; }