public void Process(
            IMetadataKindIdentity metadataKind,
            MetadataSet flattenedMetadata,
            MetadataSet concreteKindMetadata,
            IMetadataElement element)
        {
            bool hasReferences = false;
            var dereferencedChilds = new List<IMetadataElement>();
            foreach (var child in element.Elements)
            {
                var reference = child as MetadataReference;
                if (reference == null)
                {
                    dereferencedChilds.Add(child);
                    continue;
                }

                IMetadataElement metadataElement;
                var absoluteId = reference.ReferencedElementId.IsAbsoluteUri
                                     ? reference.ReferencedElementId
                                     : element.Identity.Id.WithRelative(reference.ReferencedElementId);

                if (!flattenedMetadata.Metadata.TryGetValue(absoluteId, out metadataElement))
                {
                    throw new InvalidOperationException($"Can't resolve metadata for referenced element: {reference.ReferencedElementId}. " +
                                                        $"References is ecounterred in {reference.Parent.Identity.Id} childs list");
                }

                hasReferences = true;
                flattenedMetadata.Metadata.Remove(reference.Identity.Id);
                concreteKindMetadata.Metadata.Remove(reference.Identity.Id);
                ((IMetadataElementUpdater)metadataElement).ReferencedBy(element);
                dereferencedChilds.Add(metadataElement);
            }

            if (!hasReferences)
            {
                return;
            }

            ((IMetadataElementUpdater)element).ReplaceChilds(dereferencedChilds);
        }
示例#2
0
        public static void NetTcpBinding(
            TestContext context, MetadataSet doc, SecurityMode security,
            bool reliableSession, TransferMode transferMode, TestLabel label)
        {
            label.EnterScope("netTcpBinding");

            var sd = (WS.ServiceDescription)doc.MetadataSections [0].Metadata;

            label.EnterScope("wsdl");

            label.EnterScope("extensions");
            Assert.That(sd.Extensions, Is.Not.Null, label.Get());
            Assert.That(sd.Extensions.Count, Is.EqualTo(1), label.Get());
            Assert.That(sd.Extensions [0], Is.InstanceOfType(typeof(XmlElement)), label.Get());

            var extension = (XmlElement)sd.Extensions [0];

            Assert.That(extension.NamespaceURI, Is.EqualTo(WspNamespace), label.Get());
            Assert.That(extension.LocalName, Is.EqualTo("Policy"), label.Get());
            label.LeaveScope();

            label.EnterScope("bindings");
            Assert.That(sd.Bindings.Count, Is.EqualTo(1), label.Get());
            var binding = sd.Bindings [0];

            Assert.That(binding.ExtensibleAttributes, Is.Null, label.Get());
            Assert.That(binding.Extensions, Is.Not.Null, label.Get());

            WS.SoapBinding soap = null;
            XmlElement     xml  = null;

            foreach (var ext in binding.Extensions)
            {
                if (ext is WS.SoapBinding)
                {
                    soap = (WS.SoapBinding)ext;
                }
                else if (ext is XmlElement)
                {
                    xml = (XmlElement)ext;
                }
            }

            CheckSoapBinding(soap, "http://schemas.microsoft.com/soap/tcp", label);

            if (context.CheckPolicyXml)
            {
                label.EnterScope("policy-xml");
                Assert.That(xml, Is.Not.Null, label.Get());

                Assert.That(xml.NamespaceURI, Is.EqualTo(WspNamespace), label.Get());
                Assert.That(xml.LocalName, Is.EqualTo("PolicyReference") | Is.EqualTo("Policy"), label.Get());
                label.LeaveScope();
            }

            label.LeaveScope();              // wsdl

            var importer = new WsdlImporter(doc);

            label.EnterScope("bindings");
            var bindings = importer.ImportAllBindings();

            CheckImportErrors(importer, label);
            Assert.That(bindings, Is.Not.Null, label.Get());
            Assert.That(bindings.Count, Is.EqualTo(1), label.Get());

            CheckNetTcpBinding(
                bindings [0], security, reliableSession,
                transferMode, label);
            label.LeaveScope();

            label.EnterScope("endpoints");
            var endpoints = importer.ImportAllEndpoints();

            CheckImportErrors(importer, label);
            Assert.That(endpoints, Is.Not.Null, label.Get());
            Assert.That(endpoints.Count, Is.EqualTo(1), label.Get());

            CheckEndpoint(endpoints [0], MetadataSamples.NetTcpUri, label);
            label.LeaveScope();

            label.LeaveScope();
        }
示例#3
0
        public static void BasicHttpBinding(
            TestContext context, MetadataSet doc, BasicHttpSecurityMode security,
            WSMessageEncoding encoding, HttpClientCredentialType clientCred,
            AuthenticationSchemes authScheme, TestLabel label)
        {
            label.EnterScope("basicHttpBinding");

            var sd = (WS.ServiceDescription)doc.MetadataSections [0].Metadata;

            label.EnterScope("wsdl");
            label.EnterScope("bindings");
            Assert.That(sd.Bindings.Count, Is.EqualTo(1), label.Get());

            var binding = sd.Bindings [0];

            Assert.That(binding.ExtensibleAttributes, Is.Null, label.Get());
            Assert.That(binding.Extensions, Is.Not.Null, label.Get());

            bool hasPolicyXml;

            switch (security)
            {
            case BasicHttpSecurityMode.None:
                hasPolicyXml = encoding == WSMessageEncoding.Mtom;
                break;

            case BasicHttpSecurityMode.Message:
            case BasicHttpSecurityMode.Transport:
            case BasicHttpSecurityMode.TransportWithMessageCredential:
                if (encoding == WSMessageEncoding.Mtom)
                {
                    throw new InvalidOperationException();
                }
                hasPolicyXml = true;
                break;

            case BasicHttpSecurityMode.TransportCredentialOnly:
                hasPolicyXml = true;
                break;

            default:
                throw new InvalidOperationException();
            }
            label.LeaveScope();

            WS.SoapBinding soap = null;
            XmlElement     xml  = null;

            foreach (var ext in binding.Extensions)
            {
                if (ext is WS.SoapBinding)
                {
                    soap = (WS.SoapBinding)ext;
                }
                else if (ext is XmlElement)
                {
                    xml = (XmlElement)ext;
                }
            }

            CheckSoapBinding(soap, WS.SoapBinding.HttpTransport, label);
            label.LeaveScope();

            label.EnterScope("policy-xml");
            if (!hasPolicyXml)
            {
                Assert.That(xml, Is.Null, label.Get());
            }
            else if (context.CheckPolicyXml)
            {
                Assert.That(xml, Is.Not.Null, label.Get());

                Assert.That(xml.NamespaceURI, Is.EqualTo(WspNamespace), label.Get());
                Assert.That(xml.LocalName, Is.EqualTo("PolicyReference") | Is.EqualTo("Policy"), label.Get());
            }
            label.LeaveScope();

            var importer = new WsdlImporter(doc);

            label.EnterScope("bindings");
            var bindings = importer.ImportAllBindings();

            CheckImportErrors(importer, label);

            Assert.That(bindings, Is.Not.Null, label.Get());
            Assert.That(bindings.Count, Is.EqualTo(1), label.Get());

            string scheme;

            if ((security == BasicHttpSecurityMode.Transport) ||
                (security == BasicHttpSecurityMode.TransportWithMessageCredential))
            {
                scheme = "https";
            }
            else
            {
                scheme = "http";
            }

            CheckBasicHttpBinding(
                bindings [0], scheme, security, encoding, clientCred,
                authScheme, label);
            label.LeaveScope();

            label.EnterScope("endpoints");
            var endpoints = importer.ImportAllEndpoints();

            CheckImportErrors(importer, label);

            Assert.That(endpoints, Is.Not.Null, label.Get());
            Assert.That(endpoints.Count, Is.EqualTo(1), label.Get());

            CheckEndpoint(endpoints [0], MetadataSamples.HttpUri, label);
            label.LeaveScope();

            label.LeaveScope();
        }
示例#4
0
 public static void SaveMetadata(string name, MetadataSet metadata)
 {
     SaveMetadataToFile(name, metadata);
 }
示例#5
0
        public static ServiceEndpoint[] GetEndpoints(string mexAddress)
        {
            if (String.IsNullOrEmpty(mexAddress))
            {
                Debug.Assert(false, "Empty address");
                return(null);
            }
            Uri address = new Uri(mexAddress);
            ServiceEndpointCollection endpoints = null;

            if (address.Scheme == "http")
            {
                HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement();
                httpBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;

                //Try the HTTP MEX Endpoint
                try
                {
                    endpoints = QueryMexEndpoint(mexAddress, httpBindingElement);
                }
                catch
                {}

                //Try over HTTP-GET
                if (endpoints == null)
                {
                    string httpGetAddress = mexAddress;
                    if (mexAddress.EndsWith("?wsdl") == false)
                    {
                        httpGetAddress += "?wsdl";
                    }
                    CustomBinding          binding   = new CustomBinding(httpBindingElement);
                    MetadataExchangeClient MEXClient = new MetadataExchangeClient(binding);
                    MetadataSet            metadata  = MEXClient.GetMetadata(new Uri(httpGetAddress), MetadataExchangeClientMode.HttpGet);
                    MetadataImporter       importer  = new WsdlImporter(metadata);
                    endpoints = importer.ImportAllEndpoints();
                }
            }
            if (address.Scheme == "https")
            {
                HttpsTransportBindingElement httpsBindingElement = new HttpsTransportBindingElement();
                httpsBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;

                //Try the HTTPS MEX Endpoint
                try
                {
                    endpoints = QueryMexEndpoint(mexAddress, httpsBindingElement);
                }
                catch
                {}

                //Try over HTTP-GET
                if (endpoints == null)
                {
                    string httpsGetAddress = mexAddress;
                    if (mexAddress.EndsWith("?wsdl") == false)
                    {
                        httpsGetAddress += "?wsdl";
                    }
                    CustomBinding          binding   = new CustomBinding(httpsBindingElement);
                    MetadataExchangeClient MEXClient = new MetadataExchangeClient(binding);
                    MetadataSet            metadata  = MEXClient.GetMetadata(new Uri(httpsGetAddress), MetadataExchangeClientMode.HttpGet);
                    MetadataImporter       importer  = new WsdlImporter(metadata);
                    endpoints = importer.ImportAllEndpoints();
                }
            }
            if (address.Scheme == "net.tcp")
            {
                TcpTransportBindingElement tcpBindingElement = new TcpTransportBindingElement();
                tcpBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;
                endpoints = QueryMexEndpoint(mexAddress, tcpBindingElement);
            }
            if (address.Scheme == "net.pipe")
            {
                NamedPipeTransportBindingElement ipcBindingElement = new NamedPipeTransportBindingElement();
                ipcBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;
                endpoints = QueryMexEndpoint(mexAddress, ipcBindingElement);
            }
            return(endpoints.ToArray());
        }
        public IList <ServiceInvokeResult> InvokeOperation(string wsdlUri, string contractName, string operationName)
        {
            var             key            = string.Format("{0}_{1}_{2}", wsdlUri, contractName, operationName);
            CompilerResults results        = null;
            var             compilerResult = CompilerResultCache.TryGetValue(key, out results);
            IEnumerable <ContractDescription> contracts = null;

            ContractDescriptionCache.TryGetValue(key, out contracts);
            Dictionary <string, IEnumerable <ServiceEndpoint> > endpointsForContracts = null;

            ServiceEndpointCache.TryGetValue(key, out endpointsForContracts);
            if (endpointsForContracts == null)
            {
                endpointsForContracts = new Dictionary <string, IEnumerable <ServiceEndpoint> >();
            }

            var resultList = new List <ServiceInvokeResult>();

            if (!compilerResult)
            {
                // 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.
                var mexAddress = new Uri(wsdlUri);


                //var contractName = GetInterfaceFromUri(mexAddress.AbsoluteUri);
                // const string operationName = "Ping";
                // var operationParameters = new object[] { null };

                // Get the metadata file from the service.
                var mexClient = new MetadataExchangeClient(mexAddress, MexMode)
                {
                    ResolveMetadataReferences = true
                };
                MetadataSet metaSet = mexClient.GetMetadata();

                // Import all contracts and endpoints
                var importer = new WsdlImporter(metaSet);
                contracts = importer.ImportAllContracts();
                ContractDescriptionCache.TryAdd(key, contracts);

                var allEndpoints = importer.ImportAllEndpoints();

                //ServisKullaniminiLogla metodu icin header bilgilerinin alinmasini saglar.


                foreach (var endpoint in allEndpoints)
                {
                    endpoint.Behaviors.Add(new BackendClientMessageInspectorBehavior());
                }

                // Generate type information for each contract
                var generator = new ServiceContractGenerator();

                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.");
                }

                ServiceEndpointCache.TryAdd(key, endpointsForContracts);

                // Generate a code file for the contracts
                var options = new CodeGeneratorOptions {
                    BracingStyle = "C"
                };
                var codeDomProvider = CodeDomProvider.CreateProvider("C#");

                // Compile the code file to an in-memory assembly
                // Don't forget to add all WCF-related assemblies as references
                var compilerParameters = new CompilerParameters(
                    new[]
                {
                    "System.dll", "System.ServiceModel.dll",
                    "System.Runtime.Serialization.dll"
                });
                compilerParameters.GenerateInMemory = true;
                results = codeDomProvider.CompileAssemblyFromDom(compilerParameters, generator.TargetCompileUnit);
                CompilerResultCache.TryAdd(key, results);
            }

            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)
                if (string.IsNullOrEmpty(contractName))
                {
                    contractName = contracts.First().Name;
                }
                Type clientProxyType = results.CompiledAssembly.GetTypes().First(
                    t => t.IsClass &&
                    t.GetInterface(contractName) != null &&
                    t.GetInterface(typeof(ICommunicationObject).Name) != null);
                if (clientProxyType == null)
                {
                    throw new ArgumentNullException(@"clientProxyType nesnesi oluşturulamadı.");
                }

                // Get the first service endpoint for the contract
                var se = endpointsForContracts[contractName].FirstOrDefault(e => e.Address.Uri.Scheme == "net.tcp") ?? //net.tcp varsa once o kullanilsin cunku daha hizli.
                         endpointsForContracts[contractName].FirstOrDefault();

                // 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);

                // Get the operation's mereflecthod, invoke it, and get the return value
                if (instance != null)
                {
                    var minfo = instance.GetType().GetMethod(operationName);
                    if (minfo == null)
                    {
                        throw new ArgumentNullException(string.Format("{0} adlı operation bulunamadı.", operationName));
                    }
                    var watch = new Stopwatch();
                    watch.Start();
                    if (InvokeStartEvent != null)
                    {
                        InvokeStartEvent(this, new DynamicServiceInvokeEventArgs()
                        {
                            ContractName = contractName, OperationName = operationName, WsdlUri = wsdlUri
                        });
                    }
                    var result = minfo.Invoke(instance, null);
                    watch.Stop();
                    if (InvokeEndEvent != null)
                    {
                        InvokeEndEvent(this, new DynamicServiceInvokeEventArgs()
                        {
                            ContractName = contractName, OperationName = operationName, WsdlUri = wsdlUri
                        });
                    }
                    var item = new ServiceInvokeResult();
                    item.ResponseTime      = watch.ElapsedMilliseconds;
                    item.ResultDescription = "Success";
                    item.Result            = result;
                    item.Address           = se.Address.Uri.AbsoluteUri;
                    item.BindingName       = se.Binding.Name;
                    resultList.Add(item);
                    CloseChannel(instance);
                }
                else
                {
                    throw new ArgumentNullException(string.Format("{0} adlı instance oluşturulamadı.", clientProxyType.Name));
                }
            }
            return(resultList);
        }
示例#7
0
        protected void btnValidate_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(tbXml.Text))
            {
                lblResults.Text = string.Empty;
            }
            else
            {
                var typeName = ddlConfigXml.SelectedItem.Text;
                var xml      = tbXml.Text.Trim();
                tbXml.Text = xml;

                try
                {
                    var type = typeof(BindingXml).Assembly.GetType("NIntegrate.ServiceModel.Configuration." + typeName);
                    var obj  = Activator.CreateInstance(type, typeName == "BindingXml" ? new object[] { ddlBindingTypes.SelectedValue, xml } : new object[] { xml });

                    if (typeName == "BindingXml")
                    {
                        (obj as BindingXml).CreateBinding();
                    }
                    else if (typeName == "EndpointBehaviorXml")
                    {
                        var contract = new ContractDescription("test");
                        var endpoint = new ServiceEndpoint(contract);
                        (obj as EndpointBehaviorXml).ApplyEndpointBehaviorConfiguration(endpoint);
                    }
                    else if (typeName == "HeadersXml")
                    {
                        (obj as HeadersXml).CreateAddressHeaders();
                    }
                    else if (typeName == "HostXml")
                    {
                        var servcieHost = new ServiceHost(typeof(TestService));
                        (obj as HostXml).ApplyHostTimeoutsConfiguration(servcieHost);
                    }
                    else if (typeName == "IdentityXml")
                    {
                        (obj as IdentityXml).CreateEndpointIdentity();
                    }
                    else if (typeName == "MetadataXml")
                    {
                        var metadataSet = new MetadataSet();
                        var importer    = new WsdlImporter(metadataSet);
                        (obj as MetadataXml).ApplyPolicyImportersConfiguration(importer);
                        (obj as MetadataXml).ApplyWsdlImportersConfiguration(importer);
                    }
                    else if (typeName == "ServiceBehaviorXml")
                    {
                        var servcieHost = new ServiceHost(typeof(TestService));
                        (obj as ServiceBehaviorXml).ApplyServiceBehaviorConfiguration(servcieHost);
                    }

                    lblResults.ForeColor = Color.Green;
                    lblResults.Text      = "OK";
                }
                catch (Exception ex)
                {
                    while (ex.InnerException != null)
                    {
                        ex = ex.InnerException;
                    }
                    lblResults.ForeColor = Color.Red;
                    lblResults.Text      = ex.Message.Replace("\r\n", "<br />");
                }
            }
        }
示例#8
0
    public static void Main()
    {
        try
        {
            SampleServiceClient wcfClient;
            // Client has an endpoint for metadata
            EndpointAddress metaAddress
                = new EndpointAddress(new Uri("http://localhost:8080/SampleService/mex"));
            EndpointAddress httpGetMetaAddress
                = new EndpointAddress(new Uri("http://localhost:8080/SampleService?wsdl"));

            // <snippet1>
            // Get the endpoints for such a service
            ServiceEndpointCollection endpoints = MetadataResolver.Resolve(typeof(SampleServiceClient), metaAddress);
            Console.WriteLine("Trying all available WS-Transfer metadata endpoints...");

            foreach (ServiceEndpoint point in endpoints)
            {
                if (point != null)
                {
                    // Create a new wcfClient using retrieved endpoints.
                    wcfClient = new SampleServiceClient(point.Binding, point.Address);
                    Console.WriteLine(
                        wcfClient.SampleMethod("Client used the "
                                               + point.Address.ToString()
                                               + " address.")
                        );
                    wcfClient.Close();
                }
            }
            // </snippet1>
            // <snippet2>
            // Get the endpoints for such a service using Http/Get request
            endpoints = MetadataResolver.Resolve(typeof(SampleServiceClient), httpGetMetaAddress.Uri, MetadataExchangeClientMode.HttpGet);
            Client.WriteParameters(endpoints);
            ISampleService serviceChannel;
            Console.WriteLine(
                "\r\nTrying all endpoints from HTTP/Get and with direct service channels...");

            foreach (ServiceEndpoint point in endpoints)
            {
                if (point != null)
                {
                    ChannelFactory <ISampleService> factory = new ChannelFactory <ISampleService>(point.Binding);
                    factory.Endpoint.Address = point.Address;
                    serviceChannel           = factory.CreateChannel();
                    Console.WriteLine("Client used the " + point.Address.ToString() + " address.");
                    Console.WriteLine(
                        serviceChannel.SampleMethod(
                            "Client used the " + point.Address.ToString() + " address."
                            )
                        );
                    factory.Close();
                }
            }
            // </snippet2>

            // <snippet3>
            // Get metadata documents.
            Console.WriteLine("URI of the metadata documents retreived:");
            MetadataExchangeClient metaTransfer
                = new MetadataExchangeClient(httpGetMetaAddress.Uri, MetadataExchangeClientMode.HttpGet);
            metaTransfer.ResolveMetadataReferences = true;
            MetadataSet otherDocs = metaTransfer.GetMetadata();
            foreach (MetadataSection doc in otherDocs.MetadataSections)
            {
                Console.WriteLine(doc.Dialect + " : " + doc.Identifier);
            }
            // </snippet3>

            Console.WriteLine("Press ENTER to exit...");
            Console.ReadLine();
        }
        catch (TimeoutException timeProblem)
        {
            Console.WriteLine("The service operation timed out. " + timeProblem.Message);
        }
        catch (FaultException unkException)
        {
            Console.WriteLine(unkException.Message);
            Console.ReadLine();
        }
        catch (CommunicationException commProblem)
        {
            Console.WriteLine("There was a communication problem. " + commProblem.Message);
        }
    }
示例#9
0
 public WebServiceDiscoveryResultWCF(DiscoveryClientProtocol protocol, MetadataSet metadata, WebReferenceItem item, ReferenceGroup refGroup) : base(WebReferencesService.WcfEngine, item)
 {
     this.refGroup = refGroup;
     this.protocol = protocol;
     this.metadata = metadata;
 }
示例#10
0
        public static void NetTcpBinding(
            TestContext context, MetadataSet doc, SecurityMode security,
            bool reliableSession, TransferMode transferMode, TestLabel label)
        {
            label.EnterScope("netTcpBinding");

            var sd = (WS.ServiceDescription)doc.MetadataSections [0].Metadata;

            label.EnterScope("wsdl");

            label.EnterScope("bindings");
            Assert.That(sd.Bindings.Count, Is.EqualTo(1), label.Get());
            var binding = sd.Bindings [0];

            Assert.That(binding.ExtensibleAttributes, Is.Null, label.Get());
            Assert.That(binding.Extensions, Is.Not.Null, label.Get());

            WS.Soap12Binding soap = null;
            XmlElement       xml  = null;

            foreach (var ext in binding.Extensions)
            {
                if (ext is WS.Soap12Binding)
                {
                    soap = (WS.Soap12Binding)ext;
                }
                else if (ext is XmlElement)
                {
                    xml = (XmlElement)ext;
                }
            }

            CheckSoapBinding(soap, "http://schemas.microsoft.com/soap/tcp", label);

            label.EnterScope("policy-xml");
            Assert.That(xml, Is.Not.Null, label.Get());
            var assertions = AssertPolicy(sd, xml, label);

            Assert.That(assertions, Is.Not.Null, label.Get());
            AssertPolicy(assertions, BinaryEncodingQName, label);
            AssertPolicy(assertions, UsingAddressingQName, label);
            if (transferMode == TransferMode.Streamed)
            {
                AssertPolicy(assertions, StreamedTransferQName, label);
            }
            switch (security)
            {
            case SecurityMode.Message:
                AssertPolicy(assertions, SymmetricBindingQName, label);
                AssertPolicy(assertions, Wss11QName, label);
                AssertPolicy(assertions, Trust10QName, label);
                break;

            case SecurityMode.Transport:
                AssertPolicy(assertions, TransportBindingQName, label);
                break;

            case SecurityMode.TransportWithMessageCredential:
                AssertPolicy(assertions, TransportBindingQName, label);
                AssertPolicy(assertions, EndorsingSupportingQName, label);
                AssertPolicy(assertions, Wss11QName, label);
                AssertPolicy(assertions, Trust10QName, label);
                break;

            default:
                break;
            }
            if (reliableSession)
            {
                AssertPolicy(assertions, ReliableSessionQName, label);
            }
            Assert.That(assertions.Count, Is.EqualTo(0), label.Get());
            label.LeaveScope();

            label.EnterScope("services");
            Assert.That(sd.Services, Is.Not.Null, label.Get());
            Assert.That(sd.Services.Count, Is.EqualTo(1), label.Get());
            var service = sd.Services [0];

            Assert.That(service.Ports, Is.Not.Null, label.Get());
            Assert.That(service.Ports.Count, Is.EqualTo(1), label.Get());
            var port = service.Ports [0];

            label.EnterScope("port");
            Assert.That(port.Extensions, Is.Not.Null, label.Get());
            Assert.That(port.Extensions.Count, Is.EqualTo(2), label.Get());

            WS.Soap12AddressBinding soap_addr_binding = null;
            XmlElement port_xml = null;

            foreach (var extension in port.Extensions)
            {
                if (extension is WS.Soap12AddressBinding)
                {
                    soap_addr_binding = (WS.Soap12AddressBinding)extension;
                }
                else if (extension is XmlElement)
                {
                    port_xml = (XmlElement)extension;
                }
                else
                {
                    Assert.Fail(label.Get());
                }
            }
            Assert.That(soap_addr_binding, Is.Not.Null, label.Get());
            Assert.That(port_xml, Is.Not.Null, label.Get());
            Assert.That(port_xml.NamespaceURI, Is.EqualTo(Wsa10Namespace), label.Get());
            Assert.That(port_xml.LocalName, Is.EqualTo("EndpointReference"), label.Get());
            label.LeaveScope();
            label.LeaveScope();

            label.LeaveScope();              // wsdl

            var importer = new WsdlImporter(doc);

            label.EnterScope("bindings");
            var bindings = importer.ImportAllBindings();

            CheckImportErrors(importer, label);
            Assert.That(bindings, Is.Not.Null, label.Get());
            Assert.That(bindings.Count, Is.EqualTo(1), label.Get());

            CheckNetTcpBinding(
                bindings [0], security, reliableSession,
                transferMode, label);
            label.LeaveScope();

            label.EnterScope("endpoints");
            var endpoints = importer.ImportAllEndpoints();

            CheckImportErrors(importer, label);
            Assert.That(endpoints, Is.Not.Null, label.Get());
            Assert.That(endpoints.Count, Is.EqualTo(1), label.Get());

            CheckEndpoint(endpoints [0], MetadataSamples.NetTcpUri, label);
            label.LeaveScope();

            label.LeaveScope();
        }
示例#11
0
        static void BasicHttpBinding_inner(
            TestContext context, MetadataSet doc, BasicHttpSecurityMode security,
            WSMessageEncoding encoding, HttpClientCredentialType clientCred,
            AuthenticationSchemes authScheme, bool isHttps, TestLabel label)
        {
            var sd = (WS.ServiceDescription)doc.MetadataSections [0].Metadata;

            label.EnterScope("wsdl");
            label.EnterScope("bindings");
            Assert.That(sd.Bindings.Count, Is.EqualTo(1), label.Get());

            var binding = sd.Bindings [0];

            Assert.That(binding.ExtensibleAttributes, Is.Null, label.Get());
            Assert.That(binding.Extensions, Is.Not.Null, label.Get());

            bool hasPolicyXml;

            switch (security)
            {
            case BasicHttpSecurityMode.None:
                if (isHttps)
                {
                    throw new InvalidOperationException();
                }
                hasPolicyXml = encoding == WSMessageEncoding.Mtom;
                break;

            case BasicHttpSecurityMode.Message:
            case BasicHttpSecurityMode.Transport:
            case BasicHttpSecurityMode.TransportWithMessageCredential:
                if (encoding == WSMessageEncoding.Mtom)
                {
                    throw new InvalidOperationException();
                }
                hasPolicyXml = true;
                break;

            case BasicHttpSecurityMode.TransportCredentialOnly:
                if (isHttps)
                {
                    throw new InvalidOperationException();
                }
                hasPolicyXml = true;
                break;

            default:
                throw new InvalidOperationException();
            }
            label.LeaveScope();

            WS.SoapBinding soap = null;
            XmlElement     xml  = null;

            foreach (var ext in binding.Extensions)
            {
                if (ext is WS.SoapBinding)
                {
                    soap = (WS.SoapBinding)ext;
                }
                else if (ext is XmlElement)
                {
                    xml = (XmlElement)ext;
                }
            }

            CheckSoapBinding(soap, WS.SoapBinding.HttpTransport, label);
            label.LeaveScope();

            label.EnterScope("policy-xml");
            if (!hasPolicyXml)
            {
                Assert.That(xml, Is.Null, label.Get());
            }
            else
            {
                Assert.That(xml, Is.Not.Null, label.Get());
                var assertions = AssertPolicy(sd, xml, label);
                Assert.That(assertions, Is.Not.Null, label.Get());
                if (clientCred == HttpClientCredentialType.Ntlm)
                {
                    AssertPolicy(assertions, NtlmAuthenticationQName, label);
                }
                if (encoding == WSMessageEncoding.Mtom)
                {
                    AssertPolicy(assertions, MtomEncodingQName, label);
                }
                switch (security)
                {
                case BasicHttpSecurityMode.Message:
                    AssertPolicy(assertions, AsymmetricBindingQName, label);
                    AssertPolicy(assertions, Wss10QName, label);
                    break;

                case BasicHttpSecurityMode.Transport:
                    AssertPolicy(assertions, TransportBindingQName, label);
                    break;

                case BasicHttpSecurityMode.TransportWithMessageCredential:
                    AssertPolicy(assertions, SignedSupportingQName, label);
                    AssertPolicy(assertions, TransportBindingQName, label);
                    AssertPolicy(assertions, Wss10QName, label);
                    break;

                default:
                    break;
                }
                Assert.That(assertions.Count, Is.EqualTo(0), label.Get());
            }
            label.LeaveScope();

            label.EnterScope("services");
            Assert.That(sd.Services, Is.Not.Null, label.Get());
            Assert.That(sd.Services.Count, Is.EqualTo(1), label.Get());
            var service = sd.Services [0];

            Assert.That(service.Ports, Is.Not.Null, label.Get());
            Assert.That(service.Ports.Count, Is.EqualTo(1), label.Get());
            var port = service.Ports [0];

            label.EnterScope("port");
            Assert.That(port.Extensions, Is.Not.Null, label.Get());
            Assert.That(port.Extensions.Count, Is.EqualTo(1), label.Get());

            WS.SoapAddressBinding soap_addr_binding = null;
            foreach (var extension in port.Extensions)
            {
                if (extension is WS.SoapAddressBinding)
                {
                    soap_addr_binding = (WS.SoapAddressBinding)extension;
                }
                else
                {
                    Assert.Fail(label.Get());
                }
            }
            Assert.That(soap_addr_binding, Is.Not.Null, label.Get());
            label.LeaveScope();

            label.LeaveScope();              // wsdl

            var importer = new WsdlImporter(doc);

            label.EnterScope("bindings");
            var bindings = importer.ImportAllBindings();

            CheckImportErrors(importer, label);

            Assert.That(bindings, Is.Not.Null, label.Get());
            Assert.That(bindings.Count, Is.EqualTo(1), label.Get());

            string scheme;

            if ((security == BasicHttpSecurityMode.Transport) ||
                (security == BasicHttpSecurityMode.TransportWithMessageCredential))
            {
                scheme = "https";
            }
            else
            {
                scheme = "http";
            }

            CheckBasicHttpBinding(
                bindings [0], scheme, security, encoding, clientCred,
                authScheme, label);
            label.LeaveScope();

            label.EnterScope("endpoints");
            var endpoints = importer.ImportAllEndpoints();

            CheckImportErrors(importer, label);

            Assert.That(endpoints, Is.Not.Null, label.Get());
            Assert.That(endpoints.Count, Is.EqualTo(1), label.Get());

            var uri = isHttps ? MetadataSamples.HttpsUri : MetadataSamples.HttpUri;

            CheckEndpoint(endpoints [0], uri, label);
            label.LeaveScope();
        }
示例#12
0
 public void ReadFromNull()
 {
     MetadataSet.ReadFrom(null);
 }
示例#13
0
        void Explore(string mexAddress)
        {
            ServiceNode existingNode = null;

            try
            {
                Uri address = new Uri(mexAddress);
                ServiceEndpointCollection endpoints = null;

                //Find if tree already contain this address
                foreach (ServiceNode node in m_MexTree.Nodes)
                {
                    if (node.MexAddress == mexAddress)
                    {
                        if (node.Text == "Unspecified Base Address" || node.Text == "Invalid Address")
                        {
                            node.ImageIndex = node.SelectedImageIndex = ServiceIndex;
                        }
                        existingNode = node;
                        break;
                    }
                }
                if (address.Scheme == "http")
                {
                    HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement();
                    httpBindingElement.MaxReceivedMessageSize *= MessageMultiplier;

                    //Try the HTTP MEX Endpoint
                    try
                    {
                        endpoints = GetEndpoints(httpBindingElement);
                    }
                    catch
                    {}
                    //Try over HTTP-GET
                    if (endpoints == null)
                    {
                        string httpGetAddress = mexAddress;
                        if (mexAddress.EndsWith("?wsdl") == false)
                        {
                            httpGetAddress += "?wsdl";
                        }
                        CustomBinding          binding   = new CustomBinding(httpBindingElement);
                        MetadataExchangeClient MEXClient = new MetadataExchangeClient(binding);
                        MetadataSet            metadata  = MEXClient.GetMetadata(new Uri(httpGetAddress), MetadataExchangeClientMode.HttpGet);
                        MetadataImporter       importer  = new WsdlImporter(metadata);
                        endpoints = importer.ImportAllEndpoints();
                    }
                }
                if (address.Scheme == "https")
                {
                    HttpsTransportBindingElement httpsBindingElement = new HttpsTransportBindingElement();
                    httpsBindingElement.MaxReceivedMessageSize *= MessageMultiplier;

                    //Try the HTTPS MEX Endpoint
                    try
                    {
                        endpoints = GetEndpoints(httpsBindingElement);
                    }
                    catch
                    {
                    }
                    //Try over HTTP-GET
                    if (endpoints == null)
                    {
                        string httpsGetAddress = mexAddress;
                        if (mexAddress.EndsWith("?wsdl") == false)
                        {
                            httpsGetAddress += "?wsdl";
                        }
                        CustomBinding          binding   = new CustomBinding(httpsBindingElement);
                        MetadataExchangeClient MEXClient = new MetadataExchangeClient(binding);
                        MetadataSet            metadata  = MEXClient.GetMetadata(new Uri(httpsGetAddress), MetadataExchangeClientMode.HttpGet);
                        MetadataImporter       importer  = new WsdlImporter(metadata);
                        endpoints = importer.ImportAllEndpoints();
                    }
                }
                if (address.Scheme == "net.tcp")
                {
                    TcpTransportBindingElement tcpBindingElement = new TcpTransportBindingElement();
                    tcpBindingElement.MaxReceivedMessageSize *= MessageMultiplier;
                    endpoints = GetEndpoints(tcpBindingElement);
                }
                if (address.Scheme == "net.pipe")
                {
                    NamedPipeTransportBindingElement ipcBindingElement = new NamedPipeTransportBindingElement();
                    ipcBindingElement.MaxReceivedMessageSize *= MessageMultiplier;
                    endpoints = GetEndpoints(ipcBindingElement);
                }
                ProcessMetaData(existingNode, mexAddress, endpoints);
            }
            catch
            {
                if (existingNode == null)
                {
                    CurrentNode = new ServiceNode(mexAddress, this, "Invalid Address", ServiceError, ServiceError);
                    m_MexTree.Nodes.Add(CurrentNode);
                }
                else
                {
                    CurrentNode.Text = "Invalid Address";
                    CurrentNode.Nodes.Clear();
                    CurrentNode.ImageIndex = CurrentNode.SelectedImageIndex = ServiceError;
                }
            }
        }
示例#14
0
 private static void CustomizeMexEndpoints(ServiceDescription description, ServiceHostBase host, MetadataSet metadata)
 {
     foreach (ChannelDispatcher channelDispatcher in host.ChannelDispatchers)
     {
         foreach (EndpointDispatcher endpoint in channelDispatcher.Endpoints)
         {
             if (endpoint.ContractName == MexContractName && endpoint.ContractNamespace == MexContractNamespace)
             {
                 DispatchRuntime dispatchRuntime = endpoint.DispatchRuntime;
                 dispatchRuntime.InstanceContextProvider = Utility.CreateInstance <IInstanceContextProvider>(SingletonInstanceContextProviderType, new Type[] { typeof(DispatchRuntime) }, new object[] { dispatchRuntime });
                 MetadataProvisionService serviceInstance = new MetadataProvisionService(metadata);
                 dispatchRuntime.SingletonInstanceContext = new InstanceContext(host, serviceInstance);
             }
         }
     }
 }
示例#15
0
        /// <summary>
        /// Get all the information about the services in a current address.
        /// Send the http://schemas.xmlsoap.org/ws/2004/09/transfer/Get message and
        /// receive the http://schemas.xmlsoap.org/ws/2004/09/transfer/GetResponse.
        /// </summary>
        /// <param name="device">The device containing the services.</param>
        public static void GetMetaData(edu.teco.DPWS.Device device)
        {
            // Custom binding with TextMessageEncoding and HttpTransport and the specific soap and wsa versions shown here:
            CustomBinding binding = new CustomBinding(
                new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressingAugust2004, Encoding.UTF8),
                new HttpTransportBindingElement());

            // A custom mex client deriving from MetadataExchangeClient. The motivation behind writing the custom client was to get at the ClientVia behavior for the MetadataExchangeClient.
            // Followed the instructions here for this.
            // Gave the physical address in the Via for the custom client and the logical address as the EP address to be put into the ws-addressing To header as:
            MetadataExchangeClient mex         = new MetadataExchangeClient(binding);
            MetadataSet            metadataSet = mex.GetMetadata(device.EndpointAddress);

            // Check for the metadata set size.
            System.Collections.ObjectModel.Collection <MetadataSection> documentCollection = metadataSet.MetadataSections;
            if (documentCollection != null)
            {
                //Get the WSDL from each MetadataSection of the metadata set
                foreach (MetadataSection section in documentCollection)
                {
                    try
                    {
                        if (section.Metadata is System.Xml.XmlElement)
                        {
                            System.Xml.XmlElement element = (System.Xml.XmlElement)section.Metadata;
                            if (element.Name == "wsdp:Relationship")
                            {
                                Relationship relationship = (Relationship)Utils.FromXML(element.OuterXml, typeof(Relationship), string.Empty);

                                foreach (System.Xml.XmlElement innerElement in relationship.Any)
                                {
                                    if (innerElement.Name == "wsdp:Host")
                                    {
                                        HostServiceType host = (HostServiceType)Utils.FromXML(innerElement.OuterXml, typeof(HostServiceType),
                                                                                              string.Empty);
                                    }
                                    else if (innerElement.Name == "wsdp:Hosted")
                                    {
                                        HostServiceType hosted = (HostServiceType)Utils.FromXML(innerElement.OuterXml, typeof(HostServiceType),
                                                                                                "http://schemas.xmlsoap.org/ws/2006/02/devprof", new System.Xml.Serialization.XmlRootAttribute("Hosted"));

                                        if (hosted.EndpointReference != null && hosted.EndpointReference.Length > 0)
                                        {
                                            Console.WriteLine("Service ID: {0}", hosted.ServiceId);

                                            foreach (edu.teco.DPWS.Service service in device.GetServices())
                                            {
                                                if (hosted.ServiceId.Equals(service.GetServiceID()))
                                                {
                                                    service.HostedEndpoint = new EndpointAddress(hosted.EndpointReference[0].Address.Value);
                                                    Console.WriteLine("Found endpoint for {0}", service.GetServiceID());
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            else if (element.Name == "wsdp:ThisModel")
                            {
                                ThisModelType thisModel = (ThisModelType)Utils.FromXML(element.OuterXml, typeof(ThisModelType), string.Empty);
                            }
                            else if (element.Name == "wsdp:ThisDevice")
                            {
                                ThisDeviceType thisDevice = (ThisDeviceType)Utils.FromXML(element.OuterXml, typeof(ThisDeviceType), string.Empty);
                                Console.WriteLine(string.Format("FirmwareVersion: {0}", thisDevice.FirmwareVersion));
                                Console.WriteLine(string.Format("FriendlyName: {0}", thisDevice.FriendlyName));
                                Console.WriteLine(string.Format("SerialNumber: {0}", thisDevice.SerialNumber));
                            }
                        }
                        else if (section.Metadata is System.Web.Services.Description.ServiceDescription)
                        {
                            System.Web.Services.Description.ServiceDescription sd = (System.Web.Services.Description.ServiceDescription)section.Metadata;
                            Console.WriteLine(string.Format("ServiceDescription name: {0}", sd.Name));
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error on getting MetaData.:{0}", ex.Message);
                    }
                }
            }
        }
示例#16
0
 public MetadataMessage(MetadataSet metadataSet)
 {
     Metadata = metadataSet;
 }
示例#17
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);
        }
 public ServiceReferenceDiscoveryEventArgs(MetadataSet metadata)
 {
     GetServices(metadata);
 }
        private void ProcessWsdl()
        {
            string           wsdlText;
            string           portType;
            string           bindingName;
            string           address;
            string           spnIdentity       = null;
            string           upnIdentity       = null;
            string           dnsIdentity       = null;
            EndpointIdentity identity          = null;
            string           serializer        = null;
            string           contractNamespace = null;
            string           bindingNamespace  = null;

            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Wsdl, out wsdlText);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Contract, out portType);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Binding, out bindingName);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Address, out address);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.SpnIdentity, out spnIdentity);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.UpnIdentity, out upnIdentity);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.DnsIdentity, out dnsIdentity);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Serializer, out serializer);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.BindingNamespace, out bindingNamespace);
            propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.ContractNamespace, out contractNamespace);

            if (string.IsNullOrEmpty(wsdlText))
            {
                throw Fx.AssertAndThrow("Wsdl should not be null at this point");
            }
            if (string.IsNullOrEmpty(portType) || string.IsNullOrEmpty(bindingName) || string.IsNullOrEmpty(address))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.ContractBindingAddressCannotBeNull)));
            }

            if (!string.IsNullOrEmpty(spnIdentity))
            {
                if ((!string.IsNullOrEmpty(upnIdentity)) || (!string.IsNullOrEmpty(dnsIdentity)))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorrectServerIdentity)));
                }
                identity = EndpointIdentity.CreateSpnIdentity(spnIdentity);
            }
            else if (!string.IsNullOrEmpty(upnIdentity))
            {
                if ((!string.IsNullOrEmpty(spnIdentity)) || (!string.IsNullOrEmpty(dnsIdentity)))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorrectServerIdentity)));
                }
                identity = EndpointIdentity.CreateUpnIdentity(upnIdentity);
            }
            else if (!string.IsNullOrEmpty(dnsIdentity))
            {
                if ((!string.IsNullOrEmpty(spnIdentity)) || (!string.IsNullOrEmpty(upnIdentity)))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorrectServerIdentity)));
                }
                identity = EndpointIdentity.CreateDnsIdentity(dnsIdentity);
            }
            else
            {
                identity = null;
            }

            bool removeXmlSerializerImporter = false;

            if (!String.IsNullOrEmpty(serializer))
            {
                if ("xml" != serializer && "datacontract" != serializer)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.MonikerIncorectSerializer)));
                }

                if ("xml" == serializer)
                {
                    useXmlSerializer = true;
                }
                else
                {
                    removeXmlSerializerImporter = true; // specifying datacontract will explicitly remove the Xml importer
                }
                // if this parameter is not set we will simply use indigo defaults
            }

            TextReader reader = new StringReader(wsdlText);

            try
            {
                try
                {
                    WsdlNS.ServiceDescription wsdl = WsdlNS.ServiceDescription.Read(reader);

                    if (String.IsNullOrEmpty(contractNamespace))
                    {
                        contractNamespace = wsdl.TargetNamespace;
                    }

                    if (String.IsNullOrEmpty(bindingNamespace))
                    {
                        bindingNamespace = wsdl.TargetNamespace;
                    }

                    WsdlNS.ServiceDescriptionCollection wsdlDocs = new WsdlNS.ServiceDescriptionCollection();
                    wsdlDocs.Add(wsdl);
                    XmlSchemaSet schemas = new XmlSchemaSet();
                    foreach (XmlSchema schema in wsdl.Types.Schemas)
                    {
                        schemas.Add(schema);
                    }

                    MetadataSet  mds = new MetadataSet(WsdlImporter.CreateMetadataDocuments(wsdlDocs, schemas, null));
                    WsdlImporter importer;

                    if (useXmlSerializer)
                    {
                        importer = CreateXmlSerializerImporter(mds);
                    }
                    else
                    {
                        if (removeXmlSerializerImporter)
                        {
                            importer = CreateDataContractSerializerImporter(mds);
                        }
                        else
                        {
                            importer = new WsdlImporter(mds);
                        }
                    }

                    XmlQualifiedName contractQname = new XmlQualifiedName(portType, contractNamespace);
                    XmlQualifiedName bindingQname  = new XmlQualifiedName(bindingName, bindingNamespace);

                    WsdlNS.PortType wsdlPortType = wsdlDocs.GetPortType(contractQname);
                    contractDescription = importer.ImportContract(wsdlPortType);

                    WsdlNS.Binding wsdlBinding = wsdlDocs.GetBinding(bindingQname);
                    Binding        binding     = importer.ImportBinding(wsdlBinding);

                    EndpointAddress endpointAddress = new EndpointAddress(new Uri(address), identity, (AddressHeaderCollection)null);

                    serviceEndpoint = new ServiceEndpoint(contractDescription, binding, endpointAddress);

                    ComPlusWsdlChannelBuilderTrace.Trace(TraceEventType.Verbose, TraceCode.ComIntegrationWsdlChannelBuilderLoaded,
                                                         SR.TraceCodeComIntegrationWsdlChannelBuilderLoaded, bindingQname, contractQname, wsdl, contractDescription, binding, wsdl.Types.Schemas);
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                    {
                        throw;
                    }

                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(SR.GetString(SR.FailedImportOfWsdl, e.Message)));
                }
            }
            finally
            {
                IDisposable disposee = reader;
                disposee.Dispose();
            }
        }
示例#20
0
 public void Setup()
 {
     collectionsMetadata       = WsdlHelper.GetMetadataSet("collections.wsdl");
     customCollectionsMetadata = WsdlHelper.GetMetadataSet("custom-collections.wsdl");
 }
 public void Setup()
 {
     collectionsMetadata       = WsdlHelper.GetMetadataSet("Test/Resources/WSDL/collections.wsdl");
     customCollectionsMetadata = WsdlHelper.GetMetadataSet("Test/Resources/WSDL/custom-collections.wsdl");
 }
示例#22
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);
            }
        }
示例#23
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();
        }
示例#24
0
        public static ServiceEndpoint[] GetEndpoints(string mexAddress)
        {
            if (string.IsNullOrWhiteSpace(mexAddress))
            {
                throw new ArgumentException("mexAddress");
            }

            Uri address = new Uri(mexAddress);
            ServiceEndpointCollection endpoints      = null;
            BindingElement            bindingElement = null;

            //Try over HTTP-GET first
            if (address.Scheme == Uri.UriSchemeHttp || address.Scheme == Uri.UriSchemeHttps)
            {
                string getAddress = mexAddress;
                if (mexAddress.EndsWith("?wsdl") == false)
                {
                    getAddress += "?wsdl";
                }
                if (address.Scheme == Uri.UriSchemeHttp)
                {
                    HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement();
                    httpBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;
                    bindingElement = httpBindingElement;
                }
                else
                {
                    HttpsTransportBindingElement httpsBindingElement = new HttpsTransportBindingElement();
                    httpsBindingElement.MaxReceivedMessageSize *= MessageSizeMultiplier;
                    bindingElement = httpsBindingElement;
                }
                CustomBinding binding = new CustomBinding(bindingElement);

                MetadataExchangeClient mexClient = new MetadataExchangeClient(binding);
                MetadataSet            metadata  = mexClient.GetMetadata(new Uri(getAddress), MetadataExchangeClientMode.HttpGet);
                MetadataImporter       importer  = new WsdlImporter(metadata);
                endpoints = importer.ImportAllEndpoints();
                return(endpoints.ToArray());
            }

            //Try MEX endpoint:

            if (address.Scheme == Uri.UriSchemeHttp)
            {
                bindingElement = new HttpTransportBindingElement();
            }
            if (address.Scheme == Uri.UriSchemeHttps)
            {
                bindingElement = new HttpsTransportBindingElement();
            }
            if (address.Scheme == Uri.UriSchemeNetTcp)
            {
                bindingElement = new TcpTransportBindingElement();
            }
            if (address.Scheme == Uri.UriSchemeNetPipe)
            {
                bindingElement = new NamedPipeTransportBindingElement();
            }

            endpoints = QueryMexEndpoint(mexAddress, bindingElement);
            return(endpoints.ToArray());
        }
        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());
        }
        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);
            }
        }
示例#27
0
        void OnExplore(object sender, EventArgs e)
        {
            m_ExploreButton.Enabled = false;

            string mexAddress = m_MexAddressTextBox.Text;

            if (String.IsNullOrEmpty(mexAddress))
            {
                Debug.Assert(false, "Empty address");
            }
            m_MexTree.Nodes.Clear();
            DisplayBlankControl();

            SplashScreen splash = new SplashScreen(Resources.Progress);

            try
            {
                Uri address = new Uri(mexAddress);
                ServiceEndpointCollection endpoints = null;

                if (address.Scheme == "http")
                {
                    HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement();
                    httpBindingElement.MaxReceivedMessageSize *= MessageMultiplier;

                    //Try the HTTP MEX Endpoint
                    try
                    {
                        endpoints = GetEndpoints(httpBindingElement);
                    }
                    catch
                    {}
                    //Try over HTTP-GET
                    if (endpoints == null)
                    {
                        string httpGetAddress = mexAddress;
                        if (mexAddress.EndsWith("?wsdl") == false)
                        {
                            httpGetAddress += "?wsdl";
                        }
                        CustomBinding          binding   = new CustomBinding(httpBindingElement);
                        MetadataExchangeClient MEXClient = new MetadataExchangeClient(binding);
                        MetadataSet            metadata  = MEXClient.GetMetadata(new Uri(httpGetAddress), MetadataExchangeClientMode.HttpGet);
                        MetadataImporter       importer  = new WsdlImporter(metadata);
                        endpoints = importer.ImportAllEndpoints();
                    }
                }
                if (address.Scheme == "https")
                {
                    HttpsTransportBindingElement httpsBindingElement = new HttpsTransportBindingElement();
                    httpsBindingElement.MaxReceivedMessageSize *= MessageMultiplier;

                    //Try the HTTPS MEX Endpoint
                    try
                    {
                        endpoints = GetEndpoints(httpsBindingElement);
                    }
                    catch
                    {
                    }
                    //Try over HTTP-GET
                    if (endpoints == null)
                    {
                        string httpsGetAddress = mexAddress;
                        if (mexAddress.EndsWith("?wsdl") == false)
                        {
                            httpsGetAddress += "?wsdl";
                        }
                        CustomBinding          binding   = new CustomBinding(httpsBindingElement);
                        MetadataExchangeClient MEXClient = new MetadataExchangeClient(binding);
                        MetadataSet            metadata  = MEXClient.GetMetadata(new Uri(httpsGetAddress), MetadataExchangeClientMode.HttpGet);
                        MetadataImporter       importer  = new WsdlImporter(metadata);
                        endpoints = importer.ImportAllEndpoints();
                    }
                }
                if (address.Scheme == "net.tcp")
                {
                    TcpTransportBindingElement tcpBindingElement = new TcpTransportBindingElement();
                    tcpBindingElement.MaxReceivedMessageSize *= MessageMultiplier;
                    endpoints = GetEndpoints(tcpBindingElement);
                }
                if (address.Scheme == "net.pipe")
                {
                    NamedPipeTransportBindingElement ipcBindingElement = new NamedPipeTransportBindingElement();
                    ipcBindingElement.MaxReceivedMessageSize *= MessageMultiplier;
                    endpoints = GetEndpoints(ipcBindingElement);
                }
                ProcessMetaData(endpoints);
            }
            catch
            {
                m_MexTree.Nodes.Clear();

                m_Root = new ServiceNode(this, "Invalid Base Address", ServiceError, ServiceError);
                m_MexTree.Nodes.Add(m_Root);
                return;
            }
            finally
            {
                splash.Close();
                m_ExploreButton.Enabled = true;
            }
        }
示例#28
0
        public static void BasicHttpsBinding(
            TestContext context, MetadataSet doc, BasicHttpSecurityMode security,
            WSMessageEncoding encoding, HttpClientCredentialType clientCred,
            AuthenticationSchemes authScheme, TestLabel label)
        {
            label.EnterScope("basicHttpsBinding");

            var sd = (WS.ServiceDescription)doc.MetadataSections [0].Metadata;

            label.EnterScope("wsdl");

            Assert.That(sd.Extensions, Is.Not.Null, label.Get());
            Assert.That(sd.Extensions.Count, Is.EqualTo(1), label.Get());
            Assert.That(sd.Extensions [0], Is.InstanceOfType(typeof(XmlElement)), label.Get());

            label.EnterScope("extensions");
            var extension = (XmlElement)sd.Extensions [0];

            Assert.That(extension.NamespaceURI, Is.EqualTo(WspNamespace), label.Get());
            Assert.That(extension.LocalName, Is.EqualTo("Policy"), label.Get());
            label.LeaveScope();

            label.EnterScope("bindings");
            Assert.That(sd.Bindings.Count, Is.EqualTo(1), label.Get());
            var binding = sd.Bindings [0];

            Assert.That(binding.ExtensibleAttributes, Is.Null, label.Get());
            Assert.That(binding.Extensions, Is.Not.Null, label.Get());
            label.LeaveScope();

            WS.SoapBinding soap = null;
            XmlElement     xml  = null;

            foreach (var ext in binding.Extensions)
            {
                if (ext is WS.SoapBinding)
                {
                    soap = (WS.SoapBinding)ext;
                }
                else if (ext is XmlElement)
                {
                    xml = (XmlElement)ext;
                }
            }

            CheckSoapBinding(soap, WS.SoapBinding.HttpTransport, label);

            if (context.CheckPolicyXml)
            {
                label.EnterScope("policy-xml");
                Assert.That(xml, Is.Not.Null, label.Get());
                Assert.That(xml.NamespaceURI, Is.EqualTo(WspNamespace), label.Get());
                Assert.That(xml.LocalName, Is.EqualTo("PolicyReference") | Is.EqualTo("Policy"), label.Get());
                label.LeaveScope();
            }

            label.LeaveScope();              // wsdl

            var importer = new WsdlImporter(doc);

            label.EnterScope("bindings");
            var bindings = importer.ImportAllBindings();

            CheckImportErrors(importer, label);
            Assert.That(bindings, Is.Not.Null, label.Get());
            Assert.That(bindings.Count, Is.EqualTo(1), label.Get());

            CheckBasicHttpBinding(
                bindings [0], "https", security, encoding,
                clientCred, authScheme, label);
            label.LeaveScope();

            label.EnterScope("endpoints");
            var endpoints = importer.ImportAllEndpoints();

            CheckImportErrors(importer, label);
            Assert.That(endpoints, Is.Not.Null, label.Get());
            Assert.That(endpoints.Count, Is.EqualTo(1), label.Get());

            CheckEndpoint(endpoints [0], MetadataSamples.HttpsUri, label);
            label.LeaveScope();

            label.LeaveScope();
        }
        private void DoMex()
        {
            string           str;
            string           str2;
            string           str3;
            string           str4;
            string           str5;
            string           str6;
            string           str7;
            string           str8;
            string           str9      = null;
            string           str10     = null;
            string           str11     = null;
            string           str12     = null;
            string           str13     = null;
            string           str14     = null;
            string           str15     = null;
            EndpointIdentity identity  = null;
            EndpointIdentity identity2 = null;
            WsdlImporter     importer;

            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Contract, out str4);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.ContractNamespace, out str5);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.BindingNamespace, out str7);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Binding, out str6);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexAddress, out str);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexBinding, out str2);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexBindingConfiguration, out str3);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Address, out str8);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.SpnIdentity, out str9);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.UpnIdentity, out str10);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.DnsIdentity, out str11);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexSpnIdentity, out str12);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexUpnIdentity, out str13);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.MexDnsIdentity, out str14);
            this.propertyTable.TryGetValue(MonikerHelper.MonikerAttribute.Serializer, out str15);
            if (string.IsNullOrEmpty(str))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerMexAddressNotSpecified")));
            }
            if (!string.IsNullOrEmpty(str12))
            {
                if (!string.IsNullOrEmpty(str13) || !string.IsNullOrEmpty(str14))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerIncorrectServerIdentityForMex")));
                }
                identity2 = EndpointIdentity.CreateSpnIdentity(str12);
            }
            else if (!string.IsNullOrEmpty(str13))
            {
                if (!string.IsNullOrEmpty(str12) || !string.IsNullOrEmpty(str14))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerIncorrectServerIdentityForMex")));
                }
                identity2 = EndpointIdentity.CreateUpnIdentity(str13);
            }
            else if (!string.IsNullOrEmpty(str14))
            {
                if (!string.IsNullOrEmpty(str12) || !string.IsNullOrEmpty(str13))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerIncorrectServerIdentityForMex")));
                }
                identity2 = EndpointIdentity.CreateDnsIdentity(str14);
            }
            else
            {
                identity2 = null;
            }
            if (string.IsNullOrEmpty(str8))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerAddressNotSpecified")));
            }
            if (string.IsNullOrEmpty(str4))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerContractNotSpecified")));
            }
            if (string.IsNullOrEmpty(str6))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerBindingNotSpecified")));
            }
            if (string.IsNullOrEmpty(str7))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerBindingNamespacetNotSpecified")));
            }
            if (!string.IsNullOrEmpty(str9))
            {
                if (!string.IsNullOrEmpty(str10) || !string.IsNullOrEmpty(str11))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerIncorrectServerIdentity")));
                }
                identity = EndpointIdentity.CreateSpnIdentity(str9);
            }
            else if (!string.IsNullOrEmpty(str10))
            {
                if (!string.IsNullOrEmpty(str9) || !string.IsNullOrEmpty(str11))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerIncorrectServerIdentity")));
                }
                identity = EndpointIdentity.CreateUpnIdentity(str10);
            }
            else if (!string.IsNullOrEmpty(str11))
            {
                if (!string.IsNullOrEmpty(str9) || !string.IsNullOrEmpty(str10))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerIncorrectServerIdentity")));
                }
                identity = EndpointIdentity.CreateDnsIdentity(str11);
            }
            else
            {
                identity = null;
            }
            MetadataExchangeClient client  = null;
            EndpointAddress        address = new EndpointAddress(new Uri(str), identity2, new AddressHeader[0]);

            if (!string.IsNullOrEmpty(str2))
            {
                System.ServiceModel.Channels.Binding mexBinding = null;
                try
                {
                    mexBinding = ConfigLoader.LookupBinding(str2, str3);
                }
                catch (ConfigurationErrorsException)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MexBindingNotFoundInConfig", new object[] { str2 })));
                }
                if (mexBinding == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MexBindingNotFoundInConfig", new object[] { str2 })));
                }
                client = new MetadataExchangeClient(mexBinding);
            }
            else
            {
                if (!string.IsNullOrEmpty(str3))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerMexBindingSectionNameNotSpecified")));
                }
                client = new MetadataExchangeClient(address);
            }
            if (identity2 != null)
            {
                client.SoapCredentials.Windows.AllowNtlm = false;
            }
            bool flag = false;

            if (!string.IsNullOrEmpty(str15))
            {
                if (("xml" != str15) && ("datacontract" != str15))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerIncorectSerializer")));
                }
                if ("xml" == str15)
                {
                    this.useXmlSerializer = true;
                }
                else
                {
                    flag = true;
                }
            }
            ServiceEndpoint           endpoint = null;
            ServiceEndpointCollection serviceEndpointsRetrieved = null;

            try
            {
                MetadataSet metadata = client.GetMetadata(address);
                if (this.useXmlSerializer)
                {
                    importer = this.CreateXmlSerializerImporter(metadata);
                }
                else if (flag)
                {
                    importer = this.CreateDataContractSerializerImporter(metadata);
                }
                else
                {
                    importer = new WsdlImporter(metadata);
                }
                serviceEndpointsRetrieved = this.ImportWsdlPortType(new XmlQualifiedName(str4, str5), importer);
                ComPlusMexChannelBuilderMexCompleteTrace.Trace(TraceEventType.Verbose, 0x50024, "TraceCodeComIntegrationMexMonikerMetadataExchangeComplete", serviceEndpointsRetrieved);
            }
            catch (Exception exception)
            {
                if (Fx.IsFatal(exception))
                {
                    throw;
                }
                if (UriSchemeSupportsDisco(address.Uri))
                {
                    try
                    {
                        DiscoveryClientProtocol protocol = new DiscoveryClientProtocol {
                            UseDefaultCredentials = true,
                            AllowAutoRedirect     = true
                        };
                        protocol.DiscoverAny(address.Uri.AbsoluteUri);
                        protocol.ResolveAll();
                        MetadataSet metadataSet = new MetadataSet();
                        foreach (object obj2 in protocol.Documents.Values)
                        {
                            this.AddDocumentToSet(metadataSet, obj2);
                        }
                        if (this.useXmlSerializer)
                        {
                            importer = this.CreateXmlSerializerImporter(metadataSet);
                        }
                        else if (flag)
                        {
                            importer = this.CreateDataContractSerializerImporter(metadataSet);
                        }
                        else
                        {
                            importer = new WsdlImporter(metadataSet);
                        }
                        serviceEndpointsRetrieved = this.ImportWsdlPortType(new XmlQualifiedName(str4, str5), importer);
                        ComPlusMexChannelBuilderMexCompleteTrace.Trace(TraceEventType.Verbose, 0x50024, "TraceCodeComIntegrationMexMonikerMetadataExchangeComplete", serviceEndpointsRetrieved);
                        goto Label_0634;
                    }
                    catch (Exception exception2)
                    {
                        if (Fx.IsFatal(exception2))
                        {
                            throw;
                        }
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerFailedToDoMexRetrieve", new object[] { exception2.Message })));
                    }
                }
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerFailedToDoMexRetrieve", new object[] { exception.Message })));
            }
Label_0634:
            if (serviceEndpointsRetrieved.Count == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerContractNotFoundInRetreivedMex")));
            }
            foreach (ServiceEndpoint endpoint2 in serviceEndpointsRetrieved)
            {
                System.ServiceModel.Channels.Binding binding = endpoint2.Binding;
                if ((binding.Name == str6) && (binding.Namespace == str7))
                {
                    endpoint = endpoint2;
                    break;
                }
            }
            if (endpoint == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MonikerSyntaxException(System.ServiceModel.SR.GetString("MonikerNoneOfTheBindingMatchedTheSpecifiedBinding")));
            }
            this.contractDescription = endpoint.Contract;
            this.serviceEndpoint     = new ServiceEndpoint(this.contractDescription, endpoint.Binding, new EndpointAddress(new Uri(str8), identity, null));
            ComPlusMexChannelBuilderTrace.Trace(TraceEventType.Verbose, 0x50025, "TraceCodeComIntegrationMexChannelBuilderLoaded", endpoint.Contract, endpoint.Binding, str8);
        }
示例#30
0
 public MetadataProvisionService(MetadataSet metadata)
 {
     Metadata = metadata;
 }
示例#31
0
        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            MetadataSet metadata = GetExportedMetadata(serviceDescription);

            CustomizeMexEndpoints(serviceDescription, serviceHostBase, metadata);
        }