private Message QpidToWcf(AmqpMessage amqpMessage)
        {
            if (amqpMessage == null)
            {
                return(null);
            }

            Message wcfMessage = null;

            byte[] managedBuffer = null;

            try
            {
                if (this.streamed)
                {
                    wcfMessage = this.encoder.ReadMessage(amqpMessage.BodyStream, int.MaxValue);
                }
                else
                {
                    int count = (int)amqpMessage.BodyStream.Length;
                    managedBuffer = this.bufferManager.TakeBuffer(count);
                    int nr = amqpMessage.BodyStream.Read(managedBuffer, 0, count);
                    ArraySegment <byte> bufseg = new ArraySegment <byte>(managedBuffer, 0, count);

                    wcfMessage = this.encoder.ReadMessage(bufseg, this.bufferManager);

                    // set to null for finally{} block, since the encoder is now responsible for
                    // returning the BufferManager memory
                    managedBuffer = null;
                }

                // This message will be discarded unless the "To" header matches
                // the WCF endpoint dispatcher's address filter (or the service is
                // AddressFilterMode=AddressFilterMode.Any).

                this.remoteAddress.ApplyTo(wcfMessage);

                if (amqpMessage.Properties != null)
                {
                    wcfMessage.Properties.Add("AmqpProperties", amqpMessage.Properties);
                }
            }
            catch (XmlException xmlException)
            {
                throw new ProtocolException(
                          "There is a problem with the XML that was received from the network. See inner exception for more details.",
                          xmlException);
            }
            catch (Exception e)
            {
                // TODO: logging
                Console.WriteLine("TX channel encoder exception " + e);
            }
            finally
            {
                // close the amqpMessage unless the body will be read at a later time.
                if (!this.streamed || wcfMessage == null)
                {
                    amqpMessage.Close();
                }

                // the handoff to the encoder failed
                if (managedBuffer != null)
                {
                    this.bufferManager.ReturnBuffer(managedBuffer);
                }
            }

            return(wcfMessage);
        }