Optimizing reading for the CustomTextMessageEncoder

Continuing the improvement of the CustomTextMessageEncoder (see this and this), this time I'll use the XmlDictionaryWriter instead of the XmlTextWriter whenever the character encoding is utf-8, utf-16 or Unicode.

To achieve this, all that's needed is to look into the character set part of the content type and act accordingly.

public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType)

{

    byte[] messageContents = new byte[buffer.Count];

    Array.Copy(buffer.Array, buffer.Offset, messageContents, 0, messageContents.Length);

    bufferManager.ReturnBuffer(buffer.Array);

 

    MemoryStream stream = new MemoryStream(messageContents);

    //return ReadMessage(stream, int.MaxValue);

    return ReadMessage(stream, int.MaxValue, contentType);

}

 

public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType)

{

    string charset = null;

    if (!string.IsNullOrEmpty(contentType))

    {

        System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(contentType);

        charset = ct.CharSet;

    }

    if ((!string.IsNullOrEmpty(charset)) && (charset.Equals(ValidatingUTF8.WebName, StringComparison.InvariantCultureIgnoreCase) || charset.Equals(ValidatingUTF16.WebName, StringComparison.InvariantCultureIgnoreCase) || charset.Equals(ValidatingBEUTF16.WebName, StringComparison.InvariantCultureIgnoreCase)))

    {

        XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(stream, XmlDictionaryReaderQuotas.Max);

        return Message.CreateMessage(reader, maxSizeOfHeaders, this.MessageVersion);

    }

    else

    {

        XmlReader reader = XmlReader.Create(stream);

        return Message.CreateMessage(reader, maxSizeOfHeaders, this.MessageVersion);

    }

}

Comments are closed.