It's 2008. Where's my flying car? RSS 2.0
 Monday, January 02, 2006

I recently needed a TCP port-forwarder that sits on a socket connection and monitors it. My concrete use-case is that I need to front the backend-server of my TV application with such a port forwarder in order to create live-TV streaming sessions as soon as a client requests them and also tears them down shortly after the client disconnects so that the session doesn’t need to time out and blocks the tuner until then. The backend also requires that I do a periodical “keep-alive” ping every 30-40 seconds, which isn’t a very practical requirement for some of my client scenarios. Therefore, I needed, generally speaking, something that would sit between the client and the backend server, monitors the data stream and would let me run some code (set up the live session and start the keep-alive timer) when I get a new client connection and just before I connect through to the target and which would let me run some code (shut down the session and stop the keep-alive) as soon as the connection is torn down.

Since, I didn’t find one (or was too blind or too lazy, you know how that goes), I wrote one. It’s a fully asynchronous TcpListener/TcpClient based implementation, it’s fast and stable enough for my purposes and it might or might not be for yours, it has a bit of tolerance for targets that don’t accept a connection on the first try, and you can hook up events to “before target connect” and “after target disconnect”. Since all the bytes fly by, you can instrument the thing further or monitor the stream as you like.  

The code is pretty straightforward, even though the asynchronous calls/callbacks admittedly make the execution paths in the implementation a bit challenging to follow, and should not require much further explanation. You construct an instance of TcpPortForwader passing the local port and the target port and host to forward to, call Start() and the listener starts listening. Stop() stops the listener. You can call Start() from any thread; the listener will implicitly use thread-pool threads to run on its own. Hook up the events and they are being raised. Simple enough. Download below.

Download: TcpPortForwarder.zip

Monday, January 02, 2006 3:08:46 AM (Pacific Standard Time, UTC-08:00)  #    Comments [1] - Trackback
CLR

Part 1, Part 2, Part 3, Part 4, Part 5

I threw a lot of unexplained code at you in Part 5 and that wasn’t really fair.

The PoxEncoder class is a replacement for Indigo’s default TextMessageEncoder class that’s used by the HTTP transport unless you explicitly configure something different. Indigo comes with three built-in encoders, namely:

·         The TextMessageEncoder serializes Indigo’s internal Message into SOAP 1.1 or SOAP 1.2 envelopes using (applies only to the latter) the desired character encodings (UTF-8, UTF-16, etc.) and of course it also deserializes incoming SOAP envelopes into the Indigo representation.

·         The MtomMessageEncoder serializes messages into SOAP 1.2 messages as specified by the MTOM specification, which allows for a much more compact transmission of binary-heavy SOAP envelopes than if you were simply using base64Binary encoded element data. MTOM is a good choice whenever the size of binary content in a SOAP envelope far exceeds the size of the rest of the data. Your mileage may vary, so that’s a thing to measure carefully unless it’s blatantly obvious such as in the case of writing a service for a digital imaging library.

·         The BinaryMessageEncoder serializes messages into SOAP 1.2 envelopes, but does so in a very compact binary format that preserves the XML information set, but is not at all like XML text. The gist of the binary encoding is the assumption that if both communicating parties are implemented with Indigo and share the same contract, the metadata existing at both ends reduces the hints that need to go on the wire. In other words: The binary encoding doesn’t need to throw all  these lengthy XML tag names and namespace names explicitly onto the wire, but can refer to them by pointing to a dictionary that’s identically constructed on both ends. The binary encoding in Indigo is a bit like the modern-day, loosely coupled grand-child of NDR and “midl.exe /Oicf” if you like. What’s important to note about this encoding is that its primary design goal is performance and interoperability is in fact a non-goal. The BinaryMessageEncoder assumes Indigo endpoints. If you don’t like that, you can always use the text encoding, which is designed for interoperability.

Our PoxEncoder here differs from all three Indigo encoders in that it does specifically not serialize SOAP messages, but rather just the body contents of a Message.

In order for you to understand what’s happening here, I’ll pick the most relevant methods and explain them in detail. We will start with the Initialize() method that is invoked by all three constructor overloads:

/// <summary>
///
Initializes common properties of the encoder.
/// </summary>
private void Initialize()
{
  if (this.MessageVersion.Envelope == EnvelopeVersion.Soap12)
  {
    // set the aprorpiate media type for SOAP 1.2
     this. mediaType = "application/soap+xml";
  }
  else if (this.MessageVersion.Envelope == EnvelopeVersion.Soap11)
  {
    // set the appropriate media type for SOAP 1.1
     this. mediaType = "text/xml";
  }
  // compose the content type from charset and media type
  this. contentType = string.Format(CultureInfo.InvariantCulture, "{0}; charset={1}", mediaType, textEncoding.WebName);
}

It is required for each MessageEncoder-derived class to implement the abstract properties MediaType, ContentType, and MessageVersion, and therefore we have to initialize the backing fields for these properties properly and return meaningful values even though the PoxEncoder is exactly the “anti-SOAP” encoder. The message version specified in the encoder is relevant for Indigo higher up on the stack, because it needs to know what rules and constraints apply to Message instances as they are constructed and processed. The content type and media types are required by the transports so that they know what content and/or media type to specify as metadata in their transport frame (eg. the Content-Type header in HTTP). If we initialize the encoder with the Soap12 message version, it will consequently report the application/soap+xml media type, even though the encoder doesn’t ever write such envelopes to the wire. You might consider that a bug in the PoxEncoder and you might be right, but it doesn’t really matter. Because any methods can return all sorts of payloads, we will override the content-type on the message-level so that this information has really no effect. I do need to clean this up a little. Later.

Now let’s look at the parts that actually do the work. I will start with the two WriteMessage overloads.

The first overload’s signature is
     public override ArraySegment<byte> WriteMessage(Message msg, int maxMessageSize, BufferManager bufferManager, int messageOffset)
and is invoked by the transport whenever a message must be wire-encoded and the output transfer mode is set to TransferMode.Buffered or TransferMode.StreamedRequest (which implies a buffered response). The second overload’s signature is
    public override void WriteMessage(Message msg, System.IO.Stream stream)
and is invoked by the transport whenever a message must be wire-encoded and the output transfer mode is set of TransferMode.Streamed or TransferMode.StreamedResponse (which implies a streamed response).

The transfer-mode property is configurable on all of the pre-built HTTP bindings and on the <httpTransport> binding element. “Buffered” encoding means that the entire message is encoded at once and written into a buffer, which is then given to the the transport for sending. “Streamed” encoding means that the message is pushed into to a stream, whereby the stream is typically immediately layered directly over the transport. That means that whenever our encoder writes data to that stream, it is immediately pushed to the remote communication partner. The “streamed” mode is the optimal choice for sending very large messages that are, for instance, too big to be reasonably handled as a single memory block. The buffered mode is better (and faster) for compact messages. I’ll dissect the buffered variant first:

public override ArraySegment<byte> WriteMessage(Message msg, int maxMessageSize, BufferManager bufferManager, int messageOffset)
{
   if (msg.IsEmpty)
   {
      // if the message is empty (no body defined) the result is an empty
      // byte array.
      byte[] buffer = bufferManager.TakeBuffer(maxMessageSize);
      return new ArraySegment<byte>(buffer, 0, 0);
   } 

If the message is empty (that means: the body is empty), we request a buffer from the buffer manager and return an empty slice of that buffer, because this encoder’s output is “nothing” if the body is empty.The BufferManager is an Indigo helper class that manages a pool of pre-allocated buffers and serves to optimize memory management by avoiding the allocation and the discarding of buffers for every message. And encoder should therefore use the buffer manager argument and use it to obtain the buffers backing the array segment that is to be returned. Once the message has been handled by the transport, the transport will return the buffer into the pool.

   else
   {
      // check RawBinary bit in the message property
          bool rawBinary = false;
          if (msg.Properties.ContainsKey(PoxEncoderMessageProperty.Name))
      {
         rawBinary = ((PoxEncoderMessageProperty)msg.Properties[PoxEncoderMessageProperty.Name]).RawBinary;
      }

If the message is not empty (we have a body), we check whether there is a PoxEncoderMessageProperty present in the message. This property is a plain CLR class that is part of my extensions and has two significant properties: Name is a static, constant string value used as the key for the message properties collection and RawBinary is a Boolean instance value that contains and indicator for whether the encoder shall encode the data as XML or as raw binary data. The Message property collection is a simple dictionary of objects keyed by strings. The properties allow application-level code to interact with infrastructure-level code in the way illustrated by this property. Whenever I want the encoder to use its “raw binary” mode, I add this property to the message and the encoder can pick up the information.

      ArraySegment<byte> retval = new ArraySegment<byte>();
      byte[] buffer = bufferManager.TakeBuffer(maxMessageSize);
      if (!rawBinary)
      {
         // If we're rendering XML data, we construct a memory stream
         // over the output buffer, layer an XMLDictionaryWriter on top of it
         // and have the message write the body content into the buffer as XML.
         // The buffer is then wrapped into an array segment and returned.
         MemoryStream stream = new MemoryStream(buffer);
         XmlWriterSettings settings = new XmlWriterSettings();
         settings.OmitXmlDeclaration = true;
         settings.Indent = true;
         settings.Encoding = this. textEncoding;
         XmlWriter innerWriter = XmlWriter.Create(stream, settings);
         XmlDictionaryWriter writer = XmlDictionaryWriter.CreateDictionaryWriter(innerWriter, false);
         msg.WriteBodyContents(writer);
         writer.Flush();
         retval = new ArraySegment<byte>(buffer, 0, (int)stream.Position);
      }

Next we take a buffer from the buffer manager and if we’re not in “raw binary” mode, we’ll construct a memory stream over the buffer, construct an XmlDictionaryWriter over that stream and ask the message to render its “body contents” into the writer and therefore into the memory stream and into the buffer. The “body contents” of a message is what would be the child nodes of the <soap:Body> element, if we were using that (but we don’t). Once the body contents have been written, we flush the writer to make sure that all buffered data is committed into the underlying stream and then construct the return value as an array segment over the buffer with the length of the bytes written to the stream.

      else
      {
         // If we're rendering raw binary data, we grab at most 'buffer.Length'
         // bytes from the binary content of the base64Binary element (if that
         // exists) and return the result wrapped into an array segment.
         XmlDictionaryReader dictReader = msg.GetReaderAtBodyContents();
         if (dictReader.NodeType == XmlNodeType.Element &&
            dictReader.LocalName == "base64Binary")
         {
            if (dictReader.Read() && dictReader.NodeType == XmlNodeType.Text)
            {
               int size = dictReader.ReadContentAsBase64(buffer, 0, buffer.Length);
               retval = new ArraySegment<byte>(buffer, 0, size);
            }
         }
      }
      return retval;
   }
}
 

If the “raw binary” mode is to be used, we are making a bit of an assumption inside the encoder. The assumption is that the body content consists of a single element named “base64Binary” and that its content is just that: base64 binary encoded content. That is of course the other side of the PoxBase64XmlStreamReader trick I explained in Part 5. For binary data we simply assume here that the body reader is our wrapper class and this is how arbitrary binary data is smuggled through the Indigo infrastructure. The array segment to be returned is constructed by reading the binary data into the buffer and setting the array segment length to the number of bytes we could get from the element content.

The streamed version of WriteMessage is quite different:

public override void WriteMessage(Message msg, System.IO.Stream stream)
{
    try
    {
        if (!msg.IsEmpty)
        {
            // check RawBinary bit in the message property
            bool rawBinary = false;
            if (msg.Properties.ContainsKey(PoxEncoderMessageProperty.Name))
            {
                rawBinary = ((PoxEncoderMessageProperty)msg.Properties[PoxEncoderMessageProperty.Name]).RawBinary;
            }
            if (!rawBinary)
            {
                // If we're rendering XML, we layer an XMLDictionaryWriter over the
                // output stream and have the message render its body content into
                // that writer and therefore onto the stream.
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.OmitXmlDeclaration = true;
                settings.Indent = true;
                settings.Encoding = this. textEncoding;
                XmlWriter innerWriter = XmlWriter.Create(stream, settings);
                XmlDictionaryWriter writer = XmlDictionaryWriter.CreateDictionaryWriter(innerWriter, false);
                msg.WriteBodyContents(writer);
                writer.Flush();
            }

The first significant difference is that if we’re using streams, we will simply ignore empty messages and do nothing with them. In streaming mode, the transport will do any setup work required for  sending a message before invoking the encoder and ready the output network stream so that the encoder can write to it. When the encoder returns, the transport considers the write action done. So if we don’t write to the output stream, there’s no payload data hitting the wire and that happens to be what we want.

If we have data and we’re not in “raw binary” mode, the encoder will construct an XmlDictionaryWriter over the supplied stream and have the message write its body contents to it. That’s all.

            Else
            {
                // If we're rendering raw binary data, we grab chunks of at most 1MByte
                // from the 'base64Binary' content element (if that exists) and write them
                // out as binary data to the output stream. Chunking is done, because we
                // have to assume that the body content is arbitrarily large. To optimize the
                // behavior for large streams, we read and write concurrently and swap buffers.
                XmlDictionaryReader dictReader = msg.GetReaderAtBodyContents();
                if (dictReader.NodeType == XmlNodeType.Element && dictReader.LocalName == "base64Binary")
                {
                    if (dictReader.Read() && dictReader.NodeType == XmlNodeType.Text)
                    {
                        byte[] buffer1 = new byte[1024*1024], buffer2 = new byte[1024*1024];
                        byte[] readBuffer = buffer1, writeBuffer = buffer2;
                       
                        int bytesRead = 0;
                        // read the first chunk into the read buffer
                        bytesRead = dictReader.ReadContentAsBase64(readBuffer, 0, readBuffer.Length);
                        do
                        {
                            // the abort condition for the loop is that we can't read
                            // any more bytes from the input because the base64Binary element is
                            // exhausted.
                            if (bytesRead > 0 )
                            {
                                // make the last read buffer the write buffer
                                writeBuffer = readBuffer;
                                // write the write buffer to the output stream asynchronously
                                IAsyncResult result = stream.BeginWrite(writeBuffer, 0, bytesRead,null,null);
                                // swap the read buffer
                                readBuffer = (readBuffer == buffer1) ? buffer2 : buffer1;
                                // read a new chunk into the 'other' buffer synchronously
                                bytesRead = dictReader.ReadContentAsBase64(readBuffer, 0, readBuffer.Length);
                                // wait for the write operation to complete
                                result.AsyncWaitHandle.WaitOne();
                                stream.EndWrite(result);
                            }
                        }
                        while (bytesRead > 0);
                    }
                }
            }
        }
    }
    catch
    {
        // the client may disconnect at any time, so that's an expected exception and absorbed.
    }
}

In streamed “raw binary” mode things get a bit more complicated. Under these circumstances we assume that the output we are sending is HUGE. The use-case I had in mind when I wrote this is the download of multi-GByte video recordings. Therefore I construct two 1MByte buffers that are used in turns to read a chunk of data from the source body reader (for which we make the same content assumption as for the buffered case: This is believed to be a PoxBase64XmlStreamReader compatible infoset) and asynchronously push the read data into the output stream.

Because it may take a while to get a huge data stream to the other side, a lot of things can happen to the network connection during that time. Therefore the encoder fully expects that the network connection terminates unexpectedly. If that happens, we’ll catch and absorb the network exception and happily return to the caller as if we’re done.

Compared to all the complexity of the WriteMessage  overloads, the respective ReadMessage methods look fairly innocent, simple, and similar:

/// <summary>
///
Reads an incoming array segment containing a message and
/// wraps it with a buffered message. The assumption is that the incoming
/// data stream is <i>not</i> a SOAP envelope, but rather an unencapsulated
/// data item, may it be some raw binary, an XML document or HTML form
/// postback data. This method is called if the inbound transfer mode of the
/// transport is "buffered".
/// </summary>
///
<param name="buffer">Buffer to wrap</param>
///
<param name="bufferManager">Buffer manager to help with allocating a copy</param>
///
<returns>Buffered message</returns>
public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager)
{
   return new PoxBufferedMessage(buffer, bufferManager);
}

/// <summary>
///
Reads an incoming stream containing a message and
/// wraps it with a streamed message. The assumption is that the incoming
/// data stream is <i>not</i> a SOAP envelope, but rather an unencapsulated
/// data item, may it be some raw binary, an XML document or HTML form
/// postback data. This method is called if the inbound transfer mode of the
/// transport is "streamed".
/// </summary>
///
<param name="stream">Input stream</param>
///
<param name="maxSizeOfHeaders">Maximum size of headers in bytes</param>
///
<returns>Stream message</returns>
public override Message ReadMessage(System.IO.Stream stream, int maxSizeOfHeaders)
{
   return new PoxStreamedMessage(stream, maxSizeOfHeaders);
}

Both variants take the raw incoming data (whatever it is) and hand it to the PoxStreamMessage class or PoxBufferedMessage class that adopt the buffer or stream as their body content, respectively. I’ll explain those in Part 7.

Happy New Year!

Monday, January 02, 2006 12:51:43 AM (Pacific Standard Time, UTC-08:00)  #    Comments [0] - Trackback
Indigo
 Friday, December 30, 2005

My little “TV anywhere“ project makes a bit more sense now, does it? Because Sabine and I will more than likely find ourselves somewhere in the Seattle area by mid-2006 (I’ll be telecommuting and “long-haul shuttling” for a while) and we are both big time German football (as in “soccer”) fans, we just need to fix a problem.

And I am doing it just because I can, of course. The whole Indigo REST/POX series here on the blog does nothing more than describe all the WCF extensions I wrote to build my personal TV server. The first screenshot here on the right shows the current state of things as it shows up in Media Player. The UI is a Windows Media Player hosted AJAX app with EPG data in tooltips as I hover over the channel icons, I can schedule recordings with a single mouse click and I have access to all my recordings on a separate channel or just on the channel that’s currently being watched. But that’s just the “Clemens on the road” version of this.

The other front-end is the “far away at home” version of it and that looks like the screen shots on the left. Meanwhile I have an AJAX front-end that’s built for Windows XP Media Center Edition (MCE) and snaps right into the MCE experience. My dad will get the PC that sits here in my living room and host it at his house behind an upgraded DSL line and my (to be bought) MCE machine over in Seattle will connect to it and give me remote (control) access to the 35 cable channels over here. That’s the plan.

The backend is and remains Beyond TV, because it’s a very flexible, programmable and – most importantly – streaming enabled TV engine. It’s an unlikely couple, but I decided that Beyond TV and MCE should have a wedding on my boxes. Works well.

The immediate question is of course still “Looks cool, when can I have it?” The issue is that this is a lot more of a tricky story than DasBlog, because I am depending on an existing backend software with its own, a bit limiting EULA, I am relying on a foundation that isn’t even released (WCF) and I am a lot more worried about the support situation, because setting this up correctly with Beyond TV alongside MCE and my service is … ummm… only something for folks who have no fear of the gates of Mordor and beyond. We’ll see what I can do…

Friday, December 30, 2005 3:08:21 PM (Pacific Standard Time, UTC-08:00)  #    Comments [0] - Trackback

 Thursday, December 29, 2005

Part 1, Part 2, Part 3, Part 4

POX means “plain old XML” and I’ve also heard a definition saying that “POX is REST without the dogma”, but that’s not really correct. POX is not really well defined, but it’s clear that the “plain” is the focus and that means typically that folks who talk about “POX web services” explicitly mean that those services don’t use SOAP. You could see POX as an antonym for SOAP.

The design of Indigo (WCF) assumes that all messages that go onto the wire and come from the wire have a shape that is aligned with SOAP. That means that they have a “body” containing the user-defined message payload and a “header” section that contains the out-of-band metadata that helps getting the message from one place to the next, possibly through a chain of intermediaries. Most of the Indigo binding elements and their implementations also assume that those metadata elements (headers) conform to their respective WS-* standard that they are dealing with.

However, Indigo isn’t hard-wired to a specific envelope format. The default “encoders” that are responsible for turning a message into data stream (or a data package) that a transport can throw down a TCP socket or into a message queue (or whatever else) and which are likewise responsible for picking up the data from the wire to turn them into Message objects have two envelope formats baked in: SOAP 1.1 and SOAP 1.2. But that doesn’t mean that you have to use those. If your envelope format were different (there seem to be thousands, I’ll name AdsML [spec] as an example) and that’s what you want to use on the wire, you can assemble a binding that will compose an Indigo transport with your encoder. Moving away from SOAP means, though, that you can’t use the standard implementations of capabilities such as message-level security, reliable delivery, and transaction flow, because all of these are built on the assumption that you are exchanging WS-* headers with the other party and all of these specs depend on the SOAP information model. But if there are comparable specifications that come with your envelope format you can of course write Indigo extensions that you can configure into a binding just like you can compose the default binding elements. It’d be a lot of work to do that, but you’d still benefit greatly from the Indigo architecture per-se.

When we want to use a REST/POX model, our envelope format is quite simple: We don’t really have an envelope.

The idea of POX is that there’s only payload and that out-of-band metadata is unnecessary fluff. The idea of REST is that there is already and appropriate place for out-of-band metadata and that’s the HTTP headers.

In order to make REST/POX work, we therefore need to replace the Indigo default encoder with an encoder that fulfills these requirements:

1.      Extract the message body XML content of any outbound message and format it for the wire as-is and without a SOAP envelope around it and

2.      Accept an arbitrary inbound XML data and wrap it into a Message-derived class so that Indigo can handle it.

Since the use-case in whose context I’ve developed these extensions is a bit more far reaching than POX, but I indeed want to support RESTful access to any data including multi-GByte unencapsulated MPEG recordings I make on my Media PC, I’ve broadened these two requirements a bit and left out the “XML” constraint:

1.      Extract the message body XML content of any outbound message and format it for the wire as-is and without a SOAP envelope around it and

2.      Accept an arbitrary inbound XML data and wrap it into a Message-derived class so that Indigo can handle it.

XML aka POX is an interesting content-type to throw around, but it’s by no means the only one and therefore let’s not restrict ourselves too much here. Any content is good.

But then again, Indigo is assuming that all messages flowing through its channels contain XML payloads and therefore we’ve got a bit of a nut to crack when we want to use Indigo for arbitrary, non-XML payloads of arbitrary size. Luckily, XML is just an illusion.

The Indigo Message holds the message body content inside an XmlDictionaryReader (which is an optimized derivation of the well-known XmlReader). To construct a message, you can walk up to the static Message.CreateMessage(string action, XmlDictionaryReader reader) factory method and pass the readily formatted body content as a reader object and the message will happily adopt it. But can we use the XmlReader to smuggle arbitrary binary content into the message so that our own encoder can later unwrap it and put it onto the wire in whatever raw binary format we like? Sure we can! The class below may look a bit like an evil hack, but it’s a perfectly legal construct:

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Schema;

namespace newtelligence.ServiceModelExtensions
{
   public class PoxBase64XmlStreamReader :
XmlTextReader
   {
      private const string xmlEnvelopeString =
           "<base64Binary xmlns:xsi=\"" + XmlSchema.InstanceNamespace + "\" " +
           "xmlns:xsd=\"" + XmlSchema.Namespace + "\" " +
           "xsi:type=\"xsd:base64Binary\">placeholder</base64Binary>";
      Stream innerStream;

      ///
<summary>
      /// Initializes a new instance of the <see cref="T:PoxBase64XmlStreamReader"/>
class.
      ///
</summary>
      /// <param name="stream">The stream.
</param>
      public PoxBase64XmlStreamReader(Stream stream)
         : base(new StringReader(xmlEnvelopeString))
      {
         innerStream = stream;
      }

      ///
<summary>
      ///
Gets The Common Language Runtime (CLR) type for the current node.
      ///
</summary>
      ///
<value></value>
      /// <returns>The CLR type that corresponds to the typed value of the node. The default is System.String.
</returns>
      public override Type ValueType
      {
         
get
         {
            if (NodeType == XmlNodeType.Text && base.Value == "placeholder")
            {
               return typeof(Byte[]);
            }
            
else
            {
               return base.ValueType;
            }
         }
      }
   
      ///
<summary>
      ///
Gets the text value of the current node.
      ///
</summary>
      public override string Value
      {
         
get
         {
            if (NodeType == XmlNodeType.Text && base.Value == "placeholder")
            {
               BinaryReader reader = new BinaryReader(innerStream);
               return Convert.ToBase64String(reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position)));
            }
            return base.Value;
         }
      }

      ///
<summary>
      ///
Reads the content and returns the Base64 decoded binary bytes.
      ///
</summary>
      /// <param name="buffer">The buffer into which to copy the resulting text. This value cannot be null.
</param>
      /// <param name="index">The offset into the buffer where to start copying the result.
</param>
      /// <param name="count">The maximum number of bytes to copy into the buffer. The actual number of bytes copied is returned from this method.
</param>
      ///
<returns>
      ///
The number of bytes written to the buffer.
      ///
</returns>
      public override int ReadContentAsBase64(byte[] buffer, int index, int count)
      {
         if (NodeType == XmlNodeType.Text && base.Value == "placeholder")
         {
            return innerStream.Read(buffer, index, count);
         }
         
else
         {
            return base.ReadContentAsBase64(buffer, index, count);
         }
      }
   }
}

The PoxBase64XmlStreamReader is a specialized XML reader reading a fixed info-set constructed from a string that has a “placeholder” in whose place the content of a wrapped data stream is returned “as base64 encoded content”. Of course that latter statement is hogwash. The data is never encoded in base64 anywhere. But the consumer of the reader thinks that it is and that’s really good enough for us here. The XmlReader creates the illusion that the wrapped data stream were the “text” node of a base64Binary typed element and if that’s what the client wants to believe, we’re happy.  The implementation trick here is of course very simple. As long as the reader isn’t hitting the text node with the “placeholder” all work is being delegated to the base class. Once we arrive at that particular node, we change tactics and return the data type (byte[]) and the content of the wrapped stream instead of the “placeholder” string. After that we continue delegating to the base class. If the client asks for the Value of the text node, we are returning a base64 encoded string representation of the wrapped stream which might end up being pretty big. However, if the client is a bit less naïve about the content, it will figure that the data type is byte[] and therefore retrieve the data in binary chunks through the ReadContentAsBase64() method. Let’s assume that the client will be that clever.

It doesn’t take too much imagination talent to do so, because I’ve got the client right here. I used Doug Purdy’s PoxEncoder that he showed at PDC05 as a basis for this and extended it (quite) a bit:

using System;
using System.IO;
using System.Xml;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Design;
using System.Runtime.CompilerServices;
using System.ServiceModel.Configuration;
using System.Configuration;
using System.Globalization;
using System.Xml.Schema;
using System.Diagnostics;

namespace newtelligence.ServiceModelExtensions
{
    /// <summary>
    /// This class is a wire-format encoder for System.ServiceModel that renders
    /// only the content (body) of a <see cref="T:Message"/> onto the wire, but not
    /// the surrounding SOAP message elements such as the enevlope, the headers or
    /// the body element. Likewise, the encoder expects input to be in 'raw', unwrapped
    /// form and will wrap it into a message for processing by the System.ServiceModel
    /// infrastructure.
    /// </summary>
    public class PoxEncoder : MessageEncoder
   {
      string contentType;
      string mediaType;
      Encoding textEncoding;
      MessageVersion messageVersion;

      /// <summary>
      /// Creates a new instance of PoxEncoder
      /// </summary>
      public PoxEncoder()
      {
          messageVersion = MessageVersion.Soap11Addressing1;
          textEncoding = Encoding.UTF8;
         Initialize();
      }

      /// <summary>
      /// Creates a new instance of PoxEncoder
      /// </summary>
      /// <param name="messageVersion"></param>
      public PoxEncoder(MessageVersion messageVersion)
      {
         this. messageVersion = messageVersion;
          textEncoding = Encoding.UTF8;
         Initialize();
      }


      /// <summary>
      /// Creates a new instance of PoxEncoder
      /// </summary>
      /// <param name="textEncoding"></param>
      /// <param name="messageVersion"></param>
      public PoxEncoder(Encoding textEncoding, MessageVersion messageVersion)
      {
         this. textEncoding = textEncoding;
         this. messageVersion = messageVersion;
         Initialize();
      }

        /// <summary>
        /// Initializes common properties of the encoder.
        /// </summary>
      private void Initialize()
      {
         if (this.MessageVersion.Envelope == EnvelopeVersion.Soap12)
         {
                // set the aprorpiate media type for SOAP 1.2
            this. mediaType = "application/soap+xml";
         }
         else if (this.MessageVersion.Envelope == EnvelopeVersion.Soap11)
         {
                // set the appropriate media type for SOAP 1.1
            this. mediaType = "text/xml";
         }
            // compose the content type from charset and media type
         this. contentType = string.Format(CultureInfo.InvariantCulture, "{0}; charset={1}", mediaType, textEncoding.WebName);
      }

        /// <summary>
        /// Gets the content type for the encoder instance
        /// </summary>
      public override string ContentType
      {
         get
         {
            return contentType;
         }
      }

        /// <summary>
        /// Gets the media type for the encoder instance
        /// </summary>
      public override string MediaType
      {
         get
         {
            return mediaType;
         }
      }

        /// <summary>
        /// Gets an indicator for whether a given input content type is
        /// supported.
        /// </summary>
        /// <param name="contentType">ContentType</param>
        /// <returns>Indicates whether the content type is supported</returns>
        /// <remarks>
        /// TODO: This currently returns 'true' for all content types because the
        /// encoder isn't locked down in features yet and this easier to debug.
        /// The plan is to support at least: application/x-www-form-urlencoded,
        /// text/xml, application/soap+xml
        /// </remarks>
      public override bool IsContentTypeSupported(string contentType)
      {
         return true;
      }

        /// <summary>
        /// Gets the supported message version of this instance
        /// </summary>
      public override MessageVersion MessageVersion
      {
         get
         {
            return messageVersion;
         }
      }

        /// <summary>
        /// Reads an incoming array segment containing a message and
        /// wraps it with a buffered message. The assumption is that the incoming
        /// data stream is <i>not</i> a SOAP envelope, but rather an unencapsulated
        /// data item, may it be some raw binary, an XML document or HTML form
        /// postback data. This method is called if the inbound transfer mode of the
        /// transport is "buffered".
        /// </summary>
        /// <param name="buffer">Buffer to wrap</param>
        /// <param name="bufferManager">Buffer manager to help with allocating a copy</param>
        /// <returns>Buffered message</returns>
        public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager)
      {
         return new PoxBufferedMessage(buffer, bufferManager);
      }

        /// <summary>
        /// Transforms an incoming message into a raw byte array that a transport can
        /// literally put on the wire as it is returned. This method is called if the outbound
        /// transfer mode of the transport is "buffered".
        /// </summary>
        /// <param name="msg">Input message</param>
        /// <param name="maxMessageSize">Maximum message size to be rendered</param>
        /// <param name="bufferManager">Buffer manager to optimize buffer allocation</param>
        /// <param name="messageOffset">Offset into the message to render.</param>
        /// <returns>Array segment containing the binary data to be put onto the wire by the transport.</returns>
        /// <remarks>
        /// <para>This method is the "secret sauce" of the the PoxEncoder. Instead of encoding the
        /// message in its entirety, this encoder will unwrap the message body and toss out
        /// the envelope and all headers. The resulting "raw" message body (everything inside
        /// and not including soap:Body) will be written out to the transport.</para>
        /// <para>The encoder has an optional, "out of band" argument that is flowing into it
        /// as part of the message's Properties. By adding a <see cref="T:PoxEncoderMessageProperty"/>
        /// to the <see cref="Message.Properties"/> and setting its <see cref="PoxEncoderMessageProperty.RawBinary"/>
        /// property to 'true', you can switch the encoder into its 'raw binary' mode.</para>
        /// <para> In 'raw binary' mode, the encoder expects that the only child of the message
        /// body element is an element with a local name of "base64Binary" containing base64 encoded
        /// binary data. If that is the case, the encoder will read the content of that element
        /// and return it (not the XML wrapper) to the transport in binary form. If the content does
        /// not comply with this requirement, an empty array is returned.
        /// </para>
        /// </remarks>
      public override ArraySegment<byte> WriteMessage(Message msg, int maxMessageSize, BufferManager bufferManager, int messageOffset)
      {
         if (msg.IsEmpty)
         {
            // if the message is empty (no body defined) the result is an empty
            // byte array.
            byte[] buffer = bufferManager.TakeBuffer(maxMessageSize);
            return new ArraySegment<byte>(buffer, 0, 0);
         }
         else
         {
            // check RawBinary bit in the message property
                bool rawBinary = false;
                if (msg.Properties.ContainsKey(PoxEncoderMessageProperty.Name))
            {
               rawBinary = ((PoxEncoderMessageProperty)msg.Properties[PoxEncoderMessageProperty.Name]).RawBinary;
            }

            ArraySegment<byte> retval = new ArraySegment<byte>();
            byte[] buffer = bufferManager.TakeBuffer(maxMessageSize);
            if (!rawBinary)
            {
               // If we're rendering XML data, we construct a memory stream
               // over the output buffer, layer an XMLDictionaryWriter on top of it
               // and have the message write the body content into the buffer as XML.
               // The buffer is then wrapped into an array segment and returned.
               MemoryStream stream = new MemoryStream(buffer);
               XmlWriterSettings settings = new XmlWriterSettings();
               settings.OmitXmlDeclaration = true;
               settings.Indent = true;
               settings.Encoding = this. textEncoding;
               XmlWriter innerWriter = XmlWriter.Create(stream, settings);
               XmlDictionaryWriter writer = XmlDictionaryWriter.CreateDictionaryWriter(innerWriter, false);
               msg.WriteBodyContents(writer);
               writer.Flush();
               retval = new ArraySegment<byte>(buffer, 0, (int)stream.Position);
            }
            else
            {
               // If we're rendering raw binary data, we grab at most 'buffer.Length'
               // bytes from the binary content of the base64Binary element (if that
               // exists) and return the result wrapped into an array segment.
               XmlDictionaryReader dictReader = msg.GetReaderAtBodyContents();
               if (dictReader.NodeType == XmlNodeType.Element &&
                  dictReader.LocalName == "base64Binary")
               {
                  if (dictReader.Read() && dictReader.NodeType == XmlNodeType.Text)
                  {
                     int size = dictReader.ReadContentAsBase64(buffer, 0, buffer.Length);
                     retval = new ArraySegment<byte>(buffer, 0, size);
                  }
               }
            }
            return retval;
         }
      }

        /// <summary>
        /// Reads an incoming stream containing a message and
        /// wraps it with a streamed message. The assumption is that the incoming
        /// data stream is <i>not</i> a SOAP envelope, but rather an unencapsulated
        /// data item, may it be some raw binary, an XML document or HTML form
        /// postback data. This method is called if the inbound transfer mode of the
        /// transport is "streamed".
        /// </summary>
        /// <param name="stream">Input stream</param>
        /// <param name="maxSizeOfHeaders">Maximum size of headers in bytes</param>
        /// <returns>Stream message</returns>
      public override Message ReadMessage(System.IO.Stream stream, int maxSizeOfHeaders)
      {
         return new PoxStreamedMessage(stream, maxSizeOfHeaders);
      }

        /// <summary>
        /// Transforms an incoming message into a stream that a transport can
        /// literally put on the wire as it is filled. This method is called if the outbound
        /// transfer mode of the transport is "streamed".
        /// </summary>
        /// <param name="msg">Input message</param>
        /// <param name="stream">Stream to write to</param>
        /// /// <remarks>
        /// <para>This method is the "secret sauce" of the the PoxEncoder. Instead of encoding the
        /// message in its entirety, this encoder will unwrap the message body and toss out
        /// the envelope and all headers. The resulting "raw" message body (everything inside
        /// and not including soap:Body) will be written out to the transport.</para>
        /// <para>The encoder has an optional, "out of band" argument that is flowing into it
        /// as part of the message's Properties. By adding a <see cref="PoxEncoderMessageProperty"/>
        /// to the <see cref="Message.Properties"/> and setting its <see cref="PoxEncoderMessageProperty.RawBinary"/>
        /// property to 'true', you can switch the encoder into its 'raw binary' mode.</para>
        /// <para> In 'raw binary' mode, the encoder expects that the only child of the message
        /// body element is an element with a local name of "base64Binary" containing base64 encoded
        /// binary data. If that is the case, the encoder will read the content of that element
        /// and write it (not the XML wrapper) onto the stream in binary form and in at most
        /// 1MByte large chunks. If the content does not comply with this requirement, nothing is written.
        /// </para>
        /// </remarks>
        public override void WriteMessage(Message msg, System.IO.Stream stream)
        {
            try
            {
                if (!msg.IsEmpty)
                {
                    // check RawBinary bit in the message property
                    bool rawBinary = false;
                    if (msg.Properties.ContainsKey(PoxEncoderMessageProperty.Name))
                    {
                        rawBinary = ((PoxEncoderMessageProperty)msg.Properties[PoxEncoderMessageProperty.Name]).RawBinary;
                    }

                    if (!rawBinary)
                    {
                        // If we're rendering XML, we layer an XMLDictionaryWriter over the
                        // output stream and have the message render its body content into
                        // that writer and therefore onto the stream.
                        XmlWriterSettings settings = new XmlWriterSettings();
                        settings.OmitXmlDeclaration = true;
                        settings.Indent = true;