public OperationContractGenerationContext(ServiceContractGenerator serviceContractGenerator, ServiceContractGenerationContext contract, 
    OperationDescription operation, CodeTypeDeclaration declaringType, CodeMemberMethod method) : this(serviceContractGenerator, contract, operation, declaringType)
 {
     if (method == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("method"));
     }
     this.syncMethod = method;
     this.beginMethod = null;
     this.endMethod = null;
 }
 // Methods
 public ServiceContractGenerationContext(ServiceContractGenerator serviceContractGenerator, ContractDescription contract, CodeTypeDeclaration contractType)
 {
    this.operations = new Collection<OperationContractGenerationContext>();
    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;
 }
 // Methods
 private 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;
 }
Esempio n. 4
0
        //<snippet8>
        static void GenerateCSCodeForService(EndpointAddress metadataAddress, string outputFile)
        {
            //<snippet10>
            MetadataExchangeClient mexClient = new MetadataExchangeClient(metadataAddress);

            mexClient.ResolveMetadataReferences = true;
            MetadataSet metaDocs = mexClient.GetMetadata();

            WsdlImporter             importer  = new WsdlImporter(metaDocs);
            ServiceContractGenerator generator = new ServiceContractGenerator();
            //</snippet10>

            // Add our custom DCAnnotationSurrogate
            // to write XSD annotations into the comments.
            object dataContractImporter;
            XsdDataContractImporter xsdDCImporter;

            if (!importer.State.TryGetValue(typeof(XsdDataContractImporter), out dataContractImporter))
            {
                Console.WriteLine("Couldn't find the XsdDataContractImporter! Adding custom importer.");
                xsdDCImporter         = new XsdDataContractImporter();
                xsdDCImporter.Options = new ImportOptions();
                importer.State.Add(typeof(XsdDataContractImporter), xsdDCImporter);
            }
            else
            {
                xsdDCImporter = (XsdDataContractImporter)dataContractImporter;
                if (xsdDCImporter.Options == null)
                {
                    Console.WriteLine("There were no ImportOptions on the importer.");
                    xsdDCImporter.Options = new ImportOptions();
                }
            }
            xsdDCImporter.Options.DataContractSurrogate = new DCAnnotationSurrogate();

            // Uncomment the following code if you are going to do your work programmatically rather than add
            // the WsdlDocumentationImporters through a configuration file.

            /*
             * // <snippet11>
             * // The following code inserts a custom WsdlImporter without removing the other
             * // importers already in the collection.
             * System.Collections.Generic.IEnumerable<IWsdlImportExtension> exts = importer.WsdlImportExtensions;
             * System.Collections.Generic.List<IWsdlImportExtension> newExts
             * = new System.Collections.Generic.List<IWsdlImportExtension>();
             * foreach (IWsdlImportExtension ext in exts)
             * {
             * Console.WriteLine("Default WSDL import extensions: {0}", ext.GetType().Name);
             * newExts.Add(ext);
             * }
             * newExts.Add(new WsdlDocumentationImporter());
             * System.Collections.Generic.IEnumerable<IPolicyImportExtension> polExts = importer.PolicyImportExtensions;
             * importer = new WsdlImporter(metaDocs, polExts, newExts);
             * // </snippet11>
             */

            System.Collections.ObjectModel.Collection <ContractDescription> contracts
                = importer.ImportAllContracts();
            importer.ImportAllEndpoints();
            foreach (ContractDescription contract in contracts)
            {
                generator.GenerateServiceContractType(contract);
            }
            if (generator.Errors.Count != 0)
            {
                throw new Exception("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("C#");
            System.CodeDom.Compiler.IndentedTextWriter textWriter
                = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(outputFile));
            codeDomProvider.GenerateCodeFromCompileUnit(
                generator.TargetCompileUnit, textWriter, options
                );
            textWriter.Close();
        }
Esempio n. 5
0
        public string GenFromWsdl(
            string uri,
            bool createAsync,
            string targetNamespace,
            string outputFile,
            Boolean generateClient)
        {
            var pd = new prepareData();

            var msg = checkAndPrepareData(uri, outputFile, targetNamespace, pd);

            if (!msg.IsNullOrWhiteSpace())
            {
                return(msg);
            }


            MetadataSet mdSet = new MetadataSet();

            mdSet.MetadataSections.Add(MetadataSection.CreateFromServiceDescription(WebDescription.ServiceDescription.Read(pd.MainTempFile)));

            foreach (var item in pd.Imperts)
            {
                using (var xr = XmlReader.Create(item))
                    mdSet.MetadataSections.Add(MetadataSection.CreateFromSchema(XmlSchema.Read(xr, null)));
            }

            WsdlImporter importer = new WsdlImporter(mdSet);

            var xsdDCImporter = new XsdDataContractImporter();

            xsdDCImporter.Options = new ImportOptions();
            xsdDCImporter.Options.Namespaces.Add("*", pd.TargetCSNamespace);

            importer.State.Add(typeof(XsdDataContractImporter), xsdDCImporter);

            var xmlOptions = new XmlSerializerImportOptions();

            xmlOptions.ClrNamespace = pd.TargetCSNamespace;
            importer.State.Add(typeof(XmlSerializerImportOptions), xmlOptions);

            var generator = new ServiceContractGenerator();

            generator.NamespaceMappings.Add("*", pd.TargetCSNamespace);

            //var options = ServiceContractGenerationOptions.TypedMessages;
            var options = ServiceContractGenerationOptions.None;

            if (generateClient)
            {
                options |= ServiceContractGenerationOptions.ClientClass;
            }

            if (createAsync)
            {
                options |= ServiceContractGenerationOptions.TaskBasedAsynchronousMethod;
            }

            generator.Options = options;

            foreach (var contract in importer.ImportAllContracts())
            {
                generator.GenerateServiceContractType(contract);
            }

            if (generator.Errors.Count != 0)
            {
                return(generator.Errors.Select(x => x.Message).JoinValuesToString(separator: Environment.NewLine));
            }

            StringBuilder sb = new StringBuilder();

            using (var sw = new StringWriter(sb))
                CodeDomProvider.CreateProvider("C#")
                .GenerateCodeFromCompileUnit(
                    generator.TargetCompileUnit,
                    new IndentedTextWriter(sw),
                    new CodeGeneratorOptions()
                {
                    BracingStyle = "C"
                });

            File.WriteAllText(outputFile, sb.ToString());

            return(null);
        }
Esempio n. 6
0
        public DynamicProxyLoader(DiscoveryClientProtocol discoveryClient, Assembly assembly, byte[] assemblyBytes, String assemblyCode, String @namespace, DynamicProxyLoaderOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            Options = options;

            if (!String.IsNullOrEmpty(@namespace))
            {
                if (!options.Namespaces.ContainsKey("*"))
                {
                    options.Namespaces.Add("*", @namespace);
                }
                else
                {
                    options.Namespaces["*"] = @namespace;
                }
            }

            DiscoveryClient = discoveryClient;

            AssemblyBytes = assemblyBytes;
            AssemblyCode  = assemblyCode;
            Assembly      = assembly;

            codeDomProvider = CodeDomProvider.CreateProvider(options.Language.ToString());
            codeCompileUnit = new CodeCompileUnit();

            contractGenerator          = new ServiceContractGenerator(codeCompileUnit);
            contractGenerator.Options |= ServiceContractGenerationOptions.ClientClass;

            webReferenceOptions = new WebReferenceOptions();

            DownloadMetadata();
            ImportMetadata();
            CreateProxy();

            if (String.IsNullOrEmpty(assemblyCode))
            {
                GenerateProxyCode();
            }

            if (assembly == null && assemblyBytes != null)
            {
                Assembly = Assembly.Load(assemblyBytes);
            }
            else if (assembly != null && assemblyBytes == null)
            {
                AssemblyBytes = File.ReadAllBytes(Assembly.Location);
            }
            else if (Assembly == null && assemblyBytes == null)
            {
                CompileProxyCode();
            }

            ServiceContracts = new List <Type>();
            foreach (var contractDescription in ContractDescriptions)
            {
                var serviceContract = Assembly.GetType(contractDescription.Name);
                if (serviceContract != null)
                {
                    ServiceContracts.Add(serviceContract);

                    if (serviceContract.Name == ContractDescription.Name)
                    {
                        ServiceContract = serviceContract;
                    }
                }
            }
        }
Esempio n. 7
0
        protected override string CreateProxyFile(DotNetProject dotNetProject, FilePath basePath, string proxyNamespace, string referenceName)
        {
            CodeCompileUnit ccu = new CodeCompileUnit();
            CodeNamespace   cns = new CodeNamespace(proxyNamespace);

            ccu.Namespaces.Add(cns);

            bool targetMoonlight = dotNetProject.TargetFramework.Id.Identifier == ("Silverlight");
            bool targetMonoTouch = dotNetProject.TargetFramework.Id.Identifier == ("MonoTouch");
            bool targetMonoDroid = dotNetProject.TargetFramework.Id.Identifier == ("MonoDroid");

            ServiceContractGenerator generator = new ServiceContractGenerator(ccu);

            generator.Options = ServiceContractGenerationOptions.ChannelInterface | ServiceContractGenerationOptions.ClientClass;
            if (refGroup.ClientOptions.GenerateAsynchronousMethods || targetMoonlight || targetMonoTouch)
            {
                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);
        }
 public CodeTypeFactory(ServiceContractGenerator parent, bool internalTypes)
 {
     this.parent = parent;
     this.internalTypes = internalTypes;
 }
        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);
            }
        }
Esempio n. 10
0
        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)
            {
                if (co.GenerateMoonlightProxy)
                {
                    var moonctx = new MoonlightChannelBaseContext();
                    cd.Behaviors.Add(new MoonlightChannelBaseContractExtension(moonctx));
                    foreach (var od in cd.Operations)
                    {
                        od.Behaviors.Add(new MoonlightChannelBaseOperationExtension(moonctx));
                    }
                    generator.GenerateServiceContractType(cd);
                    moonctx.Fixup();
                }
                else
                {
                    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);
            }
        }
        public static Func <string, dynamic> Create(Uri uri)
        {
            var mexClient = new MetadataExchangeClient(uri, MetadataExchangeClientMode.HttpGet)
            {
                ResolveMetadataReferences = true
            };
            var metaDocs = mexClient.GetMetadata();

            var importer = new WsdlImporter(metaDocs);

            var contracts    = importer.ImportAllContracts();
            var allEndpoints = importer.ImportAllEndpoints();

            var generator = new ServiceContractGenerator(
                (CodeCompileUnit)importer.State[typeof(CodeCompileUnit)])
            {
                Options = ServiceContractGenerationOptions.TaskBasedAsynchronousMethod
                          | ServiceContractGenerationOptions.ChannelInterface
                          | ServiceContractGenerationOptions.ClientClass
            };

            foreach (var contract in contracts)
            {
                generator.GenerateServiceContractType(contract);
            }

            if (generator.Errors.Count != 0)
            {
                throw new Exception("There were errors during code generation.");
            }

            var codeDomProvider = CodeDomProvider.CreateProvider("C#");

#if DEBUG
            // Output source to file
            using (var textWriter = new IndentedTextWriter(new StreamWriter(@".\ProxyClient.g.cs")))
            {
                codeDomProvider.GenerateCodeFromCompileUnit(generator.TargetCompileUnit, textWriter, new CodeGeneratorOptions());
                textWriter.Flush();
            }
#endif

            var compiled = codeDomProvider.CompileAssemblyFromDom(
                options: new CompilerParameters
            {
                GenerateInMemory      = true,
                TreatWarningsAsErrors = false,
                TempFiles             = new TempFileCollection(@".")
                {
                    KeepFiles = false
                }
            },
                compilationUnits: generator.TargetCompileUnit);

            if (compiled.Errors.HasErrors)
            {
                throw new Exception("There were errors during code compilation");
            }

            var assembly = compiled.CompiledAssembly;

            return(contractName =>
            {
                var contract = contracts.First(c => c.Name == contractName);
                var endpoint = allEndpoints.First(ep => ep.Contract == contract);

                var clientProxyType = assembly.GetTypes().First(
                    t => t.IsClass &&
                    t.GetInterface(contract.Name) != null &&
                    t.GetInterface(typeof(ICommunicationObject).Name) != null);

                return assembly.CreateInstance(
                    typeName: clientProxyType.Name,
                    args: new object[] { endpoint.Binding, endpoint.Address },

                    ignoreCase: false,
                    bindingAttr: BindingFlags.Default,
                    binder: null,
                    culture: CultureInfo.CurrentCulture,
                    activationAttributes: new object[] { });
            });
        }
Esempio n. 12
0
 protected CodeFixup(ServiceContractGenerator generator)
 {
     this.generator = generator;
 }
Esempio n. 13
0
        /// <summary>
        /// Generates the service model client code for the metadat set.
        /// </summary>
        /// <param name="metaDocs">The metadata set document.</param>
        /// <param name="codeFile">The output file to write the code to.</param>
        public static void GenerateServiceModelClient(MetadataSet metaDocs, string codeFile)
        {
            // Make sure the page reference exists.
            if (metaDocs == null)
            {
                throw new ArgumentNullException("metaDocs");
            }
            if (codeFile == null)
            {
                throw new ArgumentNullException("codeFile");
            }

            WsdlImporter             importer  = new WsdlImporter(metaDocs);
            ServiceContractGenerator generator = new ServiceContractGenerator();

            // Add our custom DCAnnotationSurrogate
            // to write XSD annotations into the comments.
            object dataContractImporter;
            XsdDataContractImporter xsdDCImporter;

            if (!importer.State.TryGetValue(typeof(XsdDataContractImporter), out dataContractImporter))
            {
                xsdDCImporter         = new XsdDataContractImporter();
                xsdDCImporter.Options = new ImportOptions();
                importer.State.Add(typeof(XsdDataContractImporter), xsdDCImporter);
            }
            else
            {
                xsdDCImporter = (XsdDataContractImporter)dataContractImporter;
                if (xsdDCImporter.Options == null)
                {
                    xsdDCImporter.Options = new ImportOptions();
                }
            }

            // Get all the contract type bindings
            System.Collections.ObjectModel.Collection <ContractDescription> contracts = importer.ImportAllContracts();

            // Generate all the contracts
            foreach (ContractDescription contract in contracts)
            {
                generator.GenerateServiceContractType(contract);
            }

            if (generator.Errors.Count != 0)
            {
                throw new System.Exception("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.IndentedTextWriter textWriter = null;
            try
            {
                // Write data to the code file.
                System.CodeDom.Compiler.CodeDomProvider codeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("C#");
                textWriter = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(codeFile));
                codeDomProvider.GenerateCodeFromCompileUnit(generator.TargetCompileUnit, textWriter, options);
            }
            finally
            {
                if (textWriter != null)
                {
                    textWriter.Close();
                }
            }
        }
 internal ContextInitializer(ServiceContractGenerator parent, ServiceContractGenerator.CodeTypeFactory typeFactory)
 {
     this.parent = parent;
     this.typeFactory = typeFactory;
     this.asyncMethods = parent.OptionsInternal.IsSet(ServiceContractGenerationOptions.AsynchronousMethods);
 }
        public static CodeCompileUnit[] LoadSvcData(string[] serviceEndpoints, string globalNamespaceName)
        {
            var concurrentDic = new ConcurrentDictionary <string, CodeCompileUnit>();

            //var logWriter = new IndentedTextWriter(new StreamWriter(@"c:\\log2.txt"));

            foreach (var serviceEndpoint in serviceEndpoints)
            {
                Console.WriteLine($"{serviceEndpoint} start");
                MetadataSet            metadataSet   = null;
                Task <MetadataSet>     mexClientData = null;
                MetadataExchangeClient mexClient     = null;


                var serviceUri =
                    new Uri(serviceEndpoint);

                var isHttps          = 0 == serviceUri.ToString().IndexOf("https://", StringComparison.Ordinal);
                var basicHttpBinding = new BasicHttpBinding
                {
                    MaxReceivedMessageSize = int.MaxValue,
                    MaxBufferSize          = int.MaxValue,
                    OpenTimeout            = new TimeSpan(0, 0, 10, 0),
                    SendTimeout            = new TimeSpan(0, 0, 10, 0),
                    ReceiveTimeout         = new TimeSpan(0, 0, 10, 0),
                    CloseTimeout           = new TimeSpan(0, 0, 10, 0),
                    AllowCookies           = false,
                    ReaderQuotas           = new XmlDictionaryReaderQuotas
                    {
                        MaxNameTableCharCount  = int.MaxValue,
                        MaxStringContentLength = int.MaxValue,
                        MaxArrayLength         = 32768,
                        MaxBytesPerRead        = 4096,
                        MaxDepth = 32
                    },
                    Security =
                    {
                        Mode      = isHttps ? BasicHttpSecurityMode.Transport : BasicHttpSecurityMode.None,
                        Transport =
                        {
                            ClientCredentialType =
                                isHttps ? HttpClientCredentialType.Certificate : HttpClientCredentialType.Basic
                        }
                    }
                };

                mexClient =
                    new MetadataExchangeClient(basicHttpBinding)
                {
                    MaximumResolvedReferences = 1000,
                    HttpCredentials           = new NetworkCredential(GlobalConfig.SitLogin, GlobalConfig.SitPassword),
                    ResolveMetadataReferences = true
                };
                mexClientData = mexClient.GetMetadataAsync(serviceUri, MetadataExchangeClientMode.HttpGet);

                do
                {
                    try
                    {
                        mexClientData.Wait();
                        metadataSet = mexClientData.Result;
                    }
                    catch (Exception exc)
                    {
                        Console.WriteLine(exc.Message);
                        //Console.WriteLine(serviceUri.ToString());
                    }

                    //System.Threading.Thread.Sleep(1000);
                } while (mexClientData == null || metadataSet == null);

                object dataContractImporter;
                XsdDataContractImporter xsdDcImporter;
                var options = new ImportOptions();

                var wsdl = new WsdlImporter(metadataSet);
                if (!wsdl.State.TryGetValue(typeof(XsdDataContractImporter), out dataContractImporter))
                {
                    xsdDcImporter = new XsdDataContractImporter {
                        Options = options
                    };
                    wsdl.State.Add(typeof(XsdDataContractImporter), xsdDcImporter);
                }
                else
                {
                    xsdDcImporter = (XsdDataContractImporter)dataContractImporter;
                    if (xsdDcImporter.Options == null)
                    {
                        xsdDcImporter.Options = options;
                    }
                }

                //IEnumerable<IWsdlImportExtension> exts = wsdl.WsdlImportExtensions;
                var newExts = new List <IWsdlImportExtension>();

                newExts.AddRange(wsdl.WsdlImportExtensions);

                newExts.Add(new WsdlDocumentationImporter());
                IEnumerable <IPolicyImportExtension> polExts = wsdl.PolicyImportExtensions;

                wsdl = new WsdlImporter(metadataSet, polExts, newExts);

                var contracts = wsdl.ImportAllContracts();
                wsdl.ImportAllEndpoints();
                wsdl.ImportAllBindings();
                var generator = new ServiceContractGenerator();

                foreach (var contract in contracts)
                {
                    generator.GenerateServiceContractType(contract);

                    var nsname = GetHumanString(contract.Namespace);
                    generator.TargetCompileUnit.UserData.Add("ModuleName", nsname);
                    generator.TargetCompileUnit.UserData.Add("NamespaceName", globalNamespaceName.TrimEnd('.') + '.');
                    concurrentDic.TryAdd(nsname, generator.TargetCompileUnit);
                    //logWriter.WriteLine(nsname);
                }

                Console.WriteLine($"{serviceEndpoint} end");
            }

            //logWriter.Flush(); logWriter.Close();
            return(concurrentDic.Select(t => t.Value).ToArray());
        }
Esempio n. 16
0
 private void CreateServiceContractGenerator()
 {
     this.contractGenerator = new ServiceContractGenerator(
         this.codeCompileUnit);
     this.contractGenerator.Options |= ServiceContractGenerationOptions.ClientClass;
 }
Esempio n. 17
0
 void CreateServiceContractGenerator()
 {
     contractGenerator = new ServiceContractGenerator(
         codeCompileUnit);
     contractGenerator.Options |= ServiceContractGenerationOptions.ClientClass;
 }
 public ServiceContractGenerationContext(ServiceContractGenerator serviceContractGenerator, ContractDescription contract, CodeTypeDeclaration contractType, CodeTypeDeclaration duplexCallbackType)
    : this(serviceContractGenerator, contract, contractType)
 {
    this.duplexCallbackType = duplexCallbackType;
 }
        public List <ServiceInstance> CreateGenerator()
        {
            var serviceInstances = new List <ServiceInstance>();

            var metadataInfo = mMetadataLoader.GetMetadata();

            var serviceContractGenerator = new ServiceContractGenerator
            {
                Options = ServiceContractGenerationOptions.ClientClass
            };

            foreach (var contract in metadataInfo.Contracts)
            {
                serviceContractGenerator.GenerateServiceContractType(contract);
            }

            if (serviceContractGenerator.Errors.Count != 0)
            {
                throw new Exception("ServiceContractGenerator: " + serviceContractGenerator.Errors.ToString());
            }

            var codeDom          = CodeDomProvider.CreateProvider("C#");
            var generatorOptions = new CodeGeneratorOptions
            {
                BracingStyle = "C"
            };

            var codeDomProvider    = CodeDomProvider.CreateProvider("C#");
            var compilerParameters = new CompilerParameters(
                new string[]
            {
                "System.dll",
                "System.ServiceModel.dll",
                "System.Runtime.Serialization.dll"
            }
                );

            var results = codeDomProvider.CompileAssemblyFromDom(compilerParameters,
                                                                 serviceContractGenerator.TargetCompileUnit);

            var contractAssembly = Assembly.LoadFile(results.PathToAssembly);
            var list             = new List <object>();

            foreach (var contract in metadataInfo.Contracts)
            {
                var endpoint         = GetEndpoint(metadataInfo, contract);
                var serviceInterface = GetServiceInterface(contractAssembly, contract);
                var serviceInstance  = new ServiceInstance
                {
                    ServiceName      = serviceInterface.Name,
                    ServiceOprations = new List <Operation>()
                };

                var proxyInstance = CreateProxyInstance(contractAssembly, serviceInterface);

                var inst = results.CompiledAssembly.CreateInstance(proxyInstance.Name, false,
                                                                   BindingFlags.CreateInstance, null,
                                                                   new object[] { endpoint.Binding, endpoint.Address },
                                                                   CultureInfo.CurrentCulture, null);

                serviceInstance.Instance = inst;
                //Generate operation
                foreach (var operationName in contract.Operations.Select(x => x.Name).ToArray())
                {
                    serviceInstance.ServiceOprations.Add(ReflectionDetails.GenerateOperation(inst, operationName));
                }
                serviceInstances.Add(serviceInstance);
            }
            return(serviceInstances);
        }