Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XmlException in WCF deserialization: "Name cannot begin with '<'" - in automatic property backing fields

I have started experiencing errors in WCF deserialization today - in code which has been unchanged and working for months.

The issue is that I am getting runtime XmlExceptions saying 'Name cannot begin with the '<' character'. I have debugged into the .NET source, and it seems the error is in deserializing return objects from our WCF service calls. These objects are defined using automatic properties, and it seems the backing fields are given names like <MyProperty>k_BackingField, which is where the XmlException is coming from.

I've seen a couple of other references online where the solution people accept is "I changed my code to not use automatic properties", which isn't really acceptable to me, as I would have 100s of objects to change, (with 1000s of properties amongst them). Also, this same code was working fine when I ran it last week, and doesn't seem to affect all serialized DTOs, only some.

To make it even more frustrating, it seems mildly intermittent. On occasion this morning, there has been no exception thrown...!

Questions;

  1. Why has this problem suddenly appeared in unchanged code and unchanged framework source?
  2. How do I fix this without modifying all the DTOs to use fully implemented properties?

UPDATE: After a day or so of working fine, this issue has reappeared - no reason I can find why it would work/not work/work again, but here we are.

I have tracked the problem down further to be related to some code I have on my ServiceContracts using the ServiceKnownType attribute, which is used to define known types for serialization. It seems that although the types being reported with errors are not even part of the service call I am making at the time, that this error is occurring on types which are part of this known types 'publishing' behaviour.

The problem occurs when I use some proxy creation code to apply some service behaviours;

IOperationBehavior innerBehavior = new PreserveReferencesOperationBehavior(
    description, this.preserveReferences, this.maxItemsInObjectGraph);
innerBehavior.ApplyClientBehavior(description, proxy);

I cannot debug the ApplyClientBehavior code as it is part of System.ServiceModel (or can I?), but something in that method is trying to validate all types I have published using my ServiceKnownType attribute, and breaking on some of them with this XmlException. I have NO IDEA why some of the types are failing - and only for some of their properties.

This is an example of the types which are getting errors reported against them;

[Serializable]
public class MyDataObject
{
    public ActivitySession(string id)
    {
        this.Id = id;
        this.IsOpen = true;
    }

    public string Id { get; set; }

    public bool IsValid { get; set; }
}

The exception reported an error against Id -> <Id>k_BackingField cannot start with '<'

So nothing controversial in that class, and no inheritance to consider. It's not even part of a service contract, only it was previously published as a known type for serialization.

This is getting quite esoteric now, so I'm not expecting an answer, but just updating where the problem is at.

like image 280
RJ Lohan Avatar asked Dec 16 '12 23:12

RJ Lohan


People also ask

How do you serialize an object in WCF?

This code constructs an instance of the DataContractSerializer that can be used only to serialize or deserialize instances of the Person class. DataContractSerializer dcs = new DataContractSerializer(typeof(Person)); // This can now be used to serialize/deserialize Person but not PurchaseOrder.

What is by serialization with respect to WCF?

The process forms a sequence of bytes into a logical object; this is called an encoding process. At runtime when WCF receives the logical message, it transforms them back into corresponding . Net objects. This process is called serialization.

What is serialization in C# with example?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.


2 Answers

I think I have found more information to help explain this issue, (at least in so far as why the error is appearing on certain types only).

The DTOs which are getting exceptions reported against them are;

  • published as part of my [ServiceKnownType] attribute
  • marked with [Serializable]
  • NOT marked with [DataContract]

Adding the [DataContract] attribute to the type resolves this issue. I have no idea why, and still no idea why this error is intermittent in when it happens, but consistent in what it affects.

like image 69
RJ Lohan Avatar answered Sep 23 '22 01:09

RJ Lohan


I looked at this question also: WCF Service Reference - Getting "XmlException: Name cannot begin with the '<' character, hexadecimal value 0x3C" on Client Side

regarding this exception:

System.Xml.XmlException: 'Name cannot begin with the '<' character, hexadecimal value 0x3C.'

  1. Check if you load any xml files that they are valid (e.g. do not contain typo's like < or >
  2. If you are using services + WCF, have a look at your Service interfaces (the interfaces with ServiceContract). This will be a good starting point. Now check to see if you have any DTO parameters in methods from the interface. Go to these DTO's and see if these DTO classes have [Serializable] or [DataContract] or similar attributes. If these classes also contain automatic properties, change them the properties to the notation with your own backing field like:

    private Foo _Bar; public Foo Bar { get { return _Bar; } set { _Bar = value; } }

If you are lucky you will see the errors go away! There seems to be a problem with automatic properties where the automatically generated backing field has a name similar to e.g. <>something, <>d_whatever or things like that. These names start with '<' character, resulting in that error.

In case of services and WCF, your service interfaces and callbacks (with datacontract) are a good place to start replacing the automatic properties. At least it gives you an idea where to start instead of replacing thousands of automatic properties.

Additionally try to catch FirstChanceExceptions by adding this code at the start of your application and write the messages to the console. This will help a lot to see if the number of "Name cannot begin with the '<' character" messages is reduced or not.

AppDomain.CurrentDomain.FirstChanceException += (object source, System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs e) => { Console.WriteLine("FirstChanceException event raised in {0}: {1}", AppDomain.CurrentDomain.FriendlyName, e.Exception.Message); };

https://docs.microsoft.com/en-us/dotnet/framework/app-domains/how-to-receive-first-chance-exception-notifications

This is what I found so far. Hope it helps.

like image 44
juFo Avatar answered Sep 27 '22 01:09

juFo