2012年1月31日

[.Net] How to debug “There is an error in XML document (1,234)”

It drives me crazy when Xml serialization failed with “There is an error in XML document (some numbers)” error, the runtime won’t tell you which element when wrong and basically you have no choice but to check every elements to see if there is any significant issue.

There is a way to debug into such issue,

Since Xml serialization depends on runtime generated assembly to serialize/deserialize objects, first we need to gain access to the source code of that generated class. To do so, add the following section to your application configuration file. (web.config or app.config)

<configuration>
   <system.diagnostics>
      <switches>
         <add name="XmlSerialization.Compilation" value="1" />
      </switches>
   </system.diagnostics>
</configuration>


Compile and run the application, in XP system, you should be able to find .cs file under C:\documents and settings\[USER NAME]\local settings\temp, the file name should be like abcdef.cs. In Win7 system, the file should be under that folder, or some sub folders, make sure you find it.



Open the file and setup break points in the consumer class and you will be able to debug the generated class and we can see with our own eyes which element is causing issue.

2012年1月12日

[WCF]Maximum number of items that can be serialized or deserialized in an object graph is '65536'

I got this error while invoking a web service server with a WCF client.

This error message indicates that the data is too large and exceed max. serialize/deserialize object limit.

To resolve this, we need to modify maxItemsInObjectGraph attribute in <dataContractSerializer> on both client side and server side.

To accomplish this via xml configuration file, add the following lines on server web.config:

<serviceBehaviors>
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
</serviceBehaviors>


And on client



<endpointBehaviors>
<behavior name="somename">
<dataContractSerializer maxItemsInObjectGraph="2147483647"/> 
...


To accomplish this via code on the server:
foreach (IServiceBehavior behavior in selfHost.Description.Behaviors)
{
try
{
if(behavior is DataContractSerializerOperationBehavior){
((DataContractSerializerOperationBehavior)behavior).MaxItemsInObjectGraph = int.MaxValue;
}
}
catch { }
}


on the client:


foreach (OperationDescription operation in pipeFactory.Endpoint.Contract.Operations)
{
foreach (IOperationBehavior behavior in operation.Behaviors)
{
try
{
if(behavior is DataContractSerializerOperationBehavior){
((DataContractSerializerOperationBehavior)behavior).MaxItemsInObjectGraph = int.MaxValue;
}
}
catch { }
}
}



And Since my server is a traditional web service, I don’t need to modify server codes (at least for my case). 

About Me