.NET WebAPI Serialization k_BackingField Nastiness - serialization

When i serialize the following:
[Serializable]
public class Error
{
public string Status { get; set; }
public string Message { get; set; }
public string ErrorReferenceCode { get; set; }
public List<FriendlyError> Errors { get; set; }
}
I get this disgusting mess:
<ErrorRootOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Printmee.Api">
<_x003C_Errors_x003E_k__BackingField>
An exception has occurred. Please contact printmee support
</_x003C_Errors_x003E_k__BackingField>
<_x003C_LookupCode_x003E_k__BackingField>988232ec-6bc9-48f3-8116-7ff7c71302dd</_x003C_LookupCode_x003E_k__BackingField>
</ErrorRootOfstring>
What gives? How can i make this pretty? JSON responses also contain the k_BackingField

By default you don't need to use neither [Serializable] nor [DataContract] to work with Web API.
Just leave your model as is, and Web API would serialize all the public properties for you.
Only if you want to have more control about what's included, you then decorate your class with [DataContract] and the properties to be included with [DataMember] (because both DCS and JSON.NET respsect these attributes).
If for some reason, you need the [Serializable] on your class (i.e. you are serializing it into a memory stream for some reason, doing deep copies etc), then you have to use both attributes in conjunction to prevent the backing field names:
[Serializable]
[DataContract]
public class Error
{
[DataMember]
public string Status { get; set; }
[DataMember]
public string Message { get; set; }
[DataMember]
public string ErrorReferenceCode { get; set; }
[DataMember]
public List<FriendlyError> Errors { get; set; }
}

There is a more general solution: you can configure the Json Serializer to ignore the [Serializable] attribute, so that you don't have to change the attributes in your classes.
You should make this configuration change in the application start, i.e. in Global.asax Application_Start event:
var serializerSettings =
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
var contractResolver =
(DefaultContractResolver)serializerSettings.ContractResolver;
contractResolver.IgnoreSerializableAttribute = true;
You can also make other changes to the Json serialization, like specifying formats for serializing dates, and many other things.
This will only apply to the Web API JSON serialization. The other serializations in the app (Web API XML serialization, MVC JsonResult...) won't be affected by this setting.

Try using DataContract instead of Serializable for marking your class. For more detail on why, look at this good blog post on serializing automatic properties.

The [DataContract] attributes dosn't worked for me, so it was not an option.
XmlSerializer ignores [XmlAttribute] in WebApi
The above resolution solved it for me.
GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;

Related

RestSharp ExecAsync<T> where T is a nested object

I have a method that calls RestSharp client ExecuteAsync<T> where the T I am passing is a nested object. I get an exception that says
InvalidProgramException: Request for the resource
/v1/accounts/AN_1476935163870 failed No parameterless constructor
defined for this object.
The object I am passing is:
public class GetAccountResponse : IGetAccountResponse
{
public GetAccountResponseBasicInfo basicInfo { get; set; }
public GetAccountResponseBillingAndPayment billingAndPayment { get; set; }
public GetAccountResponseMetrics metrics { get; set; }
public string billToContact { get; set; }
public string soldToContact { get; set; }
public bool success { get; set; }
}
Where the objects for the properties basicInfo, billingAndPayment, and metrics are classes that have definitions and I have not defined a consturctor. I also have tried replacing the objects with interfaces but it still throws an exception.
Thank you
There are two possible causes of this issue:
Regression in RestSharp that added the new constraint to typed request methods, which was fixed this week
Serialization issue. In that case, you can try another serializer, we have libraries that support NewtosoftJson, Utf8Json and System.Text.Json in addition to the built-in SimpleJson

WCF return type is object

I have a WCF method:
public IQueryable<AmenitySummary> GetAmenities(string searchTerm)
Now, AmenitySummary is defined thus
[DataContract]
public class AmenitySummary
{
[DataMember]
public int AmenityId { get; set; }
[DataMember]
public string Amenity { get; set; }
[DataMember]
public string LowerCaseAmenity { get; set; }
}
In my client side solution I have a project in which I call this method. The problem is that the signature in the Reference.cs file is this
public object GetAmenities(string searchTerm) {
return base.Channel.GetAmenities(searchTerm);
}
How comes? Why isn't the return type IQueryable<AmenitySummary>? What am I missing?
Not only that, but when I try to use AmenitySummary on the client side I can't do it as it's not recognised. I think this is linked.
Thanks,
S
IQueryable is not serialiable without specific references (see svcutil.exe /references).
Otherwise use a WCF DataService (OData) or return an array of AmenitySummary from the service. In the later case you can convert the array to an IQuaryable instance.
I think it's because of IQueryable. You probably need to expose it too.
See this post:
Expose IQueryable Over WCF Service

Can I use DataContract and Serializable together?

I am working on WCF service. My all class are already serialize using [Serializable] attribute but due to "k__BackingField" Property Naming problem I used DataContract and DataMember attribute.
so Can i use both attribute together like following:
[Serializable]
[DataContract]
public class User
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int UserID { get; set; }
}
is this correct?
I also got similar solution here.
C# automatic property deserialization of JSON
Serializable and DataContract (not versus?)
I found an article on MSDN according to this we can use both attribute DataContract and Serializable together.
With [Serializable], all fields become part of the data contract (unless they are marked with [NonSerialized]). With [DataContract], only members marked with [DataMember] are included. Note that if a type has both [DataContract] and [Serializable] attributes on it, it will use the [DataContract] mapping
http://msdn.microsoft.com/en-us/magazine/cc163569.aspx
if the problem is in naming why don't you use
[XmlElement(ElementName = "Name")]
public string Name { get; set; }

WCF client side List<>

I got a WCF service with a method (GetUserSoftware)to send a List to a client.
the software I have defined like this:
[DataContract]
public class Software
{
public string SoftwareID { get; set; }
public string SoftwareName { get; set; }
public string DownloadPath { get; set; }
public int PackageID { get; set; }
}
the method is going through my db to get all software availeble to the clien, and generates a list of that to send back to the client.
problem is i on the client side the list is turned into an array. and every item in that array dont contain any of my software attributs.
i have debugged my way through the server side. and seen that the list its about to send is correct. with the expected software and attributs in it.
any one know how to work around this or know what i can do ?
Did you forget [DataMemeber] attribute on your properties?
When you use DataContract attribute for a type you have to use DataMember attribute for each property or field you want to serialize and transfer between service and client. Collections are by default created as arrays. If you don't like it you can change this behavior in Add Service Reference window -> Advanced settings where you can select which collection type should be used.
First off, each of the properties that you want to serialize should have the [DataMember] attribute:
[DataContract]
public class Software
{
[DataMember]
public string SoftwareID { get; set; }
[DataMember]
public string SoftwareName { get; set; }
[DataMember]
public string DownloadPath { get; set; }
[DataMember]
public int PackageID { get; set; }
}
Second, the translation to an Array would be handled by the client, not the server.
You can mantain List instead of array on the clien when you add the Service Reference: click the "advanced" button and change the collection type to the one you want.
I was suffering with same problem and now I solved it! It was a ServiceKnownType problem. If you have a in known type loader we have to add runtime Type like;
Type aaa = Type.GetType("System.Collections.Generic.List`1[[ProjectName.BusinessObjects.Bank, ProjectName.BusinessObjects, Version=4.0.0.0, Culture=neutral, PublicKeyToken=null]]");
knownTypes.Add(aaa);
Anyone having same problem can try this. It's working in my environment!

Solve a circular reference in WCF from my POCOs

I have a couple of classes (for now) and I'm trying to clear up a circular reference between the two since it is killing WCF's serialization.
I am using EF with POCOs in a WCF REST service is that helps. I have simplified my problem down to bare bones for an easy example here:
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Groups
{
[WebGet(UriTemplate = "")]
public Message GetCollection()
{
var message = new Message { Body = "Test message" };
var group = new Group { Title = "Title of group" };
message.Group = group;
group.Messages = new List<Message> { message };
return message;
}
}
public class Message
{
public string Body { get; set; }
public Group Group { get; set; }
}
[DataContract(IsReference = true)]
public class Group
{
public string Title { get; set; }
public ICollection<Message> Messages { get; set; }
}
I have added the [DataContract(IsReference = true)] to the Group class so that the circular reference is cleaned up however my returned results end up like this:
<Message xmlns="http://schemas.datacontract.org/2004/07/LmApi" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Body>Test message</Body>
<Group z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/"/>
</Message>
Where are the properties of the Group and how can I get them?
BritishDeveloper,
There are no properties associated with Group. That's why all you see is the ID of 1.
The reason is that as soon as you annotate the Group class with [DataContract(IsReference = true)], you are telling the DataContract serializer that it's no longer a POCO type. It's a DataContract type.
So, to serialize Group with properties, you now need to go ahead and annotate the Title and Message properties with DataMemberAttribute.
An alternative would be use the "preserveObjectReferences", which you can pass as a parameter to DataContractSerializer, DataContractSerializerOperationBehavior, and other classes.
Hope this helps!
I decided to make my own smaller classes that have a constructor that takes an entity and sets all of this lighterweight properties correctly.
Basically it is a very small copy of the class that has just the properties needed in the payload. (Obviously I have excluded the problem navigation properties)
This is similar to Circular References and WCF Here is my answer modified for this case
I had the same problem and resolved it by excluding the navigation property back to the parent from the DataContract
[DataContract]
public partial class Message
{
[DataMember]
public virtual string Body { get; set; }
[DataMember]
public virtual Group Group { get; set; }
}
[DataContract]
public partial class Group
{
[DataMember]
public virtual string Title { get; set; }
public virtual ICollection<Message> Messages {get; set;}
}