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); }
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(); }
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 ServiceMetadataInformation ImportMetadata(Collection<MetadataSection> metadataCollection, MetadataImporterSerializerFormatMode formatMode) { CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); CodeDomProvider codeDomProvider = m_CodeDomProviderFactory.CreateProvider(); WsdlImporter importer = new WsdlImporter(new MetadataSet(metadataCollection)); switch (formatMode) { case MetadataImporterSerializerFormatMode.DataContractSerializer: AddStateForDataContractSerializerImport(importer, formatMode, codeCompileUnit, codeDomProvider); break; case MetadataImporterSerializerFormatMode.XmlSerializer: AddStateForXmlSerializerImport(importer, codeCompileUnit, codeDomProvider); break; case MetadataImporterSerializerFormatMode.Auto: AddStateForDataContractSerializerImport(importer, formatMode, codeCompileUnit, codeDomProvider); AddStateForXmlSerializerImport(importer, codeCompileUnit, codeDomProvider); break; } if (!importer.State.ContainsKey(typeof(WrappedOptions))) { importer.State.Add(typeof(WrappedOptions), new WrappedOptions { WrappedFlag = false }); } Collection<Binding> bindings = importer.ImportAllBindings(); Collection<ContractDescription> contracts = importer.ImportAllContracts(); ServiceEndpointCollection endpoints = importer.ImportAllEndpoints(); Collection<MetadataConversionError> importErrors = importer.Errors; bool success = true; if (importErrors != null) { foreach (MetadataConversionError error in importErrors) { if (!error.IsWarning) { success = false; break; } } } if (!success) { //TODO: Throw exception } return new ServiceMetadataInformation(codeCompileUnit, codeDomProvider) { Bindings = bindings, Contracts = contracts, Endpoints = endpoints }; }
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 WebService(string path) { var metadataAddress = new EndpointAddress(path); var mexClient = new MetadataExchangeClient(metadataAddress.Uri, MetadataExchangeClientMode.HttpGet); mexClient.ResolveMetadataReferences = true; var metadata = mexClient.GetMetadata(metadataAddress.Uri, MetadataExchangeClientMode.HttpGet); var metadataSet = new MetadataSet(metadata.MetadataSections); var importer = new WsdlImporter(metadataSet); AllWsdlDocuments = importer.WsdlDocuments; AllContracts = importer.ImportAllContracts(); AllBindings = importer.ImportAllBindings(); AllEndpoints = importer.ImportAllEndpoints(); //AllContracts.First().Operations.First(). }
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; }
private void ImportMetadata(WsdlImporter wsdlImporter, out ServiceEndpointCollection endpoints, out Collection<System.ServiceModel.Channels.Binding> bindings, out Collection<ContractDescription> contracts) { endpoints = wsdlImporter.ImportAllEndpoints(); bindings = wsdlImporter.ImportAllBindings(); contracts = wsdlImporter.ImportAllContracts(); ThrowOnMetadataConversionErrors(wsdlImporter.Errors); }
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(); }
private void ImportMetadata() { this.codeCompileUnit = new CodeCompileUnit(); CreateCodeDomProvider(); WsdlImporter importer = new WsdlImporter(new MetadataSet(metadataCollection)); AddStateForDataContractSerializerImport(importer); AddStateForXmlSerializerImport(importer); this.bindings = importer.ImportAllBindings(); this.contracts = importer.ImportAllContracts(); this.endpoints = importer.ImportAllEndpoints(); this.importWarnings = importer.Errors; bool success = true; if (this.importWarnings != null) { foreach (MetadataConversionError error in this.importWarnings) { if (!error.IsWarning) { success = false; break; } } } if (!success) { DynamicProxyException exception = new DynamicProxyException( Constants.ErrorMessages.ImportError); exception.MetadataImportErrors = this.importWarnings; throw exception; } }
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; }
// Code to generate the proxy public static string GenerateCSCodeForService(string gennamespace, EndpointAddress metadataAddress) { var mexClient = new MetadataExchangeClient(metadataAddress.Uri, MetadataExchangeClientMode.HttpGet); mexClient.ResolveMetadataReferences = true; var metadata = mexClient.GetMetadata(metadataAddress.Uri, MetadataExchangeClientMode.HttpGet); var metadataSet = new MetadataSet(metadata.MetadataSections); var importer = new WsdlImporter(metadataSet); var importAllContracts = importer.ImportAllContracts(); var codeDomProvider = CodeDomProvider.CreateProvider("CSharp"); var output = new StringWriter(); return string.Empty; //importer.ImportAllBindings() //return codeDomExperiment(gennamespace, codeDomProvider, output, importAllContracts); // var generator = new ServiceContractGenerator(); // generator.Options = ServiceContractGenerationOptions.TypedMessages // //| ServiceContractGenerationOptions.AsynchronousMethods // //| ServiceContractGenerationOptions.ClientClass // //| ServiceContractGenerationOptions.EventBasedAsynchronousMethods // //| ServiceContractGenerationOptions.InternalTypes // ; // // This line enables a namespace wrapping all classes // generator.NamespaceMappings.Add("*", gennamespace); // //generator.NamespaceMappings.Add("?", gennamespace); // Contract descript namespace? // importer.State.Remove(typeof (XsdDataContractExporter)); // This doesn't do anything in the sample // // var importer2 = new XsdDataContractImporter(); // var options2 = new ImportOptions(); // options2.EnableDataBinding = true; // HERE we implement INotifyPropertyChanged // options2.GenerateInternal = false; // Control if class is internal // importer2.Options = options2; // importer2.Options.Namespaces.Add("*", gennamespace); // // Not used in sample but presumably allows array types to be mapped to a specific ienumerable<> // importer2.Options.ReferencedCollectionTypes.Add(typeof (ObservableCollection<>)); // // // Here we override the default importer with our own, // importer.State.Add(typeof (XsdDataContractImporter), importer2); // // // Collection<ContractDescription> collection = importer.ImportAllContracts(); // importer.ImportAllEndpoints(); // foreach (ContractDescription description in collection) // { // generator.GenerateServiceContractType(description); // } // if (generator.Errors.Count != 0) // { // generator.Errors.ToList().ForEach( // mce => Console.WriteLine("{0}: {1}", mce.IsWarning ? "Warning" : "Error", mce.Message)); // throw new Exception("There were errors during code compilation."); // } // //new WcfSilverlightCodeGenerationExtension().ClientGenerated(generator); // var options = new CodeGeneratorOptions(); // // var provider = CodeDomProvider.CreateProvider("C#"); // // var sb = new StringBuilder(); // var sw = new StringWriter(sb); // // using (var writer = new IndentedTextWriter(sw)) // { // provider.GenerateCodeFromCompileUnit(generator.TargetCompileUnit, writer, options); // } // // return sb.ToString(); }
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); } }
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 void ImportXmlTypes () { // part of bug #670945 var mset = new MetadataSet (); WSServiceDescription sd = null; sd = WSServiceDescription.Read (XmlReader.Create ("Test/XmlFiles/670945.wsdl")); mset.MetadataSections.Add (new MetadataSection () { Dialect = MetadataSection.ServiceDescriptionDialect, Metadata = sd }); var imp = new WsdlImporter (mset); var sec = imp.ImportAllContracts (); // FIXME: examine resulting operations. }
/// <summary> /// Checks if the specified url points to the load balancing service. /// </summary> /// <param name="serviceUrl">Url to check for service presence.</param> /// <returns>true if and only if the <paramref name="serviceUrl"/> /// points to the load balancing service.</returns> public static bool HasLoadBalanceService(string serviceUrl) { var hasService = false; try { var metadataUri = new Uri(serviceUrl + "?wsdl"); var mexClient = new MetadataExchangeClient( metadataUri, MetadataExchangeClientMode.HttpGet); var metadataRetrievalWrapper = new RetriableInvocationWrapper( MAX_RETRY_COUNT, _PrepareForRetry); var metaDocs = metadataRetrievalWrapper.Invoke( () => mexClient.GetMetadata()); var importer = new WsdlImporter(metaDocs); var contracts = importer.ImportAllContracts(); foreach (var contract in contracts) { if (string.Equals( contract.Name, LOAD_BALANCE_SERVICE_CONTRACT_NAME, StringComparison.InvariantCulture)) { hasService = true; break; } } } catch (InvalidOperationException e) { Logger.Warning(e); } catch (Exception e) { if (!ServiceHelper.IsCommunicationError(e)) { throw; } Logger.Warning(e); } return hasService; }
/// <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); }
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 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]); }
private void AssertMetadataForWsHttp(MetadataSet metadata) { WsdlImporter importer = new WsdlImporter(metadata); Collection<ContractDescription> contracts = importer.ImportAllContracts(); Collection<Binding> bindings = importer.ImportAllBindings(); ServiceEndpointCollection endpoints = importer.ImportAllEndpoints(); Assert.IsTrue(metadata.MetadataSections.Count == 4 || metadata.MetadataSections.Count == 5); Assert.AreEqual(0, importer.Errors.Count); Assert.AreEqual(1, contracts.Count); Assert.AreEqual(1, bindings.Count); Assert.AreEqual(1, endpoints.Count); Assert.AreEqual("IMyService", contracts[0].Name); Assert.AreEqual(typeof(WSHttpBinding), bindings[0].GetType()); }
/// <summary> /// Given a WSDL importer, a set of metadata files and a compile unit, import the metadata /// files. /// </summary> /// <param name="importer"></param> /// <param name="compileUnit"></param> /// <param name="generationErrors"> /// Errors encountered whie importing the model. Any new errors will be appended to this list. /// </param> /// <param name="serviceEndpointList">List of endpoints imported</param> /// <param name="bindingCollection">The collection of bindings imported</param> /// <param name="contractCollection">The collection of contracts imported</param> protected static void ImportWCFModel(WsdlImporter importer, System.CodeDom.CodeCompileUnit compileUnit, IList<ProxyGenerationError> generationErrors, out List<ServiceEndpoint> serviceEndpointList, out IEnumerable<System.ServiceModel.Channels.Binding> bindingCollection, out IEnumerable<ContractDescription> contractCollection) { // We want to remove soap1.2 endpoints for ASMX references, but we can't use the "normal" way // of using a IWsdlImportExtension to do so since BeforeImport is called too late (DevDiv 7857) // If DevDiv 7857 is fixed, we can remove the following two lines and instead add the // AsmxEndpointPickerExtension to the importer's wsdl import extensions... IWsdlImportExtension asmxFixerUpper = new AsmxEndpointPickerExtension(); asmxFixerUpper.BeforeImport(importer.WsdlDocuments, null, null); // NOTE: we should import Endpoint before Contracts, otherwise some information (related to binding) will be lost in the model (devdiv: 22396) serviceEndpointList = new List<ServiceEndpoint>(); // // First we import all the endpoints (ports). This is required so that any WsdlImportExtension's BeforeImport // gets called before we actually try to import anything from the WSDL object model. // If we don't do this, we run into problems if any wsdl import extensions want to delete a specific port // and this port happens to be the first port we try to import (you can't interrupt the import) importer.ImportAllEndpoints(); // // We need to go through each endpoint element and "re-import" it in order to get the mapping // between the wsdlPort and the ServiceEndpoint... Importing the same endpoint twice is a no-op // as far as the endpoint collection is concerned - it is simply a hashtable lookup to retreive // the already generated information... // foreach (System.Web.Services.Description.ServiceDescription wsdlServiceDescription in importer.WsdlDocuments) { foreach (System.Web.Services.Description.Service wsdlService in wsdlServiceDescription.Services) { foreach (System.Web.Services.Description.Port servicePort in wsdlService.Ports) { try { ServiceEndpoint newEndpoint = importer.ImportEndpoint(servicePort); serviceEndpointList.Add(newEndpoint); } catch (InvalidOperationException) { // Invalid operation exceptions should already be in the errors collection for the importer, so we don't // need to add another generationError. The most probable cause for this is that the we failed to import // the endpoint... } catch (Exception ex) { // It is bad, because WsdlImporter.WsdlImportException is a private class generationErrors.Add(new ProxyGenerationError(ProxyGenerationError.GeneratorState.GenerateCode, wsdlServiceDescription.RetrievalUrl, ex)); } } } } bindingCollection = importer.ImportAllBindings(); System.Diagnostics.Debug.Assert(bindingCollection != null, "The importer should never return a NULL binding collection!"); contractCollection = importer.ImportAllContracts(); System.Diagnostics.Debug.Assert(contractCollection != null, "The importer should never return a NULL contract collection!"); foreach (MetadataConversionError error in importer.Errors) { generationErrors.Add(new ProxyGenerationError(error)); } }
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"); }