示例#1
0
        internal MetadataSet GetMetadataInternal(EndpointAddress address, MetadataExchangeClientMode mode)
        {
            if (binding == null)
            {
                binding = MetadataExchangeBindings.CreateMexHttpBinding();
            }

            MetadataProxy proxy = new MetadataProxy(binding, address);

            proxy.Open();

            SMMessage msg = SMMessage.CreateMessage(
                MessageVersion.Soap12WSAddressing10,
                "http://schemas.xmlsoap.org/ws/2004/09/transfer/Get");

            msg.Headers.ReplyTo = new EndpointAddress(
                "http://www.w3.org/2005/08/addressing/anonymous");
            //msg.Headers.From = new EndpointAddress ("http://localhost");
            msg.Headers.To        = address.Uri;
            msg.Headers.MessageId = new UniqueId();

            SMMessage ret;

            try {
                ret = proxy.Get(msg);
            } catch (Exception e) {
                throw new InvalidOperationException(
                          "Metadata contains a reference that cannot be resolved : " + address.Uri.AbsoluteUri, e);
            }

            return(MetadataSet.ReadFrom(ret.GetReaderAtBodyContents()));
        }
    public static IAsyncResult BeginResolve(Type contract, Uri address, MetadataExchangeClientMode mode, AsyncCallback callback, Object asyncState)
    {
      Contract.Requires(address != null);
      Contract.Ensures(Contract.Result<System.IAsyncResult>() != null);

      return default(IAsyncResult);
    }
示例#3
0
        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);
        }
 public static void Validate(MetadataExchangeClientMode value)
 {
     if (!IsDefined(value))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("value", (int)value, typeof(MetadataExchangeClientMode)));
     }
 }
示例#5
0
        public static IAsyncResult BeginResolve(Type contract, Uri address, MetadataExchangeClientMode mode, AsyncCallback callback, Object asyncState)
        {
            Contract.Requires(address != null);
            Contract.Ensures(Contract.Result <System.IAsyncResult>() != null);

            return(default(IAsyncResult));
        }
示例#6
0
        public static ServiceEndpointCollection Resolve(Type contract, Uri address, MetadataExchangeClientMode mode)
        {
            Contract.Requires(address != null);
            Contract.Ensures(Contract.Result <System.ServiceModel.Description.ServiceEndpointCollection>() != null);

            return(default(ServiceEndpointCollection));
        }
示例#7
0
 public static ServiceEndpointCollection Resolve(
     Type contract,
     Uri address,
     MetadataExchangeClientMode mode)
 {
     return(Resolve(ToContracts(contract), address, mode));
 }
 public static void Validate(MetadataExchangeClientMode value)
 {
     if (!IsDefined(value))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("value", (int) value, typeof(MetadataExchangeClientMode)));
     }
 }
示例#9
0
 // 4.
 public static ServiceEndpointCollection Resolve(
     IEnumerable <ContractDescription> contracts,
     Uri address,
     MetadataExchangeClientMode mode)
 {
     return(Resolve(contracts, new EndpointAddress(address), new MetadataExchangeClient(address, mode)));
 }
        public FactoryServiceHelper(Uri url)
        {
            adresse = url;
            Uri mexAddress = new Uri(adresse.ToString() + "?wsdl");
            //for MEX endpoints use a MEX address and a mexMode of .MetadataExchange
            MetadataExchangeClientMode mexMode   = MetadataExchangeClientMode.HttpGet;
            MetadataExchangeClient     mexClient = new MetadataExchangeClient(mexAddress, mexMode);

            mexClient.ResolveMetadataReferences = true;
            serviceMetadata = mexClient.GetMetadata();

            WsdlImporter importer = new WsdlImporter(serviceMetadata);

            System.Collections.ObjectModel.Collection <ContractDescription> contracts = importer.ImportAllContracts();

            BasicHttpBinding Binding = new BasicHttpBinding();
            EndpointAddress  address = new EndpointAddress(adresse.ToString());

            ChannelFactory <IRequestChannel> factory =
                new ChannelFactory <IRequestChannel>(Binding, address);

            serviceChannel  = factory.CreateChannel();
            serviceInfo     = contracts[0];
            targetNamespace = serviceInfo.Namespace;
            serviceName     = serviceInfo.Name;
        }
    public static IAsyncResult BeginResolve(IEnumerable<ContractDescription> contracts, Uri address, MetadataExchangeClientMode mode, AsyncCallback callback, Object asyncState)
    {
      Contract.Requires(address != null);
      Contract.Requires(address.IsAbsoluteUri);
      Contract.Ensures(Contract.Result<System.IAsyncResult>() != null);

      return default(IAsyncResult);
    }
 public static IAsyncResult BeginResolve(Type contract, Uri address, MetadataExchangeClientMode mode, AsyncCallback callback, object asyncState)
 {
     if (contract == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contract");
     }
     return(BeginResolve(CreateContractCollection(contract), address, mode, callback, asyncState));
 }
 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();
 }
 public static ServiceEndpointCollection Resolve(Type contract, Uri address, MetadataExchangeClientMode mode)
 {
     if (contract == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contract");
     }
     return(Resolve(CreateContractCollection(contract), address, mode));
 }
 public static bool IsDefined(MetadataExchangeClientMode x)
 {
     if (x != MetadataExchangeClientMode.MetadataExchange)
     {
         return (x == MetadataExchangeClientMode.HttpGet);
     }
     return true;
 }
 public static IAsyncResult BeginResolve(Type contract, Uri address, MetadataExchangeClientMode mode, AsyncCallback callback, object asyncState)
 {
     if (contract == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contract");
     }
     return BeginResolve(CreateContractCollection(contract), address, mode, callback, asyncState);
 }
 public static bool IsDefined(MetadataExchangeClientMode x)
 {
     if (x != MetadataExchangeClientMode.MetadataExchange)
     {
         return(x == MetadataExchangeClientMode.HttpGet);
     }
     return(true);
 }
        public static ServiceEndpointCollection Resolve(Type contract, Uri address, MetadataExchangeClientMode mode)
        {
            if (contract == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contract");
            }

            return Resolve(CreateContractCollection(contract), address, mode);
        }
示例#19
0
        /// <summary>
        /// Generates the service model client configuration code for the endpoint.
        /// </summary>
        /// <param name="endpointAddress">The metadata endpoint address.</param>
        /// <param name="mexMode">The metadata exchange client mode.</param>
        /// <param name="operationTimeout">The operation time.</param>
        /// <param name="xmlFile">The name of the file where client configuration is written,
        /// the file is created in the same path as the application configuration file (debug or release).</param>
        public static void GenerateServiceModelClientConfigurationCode(EndpointAddress endpointAddress,
                                                                       MetadataExchangeClientMode mexMode, TimeSpan operationTimeout, string xmlFile)
        {
            // Get the meta data set from the endpoint.
            System.ServiceModel.Description.MetadataSet docs =
                Nequeo.Net.ServiceModel.ServiceModelInformation.GetServiceMetadata(endpointAddress, mexMode, operationTimeout);

            // Generate the code file
            GenerateServiceModelEndpoints(docs, xmlFile, Nequeo.Handler.Common.InfoHelper.GetApplicationConfigurationFile());
        }
示例#20
0
        /// <summary>
        /// Generates the service model client code for the endpoint.
        /// </summary>
        /// <param name="endpointAddress">The metadata endpoint address.</param>
        /// <param name="mexMode">The metadata exchange client mode.</param>
        /// <param name="operationTimeout">The operation time.</param>
        /// <param name="codeFilePath">The full path an file name where the C# code is written</param>
        public static void GenerateServiceModelClientCode(EndpointAddress endpointAddress,
                                                          MetadataExchangeClientMode mexMode, TimeSpan operationTimeout, string codeFilePath)
        {
            // Get the meta data set from the endpoint.
            System.ServiceModel.Description.MetadataSet docs =
                Nequeo.Net.ServiceModel.ServiceModelInformation.GetServiceMetadata(endpointAddress, mexMode, operationTimeout);

            // Generate the code file
            GenerateServiceModelClient(docs, codeFilePath);
        }
示例#21
0
        private async Task <bool> ResolveMetadataAsync(Uri serviceUri, MetadataExchangeClientMode metadataExchangeMode, bool captureException, CancellationToken cancellationToken)
        {
            bool authenticateUser;

            do
            {
                try
                {
                    authenticateUser = false;
                    _currentRequest  = null;
                    cancellationToken.ThrowIfCancellationRequested();

                    IAsyncResult result = this.BeginGetMetadata(serviceUri, metadataExchangeMode, null, null);

                    while (!result.IsCompleted)
                    {
                        if (cancellationToken.IsCancellationRequested)
                        {
                            _currentRequest?.Abort();
                            cancellationToken.ThrowIfCancellationRequested();
                        }
                        await Task.Delay(100);
                    }

                    _metadataSet         = this.EndGetMetadata(result);
                    _metadataException   = null;
                    _clientAuthenticated = true;
                }
                catch (Exception ex)
                {
                    if (Utils.IsFatalOrUnexpected(ex))
                    {
                        throw;
                    }

                    authenticateUser = RequiresAuthentication(ex, serviceUri, out bool isAuthError);
                    if (isAuthError)
                    {
                        // the user could not be authenticated.
                        // observe that we don't throw if the user doesn't need to be authenticated exceptions can be capture below.
                        throw;
                    }

                    if (captureException)
                    {
                        _metadataException = ex;
                    }
                }
            }while (authenticateUser);

            return(this.HasServiceMetadata);
        }
示例#22
0
        // 6.
        public static ServiceEndpointCollection Resolve(
            IEnumerable <ContractDescription> contracts,
            Uri address,
            MetadataExchangeClientMode mode,
            MetadataExchangeClient client)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            return(ResolveContracts(contracts, () => client.GetMetadata(address, mode)));
        }
示例#23
0
        public static MetadataSet GetMetadataSet(string url)
        {
            MetadataExchangeClientMode mode = MetadataExchangeClientMode.MetadataExchange;
            int maxReceivedMessageSize      = 3000000;
            Uri address = new Uri(url);

            System.ServiceModel.Channels.Binding mexBinding = null;
            if (string.Compare(address.Scheme, "http", StringComparison.OrdinalIgnoreCase) == 0)
            {
                mexBinding = MetadataExchangeBindings.CreateMexHttpBinding();
            }
            else if (string.Compare(address.Scheme, "https", StringComparison.OrdinalIgnoreCase) == 0)
            {
                mexBinding = MetadataExchangeBindings.CreateMexHttpsBinding();
            }
            else if (string.Compare(address.Scheme, "net.tcp", StringComparison.OrdinalIgnoreCase) == 0)
            {
                mexBinding = MetadataExchangeBindings.CreateMexTcpBinding();
            }
            else if (string.Compare(address.Scheme, "net.pipe", StringComparison.OrdinalIgnoreCase) == 0)
            {
                mexBinding = MetadataExchangeBindings.CreateMexNamedPipeBinding();
            }
            else
            {
                throw new Exception(string.Format("Not supported schema '{0}' for metadata exchange"));
            }

            if (mexBinding is WSHttpBinding)
            {
                (mexBinding as WSHttpBinding).MaxReceivedMessageSize = maxReceivedMessageSize;
                mode = MetadataExchangeClientMode.HttpGet;
            }
            else if (mexBinding is CustomBinding)
            {
                (mexBinding as CustomBinding).Elements.Find <TransportBindingElement>().MaxReceivedMessageSize = maxReceivedMessageSize;
            }
            else
            {
                throw new Exception(string.Format("Not supported binding for metadata exchange"));
            }

            MetadataExchangeClient proxy = new MetadataExchangeClient(mexBinding);

            proxy.ResolveMetadataReferences = true;
            MetadataSet mds = proxy.GetMetadata(address, mode);

            return(mds);
        }
        public MetadataExchangeClient(Uri address, MetadataExchangeClientMode mode)
        {
            Validate(address, mode);

            if (mode == MetadataExchangeClientMode.HttpGet)
            {
                this.ctorUri = address;
            }
            else
            {
                this.ctorEndpointAddress = new EndpointAddress(address);
            }

            CreateChannelFactory(address.Scheme);
        }
        /// <summary>
        /// Gets the service metadata information.
        /// </summary>
        /// <param name="metadataAddress">The metadata endpoint address.</param>
        /// <param name="mexMode">The metadata exchange client mode.</param>
        /// <param name="operationTimeout">The operation time.</param>
        /// <returns>The metadata document set.</returns>
        public static MetadataSet GetServiceMetadata(
            EndpointAddress metadataAddress, MetadataExchangeClientMode mexMode, TimeSpan operationTimeout)
        {
            // Create a new metadata client to return
            // metadata information for the service.
            MetadataExchangeClient mexClient = new MetadataExchangeClient(metadataAddress.Uri, mexMode);

            // Assign each property
            mexClient.OperationTimeout          = operationTimeout;
            mexClient.ResolveMetadataReferences = true;

            // Get the metadata from the service
            MetadataSet metaDocs = mexClient.GetMetadata();

            // Return the metadata document set.
            return(metaDocs);
        }
 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, new AddressHeader[0]), mode, client, contracts, callback, asyncState);
 }
        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);
        }
        internal MetadataSet GetMetadataInternal(EndpointAddress address, MetadataExchangeClientMode mode)
        {
            // FIXME: give dialect and identifier
            var cf = GetChannelFactory(address, null, null);

            cf.Open();
            var proxy           = cf.CreateChannel();
            var asClientChannel = proxy as IClientChannel;

            if (asClientChannel == null)
            {
                throw new InvalidOperationException("The channel factory must return an IClientChannel implementation");
            }
            asClientChannel.OperationTimeout = OperationTimeout;
            asClientChannel.Open();

            SMMessage msg = SMMessage.CreateMessage(
                MessageVersion.Soap12WSAddressing10,
                "http://schemas.xmlsoap.org/ws/2004/09/transfer/Get");

            msg.Headers.ReplyTo = new EndpointAddress(
                "http://www.w3.org/2005/08/addressing/anonymous");
            //msg.Headers.From = new EndpointAddress ("http://localhost");
            msg.Headers.To        = address.Uri;
            msg.Headers.MessageId = new UniqueId();

            SMMessage ret;

            try
            {
                ret = proxy.Get(msg);
            }
            catch (Exception e)
            {
                throw new InvalidOperationException(
                          "Metadata contains a reference that cannot be resolved : " + address.Uri.AbsoluteUri, e);
            }

            return(MetadataSet.ReadFrom(ret.GetReaderAtBodyContents()));
        }
		public static ServiceEndpointCollection Resolve (
				Type contract,
				Uri address,
				MetadataExchangeClientMode mode)
		{
			return Resolve (ToContracts (contract), address, mode);
		}
 public static ServiceEndpointCollection Resolve(IEnumerable<ContractDescription> contracts, Uri address, MetadataExchangeClientMode mode)
 {
     return Resolve(contracts, address, mode, new MetadataExchangeClient(address, mode));
 }
 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();
 }
        public MetadataSet GetMetadata(Uri address, MetadataExchangeClientMode mode)
        {
            Validate(address, mode);

            MetadataRetriever retriever;
            if (mode == MetadataExchangeClientMode.HttpGet)
            {
                retriever = new MetadataLocationRetriever(address, this);
            }
            else
            {
                retriever = new MetadataReferenceRetriever(new EndpointAddress(address), this);
            }
            return GetMetadata(retriever);
        }
		/* FIXME: What is the mode/client used for here? 
		 * According to the tests, address is used */
		public static ServiceEndpointCollection Resolve (
				IEnumerable<ContractDescription> contracts,
				Uri address,
				MetadataExchangeClientMode mode,
				MetadataExchangeClient client)
		{
			if (client == null)
				throw new ArgumentNullException ("client");

			return ResolveContracts (contracts, () => new MetadataExchangeClient ().GetMetadata (address, mode));
		}
    public static ServiceEndpointCollection Resolve(Type contract, Uri address, MetadataExchangeClientMode mode)
    {
      Contract.Requires(address != null);
      Contract.Ensures(Contract.Result<System.ServiceModel.Description.ServiceEndpointCollection>() != null);

      return default(ServiceEndpointCollection);
    }
 public MetadataExchangeClient(Uri address, MetadataExchangeClientMode mode)
 {
     this.resolveTimeout = TimeSpan.FromMinutes(1.0);
     this.maximumResolvedReferences = 10;
     this.resolveMetadataReferences = true;
     this.thisLock = new object();
     this.Validate(address, mode);
     if (mode == MetadataExchangeClientMode.HttpGet)
     {
         this.ctorUri = address;
     }
     else
     {
         this.ctorEndpointAddress = new EndpointAddress(address, new AddressHeader[0]);
     }
     this.CreateChannelFactory(address.Scheme);
 }
示例#36
0
		public MetadataExchangeClient (Uri address, MetadataExchangeClientMode mode)
		{
			this.address = new EndpointAddress (address.AbsoluteUri);
			this.mode = mode;
		}
示例#37
0
 public IAsyncResult BeginGetMetadata(Uri address, MetadataExchangeClientMode mode, AsyncCallback callback, object asyncState)
 {
     PrepareGetter();
     return(getter.BeginInvoke(() => GetMetadata(address, mode), callback, asyncState));
 }
    public static ServiceEndpointCollection Resolve(IEnumerable<ContractDescription> contracts, Uri address, MetadataExchangeClientMode mode, MetadataExchangeClient client)
    {
      Contract.Ensures(Contract.Result<System.ServiceModel.Description.ServiceEndpointCollection>() != null);

      return default(ServiceEndpointCollection);
    }
示例#39
0
		internal MetadataSet GetMetadataInternal (EndpointAddress address, MetadataExchangeClientMode mode)
		{
			// FIXME: give dialect and identifier
			var cf = GetChannelFactory (address, null, null);
			cf.Open ();
			var proxy = cf.CreateChannel ();
			var asClientChannel = proxy as IClientChannel;
			if (asClientChannel == null)
				throw new InvalidOperationException ("The channel factory must return an IClientChannel implementation");
			asClientChannel.OperationTimeout = OperationTimeout;
			asClientChannel.Open ();

			SMMessage msg = SMMessage.CreateMessage ( 
					MessageVersion.Soap12WSAddressing10, 
					"http://schemas.xmlsoap.org/ws/2004/09/transfer/Get");

			msg.Headers.ReplyTo = new EndpointAddress (
					"http://www.w3.org/2005/08/addressing/anonymous");
			//msg.Headers.From = new EndpointAddress ("http://localhost");
			msg.Headers.To = address.Uri;
			msg.Headers.MessageId = new UniqueId ();

			SMMessage ret;
			try {
				ret = proxy.Get (msg);
			} catch (Exception e) {
				throw new InvalidOperationException (
						"Metadata contains a reference that cannot be resolved : " + address.Uri.AbsoluteUri, e);
			}

			return MetadataSet.ReadFrom (ret.GetReaderAtBodyContents ());
		}
示例#40
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));
        }
示例#41
0
 public static IAsyncResult BeginResolve(IEnumerable <ContractDescription> contracts, Uri address, MetadataExchangeClientMode mode, AsyncCallback callback, object asyncState)
 {
     return(BeginResolve(contracts, address, mode, new MetadataExchangeClient(address, mode), callback, asyncState));
 }
		public static IAsyncResult BeginResolve (IEnumerable<ContractDescription> contracts, EndpointAddress address, MetadataExchangeClientMode mode, MetadataExchangeClient client, AsyncCallback callback, object asyncState)
		{
			return resolver.BeginInvoke (contracts, () => client.GetMetadataInternal (address, mode), callback, asyncState);
		}
 public static IAsyncResult BeginResolve(IEnumerable<ContractDescription> contracts, Uri address, MetadataExchangeClientMode mode, AsyncCallback callback, object asyncState)
 {
     return BeginResolve(contracts, address, mode, new MetadataExchangeClient(address, mode), callback, asyncState);
 }
		public static IAsyncResult BeginResolve (Type contract, Uri address, MetadataExchangeClientMode mode, AsyncCallback callback, object asyncState)
		{
			return BeginResolve (ToContracts (contract), new EndpointAddress (address), mode, callback, asyncState);
		}
示例#45
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));
        }
        /// <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);
        }
示例#47
0
		public MetadataSet GetMetadata (Uri address, MetadataExchangeClientMode mode)
		{
			return GetMetadataInternal (new EndpointAddress (address.AbsoluteUri), mode);
		}
示例#48
0
        private DataTable GetDataFromMethod(string Uri, string endpointAddress, BasicHttpBinding basicHttpBinding, string contractname, string methodName, object[] paramArray)
        {
            DataTable dt         = null;
            Uri       mexAddress = new Uri(Uri);
            MetadataExchangeClientMode mexMode = MetadataExchangeClientMode.HttpGet;
            string contractName = contractname;



            // Get the metadata file from the service.
            MetadataExchangeClient mexClient = new MetadataExchangeClient(mexAddress, mexMode);

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


            // Import all contracts and endpoints
            WsdlImporter importer = new WsdlImporter(metaSet);
            Collection <ContractDescription> contracts    = importer.ImportAllContracts();
            ServiceEndpointCollection        allEndpoints = importer.ImportAllEndpoints();


            // Generate type information for each contract
            ServiceContractGenerator generator = new ServiceContractGenerator();
            var endpointsForContracts          = new Dictionary <string, IEnumerable <ServiceEndpoint> >();

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



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

            // Generate a code file for the contracts
            CodeGeneratorOptions options = new CodeGeneratorOptions();

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

            // Compile the code file to an in-memory assembly
            // Don't forget to add all WCF-related assemblies as references
            CompilerParameters compilerParameters = new CompilerParameters(
                new string[]
            {
                "System.dll", "System.ServiceModel.dll",
                "System.Runtime.Serialization.dll"
            });

            compilerParameters.GenerateInMemory = true;

            CompilerResults results = codeDomProvider.CompileAssemblyFromDom(
                compilerParameters, generator.TargetCompileUnit);

            if (results.Errors.Count > 0)
            {
                throw new Exception("There were errors during generated code compilation");
            }
            else
            {
                // Find the proxy type that was generated for the specified contract
                // (identified by a class that implements the contract and ICommunicationbject)
                Type clientProxyType = results.CompiledAssembly.GetTypes()
                                       .First(
                    t => t.IsClass &&
                    t.GetInterface(contractName) != null &&
                    t.GetInterface(typeof(ICommunicationObject).Name) != null);

                // Get the first service endpoint for the contract
                ServiceEndpoint se       = endpointsForContracts[contractName].First();
                EndpointAddress endPoint = new EndpointAddress(endpointAddress);
                se.Address = endPoint;
                se.Binding = basicHttpBinding;


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



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


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



            return(dt);
        }
示例#49
0
		public IAsyncResult BeginGetMetadata (Uri address, MetadataExchangeClientMode mode, AsyncCallback callback, object asyncState)
		{
			PrepareGetter ();
			return getter.BeginInvoke (() => GetMetadata (address, mode), callback, asyncState);
		}
        void Validate(Uri address, MetadataExchangeClientMode mode)
        {
            if (address == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address");
            }

            if (!address.IsAbsoluteUri)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("address", SR.GetString(SR.SFxCannotGetMetadataFromRelativeAddress, address));
            }

            if (mode == MetadataExchangeClientMode.HttpGet && !IsHttpOrHttps(address))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("address", SR.GetString(SR.SFxCannotHttpGetMetadataFromAddress, address));
            }

            MetadataExchangeClientModeHelper.Validate(mode);
        }
示例#51
0
 public MetadataSet GetMetadata(Uri address, MetadataExchangeClientMode mode)
 {
     return(GetMetadataInternal(new EndpointAddress(address.AbsoluteUri), mode));
 }
        public IAsyncResult BeginGetMetadata(Uri address, MetadataExchangeClientMode mode, AsyncCallback callback, object asyncState)
        {
            Validate(address, mode);

            if (mode == MetadataExchangeClientMode.HttpGet)
            {
                return this.BeginGetMetadata(new MetadataLocationRetriever(address, this), callback, asyncState);
            }
            else
            {
                return this.BeginGetMetadata(new MetadataReferenceRetriever(new EndpointAddress(address), this), callback, asyncState);
            }
        }
示例#53
0
 public MetadataExchangeClient(Uri address, MetadataExchangeClientMode mode)
 {
     this.address = new EndpointAddress(address.AbsoluteUri);
     this.mode    = mode;
 }
        public Task<MetadataSet> GetMetadataAsync(Uri address, MetadataExchangeClientMode mode)
        {
            Validate(address, mode);

            MetadataRetriever retriever = (mode == MetadataExchangeClientMode.HttpGet)
                                                ? (MetadataRetriever) new MetadataLocationRetriever(address, this)
                                                : (MetadataRetriever) new MetadataReferenceRetriever(new EndpointAddress(address), this);

            return Task.Factory.FromAsync<MetadataRetriever, MetadataSet>(this.BeginGetMetadata, this.EndGetMetadata, retriever, /* state */ null);
        }
 static public bool IsDefined(MetadataExchangeClientMode x)
 {
     return
         x == MetadataExchangeClientMode.MetadataExchange ||
         x == MetadataExchangeClientMode.HttpGet ||
         false;
 }
 private void Validate(Uri address, MetadataExchangeClientMode mode)
 {
     if (address == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address");
     }
     if (!address.IsAbsoluteUri)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("address", System.ServiceModel.SR.GetString("SFxCannotGetMetadataFromRelativeAddress", new object[] { address }));
     }
     if ((mode == MetadataExchangeClientMode.HttpGet) && !this.IsHttpOrHttps(address))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("address", System.ServiceModel.SR.GetString("SFxCannotHttpGetMetadataFromAddress", new object[] { address }));
     }
     MetadataExchangeClientModeHelper.Validate(mode);
 }
示例#57
0
        }     //end subtraction webservice Invoke function..

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

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

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

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

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

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


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


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

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

                foreach (ContractDescription contract in contracts)
                {
                    generator.GenerateServiceContractType(contract);
                    endpointsForContracts[contract.Name] = allEndpoints.Where(
                        se => se.Contract.Name == contract.Name).ToList();
                }

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

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

                CompilerParameters compilerParameters = new CompilerParameters(
                    new string[] {
                    "System.dll", "System.ServiceModel.dll",
                    "System.Runtime.Serialization.dll"
                });
                compilerParameters.GenerateInMemory = true;

                CompilerResults results = codeDomProvider.CompileAssemblyFromDom(
                    compilerParameters, generator.TargetCompileUnit);

                if (results.Errors.Count > 0)
                {
                    throw new Exception("There were errors during generated code compilation");
                }
                else
                {
                    Type clientProxyType = results.CompiledAssembly.GetTypes().First(
                        t => t.IsClass &&
                        t.GetInterface(contractName) != null &&
                        t.GetInterface(typeof(ICommunicationObject).Name) != null);

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

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


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

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

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

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

                MetadataExchangeClientMode mexMode = MetadataExchangeClientMode.HttpGet;

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

                metadataExchangeClient.ResolveMetadataReferences = true;

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

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

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

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

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

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

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

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

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

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

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

                compilerParameters.GenerateInMemory = true;

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

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

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

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

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

                throw ex;
            }
        }
 public MetadataSet GetMetadata(Uri address, MetadataExchangeClientMode mode)
 {
     return(default(MetadataSet));
 }
示例#60
-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;
        }