private Dictionary <string, IEnumerable <ServiceEndpoint> > GetEndPointsOfEachServiceContract(WsdlImporter imptr, Collection <ContractDescription> svcCtrDescs)
        {
            ServiceEndpointCollection allEP = imptr.ImportAllEndpoints();
            var ctrEP = new Dictionary <string, IEnumerable <ServiceEndpoint> >();

            foreach (ContractDescription svcCtrDesc in svcCtrDescs)
            {
                List <ServiceEndpoint> eps = allEP.Where(x => x.Contract.Name == svcCtrDesc.Name).ToList();
                ctrEP.Add(svcCtrDesc.Name, eps);
            }
            return(ctrEP);
        }
Beispiel #2
0
        }     //end subtraction webservice Invoke function..

        private void calculateMultiplication(Uri multiplicationServiceURI, Multiplication.MathData[] cmplxTyp_ip)
        {
            try
            {
                Uri mexAddress = multiplicationServiceURI;
                MetadataExchangeClientMode mexMode = MetadataExchangeClientMode.HttpGet;
                string contractName   = "IMultiplication";
                string operationName  = "GetDataUsingDataContract";
                string operationName1 = "MultiplyArray";

                Multiplication.CompositeType ip = new Multiplication.CompositeType()
                {
                    BoolValue   = true,
                    StringValue = "---test string--"
                };

                object[] operationParameters  = new object[] { ip };
                object[] operationParameters1 = new object[] { cmplxTyp_ip };

                MetadataExchangeClient mexClient = new MetadataExchangeClient(mexAddress, mexMode);
                mexClient.ResolveMetadataReferences = true;
                MetadataSet metaSet = mexClient.GetMetadata();

                WsdlImporter importer = new WsdlImporter(metaSet);
                //BEGIN INSERT
                XsdDataContractImporter xsd = new XsdDataContractImporter();
                xsd.Options = new ImportOptions();
                xsd.Options.ImportXmlType        = true;
                xsd.Options.GenerateSerializable = true;
                //xsd.Options.ReferencedTypes.Add(typeof(KeyValuePair<string, string>));
                //xsd.Options.ReferencedTypes.Add(typeof(System.Collections.Generic.List<KeyValuePair<string, string>>));

                xsd.Options.ReferencedTypes.Add(typeof(Multiplication.CompositeType));
                xsd.Options.ReferencedTypes.Add(typeof(Multiplication.MathData));
                xsd.Options.ReferencedTypes.Add(typeof(System.Collections.Generic.List <Multiplication.MathData>));


                importer.State.Add(typeof(XsdDataContractImporter), xsd);
                //END INSERT


                Collection <ContractDescription> contracts    = importer.ImportAllContracts();
                ServiceEndpointCollection        allEndpoints = importer.ImportAllEndpoints();

                ServiceContractGenerator generator = new ServiceContractGenerator();
                var endpointsForContracts          = new Dictionary <string, IEnumerable <ServiceEndpoint> >();

                foreach (ContractDescription contract in contracts)
                {
                    generator.GenerateServiceContractType(contract);
                    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.");
                }

                CodeGeneratorOptions options = new CodeGeneratorOptions();
                options.BracingStyle = "C";
                CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("C#");

                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
                {
                    Type clientProxyType = results.CompiledAssembly.GetTypes().First(
                        t => t.IsClass &&
                        t.GetInterface(contractName) != null &&
                        t.GetInterface(typeof(ICommunicationObject).Name) != null);

                    ServiceEndpoint se = endpointsForContracts[contractName].First();

                    object instance = results.CompiledAssembly.CreateInstance(
                        clientProxyType.Name,
                        false,
                        System.Reflection.BindingFlags.CreateInstance,
                        null,
                        new object[] { se.Binding, se.Address },
                        CultureInfo.CurrentCulture, null);


                    var methodInfo  = instance.GetType().GetMethod(operationName);
                    var methodInfo1 = instance.GetType().GetMethod(operationName1);

                    object  retVal  = methodInfo.Invoke(instance, BindingFlags.InvokeMethod, null, operationParameters, null);
                    dynamic retVal1 = methodInfo1.Invoke(instance, BindingFlags.InvokeMethod, null, operationParameters1, null);
                    Console.WriteLine(retVal.ToString());

                    for (int x = 0; x < cmplxTyp_ip.Length; x++)
                    {
                        Console.WriteLine(" --Multiplication output RECORD {0 } ----", x);
                        Console.WriteLine(" FArg1 *farg2 : {0 } ", retVal1[x].FRsltArg);
                        Console.WriteLine(" strFArg1 * arg2 : {0 }", retVal1[x].StrConcatRslt);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            } //end of mex binding try block
        }     //end of MULTIPLICATION webservice Invoke function...
Beispiel #3
0
        private object GetProxyInstance(ref CompilerResults compilerResults, string url_servicio, string contractName)
        {
            try
            {
                // Definir el WSDL Obtener la dirección, el nombre del contrato y los parámetros, con esto podemos extraer los detalles del WSDL en cualquier momento
                object proxyInstance = null;

                // Para los puntos finales HttpGet use una dirección WSDL de servicio un mexMode de .HttpGet y para los puntos finales MEX use una dirección MEX y un mexMode de .MetadataExchange
                Uri address = new Uri(url_servicio);

                MetadataExchangeClientMode mexMode = MetadataExchangeClientMode.HttpGet;

                // Obtenga el archivo de metadatos del servicio.
                MetadataExchangeClient metadataExchangeClient = new MetadataExchangeClient(address, mexMode);

                metadataExchangeClient.ResolveMetadataReferences = true;

                // También se pueden proporcionar credenciales si el servicio lo necesita con ayuda de dos líneas.   ICredentials networkCredential = new NetworkCredential("", "", ""); metadataExchangeClient.HttpCredentials = networkCredential;
                // Obtiene la información de metadatos del servicio.
                MetadataSet metadataSet = metadataExchangeClient.GetMetadata();

                // Importar todos los contratos y endpoints.
                WsdlImporter wsdlImporter = new WsdlImporter(metadataSet);

                // Importar todos los contratos.
                Collection <ContractDescription> contracts = wsdlImporter.ImportAllContracts();

                //importa todos los endpoints.
                ServiceEndpointCollection allEndpoints = wsdlImporter.ImportAllEndpoints();

                // Generar información de tipo para cada contrato.
                ServiceContractGenerator serviceContractGenerator = new ServiceContractGenerator();

                //Dictionary se ha definido para mantener todos los puntos finales del contrato presentes el nombre del contrato es la clave del elemento del diccionario.
                var endpointsForContracts = new Dictionary <string, IEnumerable <ServiceEndpoint> >();

                foreach (ContractDescription contract in contracts)
                {
                    serviceContractGenerator.GenerateServiceContractType(contract);

                    // lista de los EndPoints de cada contrato.
                    endpointsForContracts[contract.Name] = allEndpoints.Where(ep => ep.Contract.Name == contract.Name).ToList();
                }

                // Genera un archivo de código para los contratos.
                CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions();
                codeGeneratorOptions.BracingStyle = "C";

                // Crea una instancia de compilación de un idioma específico.
                CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("C#");

                // Agrega WCF-related assemblies references as copiler parameters, para hacer la compilación de un contrato de servicio particular.
                CompilerParameters compilerParameters = new CompilerParameters(new string[] { "System.dll", "System.ServiceModel.dll", "System.Runtime.Serialization.dll" });

                compilerParameters.GenerateInMemory = true;

                // Obtiene el ensamblado compilado.
                compilerResults = codeDomProvider.CompileAssemblyFromDom(compilerParameters, serviceContractGenerator.TargetCompileUnit);

                if (compilerResults.Errors.Count <= 0)
                {
                    // Encuentra el tipo de proxy que se generó para el contrato especificado.
                    Type proxyType = compilerResults.CompiledAssembly.GetTypes().First(t => t.IsClass && t.GetInterface(contractName) != null &&
                                                                                       t.GetInterface(typeof(ICommunicationObject).Name) != null);

                    // Ahora obtenemos el primer punto final de servicio para el contrato particular.
                    ServiceEndpoint serviceEndpoint = endpointsForContracts[contractName].First();

                    // Crea una instancia del proxy pasando el enlace y la dirección del endpoint como parámetros.
                    proxyInstance = compilerResults.CompiledAssembly.CreateInstance(proxyType.Name, false, System.Reflection.BindingFlags.CreateInstance, null,
                                                                                    new object[] { serviceEndpoint.Binding, serviceEndpoint.Address }, CultureInfo.CurrentCulture, null);
                }
                return(proxyInstance);
            }
            catch (Exception ex)
            {
                Tracking("GetProxyInstance Error: " + ex.Message + " Nro# " + eventId);

                eventLog1.WriteEntry("GetProxyInstance Error: " + ex.Message + " Nro# " + eventId, EventLogEntryType.Error, eventId);

                throw ex;
            }
        }
        /// <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);
        }
Beispiel #5
0
        private DataTable GetDataFromMethod(string Uri, string endpointAddress, BasicHttpBinding basicHttpBinding, string contractname, string methodName, object[] paramArray)
        {
            DataTable dt         = null;
            Uri       mexAddress = new Uri(Uri);
            MetadataExchangeClientMode mexMode = MetadataExchangeClientMode.HttpGet;
            string contractName = contractname;



            // 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 ICommunicationbject)
                Type clientProxyType = results.CompiledAssembly.GetTypes()
                                       .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();
                EndpointAddress endPoint = new EndpointAddress(endpointAddress);
                se.Address = endPoint;
                se.Binding = basicHttpBinding;


                // Create an instance of the proxy
                // Pass the endpoint's binding and address as parameters
                // to the ctor
                object instance = results.CompiledAssembly.CreateInstance(
                    clientProxyType.Name,
                    false,
                    System.Reflection.BindingFlags.CreateInstance,
                    null,
                    new object[] { se.Binding, se.Address },
                    CultureInfo.CurrentCulture, null);



                try
                {
                    var retVal = (IEnumerable <Object>)instance.GetType().GetMethod(methodName).Invoke(instance, paramArray);


                    if (retVal != null)
                    {
                        dt = HelperMethods.GetDataTableFromObjects(retVal.ToArray());
                        if (dt != null)
                        {
                            dt.Columns.Remove("ExtensionData");
                        }
                        else
                        {
                            log.Warn(string.Format("Wed Feed: Dataset empty for {0}", methodName));
                        }
                    }
                    else
                    {
                        dt = null;
                    }
                }
                catch (Exception exp)
                {
                    // File.WriteAllText();
                    log.Error(string.Format("Error Occured Operation: {0}", methodName), exp);
                }
            }



            return(dt);
        }
Beispiel #6
0
        private object GetProxyInstance(ref CompilerResults compilerResults)
        {
            object proxyInstance = null;

            // Define the WSDL Get address, contract name and parameters, with this we can extract WSDL details any time
            Uri address = new Uri("http://localhost:15277/ServiceArea.svc?wsdl");
            // 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;
            string contractName = "IServiceArea";

            // 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("", "", "");
            //metadataExchangeClient.HttpCredentials = networkCredential;
            metadataExchangeClient.MaximumResolvedReferences = 200;
            //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> >();

            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();
            }

            // 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.
            compilerResults = codeDomProvider.CompileAssemblyFromDom(compilerParameters, serviceContractGenerator.TargetCompileUnit);

            if (compilerResults.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 = compilerResults.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();

                // Create an instance of the proxy by passing the endpoint binding and address as parameters.
                proxyInstance = compilerResults.CompiledAssembly.CreateInstance(proxyType.Name, false, BindingFlags.CreateInstance, null,
                                                                                new object[] { serviceEndpoint.Binding, serviceEndpoint.Address }, CultureInfo.CurrentCulture, null);
            }

            return(proxyInstance);
        }
        public object CreateDynamicClientProxy(string ResourceUrl)
        {
            if (!ResourceUrl.EndsWith("?wsdl", true, CultureInfo.CurrentCulture))
            {
                ResourceUrl = string.Concat(ResourceUrl, "?wsdl");
            }
            HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(ResourceUrl);

            httpWebRequest.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            System.IO.Stream stream = httpWebResponse.GetResponseStream();

            //read the downloaded WSDL file
            System.Web.Services.Description.ServiceDescription serviceDescription = System.Web.Services.Description.ServiceDescription.Read(stream);

            Uri mexAddress = new Uri(ResourceUrl);
            MetadataExchangeClientMode mexMode = MetadataExchangeClientMode.HttpGet;

            MetadataExchangeClient mexClient = new MetadataExchangeClient(mexAddress, mexMode);

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

            WsdlImporter importer = new WsdlImporter(metaSet);
            Collection <ContractDescription> contracts    = importer.ImportAllContracts();
            ServiceEndpointCollection        allEndpoints = importer.ImportAllEndpoints();

            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 ICommunicationbject)
                Type clientProxyType = results.CompiledAssembly.GetTypes().First(
                    t => t.IsClass &&
                    t.GetInterface(serviceDescription.PortTypes[0].Name) != null &&
                    t.GetInterface(typeof(ICommunicationObject).Name) != null);

                // Get the first service endpoint for the contract
                ServiceEndpoint se = endpointsForContracts[serviceDescription.PortTypes[0].Name].First();

                // Create an instance of the proxy
                // Pass the endpoint's binding and address as parameters
                // to the ctor
                object ClientProxyInstance = results.CompiledAssembly.CreateInstance(
                    clientProxyType.Name,
                    false,
                    System.Reflection.BindingFlags.CreateInstance,
                    null,
                    new object[] { se.Binding, se.Address },
                    CultureInfo.CurrentCulture, null);



                //this.Resources.Add(retVal.ToString(), )
                return(ClientProxyInstance);
            }
        }
Beispiel #8
0
        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);
            }
        }