WP7 QuickTip: Don’t believe everything you debug

I had an issue on a WP 7.0 app the other day that I spent several hours working on after Bing offered no help.  Its rare to find an exception that no one has blogged or posted about.  So I’m going to share my learning.

The scenario: I have a REST JSON service that I’m calling and want to deserialize the result to a strongly typed object.  I’m using the HttpWebRequest to GET the JSON and the DataContractJsonSerializer from the System.Runtime.Serialization.Json namespace in the System.Runtime.Serialization assembly to deserialize the response stream.

If you create the HTTP request correctly and the response type matches the JSON structure everything will work.  I, however, had an issue.  It was all wrapped in a try/catch in the app I was working on so I added a break point and did a quick watch on the deserialize call to dig into the issue.  That’s when I ran into this:

Invalid byte encoding.

image

Bing/Google collectively had about 4 results for this error in the context of C#, none of which were related to JSON.  So that’s when I started digging deeper into my WCF JSON service and its configuration but nothing seemed to work.  I kept getting this error.  I finally started hitting the WCF from the web browser directly and a test client to find that my UriTemplate wasn’t quite right, so I fixed it.  Then I returned back to my WP app to find the same “byte encoding” error.

After several hours across several days I removed the breakpoint and the call worked fine. 

Confused, I add the breakpoint back and the error returned.  So after much troubleshooting the breakpoint itself caused this error.  Not exactly sure where but at some point during the break the network stream is being opened and read then the DataContractJsonSerializer fails when attempting to read the stream again. 

I created some quick test code to verify this.  The code calls the Bing JSON web service and should return an error because I didn’t include the app ID.   The test here is whether the error message can be deserialized.  The solution has three projects:  a WP 7.0 project, 7.1 project and a console app project.  Each works correctly without breakpoints but when you add a breakpoint and attempt to deserialize the JSON and you will get the error.  The console app gives a different error but it seems to be the same result.

"Expecting element ‘root’ from namespace ”.. Encountered ‘None’  with name ”, namespace ”. "

image

The test solution can be found at byte-encoding-error-test

Happy Coding!

Leave a Reply