KB: XML schema validation errors when Exchange Web Service requests and responses have invalid XML characters

…I recently submitted the following KB article for publication but wanted to get the content out. I will update this post when the KB article is published…

SYMPTOMS

Scenario 1

When you submit an Exchange Web Services request to Microsoft Exchange Server 2007 that contains invalid XML characters, you may get the following ErrorSchemaValidation exception response:

“The request failed schema validation: [character], hexadecimal value [value], is an invalid character.”

Scenario 2

When you submit an Exchange Web Services request to Microsoft Exchange Server 2007 that returns item properties in the response containing invalid XML characters using the Visual Studio auto-generated proxy classes, you may get the following InvalidOperationException exception:

”There is an error in XML document”

“[character] hexadecimal value [value], is an invalid character.”

CAUSE

It is possible for Exchange item properties to have values that contain characters outside the valid range in the XML specification which is defined here:

https://www.w3.org/TR/2000/WD-xml-2e-20000814#dt-character

When an Exchange Web Services client makes a request to retrieve that item property, the Exchange server encodes the property values to ensure the response is transmittable.  If this response is received by the client and subsequently validated against the XML schema, it will fail validation because of the invalid XML characters.

Conversely, if an Exchange Web Services client tries to send these characters in a request, even if they are encoded, the Exchange server will try and validate the request against the XML schema which will fail.

RESOLUTION

Scenario 1

There is no way to successfully post an Exchange Web Service request that contains invalid XML characters.  If you are updating a property’s value that contains invalid characters you must decide whether to replace or omit these characters.

Scenario 2

In order to read Exchange Web Service responses from Microsoft Exchange Server 2007 that contain invalid XML characters, you should skip XML validation. If you are using the Visual Studio auto-generated proxy classes for Exchange Web Services then you can create a special partial class which overrides the GetReaderForMessage method of the ExchangeServiceBinding class which turns XML validation off:

public partial class MyExchangeServiceBinding: ExchangeServiceBinding
{
    protected overrideXmlReader GetReaderForMessage(
        SoapClientMessage message,
        int bufferSize)
    {
        XmlReader retval = base.GetReaderForMessage(
            message,
            bufferSize);

        XmlTextReader xrt = retval asXmlTextReader;

        if(null!= xrt)
        {
            xrt.Normalization = false;
        }

        returnretval;
    }
}