Why is prefix of underscore on public properties in my JSON result set - wcf

I use ASP.NET WCF to return .NET objects in JSON format through jquery calls.
When I changed my .NET classes to serializable, which I expose through methods in my WCF class, the objects property names suddenly changed from:
Name to _Name.
So all code in my javascript classes where I access json objects is wrong.
Why do the properties have a underscore prefix now?
And how do I change it back without removing the serializable attribute on the classes?
Thanks.
Christian

When you say that you "changed the class to serializable", does it mean you added the [Serializable] attribute on them? If this is the case: classes marked with that attribute have all of their fields serialized (no properties). In the example below, this class doesn't have any attributes, and it does have a parameter-less constructor, so it's considered a "POCO" (plain-old CLR object) type. POCO types have their public members (fields or properties) serialized. If you decorate it with [Serializable], then it will fall into the serializable rule.
Why do you need to mark your type with [Serializable]? If you really need to do that (for some legacy serializer), you can also decorate your type with [DataContract] and [DataMember] attributes, which are honored by the WCF serializer. You'd add [DataContract] on the type, and [DataMember] on the properties which you want serialized.
public class Person
{
private string _Name;
private int _Age;
public string Name {
get { return this._Name; }
set { this._Name = value; }
}
public string Age {
get { return this._Age; }
set { this._Age = value; }
}
}

Related

DDD ValueObject and Enumeration , is there any good way to implement serialization?

In DDD, Value Object and Enumeration are quite beautiful so that I want use both two in the daily program logic, not only domain logic. When use customized value objects and enumerations, serialization problem is coming : should I implemented all the value objects and enumeration with System.Text.Json.JsonConverter<T> , or is there any good way to handle serialization and deserialization ?
Update:
to make it clear, Eumeration demo as below(ValueObject derived classes are same.):
[JsonConverter(typeof(CustomizedConverter))]
public class CustomizedEnumeration1 : Enumeration
{
public string Customized { get; protected set; }
public ... // some other customized property or class
public CustomizedEnumeration(int id, string name, string customized) : base(id, string) {
Customized = customized;
}
}
public class Customized2 : Enumeration
{ ... }
public class OtherCustomized: Enumeration
{ ... }
In DDD, properties sometimes are sealed by protected/private setter, deserialization has no right to set the value. Many derived classes can't deserialize as expected, so we have to rewrite serialization with System.Text.Json.JsonConverter<T> one by one. rewrite every derived Enumeration / Valueobject converter is not good, can any one point out any easy abstraction for that ?
You can achieve your desired result. You need to switch to NewtonsoftJson serialization.
Call this in Startup.cs in the ConfigureServices method:
services.AddControllers().AddNewtonsoftJson();
After this, your constructor will be called by deserialization for classes with private setter.
There is no need for custom converters.
For reference, I am using ASP Net Core 3.1

silverlight domain service don't allow return a generic object

I have a domain service running smooth, some expose functions that return generic lists of defined entity, but for some reason, I had add some common information so I created a generic object to wrap the collection with the extra information that I need return.
but when after made the change and try use the service in the client, the function don't show up in the context, I already search about it and what I found was attributes for generic IQueryable
my wrap class
public class Wrap<T>
{
public String commonProperty { get; set; }
public String anotherCommonProperty { get; set; }
public List<T> items { get; set; }
}
in my service domain
public Wrap<SomeClass> GetAll()
{
Wrap<SomeClass> myObject = new Wrap<SomeClass>();
myObject.items = new List<SomeClass>();
myObject.commonProperty = "some info";
myObject.anotherCommonProperty = "some info";
return myObject;
}
Maybe adding the [KnownType(typeof(SomeClass))] attribute in the Wrap<T> class, the problem is that you need to include one KnowType attribute for every class in your domain (this is because you are making a polymorphic service).
And adding the [ServiceKnownType(typeof(SomeClass))] in the GetAll method in the service (this is for wcf services I don't know if is valid for domain services).
WCF RIA domain services does not support generic entity types. IEnumerable<T> and IQueryable<T> are special cases.
Your method was ignored because it did not match supported method type.
Before changes GetAll was recognized as Query method. You can force that by adding attribute.
[Query]
public Wrap<SomeClass> GetAll()
Now it does not dissapear silently. But generates compile time error instead:
Type 'Wrap`1' is not a valid entity type. Entity types cannot be
generic.

DataContract properties names during proxy generation with svcutil

Is there any switch that instructs svcutil to generate DataContract properties with their names as defined in code? For example when I create a proxy which uses the following DataContract:
[DataContract(Namespace = "http://schemas.mynamespace.com/2012/08")]
public class MyDataContract
{
[DataMember(IsRequired = true, Order = 0)]
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
}
I get this DataContract on the proxy generated class:
public partial class MyDataContract : object
{
private int _idField;
[System.Runtime.Serialization.DataMemberAttribute(IsRequired=true)]
public int _id
{
get
{
return this._idField;
}
set
{
this._idField = value;
}
}
}
The order property of the DataMemberAttribute is always ommited as well for the first 3 properties and a MessageContract ommits an IDisposable implementation.
Well, I cannot comment on the omitted order, but I may be able to help on the rest:
One usually specifies the DataMember attribute on the property, not on the field. The data-contract itself does not distinguish between a property and a field, but it knows the name, type, if it is mandatory, etc. etc.
Added: What Chris said: With [DataMember(Name="whateveryouwant")] you'll be able to set a name different from the field/property name. I do not like such usage, though, but it is helpful when refactoring code, but still keeping the API compatible.
Only other DataContract (and some intrinsically supported) types are serialized to/from messages. IDisposable seems not to be one.
Serializing the inherited IDisposable of a MessageContract would not make any sense. A message-contract is the .NET representation of a SOAP message. It literally has nothing else to do but to provide a 1:1 mapping between what is in the SOAP message XML, and the accessible .NET types.
A message is part of a ServiceContract, in that it specifies which kind of message must be sent to a certain operation to be a valid invocation, and another (response-)message contract specifies how the data, that the operation returns, will be structured. Nothing else; it is a data-aggregate.
If you want to capture the result of a service-operation on the client, and for convenience automatically send a message back upon going out of scope (or for instance unregistering from a service), you will have to implement this on the client-side. Be aware, however, that the service must not require this to happen (due to lost connections, crashes, etc.).
Use the name property on DataMember attribute
Such as:
[DataMember(Name="myname")]

Problem with sending object via wcf service with private fields

I have a class Car
public class Car
{
private Member _owner;
public string OwnerName
{
get { return _owner.Name; }
}
public Car(Member owner)
{
_owner = owner;
}
}
I'm using it both at Silverlight application and wcf service
So, at application I call WCF service to give me instance of car class, but when I get it at application, I see that _owner is empy.
I know that it is empty because of private, but how can I deal with it?
I'm using this class in my app as model (MVVM) if it could helps :/
For a start none of your properties are marked as DataMembers. The class isn't marked as a DataContract. If this is getting returned from a WCF service I would expect to see:
[Serializable]
[DataContract]
public class Car
{
private Member _owner;
[DataMember]
public string OwnerName
{
//getter
//setter
}
etc..
}
Does Member have to be private? Could it be converted into a property?
Keep in mind that a [DataMember] property needs both a set and a get (so that WCF can read into and from the object).
http://msdn.microsoft.com/en-us/library/ms733127.aspx
From a WCF serialization point of view, your Car class actually looks something like this to the WCF service:
public class Car
{
public string OwnerName { get; set; }
//other public properties here....
}
The WCF serializer uses the .NET class definition as a template for serializing its contents as a simple data transfer object. When the WCF service sends back a Car instance, only the public properties will contain values. The serializer ignores all methods in the class. Also, later versions of WCF don't require the DataContract/DataMember attribute markup.
The _owner variable is never initialized because it is not part of the public properties of the Car class. You'll need to modify the structure of the Car class (maybe add a public Owner property of type Member) to get all the data sent from the WCF service to your client.
When you are using the default Data Contract Serializer with WCF services it serializes and deserializes only the public properties of the class. Also another thing to note is that while deserializing the object graph the constructor is not called. You can have a public property with getter and setter.
Here is a very nice article by Jeremy Likeness explaining the problem similar to yours. From Architecture as well as best practices point of view you can use a POCO class generally called as DTO (Data Transfer Object) when transferring objects between the service layer and the clients.

Is it possible to serialize objects without a parameterless constructor in WCF?

I know that a private parameterless constructor works but what about an object with no parameterless constructors?
I would like to expose types from a third party library so I have no control over the type definitions.
If there is a way what is the easiest? E.g. I don't what to have to create a sub type.
Edit:
What I'm looking for is something like the level of customization shown here: http://msdn.microsoft.com/en-us/magazine/cc163902.aspx
although I don't want to have to resort to streams to serialize/deserialize.
You can't really make arbitrary types serializable; in some cases (XmlSerializer, for example) the runtime exposes options to spoof the attributes. But DataContractSerializer doesn't allow this. Feasible options:
hide the classes behind your own types that are serializable (lots of work)
provide binary formatter surrogates (yeuch)
write your own serialization core (a lot of work to get right)
Essentially, if something isn't designed for serialization, very little of the framework will let you serialize it.
I just ran a little test, using a WCF Service that returns an basic object that does not have a default constructor.
//[DataContract]
//[Serializable]
public class MyObject
{
public MyObject(string _name)
{
Name = _name;
}
//[DataMember]
public string Name { get; set; }
//[DataMember]
public string Address { get; set; }
}
Here is what the service looks like:
public class MyService : IMyService
{
#region IMyService Members
public MyObject GetByName(string _name)
{
return new MyObject(_name) { Address = "Test Address" };
}
#endregion
}
This actually works, as long as MyObject is either a [DataContract] or [Serializable]. Interestingly, it doesn't seem to need the default constructor on the client side. There is a related post here:
How does WCF deserialization instantiate objects without calling a constructor?
I am not a WCF expert but it is unlikely that they support serialization on a constructor with arbitrary types. Namely because what would they pass in for values? You could pass null for reference types and empty values for structs. But what good would a type be that could be constructed with completely empty data?
I think you are stuck with 1 of 2 options
Sub class the type in question and pass appropriate default values to the non-parameterless constructor
Create a type that exists soley for serialization. Once completed it can create an instance of the original type that you are interested in. It is a bridge of sorts.
Personally I would go for #2. Make the class a data only structure and optimize it for serialization and factory purposes.