/// <summary>
        /// Requests message processing from the current sink.
        /// </summary>
        /// <param name="msg">The message to process.</param>
        /// <param name="requestHeaders">The headers to add to the outgoing message heading to the server.</param>
        /// <param name="requestStream">The stream headed to the transport sink.</param>
        /// <param name="responseHeaders">When this method returns, contains an ITransportHeaders interface that holds the headers that the server returned. This parameter is passed uninitialized.</param>
        /// <param name="responseStream">When this method returns, contains a Stream coming back from the transport sink. This parameter is passed uninitialized.</param>
        public void ProcessMessage(IMessage msg, ITransportHeaders requestHeaders, Stream requestStream,
                                   out ITransportHeaders responseHeaders, out Stream responseStream)
        {
            BinaryLogWriter   binaryLogWriter   = this.ITransportContext.BinaryLogWriter;
            ITransportContext iTransportContext = this.ITransportContext;

            if (!GenuineUtility.CheckUrlOnConnectivity(this._recipientUri))
            {
                // get the transport context from the Uri Storage
                iTransportContext = UriStorage.GetTransportContext(this._recipientUri);
                if (iTransportContext == null)
                {
                    iTransportContext = this.ITransportContext;
                }
            }

            Message message = Message.CreateOutcomingMessage(iTransportContext, msg, requestHeaders, requestStream, true);

            try
            {
                message.Recipient = iTransportContext.KnownHosts[this._recipientUri];

                // LOG: put down the log record
                if (binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0)
                {
                    binaryLogWriter.WriteMessageCreatedEvent("GenuineTcpClientTransportSink.ProcessMessage",
                                                             LogMessageType.MessageCreated, null, message, true, message.Recipient,
                                                             this.ITransportContext.BinaryLogWriter[LogCategory.MessageProcessing] > 1 ? message.Stream : null,
                                                             msg.Properties["__Uri"] as string, BinaryLogWriter.ParseInvocationMethod(msg.Properties["__MethodName"] as string, msg.Properties["__TypeName"] as string),
                                                             GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, -1, -1, null, -1, null,
                                                             "Synchronous .NET Remoting invocaiton is being initiated.");

                    message.ITransportHeaders[Message.TransportHeadersInvocationTarget] = msg.Properties["__Uri"] as string;
                    message.ITransportHeaders[Message.TransportHeadersMethodName]       = BinaryLogWriter.ParseInvocationMethod(msg.Properties["__MethodName"] as string, msg.Properties["__TypeName"] as string);

                    binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "GenuineTcpClientTransportSink.ProcessMessage",
                                               LogMessageType.MessageRequestInvoking, null, message, message.Recipient,
                                               null,
                                               GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
                                               null, null, -1, GenuineUtility.TickCount, 0, 0, null, null, null, null,
                                               "The .NET Remoting synchronous invocation has been made.");
                }

                SyncSinkStackResponseProcessor syncSinkStackResponseProcessor = new SyncSinkStackResponseProcessor(iTransportContext, message);
                iTransportContext.IIncomingStreamHandler.RegisterResponseProcessor(message.MessageId, syncSinkStackResponseProcessor);
                message.CancelSending = syncSinkStackResponseProcessor.IsReceivedEvent;

                try
                {
                    // send the message or initiate the sending
                    iTransportContext.ConnectionManager.Send(message);
                }
                catch (Exception ex)
                {
                    // if it's a response processor's problem, force its exception to be fired
                    if (syncSinkStackResponseProcessor.DispatchedException != null)
                    {
                        throw OperationException.WrapException(syncSinkStackResponseProcessor.DispatchedException);
                    }

                    syncSinkStackResponseProcessor.DispatchException(ex);
                    throw;
                }

                if (!GenuineUtility.WaitOne(syncSinkStackResponseProcessor.IsReceivedEvent, GenuineUtility.GetMillisecondsLeft(message.FinishTime)))
                {
                    throw GenuineExceptions.Get_Send_ServerDidNotReply();
                }
                if (syncSinkStackResponseProcessor.DispatchedException != null)
                {
                    throw OperationException.WrapException(syncSinkStackResponseProcessor.DispatchedException);
                }

                // LOG: put down the log record
                if (binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0)
                {
                    binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "GenuineTcpClientTransportSink.ProcessMessage",
                                               LogMessageType.MessageDispatched, null, syncSinkStackResponseProcessor.Response, syncSinkStackResponseProcessor.Response.Sender,
                                               null,
                                               GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
                                               null, null, -1,
                                               GenuineUtility.TickCount, 0, message.SeqNo, null, null, null, null,
                                               "The .NET Remoting synchronous invocation has been completed.");
                }

                responseHeaders = syncSinkStackResponseProcessor.Response.ITransportHeaders;
                responseStream  = syncSinkStackResponseProcessor.Response.Stream;
            }
            catch (Exception ex)
            {
                // LOG: put down the log record
                if (binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0)
                {
                    binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "GenuineTcpClientTransportSink.ProcessMessage",
                                               LogMessageType.MessageDispatched, ex, message, message.Recipient, null,
                                               GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, null, -1,
                                               GenuineUtility.TickCount, 0, message.SeqNo, null, null, null, null,
                                               "The exception is dispatched to the caller context.");
                }

                throw;
            }
        }
        /// <summary>
        /// Handles incoming message (message, response or event).
        /// </summary>
        /// <param name="message">The message to handle.</param>
        public void HandleIncomingMessage(Message message)
        {
            BinaryLogWriter binaryLogWriter = message.ITransportContext.BinaryLogWriter;

            try
            {
                ServerChannelSinkStack stack = new ServerChannelSinkStack();
                stack.Push(this, message);

                ITransportHeaders responseHeaders;
                Stream            responseStream;
                IMessage          responseMsg;

                // FIX: 2.5.8 removing the application name from the object URI
                string applicationName = RemotingConfiguration.ApplicationName;
                if (applicationName != null)
                {
                    string uri = (string)message.ITransportHeaders["__RequestUri"];
                    if (uri.Length > applicationName.Length && uri.StartsWith(applicationName))
                    {
                        int sizeToBeCut = applicationName.Length + (uri[applicationName.Length] == '/' ? 1 : 0);
                        uri = uri.Substring(sizeToBeCut);
                        message.ITransportHeaders["__RequestUri"] = uri;
                    }
                }

                message.ITransportHeaders["__CustomErrorsEnabled"]       = false;
                message.ITransportHeaders[CommonTransportKeys.IPAddress] = message.Sender.PhysicalAddress is IPEndPoint ? ((IPEndPoint)message.Sender.PhysicalAddress).Address : message.Sender.PhysicalAddress;

                // LOG: put down the log record
                if (binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0)
                {
                    binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "GenuineUniversalServerTransportSink.HandleIncomingMessage",
                                               LogMessageType.MessageRequestInvoking, null, message, message.Sender,
                                               null,
                                               GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
                                               null, null, -1, GenuineUtility.TickCount, 0, 0, null, null, null, null,
                                               "The .NET Remoting request is being invoked.");
                }

                ServerProcessing serverProcessing = this._nextChannelSink.ProcessMessage(stack, null, message.ITransportHeaders, message.Stream, out responseMsg, out responseHeaders, out responseStream);

                switch (serverProcessing)
                {
                case ServerProcessing.Complete:
                    Message reply = new Message(message, responseHeaders, responseStream);

                    // LOG: put down the log record
                    if (binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0)
                    {
                        string invocationTarget = responseMsg.Properties["__Uri"] as string;
                        string methodName       = BinaryLogWriter.ParseInvocationMethod(responseMsg.Properties["__MethodName"] as string, responseMsg.Properties["__TypeName"] as string);
                        binaryLogWriter.WriteMessageCreatedEvent("GenuineUniversalServerTransportSink.HandleIncomingMessage",
                                                                 LogMessageType.MessageCreated, null, reply, false, reply.Recipient,
                                                                 binaryLogWriter[LogCategory.MessageProcessing] > 1 ? reply.Stream : null,
                                                                 invocationTarget, methodName,
                                                                 GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, -1, -1, null, -1, null,
                                                                 "The response message has been created.");

                        reply.ITransportHeaders[Message.TransportHeadersInvocationTarget] = invocationTarget;
                        reply.ITransportHeaders[Message.TransportHeadersMethodName]       = methodName;

                        binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "GenuineUniversalServerTransportSink.HandleIncomingMessage",
                                                   LogMessageType.MessageRequestInvoked, null, reply, message.Sender,
                                                   null,
                                                   GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
                                                   null, null, -1, GenuineUtility.TickCount, 0, message.SeqNo, null, null, null, null,
                                                   "The .NET Remoting invocation has been performed.");
                    }

                    message.ITransportContext.ConnectionManager.Send(reply);
                    break;

                case ServerProcessing.Async:
                    // asyncProcessResponse will be called later
                    break;

                case ServerProcessing.OneWay:
                    // LOG: put down the log record
                    if (binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0)
                    {
                        binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "GenuineUniversalServerTransportSink.HandleIncomingMessage",
                                                   LogMessageType.MessageRequestInvoked, null, null, message.Sender,
                                                   null,
                                                   GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
                                                   null, null, -1, GenuineUtility.TickCount, 0, message.SeqNo, null, null, null, null,
                                                   "One-way .NET Remoting invocation has been performed. No response is available.");
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                try
                {
                    // LOG: put down the log record
                    if (binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0)
                    {
                        binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "GenuineUniversalServerTransportSink.HandleIncomingMessage",
                                                   LogMessageType.MessageRequestInvoking, ex, message, message.Sender,
                                                   null,
                                                   GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
                                                   null, null, -1, 0, 0, 0, null, null, null, null,
                                                   "The .NET Remoting request resulted in exception. The exception is being sent back.");
                    }

                    // return this exception as a result
                    var binaryFormatter     = new BinaryFormatter().Safe();
                    var serializedException = new GenuineChunkedStream(false);
                    binaryFormatter.Serialize(serializedException, ex);

                    var reply = new Message(message, new TransportHeaders(), serializedException);
                    reply.ContainsSerializedException = true;
                    this.ITransportContext.ConnectionManager.Send(reply);
                }
                catch (Exception internalEx)
                {
                    // It's a destiny not to deliver an exception back to the caller

                    // LOG: put down the log record
                    if (binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0)
                    {
                        binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "GenuineUniversalServerTransportSink.HandleIncomingMessage",
                                                   LogMessageType.MessageRequestInvoking, internalEx, message, message.Sender,
                                                   null,
                                                   GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
                                                   null, null, -1, 0, 0, 0, null, null, null, null,
                                                   "The source exception cannot be sent over the network. Both exceptions are ignored.");
                    }
                }
            }
        }
        /// <summary>
        /// Requests asynchronous processing of a method call on the current sink.
        /// </summary>
        /// <param name="sinkStack">A stack of channel sinks that called this sink.</param>
        /// <param name="msg">The message to process.</param>
        /// <param name="headers">The headers to add to the outgoing message heading to the server.</param>
        /// <param name="stream">The stream headed to the transport sink.</param>
        public void AsyncProcessRequest(IClientChannelSinkStack sinkStack, IMessage msg,
                                        ITransportHeaders headers, Stream stream)
        {
            ITransportContext iTransportContext = this.ITransportContext;

            if (!GenuineUtility.CheckUrlOnConnectivity(this._recipientUri))
            {
                // get the transport context from the Uri Storage
                iTransportContext = UriStorage.GetTransportContext(this._recipientUri);
                if (iTransportContext == null)
                {
                    iTransportContext = this.ITransportContext;
                }
            }

            Message message = Message.CreateOutcomingMessage(iTransportContext, msg, headers, stream, false);

            message.Recipient = iTransportContext.KnownHosts[this._recipientUri];
            IMethodMessage iMethodMessage = (IMethodMessage)msg;

            message.IsOneWay = RemotingServices.IsOneWay(iMethodMessage.MethodBase);

            // LOG: put down the log record
            BinaryLogWriter binaryLogWriter = this.ITransportContext.BinaryLogWriter;

            if (binaryLogWriter != null && binaryLogWriter[LogCategory.MessageProcessing] > 0)
            {
                binaryLogWriter.WriteMessageCreatedEvent("GenuineTcpClientTransportSink.AsyncProcessRequest",
                                                         LogMessageType.MessageCreated, null, message, true, message.Recipient,
                                                         this.ITransportContext.BinaryLogWriter[LogCategory.MessageProcessing] > 1 ? message.Stream : null,
                                                         msg.Properties["__Uri"] as string, BinaryLogWriter.ParseInvocationMethod(msg.Properties["__MethodName"] as string, msg.Properties["__TypeName"] as string),
                                                         GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name, null, -1, -1, null, -1, null,
                                                         "Asynchronous .NET Remoting invocaiton is being initiated.");

                message.ITransportHeaders[Message.TransportHeadersInvocationTarget] = msg.Properties["__Uri"] as string;
                message.ITransportHeaders[Message.TransportHeadersMethodName]       = BinaryLogWriter.ParseInvocationMethod(msg.Properties["__MethodName"] as string, msg.Properties["__TypeName"] as string);

                binaryLogWriter.WriteEvent(LogCategory.MessageProcessing, "GenuineTcpClientTransportSink.AsyncProcessRequest",
                                           LogMessageType.MessageRequestInvoking, null, message, message.Recipient,
                                           null,
                                           GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
                                           null, null, -1,
                                           GenuineUtility.TickCount, 0, 0, null, null, null, null,
                                           "The .NET Remoting asynchronous invocation is being initiated.");
            }

            // register the response handler
            AsyncSinkStackResponseProcessor asyncSinkStackResponseProcessor = null;

            if (!message.IsOneWay)
            {
                asyncSinkStackResponseProcessor = new AsyncSinkStackResponseProcessor(iTransportContext, message, sinkStack);
                iTransportContext.IIncomingStreamHandler.RegisterResponseProcessor(message.MessageId, asyncSinkStackResponseProcessor);
            }

            try
            {
                // and try to send the message
                iTransportContext.ConnectionManager.Send(message);
            }
            catch (Exception ex)
            {
                asyncSinkStackResponseProcessor.DispatchException(ex);
                throw;
            }
        }