コード例 #1
0
 private void CreateBinding()
 {
     Collection<BindingElement> bindingElementsInTopDownChannelStackOrder = new Collection<BindingElement>();
     BindingElement securityBindingElement = this.config.SecurityManager.GetSecurityBindingElement();
     if (securityBindingElement != null)
     {
         bindingElementsInTopDownChannelStackOrder.Add(securityBindingElement);
     }
     TcpTransportBindingElement item = new TcpTransportBindingElement {
         MaxReceivedMessageSize = this.config.MaxReceivedMessageSize,
         MaxBufferPoolSize = this.config.MaxBufferPoolSize,
         TeredoEnabled = true
     };
     MessageEncodingBindingElement encodingBindingElement = null;
     if (this.messageHandler != null)
     {
         encodingBindingElement = this.messageHandler.EncodingBindingElement;
     }
     if (encodingBindingElement == null)
     {
         BinaryMessageEncodingBindingElement element4 = new BinaryMessageEncodingBindingElement();
         this.config.ReaderQuotas.CopyTo(element4.ReaderQuotas);
         bindingElementsInTopDownChannelStackOrder.Add(element4);
     }
     else
     {
         bindingElementsInTopDownChannelStackOrder.Add(encodingBindingElement);
     }
     bindingElementsInTopDownChannelStackOrder.Add(item);
     this.binding = new CustomBinding(bindingElementsInTopDownChannelStackOrder);
     this.binding.ReceiveTimeout = TimeSpan.MaxValue;
 }
        protected internal override BindingElement CreateBindingElement()
        {
            BinaryMessageEncodingBindingElement binding = new BinaryMessageEncodingBindingElement();

            this.ApplyConfiguration(binding);
            return(binding);
        }
コード例 #3
0
        private Binding CreateBinaryBinding(bool isSecure)
        {
            var binaryElement = new BinaryMessageEncodingBindingElement();

#if WPF
            binaryElement.ReaderQuotas.MaxStringContentLength = 2147483647;
#endif

            BindingElementCollection elements = new BindingElementCollection();
            elements.Add(binaryElement);

            if (isSecure)
            {
                elements.Add(new HttpsTransportBindingElement()
                {
                    MaxBufferSize = 2147483647, MaxReceivedMessageSize = 2147483647
                });
            }
            else
            {
                elements.Add(new HttpTransportBindingElement()
                {
                    MaxBufferSize = 2147483647, MaxReceivedMessageSize = 2147483647
                });
            }

            return(new CustomBinding(elements));
        }
コード例 #4
0
 private NetTcpBinding(TcpTransportBindingElement transport,
                       BinaryMessageEncodingBindingElement encoding,
                       NetTcpSecurity security)
     : this()
 {
     _security = security;
 }
コード例 #5
0
        private Binding GetChannelBinding()
        {
            switch (ApplicationStartupParameters.Current.Mode)
            {
            case ApplicationServiceMode.BasicHttp:
                var binaryMessageEncoding = new BinaryMessageEncodingBindingElement();

                if (HtmlPage.Document.DocumentUri.Scheme.Equals(Uri.UriSchemeHttp))
                {
                    var http = new HttpTransportBindingElement
                    {
                        MaxReceivedMessageSize = int.MaxValue,
                        MaxBufferSize          = int.MaxValue,
                        TransferMode           = TransferMode.Buffered
                    };
                    _binding = new CustomBinding(binaryMessageEncoding, http);
                    return(_binding);
                }
                var https = new HttpsTransportBindingElement
                {
                    MaxReceivedMessageSize = int.MaxValue,
                    MaxBufferSize          = int.MaxValue,
                    TransferMode           = TransferMode.Buffered
                };
                _binding = new CustomBinding(binaryMessageEncoding, https);
                return(_binding);
            }

            return(null);
        }
    public static void MessageVersion_Property_Sets(MessageVersion version)
    {
        BinaryMessageEncodingBindingElement bindingElement = new BinaryMessageEncodingBindingElement();

        bindingElement.MessageVersion = version;
        Assert.Equal <MessageVersion>(version, bindingElement.MessageVersion);
    }
コード例 #7
0
        private void InitializeFrom(TcpTransportBindingElement transport, BinaryMessageEncodingBindingElement encoding, TransactionFlowBindingElement context, ReliableSessionBindingElement session)
        {
            // TODO: Fx.Assert(transport != null, "Invalid (null) transport value.");
            // TODO: Fx.Assert(encoding != null, "Invalid (null) encoding value.");
            // TODO: Fx.Assert(context != null, "Invalid (null) context value.");
            // TODO: Fx.Assert(security != null, "Invalid (null) security value.");

            // transport
            this.HostNameComparisonMode = transport.HostNameComparisonMode;
            this.MaxBufferPoolSize      = transport.MaxBufferPoolSize;
            this.MaxBufferSize          = transport.MaxBufferSize;

            this.MaxReceivedMessageSize = transport.MaxReceivedMessageSize;
            this.PortSharingEnabled     = transport.PortSharingEnabled;
            this.TransferMode           = transport.TransferMode;

            // encoding
            this.ReaderQuotas = encoding.ReaderQuotas;

            // context
            this.TransactionFlow     = context.Transactions;
            this.TransactionProtocol = context.TransactionProtocol;

            //session
            if (session != null)
            {
                // only set properties that have standard binding manifestations
                _session.InactivityTimeout = session.InactivityTimeout;
                _session.Ordered           = session.Ordered;
            }
        }
コード例 #8
0
 private void Initialize()
 {
     this.resolverSettings = new PeerResolverSettings();
     this.transport        = new PeerTransportBindingElement();
     this.encoding         = new BinaryMessageEncodingBindingElement();
     this.peerSecurity     = new PeerSecuritySettings();
 }
コード例 #9
0
        public override BindingElementCollection CreateBindingElements()
        {
            BindingElement         tx  = new TransactionFlowBindingElement(TransactionProtocol.WSAtomicTransactionOctober2004);
            SecurityBindingElement sec = CreateMessageSecurity();
            var msg = new BinaryMessageEncodingBindingElement();

            if (ReaderQuotas != null)
            {
                ReaderQuotas.CopyTo(msg.ReaderQuotas);
            }
            var                   trsec = CreateTransportSecurity();
            BindingElement        tr    = GetTransport();
            List <BindingElement> list  = new List <BindingElement> ();

            if (tx != null)
            {
                list.Add(tx);
            }
            if (sec != null)
            {
                list.Add(sec);
            }
            list.Add(msg);
            if (trsec != null)
            {
                list.Add(trsec);
            }
            list.Add(tr);
            return(new BindingElementCollection(list.ToArray()));
        }
コード例 #10
0
        // check that properties of the HttpTransportBindingElement and
        // MessageEncodingBindingElement not exposed as properties on BasicHttpBinding
        // match default values of the binding elements
        private bool IsBindingElementsMatch(TcpTransportBindingElement transport, BinaryMessageEncodingBindingElement encoding)
        {
            if (!_transport.IsMatch(transport))
            {
                return(false);
            }

            if (!_encoding.IsMatch(encoding))
            {
                return(false);
            }

            if (!_context.IsMatch(_context))
            {
                return(false);
            }

            if (_reliableSession.Enabled)
            {
                if (!_session.IsMatch(_session))
                {
                    return(false);
                }
            }

            return(true);
        }
コード例 #11
0
ファイル: NetTcpBinding.cs プロジェクト: shijiaxing/wcf
 private NetTcpBinding(TcpTransportBindingElement transport,
               BinaryMessageEncodingBindingElement encoding,
               NetTcpSecurity security)
     : this()
 {
     _security = security;
 }
コード例 #12
0
        void InitializeFrom(HttpTransportBindingElement transport, MessageEncodingBindingElement encoding, ReliableSessionBindingElement session)
        {
            this.InitializeFrom(transport, encoding);
            if (encoding is BinaryMessageEncodingBindingElement)
            {
                this.messageEncoding = NetHttpMessageEncoding.Binary;
                BinaryMessageEncodingBindingElement binary = (BinaryMessageEncodingBindingElement)encoding;
                this.ReaderQuotas = binary.ReaderQuotas;
            }

            if (encoding is TextMessageEncodingBindingElement)
            {
                this.messageEncoding = NetHttpMessageEncoding.Text;
            }
            else if (encoding is MtomMessageEncodingBindingElement)
            {
                this.messageEncoding = NetHttpMessageEncoding.Mtom;
            }

            if (session != null)
            {
                // only set properties that have standard binding manifestations
                this.session.InactivityTimeout = session.InactivityTimeout;
                this.session.Ordered           = session.Ordered;
            }
        }
        public void FileSystemDispatcher_Picks_Up_Existing_Messages()
        {
            BinaryMessageEncodingBindingElement element = new BinaryMessageEncodingBindingElement();
            MessageEncoder encoder = element.CreateMessageEncoderFactory().Encoder;

            ServiceBusRuntime dispatchRuntime = new ServiceBusRuntime(new DirectDeliveryCore());
            var subscription = new SubscriptionEndpoint(Guid.NewGuid(), "File System Dispatcher", null, null, typeof(IContract), new FileSystemDispatcher(new ConverterMessageDeliveryWriterFactory(encoder, typeof(IContract)), Config.IncomingFilePath), new PassThroughMessageFilter());

            dispatchRuntime.Subscribe(subscription);

            ServiceBusRuntime listenerRuntime = new ServiceBusRuntime(new DirectDeliveryCore());
            var listener = new ListenerEndpoint(Guid.NewGuid(), "File System Listener", null, null, typeof(IContract), new FileSystemListener(new ConverterMessageDeliveryReaderFactory(encoder, typeof(IContract)), Config.IncomingFilePath, Config.ProcessedFilePath));

            listenerRuntime.AddListener(listener);
            listenerRuntime.Subscribe(new SubscriptionEndpoint(Guid.NewGuid(), "Pass through", null, null, typeof(IContract), new ActionDispatcher((se, md) => { }), new PassThroughMessageFilter()));

            var dispatchTester = new ServiceBusTest(dispatchRuntime);
            var listenerTester = new ServiceBusTest(listenerRuntime);


            string message = "test this thing";

            dispatchTester.StartAndStop(() =>
            {
                dispatchRuntime.PublishOneWay(typeof(IContract), "PublishThis", message);

                listenerTester.WaitForDeliveries(1, TimeSpan.FromSeconds(10), () =>
                {
                });
            });

            dispatchRuntime.RemoveSubscription(subscription);
        }
コード例 #14
0
        public void FileSystemDispatcher_Picks_Up_Existing_Messages()
        {
            BinaryMessageEncodingBindingElement element = new BinaryMessageEncodingBindingElement();
            MessageEncoder encoder = element.CreateMessageEncoderFactory().Encoder;

            ServiceBusRuntime dispatchRuntime = new ServiceBusRuntime(new DirectDeliveryCore());
            var subscription = new SubscriptionEndpoint(Guid.NewGuid(), "File System Dispatcher", null, null, typeof(IContract), new FileSystemDispatcher(new ConverterMessageDeliveryWriterFactory(encoder,typeof(IContract)),Config.IncomingFilePath), new PassThroughMessageFilter());
            dispatchRuntime.Subscribe(subscription);

            ServiceBusRuntime listenerRuntime = new ServiceBusRuntime(new DirectDeliveryCore());
            var listener = new ListenerEndpoint(Guid.NewGuid(), "File System Listener", null, null, typeof(IContract), new FileSystemListener(new ConverterMessageDeliveryReaderFactory(encoder, typeof(IContract)),Config.IncomingFilePath, Config.ProcessedFilePath));
            listenerRuntime.AddListener(listener);
            listenerRuntime.Subscribe(new SubscriptionEndpoint(Guid.NewGuid(), "Pass through", null, null, typeof(IContract), new ActionDispatcher((se, md) => { }), new PassThroughMessageFilter()));

            var dispatchTester = new ServiceBusTest(dispatchRuntime);
            var listenerTester = new ServiceBusTest(listenerRuntime);

            string message = "test this thing";

            dispatchTester.StartAndStop(() =>
            {
                dispatchRuntime.PublishOneWay(typeof(IContract), "PublishThis", message);

                listenerTester.WaitForDeliveries(1, TimeSpan.FromSeconds(10), () =>
                {
                });
            });

            dispatchRuntime.RemoveSubscription(subscription);
        }
コード例 #15
0
        public void Enqueue_Transactions_Abort_Properly()
        {
            recreateQueue();


            BinaryMessageEncodingBindingElement element = new BinaryMessageEncodingBindingElement();
            MessageEncoder encoder = element.CreateMessageEncoderFactory().Encoder;

            MessageDeliveryFormatter formatter = new MessageDeliveryFormatter(new ConverterMessageDeliveryReaderFactory(encoder, typeof(IContract)), new ConverterMessageDeliveryWriterFactory(encoder, typeof(IContract)));

            MsmqMessageDeliveryQueue queue = new MsmqMessageDeliveryQueue(Config.TestQueuePath, formatter);

            SubscriptionEndpoint endpoint = new SubscriptionEndpoint(Guid.NewGuid(), "SubscriptionName", "http://localhost/test", "SubscriptionConfigName", typeof(IContract), new WcfProxyDispatcher(), new PassThroughMessageFilter());

            MessageDelivery enqueued = new MessageDelivery(endpoint.Id, typeof(IContract), "PublishThis", "randomMessageData", 3, new MessageDeliveryContext());

            Assert.IsNull(queue.Peek(TimeSpan.FromSeconds(1))); // make sure queue is null before starting

            // Enqueue, but abort transaction
            using (TransactionScope ts = new TransactionScope())
            {
                queue.Enqueue(enqueued);
            }

            using (TransactionScope ts = new TransactionScope())
            {
                MessageDelivery dequeued = queue.Dequeue(TimeSpan.FromSeconds(5));
                Assert.IsNull(dequeued);
            }
        }
コード例 #16
0
 NetTcpBinding(TcpTransportBindingElement transport, BinaryMessageEncodingBindingElement encoding, TransactionFlowBindingElement context, ReliableSessionBindingElement session, NetTcpSecurity security)
     : this()
 {
     this.security = security;
     this.ReliableSession.Enabled = session != null;
     InitializeFrom(transport, encoding, context, session);
 }
コード例 #17
0
 private NetTcpBinding(TcpTransportBindingElement transport, BinaryMessageEncodingBindingElement encoding, TransactionFlowBindingElement context, ReliableSessionBindingElement session, NetTcpSecurity security)
     : this()
 {
     _security = security;
     this.ReliableSession.Enabled = session != null;
     InitializeFrom(transport, encoding, context, session);
 }
コード例 #18
0
        public static ServiceBusRuntime MsmqRuntime <T>()
        {
            // Drop test queues if they already exist
            if (MsmqMessageDeliveryQueue.Exists(_testQueuePath))
            {
                MsmqMessageDeliveryQueue.Delete(_testQueuePath);
            }
            if (MsmqMessageDeliveryQueue.Exists(_retryQueuePath))
            {
                MsmqMessageDeliveryQueue.Delete(_retryQueuePath);
            }
            if (MsmqMessageDeliveryQueue.Exists(_failQueuePath))
            {
                MsmqMessageDeliveryQueue.Delete(_failQueuePath);
            }

            // Create test queues
            MsmqMessageDeliveryQueue.Create(_testQueuePath);
            MsmqMessageDeliveryQueue.Create(_retryQueuePath);
            MsmqMessageDeliveryQueue.Create(_failQueuePath);


            BinaryMessageEncodingBindingElement element = new BinaryMessageEncodingBindingElement();
            MessageEncoder encoder = element.CreateMessageEncoderFactory().Encoder;

            MessageDeliveryFormatter formatter = new MessageDeliveryFormatter(new ConverterMessageDeliveryReaderFactory(encoder, typeof(T)), new ConverterMessageDeliveryWriterFactory(encoder, typeof(T)));

            MsmqMessageDeliveryQueue testQueue  = new MsmqMessageDeliveryQueue(_testQueuePath, formatter);
            MsmqMessageDeliveryQueue retryQueue = new MsmqMessageDeliveryQueue(_retryQueuePath, formatter);
            MsmqMessageDeliveryQueue failQueue  = new MsmqMessageDeliveryQueue(_failQueuePath, formatter);

            return(new ServiceBusRuntime(new QueuedDeliveryCore(testQueue, retryQueue, failQueue)));
        }
コード例 #19
0
        private static Binding GetBinding()
        {
            var httpTransport = new HttpTransportBindingElement()
            {
                MaxBufferSize          = 2147483647,
                MaxBufferPoolSize      = 2147483647,
                MaxReceivedMessageSize = 2147483647
            };

            var binaryEconding = new BinaryMessageEncodingBindingElement()
            {
                ReaderQuotas = new XmlDictionaryReaderQuotas()
                {
                    MaxDepth = 32,
                    MaxStringContentLength = 5242880,
                    MaxArrayLength         = 200000,
                    MaxBytesPerRead        = 4096,
                    MaxNameTableCharCount  = 16384
                }
            };

            var retBinding = new CustomBinding(binaryEconding, httpTransport)
            {
                Name           = "http_Unsecured",
                SendTimeout    = TimeSpan.MaxValue,
                ReceiveTimeout = TimeSpan.MaxValue
            };

            return(retBinding);
        }
    public static void MaxSessionSize_Property_Sets(int value)
    {
        BinaryMessageEncodingBindingElement bindingElement = new BinaryMessageEncodingBindingElement();

        bindingElement.MaxSessionSize = value;
        Assert.Equal <int>(value, bindingElement.MaxSessionSize);
    }
コード例 #21
0
        // check that properties of the HttpTransportBindingElement and
        // MessageEncodingBindingElement not exposed as properties on BasicHttpBinding
        // match default values of the binding elements
        private bool IsBindingElementsMatch(TcpTransportBindingElement transport, BinaryMessageEncodingBindingElement encoding, TransactionFlowBindingElement context, ReliableSessionBindingElement session)
        {
            if (!_transport.IsMatch(transport))
            {
                return(false);
            }
            if (!_encoding.IsMatch(encoding))
            {
                return(false);
            }
            if (!_context.IsMatch(context))
            {
                return(false);
            }
            if (_reliableSession.Enabled)
            {
                if (!_session.IsMatch(session))
                {
                    return(false);
                }
            }
            else if (session != null)
            {
                return(false);
            }

            return(true);
        }
コード例 #22
0
 private static NetworkDetector.ConnectivityStatus CheckTcpConnectivity(Uri baseAddress, out Exception exception)
 {
     NetworkDetector.ConnectivityStatus connectivityStatu = NetworkDetector.ConnectivityStatus.Unavailable;
     exception = null;
     if (!RelayEnvironment.GetEnvironmentVariable("RELAYFORCEHTTP", false) && !RelayEnvironment.GetEnvironmentVariable("RELAYFORCEHTTPS", false))
     {
         try
         {
             BinaryMessageEncodingBindingElement binaryMessageEncodingBindingElement = new BinaryMessageEncodingBindingElement();
             TcpTransportBindingElement          tcpTransportBindingElement          = new TcpTransportBindingElement();
             tcpTransportBindingElement.ConnectionPoolSettings.MaxOutboundConnectionsPerEndpoint = 100;
             tcpTransportBindingElement.MaxReceivedMessageSize = (long)65536;
             CustomBinding customBinding = new CustomBinding();
             customBinding.Elements.Add(binaryMessageEncodingBindingElement);
             customBinding.Elements.Add(tcpTransportBindingElement);
             customBinding.OpenTimeout    = TimeSpan.FromSeconds(10);
             customBinding.SendTimeout    = TimeSpan.FromSeconds(10);
             customBinding.ReceiveTimeout = TimeSpan.MaxValue;
             int num = 9350;
             Uri uri = ServiceBusUriHelper.CreateServiceUri("net.tcp", string.Concat(baseAddress.DnsSafeHost, ":", num.ToString(CultureInfo.InvariantCulture)), "/");
             IChannelFactory <IDuplexSessionChannel> channelFactory = null;
             IDuplexSessionChannel duplexSessionChannel             = null;
             try
             {
                 channelFactory = customBinding.BuildChannelFactory <IDuplexSessionChannel>(new object[0]);
                 channelFactory.Open();
                 duplexSessionChannel = channelFactory.CreateChannel(new EndpointAddress(uri, new AddressHeader[0]));
                 duplexSessionChannel.Open();
                 Message message = Message.CreateMessage(MessageVersion.Default, "http://schemas.microsoft.com/netservices/2009/05/servicebus/connect/OnewayPing", new OnewayPingMessage());
                 duplexSessionChannel.Send(message, customBinding.SendTimeout);
                 duplexSessionChannel.Close();
                 duplexSessionChannel = null;
                 channelFactory.Close();
                 channelFactory = null;
             }
             finally
             {
                 if (duplexSessionChannel != null)
                 {
                     duplexSessionChannel.Abort();
                 }
                 if (channelFactory != null)
                 {
                     channelFactory.Abort();
                 }
             }
             connectivityStatu = NetworkDetector.ConnectivityStatus.Available;
         }
         catch (CommunicationException communicationException)
         {
             exception = communicationException;
         }
         catch (TimeoutException timeoutException)
         {
             exception = timeoutException;
         }
     }
     NetworkDetector.LogResult(baseAddress, "Tcp", connectivityStatu);
     return(connectivityStatu);
 }
コード例 #23
0
        /// <summary>
        /// Generates a <see cref="BasicHttpBinding"/> which is configured to speak to the
        /// "soap" endpoint
        /// </summary>
        /// <param name="endpoint">Absolute service URI without protocol suffix such as "/soap" or "/binary"</param>
        /// <param name="requiresSecureEndpoint"><c>true</c> if communication must be secured, otherwise <c>false</c></param>
        /// <returns>A <see cref="Binding"/> which is compatible with soap endpoint</returns>
        protected override Binding CreateBinding(Uri endpoint, bool requiresSecureEndpoint)
        {
            var encoding = new BinaryMessageEncodingBindingElement();

            HttpTransportBindingElement transport;

            if (endpoint.Scheme.Equals(Uri.UriSchemeHttps))
            {
                transport = new HttpsTransportBindingElement();
            }
            else if (requiresSecureEndpoint)
            {
                throw new InvalidOperationException("use https to connect to secure endpoint");
            }
            else
            {
                transport = new HttpTransportBindingElement();
            }

            transport.MaxReceivedMessageSize = int.MaxValue;
            CustomBinding binding = new CustomBinding(encoding, transport);

            transport.AllowCookies = true;
            return(binding);
        }
コード例 #24
0
        public override BindingElementCollection CreateBindingElements()
        {
            BinaryMessageEncodingBindingElement be =
                new BinaryMessageEncodingBindingElement();

            quotas.CopyTo(be.ReaderQuotas);
            MsmqTransportBindingElement te =
                new MsmqTransportBindingElement();

            te.MaxPoolSize           = (int)MaxBufferPoolSize;
            te.QueueTransferProtocol = QueueTransferProtocol;
            te.UseActiveDirectory    = UseActiveDirectory;
            te.CustomDeadLetterQueue = CustomDeadLetterQueue;
            te.DeadLetterQueue       = DeadLetterQueue;
            te.Durable                = Durable;
            te.ExactlyOnce            = ExactlyOnce;
            te.MaxReceivedMessageSize = MaxReceivedMessageSize;
            te.MaxRetryCycles         = MaxRetryCycles;
            te.MsmqTransportSecurity.MsmqAuthenticationMode  = Security.Transport.MsmqAuthenticationMode;
            te.MsmqTransportSecurity.MsmqEncryptionAlgorithm = Security.Transport.MsmqEncryptionAlgorithm;
            te.MsmqTransportSecurity.MsmqProtectionLevel     = Security.Transport.MsmqProtectionLevel;
            te.MsmqTransportSecurity.MsmqSecureHashAlgorithm = Security.Transport.MsmqSecureHashAlgorithm;
            te.ReceiveErrorHandling = ReceiveErrorHandling;
            te.ReceiveRetryCount    = ReceiveRetryCount;
            te.RetryCycleDelay      = RetryCycleDelay;
            te.TimeToLive           = TimeToLive;
            te.UseMsmqTracing       = UseMsmqTracing;
            te.UseSourceJournal     = UseSourceJournal;

            return(new BindingElementCollection(new BindingElement [] { be, te }));
        }
コード例 #25
0
ファイル: samplecli15.cs プロジェクト: stanasse/olive
    static void Run()
    {
        SymmetricSecurityBindingElement sbe =
            new SymmetricSecurityBindingElement();

        sbe.MessageSecurityVersion       = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
        sbe.RequireSignatureConfirmation = true;
        //sbe.IncludeTimestamp = false;

        X509SecurityTokenParameters p =
            new X509SecurityTokenParameters(X509KeyIdentifierClauseType.Thumbprint, SecurityTokenInclusionMode.AlwaysToRecipient);

        p.RequireDerivedKeys = false;
        sbe.EndpointSupportingTokenParameters.Endorsing.Add(p);
        sbe.ProtectionTokenParameters =
            new X509SecurityTokenParameters(X509KeyIdentifierClauseType.Thumbprint, SecurityTokenInclusionMode.Never);
        //sbe.SetKeyDerivation (false);
        //sbe.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
        var              mbe     = new BinaryMessageEncodingBindingElement();
        var              tbe     = new TcpTransportBindingElement();
        CustomBinding    binding = new CustomBinding(new XBE(), sbe, mbe, tbe);
        X509Certificate2 cert    = new X509Certificate2("test.pfx", "mono");
        X509Certificate2 cert2   = cert;      //new X509Certificate2 ("test2.cer");
        FooProxy         proxy   = new FooProxy(binding,
                                                new EndpointAddress(new Uri("http://localhost:8080"), new X509CertificateEndpointIdentity(cert2)));

        //proxy.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
        proxy.ClientCredentials.ClientCertificate.Certificate = cert;
        proxy.Open();
        Console.WriteLine(proxy.Echo("TEST FOR ECHO"));
    }
コード例 #26
0
        public static CustomBinding CreateBinding(bool portSharingEnabled, int maxReceivedMessageSize, long maxBufferPoolSize, bool useSslStreamSecurity, bool clientCertificateAuthEnabled, DnsEndpointIdentity endpointIdentity, IssuedSecurityTokenParameters issuedTokenParameters)
        {
            TransactionFlowBindingElement       transactionFlowBindingElement       = new TransactionFlowBindingElement();
            BinaryMessageEncodingBindingElement binaryMessageEncodingBindingElement = new BinaryMessageEncodingBindingElement();

            binaryMessageEncodingBindingElement.ReaderQuotas.MaxStringContentLength = maxReceivedMessageSize;
            TcpTransportBindingElement tcpTransportBindingElement = new TcpTransportBindingElement()
            {
                PortSharingEnabled     = portSharingEnabled,
                MaxReceivedMessageSize = (long)maxReceivedMessageSize,
                MaxBufferPoolSize      = maxBufferPoolSize
            };
            CustomBinding customBinding = new CustomBinding();

            customBinding.Elements.Add(transactionFlowBindingElement);
            if (useSslStreamSecurity)
            {
                SslStreamSecurityBindingElement sslStreamSecurityBindingElement = new SslStreamSecurityBindingElement();
                if (endpointIdentity != null)
                {
                    sslStreamSecurityBindingElement.IdentityVerifier = new LenientDnsIdentityVerifier(endpointIdentity);
                }
                sslStreamSecurityBindingElement.RequireClientCertificate = clientCertificateAuthEnabled;
                customBinding.Elements.Add(sslStreamSecurityBindingElement);
            }
            customBinding.Elements.Add(binaryMessageEncodingBindingElement);
            customBinding.Elements.Add(tcpTransportBindingElement);
            return(customBinding);
        }
コード例 #27
0
        private static Binding CreateBinding(Uri address)
        {
            var encoding = new BinaryMessageEncodingBindingElement()
            {
            };

            // ServiceUtility.SetReaderQuotas(encoding.ReaderQuotas);


            HttpTransportBindingElement transport;

            if (address.Scheme.Equals(Uri.UriSchemeHttps))
            {
                transport = new HttpsTransportBindingElement();
            }
            else
            {
                transport = new HttpTransportBindingElement();
            }


            /*
             * transport.MaxReceivedMessageSize = ServiceUtility.MaxReceivedMessageSize;
             * if (ServiceUtility.AuthenticationScheme != AuthenticationSchemes.None)
             * {
             *  transport.AuthenticationScheme = ServiceUtility.AuthenticationScheme;
             * }
             */

            return(new CustomBinding(encoding, transport));
        }
コード例 #28
0
 internal static CustomBinding BuildCustomBinding(bool isSsl)
 {
     BinaryMessageEncodingBindingElement binary = new BinaryMessageEncodingBindingElement();
     HttpTransportBindingElement transport = isSsl ? new HttpsTransportBindingElement() : new HttpTransportBindingElement();
     transport.MaxBufferSize = 2147483647;
     transport.MaxReceivedMessageSize = 2147483647;
     return new CustomBinding(binary, transport);
 }
コード例 #29
0
 private void Initialize()
 {
     this.transport       = new TcpTransportBindingElement();
     this.encoding        = new BinaryMessageEncodingBindingElement();
     this.context         = GetDefaultTransactionFlowBindingElement();
     this.session         = new ReliableSessionBindingElement();
     this.reliableSession = new OptionalReliableSession(this.session);
 }
コード例 #30
0
        internal static bool TryCreate(BindingElementCollection elements, out Binding binding)
        {
            Microsoft.ServiceBus.UnifiedSecurityMode unifiedSecurityMode;
            NetOnewayRelaySecurity netOnewayRelaySecurity;
            bool flag;

            binding = null;
            if (elements.Count > 3)
            {
                return(false);
            }
            SecurityBindingElement securityBindingElement = null;
            BinaryMessageEncodingBindingElement  binaryMessageEncodingBindingElement  = null;
            RelayedOnewayTransportBindingElement relayedOnewayTransportBindingElement = null;

            using (IEnumerator <BindingElement> enumerator = elements.GetEnumerator())
            {
                while (enumerator.MoveNext())
                {
                    BindingElement current = enumerator.Current;
                    if (current is SecurityBindingElement)
                    {
                        securityBindingElement = current as SecurityBindingElement;
                    }
                    else if (current is TransportBindingElement)
                    {
                        relayedOnewayTransportBindingElement = current as RelayedOnewayTransportBindingElement;
                    }
                    else if (!(current is MessageEncodingBindingElement))
                    {
                        flag = false;
                        return(flag);
                    }
                    else
                    {
                        binaryMessageEncodingBindingElement = current as BinaryMessageEncodingBindingElement;
                    }
                }
                unifiedSecurityMode = (!relayedOnewayTransportBindingElement.TransportProtectionEnabled ? Microsoft.ServiceBus.UnifiedSecurityMode.None | Microsoft.ServiceBus.UnifiedSecurityMode.Message : Microsoft.ServiceBus.UnifiedSecurityMode.Transport | Microsoft.ServiceBus.UnifiedSecurityMode.TransportWithMessageCredential);
                if (binaryMessageEncodingBindingElement == null)
                {
                    return(false);
                }
                if (!NetOnewayRelayBinding.TryCreateSecurity(securityBindingElement, relayedOnewayTransportBindingElement.RelayClientAuthenticationType, unifiedSecurityMode, out netOnewayRelaySecurity))
                {
                    return(false);
                }
                NetOnewayRelayBinding netOnewayRelayBinding = new NetOnewayRelayBinding(netOnewayRelaySecurity);
                NetOnewayRelayBinding.InitializeFrom(relayedOnewayTransportBindingElement, binaryMessageEncodingBindingElement);
                if (!netOnewayRelayBinding.IsBindingElementsMatch(relayedOnewayTransportBindingElement, binaryMessageEncodingBindingElement))
                {
                    return(false);
                }
                binding = netOnewayRelayBinding;
                return(true);
            }
            return(flag);
        }
コード例 #31
0
        private void InitializeValue()
        {
            _compressionTypeOptions = CompressionTypeOptions.None;
            _operationBehaviours    = new Dictionary <string, OperationBehaviourElement>();

            this._encoding      = new BinaryMessageEncodingBindingElement();
            this._transport     = GetTransport();
            this._mainTransport = new ProtoBufMetaDataBindingElement(this._transport);
        }
コード例 #32
0
        private void Initialize()
        {
            _transport = new TcpTransportBindingElement();
            _encoding  = new BinaryMessageEncodingBindingElement();

            // NetNative and CoreCLR initialize to what TransportBindingElement does in the desktop
            // This property is not available in shipped contracts
            _maxBufferPoolSize = TransportDefaults.MaxBufferPoolSize;
        }
コード例 #33
0
 private void InitializeFrom(PeerTransportBindingElement transport, BinaryMessageEncodingBindingElement encoding)
 {
     this.MaxBufferPoolSize      = transport.MaxBufferPoolSize;
     this.MaxReceivedMessageSize = transport.MaxReceivedMessageSize;
     this.ListenIPAddress        = transport.ListenIPAddress;
     this.Port          = transport.Port;
     this.Security.Mode = transport.Security.Mode;
     this.ReaderQuotas  = encoding.ReaderQuotas;
 }
コード例 #34
0
        private void InitializeValue()
        {
            _compressionTypeOptions = CompressionTypeOptions.None;
            _operationBehaviours = new Dictionary<string, OperationBehaviourElement>();

            this._encoding = new BinaryMessageEncodingBindingElement();
            this._transport = GetTransport();
            this._mainTransport = new ProtoBufMetaDataBindingElement(this._transport);
        }
    public static void CompressionFormat_Property_Sets(CompressionFormat format)
    {
        BinaryMessageEncodingBindingElement bindingElement = new BinaryMessageEncodingBindingElement();
        bindingElement.CompressionFormat = format;
        Assert.Equal(format, bindingElement.CompressionFormat);

        // Note: invalid formats can be tested once we have a transport underneath, as it's the transport that determines 
        // whether or not the CompressionFormat is valid for it. 
    }
コード例 #36
0
		static ClientMessageUtility()
		{
			ClientMessageUtility.defaultEncoderBindingElement = new BinaryMessageEncodingBindingElement();
			ClientMessageUtility.defaultEncoderBindingElement.ReaderQuotas.MaxArrayLength = 61440;
			ClientMessageUtility.defaultEncoderBindingElement.ReaderQuotas.MaxStringContentLength = 61440;
			ClientMessageUtility.defaultEncoderBindingElement.ReaderQuotas.MaxDepth = 32;
			ClientMessageUtility.defaultEncoderBindingElement.MaxReadPoolSize = 128;
			ClientMessageUtility.defaultEncoderBindingElement.MaxWritePoolSize = 128;
			ClientMessageUtility.defaultEncoderFactory = ClientMessageUtility.defaultEncoderBindingElement.CreateMessageEncoderFactory();
		}
コード例 #37
0
ファイル: TestHelper.cs プロジェクト: v-yarli/CoreWCF
        private static Message DeserialzieMessageFromStream(MemoryStream ms, MessageVersion messageVersion)
        {
            var bmebe = new BinaryMessageEncodingBindingElement();

            bmebe.MessageVersion = messageVersion;
            bmebe.ReaderQuotas   = XmlDictionaryReaderQuotas.Max;
            var bmef = bmebe.CreateMessageEncoderFactory();

            return(bmef.Encoder.ReadMessage(ms, int.MaxValue));
        }
コード例 #38
0
        /// <summary>
        /// Initializes the binding.
        /// </summary>
        /// <param name="namespaceUris">The namespace uris.</param>
        /// <param name="factory">The factory.</param>
        /// <param name="configuration">The configuration.</param>
        /// <param name="description">The description.</param>
        public UaSoapXmlOverTcpBinding(
            NamespaceTable        namespaceUris,
            EncodeableFactory     factory,
            EndpointConfiguration configuration,
            EndpointDescription   description)
        :
            base(namespaceUris, factory, configuration)
        {                   
            if (description != null && description.SecurityMode != MessageSecurityMode.None)
            {
                SymmetricSecurityBindingElement bootstrap = (SymmetricSecurityBindingElement)SecurityBindingElement.CreateMutualCertificateBindingElement();
                
                bootstrap.MessageProtectionOrder       = MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature;
                bootstrap.DefaultAlgorithmSuite        = SecurityPolicies.ToSecurityAlgorithmSuite(description.SecurityPolicyUri);
                bootstrap.IncludeTimestamp             = true;
                bootstrap.MessageSecurityVersion       = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;
                // bootstrap.MessageSecurityVersion       = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
                bootstrap.RequireSignatureConfirmation = false;
                bootstrap.SecurityHeaderLayout         = SecurityHeaderLayout.Strict;
                
                m_security = (SymmetricSecurityBindingElement)SecurityBindingElement.CreateSecureConversationBindingElement(bootstrap, true);
                
                m_security.MessageProtectionOrder       = MessageProtectionOrder.EncryptBeforeSign;
                m_security.DefaultAlgorithmSuite        = SecurityPolicies.ToSecurityAlgorithmSuite(description.SecurityPolicyUri);
                m_security.IncludeTimestamp             = true;
                m_security.MessageSecurityVersion       = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;
                // m_security.MessageSecurityVersion       = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
                m_security.RequireSignatureConfirmation = false;
                m_security.SecurityHeaderLayout         = SecurityHeaderLayout.Strict;

                m_security.SetKeyDerivation(true);
            }
            
            m_encoding = new BinaryMessageEncodingBindingElement();
           
            // WCF does not distinguish between arrays and byte string.
            int maxArrayLength = configuration.MaxArrayLength;

            if (configuration.MaxArrayLength < configuration.MaxByteStringLength)
            {
                maxArrayLength = configuration.MaxByteStringLength;
            }

            m_encoding.ReaderQuotas.MaxArrayLength         = maxArrayLength;
            m_encoding.ReaderQuotas.MaxStringContentLength = configuration.MaxStringLength;
            m_encoding.ReaderQuotas.MaxBytesPerRead        = Int32.MaxValue;
            m_encoding.ReaderQuotas.MaxDepth               = Int32.MaxValue;
            m_encoding.ReaderQuotas.MaxNameTableCharCount  = Int32.MaxValue;

            m_transport = new System.ServiceModel.Channels.TcpTransportBindingElement();

            m_transport.ManualAddressing       = false;
            m_transport.MaxBufferPoolSize      = Int32.MaxValue;
            m_transport.MaxReceivedMessageSize = configuration.MaxMessageSize;
        }
    public static void Default_Ctor_Initializes_Properties()
    {
        BinaryMessageEncodingBindingElement bindingElement = new BinaryMessageEncodingBindingElement();

        Assert.Equal<CompressionFormat>(CompressionFormat.None, bindingElement.CompressionFormat);
        Assert.Equal<int>(2048, bindingElement.MaxSessionSize);
        Assert.Equal<MessageVersion>(MessageVersion.Default, bindingElement.MessageVersion);

        Assert.True(TestHelpers.XmlDictionaryReaderQuotasAreEqual(bindingElement.ReaderQuotas, new XmlDictionaryReaderQuotas()),
            "BinaryEncodingBindingElement_DefaultCtor: Assert property 'XmlDictionaryReaderQuotas' == default value failed.");
    }
コード例 #40
0
 private void CreateAndWriteMessage(byte[] bytes) {
   using (var stream = new MemoryStream(bytes, false)) {
     var mebe = new BinaryMessageEncodingBindingElement();
     mebe.MessageVersion = MessageVersion.Soap12;
     mebe.ReaderQuotas.MaxArrayLength = XmlDictionaryReaderQuotas.Max.MaxArrayLength;
     mebe.ReaderQuotas.MaxDepth = XmlDictionaryReaderQuotas.Max.MaxDepth;
     mebe.ReaderQuotas.MaxStringContentLength = XmlDictionaryReaderQuotas.Max.MaxStringContentLength;
     var factory = mebe.CreateMessageEncoderFactory();
     var msg = factory.Encoder.ReadMessage(stream, 1024 * 16);     // I have no idea what header size to give it ...
     WriteMessage(msg);
   }
 }
 private void InitializeFrom(NamedPipeTransportBindingElement namedPipe, BinaryMessageEncodingBindingElement encoding, TransactionFlowBindingElement context)
 {
     this.Initialize();
     this.HostNameComparisonMode = namedPipe.HostNameComparisonMode;
     this.MaxBufferPoolSize = namedPipe.MaxBufferPoolSize;
     this.MaxBufferSize = namedPipe.MaxBufferSize;
     this.MaxConnections = namedPipe.MaxPendingConnections;
     this.MaxReceivedMessageSize = namedPipe.MaxReceivedMessageSize;
     this.TransferMode = namedPipe.TransferMode;
     this.ReaderQuotas = encoding.ReaderQuotas;
     this.TransactionFlow = context.Transactions;
     this.TransactionProtocol = context.TransactionProtocol;
 }
コード例 #42
0
ファイル: NetHttpBinding.cs プロジェクト: spzenk/sfdocsamples
        public NetHttpBinding(NetHttpSecurityMode securityMode)
        {
            if (securityMode != NetHttpSecurityMode.Transport &&
                securityMode != NetHttpSecurityMode.TransportCredentialOnly &&
                securityMode != NetHttpSecurityMode.None)
            {
                throw new ArgumentOutOfRangeException("securityMode");
            }

            this.securityMode = securityMode;   
            this.httpTransport = new HttpTransportBindingElement();
            this.httpsTransport = new HttpsTransportBindingElement();
            this.binaryEncoding = new BinaryMessageEncodingBindingElement();
        }
コード例 #43
0
        static void Main(string[] args)
        {
            // TODO: extract into a properties file
            string serviceName = "CAService";
            string baseAddress = "net.tcp://localhost:3333/";
            ServiceHost caHost = new ServiceHost(typeof(Simulation), new Uri(baseAddress + serviceName));

            try {
                // Configure the TCP binding
                NetTcpBinding tcpBinding = new NetTcpBinding();
                tcpBinding.MaxReceivedMessageSize = Int32.MaxValue;
                tcpBinding.MaxBufferPoolSize = Int32.MaxValue;
                tcpBinding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;

                // Configure a binary message encoding binding element
                BinaryMessageEncodingBindingElement binaryBinding = new BinaryMessageEncodingBindingElement();
                binaryBinding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
                binaryBinding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue;
                binaryBinding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;

                // Configure a MEX TCP binding to send metadata
                CustomBinding mexBinding = new CustomBinding(MetadataExchangeBindings.CreateMexTcpBinding());
                mexBinding.Elements.Insert(0, binaryBinding);
                mexBinding.Elements.Find<TcpTransportBindingElement>().MaxReceivedMessageSize = Int32.MaxValue;

                // Configure the host
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                caHost.Description.Behaviors.Add(smb);
                caHost.AddServiceEndpoint(typeof(IMetadataExchange), mexBinding, baseAddress + serviceName + "/mex");
                caHost.AddServiceEndpoint(typeof(ICAService), tcpBinding, baseAddress + serviceName);
                ServiceDebugBehavior debug = caHost.Description.Behaviors.Find<ServiceDebugBehavior>();
                if (debug == null) caHost.Description.Behaviors.Add(new ServiceDebugBehavior() { IncludeExceptionDetailInFaults = true });
                else if (!debug.IncludeExceptionDetailInFaults) debug.IncludeExceptionDetailInFaults = true;

                // Open the host and run until Enter is pressed
                caHost.Open();
                Console.WriteLine("CA Simulator Server is running. Press Enter to exit.");
                Console.ReadLine();
                caHost.Close();
            }
            catch (CommunicationException e) {
                Console.WriteLine(e.Message);
                caHost.Abort();
            }
            catch (InvalidOperationException e) {
                Console.WriteLine(e.Message);
                caHost.Abort();
            }
        }
コード例 #44
0
ファイル: ChatServer.cs プロジェクト: jezell/iserviceoriented
        public ChatServer()
        {
            BinaryMessageEncodingBindingElement element = new BinaryMessageEncodingBindingElement();
            MessageEncoder encoder = element.CreateMessageEncoderFactory().Encoder;

            MessageDeliveryFormatter formatter = new MessageDeliveryFormatter(new ConverterMessageDeliveryReaderFactory(encoder, typeof(IChatService)), new ConverterMessageDeliveryWriterFactory(encoder, typeof(IChatService)));
            _serviceBus = new ServiceBusRuntime(new DirectDeliveryCore() , new WcfManagementService());
            _serviceBus.AddListener(new ListenerEndpoint(Guid.NewGuid(), "Chat Service", "ChatServer", "http://localhost/chatServer", typeof(IChatService), new WcfServiceHostListener()));
            _serviceBus.Subscribe(new SubscriptionEndpoint(Guid.NewGuid(), "No subscribers", "ChatClient", "", typeof(IChatService), new MethodDispatcher(new UnhandledReplyHandler(_serviceBus)), new UnhandledMessageFilter(typeof(SendMessageRequest)), true));
            _serviceBus.UnhandledException+= (o, ex) =>
                {
                    Console.WriteLine("Unhandled Exception: "+ex.ExceptionObject);
                };
        }
コード例 #45
0
ファイル: GeocachingLive.cs プロジェクト: gahadzikwa/GAPP
        public GeocachingLiveV6(bool testSite)
        {

            BinaryMessageEncodingBindingElement binaryMessageEncoding = new BinaryMessageEncodingBindingElement()
            {
                ReaderQuotas = new XmlDictionaryReaderQuotas()
                {
                    MaxStringContentLength = int.MaxValue,
                    MaxBytesPerRead = int.MaxValue,
                    MaxDepth = int.MaxValue,
                    MaxArrayLength = int.MaxValue
                }
            };

            HttpTransportBindingElement httpTransport = new HttpsTransportBindingElement()
            {
                MaxBufferSize = int.MaxValue,
                MaxReceivedMessageSize = int.MaxValue,
                AllowCookies = false,
                //UseDefaultWebProxy = true,
            };

            // add the binding elements into a Custom Binding
            CustomBinding binding = new CustomBinding(binaryMessageEncoding, httpTransport);

            EndpointAddress endPoint;
            if (testSite)
            {
                endPoint = new EndpointAddress("https://staging.api.groundspeak.com/Live/V6Beta/geocaching.svc/Silverlightsoap");
                _token = Core.Settings.Default.LiveAPITokenStaging;
            }
            else
            {
                endPoint = new EndpointAddress("https://api.groundspeak.com/LiveV6/Geocaching.svc/Silverlightsoap");
                _token = Core.Settings.Default.LiveAPIToken;
            }

            try
            {
                _client = new LiveV6.LiveClient(binding, endPoint);
            }
            catch(Exception e)
            {
                Core.ApplicationData.Instance.Logger.AddLog(this, e);
            }

        }
コード例 #46
0
ファイル: GeocachingLive.cs プロジェクト: RH-Code/GAPP
        public GeocachingLiveV6(Framework.Interfaces.ICore core, bool testSite)
        {
            _core = core;

            BinaryMessageEncodingBindingElement binaryMessageEncoding = new BinaryMessageEncodingBindingElement()
            {
                ReaderQuotas = new XmlDictionaryReaderQuotas()
                {
                    MaxStringContentLength = int.MaxValue,
                    MaxBytesPerRead = int.MaxValue,
                    MaxDepth = int.MaxValue,
                    MaxArrayLength = int.MaxValue
                }
            };

            HttpTransportBindingElement httpTransport = new HttpsTransportBindingElement() 
            { 
                MaxBufferSize = int.MaxValue, 
                MaxReceivedMessageSize = int.MaxValue,
                AllowCookies = false, 
            };

            // add the binding elements into a Custom Binding
            CustomBinding binding = new CustomBinding(binaryMessageEncoding, httpTransport);            

            EndpointAddress endPoint;
            if (testSite)
            {
                endPoint = new EndpointAddress("https://staging.api.groundspeak.com/Live/V6Beta/geocaching.svc/Silverlightsoap");
                _token = core.GeocachingComAccount.APITokenStaging;
            }
            else
            {
                endPoint = new EndpointAddress("https://api.groundspeak.com/LiveV6/Geocaching.svc/Silverlightsoap");
                _token = core.GeocachingComAccount.APIToken;
            }

            try
            {
                _client = new LiveV6.LiveClient(binding, endPoint);
            }
            catch
            {
            }

        }
コード例 #47
0
        public FileDownloadService()
        {
            TcpTransportBindingElement transport = new TcpTransportBindingElement();
            transport.MaxReceivedMessageSize = long.MaxValue;
            transport.MaxBufferSize = int.MaxValue;
            transport.MaxBufferPoolSize = long.MaxValue;
            transport.TransferMode = TransferMode.Streamed;

            BinaryMessageEncodingBindingElement encoder = new BinaryMessageEncodingBindingElement();
            CustomBinding binding = new CustomBinding(encoder, transport);
            binding.ReceiveTimeout = TimeSpan.MaxValue;
            binding.SendTimeout = TimeSpan.MaxValue;
            binding.CloseTimeout = TimeSpan.MaxValue;

            serviceHost = new ServiceHost(this);
            serviceHost.AddServiceEndpoint(typeof(IFileDownloadService), binding, "net.tcp://localhost:8020");
            serviceHost.Open();
        }
コード例 #48
0
ファイル: CustomHttpBinding.cs プロジェクト: dizzydezz/jmm
		private void InitializeValue()
		{
			this.transport = new HttpTransportBindingElement();
			this.transport.MaxBufferSize = int.MaxValue;
			this.transport.MaxReceivedMessageSize = int.MaxValue;
			this.transport.TransferMode = System.ServiceModel.TransferMode.Streamed;
			
			this.ReceiveTimeout = TimeSpan.MaxValue;
			this.SendTimeout = TimeSpan.MaxValue;
			this.CloseTimeout = TimeSpan.MaxValue;
			this.Name = "FileStreaming";

			//this.Security.Mode = BasicHttpSecurityMode.None;

			this.encoding = new BinaryMessageEncodingBindingElement();
			this.encoding.ReaderQuotas.MaxArrayLength = int.MaxValue;
			this.encoding.ReaderQuotas.MaxBytesPerRead = int.MaxValue;
		}
コード例 #49
0
ファイル: ZMQBinding.cs プロジェクト: ronybot/MessageBus
        public override BindingElementCollection CreateBindingElements()
        {
            BinaryMessageEncodingBindingElement encoding = new BinaryMessageEncodingBindingElement();

            ZMQTransportBindingElement transport = new ZMQTransportBindingElement(Scheme, SocketMode);

            if (ReaderQuotas != null)
            {
                ReaderQuotas.CopyTo(encoding.ReaderQuotas);
            }

            BindingElementCollection collection = new BindingElementCollection
                {
                    encoding,
                    transport
                };

            return collection;
        }
        /// <summary>
        /// Initializes the binding.
        /// </summary>
        /// <param name="namespaceUris">The namespace uris.</param>
        /// <param name="factory">The factory.</param>
        /// <param name="configuration">The configuration.</param>
        /// <param name="description">The description.</param>
        public UaSoapXmlOverTcpBinding(
            NamespaceTable        namespaceUris,
            EncodeableFactory     factory,
            EndpointConfiguration configuration,
            EndpointDescription   description)
        :
            base(namespaceUris, factory, configuration)
        {                   
            if (description != null && description.SecurityMode != MessageSecurityMode.None)
            {
                TransportSecurityBindingElement bootstrap = SecurityBindingElement.CreateUserNameOverTransportBindingElement();
                bootstrap.IncludeTimestamp             = true;
                bootstrap.MessageSecurityVersion       = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
                bootstrap.SecurityHeaderLayout         = SecurityHeaderLayout.Strict;
                
                m_security = SecurityBindingElement.CreateSecureConversationBindingElement(bootstrap);
                m_security.IncludeTimestamp             = true;
                m_security.MessageSecurityVersion       = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
                m_security.SecurityHeaderLayout         = SecurityHeaderLayout.Strict;
            }
            
            m_encoding = new BinaryMessageEncodingBindingElement();
           
            // WCF does not distinguish between arrays and byte string.
            int maxArrayLength = configuration.MaxArrayLength;

            if (configuration.MaxArrayLength < configuration.MaxByteStringLength)
            {
                maxArrayLength = configuration.MaxByteStringLength;
            }

            m_encoding.ReaderQuotas.MaxArrayLength         = maxArrayLength;
            m_encoding.ReaderQuotas.MaxStringContentLength = configuration.MaxStringLength;
            m_encoding.ReaderQuotas.MaxBytesPerRead        = Int32.MaxValue;
            m_encoding.ReaderQuotas.MaxDepth               = Int32.MaxValue;
            m_encoding.ReaderQuotas.MaxNameTableCharCount  = Int32.MaxValue;

            m_transport = new TcpTransportBindingElement();

            m_transport.ManualAddressing       = false;
            m_transport.MaxReceivedMessageSize = configuration.MaxMessageSize;
        }
コード例 #51
0
ファイル: samplesvc15.cs プロジェクト: alesliehughes/olive
	public static void Main ()
	{
Console.WriteLine ("WARNING!! This test is not configured enought to work fine on .NET either.");

		SymmetricSecurityBindingElement sbe =
			new SymmetricSecurityBindingElement ();
		sbe.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
		sbe.RequireSignatureConfirmation = true;
		//sbe.IncludeTimestamp = false;

		sbe.ProtectionTokenParameters =
			new X509SecurityTokenParameters (X509KeyIdentifierClauseType.Thumbprint, SecurityTokenInclusionMode.Never);
		X509SecurityTokenParameters p =
			new X509SecurityTokenParameters (X509KeyIdentifierClauseType.Thumbprint, SecurityTokenInclusionMode.AlwaysToRecipient);
		p.RequireDerivedKeys = false;
		sbe.EndpointSupportingTokenParameters.Endorsing.Add (p);
		//sbe.SetKeyDerivation (false);
		//sbe.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
		ServiceHost host = new ServiceHost (typeof (Foo));
		var mbe = new BinaryMessageEncodingBindingElement ();
		var tbe = new TcpTransportBindingElement ();
		CustomBinding binding = new CustomBinding (sbe, mbe, tbe);
		binding.ReceiveTimeout = TimeSpan.FromSeconds (5);
		host.AddServiceEndpoint ("IFoo",
			binding, new Uri ("http://localhost:8080"));
		ServiceCredentials cred = new ServiceCredentials ();
		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;
		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 ();
	}
コード例 #52
0
        //Called by the WCF to apply the configuration settings (the property above) to the binding element
        public override void ApplyConfiguration(BindingElement bindingElement)
        {
            GZipMessageEncodingBindingElement binding = (GZipMessageEncodingBindingElement)bindingElement;
            PropertyInformationCollection propertyInfo = this.ElementInformation.Properties;
            if (propertyInfo["innerMessageEncoding"].ValueOrigin != PropertyValueOrigin.Default)
            {
                switch (this.InnerMessageEncoding)
                {
                    case "textMessageEncoding":
                        var innerMessageEncodingBindingElement = new TextMessageEncodingBindingElement();
                        ReaderQuotaHelper.SetReaderQuotas(innerMessageEncodingBindingElement.ReaderQuotas);
                        binding.InnerMessageEncodingBindingElement = innerMessageEncodingBindingElement;
                        break;

                    case "binaryMessageEncoding":
                        var binaryMessageEncodingBindingElement = new BinaryMessageEncodingBindingElement();
                        ReaderQuotaHelper.SetReaderQuotas(binaryMessageEncodingBindingElement.ReaderQuotas);
                        binding.InnerMessageEncodingBindingElement = binaryMessageEncodingBindingElement;
                        break;
                }
            }
        }
コード例 #53
0
ファイル: Program.cs プロジェクト: GusLab/WCFSamples
        static void TestWithUntypedMessage()
        {
            string baseAddress = SizedTcpDuplexTransportBindingElement.SizedTcpScheme + "://localhost:8000";
            ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
            MessageEncodingBindingElement encodingBE = new BinaryMessageEncodingBindingElement();
            Binding binding = new CustomBinding(encodingBE, new SizedTcpDuplexTransportBindingElement());
            host.AddServiceEndpoint(typeof(IUntypedTest), binding, "");
            host.Open();

            Console.WriteLine("Host opened");

            Socket socket = GetConnectedSocket(8000);

            Message input = Message.CreateMessage(MessageVersion.Soap12WSAddressing10, "myAction", "Hello world");
            input.Headers.To = new Uri(baseAddress);
            input.Headers.ReplyTo = new EndpointAddress("http://www.w3.org/2005/08/addressing/anonymous");

            MessageEncoder encoder = encodingBE.CreateMessageEncoderFactory().Encoder;
            BufferManager bufferManager = BufferManager.CreateBufferManager(int.MaxValue, int.MaxValue);
            ArraySegment<byte> encoded = encoder.WriteMessage(input, int.MaxValue, bufferManager, 4);
            Formatting.SizeToBytes(encoded.Count, encoded.Array, 0);

            Console.WriteLine("Sending those bytes:");
            Debugging.PrintBytes(encoded.Array, encoded.Count + encoded.Offset);
            socket.Send(encoded.Array, 0, encoded.Offset + encoded.Count, SocketFlags.None);
            byte[] recvBuffer = new byte[10000];
            int bytesRecvd = socket.Receive(recvBuffer);
            Console.WriteLine("Received {0} bytes", bytesRecvd);
            Debugging.PrintBytes(recvBuffer, bytesRecvd);

            socket.Close();

            Console.WriteLine("Press ENTER to close");
            Console.ReadLine();
            host.Close();
        }
 public static void MessageVersion_Property_Set_Null_Value_Throws()
 {
     BinaryMessageEncodingBindingElement bindingElement = new BinaryMessageEncodingBindingElement();
     Assert.Throws<ArgumentNullException>(() => bindingElement.MessageVersion = null);
 }
コード例 #55
0
        private Binding CreateBinaryBinding(bool isSecure)
        {
            var binaryElement = new BinaryMessageEncodingBindingElement();
            #if WPF
            binaryElement.ReaderQuotas.MaxStringContentLength = 2147483647;
            #endif

            BindingElementCollection elements = new BindingElementCollection();
            elements.Add(binaryElement);

            if (isSecure)
                elements.Add(new HttpsTransportBindingElement() { MaxBufferSize = 2147483647, MaxReceivedMessageSize = 2147483647 });
            else
                elements.Add(new HttpTransportBindingElement() { MaxBufferSize = 2147483647, MaxReceivedMessageSize = 2147483647 });

            return new CustomBinding(elements);
        }
コード例 #56
0
        /// <summary>
        /// Create a BrokeredMessage for a WCF receiver.
        /// </summary>
        /// <param name="messageTemplate">The message template.</param>
        /// <param name="taskId">The task Id.</param>
        /// <param name="updateMessageId">Indicates whether to use a unique id for each message.</param>
        /// <param name="oneSessionPerTask">Indicates whether to use a different session for each sender task.</param>
        /// <param name="to">The uri of the target topic or queue.</param>
        /// <returns>The cloned BrokeredMessage object.</returns>
        public BrokeredMessage CreateMessageForWcfReceiver(BrokeredMessage messageTemplate,
                                                           int taskId,
                                                           bool updateMessageId,
                                                           bool oneSessionPerTask,
                                                           Uri to)
        {
            string messageText;
            using (var reader = new StreamReader(messageTemplate.Clone().GetBody<Stream>()))
            {
                messageText = reader.ReadToEnd();
            }
            var isXml = XmlHelper.IsXml(messageText);
            var isJson = !isXml && JsonSerializerHelper.IsJson(messageText);
            Message message = null;
            MessageEncodingBindingElement element;
            var outputStream = new MemoryStream();
            if (scheme == DefaultScheme)
            {
                element = new BinaryMessageEncodingBindingElement();
            }
            else
            {
                element = new TextMessageEncodingBindingElement();
            }
            var encoderFactory = element.CreateMessageEncoderFactory();
            var encoder = encoderFactory.Encoder;
            if (isXml)
            {
                using (var stringReader = new StringReader(messageText))
                {
                    using (var xmlReader = XmlReader.Create(stringReader))
                    {
                        using (var dictionaryReader = XmlDictionaryReader.CreateDictionaryReader(xmlReader))
                        {
                            message = Message.CreateMessage(MessageVersion.Default, "*", dictionaryReader);
                            encoder.WriteMessage(message, outputStream);
                            outputStream.Seek(0, SeekOrigin.Begin);
                        }
                    }
                }
            }
            else
            {
                if (isJson)
                {
                    message = Message.CreateMessage(MessageVersion.Default, "*", new StringBodyWriter(messageText));
                    encoder.WriteMessage(message, outputStream);
                    outputStream.Seek(0, SeekOrigin.Begin);
                }
            }

            if (message != null && outputStream.Length > 0)
            {
                message.Headers.To = to;

                var outboundMessage = new BrokeredMessage(outputStream, true)
                {
                    ContentType = encoder.ContentType
                };
                if (!string.IsNullOrWhiteSpace(messageTemplate.Label))
                {
                    outboundMessage.Label = messageTemplate.Label;
                }
                if (!string.IsNullOrWhiteSpace(messageTemplate.ContentType))
                {
                    outboundMessage.ContentType = messageTemplate.ContentType;
                }
                outboundMessage.MessageId = updateMessageId ? Guid.NewGuid().ToString() : messageTemplate.MessageId;
                outboundMessage.SessionId = oneSessionPerTask ? taskId.ToString(CultureInfo.InvariantCulture) : messageTemplate.SessionId;
                if (!string.IsNullOrWhiteSpace(messageTemplate.CorrelationId))
                {
                    outboundMessage.CorrelationId = messageTemplate.CorrelationId;
                }
                if (!string.IsNullOrWhiteSpace(messageTemplate.To))
                {
                    outboundMessage.To = messageTemplate.To;
                }
                if (!string.IsNullOrWhiteSpace(messageTemplate.ReplyTo))
                {
                    outboundMessage.ReplyTo = messageTemplate.ReplyTo;
                }
                if (!string.IsNullOrWhiteSpace(messageTemplate.ReplyToSessionId))
                {
                    outboundMessage.ReplyToSessionId = messageTemplate.ReplyToSessionId;
                }
                outboundMessage.TimeToLive = messageTemplate.TimeToLive;
                outboundMessage.ScheduledEnqueueTimeUtc = messageTemplate.ScheduledEnqueueTimeUtc;
                outboundMessage.ForcePersistence = messageTemplate.ForcePersistence;
                foreach (var property in messageTemplate.Properties)
                {
                    outboundMessage.Properties.Add(property.Key, property.Value);
                }
                return outboundMessage;
            }
            throw new ApplicationException(MessageIsNotXmlOrJson);
        }
コード例 #57
0
        /// <summary>
        /// This method is used to receive message from a queue or a subscription.
        /// </summary>
        /// <param name="messageReceiver">The message receiver used to receive messages.</param>
        /// <param name="taskId">The receiver task id.</param>
        /// <param name="timeout">The receive receiveTimeout.</param>
        /// <param name="filter">The filter expression is used to determine messages to move the dead-letter queue or to defer.</param>
        /// <param name="moveToDeadLetterQueue">Indicates whether to move messages to the dead-letter queue.</param>
        /// <param name="completeReceive">Indicates whether to complete a receive operation when ReceiveMode is equal to PeekLock.</param>
        /// <param name="defer">Indicates whether to defer messages.</param>
        /// <param name="logging">Indicates whether logging of message content and properties is enabled.</param>
        /// <param name="verbose">Indicates whether verbose logging is enabled.</param>
        /// <param name="statistics">Indicates whether to enable receiver statistics.</param>
        /// <param name="receiveBatch">Indicates whether to use ReceiveBatch.</param>
        /// <param name="batchSize">Indicates the batch size.</param>
        /// <param name="receiverThinkTime">Indicates whether to use think time.</param>
        /// <param name="thinkTime">Indicates the value of the think time in milliseconds.</param>
        /// <param name="messageInspector">A BrokeredMessage inspector object.</param>
        /// <param name="updateStatistics">When statistics = true, this delegate is invoked to update statistics.</param>
        /// <param name="cancellationTokenSource">The cancellation token.</param>
        /// <param name="traceMessage">A trace message.</param>
        /// <returns>True if the method completed without exceptions, false otherwise.</returns>
        public bool ReceiveMessages(MessageReceiver messageReceiver,
                                    int taskId,
                                    int timeout,
                                    Filter filter,
                                    bool moveToDeadLetterQueue,
                                    bool completeReceive,
                                    bool defer,
                                    bool logging,
                                    bool verbose,
                                    bool statistics,
                                    bool receiveBatch,
                                    int batchSize,
                                    bool receiverThinkTime,
                                    int thinkTime,
                                    IBrokeredMessageInspector messageInspector,
                                    UpdateStatisticsDelegate updateStatistics,
                                    CancellationTokenSource cancellationTokenSource,
                                    out string traceMessage)
        {
            if (messageReceiver == null)
            {
                throw new ArgumentNullException(MessageReceiverCannotBeNull);
            }

            if (cancellationTokenSource == null)
            {
                throw new ArgumentNullException(CancellationTokenSourceCannotBeNull);
            }

            BrokeredMessage inboundMessage = null;
            StringBuilder builder;
            var isCompleted = false;
            var ok = true;
            var receivedFromDeadLetterQueue = messageReceiver.Path.EndsWith(DeadLetterQueue);
            var readingDeferredMessages = false;
            long messagesReceived = 0;
            long totalReceiveElapsedTime = 0;
            long totalCompleteElapsedTime = 0;
            long minimumReceiveTime = long.MaxValue;
            long maximumReceiveTime = 0;
            long minimumCompleteTime = long.MaxValue;
            long maximumCompleteTime = 0;
            long fetchedMessages = 0;
            long prefetchElapsedTime = 0;
            string exceptionMessage = null;
            var messageDeferProvider = Activator.CreateInstance(messageDeferProviderType) as IMessageDeferProvider;

            try
            {
                MessageEncodingBindingElement element;
                if (scheme == DefaultScheme)
                {
                    element = new BinaryMessageEncodingBindingElement();
                }
                else
                {
                    element = new TextMessageEncodingBindingElement();
                }
                var encoderFactory = element.CreateMessageEncoderFactory();
                var encoder = encoderFactory.Encoder;
                if (receiveBatch && batchSize > 0)
                {
                    while (!isCompleted &&
                           !cancellationTokenSource.Token.IsCancellationRequested)
                    {
                        IList<BrokeredMessage> messageList = null;
                        try
                        {
                            var stopwatch = new Stopwatch();
                            stopwatch.Start();
                            var messageEnumerable = messageReceiver.ReceiveBatch(batchSize, TimeSpan.FromSeconds(timeout));
                            stopwatch.Stop();
                            messageList = messageEnumerable as IList<BrokeredMessage> ?? messageEnumerable.ToList();
                            if (messageInspector != null)
                            {
                                messageList = messageList.Select(b => messageInspector.AfterReceiveMessage(b, writeToLog)).ToList();
                            }
                            isCompleted = messageEnumerable == null || !messageList.Any();
                            if (isCompleted)
                            {
                                continue;
                            }
                            if (messageReceiver.Mode == ReceiveMode.PeekLock)
                            {
                                if (completeReceive)
                                {
                                    stopwatch = new Stopwatch();
                                    stopwatch.Start();
                                    messageReceiver.CompleteBatch(messageList.Select(b => b.LockToken));
                                    stopwatch.Stop();
                                    if (stopwatch.ElapsedMilliseconds > maximumCompleteTime)
                                    {
                                        maximumCompleteTime = stopwatch.ElapsedMilliseconds;
                                    }
                                    if (stopwatch.ElapsedMilliseconds < minimumCompleteTime)
                                    {
                                        minimumCompleteTime = stopwatch.ElapsedMilliseconds;
                                    }
                                    totalCompleteElapsedTime += stopwatch.ElapsedMilliseconds;
                                    messagesReceived += messageList.Count;
                                }
                            }
                            else
                            {
                                messagesReceived += messageList.Count;
                            }
                            if (stopwatch.ElapsedMilliseconds > maximumReceiveTime)
                            {
                                maximumReceiveTime = stopwatch.ElapsedMilliseconds;
                            }
                            if (stopwatch.ElapsedMilliseconds < minimumReceiveTime)
                            {
                                minimumReceiveTime = stopwatch.ElapsedMilliseconds;
                            }
                            totalReceiveElapsedTime += stopwatch.ElapsedMilliseconds;
                            if (statistics)
                            {
                                if (messageReceiver.PrefetchCount > 0)
                                {
                                    if (stopwatch.ElapsedMilliseconds == 0)
                                    {
                                        fetchedMessages += messageList.Count;
                                    }
                                    else
                                    {
                                        if (fetchedMessages > 0)
                                        {
                                            updateStatistics(fetchedMessages,
                                                             prefetchElapsedTime,
                                                             DirectionType.Receive);
                                            fetchedMessages = messageList.Count;
                                        }
                                        else
                                        {
                                            fetchedMessages += messageList.Count;
                                        }
                                        prefetchElapsedTime = stopwatch.ElapsedMilliseconds;
                                    }
                                }
                                else
                                {
                                    updateStatistics(messageList.Count, stopwatch.ElapsedMilliseconds, DirectionType.Receive);
                                }
                            }
                            builder = new StringBuilder();

                            if (logging)
                            {
                                // ReSharper disable ForCanBeConvertedToForeach
                                for (var i = 0; i < messageList.Count; i++)
                                // ReSharper restore ForCanBeConvertedToForeach
                                {
                                    if (messageReceiver.Mode == ReceiveMode.PeekLock &&
                                        !completeReceive)
                                    {
                                        builder.AppendLine(string.Format(MessagePeekedButNotConsumed,
                                                                         taskId,
                                                                         string.IsNullOrWhiteSpace(messageList[i].MessageId)
                                                                             ? NullValue
                                                                             : messageList[i].MessageId,
                                                                         string.IsNullOrWhiteSpace(messageList[i].SessionId)
                                                                             ? NullValue
                                                                             : messageList[i].SessionId,
                                                                         string.IsNullOrWhiteSpace(messageList[i].Label)
                                                                             ? NullValue
                                                                             : messageList[i].Label,
                                                                         messageList[i].Size));
                                    }
                                    else
                                    {
                                        builder.AppendLine(string.Format(MessageSuccessfullyReceived,
                                                                         taskId,
                                                                         string.IsNullOrWhiteSpace(messageList[i].MessageId)
                                                                             ? NullValue
                                                                             : messageList[i].MessageId,
                                                                         string.IsNullOrWhiteSpace(messageList[i].SessionId)
                                                                             ? NullValue
                                                                             : messageList[i].SessionId,
                                                                         string.IsNullOrWhiteSpace(messageList[i].Label)
                                                                             ? NullValue
                                                                             : messageList[i].Label,
                                                                         messageList[i].Size,
                                                                         messageList[i].DeliveryCount));
                                    }
                                    if (verbose)
                                    {
                                        GetMessageAndProperties(builder, messageList[i], encoder);
                                    }
                                }
                                traceMessage = builder.ToString();
                                WriteToLog(traceMessage.Substring(0, traceMessage.Length - 1));
                            }
                        }
                        catch (Exception ex)
                        {
                            if (messageList != null &&
                                messageList.Count > 0 &&
                                messageReceiver.Mode == ReceiveMode.PeekLock)
                            {
                                try
                                {
                                    var stopwatch = new Stopwatch();
                                    stopwatch.Start();
                                    messageReceiver.CompleteBatch(messageList.Select(b => b.LockToken));
                                    stopwatch.Stop();
                                    if (stopwatch.ElapsedMilliseconds > maximumCompleteTime)
                                    {
                                        maximumCompleteTime = stopwatch.ElapsedMilliseconds;
                                    }
                                    if (stopwatch.ElapsedMilliseconds < minimumCompleteTime)
                                    {
                                        minimumCompleteTime = stopwatch.ElapsedMilliseconds;
                                    }
                                    totalCompleteElapsedTime += stopwatch.ElapsedMilliseconds;
                                }
                                // ReSharper disable EmptyGeneralCatchClause
                                catch (Exception)
                                // ReSharper restore EmptyGeneralCatchClause
                                {
                                }
                            }
                            exceptionMessage = string.Format(ExceptionOccurred, ex.Message);
                            isCompleted = true;
                            ok = false;
                        }
                        finally
                        {
                            if (messageList != null &&
                                messageList.Count > 0)
                            {
                                foreach (var message in messageList)
                                {
                                    message.Dispose();
                                }
                            }
                        }
                        if (receiverThinkTime)
                        {
                            WriteToLog(string.Format(SleepingFor, thinkTime));
                            Thread.Sleep(thinkTime);
                        }
                    }
                }
                else
                {
                    while (!isCompleted &&
                           !cancellationTokenSource.Token.IsCancellationRequested)
                    {
                        try
                        {
                            var stopwatch = new Stopwatch();
                            var movedToDeadLetterQueue = false;
                            var deferredMessage = false;
                            var readDeferredMessage = false;

                            if (!readingDeferredMessages)
                            {
                                stopwatch.Start();
                                inboundMessage = messageReceiver.Receive(TimeSpan.FromSeconds(timeout));
                                stopwatch.Stop();
                                if (inboundMessage != null && messageInspector != null)
                                {
                                    inboundMessage = messageInspector.AfterReceiveMessage(inboundMessage);
                                }
                                isCompleted = inboundMessage == null &&
                                              messageDeferProvider.Count == 0;
                            }
                            else
                            {
                                isCompleted = messageDeferProvider.Count == 0;
                                if (!isCompleted)
                                {
                                    long sequenceNumber;
                                    if (messageDeferProvider.Dequeue(out sequenceNumber))
                                    {
                                        stopwatch.Start();
                                        inboundMessage = messageReceiver.Receive(sequenceNumber);
                                        stopwatch.Stop();
                                        if (inboundMessage != null && messageInspector != null)
                                        {
                                            inboundMessage = messageInspector.AfterReceiveMessage(inboundMessage);
                                        }
                                        readDeferredMessage = true;
                                    }
                                }
                            }
                            if (!readingDeferredMessages)
                            {
                                readingDeferredMessages = inboundMessage == null && messageDeferProvider.Count > 0;
                            }

                            if (isCompleted ||
                                inboundMessage == null)
                            {
                                continue;
                            }
                            if (stopwatch.ElapsedMilliseconds > maximumReceiveTime)
                            {
                                maximumReceiveTime = stopwatch.ElapsedMilliseconds;
                            }
                            if (stopwatch.ElapsedMilliseconds < minimumReceiveTime)
                            {
                                minimumReceiveTime = stopwatch.ElapsedMilliseconds;
                            }
                            totalReceiveElapsedTime += stopwatch.ElapsedMilliseconds;
                            if (statistics)
                            {
                                if (messageReceiver.PrefetchCount > 0)
                                {
                                    if (stopwatch.ElapsedMilliseconds == 0)
                                    {
                                        fetchedMessages++;
                                    }
                                    else
                                    {
                                        if (fetchedMessages > 0)
                                        {
                                            updateStatistics(fetchedMessages,
                                                             prefetchElapsedTime,
                                                             DirectionType.Receive);
                                            fetchedMessages = 1;
                                        }
                                        else
                                        {
                                            fetchedMessages++;
                                        }
                                        prefetchElapsedTime = stopwatch.ElapsedMilliseconds;
                                    }
                                }
                                else
                                {
                                    updateStatistics(1, stopwatch.ElapsedMilliseconds, DirectionType.Receive);
                                }
                            }
                            builder = new StringBuilder();

                            if (defer &&
                                !readingDeferredMessages &&
                                filter != null &&
                                filter.Match(inboundMessage))
                            {
                                inboundMessage.Defer();
                                messageDeferProvider.Enqueue(inboundMessage.SequenceNumber);
                                deferredMessage = true;
                            }

                            if (!deferredMessage &&
                                moveToDeadLetterQueue &&
                                filter != null &&
                                filter.Match(inboundMessage))
                            {
                                inboundMessage.DeadLetter();
                                movedToDeadLetterQueue = true;
                                messagesReceived++;
                            }


                            if (!deferredMessage &&
                                !movedToDeadLetterQueue)
                            {
                                if (messageReceiver.Mode == ReceiveMode.PeekLock)
                                {
                                    if (completeReceive)
                                    {
                                        stopwatch = new Stopwatch();
                                        stopwatch.Start();
                                        inboundMessage.Complete();
                                        stopwatch.Stop();
                                        if (stopwatch.ElapsedMilliseconds > maximumCompleteTime)
                                        {
                                            maximumCompleteTime = stopwatch.ElapsedMilliseconds;
                                        }
                                        if (stopwatch.ElapsedMilliseconds < minimumCompleteTime)
                                        {
                                            minimumCompleteTime = stopwatch.ElapsedMilliseconds;
                                        }
                                        totalCompleteElapsedTime += stopwatch.ElapsedMilliseconds;
                                        messagesReceived++;
                                    }
                                    else
                                    {
                                        stopwatch = new Stopwatch();
                                        inboundMessage.Abandon();
                                        stopwatch.Stop();
                                        if (stopwatch.ElapsedMilliseconds > maximumCompleteTime)
                                        {
                                            maximumCompleteTime = stopwatch.ElapsedMilliseconds;
                                        }
                                        if (stopwatch.ElapsedMilliseconds < minimumCompleteTime)
                                        {
                                            minimumCompleteTime = stopwatch.ElapsedMilliseconds;
                                        }
                                        totalCompleteElapsedTime += stopwatch.ElapsedMilliseconds;
                                    }
                                }
                                else
                                {
                                    messagesReceived++;
                                }
                            }

                            if (logging)
                            {
                                if (messageReceiver.Mode == ReceiveMode.PeekLock &&
                                    !completeReceive &&
                                    !deferredMessage &&
                                    !movedToDeadLetterQueue)
                                {
                                    builder.AppendLine(string.Format(MessagePeekedButNotConsumed,
                                                                     taskId,
                                                                     string.IsNullOrWhiteSpace(inboundMessage.MessageId)
                                                                         ? NullValue
                                                                         : inboundMessage.MessageId,
                                                                     string.IsNullOrWhiteSpace(inboundMessage.SessionId)
                                                                         ? NullValue
                                                                         : inboundMessage.SessionId,
                                                                     string.IsNullOrWhiteSpace(inboundMessage.Label)
                                                                         ? NullValue
                                                                         : inboundMessage.Label,
                                                                     inboundMessage.Size));
                                }
                                else
                                {
                                    builder.AppendLine(string.Format(MessageSuccessfullyReceived,
                                                                     taskId,
                                                                     string.IsNullOrWhiteSpace(inboundMessage.MessageId)
                                                                         ? NullValue
                                                                         : inboundMessage.MessageId,
                                                                     string.IsNullOrWhiteSpace(inboundMessage.SessionId)
                                                                         ? NullValue
                                                                         : inboundMessage.SessionId,
                                                                     string.IsNullOrWhiteSpace(inboundMessage.Label)
                                                                         ? NullValue
                                                                         : inboundMessage.Label,
                                                                     inboundMessage.Size,
                                                                     inboundMessage.DeliveryCount));
                                }
                                if (deferredMessage)
                                {
                                    builder.AppendLine(MessageDeferred);
                                }
                                if (readDeferredMessage)
                                {
                                    builder.AppendLine(ReadMessageDeferred);
                                }
                                if (movedToDeadLetterQueue)
                                {
                                    builder.AppendLine(MessageMovedToDeadLetterQueue);
                                }
                                if (receivedFromDeadLetterQueue)
                                {
                                    builder.AppendLine(MessageReadFromDeadLetterQueue);
                                }
                                if (verbose)
                                {
                                    GetMessageAndProperties(builder, inboundMessage, encoder);
                                }
                            }

                            if (logging)
                            {
                                traceMessage = builder.ToString();
                                WriteToLog(traceMessage.Substring(0, traceMessage.Length - 1));
                            }
                        }
                        catch (Exception ex)
                        {
                            if (inboundMessage != null &&
                                messageReceiver.Mode == ReceiveMode.PeekLock)
                            {
                                try
                                {
                                    inboundMessage.Abandon();
                                }
                                // ReSharper disable EmptyGeneralCatchClause
                                catch (Exception)
                                // ReSharper restore EmptyGeneralCatchClause
                                {
                                }
                            }
                            exceptionMessage = string.Format(ExceptionOccurred, ex.Message);
                            isCompleted = true;
                            ok = false;
                        }
                        finally
                        {
                            if (inboundMessage != null)
                            {
                                inboundMessage.Dispose();
                            }
                        }
                        if (receiverThinkTime)
                        {
                            WriteToLog(string.Format(SleepingFor, thinkTime));
                            Thread.Sleep(thinkTime);
                        }
                    }
                }

                if (messageReceiver.PrefetchCount > 0 && fetchedMessages > 0 && prefetchElapsedTime > 0)
                {
                    updateStatistics(fetchedMessages, prefetchElapsedTime, DirectionType.Receive);
                }
            }
            catch (Exception ex)
            {
                exceptionMessage = string.Format(ExceptionOccurred, ex.Message);
                ok = false;
            }
            if (messagesReceived == 0)
            {
                WriteToLog(string.Format(NoMessageWasReceived, taskId));
            }
            var averageReceiveTime = messagesReceived > 0 ? totalReceiveElapsedTime / messagesReceived : maximumReceiveTime;
            var averageCompleteTime = messagesReceived > 0 ? totalCompleteElapsedTime / messagesReceived : maximumCompleteTime;
            // ReSharper disable RedundantCast
            var messagesPerSecond = totalReceiveElapsedTime > 0 ? (double)(messagesReceived * 1000) / (double)totalReceiveElapsedTime : 0;
            // ReSharper restore RedundantCast
            builder = new StringBuilder();
            builder.AppendLine(string.Format(CultureInfo.CurrentCulture,
                                             ReceiverStatisticsHeader,
                                             taskId));
            if (!string.IsNullOrWhiteSpace(exceptionMessage))
            {
                builder.AppendLine(exceptionMessage);
            }
            if (messageReceiver.Mode == ReceiveMode.ReceiveAndDelete)
            {
                builder.AppendLine(string.Format(CultureInfo.CurrentCulture,
                                                 ReceiverStatitiscsLine1,
                                                 messagesReceived,
                                                 messagesPerSecond,
                                                 totalReceiveElapsedTime));
            }
            else
            {
                builder.AppendLine(string.Format(CultureInfo.CurrentCulture,
                                                 ReceiverStatitiscsWithCompleteLine1,
                                                 messagesReceived,
                                                 messagesPerSecond,
                                                 totalReceiveElapsedTime,
                                                 totalCompleteElapsedTime));
            }
            builder.AppendLine(string.Format(CultureInfo.CurrentCulture,
                                             ReceiverStatitiscsLine2,
                                             averageReceiveTime,
                                             minimumReceiveTime == long.MaxValue ? 0 : minimumReceiveTime,
                                             maximumReceiveTime));
            if (messageReceiver.Mode == ReceiveMode.PeekLock)
            {
                builder.AppendLine(string.Format(CultureInfo.CurrentCulture,
                                             ReceiverStatitiscsLine3,
                                             averageCompleteTime,
                                             minimumCompleteTime == long.MaxValue ? 0 : minimumCompleteTime,
                                             maximumCompleteTime));
            }
            traceMessage = builder.ToString();
            return ok;
        }
コード例 #58
0
        /// <summary>
        /// This method is used to receive message from a queue or a subscription.
        /// </summary>
        /// <param name="entityDescription">The description of the entity from which to read messages.</param>
        /// <param name="messageCount">The number of messages to read.</param>
        /// <param name="complete">This parameter indicates whether to complete the receive operation.</param>
        /// <param name="deadletterQueue">This parameter indicates whether to read messages from the deadletter queue.</param>
        /// <param name="receiveTimeout">Receive receiveTimeout.</param>
        /// <param name="sessionTimeout">Session timeout</param>
        /// <param name="cancellationTokenSource">Cancellation token source.</param>
        public void ReceiveMessages(EntityDescription entityDescription, int? messageCount, bool complete, bool deadletterQueue, TimeSpan receiveTimeout, TimeSpan sessionTimeout, CancellationTokenSource cancellationTokenSource)
        {
            var receiverList = new List<MessageReceiver>();
            if (brokeredMessageList != null &&
                brokeredMessageList.Count > 0)
            {
                brokeredMessageList.ForEach(b => b.Dispose());
            }
            brokeredMessageList = new List<BrokeredMessage>();
            MessageEncodingBindingElement element;
            if (scheme == DefaultScheme)
            {
                element = new BinaryMessageEncodingBindingElement
                {
                    ReaderQuotas = new XmlDictionaryReaderQuotas
                    {
                        MaxArrayLength = int.MaxValue,
                        MaxBytesPerRead = int.MaxValue,
                        MaxDepth = int.MaxValue,
                        MaxNameTableCharCount = int.MaxValue,
                        MaxStringContentLength = int.MaxValue
                    }
                };
            }
            else
            {
                element = new TextMessageEncodingBindingElement
                {
                    ReaderQuotas = new XmlDictionaryReaderQuotas
                    {
                        MaxArrayLength = int.MaxValue,
                        MaxBytesPerRead = int.MaxValue,
                        MaxDepth = int.MaxValue,
                        MaxNameTableCharCount = int.MaxValue,
                        MaxStringContentLength = int.MaxValue
                    }
                };
            }
            var encoderFactory = element.CreateMessageEncoderFactory();
            var encoder = encoderFactory.Encoder;

            MessageReceiver messageReceiver = null;
            if (entityDescription is QueueDescription)
            {
                var queueDescription = entityDescription as QueueDescription;
                if (deadletterQueue)
                {
                    messageReceiver = messagingFactory.CreateMessageReceiver(QueueClient.FormatDeadLetterPath(queueDescription.Path),
                                                                             ReceiveMode.PeekLock);
                }
                else
                {
                    if (queueDescription.RequiresSession)
                    {
                        var queueClient = messagingFactory.CreateQueueClient(queueDescription.Path,
                                                                             ReceiveMode.PeekLock);
                        messageReceiver = queueClient.AcceptMessageSession(sessionTimeout);
                    }
                    else
                    {
                        messageReceiver = messagingFactory.CreateMessageReceiver(queueDescription.Path,
                                                                                 ReceiveMode.PeekLock);
                    }
                }
            }
            else
            {
                if (entityDescription is SubscriptionDescription)
                {
                    var subscriptionDescription = entityDescription as SubscriptionDescription;
                    if (deadletterQueue)
                    {
                        messageReceiver = messagingFactory.CreateMessageReceiver(SubscriptionClient.FormatDeadLetterPath(subscriptionDescription.TopicPath,
                                                                                                                            subscriptionDescription.Name),
                                                                                    ReceiveMode.PeekLock);
                    }
                    else
                    {
                        if (subscriptionDescription.RequiresSession)
                        {
                            var subscriptionClient = messagingFactory.CreateSubscriptionClient(subscriptionDescription.TopicPath,
                                                                                                subscriptionDescription.Name,
                                                                                                ReceiveMode.PeekLock);
                            messageReceiver = subscriptionClient.AcceptMessageSession(sessionTimeout);
                        }
                        else
                        {
                            messageReceiver = messagingFactory.CreateMessageReceiver(SubscriptionClient.FormatSubscriptionPath(subscriptionDescription.TopicPath,
                                                                                                                                subscriptionDescription.Name),
                                                                                        ReceiveMode.PeekLock);
                        }
                    }
                }
            }
            if (messageReceiver != null)
            {
                messageReceiver.PrefetchCount = 0;
                receiverList.Add(messageReceiver);
                ReceiveNextMessage(messageCount, 0, messageReceiver, ReceiveCallback, encoder, complete, receiveTimeout, cancellationTokenSource.Token);
            }
        }
コード例 #59
0
 /// <summary>
 /// Reads the content of the EventData passed as argument.
 /// </summary>
 /// <param name="eventDataToRead">The EventData to read.</param>
 /// <param name="bodyType">BodyType</param>
 /// <returns>The content of the EventData.</returns>
 public string GetMessageText(EventData eventDataToRead, out BodyType bodyType)
 {
     string eventDataText = null;
     Stream stream = null;
     bodyType = BodyType.Stream;
     if (eventDataToRead == null)
     {
         return null;
     }
     var inboundMessage = eventDataToRead.Clone();
     try
     {
         stream = inboundMessage.GetBody<Stream>();
         if (stream != null)
         {
             var element = new BinaryMessageEncodingBindingElement
             {
                 ReaderQuotas = new XmlDictionaryReaderQuotas
                 {
                     MaxArrayLength = int.MaxValue,
                     MaxBytesPerRead = int.MaxValue,
                     MaxDepth = int.MaxValue,
                     MaxNameTableCharCount = int.MaxValue,
                     MaxStringContentLength = int.MaxValue
                 }
             };
             var encoderFactory = element.CreateMessageEncoderFactory();
             var encoder = encoderFactory.Encoder;
             var stringBuilder = new StringBuilder();
             var eventData = encoder.ReadMessage(stream, MaxBufferSize);
             using (var reader = eventData.GetReaderAtBodyContents())
             {
                 // The XmlWriter is used just to indent the XML eventData
                 var settings = new XmlWriterSettings { Indent = true };
                 using (var writer = XmlWriter.Create(stringBuilder, settings))
                 {
                     writer.WriteNode(reader, true);
                 }
             }
             eventDataText = stringBuilder.ToString();
             bodyType = BodyType.Wcf;
         }
     }
     catch (Exception)
     {
         inboundMessage = eventDataToRead.Clone();
         try
         {
             stream = inboundMessage.GetBody<Stream>();
             if (stream != null)
             {
                 var element = new BinaryMessageEncodingBindingElement
                 {
                     ReaderQuotas = new XmlDictionaryReaderQuotas
                     {
                         MaxArrayLength = int.MaxValue,
                         MaxBytesPerRead = int.MaxValue,
                         MaxDepth = int.MaxValue,
                         MaxNameTableCharCount = int.MaxValue,
                         MaxStringContentLength = int.MaxValue
                     }
                 };
                 var encoderFactory = element.CreateMessageEncoderFactory();
                 var encoder = encoderFactory.Encoder;
                 var eventData = encoder.ReadMessage(stream, MaxBufferSize);
                 using (var reader = eventData.GetReaderAtBodyContents())
                 {
                     eventDataText = reader.ReadString();
                 }
                 bodyType = BodyType.Wcf;
             }
         }
         catch (Exception)
         {
             try
             {
                 if (stream != null)
                 {
                     try
                     {
                         stream.Seek(0, SeekOrigin.Begin);
                         var serializer = new CustomDataContractBinarySerializer(typeof(string));
                         eventDataText = serializer.ReadObject(stream) as string;
                         bodyType = BodyType.String;
                     }
                     catch (Exception)
                     {
                         try
                         {
                             stream.Seek(0, SeekOrigin.Begin);
                             using (var reader = new StreamReader(stream))
                             {
                                 eventDataText = reader.ReadToEnd();
                                 if (eventDataText.ToCharArray().GroupBy(c => c).
                                     Where(g => char.IsControl(g.Key) && g.Key != '\t' && g.Key != '\n' && g.Key != '\r').
                                     Select(g => g.First()).Any())
                                 {
                                     stream.Seek(0, SeekOrigin.Begin);
                                     using (var binaryReader = new BinaryReader(stream))
                                     {
                                         var bytes = binaryReader.ReadBytes((int)stream.Length);
                                         eventDataText = BitConverter.ToString(bytes).Replace('-', ' ');
                                     }
                                 }
                             }
                         }
                         catch (Exception)
                         {
                             eventDataText = UnableToReadMessageBody;
                         }
                     }
                 }
                 else
                 {
                     eventDataText = UnableToReadMessageBody;
                 }
             }
             catch (Exception)
             {
                 eventDataText = UnableToReadMessageBody;
             }
         }
     }
     return eventDataText;
 }
コード例 #60
0
 /// <summary>
 /// Reads the message contained in a stream.
 /// </summary>
 /// <param name="stream">The stream containing the message.</param>
 /// <param name="isBinary">Indicates if the body is binary or not.</param>
 /// <returns>The message.</returns>
 private static string GetMessageText(Stream stream, bool isBinary = false)
 {
     string messageText;
     if (stream == null)
     {
         return null;
     }
     try
     {
         var element = new BinaryMessageEncodingBindingElement
         {
             ReaderQuotas = new XmlDictionaryReaderQuotas
             {
                 MaxArrayLength = int.MaxValue,
                 MaxBytesPerRead = int.MaxValue,
                 MaxDepth = int.MaxValue,
                 MaxNameTableCharCount = int.MaxValue,
                 MaxStringContentLength = int.MaxValue
             }
         };
         var encoderFactory = element.CreateMessageEncoderFactory();
         var encoder = encoderFactory.Encoder;
         var stringBuilder = new StringBuilder();
         var message = encoder.ReadMessage(stream, MaxBufferSize);
         using (var reader = message.GetReaderAtBodyContents())
         {
             // The XmlWriter is used just to indent the XML message
             var settings = new XmlWriterSettings { Indent = true };
             using (var writer = XmlWriter.Create(stringBuilder, settings))
             {
                 writer.WriteNode(reader, true);
             }
         }
         messageText = stringBuilder.ToString();
     }
     catch (Exception)
     {
         try
         {
             stream.Seek(0, SeekOrigin.Begin);
             var element = new BinaryMessageEncodingBindingElement
             {
                 ReaderQuotas = new XmlDictionaryReaderQuotas
                 {
                     MaxArrayLength = int.MaxValue,
                     MaxBytesPerRead = int.MaxValue,
                     MaxDepth = int.MaxValue,
                     MaxNameTableCharCount = int.MaxValue,
                     MaxStringContentLength = int.MaxValue
                 }
             };
             var encoderFactory = element.CreateMessageEncoderFactory();
             var encoder = encoderFactory.Encoder;
             var message = encoder.ReadMessage(stream, MaxBufferSize);
             using (var reader = message.GetReaderAtBodyContents())
             {
                 messageText = reader.ReadString();
             }
         }
         catch (Exception)
         {
                 try
                 {
                     stream.Seek(0, SeekOrigin.Begin);
                     var serializer = new CustomDataContractBinarySerializer(typeof(string));
                     messageText = serializer.ReadObject(stream) as string;
                 }
                 catch (Exception)
                 {
                 try
                 {
                     stream.Seek(0, SeekOrigin.Begin);
                     if (isBinary)
                     {
                         using (var binaryReader = new BinaryReader(stream))
                         {
                             var bytes = binaryReader.ReadBytes((int)stream.Length);
                             messageText = BitConverter.ToString(bytes).Replace('-', ' ');
                         }
                     }
                     else
                     {
                         using (var reader = new StreamReader(stream))
                         {
                             messageText = reader.ReadToEnd();
                             if (messageText.ToCharArray().GroupBy(c => c).
                                 Where(g => char.IsControl(g.Key) && g.Key != '\t' && g.Key != '\n' && g.Key != '\r').
                                 Select(g => g.First()).Any())
                             {
                                 stream.Seek(0, SeekOrigin.Begin);
                                 using (var binaryReader = new BinaryReader(stream))
                                 {
                                     var bytes = binaryReader.ReadBytes((int)stream.Length);
                                     messageText = BitConverter.ToString(bytes).Replace('-', ' ');
                                 }
                             }
                         }
                     }
                 }
                 catch (Exception)
                 {
                     messageText = UnableToReadMessageBody;
                 }
             }
         }
     }
     return messageText;
 }