SerializeBinaryMessage() static private method

static private SerializeBinaryMessage ( IMessage msg, bool includeVersions ) : Stream
msg IMessage
includeVersions bool
return Stream
        } // AsyncProcessMessage

        // helper function to serialize the message
        private void SerializeMessage(IMessage msg,
                                      out ITransportHeaders headers, out Stream stream)
        {
            BaseTransportHeaders requestHeaders = new BaseTransportHeaders();

            headers = requestHeaders;

            // add other http soap headers
            requestHeaders.ContentType = CoreChannel.BinaryMimeType;
            if (_channelProtocol == SinkChannelProtocol.Http)
            {
                headers["__RequestVerb"] = "POST";
            }

            bool bMemStream = false;

            stream = _nextSink.GetRequestStream(msg, headers);
            if (stream == null)
            {
                stream     = new ChunkedMemoryStream(CoreChannel.BufferPool);
                bMemStream = true;
            }
            CoreChannel.SerializeBinaryMessage(msg, stream, _includeVersioning);
            if (bMemStream)
            {
                stream.Position = 0;
            }
        } // SerializeMessage
        } // AsyncProcessResponse

        private void SerializeResponse(IServerResponseChannelSinkStack sinkStack,
                                       IMessage msg, ref ITransportHeaders headers,
                                       out Stream stream)
        {
            BaseTransportHeaders responseHeaders = new BaseTransportHeaders();

            if (headers != null)
            {
                // copy old headers into new headers
                foreach (DictionaryEntry entry in headers)
                {
                    responseHeaders[entry.Key] = entry.Value;
                }
            }
            headers = responseHeaders;

            if (_protocol == Protocol.Http)
            {
                responseHeaders.ContentType = CoreChannel.BinaryMimeType;
            }

            bool bMemStream = false;

            stream = sinkStack.GetResponseStream(msg, headers);
            if (stream == null)
            {
                stream     = new ChunkedMemoryStream(CoreChannel.BufferPool);
                bMemStream = true;
            }


            bool bBashUrl = CoreChannel.SetupUrlBashingForIisSslIfNecessary();

            try
            {
                CallContext.SetData("__ClientIsClr", true);
                CoreChannel.SerializeBinaryMessage(msg, stream, _includeVersioning);
            }
            finally
            {
                CallContext.FreeNamedDataSlot("__ClientIsClr");
                CoreChannel.CleanupUrlBashingForIisSslIfNecessary(bBashUrl);
            }

            if (bMemStream)
            {
                stream.Position = 0;
            }
        } // SerializeResponse
        private void SerializeResponse(IServerResponseChannelSinkStack sinkStack, IMessage msg, ref ITransportHeaders headers, out Stream stream)
        {
            BaseTransportHeaders headers2 = new BaseTransportHeaders();

            if (headers != null)
            {
                foreach (DictionaryEntry entry in headers)
                {
                    headers2[entry.Key] = entry.Value;
                }
            }
            headers = headers2;
            if (this._protocol == Protocol.Http)
            {
                headers2.ContentType = "application/octet-stream";
            }
            bool flag = false;

            stream = sinkStack.GetResponseStream(msg, headers);
            if (stream == null)
            {
                stream = new ChunkedMemoryStream(CoreChannel.BufferPool);
                flag   = true;
            }
            bool bBashedUrl = CoreChannel.SetupUrlBashingForIisSslIfNecessary();

            try
            {
                CallContext.SetData("__ClientIsClr", true);
                CoreChannel.SerializeBinaryMessage(msg, stream, this._includeVersioning);
            }
            finally
            {
                CallContext.FreeNamedDataSlot("__ClientIsClr");
                CoreChannel.CleanupUrlBashingForIisSslIfNecessary(bBashedUrl);
            }
            if (flag)
            {
                stream.Position = 0L;
            }
        }
        private void SerializeMessage(IMessage msg, out ITransportHeaders headers, out Stream stream)
        {
            BaseTransportHeaders headers2 = new BaseTransportHeaders();

            headers = headers2;
            headers2.ContentType = "application/octet-stream";
            if (this._channelProtocol == SinkChannelProtocol.Http)
            {
                headers["__RequestVerb"] = "POST";
            }
            bool flag = false;

            stream = this._nextSink.GetRequestStream(msg, headers);
            if (stream == null)
            {
                stream = new ChunkedMemoryStream(CoreChannel.BufferPool);
                flag   = true;
            }
            CoreChannel.SerializeBinaryMessage(msg, stream, this._includeVersioning);
            if (flag)
            {
                stream.Position = 0L;
            }
        }
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack,
                                               IMessage requestMsg,
                                               ITransportHeaders requestHeaders, Stream requestStream,
                                               out IMessage responseMsg, out ITransportHeaders responseHeaders,
                                               out Stream responseStream)
        {
            if (requestMsg != null)
            {
                // The message has already been deserialized so delegate to the next sink.
                return(_nextSink.ProcessMessage(
                           sinkStack,
                           requestMsg, requestHeaders, requestStream,
                           out responseMsg, out responseHeaders, out responseStream));
            }

            if (requestHeaders == null)
            {
                throw new ArgumentNullException("requestHeaders");
            }

            BaseTransportHeaders wkRequestHeaders = requestHeaders as BaseTransportHeaders;

            ServerProcessing processing;

            responseHeaders = null;
            responseStream  = null;

            String verb        = null;
            String contentType = null;

            bool bCanServiceRequest = true;

            // determine the content type
            String contentTypeHeader = null;

            if (wkRequestHeaders != null)
            {
                contentTypeHeader = wkRequestHeaders.ContentType;
            }
            else
            {
                contentTypeHeader = requestHeaders["Content-Type"] as String;
            }
            if (contentTypeHeader != null)
            {
                String charsetValue;
                HttpChannelHelper.ParseContentType(contentTypeHeader,
                                                   out contentType, out charsetValue);
            }

            // check to see if Content-Type matches
            if ((contentType != null) &&
                (String.CompareOrdinal(contentType, CoreChannel.BinaryMimeType) != 0))
            {
                bCanServiceRequest = false;
            }

            // check for http specific verbs
            if (_protocol == Protocol.Http)
            {
                verb = (String)requestHeaders["__RequestVerb"];
                if (!verb.Equals("POST") && !verb.Equals("M-POST"))
                {
                    bCanServiceRequest = false;
                }
            }

            // either delegate or return an error message if we can't service the request
            if (!bCanServiceRequest)
            {
                // delegate to next sink if available
                if (_nextSink != null)
                {
                    return(_nextSink.ProcessMessage(sinkStack, null, requestHeaders, requestStream,
                                                    out responseMsg, out responseHeaders, out responseStream));
                }
                else
                {
                    // send back an error message
                    if (_protocol == Protocol.Http)
                    {
                        // return a client bad request error
                        responseHeaders = new TransportHeaders();
                        responseHeaders["__HttpStatusCode"]   = "400";
                        responseHeaders["__HttpReasonPhrase"] = "Bad Request";
                        responseStream = null;
                        responseMsg    = null;
                        return(ServerProcessing.Complete);
                    }
                    else
                    {
                        // The transport sink will catch this and do something here.
                        throw new RemotingException(
                                  CoreChannel.GetResourceString("Remoting_Channels_InvalidRequestFormat"));
                    }
                }
            }


            try
            {
                String objectUri = null;

                bool   bIsCustomErrorEnabled = true;
                object oIsCustomErrorEnabled = requestHeaders["__CustomErrorsEnabled"];
                if (oIsCustomErrorEnabled != null && oIsCustomErrorEnabled is bool)
                {
                    bIsCustomErrorEnabled = (bool)oIsCustomErrorEnabled;
                }
                CallContext.SetData("__CustomErrorsEnabled", bIsCustomErrorEnabled);

                if (wkRequestHeaders != null)
                {
                    objectUri = wkRequestHeaders.RequestUri;
                }
                else
                {
                    objectUri = (String)requestHeaders[CommonTransportKeys.RequestUri];
                }

                if (objectUri != lastUri && RemotingServices.GetServerTypeForUri(objectUri) == null)
                {
                    throw new RemotingException(
                              CoreChannel.GetResourceString("Remoting_ChnlSink_UriNotPublished"));
                }
                else
                {
                    lastUri = objectUri;
                }

                PermissionSet currentPermissionSet = null;
                if (this.TypeFilterLevel != TypeFilterLevel.Full)
                {
                    currentPermissionSet = new PermissionSet(PermissionState.None);
                    currentPermissionSet.SetPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter));
                }

                try {
                    if (currentPermissionSet != null)
                    {
                        currentPermissionSet.PermitOnly();
                    }

                    // Deserialize Request - Stream to IMessage
                    requestMsg = CoreChannel.DeserializeBinaryRequestMessage(objectUri, requestStream, _strictBinding, this.TypeFilterLevel);
                }
                finally {
                    if (currentPermissionSet != null)
                    {
                        CodeAccessPermission.RevertPermitOnly();
                    }
                }
                requestStream.Close();

                if (requestMsg == null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_DeserializeMessage"));
                }


                // Dispatch Call
                sinkStack.Push(this, null);
                processing =
                    _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null,
                                             out responseMsg, out responseHeaders, out responseStream);
                // make sure that responseStream is null
                if (responseStream != null)
                {
                    throw new RemotingException(
                              CoreChannel.GetResourceString("Remoting_ChnlSink_WantNullResponseStream"));
                }

                switch (processing)
                {
                case ServerProcessing.Complete:
                {
                    if (responseMsg == null)
                    {
                        throw new RemotingException(CoreChannel.GetResourceString("Remoting_DispatchMessage"));
                    }

                    sinkStack.Pop(this);

                    SerializeResponse(sinkStack, responseMsg,
                                      ref responseHeaders, out responseStream);
                    break;
                } // case ServerProcessing.Complete

                case ServerProcessing.OneWay:
                {
                    sinkStack.Pop(this);
                    break;
                } // case ServerProcessing.OneWay:

                case ServerProcessing.Async:
                {
                    sinkStack.Store(this, null);
                    break;
                } // case ServerProcessing.Async
                } // switch (processing)
            }
            catch (Exception e)
            {
                processing  = ServerProcessing.Complete;
                responseMsg = new ReturnMessage(e, (IMethodCallMessage)(requestMsg == null?new ErrorMessage():requestMsg));
                //

                CallContext.SetData("__ClientIsClr", true);
                responseStream = (MemoryStream)CoreChannel.SerializeBinaryMessage(responseMsg, _includeVersioning);
                CallContext.FreeNamedDataSlot("__ClientIsClr");
                responseStream.Position = 0;
                responseHeaders         = new TransportHeaders();

                if (_protocol == Protocol.Http)
                {
                    responseHeaders["Content-Type"] = CoreChannel.BinaryMimeType;
                }
            }
            finally{
                CallContext.FreeNamedDataSlot("__CustomErrorsEnabled");
            }

            return(processing);
        } // ProcessMessage
        } // StrictBinding



        /// <include file='doc\BinaryFormatterSinks.uex' path='docs/doc[@for="BinaryServerFormatterSink.ProcessMessage"]/*' />
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack,
                                               IMessage requestMsg,
                                               ITransportHeaders requestHeaders, Stream requestStream,
                                               out IMessage responseMsg, out ITransportHeaders responseHeaders,
                                               out Stream responseStream)
        {
            if (requestMsg != null)
            {
                // The message has already been deserialized so delegate to the next sink.
                return(_nextSink.ProcessMessage(
                           sinkStack,
                           requestMsg, requestHeaders, requestStream,
                           out responseMsg, out responseHeaders, out responseStream));
            }

            if (requestHeaders == null)
            {
                throw new ArgumentNullException("requestHeaders");
            }

            BaseTransportHeaders wkRequestHeaders = requestHeaders as BaseTransportHeaders;

            ServerProcessing processing;

            responseHeaders = null;
            responseStream  = null;

            String verb        = null;
            String contentType = null;

            bool bCanServiceRequest = true;

            // determine the content type
            String contentTypeHeader = null;

            if (wkRequestHeaders != null)
            {
                contentTypeHeader = wkRequestHeaders.ContentType;
            }
            else
            {
                contentTypeHeader = requestHeaders["Content-Type"] as String;
            }
            if (contentTypeHeader != null)
            {
                String charsetValue;
                HttpChannelHelper.ParseContentType(contentTypeHeader,
                                                   out contentType, out charsetValue);
            }

            // check to see if Content-Type matches
            if ((contentType != null) &&
                (String.CompareOrdinal(contentType, CoreChannel.BinaryMimeType) != 0))
            {
                bCanServiceRequest = false;
            }

            // check for http specific verbs
            if (_protocol == Protocol.Http)
            {
                verb = (String)requestHeaders["__RequestVerb"];
                if (!verb.Equals("POST") && !verb.Equals("M-POST"))
                {
                    bCanServiceRequest = false;
                }
            }

            // either delegate or return an error message if we can't service the request
            if (!bCanServiceRequest)
            {
                // delegate to next sink if available
                if (_nextSink != null)
                {
                    return(_nextSink.ProcessMessage(sinkStack, null, requestHeaders, requestStream,
                                                    out responseMsg, out responseHeaders, out responseStream));
                }
                else
                {
                    // send back an error message
                    if (_protocol == Protocol.Http)
                    {
                        // return a client bad request error
                        responseHeaders = new TransportHeaders();
                        responseHeaders["__HttpStatusCode"]   = "400";
                        responseHeaders["__HttpReasonPhrase"] = "Bad Request";
                        responseStream = null;
                        responseMsg    = null;
                        return(ServerProcessing.Complete);
                    }
                    else
                    {
                        // The transport sink will catch this and do something here.
                        throw new RemotingException(
                                  CoreChannel.GetResourceString("Remoting_Channels_InvalidRequestFormat"));
                    }
                }
            }


            try
            {
                String objectUri = null;
                if (wkRequestHeaders != null)
                {
                    objectUri = wkRequestHeaders.RequestUri;
                }
                else
                {
                    objectUri = (String)requestHeaders[CommonTransportKeys.RequestUri];
                }

                if (RemotingServices.GetServerTypeForUri(objectUri) == null)
                {
                    throw new RemotingException(
                              CoreChannel.GetResourceString("Remoting_ChnlSink_UriNotPublished"));
                }

                RemotingServices.LogRemotingStage(CoreChannel.SERVER_MSG_DESER);
                // Deserialize Request - Stream to IMessage
                requestMsg =
                    CoreChannel.DeserializeBinaryRequestMessage(objectUri, requestStream, _strictBinding);
                requestStream.Close();

                if (requestMsg == null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_DeserializeMessage"));
                }


                // Dispatch Call
                sinkStack.Push(this, null);
                RemotingServices.LogRemotingStage(CoreChannel.SERVER_MSG_SINK_CHAIN);
                processing =
                    _nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null,
                                             out responseMsg, out responseHeaders, out responseStream);
                // make sure that responseStream is null
                if (responseStream != null)
                {
                    throw new RemotingException(
                              CoreChannel.GetResourceString("Remoting_ChnlSink_WantNullResponseStream"));
                }

                switch (processing)
                {
                case ServerProcessing.Complete:
                {
                    if (responseMsg == null)
                    {
                        throw new RemotingException(CoreChannel.GetResourceString("Remoting_DispatchMessage"));
                    }

                    sinkStack.Pop(this);

                    RemotingServices.LogRemotingStage(CoreChannel.SERVER_RET_SER);
                    SerializeResponse(sinkStack, responseMsg,
                                      ref responseHeaders, out responseStream);
                    break;
                } // case ServerProcessing.Complete

                case ServerProcessing.OneWay:
                {
                    sinkStack.Pop(this);
                    break;
                } // case ServerProcessing.OneWay:

                case ServerProcessing.Async:
                {
                    sinkStack.Store(this, null);
                    break;
                } // case ServerProcessing.Async
                } // switch (processing)
            }
            catch (Exception e)
            {
                processing              = ServerProcessing.Complete;
                responseMsg             = new ReturnMessage(e, (IMethodCallMessage)(requestMsg == null?new ErrorMessage():requestMsg));
                responseStream          = (MemoryStream)CoreChannel.SerializeBinaryMessage(responseMsg, _includeVersioning);
                responseStream.Position = 0;
                responseHeaders         = new TransportHeaders();

                if (_protocol == Protocol.Http)
                {
                    responseHeaders["Content-Type"] = CoreChannel.BinaryMimeType;
                }
            }

            RemotingServices.LogRemotingStage(CoreChannel.SERVER_RET_SEND);
            return(processing);
        } // ProcessMessage
        public ServerProcessing ProcessMessage(IServerChannelSinkStack sinkStack, IMessage requestMsg, ITransportHeaders requestHeaders, Stream requestStream, out IMessage responseMsg, out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            ServerProcessing complete;

            if (requestMsg != null)
            {
                return(this._nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream));
            }
            if (requestHeaders == null)
            {
                throw new ArgumentNullException("requestHeaders");
            }
            BaseTransportHeaders headers = requestHeaders as BaseTransportHeaders;

            responseHeaders = null;
            responseStream  = null;
            string str         = null;
            string str2        = null;
            bool   flag        = true;
            string contentType = null;

            if (headers != null)
            {
                contentType = headers.ContentType;
            }
            else
            {
                contentType = requestHeaders["Content-Type"] as string;
            }
            if (contentType != null)
            {
                string str4;
                HttpChannelHelper.ParseContentType(contentType, out str2, out str4);
            }
            if ((str2 != null) && (string.CompareOrdinal(str2, "application/octet-stream") != 0))
            {
                flag = false;
            }
            if (this._protocol == Protocol.Http)
            {
                str = (string)requestHeaders["__RequestVerb"];
                if (!str.Equals("POST") && !str.Equals("M-POST"))
                {
                    flag = false;
                }
            }
            if (!flag)
            {
                if (this._nextSink != null)
                {
                    return(this._nextSink.ProcessMessage(sinkStack, null, requestHeaders, requestStream, out responseMsg, out responseHeaders, out responseStream));
                }
                if (this._protocol != Protocol.Http)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_Channels_InvalidRequestFormat"));
                }
                responseHeaders = new TransportHeaders();
                responseHeaders["__HttpStatusCode"]   = "400";
                responseHeaders["__HttpReasonPhrase"] = "Bad Request";
                responseStream = null;
                responseMsg    = null;
                return(ServerProcessing.Complete);
            }
            try
            {
                string uRI  = null;
                bool   data = true;
                object obj2 = requestHeaders["__CustomErrorsEnabled"];
                if ((obj2 != null) && (obj2 is bool))
                {
                    data = (bool)obj2;
                }
                CallContext.SetData("__CustomErrorsEnabled", data);
                if (headers != null)
                {
                    uRI = headers.RequestUri;
                }
                else
                {
                    uRI = (string)requestHeaders["__RequestUri"];
                }
                if ((uRI != this.lastUri) && (RemotingServices.GetServerTypeForUri(uRI) == null))
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_ChnlSink_UriNotPublished"));
                }
                this.lastUri = uRI;
                PermissionSet set = null;
                if (this.TypeFilterLevel != System.Runtime.Serialization.Formatters.TypeFilterLevel.Full)
                {
                    set = new PermissionSet(PermissionState.None);
                    set.SetPermission(new SecurityPermission(SecurityPermissionFlag.SerializationFormatter));
                }
                try
                {
                    if (set != null)
                    {
                        set.PermitOnly();
                    }
                    requestMsg = CoreChannel.DeserializeBinaryRequestMessage(uRI, requestStream, this._strictBinding, this.TypeFilterLevel);
                }
                finally
                {
                    if (set != null)
                    {
                        CodeAccessPermission.RevertPermitOnly();
                    }
                }
                requestStream.Close();
                if (requestMsg == null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_DeserializeMessage"));
                }
                sinkStack.Push(this, null);
                complete = this._nextSink.ProcessMessage(sinkStack, requestMsg, requestHeaders, null, out responseMsg, out responseHeaders, out responseStream);
                if (responseStream != null)
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_ChnlSink_WantNullResponseStream"));
                }
                switch (complete)
                {
                case ServerProcessing.Complete:
                    if (responseMsg == null)
                    {
                        throw new RemotingException(CoreChannel.GetResourceString("Remoting_DispatchMessage"));
                    }
                    break;

                case ServerProcessing.OneWay:
                    sinkStack.Pop(this);
                    return(complete);

                case ServerProcessing.Async:
                    sinkStack.Store(this, null);
                    return(complete);

                default:
                    return(complete);
                }
                sinkStack.Pop(this);
                this.SerializeResponse(sinkStack, responseMsg, ref responseHeaders, out responseStream);
                return(complete);
            }
            catch (Exception exception)
            {
                complete    = ServerProcessing.Complete;
                responseMsg = new ReturnMessage(exception, (requestMsg == null) ? ((IMethodCallMessage) new System.Runtime.Remoting.Channels.Http.ErrorMessage()) : ((IMethodCallMessage)requestMsg));
                CallContext.SetData("__ClientIsClr", true);
                responseStream = (MemoryStream)CoreChannel.SerializeBinaryMessage(responseMsg, this._includeVersioning);
                CallContext.FreeNamedDataSlot("__ClientIsClr");
                responseStream.Position = 0L;
                responseHeaders         = new TransportHeaders();
                if (this._protocol == Protocol.Http)
                {
                    responseHeaders["Content-Type"] = "application/octet-stream";
                }
            }
            finally
            {
                CallContext.FreeNamedDataSlot("__CustomErrorsEnabled");
            }
            return(complete);
        }