Exemple #1
0
        bool PrepareReply(ref Message message)
        {
            bool closeOnReceivedEof = false;

            // null means we're done
            if (message == null)
            {
                // A null message means either a one-way request or that the service operation returned null and
                // hence we can close the HttpOutput. By default we keep the HttpOutput open to allow the writing to the output
                // even after the HttpInput EOF is received and the HttpOutput will be closed only on close of the HttpRequestContext.
                closeOnReceivedEof = true;
                message            = CreateAckMessage(HttpStatusCode.Accepted, string.Empty);
            }

            if (!listener.ManualAddressing)
            {
                if (message.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
                {
                    if (message.Headers.To == null ||
                        listener.AnonymousUriPrefixMatcher == null ||
                        !listener.AnonymousUriPrefixMatcher.IsAnonymousUri(message.Headers.To))
                    {
                        message.Headers.To = message.Version.Addressing.AnonymousUri;
                    }
                }
                else if (message.Version.Addressing == AddressingVersion.WSAddressing10 ||
                         message.Version.Addressing == AddressingVersion.None)
                {
                    if (message.Headers.To != null &&
                        (listener.AnonymousUriPrefixMatcher == null ||
                         !listener.AnonymousUriPrefixMatcher.IsAnonymousUri(message.Headers.To)))
                    {
                        message.Headers.To = null;
                    }
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                              new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, message.Version.Addressing)));
                }
            }

            message.Properties.AllowOutputBatching = false;
            this.httpOutput = GetHttpOutputCore(message);

            // Reuse the HttpInput we got previously.
            HttpInput input = this.httpPipeline.HttpInput;

            if (input != null)
            {
                HttpDelayedAcceptStream requestStream = input.GetInputStream(false) as HttpDelayedAcceptStream;
                if (requestStream != null && TransferModeHelper.IsRequestStreamed(listener.TransferMode) &&
                    requestStream.EnableDelayedAccept(this.httpOutput, closeOnReceivedEof))
                {
                    return(false);
                }
            }

            return(true);
        }
Exemple #2
0
        private bool PrepareReply(ref Message message)
        {
            if (message == null)
            {
                message = this.CreateAckMessage(HttpStatusCode.Accepted, string.Empty);
            }
            if (!this.listener.ManualAddressing)
            {
                if (message.Version.Addressing != AddressingVersion.WSAddressingAugust2004)
                {
                    if ((message.Version.Addressing != AddressingVersion.WSAddressing10) && (message.Version.Addressing != AddressingVersion.None))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("AddressingVersionNotSupported", new object[] { message.Version.Addressing })));
                    }
                    if ((message.Headers.To != null) && ((this.listener.AnonymousUriPrefixMatcher == null) || !this.listener.AnonymousUriPrefixMatcher.IsAnonymousUri(message.Headers.To)))
                    {
                        message.Headers.To = null;
                    }
                }
                else if (((message.Headers.To == null) || (this.listener.AnonymousUriPrefixMatcher == null)) || !this.listener.AnonymousUriPrefixMatcher.IsAnonymousUri(message.Headers.To))
                {
                    message.Headers.To = message.Version.Addressing.AnonymousUri;
                }
            }
            message.Properties.AllowOutputBatching = false;
            this.httpOutput = this.GetHttpOutput(message);
            HttpDelayedAcceptStream inputStream = this.HttpInput.InputStream as HttpDelayedAcceptStream;

            if (((inputStream != null) && TransferModeHelper.IsRequestStreamed(this.listener.TransferMode)) && inputStream.EnableDelayedAccept(this.httpOutput))
            {
                return(false);
            }
            return(true);
        }
        void IPolicyExportExtension.ExportPolicy(MetadataExporter exporter, PolicyConversionContext context)
        {
            if (exporter == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("exporter");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            ICollection <XmlElement> policyAssertions = context.GetBindingAssertions();

            if (TransferModeHelper.IsRequestStreamed(this.TransferMode) ||
                TransferModeHelper.IsResponseStreamed(this.TransferMode))
            {
                policyAssertions.Add(new XmlDocument().CreateElement(TransportPolicyConstants.DotNetFramingPrefix,
                                                                     TransportPolicyConstants.StreamedName, TransportPolicyConstants.DotNetFramingNamespace));
            }

            bool createdNew;
            MessageEncodingBindingElement encodingBindingElement = FindMessageEncodingBindingElement(context.BindingElements, out createdNew);

            if (createdNew && encodingBindingElement is IPolicyExportExtension)
            {
                encodingBindingElement = new BinaryMessageEncodingBindingElement();
                ((IPolicyExportExtension)encodingBindingElement).ExportPolicy(exporter, context);
            }

            WsdlExporter.WSAddressingHelper.AddWSAddressingAssertion(exporter, context, encodingBindingElement.MessageVersion.Addressing);
        }
Exemple #4
0
        void IPolicyExportExtension.ExportPolicy(MetadataExporter exporter, PolicyConversionContext context)
        {
            bool flag;

            if (exporter == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("exporter");
            }
            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }
            ICollection <XmlElement> bindingAssertions = context.GetBindingAssertions();

            if (TransferModeHelper.IsRequestStreamed(this.TransferMode) || TransferModeHelper.IsResponseStreamed(this.TransferMode))
            {
                bindingAssertions.Add(new XmlDocument().CreateElement("msf", "Streamed", "http://schemas.microsoft.com/ws/2006/05/framing/policy"));
            }
            MessageEncodingBindingElement element = this.FindMessageEncodingBindingElement(context.BindingElements, out flag);

            if (flag && (element is IPolicyExportExtension))
            {
                element = new BinaryMessageEncodingBindingElement();
                ((IPolicyExportExtension)element).ExportPolicy(exporter, context);
            }
            WsdlExporter.WSAddressingHelper.AddWSAddressingAssertion(exporter, context, element.MessageVersion.Addressing);
        }
        internal void SetWebSocketInfo(WebSocketContext webSocketContext, RemoteEndpointMessageProperty remoteEndpointMessageProperty, SecurityMessageProperty handshakeSecurityMessageProperty, byte[] innerBuffer, bool shouldDisposeWebSocketAfterClosed, HttpRequestMessage requestMessage)
        {
            Fx.Assert(webSocketContext != null, "webSocketContext should not be null.");
            this.ShouldDisposeWebSocketAfterClosed = shouldDisposeWebSocketAfterClosed;
            this.webSocketContext = webSocketContext;
            this.WebSocket        = webSocketContext.WebSocket;
            this.InternalBuffer   = innerBuffer;

            if (handshakeSecurityMessageProperty != null)
            {
                this.RemoteSecurity = handshakeSecurityMessageProperty;
            }

            bool inputUseStreaming = TransferModeHelper.IsRequestStreamed(this.TransferMode);

            this.webSocketMessageSource = new WebSocketMessageSource(
                this,
                this.webSocketContext,
                inputUseStreaming,
                remoteEndpointMessageProperty,
                this,
                requestMessage);

            this.SetMessageSource(this.webSocketMessageSource);
        }
Exemple #6
0
        internal HttpChannelFactory(HttpTransportBindingElement bindingElement, BindingContext context)
            : base(bindingElement, context, HttpTransportDefaults.GetDefaultMessageEncoderFactory())
        {
            // validate setting interactions
            if (bindingElement.TransferMode == TransferMode.Buffered)
            {
                if (bindingElement.MaxReceivedMessageSize > int.MaxValue)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                              new ArgumentOutOfRangeException("bindingElement.MaxReceivedMessageSize",
                                                              SR.MaxReceivedMessageSizeMustBeInIntegerRange));
                }

                if (bindingElement.MaxBufferSize != bindingElement.MaxReceivedMessageSize)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
                                                                                 SR.MaxBufferSizeMustMatchMaxReceivedMessageSize);
                }
            }
            else
            {
                if (bindingElement.MaxBufferSize > bindingElement.MaxReceivedMessageSize)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
                                                                                 SR.MaxBufferSizeMustNotExceedMaxReceivedMessageSize);
                }
            }

            if (TransferModeHelper.IsRequestStreamed(bindingElement.TransferMode) &&
                bindingElement.AuthenticationScheme != AuthenticationSchemes.Anonymous)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
                                                                             SR.HttpAuthDoesNotSupportRequestStreaming);
            }

            _allowCookies = bindingElement.AllowCookies;

            if (_allowCookies)
            {
                _httpCookieContainerManager = new HttpCookieContainerManager();
            }

            if (!bindingElement.AuthenticationScheme.IsSingleton())
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.Format(SR.HttpRequiresSingleAuthScheme,
                                                                                                bindingElement.AuthenticationScheme));
            }
            _authenticationScheme = bindingElement.AuthenticationScheme;
            _maxBufferSize        = bindingElement.MaxBufferSize;
            _transferMode         = bindingElement.TransferMode;
            _useDefaultWebProxy   = bindingElement.UseDefaultWebProxy;

            _channelCredentials   = context.BindingParameters.Find <SecurityCredentialsManager>();
            _securityCapabilities = bindingElement.GetProperty <ISecurityCapabilities>(context);
        }
Exemple #7
0
        public static async Task WriteMessageAsync(Message message, IConnection connection, bool isRequest,
                                                   IConnectionOrientedTransportFactorySettings settings, CancellationToken token)
        {
            // TODO: Switch to using the token as this is supposed to use remaining time
            var timeoutHelper = new TimeoutHelper(TimeoutHelper.GetOriginalTimeout(token));

            byte[] endBytes = null;
            if (message != null)
            {
                MessageEncoder messageEncoder     = settings.MessageEncoderFactory.Encoder;
                byte[]         envelopeStartBytes = SingletonEncoder.EnvelopeStartBytes;

                bool writeStreamed;
                if (isRequest)
                {
                    endBytes      = SingletonEncoder.EnvelopeEndFramingEndBytes;
                    writeStreamed = TransferModeHelper.IsRequestStreamed(settings.TransferMode);
                }
                else
                {
                    endBytes      = SingletonEncoder.EnvelopeEndBytes;
                    writeStreamed = TransferModeHelper.IsResponseStreamed(settings.TransferMode);
                }

                if (writeStreamed)
                {
                    await connection.WriteAsync(envelopeStartBytes, 0, envelopeStartBytes.Length, false, timeoutHelper.RemainingTime());

                    Stream connectionStream   = new StreamingOutputConnectionStream(connection, settings);
                    Stream writeTimeoutStream = new TimeoutStream(connectionStream, timeoutHelper.RemainingTime());
                    messageEncoder.WriteMessage(message, writeTimeoutStream);
                }
                else
                {
                    ArraySegment <byte> messageData = messageEncoder.WriteMessage(message,
                                                                                  int.MaxValue, settings.BufferManager, envelopeStartBytes.Length + IntEncoder.MaxEncodedSize);
                    messageData = SingletonEncoder.EncodeMessageFrame(messageData);
                    Buffer.BlockCopy(envelopeStartBytes, 0, messageData.Array, messageData.Offset - envelopeStartBytes.Length,
                                     envelopeStartBytes.Length);
                    await connection.WriteAsync(messageData.Array, messageData.Offset - envelopeStartBytes.Length,
                                                messageData.Count + envelopeStartBytes.Length, true, timeoutHelper.RemainingTime(), settings.BufferManager);
                }
            }
            else if (isRequest) // context handles response end bytes
            {
                endBytes = SingletonEncoder.EndBytes;
            }

            if (endBytes != null)
            {
                await connection.WriteAsync(endBytes, 0, endBytes.Length,
                                            true, timeoutHelper.RemainingTime());
            }
        }
        public static void WriteMessage(Message message, IConnection connection, bool isRequest,
                                        IConnectionOrientedTransportFactorySettings settings, ref TimeoutHelper timeoutHelper)
        {
            byte[] endBytes = null;
            if (message != null)
            {
                MessageEncoder messageEncoder     = settings.MessageEncoderFactory.Encoder;
                byte[]         envelopeStartBytes = SingletonEncoder.EnvelopeStartBytes;

                bool writeStreamed;
                if (isRequest)
                {
                    endBytes      = SingletonEncoder.EnvelopeEndFramingEndBytes;
                    writeStreamed = TransferModeHelper.IsRequestStreamed(settings.TransferMode);
                }
                else
                {
                    endBytes      = SingletonEncoder.EnvelopeEndBytes;
                    writeStreamed = TransferModeHelper.IsResponseStreamed(settings.TransferMode);
                }

                if (writeStreamed)
                {
                    connection.Write(envelopeStartBytes, 0, envelopeStartBytes.Length, false, timeoutHelper.RemainingTime());
                    Stream connectionStream   = new StreamingOutputConnectionStream(connection, settings);
                    Stream writeTimeoutStream = new TimeoutStream(connectionStream, timeoutHelper.RemainingTime());
                    messageEncoder.WriteMessage(message, writeTimeoutStream);
                }
                else
                {
                    ArraySegment <byte> messageData = messageEncoder.WriteMessage(message,
                                                                                  int.MaxValue, settings.BufferManager, envelopeStartBytes.Length + IntEncoder.MaxEncodedSize);
                    messageData = SingletonEncoder.EncodeMessageFrame(messageData);
                    Buffer.BlockCopy(envelopeStartBytes, 0, messageData.Array, messageData.Offset - envelopeStartBytes.Length,
                                     envelopeStartBytes.Length);
                    connection.Write(messageData.Array, messageData.Offset - envelopeStartBytes.Length,
                                     messageData.Count + envelopeStartBytes.Length, true, timeoutHelper.RemainingTime(), settings.BufferManager);
                }
            }
            else if (isRequest) // context handles response end bytes
            {
                endBytes = SingletonEncoder.EndBytes;
            }

            if (endBytes != null)
            {
                connection.Write(endBytes, 0, endBytes.Length,
                                 true, timeoutHelper.RemainingTime());
            }
        }
Exemple #9
0
        internal HttpRequestMessage GetHttpRequestMessage(EndpointAddress to, Uri via)
        {
            Uri httpRequestUri = via;

            HttpRequestMessage requestMessage = null;

            requestMessage = new HttpRequestMessage(HttpMethod.Post, httpRequestUri);
            if (TransferModeHelper.IsRequestStreamed(TransferMode))
            {
                requestMessage.Headers.TransferEncodingChunked = true;
            }

            requestMessage.Headers.CacheControl = s_requestCacheHeader;
            return(requestMessage);
        }
 protected HttpInput(IHttpTransportFactorySettings settings, bool isRequest, bool enableChannelBinding)
 {
     this.settings             = settings;
     this.bufferManager        = settings.BufferManager;
     this.messageEncoder       = settings.MessageEncoderFactory.Encoder;
     this.webException         = null;
     this.isRequest            = isRequest;
     this.inputStream          = null;
     this.enableChannelBinding = enableChannelBinding;
     if (isRequest)
     {
         this.streamed = TransferModeHelper.IsRequestStreamed(settings.TransferMode);
     }
     else
     {
         this.streamed = TransferModeHelper.IsResponseStreamed(settings.TransferMode);
     }
 }
 public static void WriteMessage(Message message, IConnection connection, bool isRequest, IConnectionOrientedTransportFactorySettings settings, ref TimeoutHelper timeoutHelper)
 {
     byte[] envelopeEndFramingEndBytes = null;
     if (message != null)
     {
         bool           flag;
         MessageEncoder encoder            = settings.MessageEncoderFactory.Encoder;
         byte[]         envelopeStartBytes = SingletonEncoder.EnvelopeStartBytes;
         if (isRequest)
         {
             envelopeEndFramingEndBytes = SingletonEncoder.EnvelopeEndFramingEndBytes;
             flag = TransferModeHelper.IsRequestStreamed(settings.TransferMode);
         }
         else
         {
             envelopeEndFramingEndBytes = SingletonEncoder.EnvelopeEndBytes;
             flag = TransferModeHelper.IsResponseStreamed(settings.TransferMode);
         }
         if (flag)
         {
             connection.Write(envelopeStartBytes, 0, envelopeStartBytes.Length, false, timeoutHelper.RemainingTime());
             Stream stream  = new StreamingOutputConnectionStream(connection, settings);
             Stream stream2 = new TimeoutStream(stream, ref timeoutHelper);
             encoder.WriteMessage(message, stream2);
         }
         else
         {
             ArraySegment <byte> segment = SingletonEncoder.EncodeMessageFrame(encoder.WriteMessage(message, 0x7fffffff, settings.BufferManager, envelopeStartBytes.Length + 5));
             Buffer.BlockCopy(envelopeStartBytes, 0, segment.Array, segment.Offset - envelopeStartBytes.Length, envelopeStartBytes.Length);
             connection.Write(segment.Array, segment.Offset - envelopeStartBytes.Length, segment.Count + envelopeStartBytes.Length, true, timeoutHelper.RemainingTime(), settings.BufferManager);
         }
     }
     else if (isRequest)
     {
         envelopeEndFramingEndBytes = SingletonEncoder.EndBytes;
     }
     if (envelopeEndFramingEndBytes != null)
     {
         connection.Write(envelopeEndFramingEndBytes, 0, envelopeEndFramingEndBytes.Length, true, timeoutHelper.RemainingTime());
     }
 }
Exemple #12
0
        internal HttpRequestMessage GetHttpRequestMessage(EndpointAddress to, Uri via, CancellationToken cancelToken, bool isWebSocketRequest)
        {
            Uri httpWebRequestUri = via;

            HttpRequestMessage requestMessage = null;

            if (!isWebSocketRequest)
            {
                requestMessage = new HttpRequestMessage(HttpMethod.Post, httpWebRequestUri);
                if (TransferModeHelper.IsRequestStreamed(TransferMode))
                {
                    requestMessage.Headers.TransferEncodingChunked = true;
                }
            }
            else
            {
                requestMessage = new HttpRequestMessage(HttpMethod.Get, httpWebRequestUri);
            }

            requestMessage.Headers.CacheControl = s_requestCacheHeader;


            return(requestMessage);
        }
Exemple #13
0
        internal void SetWebSocketInfo(WebSocketContext webSocketContext, RemoteEndpointMessageProperty remoteEndpointMessageProperty, SecurityMessageProperty handshakeSecurityMessageProperty, bool shouldDisposeWebSocketAfterClosed, HttpContext httpContext)
        {
            Fx.Assert(webSocketContext != null, "webSocketContext should not be null.");
            ShouldDisposeWebSocketAfterClosed = shouldDisposeWebSocketAfterClosed;
            _webSocketContext = webSocketContext;
            WebSocket         = webSocketContext.WebSocket;

            if (handshakeSecurityMessageProperty != null)
            {
                RemoteSecurity = handshakeSecurityMessageProperty;
            }

            bool inputUseStreaming = TransferModeHelper.IsRequestStreamed(TransferMode);

            _webSocketMessageSource = new WebSocketMessageSource(
                this,
                _webSocketContext,
                inputUseStreaming,
                remoteEndpointMessageProperty,
                this,
                httpContext);

            SetMessageSource(_webSocketMessageSource);
        }
Exemple #14
0
        internal HttpChannelFactory(HttpTransportBindingElement bindingElement, BindingContext context)
            : base(bindingElement, context, HttpTransportDefaults.GetDefaultMessageEncoderFactory())
        {
            // validate setting interactions
            if (bindingElement.TransferMode == TransferMode.Buffered)
            {
                if (bindingElement.MaxReceivedMessageSize > int.MaxValue)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                              new ArgumentOutOfRangeException("bindingElement.MaxReceivedMessageSize",
                                                              SR.MaxReceivedMessageSizeMustBeInIntegerRange));
                }

                if (bindingElement.MaxBufferSize != bindingElement.MaxReceivedMessageSize)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
                                                                                 SR.MaxBufferSizeMustMatchMaxReceivedMessageSize);
                }
            }
            else
            {
                if (bindingElement.MaxBufferSize > bindingElement.MaxReceivedMessageSize)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
                                                                                 SR.MaxBufferSizeMustNotExceedMaxReceivedMessageSize);
                }
            }

            if (TransferModeHelper.IsRequestStreamed(bindingElement.TransferMode) &&
                bindingElement.AuthenticationScheme != AuthenticationSchemes.Anonymous)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement",
                                                                             SR.HttpAuthDoesNotSupportRequestStreaming);
            }

            _allowCookies = bindingElement.AllowCookies;

            if (_allowCookies)
            {
                _httpCookieContainerManager = new HttpCookieContainerManager();
            }

            if (!bindingElement.AuthenticationScheme.IsSingleton())
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("value", SR.Format(SR.HttpRequiresSingleAuthScheme,
                                                                                                bindingElement.AuthenticationScheme));
            }
            _authenticationScheme = bindingElement.AuthenticationScheme;
            _maxBufferSize        = bindingElement.MaxBufferSize;
            _transferMode         = bindingElement.TransferMode;
            _useDefaultWebProxy   = bindingElement.UseDefaultWebProxy;

            _channelCredentials   = context.BindingParameters.Find <SecurityCredentialsManager>();
            _securityCapabilities = bindingElement.GetProperty <ISecurityCapabilities>(context);

            _webSocketSettings = WebSocketHelper.GetRuntimeWebSocketSettings(bindingElement.WebSocketSettings);
            int webSocketBufferSize = WebSocketHelper.ComputeClientBufferSize(MaxReceivedMessageSize);

            _bufferPool               = new ConnectionBufferPool(webSocketBufferSize);
            _clientWebSocketFactory   = ClientWebSocketFactory.GetFactory();
            _webSocketSoapContentType = new Lazy <string>(() => MessageEncoderFactory.CreateSessionEncoder().ContentType, LazyThreadSafetyMode.ExecutionAndPublication);
        }
            public WriteMessageAsyncResult(Message message, IConnection connection, bool isRequest, IConnectionOrientedTransportFactorySettings settings, ref TimeoutHelper timeoutHelper, AsyncCallback callback, object state) : base(callback, state)
            {
                this.connection    = connection;
                this.encoder       = settings.MessageEncoderFactory.Encoder;
                this.bufferManager = settings.BufferManager;
                this.timeoutHelper = timeoutHelper;
                this.message       = message;
                this.settings      = settings;
                bool flag  = true;
                bool flag2 = false;

                if (message == null)
                {
                    if (isRequest)
                    {
                        this.endBytes = SingletonEncoder.EndBytes;
                    }
                    flag2 = this.WriteEndBytes();
                }
                else
                {
                    try
                    {
                        bool   flag3;
                        byte[] envelopeStartBytes = SingletonEncoder.EnvelopeStartBytes;
                        if (isRequest)
                        {
                            this.endBytes = SingletonEncoder.EnvelopeEndFramingEndBytes;
                            flag3         = TransferModeHelper.IsRequestStreamed(settings.TransferMode);
                        }
                        else
                        {
                            this.endBytes = SingletonEncoder.EnvelopeEndBytes;
                            flag3         = TransferModeHelper.IsResponseStreamed(settings.TransferMode);
                        }
                        if (flag3)
                        {
                            if (onWriteStartBytes == null)
                            {
                                onWriteStartBytes = Fx.ThunkCallback(new AsyncCallback(StreamingConnectionHelper.WriteMessageAsyncResult.OnWriteStartBytes));
                            }
                            IAsyncResult result = connection.BeginWrite(envelopeStartBytes, 0, envelopeStartBytes.Length, true, timeoutHelper.RemainingTime(), onWriteStartBytes, this);
                            if (result.CompletedSynchronously)
                            {
                                if (onWriteStartBytesScheduled == null)
                                {
                                    onWriteStartBytesScheduled = new Action <object>(StreamingConnectionHelper.WriteMessageAsyncResult.OnWriteStartBytesScheduled);
                                }
                                ActionItem.Schedule(onWriteStartBytesScheduled, result);
                            }
                        }
                        else
                        {
                            ArraySegment <byte> segment = SingletonEncoder.EncodeMessageFrame(settings.MessageEncoderFactory.Encoder.WriteMessage(message, 0x7fffffff, this.bufferManager, envelopeStartBytes.Length + 5));
                            this.bufferToFree = segment.Array;
                            Buffer.BlockCopy(envelopeStartBytes, 0, segment.Array, segment.Offset - envelopeStartBytes.Length, envelopeStartBytes.Length);
                            if (onWriteBufferedMessage == null)
                            {
                                onWriteBufferedMessage = Fx.ThunkCallback(new AsyncCallback(StreamingConnectionHelper.WriteMessageAsyncResult.OnWriteBufferedMessage));
                            }
                            IAsyncResult result2 = connection.BeginWrite(segment.Array, segment.Offset - envelopeStartBytes.Length, segment.Count + envelopeStartBytes.Length, true, timeoutHelper.RemainingTime(), onWriteBufferedMessage, this);
                            if (result2.CompletedSynchronously)
                            {
                                flag2 = this.HandleWriteBufferedMessage(result2);
                            }
                        }
                        flag = false;
                    }
                    finally
                    {
                        if (flag)
                        {
                            this.Cleanup();
                        }
                    }
                }
                if (flag2)
                {
                    base.Complete(true);
                }
            }