コード例 #1
0
ファイル: RawMapper.cs プロジェクト: Klaudit/inbox2_desktop
 //Used by live contacts channel and Solr search and RelatedItems
 public static CustomBinding GetCustomBinding(Binding source)
 {
     CustomBinding result = new CustomBinding(source);
     WebMessageEncodingBindingElement element = result.Elements.Find<WebMessageEncodingBindingElement>();
     element.ContentTypeMapper = new RawMapper();
     return result;
 }
コード例 #2
0
ファイル: Another_Topic_Consumer.cs プロジェクト: ncdc/qpid
        static void Main(string[] args)
        {
            // Create binding for the service endpoint.
            CustomBinding amqpBinding = new CustomBinding();
            amqpBinding.Elements.Add(new BinaryMessageEncodingBindingElement());
            amqpBinding.Elements.Add(new AmqpTransportBindingElement());

            // Create ServiceHost.
            ServiceHost serviceHost = new ServiceHost(typeof(HelloService), new Uri[] { new Uri("http://localhost:8080/HelloService2") });

            // Add behavior for our MEX endpoint.
            ServiceMetadataBehavior mexBehavior = new ServiceMetadataBehavior();
            mexBehavior.HttpGetEnabled = true;
            serviceHost.Description.Behaviors.Add(mexBehavior);

            // Add MEX endpoint.
            serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), new BasicHttpBinding(), "MEX");

            // Add AMQP endpoint.
            Uri amqpUri = new Uri("amqp:news");
            serviceHost.AddServiceEndpoint(typeof(IHelloService), amqpBinding, amqpUri.ToString());

            serviceHost.Open();

            Console.WriteLine();
            Console.WriteLine("The consumer is now listening on the queue \"news\".");
            Console.WriteLine("Press <ENTER> to terminate service.");
            Console.WriteLine();
            Console.ReadLine();

            if (serviceHost.State != CommunicationState.Faulted)
            {
                serviceHost.Close();
            }
        }
コード例 #3
0
ファイル: REWBITest.cs プロジェクト: nnyegaard/REWBI
        public void ReceiveFactory()
        {
            Binding binding = new CustomBinding(new RedisMessageBindingElement(), new RedisReceiveTransportBinding());

            IChannelFactory<IRequestChannel> factory = binding.BuildChannelFactory<IRequestChannel>();
            Assert.IsInstanceOf<RedisReceiveFactory>(factory);
        }
コード例 #4
0
ファイル: service.cs プロジェクト: spzenk/sfdocsamples
        // Host the service within this EXE console application.
        public static void Main()
        {
            Uri baseAddress = new Uri("http://localhost:8000/servicemodelsamples/service");

            // Create a ServiceHost for the CalculatorService type and provide the base address.
            using (ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService), baseAddress))
            {
                // Create a custom binding containing two binding elements
                ReliableSessionBindingElement reliableSession = new ReliableSessionBindingElement();
                reliableSession.Ordered = true;

                HttpTransportBindingElement httpTransport = new HttpTransportBindingElement();
                httpTransport.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous;
                httpTransport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;

                CustomBinding binding = new CustomBinding(reliableSession, httpTransport);

                // Add an endpoint using that binding
                serviceHost.AddServiceEndpoint(typeof(ICalculator), binding, "");
              
                // Open the ServiceHost to create listeners and start listening for messages.
                serviceHost.Open();

                // The service can now be accessed.
                Console.WriteLine("The service is ready.");
                Console.WriteLine("Press <ENTER> to terminate service.");
                Console.WriteLine();
                Console.ReadLine();
            }
        }
コード例 #5
0
        DeviceClient GetService()
        {
            DeviceClient service = new DeviceClient();

            service.Endpoint.Address = new EndpointAddress(tbAddress.Text);
            System.ServiceModel.Channels.CustomBinding cb = (System.ServiceModel.Channels.CustomBinding)service.Endpoint.Binding;

            if (cbHttps.Checked)
            {
                HttpsTransportBindingElement elem = new HttpsTransportBindingElement();
                cb.Elements[1] = elem;
            }

            if (cbTrace.Checked)
            {
                if (cbLowLevelTrace.Checked)
                {
                    CustomTextMessageBindingElement ctmbe = new CustomTextMessageBindingElement();
                    cb.Elements[0] = ctmbe;
                    ctmbe.SetListener(_textBoxListener);
                }
                else
                {
                    service.Endpoint.Behaviors.Add(new TraceBehavior(_textBoxListener));
                }
            }

            return(service);
        }
コード例 #6
0
    public static void SameBinding_Binary_EchoComplexString()
    {
        CustomBinding binding = null;
        ChannelFactory<IWcfService> factory = null;
        EndpointAddress endpointAddress = null;
        IWcfService serviceProxy = null;
        ComplexCompositeType compositeObject = null;
        ComplexCompositeType result = null;

        try
        {
            // *** SETUP *** \\
            binding = new CustomBinding(new BinaryMessageEncodingBindingElement(), new HttpTransportBindingElement());
            endpointAddress = new EndpointAddress(Endpoints.HttpBinary_Address);
            factory = new ChannelFactory<IWcfService>(binding, endpointAddress);
            serviceProxy = factory.CreateChannel();
            compositeObject = ScenarioTestHelpers.GetInitializedComplexCompositeType();

            // *** EXECUTE *** \\
            result = serviceProxy.EchoComplex(compositeObject);

            // *** VALIDATE *** \\
            Assert.True(compositeObject.Equals(result), String.Format("    Error: expected response from service: '{0}' Actual was: '{1}'", compositeObject, result));

            // *** CLEANUP *** \\
            factory.Close();
            ((ICommunicationObject)serviceProxy).Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
コード例 #7
0
        private void btnSetDiscoveryMode_Click(object sender, EventArgs e)
        {
            try
            {
                DiscoveryMode mode = (DiscoveryMode)comboBoxDiscoveryMode.SelectedValue;

                DeviceClient service = GetService();

                if (cbTrace.Checked)
                {
                    if (cbLowLevelTrace.Checked)
                    {
                        System.ServiceModel.Channels.CustomBinding cb    = (System.ServiceModel.Channels.CustomBinding)service.Endpoint.Binding;
                        CustomTextMessageBindingElement            ctmbe = (CustomTextMessageBindingElement)cb.Elements[0];

                        string value = "Discoverrable";
                        string path  = "/s:Envelope/s:Body/onvif:SetDiscoveryMode/onvif:DiscoveryMode";
                        Dictionary <string, string> namespaces = new Dictionary <string, string>();
                        namespaces.Add("s", "http://www.w3.org/2003/05/soap-envelope");
                        namespaces.Add("onvif", "http://www.onvif.org/ver10/device/wsdl");
                        ctmbe.AddBreakingBehaviour(new BreakingBehaviour(path, value, namespaces));
                    }
                }

                service.SetDiscoveryMode(mode);
                ShowStatusMessage("Done");
                service.Close();
            }
            catch (Exception ex)
            {
                ShowStatusMessage("Operation failed");
                TraceException(ex);
                MessageBox.Show(ex.Message);
            }
        }
コード例 #8
0
 public OrionInfoServiceCompressed(string username, string password, bool v3 = false)
 {
     _endpoint = v3 ? Settings.Default.OrionV3EndpointPathCompressed : Settings.Default.OrionEndpointPathCompressed;
     _endpointConfigName = "OrionTcpBindingCompressed";
     _binding = new CustomBinding("CompressedUserName");
     _credentials = new UsernameCredentials(username, password);
 }
コード例 #9
0
ファイル: samplesvc10.cs プロジェクト: alesliehughes/olive
	public static void Main ()
	{
		SymmetricSecurityBindingElement sbe =
			new SymmetricSecurityBindingElement ();
		sbe.ProtectionTokenParameters =
			new SslSecurityTokenParameters ();
		ServiceHost host = new ServiceHost (typeof (Foo));
		HttpTransportBindingElement hbe =
			new HttpTransportBindingElement ();
		CustomBinding binding = new CustomBinding (sbe, hbe);
		binding.ReceiveTimeout = TimeSpan.FromSeconds (5);
		host.AddServiceEndpoint ("IFoo",
			binding, new Uri ("http://localhost:8080"));
		ServiceCredentials cred = new ServiceCredentials ();
		cred.SecureConversationAuthentication.SecurityStateEncoder =
			new MyEncoder ();
		cred.ServiceCertificate.Certificate =
			new X509Certificate2 ("test.pfx", "mono");
		cred.ClientCertificate.Authentication.CertificateValidationMode =
			X509CertificateValidationMode.None;
		host.Description.Behaviors.Add (cred);
		host.Description.Behaviors.Find<ServiceDebugBehavior> ()
			.IncludeExceptionDetailInFaults = true;
//		foreach (ServiceEndpoint se in host.Description.Endpoints)
//			se.Behaviors.Add (new StdErrInspectionBehavior ());
		ServiceMetadataBehavior smb = new ServiceMetadataBehavior ();
		smb.HttpGetEnabled = true;
		smb.HttpGetUrl = new Uri ("http://localhost:8080/wsdl");
		host.Description.Behaviors.Add (smb);
		host.Open ();
		Console.WriteLine ("Hit [CR] key to close ...");
		Console.ReadLine ();
		host.Close ();
	}
コード例 #10
0
    public static void SameBinding_Soap11_EchoString()
    {
        string variationDetails = "Client:: CustomBinding/HttpTransport/TextEncoding/Soap11 = None\nServer:: CustomBinding/HttpTransport/TextEncoding/Soap11";
        string testString = "Hello";
        StringBuilder errorBuilder = new StringBuilder();
        bool success = false;

        try
        {
            CustomBinding binding = new CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8), new HttpTransportBindingElement());

            ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpSoap11_Address));
            IWcfService serviceProxy = factory.CreateChannel();

            string result = serviceProxy.Echo(testString);
            success = string.Equals(result, testString);

            if (!success)
            {
                errorBuilder.AppendLine(String.Format("    Error: expected response from service: '{0}' Actual was: '{1}'", testString, result));
            }
        }
        catch (Exception ex)
        {
            errorBuilder.AppendLine(String.Format("    Error: Unexpected exception was caught while doing the basic echo test for variation...\n'{0}'\nException: {1}", variationDetails, ex.ToString()));
            for (Exception innerException = ex.InnerException; innerException != null; innerException = innerException.InnerException)
            {
                errorBuilder.AppendLine(String.Format("Inner exception: {0}", innerException.ToString()));
            }
        }

        Assert.True(errorBuilder.Length == 0, "Test case FAILED with errors: " + errorBuilder.ToString());
    }
コード例 #11
0
	static void RunCodeUnderDiscoveryHost (Uri serviceUri, Uri dHostUri, Action<Uri,AnnouncementEndpoint,DiscoveryEndpoint> action)
	{
		var aEndpoint = new UdpAnnouncementEndpoint (DiscoveryVersion.WSDiscoveryApril2005, new Uri ("soap.udp://239.255.255.250:3802/"));
		var dbinding = new CustomBinding (new HttpTransportBindingElement ());
		var dAddress = new EndpointAddress (dHostUri);
		var dEndpoint = new DiscoveryEndpoint (dbinding, dAddress);

		var ib = new InspectionBehavior ();
		ib.RequestReceived += delegate (ref Message msg, IClientChannel
channel, InstanceContext instanceContext) {
			var mb = msg.CreateBufferedCopy (0x10000);
			msg = mb.CreateMessage ();
			Console.Error.WriteLine (mb.CreateMessage ());
			return null;
			};
		ib.ReplySending += delegate (ref Message msg, object o) {
			var mb = msg.CreateBufferedCopy (0x10000);
			msg = mb.CreateMessage ();
			Console.Error.WriteLine (mb.CreateMessage ());
			};

		dEndpoint.Behaviors.Add (ib);
		aEndpoint.Behaviors.Add (ib);

		action (serviceUri, aEndpoint, dEndpoint);
	}
コード例 #12
0
ファイル: Service.cs プロジェクト: EdiCarlos/MyPractices
        public static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8000/servicesamplemodel/service");
            using (ServiceHost host = new ServiceHost(typeof(Service), baseAddress))
            {
                ReliableSessionBindingElement reliableBinding = new ReliableSessionBindingElement();
                reliableBinding.Ordered = true;

                HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement();
                httpBindingElement.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous;
                httpBindingElement.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;

                CustomBinding customBinding = new CustomBinding(reliableBinding, httpBindingElement);

                host.AddServiceEndpoint(typeof(ICalculator), customBinding, "");

                host.Open();

                // The service can now be accessed.
                Console.WriteLine("The service is ready.");
                Console.WriteLine("Press <ENTER> to terminate service.");
                Console.WriteLine();
                Console.ReadLine();

            }
        }
コード例 #13
0
    public static void SameBinding_Binary_EchoComplexString()
    {
        string variationDetails = "Client:: CustomBinding/BinaryEncoder/Http\nServer:: CustomBinding/BinaryEncoder/Http";
        StringBuilder errorBuilder = new StringBuilder();
        bool success = false;

        try
        {
            CustomBinding binding = new CustomBinding(new BinaryMessageEncodingBindingElement(), new HttpTransportBindingElement());
            ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBinary_Address));
            IWcfService serviceProxy = factory.CreateChannel();

            ComplexCompositeType compositeObject = ScenarioTestHelpers.GetInitializedComplexCompositeType();

            ComplexCompositeType result = serviceProxy.EchoComplex(compositeObject);
            success = compositeObject.Equals(result);

            if (!success)
            {
                errorBuilder.AppendLine(String.Format("    Error: expected response from service: '{0}' Actual was: '{1}'", compositeObject, result));
            }
        }
        catch (Exception ex)
        {
            errorBuilder.AppendLine(String.Format("    Error: Unexpected exception was caught while doing the basic echo test for variation...\n'{0}'\nException: {1}", variationDetails, ex.ToString()));
            for (Exception innerException = ex.InnerException; innerException != null; innerException = innerException.InnerException)
            {
                errorBuilder.AppendLine(String.Format("Inner exception: {0}", innerException.ToString()));
            }
        }

        Assert.True(errorBuilder.Length == 0, errorBuilder.ToString());
    }
コード例 #14
0
    public static void DefaultSettings_Https_Text_Echo_RoundTrips_String()
    {
        string testString = "Hello";
        CustomBinding binding = null;
        ChannelFactory<IWcfService> factory = null;
        IWcfService serviceProxy = null;

        try
        {
            // *** SETUP *** \\
            binding = new CustomBinding(new TextMessageEncodingBindingElement(), new HttpsTransportBindingElement());
            factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpsSoap12_Address));
            serviceProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            string result = serviceProxy.Echo(testString);

            // *** VALIDATE *** \\
            Assert.NotNull(result);
            Assert.Equal(testString, result);

            // *** CLEANUP *** \\
            factory.Close();
            ((ICommunicationObject)serviceProxy).Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
コード例 #15
0
ファイル: Program.cs プロジェクト: porter1130/MyTest
        static void Main(string[] args)
        {
            try {
                BindingElement[] bindingElements = new BindingElement[2];
                bindingElements[0] = new TextMessageEncodingBindingElement();
                bindingElements[1] = new HttpTransportBindingElement();

                CustomBinding binding = new CustomBinding(bindingElements);

                IChannelListener<IReplyChannel> listener=binding.BuildChannelListener<IReplyChannel>(new Uri("http://localhost:9090/RequestReplyService"),new BindingParameterCollection());
                listener.Open();

                IReplyChannel replyChannel = listener.AcceptChannel();
                replyChannel.Open();
                Console.WriteLine("starting to receive message....");

                RequestContext requestContext = replyChannel.ReceiveRequest();
                Console.WriteLine("Received a Message, action:{0},body:{1}", requestContext.RequestMessage.Headers.Action,
                                    requestContext.RequestMessage.GetBody<string>());
                Message message = Message.CreateMessage(binding.MessageVersion, "response", "response Message");
                requestContext.Reply(message);

                requestContext.Close();
                replyChannel.Close();
                listener.Close();

            }
            catch (Exception ex) {
                Console.WriteLine(ex.ToString());
            }
            finally {
                Console.Read();
            }
        }
コード例 #16
0
    public static void DefaultSettings_Tcp_Binary_Echo_RoundTrips_String()
    {
        string testString = "Hello";
        ChannelFactory<IWcfService> factory = null;
        IWcfService serviceProxy = null;

        try
        {
            // *** SETUP *** \\
            CustomBinding binding = new CustomBinding(
                new SslStreamSecurityBindingElement(),
                new BinaryMessageEncodingBindingElement(),
                new TcpTransportBindingElement());

            var endpointIdentity = new DnsEndpointIdentity(Endpoints.Tcp_CustomBinding_SslStreamSecurity_HostName);
            factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(new Uri(Endpoints.Tcp_CustomBinding_SslStreamSecurity_Address), endpointIdentity));
            serviceProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            string result = serviceProxy.Echo(testString);

            // *** VALIDATE *** \\
            Assert.Equal(testString, result);

            // *** CLEANUP *** \\
            ((ICommunicationObject)serviceProxy).Close();
            factory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
コード例 #17
0
ファイル: Output.cs プロジェクト: porter1130/MyTest
        static void Main(string[] args)
        {
            try
            {
                BindingElement[] bindingElements = new BindingElement[2];
                bindingElements[0] = new TextMessageEncodingBindingElement();
                bindingElements[1] = new HttpTransportBindingElement();

                CustomBinding binding = new CustomBinding(bindingElements);
                using (Message message = Message.CreateMessage(binding.MessageVersion, "sendMessage", "Message Body"))
                {
                    IChannelFactory<IRequestChannel> factory = binding.BuildChannelFactory<IRequestChannel>(new BindingParameterCollection());
                    factory.Open();

                    IRequestChannel requestChannel = factory.CreateChannel(new EndpointAddress("http://localhost:9090/RequestReplyService"));
                    requestChannel.Open();
                    Message response = requestChannel.Request(message);

                    Console.WriteLine("Successful send message!");

                    Console.WriteLine("Receive a return message, action: {0}, body: {1}", response.Headers.Action, response.GetBody<String>());
                    requestChannel.Close();
                    factory.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally {
                Console.Read();
            }
        }
コード例 #18
0
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8773/WSHttpService");

            WSHttpBinding binding = new WSHttpBinding();

            binding.Name = "WSHttp_Binding";
            binding.HostNameComparisonMode = HostNameComparisonMode.WeakWildcard;
            CustomBinding customBinding = new CustomBinding(binding);
            SymmetricSecurityBindingElement securityBinding = (SymmetricSecurityBindingElement)customBinding.Elements.Find<SecurityBindingElement>();

            /// Change the MaxClockSkew to 2 minutes on both service and client settings.
            TimeSpan newClockSkew = new TimeSpan(0, 2, 0);

            securityBinding.LocalServiceSettings.MaxClockSkew = newClockSkew;
            securityBinding.LocalClientSettings.MaxClockSkew = newClockSkew;

            using (ServiceHost host = new ServiceHost(typeof(WSHttpService), baseAddress))
            {
                host.AddServiceEndpoint(typeof(IWSHttpService), customBinding, "http://localhost:8773/WSHttpService/mex");
                // Enable metadata publishing.
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                host.Description.Behaviors.Add(smb);
                host.Open();

                Console.WriteLine("The service is ready at {0}", baseAddress);
                Console.WriteLine("Press <Enter> to stop the service.");
                Console.ReadLine();

                // Close the ServiceHost.
                host.Close();
            }
        }
コード例 #19
0
ファイル: ClientBaseTests.4.4.0.cs プロジェクト: roncain/wcf
    public static void ClientBaseOfT_ClientCredentials()
    {
        MyClientBase client = null;
        ClientCredentials clientCredentials = null;

        try
        {
            // *** SETUP *** \\
            CustomBinding customBinding = new CustomBinding();
            customBinding.Elements.Add(new TextMessageEncodingBindingElement());
            customBinding.Elements.Add(new HttpTransportBindingElement());

            string endpoint = Endpoints.HttpSoap12_Address;
            client = new MyClientBase(customBinding, new EndpointAddress(endpoint));

            // *** EXECUTE *** \\
            clientCredentials = client.ClientCredentials;

            // *** VALIDATE *** \\
            Assert.True(clientCredentials != null, "ClientCredentials should not be null");
            Assert.True(clientCredentials.ClientCertificate != null, "ClientCredentials.ClientCertificate should not be null");
            Assert.True(clientCredentials.ServiceCertificate != null, "ClientCredentials.ServiceCertificate should not be null");
            Assert.True(clientCredentials.HttpDigest != null, "ClientCredentials.HttpDigest should not be null");

            // *** CLEANUP *** \\
            ((ICommunicationObject)client).Close();

        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects(client);
        }
    }
コード例 #20
0
 private SMC.Binding CreateDefaultBinding()
 {
     SMC.CustomBinding binding = new SMC.CustomBinding();
     binding.Elements.Add(new SMC.TextMessageEncodingBindingElement(SMC.MessageVersion.Soap11, System.Text.Encoding.UTF8));
     binding.Elements.Add(new SMC.HttpTransportBindingElement());
     return(binding);
 }
コード例 #21
0
 public static System.ServiceModel.Channels.Binding CreateDefaultBinding()
 {
     System.ServiceModel.Channels.CustomBinding binding = new System.ServiceModel.Channels.CustomBinding();
     binding.Elements.Add(new System.ServiceModel.Channels.TextMessageEncodingBindingElement(System.ServiceModel.Channels.MessageVersion.Soap11, System.Text.Encoding.UTF8));
     binding.Elements.Add(new System.ServiceModel.Channels.HttpTransportBindingElement());
     return(binding);
 }
コード例 #22
0
        public async Task<RelayConnection> ConnectAsync()
        {
            var tb = new TransportClientEndpointBehavior(tokenProvider);
            var bindingElement = new TcpRelayTransportBindingElement(
                RelayClientAuthenticationType.RelayAccessToken)
            {
                TransferMode = TransferMode.Buffered,
                ConnectionMode = TcpRelayConnectionMode.Relayed,
                ManualAddressing = true
            };
            bindingElement.GetType()
                .GetProperty("TransportProtectionEnabled",
                    BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic)
                .SetValue(bindingElement, true);

            var rt = new CustomBinding(
                new BinaryMessageEncodingBindingElement(),
                bindingElement);

            var cf = rt.BuildChannelFactory<IDuplexSessionChannel>(tb);
            await Task.Factory.FromAsync(cf.BeginOpen, cf.EndOpen, null);
            var ch = cf.CreateChannel(new EndpointAddress(address));
            await Task.Factory.FromAsync(ch.BeginOpen, ch.EndOpen, null);
            return new RelayConnection(ch)
            {
                WriteTimeout = (int) rt.SendTimeout.TotalMilliseconds,
                ReadTimeout = (int) rt.ReceiveTimeout.TotalMilliseconds
            };
        }
コード例 #23
0
ファイル: Blip.cs プロジェクト: SkyKnight/WcfBlip
 private Binding GetBinding()
 {
     CustomBinding binding = new CustomBinding(new WebHttpBinding());
     WebMessageEncodingBindingElement element = binding.Elements.Find<WebMessageEncodingBindingElement>();
     element.ContentTypeMapper = new BlipMapper();
     return binding;
 }
コード例 #24
0
ファイル: TextTests.cs プロジェクト: weshaggard/wcf
    public static void CustomTextMessageEncoder_Http_RequestReply_Buffered()
    {
        ChannelFactory<IWcfService> channelFactory = null;
        IWcfService client = null;
        string testString = "Hello";

        try
        {
            // *** SETUP *** \\
            CustomBinding binding = new CustomBinding(new CustomTextMessageBindingElement(Encoding.UTF8.WebName),
                new HttpTransportBindingElement
                {
                    MaxReceivedMessageSize = ScenarioTestHelpers.SixtyFourMB,
                    MaxBufferSize = ScenarioTestHelpers.SixtyFourMB
                });

            channelFactory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.CustomTextEncoderBuffered_Address));
            client = channelFactory.CreateChannel();

            // *** EXECUTE *** \\
            string result = client.Echo(testString);

            // *** VALIDATE *** \\
            Assert.Equal(result, testString);

            // *** CLEANUP *** \\
            ((ICommunicationObject)client).Close();
            channelFactory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\  
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)client, channelFactory);
        }
    }
コード例 #25
0
ファイル: ProxyClient.cs プロジェクト: JiahuiGuo/openPDC
        public static DuplexServiceClient GetDuplexServiceProxyClient()
        {
            string baseServiceUrl = Application.Current.Resources["BaseServiceUrl"].ToString();
            EndpointAddress address = new EndpointAddress(baseServiceUrl + "DuplexService/PhasorDataDuplexService.svc");
            CustomBinding binding;
            if (HtmlPage.Document.DocumentUri.Scheme.ToLower().StartsWith("https"))
            {
                HttpsTransportBindingElement httpsTransportBindingElement = new HttpsTransportBindingElement();
                httpsTransportBindingElement.MaxReceivedMessageSize = int.MaxValue;
                binding = new CustomBinding(
                                    new PollingDuplexBindingElement(),
                                    new BinaryMessageEncodingBindingElement(),
                                    httpsTransportBindingElement
                                    );
            }
            else
            {
                HttpTransportBindingElement httpTransportBindingElement = new HttpTransportBindingElement();
                httpTransportBindingElement.MaxReceivedMessageSize = int.MaxValue;	// 65536 * 50;
                binding = new CustomBinding(
                                    new PollingDuplexBindingElement(),
                                    new BinaryMessageEncodingBindingElement(),
                                    httpTransportBindingElement
                                    );
            }

            binding.CloseTimeout = new TimeSpan(0, 20, 0);
            binding.OpenTimeout = new TimeSpan(0, 20, 0);
            binding.ReceiveTimeout = new TimeSpan(0, 20, 0);
            binding.SendTimeout = new TimeSpan(0, 20, 0);

            return new DuplexServiceClient(binding, address);
        }
コード例 #26
0
	static void RunCodeUnderDiscoveryHost (Uri serviceUri, Uri aHostUri, Action<Uri,AnnouncementEndpoint,DiscoveryEndpoint> action)
	{
		var abinding = new CustomBinding (new HttpTransportBindingElement ());
		var aAddress = new EndpointAddress (aHostUri);
		var aEndpoint = new AnnouncementEndpoint (abinding, aAddress);
		var dBinding = new CustomBinding (new TextMessageEncodingBindingElement (), new TcpTransportBindingElement ());
		var dEndpoint = new DiscoveryEndpoint (DiscoveryVersion.WSDiscovery11, ServiceDiscoveryMode.Adhoc, dBinding, new EndpointAddress ("net.tcp://localhost:9090/"));

		var ib = new InspectionBehavior ();
		ib.RequestReceived += delegate (ref Message msg, IClientChannel
channel, InstanceContext instanceContext) {
			var mb = msg.CreateBufferedCopy (0x10000);
			msg = mb.CreateMessage ();
			Console.Error.WriteLine (mb.CreateMessage ());
			return null;
			};
		ib.ReplySending += delegate (ref Message msg, object o) {
			var mb = msg.CreateBufferedCopy (0x10000);
			msg = mb.CreateMessage ();
			Console.Error.WriteLine (mb.CreateMessage ());
			};
		dEndpoint.Behaviors.Add (ib);
		aEndpoint.Behaviors.Add (ib);

		action (serviceUri, aEndpoint, dEndpoint);
	}
コード例 #27
0
ファイル: ClientBaseTests.cs プロジェクト: peterluo0822/wcf
    public static void MessageProperty_HttpRequestMessageProperty_RoundTrip_Verify()
    {
            CustomBinding customBinding = new CustomBinding();
            customBinding.Elements.Add(new TextMessageEncodingBindingElement());
            customBinding.Elements.Add(new HttpTransportBindingElement());

            MyClientBase<IWcfService> client = new MyClientBase<IWcfService>(customBinding, new EndpointAddress(Endpoints.DefaultCustomHttp_Address));
            client.Endpoint.EndpointBehaviors.Add(new ClientMessagePropertyBehavior());

        try
        {
            IWcfService serviceProxy = client.ChannelFactory.CreateChannel();
            TestHttpRequestMessageProperty property = serviceProxy.EchoHttpRequestMessageProperty();

            Assert.NotNull(property);
            Assert.True(property.SuppressEntityBody == false, "Expected SuppressEntityBody to be 'false'");
            Assert.Equal("POST", property.Method);
            Assert.Equal("My%20address", property.QueryString);
            Assert.True(property.Headers.Count > 0, "TestHttpRequestMessageProperty.Headers should not have empty headers");
            Assert.Equal("my value", property.Headers["customer"]);
            }
        finally
            {
            if (client != null && client.State != CommunicationState.Closed)
                {
                client.Abort(); 
                }
                }
                }
コード例 #28
0
ファイル: UdpTestService.cs プロジェクト: spzenk/sfdocsamples
        static void ServiceFromCode()
        {
            Console.Out.WriteLine("Testing Udp From Code.");

            Binding datagramBinding = new CustomBinding(new BinaryMessageEncodingBindingElement(), new UdpTransportBindingElement());

            // using the 2-way calculator method requires a session since UDP is not inherently request-response
            SampleProfileUdpBinding calculatorBinding = new SampleProfileUdpBinding(true);
            calculatorBinding.ClientBaseAddress = new Uri("soap.udp://localhost:8003/");

            Uri calculatorAddress = new Uri("soap.udp://localhost:8001/");
            Uri datagramAddress = new Uri("soap.udp://localhost:8002/datagram");

            // we need an http base address so that svcutil can access our metadata
            ServiceHost service = new ServiceHost(typeof(CalculatorService), new Uri("http://localhost:8000/udpsample/"));
            ServiceMetadataBehavior metadataBehavior = new ServiceMetadataBehavior();
            metadataBehavior.HttpGetEnabled = true;
            service.Description.Behaviors.Add(metadataBehavior);
            service.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexHttpBinding(), "mex");

            service.AddServiceEndpoint(typeof(ICalculatorContract), calculatorBinding, calculatorAddress);
            service.AddServiceEndpoint(typeof(IDatagramContract), datagramBinding, datagramAddress);
            service.Open();

            Console.WriteLine("Service is started from code...");
            Console.WriteLine("Press <ENTER> to terminate the service and start service from config...");
            Console.ReadLine();

            service.Close();
        }
コード例 #29
0
        protected override ServiceHost CreateServiceHost(Type serviceType, 
                                                         Uri[] baseAddresses)
        {
            WebServiceHost2Ex webServiceHost2Ex =
                new WebServiceHost2Ex(serviceType, baseAddresses);

            //new code
            Uri[] defaultAddresses = new Uri[1];
            defaultAddresses[0] = baseAddresses[0];

            // Bind up the JSONP extension
            CustomBinding cb = new CustomBinding(new WebHttpBinding());
            cb.Name = "JSONPBinding";

            // Replace the current MessageEncodingBindingElement with the JSONP element
            var currentEncoder = cb.Elements.Find<MessageEncodingBindingElement>();
            if (currentEncoder != default(MessageEncodingBindingElement))
            {
                cb.Elements.Remove(currentEncoder);
                cb.Elements.Insert(0, new JSONPBindingElement());
            }

            webServiceHost2Ex.AddServiceEndpoint(serviceType.GetInterfaces()[0], cb, defaultAddresses[0]);

            return webServiceHost2Ex;
        }
コード例 #30
0
ファイル: CustomBindingTest.cs プロジェクト: weshaggard/wcf
 // Create a CustomBinding and set/get its name to validate it was created and usable.
 public static void CustomBinding_Name_Property(string bindingName)
 {
     CustomBinding customBinding = new CustomBinding();
     customBinding.Name = bindingName;
     string actualBindingName = customBinding.Name;
     Assert.Equal<string>(bindingName, actualBindingName);
 }
コード例 #31
0
ファイル: BasicServices.cs プロジェクト: JuRogn/OA
        private NewsCallBackWS.NewsCallBackClient CreateCallBack()
        {
            try
            {
                var serviceName = "/Main/NewsCallBack.svc";
                if (!string.IsNullOrEmpty(SMT.SAAS.Main.CurrentContext.Common.HostAddress))
                {
                    StringBuilder addressBuilder = new StringBuilder();
                    addressBuilder.Append("http://");
                    addressBuilder.Append(SMT.SAAS.Main.CurrentContext.Common.HostAddress.ToString());
                    addressBuilder.Append(serviceName);
                    serviceAddress = addressBuilder.ToString();
                }


                EndpointAddress address = new EndpointAddress(serviceAddress);
                CustomBinding binding = new CustomBinding(
                    new PollingDuplexBindingElement()
                    {
                        InactivityTimeout = TimeSpan.FromDays(1),
                        ClientPollTimeout = TimeSpan.FromDays(1)
                    },
                    new BinaryMessageEncodingBindingElement(),
                    new HttpTransportBindingElement());
                return new NewsCallBackWS.NewsCallBackClient(binding, address);
                //DuplexMode=PollingDuplexMode.SingleMessagePerPoll,

            }
            catch (Exception ex)
            {
                return null;
            }
        }
コード例 #32
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                //string xx = textBox1.Text;
                CustomBinding binding = new CustomBinding(new CustomTextMessageBindingElement("iso-8859-1", "text/xml", MessageVersion.Soap11), new HttpTransportBindingElement());
                FVEWebService.FVEWebServicePortTypeClient prueba = new FVEWebService.FVEWebServicePortTypeClient();
                prueba.Endpoint.Binding = binding;

                FVEWebService.Productos prod = new FVEWebService.Productos();
                
                prod = prueba.foBuscarProducto(20165501);
                MessageBox.Show(prod.prod_nom);
                
                
               
               
                ////string Arreglo =  prueba.Prod();
                //PruebaWS.Productos Arreglo = prueba.foObtenerProductos();
                //if (Arreglo.Length > 0)
                //{
                //    MessageBox.Show("Hay: " + Arreglo.Length + " productos");
                //}
                //else {
                //    MessageBox.Show("No Hay");
                //}

                pictureBox1.Load("http://www.punk-hxc.com/especiales/punk-hardcore.jpg");

            }catch(Exception ex){
                MessageBox.Show(ex.Message);
            }
        }
コード例 #33
0
ファイル: TypedProxyTests.cs プロジェクト: TerabyteX/wcf
 public static void ServiceContract_TypedProxy_AsyncBeginEnd_Call()
 {
     CustomBinding customBinding = new CustomBinding();
     customBinding.Elements.Add(new TextMessageEncodingBindingElement());
     customBinding.Elements.Add(new HttpTransportBindingElement());
     ServiceContract_TypedProxy_AsyncBeginEnd_Call(customBinding, Endpoints.DefaultCustomHttp_Address, "ServiceContract_TypedProxy_AsyncBeginEnd_Call");
 }
コード例 #34
0
    public static void CustomBinding_Message_Interceptor()
    {
        ChannelFactory<IWcfChannelExtensibilityContract> factory = null;
        IWcfChannelExtensibilityContract serviceProxy = null;

        try
        {
            // *** SETUP *** \\
            CustomBinding binding = new CustomBinding(
                new InterceptingBindingElement(new MessageModifier()),
                new HttpTransportBindingElement());

            factory = new ChannelFactory<IWcfChannelExtensibilityContract>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_ChannelExtensibility));
            serviceProxy = factory.CreateChannel();

            // *** EXECUTE & VALIDATE *** \\
            int[] windSpeeds = new int[] { 100, 90, 80, 70, 60, 50, 40, 30, 20, 10 };
            for (int i = 0; i < 10; i++)
            {
                serviceProxy.ReportWindSpeed(windSpeeds[i]);
            }

            // *** CLEANUP *** \\
            ((ICommunicationObject)serviceProxy).Close();
            factory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
コード例 #35
0
ファイル: Client.cs プロジェクト: waffle-iron/nequeo
 /// <summary>
 /// Default constructor
 /// </summary>
 /// <param name="binding">Contains the binding elements that specify the protocols,
 /// transports, and message encoders used for communication between clients and services.</param>
 /// <param name="username">The UserName username</param>
 /// <param name="password">The UserName password</param>
 /// <param name="usernameWindows">The Windows ClientCredential username</param>
 /// <param name="passwordWindows">The Windows ClientCredential password</param>
 /// <param name="clientCertificate">The client x509 certificate.</param>
 /// <param name="validationMode">An enumeration that lists the ways of validating a certificate.</param>
 /// <param name="x509CertificateValidator">The certificate validator. If null then the certificate is always passed.</param>
 public Client(System.ServiceModel.Channels.CustomBinding binding, string username = null, string password = null,
               string usernameWindows                            = null, string passwordWindows = null,
               X509Certificate2 clientCertificate                = null,
               X509CertificateValidationMode validationMode      = X509CertificateValidationMode.Custom,
               X509CertificateValidator x509CertificateValidator = null) :
     base(
         new Uri(Nequeo.Management.ServiceModel.Properties.Settings.Default.ServiceAddress),
         binding,
         username, password, usernameWindows, passwordWindows, clientCertificate, validationMode, x509CertificateValidator)
 {
     OnCreated();
 }
コード例 #36
0
 private static System.ServiceModel.Channels.Binding CreateDefaultBinding()
 {
     System.ServiceModel.Channels.CustomBinding binding = new System.ServiceModel.Channels.CustomBinding();
     binding.Elements.Add(new System.ServiceModel.Channels.TextMessageEncodingBindingElement(System.ServiceModel.Channels.MessageVersion.Soap11, System.Text.Encoding.UTF8));
     System.ServiceModel.Channels.HttpTransportBindingElement http = new System.ServiceModel.Channels.HttpTransportBindingElement();
     http.MaxBufferPoolSize      = Int32.MaxValue;
     http.MaxBufferSize          = Int32.MaxValue;
     http.MaxReceivedMessageSize = Int32.MaxValue;
     http.TransferMode           = System.ServiceModel.TransferMode.Buffered;
     binding.Elements.Add(http);
     return(binding);
 }
コード例 #37
0
ファイル: Client.cs プロジェクト: waffle-iron/nequeo
 /// <summary>
 /// Default constructor
 /// </summary>
 /// <param name="endPointAddress">The specific end point address</param>
 /// <param name="binding">Contains the binding elements that specify the protocols,
 /// transports, and message encoders used for communication between clients and services.</param>
 /// <param name="username">The UserName username</param>
 /// <param name="password">The UserName password</param>
 /// <param name="usernameWindows">The Windows ClientCredential username</param>
 /// <param name="passwordWindows">The Windows ClientCredential password</param>
 /// <param name="clientCertificate">The client x509 certificate.</param>
 /// <param name="validationMode">An enumeration that lists the ways of validating a certificate.</param>
 /// <param name="x509CertificateValidator">The certificate validator. If null then the certificate is always passed.</param>
 public Client(string endPointAddress, System.ServiceModel.Channels.CustomBinding binding,
               string username                                   = null, string password = null,
               string usernameWindows                            = null, string passwordWindows = null,
               X509Certificate2 clientCertificate                = null,
               X509CertificateValidationMode validationMode      = X509CertificateValidationMode.Custom,
               X509CertificateValidator x509CertificateValidator = null) :
     base(
         new Uri(endPointAddress), binding,
         username, password, usernameWindows, passwordWindows, clientCertificate, validationMode, x509CertificateValidator)
 {
     OnCreated();
 }
コード例 #38
0
        public static ServiceReference1.Media2Client GetMedia2Client(string uri, string username = "", string password = "", double devideviceTimeOffset = 0)
        {
            UriBuilder deviceUri = new UriBuilder("");

            System.ServiceModel.Channels.Binding binding;
            HttpTransportBindingElement          httpTransport = new HttpTransportBindingElement();

            httpTransport.AuthenticationScheme = System.Net.AuthenticationSchemes.Digest;
            binding        = new System.ServiceModel.Channels.CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.Soap12, Encoding.UTF8), httpTransport);
            deviceUri.Host = uri;
            Media2Client media2Client = new Media2Client(binding, new EndpointAddress(deviceUri.ToString()));

            return(media2Client);
        }
コード例 #39
0
        public static DeviceClient GetClient(string ip, int port, double deviceTimeOffset, out System.ServiceModel.Channels.CustomBinding binding, out UriBuilder deviceUri, string username = "", string password = "")
        {
            deviceUri = new UriBuilder("");

            HttpTransportBindingElement httpTransport = new HttpTransportBindingElement();

            httpTransport.AuthenticationScheme = System.Net.AuthenticationSchemes.Digest;
            deviceUri.Host = ip;
            var messageElement = new TextMessageEncodingBindingElement();

            messageElement.MessageVersion = MessageVersion.CreateVersion(EnvelopeVersion.Soap12, AddressingVersion.None);
            System.ServiceModel.Channels.CustomBinding customBinding = new System.ServiceModel.Channels.CustomBinding(messageElement, httpTransport);
            binding = new System.ServiceModel.Channels.CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.Soap12, Encoding.UTF8), httpTransport);
            DeviceClient Device = new DeviceClient(binding, new EndpointAddress(deviceUri.ToString()));

            return(Device);
        }
コード例 #40
0
        private static void GetCustomBindingDetails(Channels.CustomBinding binding, ref string name, ref string mode, ref string credentialType)
        {
            name = GetBindingName <Channels.CustomBinding>(binding);

            Text.StringBuilder sb = new Text.StringBuilder();
            foreach (Channels.BindingElement element in binding.Elements)
            {
                if (sb.Length > 0)
                {
                    sb.Append(",");
                }

                // Only dump the name with the known binding elements
                sb.Append(IsKnownType(element) ? (element.GetType().Name) : "UserBindingElement");
            }
            mode = sb.ToString();
        }
コード例 #41
0
        public static ServiceReference1.MediaClient GetMedia1Client(string uri, double devideviceTimeOffset, string username = "", string password = "")
        {
            EndpointAddress             endpointAddress             = new EndpointAddress(uri);
            HttpTransportBindingElement httpTransportBindingElement = new HttpTransportBindingElement();

            httpTransportBindingElement.AuthenticationScheme = AuthenticationSchemes.Digest;

            var MessageEl = new TextMessageEncodingBindingElement();

            MessageEl.MessageVersion = MessageVersion.CreateVersion(EnvelopeVersion.Soap12, AddressingVersion.None);
            System.ServiceModel.Channels.CustomBinding customBinding = new System.ServiceModel.Channels.CustomBinding(MessageEl, httpTransportBindingElement);

            ServiceReference1.MediaClient media1Client = new ServiceReference1.MediaClient(customBinding, endpointAddress);

            if (username != string.Empty)
            {
                PasswordDigestBehavior behavior = new PasswordDigestBehavior(username, password, devideviceTimeOffset);
                media1Client.Endpoint.EndpointBehaviors.Add(behavior);
            }
            return(media1Client);
        }
コード例 #42
0
        public void Start()
        {
            Logging.Log(LogLevelEnum.Info, "Starting WCF service");
            ServiceAddress    = string.Format("net.tcp://{0}:{1}/", Utilities.GetIPv4Address(Settings.Instance.UseLoopback).ToString(), Settings.Instance.WcfPort);
            MexServiceAddress = string.Format("net.tcp://{0}:{1}/mex/", Utilities.GetIPv4Address().ToString(), Settings.Instance.WcfMexPort);
            Logging.Log(LogLevelEnum.Debug, string.Format("Service host address: {0}", ServiceAddress));
            Logging.Log(LogLevelEnum.Debug, string.Format("MEX Service host address: {0}", MexServiceAddress));
            serviceHost = new ServiceModel.ServiceHost(typeof(TService), new Uri(ServiceAddress));
            serviceHost.AddServiceEndpoint(typeof(TContract), new ServiceModel.NetTcpBinding(ServiceModel.SecurityMode.None), "");

            // Add TCP MEX endpoint
            ServiceModelChannels.BindingElement             bindingElement   = new ServiceModelChannels.TcpTransportBindingElement();
            ServiceModelChannels.CustomBinding              binding          = new ServiceModelChannels.CustomBinding(bindingElement);
            ServiceModelDescription.ServiceMetadataBehavior metadataBehavior = serviceHost.Description.Behaviors.Find <ServiceModelDescription.ServiceMetadataBehavior>();
            if (metadataBehavior == null)
            {
                metadataBehavior = new ServiceModelDescription.ServiceMetadataBehavior();
                serviceHost.Description.Behaviors.Add(metadataBehavior);
            }
            serviceHost.AddServiceEndpoint(typeof(ServiceModelDescription.IMetadataExchange), binding, MexServiceAddress);

            serviceHost.Open();
            Logging.Log(LogLevelEnum.Info, "WCF service started");
        }
コード例 #43
0
        public static DeviceClient GetClient(string ip, int port, string username = "", string password = "")
        {
            EndpointAddress serviceAddress = new EndpointAddress(string.Format("", ip, port));

            HttpTransportBindingElement httpBindingElement = new HttpTransportBindingElement();

            httpBindingElement.AuthenticationScheme = AuthenticationSchemes.Digest;

            var messageElement = new TextMessageEncodingBindingElement();

            messageElement.MessageVersion = MessageVersion.CreateVersion(EnvelopeVersion.Soap12, AddressingVersion.None);
            System.ServiceModel.Channels.CustomBinding customBinding = new System.ServiceModel.Channels.CustomBinding(messageElement, httpBindingElement);

            DeviceClient deviceClient = new DeviceClient(customBinding, serviceAddress);

            if (username != string.Empty)
            {
                // Handles adding of SOAP Security header containing User Token (user, nonce, pwd digest)
                PasswordDigestBehavior behavior = new PasswordDigestBehavior(username, password);
                deviceClient.Endpoint.Behaviors.Add(behavior);
            }

            return(deviceClient);
        }
コード例 #44
0
ファイル: ChannelBuilder.cs プロジェクト: Potapy4/dotnet-wcf
 public ChannelBuilder(ChannelBuilder channelBuilder)
 {
     _binding           = new CustomBinding(channelBuilder.Binding);
     _bindingParameters = channelBuilder.BindingParameters;
 }
コード例 #45
0
 internal static IChannelListener CreateChannelListener <TChannel>(TransportBindingElement transport) where TChannel : class, IChannel
 {
     System.ServiceModel.Channels.Binding binding = new CustomBinding(new BindingElement[] { transport });
     return(binding.BuildChannelListener <TChannel>(new object[0]));
 }
コード例 #46
0
        public static ServiceChannelFactory BuildChannelFactory(ServiceEndpoint serviceEndpoint, bool useActiveAutoClose)
        {
            if (serviceEndpoint == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(serviceEndpoint));
            }

            serviceEndpoint.EnsureInvariants();
            serviceEndpoint.ValidateForClient();

            ChannelRequirements requirements;
            ContractDescription contractDescription = serviceEndpoint.Contract;

            ChannelRequirements.ComputeContractRequirements(contractDescription, out requirements);

            BindingParameterCollection parameters;
            ClientRuntime clientRuntime = DispatcherBuilder.BuildProxyBehavior(serviceEndpoint, out parameters);

            Binding binding = serviceEndpoint.Binding;

            Type[] requiredChannels = ChannelRequirements.ComputeRequiredChannels(ref requirements);

            CustomBinding  customBinding = new CustomBinding(binding);
            BindingContext context       = new BindingContext(customBinding, parameters);

            customBinding = new CustomBinding(context.RemainingBindingElements);
            customBinding.CopyTimeouts(serviceEndpoint.Binding);

            foreach (Type type in requiredChannels)
            {
                if (type == typeof(IOutputChannel) && customBinding.CanBuildChannelFactory <IOutputChannel>(parameters))
                {
                    return(new ServiceChannelFactoryOverOutput(customBinding.BuildChannelFactory <IOutputChannel>(parameters), clientRuntime, binding));
                }

                if (type == typeof(IRequestChannel) && customBinding.CanBuildChannelFactory <IRequestChannel>(parameters))
                {
                    return(new ServiceChannelFactoryOverRequest(customBinding.BuildChannelFactory <IRequestChannel>(parameters), clientRuntime, binding));
                }

                if (type == typeof(IDuplexChannel) && customBinding.CanBuildChannelFactory <IDuplexChannel>(parameters))
                {
                    if (requirements.usesReply &&
                        binding.CreateBindingElements().Find <TransportBindingElement>().ManualAddressing)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                                                                                      SR.CantCreateChannelWithManualAddressing));
                    }

                    return(new ServiceChannelFactoryOverDuplex(customBinding.BuildChannelFactory <IDuplexChannel>(parameters), clientRuntime, binding));
                }

                if (type == typeof(IOutputSessionChannel) && customBinding.CanBuildChannelFactory <IOutputSessionChannel>(parameters))
                {
                    return(new ServiceChannelFactoryOverOutputSession(customBinding.BuildChannelFactory <IOutputSessionChannel>(parameters), clientRuntime, binding, false));
                }

                if (type == typeof(IRequestSessionChannel) && customBinding.CanBuildChannelFactory <IRequestSessionChannel>(parameters))
                {
                    return(new ServiceChannelFactoryOverRequestSession(customBinding.BuildChannelFactory <IRequestSessionChannel>(parameters), clientRuntime, binding, false));
                }

                if (type == typeof(IDuplexSessionChannel) && customBinding.CanBuildChannelFactory <IDuplexSessionChannel>(parameters))
                {
                    if (requirements.usesReply &&
                        binding.CreateBindingElements().Find <TransportBindingElement>().ManualAddressing)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                                                                                      SR.CantCreateChannelWithManualAddressing));
                    }

                    return(new ServiceChannelFactoryOverDuplexSession(customBinding.BuildChannelFactory <IDuplexSessionChannel>(parameters), clientRuntime, binding, useActiveAutoClose));
                }
            }

            foreach (Type type in requiredChannels)
            {
                // For SessionMode.Allowed or SessionMode.NotAllowed we will accept session-ful variants as well
                if (type == typeof(IOutputChannel) && customBinding.CanBuildChannelFactory <IOutputSessionChannel>(parameters))
                {
                    return(new ServiceChannelFactoryOverOutputSession(customBinding.BuildChannelFactory <IOutputSessionChannel>(parameters), clientRuntime, binding, true));
                }

                if (type == typeof(IRequestChannel) && customBinding.CanBuildChannelFactory <IRequestSessionChannel>(parameters))
                {
                    return(new ServiceChannelFactoryOverRequestSession(customBinding.BuildChannelFactory <IRequestSessionChannel>(parameters), clientRuntime, binding, true));
                }

                // and for SessionMode.Required, it is possible that the InstanceContextProvider is handling the session management, so
                // accept datagram variants if that is the case
                if (type == typeof(IRequestSessionChannel) && customBinding.CanBuildChannelFactory <IRequestChannel>(parameters) &&
                    customBinding.GetProperty <IContextSessionProvider>(parameters) != null)
                {
                    return(new ServiceChannelFactoryOverRequest(customBinding.BuildChannelFactory <IRequestChannel>(parameters), clientRuntime, binding));
                }
            }

            // we put a lot of work into creating a good error message, as this is a common case
            Dictionary <Type, byte> supportedChannels = new Dictionary <Type, byte>();

            if (customBinding.CanBuildChannelFactory <IOutputChannel>(parameters))
            {
                supportedChannels.Add(typeof(IOutputChannel), 0);
            }
            if (customBinding.CanBuildChannelFactory <IRequestChannel>(parameters))
            {
                supportedChannels.Add(typeof(IRequestChannel), 0);
            }
            if (customBinding.CanBuildChannelFactory <IDuplexChannel>(parameters))
            {
                supportedChannels.Add(typeof(IDuplexChannel), 0);
            }
            if (customBinding.CanBuildChannelFactory <IOutputSessionChannel>(parameters))
            {
                supportedChannels.Add(typeof(IOutputSessionChannel), 0);
            }
            if (customBinding.CanBuildChannelFactory <IRequestSessionChannel>(parameters))
            {
                supportedChannels.Add(typeof(IRequestSessionChannel), 0);
            }
            if (customBinding.CanBuildChannelFactory <IDuplexSessionChannel>(parameters))
            {
                supportedChannels.Add(typeof(IDuplexSessionChannel), 0);
            }

            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ChannelRequirements.CantCreateChannelException(
                                                                          supportedChannels.Keys, requiredChannels, binding.Name));
        }
コード例 #47
0
        static void Main(string[] args)
        {
            // Setup Log4Net configuration by loading it from configuration file
            // log4net is not necessary and is only being used for demonstration
            XmlConfigurator.Configure();

            // To ensure that the WSP is up and running.
            Thread.Sleep(1000);

            // Retrieve token
            IStsTokenService stsTokenService =
                new StsTokenServiceCache(
                    TokenServiceConfigurationFactory.CreateConfiguration()
                    );
            var securityToken = stsTokenService.GetToken();

            // Call WSP with token
            var hostname        = "https://localhost:8443/HelloWorld/services/helloworld";
            var customBinding   = new Channels.CustomBinding();
            var endpointAddress = new System.ServiceModel.EndpointAddress(
                new Uri(hostname),
                System.ServiceModel.EndpointIdentity.CreateDnsIdentity(
                    //"wsp.oioidws-net.dk TEST (funktionscertifikat)"
                    "eID JAVA test (funktionscertifikat)"
                    ),
                new Channels.AddressHeader[] { }
                );

            var asymmetric =
                new Channels.AsymmetricSecurityBindingElement
                (
                    new SecurityTokens.X509SecurityTokenParameters(
                        SecurityTokens.X509KeyIdentifierClauseType.Any,
                        SecurityTokens.SecurityTokenInclusionMode.AlwaysToInitiator
                        ),
                    new Soap.StrCustomization.CustomizedIssuedSecurityTokenParameters(
                        "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"
                        )
            {
                UseStrTransform = true
            }
                )
            {
                AllowSerializedSigningTokenOnReply = true,
                ProtectTokens = true
            };

            asymmetric.SetKeyDerivation(false);
            var messageEncoding =
                new Channels.TextMessageEncodingBindingElement
            {
                MessageVersion =
                    Channels.MessageVersion.Soap12WSAddressing10
            };
            var transport =
                (hostname.ToLower().StartsWith("https://"))
                    ? new Channels.HttpsTransportBindingElement()
                    : new Channels.HttpTransportBindingElement();

            customBinding.Elements.Add(asymmetric);
            customBinding.Elements.Add(messageEncoding);
            customBinding.Elements.Add(transport);

            System.ServiceModel.ChannelFactory <HelloWorldPortType> factory =
                new System.ServiceModel.ChannelFactory <HelloWorldPortType>(
                    customBinding, endpointAddress
                    );
            factory.Credentials.UseIdentityConfiguration = true;
            factory.Credentials.ServiceCertificate.SetScopedCertificate(
                X509Certificates.StoreLocation.LocalMachine,
                X509Certificates.StoreName.My,
                X509Certificates.X509FindType.FindByThumbprint,
                //"1F0830937C74B0567D6B05C07B6155059D9B10C7",
                "85398FCF737FB76F554C6F2422CC39D3A35EC26F",
                new Uri(hostname)
                );
            factory.Endpoint.Behaviors.Add(
                new Soap.Behaviors.SoapClientBehavior()
                );

            var channelWithIssuedToken =
                factory.CreateChannelWithIssuedToken(securityToken);

            var helloWorldRequestJohn = new HelloWorldRequest("John");

            Console.WriteLine(
                channelWithIssuedToken.HelloWorld(helloWorldRequestJohn).response
                );

            var helloWorldRequestJane = new HelloWorldRequest("Jane");

            Console.WriteLine(
                channelWithIssuedToken.HelloWorld(helloWorldRequestJane).response
                );

            try
            {
                // third call will trigger a SOAPFault
                var helloWorldRequest = new HelloWorldRequest("");
                Console.WriteLine(
                    channelWithIssuedToken.HelloWorld(helloWorldRequest).response
                    );
            }
            catch (Exception ex)
            {
                Console.WriteLine("Expected SOAPFault caught: " + ex.Message);
            }

            // Encrypted calls fails client side. However, encryption at message
            // level is not required and no further investigation has been
            // putted into this issue yet.
            //
            // Console.WriteLine(channelWithIssuedToken.HelloEncryptAndSign("Schultz"));

            Console.WriteLine("Press <Enter> to stop the service.");
            Console.ReadLine();
        }
        public void ImportEndpoint(WsdlImporter importer, WsdlEndpointConversionContext context)
        {
            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }
            if (context.Endpoint == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context.Endpoint");
            }
            if (context.Endpoint.Binding == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context.Endpoint.Binding");
            }

            // Try to post-process the unrecognized RequireHttpCookie assertion to augment the AllowCookies value
            // of HttpTransportBindingElement

            CustomBinding customBinding = context.Endpoint.Binding as CustomBinding;

            if (customBinding != null)
            {
                UnrecognizedAssertionsBindingElement unrecognized = null;
                unrecognized = customBinding.Elements.Find <UnrecognizedAssertionsBindingElement>();
                HttpTransportBindingElement http = null;
                if (unrecognized != null)
                {
                    XmlElement httpUseCookieAssertion = null;
                    if (ContextBindingElementPolicy.TryGetHttpUseCookieAssertion(unrecognized.BindingAsserions, out httpUseCookieAssertion))
                    {
                        foreach (BindingElement element in customBinding.Elements)
                        {
                            http = element as HttpTransportBindingElement;
                            if (http != null)
                            {
                                http.AllowCookies = true;
                                unrecognized.BindingAsserions.Remove(httpUseCookieAssertion);
                                if (unrecognized.BindingAsserions.Count == 0)
                                {
                                    customBinding.Elements.Remove(unrecognized);
                                }
                                break;
                            }
                        }
                    }
                }

                // Try to upgrade to standard binding

                BindingElementCollection bindingElements = customBinding.CreateBindingElements();
                Binding binding;
                if (!WSHttpContextBinding.TryCreate(bindingElements, out binding) &&
                    !NetTcpContextBinding.TryCreate(bindingElements, out binding))
                {
                    // Work around BasicHttpBinding.TryCreate insensitivity to HttpTransportBindingElement.AllowCookies value

                    if (http == null)
                    {
                        foreach (BindingElement bindingElement in bindingElements)
                        {
                            http = bindingElement as HttpTransportBindingElement;
                            if (http != null)
                            {
                                break;
                            }
                        }
                    }
                    if (http != null && http.AllowCookies)
                    {
                        http.AllowCookies = false;
                        if (BasicHttpBinding.TryCreate(bindingElements, out binding))
                        {
                            ((BasicHttpBinding)binding).AllowCookies = true;
                        }
                    }
                }

                if (binding != null)
                {
                    binding.Name             = context.Endpoint.Binding.Name;
                    binding.Namespace        = context.Endpoint.Binding.Namespace;
                    context.Endpoint.Binding = binding;
                }
            }
        }
コード例 #49
0
        internal static IChannelFactory <TChannel> CreateChannelFactory <TChannel>(TransportBindingElement transport)
        {
            Binding binding = new CustomBinding(transport);

            return(binding.BuildChannelFactory <TChannel>());
        }
コード例 #50
0
ファイル: BindingContext.cs プロジェクト: mbearup/wcf
 private BindingContext(CustomBinding binding,
                        BindingElementCollection remainingBindingElements,
                        BindingParameterCollection parameters)
 {
     Initialize(binding, remainingBindingElements, parameters);
 }
コード例 #51
0
ファイル: Program.cs プロジェクト: openmedicus/OIOIDWS.Net
        static void Main(string[] args)
        {
            // Setup Log4Net configuration by loading it from configuration file
            // log4net is not necessary and is only being used for demonstration
            XmlConfigurator.Configure();

            // To ensure that the WSP is up and running.
            Thread.Sleep(1000);

            // Retrieve token
            IStsTokenService stsTokenService =
                new StsTokenServiceCache(
                    TokenServiceConfigurationFactory.CreateConfiguration()
                    );
            var securityToken = stsTokenService.GetToken();

            // Call WSP with token
            var hostname        = "https://Digst.OioIdws.Wsp:9090/HelloWorld";
            var customBinding   = new Channels.CustomBinding();
            var endpointAddress = new System.ServiceModel.EndpointAddress(
                new Uri(hostname),
                System.ServiceModel.EndpointIdentity.CreateDnsIdentity(
                    "wsp.oioidws-net.dk TEST (funktionscertifikat)"
                    ),
                new Channels.AddressHeader[] { }
                );

            var asymmetric =
                new Channels.AsymmetricSecurityBindingElement
                (
                    new SecurityTokens.X509SecurityTokenParameters(
                        SecurityTokens.X509KeyIdentifierClauseType.Any,
                        SecurityTokens.SecurityTokenInclusionMode.AlwaysToInitiator
                        ),
                    new Soap.StrCustomization.CustomizedIssuedSecurityTokenParameters(
                        "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0"
                        )
            {
                UseStrTransform = true
            }
                )
            {
                AllowSerializedSigningTokenOnReply = true,
                ProtectTokens = true
            };

            asymmetric.SetKeyDerivation(false);
            var messageEncoding =
                new Channels.TextMessageEncodingBindingElement
            {
                MessageVersion =
                    Channels.MessageVersion.Soap12WSAddressing10
            };
            var transport =
                (hostname.ToLower().StartsWith("https://"))
                    ? new Channels.HttpsTransportBindingElement()
                    : new Channels.HttpTransportBindingElement();

            customBinding.Elements.Add(asymmetric);
            customBinding.Elements.Add(messageEncoding);
            customBinding.Elements.Add(transport);

            System.ServiceModel.ChannelFactory <IHelloWorld> factory =
                new System.ServiceModel.ChannelFactory <IHelloWorld>(
                    customBinding, endpointAddress
                    );
            factory.Credentials.UseIdentityConfiguration = true;
            factory.Credentials.ServiceCertificate.SetScopedCertificate(
                X509Certificates.StoreLocation.LocalMachine,
                X509Certificates.StoreName.My,
                X509Certificates.X509FindType.FindByThumbprint,
                "1F0830937C74B0567D6B05C07B6155059D9B10C7",
                new Uri(hostname)
                );
            factory.Endpoint.Behaviors.Add(
                new Soap.Behaviors.SoapClientBehavior()
                );

            var channelWithIssuedToken =
                factory.CreateChannelWithIssuedToken(securityToken);

            Console.WriteLine(channelWithIssuedToken.HelloNone("Schultz"));
            Console.WriteLine(channelWithIssuedToken.HelloSign("Schultz"));
            Console.WriteLine(channelWithIssuedToken.HelloEncryptAndSign("Schultz"));

            // Checking that SOAP faults can be read. SOAP faults are encrypted
            // in Sign and EncryptAndSign mode if no special care is taken.
            try
            {
                channelWithIssuedToken.HelloSignError("Schultz");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            // Checking that SOAP faults can be read when only being signed.
            // SOAP faults are only signed if special care is taken.
            try
            {
                channelWithIssuedToken.HelloSignErrorNotEncrypted("Schultz");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadLine();
        }
コード例 #52
0
 internal static IChannelFactory <TChannel> CreateChannelFactory <TChannel>(TransportBindingElement transport)
 {
     System.ServiceModel.Channels.Binding binding = new CustomBinding(new BindingElement[] { transport });
     return(binding.BuildChannelFactory <TChannel>(new object[0]));
 }