public static IAsyncResult BeginResolve(IEnumerable<ContractDescription> contracts, System.ServiceModel.EndpointAddress address, MetadataExchangeClient client, AsyncCallback callback, Object asyncState)
    {
      Contract.Requires(address != null);
      Contract.Ensures(Contract.Result<System.IAsyncResult>() != null);

      return default(IAsyncResult);
    }
Example #2
0
 static void UseWcf()
 {
     /*
      动态下载服务元数据
      */
     MetadataExchangeClient metaExchangeClient =
         new MetadataExchangeClient(
             new Uri("http://localhost:8002/ManualService"),
             MetadataExchangeClientMode.HttpGet
         );
     //下载元数据
     MetadataSet metadataSet = metaExchangeClient.GetMetadata();
     WsdlImporter importer = new WsdlImporter(metadataSet);
     ServiceEndpointCollection endpointCollection = importer.ImportAllEndpoints();
     IManulService manulProxy = null;
     foreach (ServiceEndpoint endPointItem in endpointCollection)
     {
         manulProxy = new ChannelFactory<IManulService>(
             endPointItem.Binding,
             endPointItem.Address
             ).CreateChannel();
         ((IChannel)manulProxy).Open();
         Console.WriteLine("WCF调用结果为:{0}",
             manulProxy.GetData());
         ((IChannel)manulProxy).Close();
     }
 }
Example #3
0
        static void GenerateVBCodeForService(Uri metadataAddress, string outputFile)
        {
            MetadataExchangeClient mexClient = new MetadataExchangeClient(metadataAddress, MetadataExchangeClientMode.HttpGet);
              mexClient.ResolveMetadataReferences = true;
              MetadataSet metaDocs = mexClient.GetMetadata();

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

              System.Collections.ObjectModel.Collection<ContractDescription> contracts = importer.ImportAllContracts();
              foreach (ContractDescription contract in contracts)
              {
            generator.GenerateServiceContractType(contract);
              }
              if (generator.Errors.Count != 0)
            throw new ApplicationException("There were errors during code compilation.");

              // Write the code dom.
              System.CodeDom.Compiler.CodeGeneratorOptions options = new System.CodeDom.Compiler.CodeGeneratorOptions();
              options.BracingStyle = "C";
              System.CodeDom.Compiler.CodeDomProvider codeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("VB");
              System.CodeDom.Compiler.IndentedTextWriter textWriter = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(outputFile));
              codeDomProvider.GenerateCodeFromCompileUnit(generator.TargetCompileUnit, textWriter, options);
              textWriter.Close();
        }
Example #4
0
        /// <summary>
        /// Find the wsdl importer
        /// </summary>
        /// <param name="wsdlUri">The wsdl uri</param>
        /// <returns>A wsdl importer</returns>
        private WsdlImporter GetWsdlImporter(Uri wsdlUri)
        {
            WSHttpBinding mexBinding = null;
            var           mode       = System.ServiceModel.Description.MetadataExchangeClientMode.HttpGet;

            if (wsdlUri.Scheme == Uri.UriSchemeHttp)
            {
                mexBinding = (WSHttpBinding)System.ServiceModel.Description.MetadataExchangeBindings.CreateMexHttpBinding();
            }
            else
            {
                mexBinding = (WSHttpBinding)System.ServiceModel.Description.MetadataExchangeBindings.CreateMexHttpsBinding();
            }
            mexBinding.MaxReceivedMessageSize = 2147483647;
            mexBinding.MaxBufferPoolSize      = int.MaxValue;
            mexBinding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
            mexBinding.ReaderQuotas.MaxNameTableCharCount  = int.MaxValue;
            mexBinding.ReaderQuotas.MaxArrayLength         = int.MaxValue;
            mexBinding.ReaderQuotas.MaxBytesPerRead        = int.MaxValue;
            mexBinding.ReaderQuotas.MaxDepth = 64;

            var mexClient = new System.ServiceModel.Description.MetadataExchangeClient(mexBinding);

            mexClient.MaximumResolvedReferences = int.MaxValue;

            var metadataSet = mexClient.GetMetadata(wsdlUri, mode);

            return(new System.ServiceModel.Description.WsdlImporter(metadataSet));
        }
 void DiscoverMexMetadata(object sender, DoWorkEventArgs e)
 {
     Uri url = (Uri)e.Argument;
     var client = new MetadataExchangeClient(url, MetadataExchangeClientMode.MetadataExchange);
     MetadataSet metadata = client.GetMetadata();
     e.Result = new ServiceReferenceDiscoveryEventArgs(metadata);
 }
 internal AsyncMetadataResolverHelper(EndpointAddress address, MetadataExchangeClientMode mode, MetadataExchangeClient client, IEnumerable <ContractDescription> knownContracts, AsyncCallback callback, object asyncState) : base(callback, asyncState)
 {
     this.address        = address;
     this.client         = client;
     this.mode           = mode;
     this.knownContracts = knownContracts;
     this.GetMetadataSetAsync();
 }
Example #7
0
		static ServiceEndpointCollection QueryMexEndpoint(string mexAddress, BindingElement bindingElement)
		{
			var binding = new CustomBinding(bindingElement);
			var MEXClient = new MetadataExchangeClient(binding);
			var metadata = MEXClient.GetMetadata(new EndpointAddress(mexAddress));
			var importer = new WsdlImporter(metadata);
			return importer.ImportAllEndpoints();
		}
    public static IAsyncResult BeginResolve(IEnumerable<ContractDescription> contracts, Uri address, MetadataExchangeClientMode mode, MetadataExchangeClient client, AsyncCallback callback, Object asyncState)
    {
      Contract.Requires(address != null);
      Contract.Requires(address.IsAbsoluteUri);
      Contract.Ensures(Contract.Result<System.IAsyncResult>() != null);

      return default(IAsyncResult);
    }
Example #9
0
 static void Main(string[] args)
 {
     MetadataExchangeClient metadataExchangeClient = new MetadataExchangeClient(new Uri("http://127.0.0.1:3721/calculatorservice/metadata"), MetadataExchangeClientMode.HttpGet);
     metadataExchangeClient.ResolveMetadataReferences = false;
     MetadataSet metadata = metadataExchangeClient.GetMetadata();
     using (XmlWriter writer = new XmlTextWriter("metadata.xml", Encoding.UTF8))
     {
         metadata.WriteTo(writer);
     }
     Process.Start("metadata.xml");
 }
Example #10
0
 static void Main(string[] args)
 {
     Console.WriteLine("URI of the metadata documetns retreived");
     //MetadataExchangeClient metaTransfer = new MetadataExchangeClient(new Uri("http://localhost:1169/Service1.svc/mex"), MetadataExchangeClientMode.MetadataExchange);
     MetadataExchangeClient metaTransfer = new MetadataExchangeClient(new Uri("http://localhost:1169/Service1.svc"), MetadataExchangeClientMode.HttpGet);
     metaTransfer.ResolveMetadataReferences = true;
     MetadataSet metadata = metaTransfer.GetMetadata();
     foreach (MetadataSection doc in metadata.MetadataSections)
         Console.WriteLine(doc.Dialect + " : " + doc.Metadata);
     Console.ReadLine();
 }
      static ServiceEndpointCollection QueryMexEndpoint(string mexAddress,Binding binding,TokenProvider tokenProvider)
      {
         dynamic extendedBinding = binding;
         extendedBinding.MaxReceivedMessageSize *= MessageSizeMultiplier;

         MetadataExchangeClient mexClient = new MetadataExchangeClient(extendedBinding);
         mexClient.SetServiceBusCredentials(tokenProvider);
         MetadataSet metadata = mexClient.GetMetadata(new EndpointAddress(mexAddress));
         MetadataImporter importer = new WsdlImporter(metadata);
         return importer.ImportAllEndpoints();
      }
Example #12
0
      static ServiceEndpointCollection QueryMexEndpoint(string mexAddress,BindingElement bindingElement)
      {
         dynamic element = bindingElement;
         element.MaxReceivedMessageSize *= MessageSizeMultiplier;

         CustomBinding binding = new CustomBinding(element);
         
         MetadataExchangeClient mexClient = new MetadataExchangeClient(binding);
         MetadataSet metadata = mexClient.GetMetadata(new EndpointAddress(mexAddress));
         MetadataImporter importer = new WsdlImporter(metadata);
         return importer.ImportAllEndpoints();
      }
Example #13
0
        // 5.
        public static ServiceEndpointCollection Resolve(
            IEnumerable <ContractDescription> contracts,
            EndpointAddress address,
            MetadataExchangeClient client)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            return(ResolveContracts(contracts, () => client.GetMetadata(address)));
        }
        static void Main()
        {
            // Specify the Metadata Exchange binding and its security mode
            WSHttpBinding mexBinding = new WSHttpBinding(SecurityMode.Message);
            mexBinding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;

            // Create a MetadataExchangeClient for retrieving metadata, and set the certificate details
            MetadataExchangeClient mexClient = new MetadataExchangeClient(mexBinding);
            mexClient.SoapCredentials.ClientCertificate.SetCertificate(
                StoreLocation.CurrentUser, StoreName.My,
                X509FindType.FindBySubjectName, "client.com");
            mexClient.SoapCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerOrChainTrust;
            mexClient.SoapCredentials.ServiceCertificate.SetDefaultCertificate(
                StoreLocation.CurrentUser, StoreName.TrustedPeople,
                X509FindType.FindBySubjectName, "localhost");

            // The contract we want to fetch metadata for
            Collection<ContractDescription> contracts = new Collection<ContractDescription>();
            ContractDescription contract = ContractDescription.GetContract(typeof(ICalculator));
            contracts.Add(contract);

            // Find endpoints for that contract
            EndpointAddress mexAddress = new EndpointAddress(ConfigurationManager.AppSettings["mexAddress"]);
            ServiceEndpointCollection endpoints = MetadataResolver.Resolve(contracts,
                mexAddress, mexClient);

            // Communicate with each endpoint that supports the ICalculator contract.
            foreach (ServiceEndpoint endpoint in endpoints)
            {
                if (endpoint.Contract.Namespace.Equals(contract.Namespace) && endpoint.Contract.Name.Equals(contract.Name))
                {
                    // Create a channel and set the certificate details to communicate with the Application endpoint
                    ChannelFactory<ICalculator> cf = new ChannelFactory<ICalculator>(endpoint.Binding, endpoint.Address);
                    cf.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My,
                        X509FindType.FindBySubjectName, "client.com");
                    cf.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerOrChainTrust;

                    ICalculator channel = cf.CreateChannel();

                    // call operations
                    DoCalculations(channel);

                    ((IChannel)channel).Close();
                    cf.Close();

                 }
            }

            Console.WriteLine();
            Console.WriteLine("Press <ENTER> to terminate client.");
            Console.ReadLine();
             
        }
        private MetadataSet GetMetaDataDocs(EndpointAddress metadataAddress)
        {
            var binding = new WSHttpBinding(SecurityMode.Transport);
            binding.MaxReceivedMessageSize = Int32.MaxValue;
            binding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue;
            var mexClient = new MetadataExchangeClient(binding)
            {
                ResolveMetadataReferences = true,
                MaximumResolvedReferences = 1000
            };

            var metaDocs = mexClient.GetMetadata(metadataAddress.Uri, MetadataExchangeClientMode.HttpGet);
            return metaDocs;
        }
        private WsdlImporter CreateImporter(EndPointSetting wsdl)
        {
            var endpoint = new EndpointAddress(wsdl.Uri);

            var binding = new WSHttpBinding(SecurityMode.None)
            {
                MaxReceivedMessageSize = Int32.MaxValue,
            };

            var mex = new MetadataExchangeClient(binding);
            mex.ResolveMetadataReferences = true;

            var metaDocs = mex.GetMetadata(new Uri(wsdl.Uri), MetadataExchangeClientMode.HttpGet);
            return new WsdlImporter(metaDocs);
        }
 public static IAsyncResult BeginResolve(IEnumerable<ContractDescription> contracts, EndpointAddress address, MetadataExchangeClient client, AsyncCallback callback, object asyncState)
 {
     if (address == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address");
     }
     if (client == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("client");
     }
     if (contracts == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contracts");
     }
     ValidateContracts(contracts);
     return new AsyncMetadataResolverHelper(address, MetadataExchangeClientMode.MetadataExchange, client, contracts, callback, asyncState);
 }
Example #18
0
        public WebService(string path)
        {
            var metadataAddress = new EndpointAddress(path);
            var mexClient = new MetadataExchangeClient(metadataAddress.Uri, MetadataExchangeClientMode.HttpGet);
            mexClient.ResolveMetadataReferences = true;

            var metadata = mexClient.GetMetadata(metadataAddress.Uri, MetadataExchangeClientMode.HttpGet);
            var metadataSet = new MetadataSet(metadata.MetadataSections);

            var importer = new WsdlImporter(metadataSet);

            AllWsdlDocuments = importer.WsdlDocuments;
            AllContracts = importer.ImportAllContracts();
            AllBindings = importer.ImportAllBindings();
            AllEndpoints = importer.ImportAllEndpoints();

            //AllContracts.First().Operations.First().
        }
Example #19
0
 static void Main(string[] args)
 {
     Binding binding = MetadataExchangeBindings.CreateMexHttpBinding();
     EndpointAddress address = new EndpointAddress("http://127.0.0.1:9999/calculatorservice/mex");
     MetadataExchangeClient metadataExchangeClient = new MetadataExchangeClient(binding);
     MetadataSet metadata = metadataExchangeClient.GetMetadata(address);
     WsdlImporter wsdlImporter = new WsdlImporter(metadata);
     //添加已知契约类型
     ContractDescription contract = ContractDescription.GetContract(typeof(ICalculator));
     wsdlImporter.KnownContracts.Add(new XmlQualifiedName(contract.Name, contract.Namespace), contract);
     ServiceEndpointCollection endpoints = wsdlImporter.ImportAllEndpoints();
     using (ChannelFactory<ICalculator> channelFactory = new ChannelFactory<ICalculator>(endpoints[0]))
     {
         ICalculator calculator = channelFactory.CreateChannel();
         Console.WriteLine("x + y = {2} when x = {0} and y = {1}", 1, 2, calculator.Add(1, 2));
     }
     Console.Read();
 }
        public static ServiceEndpointCollection Resolve(IEnumerable<ContractDescription> contracts, Uri address, MetadataExchangeClientMode mode, MetadataExchangeClient client)
        {
            if (address == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address");
            }
            MetadataExchangeClientModeHelper.Validate(mode);
            if (client == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("client");
            }
            if (contracts == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contracts");
            }
            ValidateContracts(contracts);

            MetadataSet metadataSet = client.GetMetadata(address, mode);
            return ImportEndpoints(metadataSet, contracts, client);
        }
        private WsdlImporter CreateImporter(EndPointSetting wsdl)
        {
            var endpoint = new EndpointAddress(wsdl.Uri);

            var binding = new WSHttpBinding(SecurityMode.None)
            {
                MaxReceivedMessageSize = Int32.MaxValue,
            };

            var mex = new MetadataExchangeClient(binding);
            mex.ResolveMetadataReferences = true;

            var sections = new SingleEnumerable<EndpointAddress>(endpoint)
                                    .Select(ma => mex.GetMetadata(ma.Uri, MetadataExchangeClientMode.HttpGet))
                                    .SelectMany(mds => mds.MetadataSections);

            var metaDocs = new MetadataSet(sections);

            return new WsdlImporter(metaDocs);
        }
		static MetadataSet ResolveWithWSMex (string url)
		{
			MetadataSet metadata = null;
			try {
				var client = new MetadataExchangeClient (new EndpointAddress (url));

				Console.WriteLine ("\nAttempting to download metadata from {0} using WS-MetadataExchange..", url);
				metadata = client.GetMetadata ();
			} catch (InvalidOperationException e) {
				//MetadataExchangeClient wraps exceptions, thrown while
				//fetching the metadata, in an InvalidOperationException
				string msg;
				msg = e.InnerException == null ? e.Message : e.InnerException.ToString ();

				Console.WriteLine ("WS-MetadataExchange query failed for the url '{0}' with exception :\n {1}",
					url, msg);
			}

			return metadata;
		}
Example #23
0
        static void GenerateVBCodeForService(EndpointAddress metadataAddress, string outputFile)
        {
          MetadataExchangeClient mexClient = new MetadataExchangeClient(metadataAddress);
          mexClient.ResolveMetadataReferences = true;
          MetadataSet metaDocs = mexClient.GetMetadata();

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

          // Uncomment the following code if you are going to do your work programmatically rather than add 
          // the WsdlDocumentationImporters through a configuration file. 
          /*
          // The following code inserts the custom WSDL programmatically adding the custom WsdlImporter without
          // removing the other importers already in the collection.
          System.Collections.Generic.IEnumerable<IWsdlImportExtension> exts = importer.WsdlExtensions;
          System.Collections.Generic.List<IWsdlImportExtension> newExts = new System.Collections.Generic.List<IWsdlImportExtension>();
          foreach (IWsdlImportExtension ext in exts)
            newExts.Add(ext);
          newExts.Add(new WsdlDocumentationImporter());
          importer = new WsdlImporter(newExts.ToArray(), metaDocs.MetadataSections);
          */

          System.Collections.ObjectModel.Collection<ContractDescription> contracts = importer.ImportAllContracts();
          foreach (ContractDescription contract in contracts)
          {
            generator.GenerateServiceContractType(contract);
          }
          if (generator.Errors.Count != 0)
            throw new ApplicationException("There were errors during code compilation.");

          // Write the code dom.
          System.CodeDom.Compiler.CodeGeneratorOptions options = new System.CodeDom.Compiler.CodeGeneratorOptions();
          options.BracingStyle = "C";
          System.CodeDom.Compiler.CodeDomProvider codeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("VB");
          System.CodeDom.Compiler.IndentedTextWriter textWriter = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(outputFile));
          codeDomProvider.GenerateCodeFromCompileUnit(generator.TargetCompileUnit, textWriter, options);
          textWriter.Close();
        }
      static ServiceEndpointCollection QueryMexEndpoint(string mexAddress,Binding binding,string issuer,string secret)
      {
         Binding extendedBinding = null;

         if(binding is NetTcpRelayBinding)
         {
            NetTcpRelayBinding actualBinding = binding as NetTcpRelayBinding;
            actualBinding.MaxReceivedMessageSize *= MessageSizeMultiplier;
            extendedBinding = actualBinding;
         }
         if(binding is WS2007HttpRelayBinding)
         {
            WS2007HttpRelayBinding actualBinding = binding as WS2007HttpRelayBinding;
            actualBinding.MaxReceivedMessageSize *= MessageSizeMultiplier;
            extendedBinding = actualBinding;
         }

         MetadataExchangeClient mexClient = new MetadataExchangeClient(extendedBinding);
         mexClient.SetServiceBusCredentials(issuer,secret);
         MetadataSet metadata = mexClient.GetMetadata(new EndpointAddress(mexAddress));
         MetadataImporter importer = new WsdlImporter(metadata);
         return importer.ImportAllEndpoints();
      }
Example #25
0
        static void Main()
        {
            // Create a MetadataExchangeClient for retrieving metadata.
            EndpointAddress mexAddress = new EndpointAddress(ConfigurationManager.AppSettings["mexAddress"]);
            MetadataExchangeClient mexClient = new MetadataExchangeClient(mexAddress);

            // Retrieve the metadata for all endpoints using metadata exchange protocol (mex).
            MetadataSet metadataSet = mexClient.GetMetadata();

            //Convert the metadata into endpoints
            WsdlImporter importer = new WsdlImporter(metadataSet);
            ServiceEndpointCollection endpoints = importer.ImportAllEndpoints();

            CalculatorClient client = null;
            ContractDescription contract = ContractDescription.GetContract(typeof(ICalculator));
            // Communicate with each endpoint that supports the ICalculator contract.
            foreach (ServiceEndpoint ep in endpoints)
            {
                if (ep.Contract.Namespace.Equals(contract.Namespace) && ep.Contract.Name.Equals(contract.Name))
                {
                    // Create a client using the endpoint address and binding.
                    client = new CalculatorClient(ep.Binding, new EndpointAddress(ep.Address.Uri));
                    Console.WriteLine("Communicate with endpoint: ");
                    Console.WriteLine("   AddressPath={0}", ep.Address.Uri.PathAndQuery);
                    Console.WriteLine("   Binding={0}", ep.Binding.Name);
                    // call operations
                    DoCalculations(client);

                    //Closing the client gracefully closes the connection and cleans up resources
                    client.Close();
                }
            }

            Console.WriteLine();
            Console.WriteLine("Press <ENTER> to terminate client.");
            Console.ReadLine();
        }
Example #26
0
 // 6
 public static IAsyncResult BeginResolve(IEnumerable <ContractDescription> contracts, Uri address, MetadataExchangeClientMode mode, MetadataExchangeClient client, AsyncCallback callback, object asyncState)
 {
     return(resolver.BeginInvoke(contracts, () => client.GetMetadata(address, mode), callback, asyncState));
 }
Example #27
0
        void DownloadWeb(model.IProxy proxy, out List<wsdlDescription.ServiceDescription> descriptions, out List<XmlSchema> schemas)
        {
            descriptions = new List<wsdlDescription.ServiceDescription>();
            schemas = new List<XmlSchema>();

            MetadataExchangeClient client;
            MetadataExchangeClientMode exchangeMode;

            if (_wsdlEndpoint.EndsWith("mex")) {

                WSHttpBinding mexBinding = utils.BindingWrapper.GetMexBinding(proxy);

                client = new MetadataExchangeClient(mexBinding);
                exchangeMode = MetadataExchangeClientMode.MetadataExchange;
            }
            else {

                BasicHttpBinding wsdlBinding = utils.BindingWrapper.GetWsdlBinding(proxy);

                client = new MetadataExchangeClient(wsdlBinding);
                exchangeMode = MetadataExchangeClientMode.HttpGet;

            }

            client.ResolveMetadataReferences = true;
            client.OperationTimeout = new TimeSpan(0, 0, _timeoutInSeconds);

            MetadataSet metadata = client.GetMetadata(new Uri(_wsdlEndpoint), exchangeMode);

            foreach (var metaDataSection in metadata.MetadataSections) {
                if (metaDataSection.Metadata is wsdlDescription.ServiceDescription) {
                    descriptions.Add((wsdlDescription.ServiceDescription)metaDataSection.Metadata);
                }
                else if (metaDataSection.Metadata is XmlSchema) {
                    schemas.Add((XmlSchema)metaDataSection.Metadata);
                }
            }
        }
		public void CanPubishMEXEndpointsWithoutBaseAddressesUsingCustomAddress()
		{
			using (new WindsorContainer()
				.AddFacility<WcfFacility>(f =>
				{
					f.DefaultBinding = new NetTcpBinding { PortSharingEnabled = true };
					f.CloseTimeout = TimeSpan.Zero;
				}
				)
				.Register(Component.For<Operations>()
					.DependsOn(new { number = 42 })
					.AsWcfService(new DefaultServiceModel().AddEndpoints(
						WcfEndpoint.ForContract<IOperations>()
							.At("net.tcp://localhost/Operations"))
					.PublishMetadata(mex => mex.AtAddress("tellMeAboutYourSelf"))
				)))
			{
				var tcpMextClient = new MetadataExchangeClient(new EndpointAddress("net.tcp://localhost/Operations/tellMeAboutYourSelf"));
				var tcpMetadata = tcpMextClient.GetMetadata();
				Assert.IsNotNull(tcpMetadata);
			}
		}
		public void CanPubishMEXEndpointsUsingDefaults()
		{
			using (new WindsorContainer()
				.AddFacility<WcfFacility>(f => f.CloseTimeout = TimeSpan.Zero)
				.Register(Component.For<Operations>()
					.DependsOn(new { number = 42 })
					.AsWcfService(new DefaultServiceModel()
						.AddBaseAddresses(
							"net.tcp://localhost/Operations",
							"http://localhost:27198/UsingWindsor.svc")
						.AddEndpoints(
							WcfEndpoint.ForContract<IOperations>()
								.BoundTo(new NetTcpBinding { PortSharingEnabled = true })
							)
						.PublishMetadata(mex => mex.EnableHttpGet())
					)
				))
			{
				var tcpMextClient = new MetadataExchangeClient(new EndpointAddress("net.tcp://localhost/Operations/mex"));
				var tcpMetadata = tcpMextClient.GetMetadata();
				Assert.IsNotNull(tcpMetadata);

				var httpMextClient = new MetadataExchangeClient(new EndpointAddress("http://localhost:27198/UsingWindsor.svc?wsdl"));
				var httpMetadata = httpMextClient.GetMetadata();
				Assert.IsNotNull(httpMextClient);
			}
		}
Example #30
0
        public static IAsyncResult BeginResolve(IEnumerable <ContractDescription> contracts, System.ServiceModel.EndpointAddress address, MetadataExchangeClient client, AsyncCallback callback, Object asyncState)
        {
            Contract.Requires(address != null);
            Contract.Ensures(Contract.Result <System.IAsyncResult>() != null);

            return(default(IAsyncResult));
        }
Example #31
0
        public static IAsyncResult BeginResolve(IEnumerable <ContractDescription> contracts, Uri address, MetadataExchangeClientMode mode, MetadataExchangeClient client, AsyncCallback callback, Object asyncState)
        {
            Contract.Requires(address != null);
            Contract.Requires(address.IsAbsoluteUri);
            Contract.Ensures(Contract.Result <System.IAsyncResult>() != null);

            return(default(IAsyncResult));
        }
Example #32
0
        public static ServiceEndpointCollection Resolve(IEnumerable <ContractDescription> contracts, Uri address, MetadataExchangeClientMode mode, MetadataExchangeClient client)
        {
            if (address == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address");
            }
            MetadataExchangeClientModeHelper.Validate(mode);
            if (client == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("client");
            }
            if (contracts == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contracts");
            }
            ValidateContracts(contracts);

            MetadataSet metadataSet = client.GetMetadata(address, mode);

            return(ImportEndpoints(metadataSet, contracts, client));
        }
Example #33
0
        private static ServiceEndpointCollection ImportEndpoints(MetadataSet metadataSet, IEnumerable <ContractDescription> contracts, MetadataExchangeClient client)
        {
            ServiceEndpointCollection endpoints = new ServiceEndpointCollection();

            WsdlImporter importer = new WsdlImporter(metadataSet);

            // remember the original proxy so user doesn't need to set it again
            importer.State.Add(MetadataExchangeClient.MetadataExchangeClientKey, client);

            foreach (ContractDescription cd in contracts)
            {
                importer.KnownContracts.Add(WsdlExporter.WsdlNamingHelper.GetPortTypeQName(cd), cd);
            }

            foreach (ContractDescription cd in contracts)
            {
                ServiceEndpointCollection contractEndpoints;
                contractEndpoints = importer.ImportEndpoints(cd);
                foreach (ServiceEndpoint se in contractEndpoints)
                {
                    endpoints.Add(se);
                }
            }

            //Trace all warnings and errors
            if (importer.Errors.Count > 0)
            {
                TraceWsdlImportErrors(importer);
            }

            return(endpoints);
        }
Example #34
0
        public static IAsyncResult BeginResolve(IEnumerable <ContractDescription> contracts, Uri address, MetadataExchangeClientMode mode, MetadataExchangeClient client,
                                                AsyncCallback callback, object asyncState)
        {
            if (address == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address");
            }
            MetadataExchangeClientModeHelper.Validate(mode);
            if (client == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("client");
            }
            if (contracts == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contracts");
            }
            ValidateContracts(contracts);

            return(new AsyncMetadataResolverHelper(new EndpointAddress(address), mode, client, contracts, callback, asyncState));
        }
Example #35
0
        public static ServiceEndpointCollection Resolve(IEnumerable <ContractDescription> contracts, System.ServiceModel.EndpointAddress address, MetadataExchangeClient client)
        {
            Contract.Requires(address != null);
            Contract.Ensures(Contract.Result <System.ServiceModel.Description.ServiceEndpointCollection>() != null);

            return(default(ServiceEndpointCollection));
        }
        private static ServiceEndpointCollection ImportEndpoints(MetadataSet metadataSet, IEnumerable <ContractDescription> contracts, MetadataExchangeClient client)
        {
            ServiceEndpointCollection endpoints = new ServiceEndpointCollection();
            WsdlImporter importer = new WsdlImporter(metadataSet);

            importer.State.Add("MetadataExchangeClientKey", client);
            foreach (ContractDescription description in contracts)
            {
                importer.KnownContracts.Add(WsdlExporter.WsdlNamingHelper.GetPortTypeQName(description), description);
            }
            foreach (ContractDescription description2 in contracts)
            {
                foreach (ServiceEndpoint endpoint in importer.ImportEndpoints(description2))
                {
                    endpoints.Add(endpoint);
                }
            }
            if (importer.Errors.Count > 0)
            {
                TraceWsdlImportErrors(importer);
            }
            return(endpoints);
        }
            public void ResolveTokenIssuerPolicy(MetadataImporter importer, PolicyConversionContext policyContext, IssuedSecurityTokenParameters parameters)
            {
                if (policyContext == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("policyContext");
                }
                if (parameters == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("parameters");
                }

                EndpointAddress mexAddress = (parameters.IssuerMetadataAddress != null) ? parameters.IssuerMetadataAddress : parameters.IssuerAddress;
                if (mexAddress == null || mexAddress.IsAnonymous || mexAddress.Uri.Equals(SelfIssuerUri))
                {
                    return;
                }
                int maximumRedirections = (int)importer.State[SecurityBindingElementImporter.MaxPolicyRedirectionsKey];

                if (maximumRedirections <= 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.MaximumPolicyRedirectionsExceeded)));
                }
                --maximumRedirections;

                //
                // Try to retrieve the proxy from the importer.State bag so that we can have secure mex
                // and it fails, then we can create a default one
                //
                MetadataExchangeClient policyFetcher = null;
                if ((importer.State != null) && (importer.State.ContainsKey(MetadataExchangeClient.MetadataExchangeClientKey)))
                {
                    policyFetcher = importer.State[MetadataExchangeClient.MetadataExchangeClientKey] as MetadataExchangeClient;
                }

                if (policyFetcher == null)
                    policyFetcher = new MetadataExchangeClient(mexAddress);

                ServiceEndpointCollection federationEndpoints = null;
                MetadataSet metadataSet = null;
                Exception mexException = null;
                try
                {
                    metadataSet = policyFetcher.GetMetadata(mexAddress);
                }
                catch (Exception e)
                {
                    if (Fx.IsFatal(e))
                        throw;
                    if (e is NullReferenceException)
                        throw;

                    mexException = e;
                }

                //
                // DCR 6729: Try the http get option here if mex failed.
                //
                if (metadataSet == null )
                {
                    try
                    {
                        metadataSet = policyFetcher.GetMetadata(mexAddress.Uri, MetadataExchangeClientMode.HttpGet);
                    }
                    catch (Exception e)
                    {
                        if (Fx.IsFatal(e))
                            throw;
                        if (e is NullReferenceException)
                            throw;

                        if (mexException == null)
                            mexException = e;
                    }
                }

                if (metadataSet == null)
                {
                    //
                    // we could not retrieve the metadata from the issuer for some reason
                    //
                    if (mexException != null)
                        importer.Errors.Add(new MetadataConversionError(SR.GetString(SR.UnableToObtainIssuerMetadata, mexAddress, mexException), false));
   
                    return;
                }
                WsdlImporter wsdlImporter;
                // NOTE: [....], Policy import/export is seperate from WSDL however, this policy importer
                //      invokes the WsdlImporter. In the event that the current MetadataImporter is a WsdlImporter,
                //      we should use it's collection of extensions for the import process. Other wise
                WsdlImporter currentWsdlImporter = importer as WsdlImporter;
                if (currentWsdlImporter != null)
                {
                    wsdlImporter = new WsdlImporter(metadataSet, importer.PolicyImportExtensions, currentWsdlImporter.WsdlImportExtensions);
                }
                else
                {
                    wsdlImporter = new WsdlImporter(metadataSet, importer.PolicyImportExtensions, null);
                }

                //
                // Copy the State from the first importer to the second one so that the state can be passed to the second round wsdl retrieval
                //
                if ((importer.State != null) && (importer.State.ContainsKey(MetadataExchangeClient.MetadataExchangeClientKey)))
                {
                    wsdlImporter.State.Add(MetadataExchangeClient.MetadataExchangeClientKey, importer.State[MetadataExchangeClient.MetadataExchangeClientKey]);
                }

                wsdlImporter.State.Add(SecurityBindingElementImporter.MaxPolicyRedirectionsKey, maximumRedirections);

                federationEndpoints = wsdlImporter.ImportAllEndpoints();

                // copy all the import errors into the current metadata importer
                for (int i = 0; i < wsdlImporter.Errors.Count; ++i)
                {
                    MetadataConversionError error = wsdlImporter.Errors[i];
                    importer.Errors.Add(new MetadataConversionError(SR.GetString(SR.ErrorImportingIssuerMetadata, mexAddress, InsertEllipsisIfTooLong(error.Message)), error.IsWarning));
                }

                if (federationEndpoints != null)
                {
                    AddCompatibleFederationEndpoints(federationEndpoints, parameters);
                    if (parameters.AlternativeIssuerEndpoints != null && parameters.AlternativeIssuerEndpoints.Count > 0)
                    {
                        importer.Errors.Add(new MetadataConversionError(SR.GetString(SR.MultipleIssuerEndpointsFound, mexAddress)));
                    }
                }
            }
Example #38
0
 public static IAsyncResult BeginResolve(Type contract, EndpointAddress address, MetadataExchangeClient client, AsyncCallback callback, object asyncState)
 {
     return(resolver.BeginInvoke(ToContracts(contract), () => client.GetMetadata(address), callback, asyncState));
 }
Example #39
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 HTTPS-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();
        }
 private static MetadataExchangeClient CreateMetadataExchangeClient(Uri serviceUri)
 {
     string scheme = serviceUri.Scheme;
     MetadataExchangeClient result = null;
     if (string.Compare(scheme, Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) == 0)
     {
         WSHttpBinding wSHttpBinding = (WSHttpBinding)MetadataExchangeBindings.CreateMexHttpBinding();
         wSHttpBinding.MaxReceivedMessageSize = 67108864L;
         wSHttpBinding.ReaderQuotas.MaxNameTableCharCount = 1048576;
         result = new MetadataExchangeClient(wSHttpBinding);
     }
     else
     {
         if (string.Compare(scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase) == 0)
         {
             WSHttpBinding wSHttpBinding2 = (WSHttpBinding)MetadataExchangeBindings.CreateMexHttpsBinding();
             wSHttpBinding2.MaxReceivedMessageSize = 67108864L;
             wSHttpBinding2.ReaderQuotas.MaxNameTableCharCount = 1048576;
             result = new MetadataExchangeClient(wSHttpBinding2);
         }
         else
         {
             if (string.Compare(scheme, Uri.UriSchemeNetTcp, StringComparison.OrdinalIgnoreCase) == 0)
             {
                 CustomBinding tcpBinding = (CustomBinding)MetadataExchangeBindings.CreateMexTcpBinding();
                 tcpBinding.Elements.Find<TcpTransportBindingElement>().MaxReceivedMessageSize = 67108864L;
                 result = new MetadataExchangeClient(tcpBinding);
             }
             else if (string.Compare(scheme, Uri.UriSchemeNetPipe, StringComparison.OrdinalIgnoreCase) != 0)
             {
                 CustomBinding namedPipeBinding = (CustomBinding)MetadataExchangeBindings.CreateMexNamedPipeBinding();
                 namedPipeBinding.Elements.Find<NamedPipeTransportBindingElement>().MaxReceivedMessageSize = 67108864L;
                 result = new MetadataExchangeClient(namedPipeBinding);
             }
         }
     }
     return result;
 }
Example #41
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();
        }
Example #42
-1
        private MetadataSet GetServiceMetadata(string wsdlUrl, MetadataExchangeClientMode clientMode, System.Net.NetworkCredential mexNetworkCredentials)
        {
            MetadataSet metadata = null;
            Binding mexBinding;

            if (clientMode == MetadataExchangeClientMode.HttpGet){
                mexBinding = new BasicHttpBinding { MaxReceivedMessageSize = 50000000L };
            }
            else
            {
                mexBinding = new WSHttpBinding(SecurityMode.None) { MaxReceivedMessageSize = 50000000L };
            }

            var mexClient = new MetadataExchangeClient(mexBinding)
            {
                ResolveMetadataReferences = true,
                MaximumResolvedReferences = 200,
                HttpCredentials = mexNetworkCredentials
            };

            try
            {
                metadata = mexClient.GetMetadata(new Uri(wsdlUrl), clientMode);
            } catch (Exception ex) {
                Console.WriteLine(String.Format("Error: {0}", ex.Message));
            }

            return metadata;
        }