Esempio n. 1
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();
        }
Esempio n. 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();
     }
 }
Esempio n. 3
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);
 }
Esempio n. 5
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();
		}
Esempio n. 6
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");
 }
Esempio n. 7
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();
      }
Esempio n. 9
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();
      }
        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;
        }
Esempio n. 11
0
        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 ServiceEndpointCollection Resolve(IEnumerable <ContractDescription> contracts, EndpointAddress address, MetadataExchangeClient client)
 {
     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(ImportEndpoints(client.GetMetadata(address), contracts, client));
 }
Esempio n. 13
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().
        }
Esempio n. 14
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);
        }
		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;
		}
Esempio n. 17
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();
        }
Esempio n. 18
0
      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();
      }
Esempio n. 19
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();
        }
Esempio n. 20
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;
            }
         }
      } 
		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);
			}
		}
Esempio n. 23
0
        // Code to generate the proxy
        public static string GenerateCSCodeForService(string gennamespace, EndpointAddress metadataAddress)
        {
            var mexClient = new MetadataExchangeClient(metadataAddress.Uri, MetadataExchangeClientMode.HttpGet);
            mexClient.ResolveMetadataReferences = true;

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

            var importer = new WsdlImporter(metadataSet);

            var importAllContracts = importer.ImportAllContracts();
            var codeDomProvider = CodeDomProvider.CreateProvider("CSharp");
            var output = new StringWriter();
            return string.Empty;
            //importer.ImportAllBindings()
            //return codeDomExperiment(gennamespace, codeDomProvider, output, importAllContracts);
            //            var generator = new ServiceContractGenerator();
            //            generator.Options = ServiceContractGenerationOptions.TypedMessages
            //                //| ServiceContractGenerationOptions.AsynchronousMethods
            //                //| ServiceContractGenerationOptions.ClientClass
            //                //| ServiceContractGenerationOptions.EventBasedAsynchronousMethods
            //                //| ServiceContractGenerationOptions.InternalTypes
            //                ;
            //            // This line enables a namespace wrapping all classes
            //            generator.NamespaceMappings.Add("*", gennamespace);
            //            //generator.NamespaceMappings.Add("?", gennamespace); // Contract descript namespace?
            //            importer.State.Remove(typeof (XsdDataContractExporter)); // This doesn't do anything in the sample
            //
            //            var importer2 = new XsdDataContractImporter();
            //            var options2 = new ImportOptions();
            //            options2.EnableDataBinding = true; // HERE we implement INotifyPropertyChanged
            //            options2.GenerateInternal = false; // Control if class is internal
            //            importer2.Options = options2;
            //            importer2.Options.Namespaces.Add("*", gennamespace);
            //            // Not used in sample but presumably allows array types to be mapped to a specific ienumerable<>
            //            importer2.Options.ReferencedCollectionTypes.Add(typeof (ObservableCollection<>));
            //
            //            // Here we override the default importer with our own,
            //            importer.State.Add(typeof (XsdDataContractImporter), importer2);
            //
            //
            //            Collection<ContractDescription> collection = importer.ImportAllContracts();
            //            importer.ImportAllEndpoints();
            //            foreach (ContractDescription description in collection)
            //            {
            //                generator.GenerateServiceContractType(description);
            //            }
            //            if (generator.Errors.Count != 0)
            //            {
            //                generator.Errors.ToList().ForEach(
            //                    mce => Console.WriteLine("{0}: {1}", mce.IsWarning ? "Warning" : "Error", mce.Message));
            //                throw new Exception("There were errors during code compilation.");
            //            }
            //            //new WcfSilverlightCodeGenerationExtension().ClientGenerated(generator);
            //            var options = new CodeGeneratorOptions();
            //
            //            var provider = CodeDomProvider.CreateProvider("C#");
            //
            //            var sb = new StringBuilder();
            //            var sw = new StringWriter(sb);
            //
            //            using (var writer = new IndentedTextWriter(sw))
            //            {
            //                provider.GenerateCodeFromCompileUnit(generator.TargetCompileUnit, writer, options);
            //            }
            //
            //            return sb.ToString();
        }
Esempio n. 24
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));
 }
Esempio n. 25
0
        public static ServiceEndpoint[] GetEndpoints(this EndpointAddress endpointAddress)
        {
            if (endpointAddress.IsNull() || endpointAddress.Uri == default(Uri))
                return null;
            Uri address = endpointAddress.Uri;

            // make sure url is end with '?wsdl'
            //if (address.AbsoluteUri.EndsWith("?wsdl", true, CultureInfo.InvariantCulture) == false)
            //{
            //    string wsdlAddress = address.AbsoluteUri + "?wsdl";
            //    address = new Uri(wsdlAddress);
            //}
            address = address.EnsureWsdl();
            ServiceEndpointCollection serviceEndpoints = null;
            BindingElement bindingElement = null;

            // address is http/https
            if (address.Scheme == Uri.UriSchemeHttp || address.Scheme == Uri.UriSchemeHttps)
            {
                if (address.Scheme == Uri.UriSchemeHttp)
                {
                    var httpBindingElement = new HttpTransportBindingElement();
                    httpBindingElement.MaxReceivedMessageSize *= 5; // default set
                    bindingElement = httpBindingElement;
                }
                else
                {
                    var httpsBindingElement = new HttpsTransportBindingElement();
                    httpsBindingElement.MaxReceivedMessageSize *= 5; // default set
                    bindingElement = httpsBindingElement;
                }

                try
                {
                    CustomBinding binding = new CustomBinding(bindingElement);
                    var mexClient = new MetadataExchangeClient(binding);
                    var metadata = mexClient.GetMetadata(address, MetadataExchangeClientMode.HttpGet);
                    serviceEndpoints = (new WsdlImporter(metadata)).ImportAllEndpoints();
                    return serviceEndpoints.ToArray();
                }
                catch
                {
                    // do nothing, try another metadata exchange to get metadata
                }
            }

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

            serviceEndpoints = QueryMexEndpoints(address.AbsoluteUri, bindingElement);
            return serviceEndpoints.ToArray();
        }
		public static IAsyncResult BeginResolve (Type contract, EndpointAddress address, MetadataExchangeClient client, AsyncCallback callback, object asyncState)
		{
			return resolver.BeginInvoke (ToContracts (contract), () => client.GetMetadata (address), callback, asyncState);
		}
		public static ServiceEndpointCollection Resolve (
				IEnumerable<ContractDescription> contracts,
				EndpointAddress address,
				MetadataExchangeClient client)
		{
			if (client == null)
				throw new ArgumentNullException ("client");

			return ResolveContracts (contracts, () => client.GetMetadata (address));
		}
Esempio n. 28
0
        private MetadataSet DiscoverMetadata(Uri address)
        {
            if (UriSchemeSupportsDisco(address) &&
                !IsMexUri(address))
            {
				return GetMetadataWithDiscovery(address);
            }
            else
            {
                MetadataExchangeClient metadataTransferClient = 
					new MetadataExchangeClient(address, MetadataExchangeClientMode.MetadataExchange);
                return metadataTransferClient.GetMetadata();
            }
        }
Esempio n. 29
0
      ServiceEndpointCollection GetEndpoints(BindingElement bindingElement)
      {
         CustomBinding binding = new CustomBinding(bindingElement);

         MetadataExchangeClient MEXClient = new MetadataExchangeClient(binding);
         MetadataSet metadata = MEXClient.GetMetadata(new EndpointAddress(m_MexAddressTextBox.Text));
         MetadataImporter importer = new WsdlImporter(metadata);
         return importer.ImportAllEndpoints();
      }
        /// <summary>
        /// compile our wsdl file
        /// </summary>
        /// <param name="astrWebServiceURI"></param>
        /// <param name="astrUsername"></param>
        /// <param name="astrPassword"></param>
        /// <param name="astrMethod"></param>
        /// <returns></returns>
        private compiledAssembly generateCompiledAssembly(string astrWebServiceURI, string astrUsername, string astrPassword, string astrMethod)
        {
            CompilerResults result = null;

            // Define the WSDL Get address, contract name and parameters, with this we can extract WSDL details any time
            //Uri address = new Uri("http://ifbenp.indfish.co.nz:16201/mws-ws/services/Vessel?wsdl"); //("http://localhost:64508/Service1.svc?wsdl");
            Uri address = new Uri(astrWebServiceURI);
            // For HttpGet endpoints use a Service WSDL address a mexMode of .HttpGet and for MEX endpoints use a MEX address and a mexMode of .MetadataExchange
            MetadataExchangeClientMode mexMode = MetadataExchangeClientMode.HttpGet;

            // Get the metadata file from the service.
            MetadataExchangeClient metadataExchangeClient = new MetadataExchangeClient(address, mexMode);
            metadataExchangeClient.ResolveMetadataReferences = true;

            //One can also provide credentials if service needs that by the help following two lines.
            ICredentials networkCredential = new NetworkCredential(astrUsername, astrPassword, "");
            metadataExchangeClient.HttpCredentials = networkCredential;

            //Gets the meta data information of the service.
            MetadataSet metadataSet = metadataExchangeClient.GetMetadata();

            // Import all contracts and endpoints.
            WsdlImporter wsdlImporter = new WsdlImporter(metadataSet);

            //Import all contracts.
            Collection<ContractDescription> contracts = wsdlImporter.ImportAllContracts();

            //Import all end points.
            ServiceEndpointCollection allEndpoints = wsdlImporter.ImportAllEndpoints();

            // Generate type information for each contract.
            ServiceContractGenerator serviceContractGenerator = new ServiceContractGenerator();

            //Dictinary has been defined to keep all the contract endpoints present, contract name is key of the dictionary item.
            var endpointsForContracts = new Dictionary<string, IEnumerable<ServiceEndpoint>>();

            string contractName = null;

            foreach (ContractDescription contract in contracts)
            {
                serviceContractGenerator.GenerateServiceContractType(contract);
                // Keep a list of each contract's endpoints.
                endpointsForContracts[contract.Name] = allEndpoints.Where(ep => ep.Contract.Name == contract.Name).ToList();
                contractName = contract.Name;
            }

            // Generate a code file for the contracts.
            CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions();
            codeGeneratorOptions.BracingStyle = "C";

            // Create Compiler instance of a specified language.
            CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("C#");

            // Adding WCF-related assemblies references as copiler parameters, so as to do the compilation of particular service contract.
            CompilerParameters compilerParameters = new CompilerParameters(new string[] { "System.dll", "System.ServiceModel.dll", "System.Runtime.Serialization.dll" });
            compilerParameters.GenerateInMemory = true;

            //Gets the compiled assembly.
            result = codeDomProvider.CompileAssemblyFromDom(compilerParameters, serviceContractGenerator.TargetCompileUnit);

            object proxyInstance = null;

            if (result.Errors.Count <= 0)
            {

                // Find the proxy type that was generated for the specified contract (identified by a class that implements the contract and ICommunicationbject - this is contract
                //implemented by all the communication oriented objects).
                Type proxyType = result.CompiledAssembly.GetTypes().First(t => t.IsClass && t.GetInterface(contractName) != null &&
                    t.GetInterface(typeof(ICommunicationObject).Name) != null);

                // Now we get the first service endpoint for the particular contract.
                ServiceEndpoint serviceEndpoint = endpointsForContracts[contractName].First();

                BasicHttpBinding newBinding = new BasicHttpBinding();

                newBinding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
                newBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
                newBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
                newBinding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Default;

                newBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;

                serviceEndpoint.Binding = newBinding;

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

                PropertyInfo clientCredentials = proxyType.GetProperty("ClientCredentials");
                if(null != clientCredentials)
                {
                    ClientCredentials credentials = new ClientCredentials();
                    credentials.UserName.UserName = astrUsername;
                    credentials.UserName.Password = astrPassword;

                    object objCredentials = clientCredentials.GetValue(proxyInstance);
                    credentials = objCredentials as ClientCredentials;

                    if (null != credentials)
                    {
                        credentials.UserName.Password = astrPassword;
                        credentials.UserName.UserName = astrUsername;
                    }
                }
            }

            compiledAssembly finalResults = new compiledAssembly() { compilerResults = result, instantiatedObject = proxyInstance };

            return (finalResults);
        }
Esempio n. 31
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();
        }
Esempio n. 32
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();
        }
Esempio n. 33
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));
 }
Esempio n. 34
-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;
        }