Serialization with internal types

Hey people, I’ve run into some issues with serialization.

The usual problem with internal types comes when you are testing. If you want the test to access those internal members, you have to add in the AssemblyInfo.cs of the “exposed” assembly something like this:

[assemblyInternalsVisibleTo(“BlablaAssemblyThatAccessessMyInternals, PublicKey=blabla”)]

But this isn’t the only problem when you deal with internals.

I happened to me just today: I have some test data formatted in XML. I wanted to deserialize it, but… the type that I wanted to deserialize was internal. I used the XmlSerializer as anyone would do in the first approach (at least I did it! J) but as soon as I ran the test it complained that

“[TypeName] is inaccessible due to its protection level. Only public types can be processed.”

Glad to know, dude!

But isn’t that a shitty message? I think so.

Then, I made a brief research on the topic and soon discovered that the DataContractSerializer could possibly make my day, so I decorated all the entities that are implied in the serialization with [DataContact] and [DataMember] attributes.

Yay, it worked!

But not the way I thought.

And this is important: the DataContractSerializer is known to be much more restrictive than the XmlSerializer. One of the restrictions is that it reads XML elements are in alphabetical order!! Yes, ORDER MATTERS!! I have realized of that after most of the properties didn’t have values set!

For example, this Entity is read correctly by the DataContractSerializer

<Entity xmlns="" xmlns:i="">
	<UserName>JMN</UserName >

Did you notice the order in the elements?

The following entity will not be read correctly!

<Entity xmlns="" xmlns:i="">
	<UserName>JMN</UserName >	

Problem solved!

More 😀


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s