I have two classes (Person and Address) that i need to send via wcf, the classes look like this:
public class PersoanaFizica :IExtensibleDataObject
{
[DataMember]
private Guid _id;
[DataMember(Name = "Id")]
protected virtual Guid Id
{
get { return _id; }
set { _id = value; }
}
private ExtensionDataObject _extensionData;
public virtual ExtensionDataObject ExtensionData
{
get
{
return _extensionData;
}
set
{
_extensionData = value;
}
}
private string _firstName;
[Searchable(PropertyName="FirstName")]
[DataMember]
public virtual string FirstName
{
get { return this._firstName; }
set { this._firstName = value; }
}
private string _lastName;
[Searchable(PropertyName="LastName")]
[DataMember]
public virtual string LastName
{
get { return this._lastName; }
set { this. _lastName = value; }
}
private Address _address;
[Searchable(PropertyName="Address")]
[DataMember]
public virtual Address Address
{
get { return this._address; }
set { this._address = value; }
}
}
public class Address : IExtensibleDataObject
{
[DataMember]
private Guid _id;
[DataMember]
public virtual Guid Id
{
get { return _id; }
set { _id = value; }
}
private ExtensionDataObject _extensionData;
public virtual ExtensionDataObject ExtensionData
{
get
{
return _extensionData;
}
set
{
_extensionData = value;
}
}
private string _country;
[Searchable(PropertyName="Country")]
[DataMember]
public virtual string Country
{
get { return this._country; }
set { this._country = value; }
}
// and some other properties related to the address
}
The problem is that when i try to send them via wcf, the client receives the Id properties set to 00000-0000-00000-00000 or something like this.
Any idea why this is happening? And how to serialize the proper values?
nope... did not help. I just looked at
the code generated by svcutil.exe
(thats what i use to generate my
client) and i couldn't find an Id
property at all. I tried changing the
protected keyword to public and
everything worked fine. It seems that
the problem is with the fact that i
need the properties to be protected
and not public.
Denis - any chance at all that your WCF client uses the XmlSerializer (which only serializes public read/write properties with a get and set method) instead of the DataContractSerializer?? The DataContractSerializer would definitely serialize a protected property or field - it really doesn't care about the .NET visibility modifiers....
You should see this in the WCF client side proxy being generated - do you have [DataContract] and [DataMember] attributes there, or do you see [XmlElement] and so forth?? Does your class in the WCF client side proxy have a [DataContractAttribute] or a [XmlTypeAttribute] on it??
You should not be marking both the field and the property with DataMember attributes! I have a feeling this is probably what's causing the issue you're seeing but I don't know that for sure. But basically by marking both the field and its backing property as DataMember's you are serializing the value twice and it will be deserialized twice and depending upon how your client-side code is generated this may even result in storing the value twice.
So long story short, mark either your fields as DataMember or the properties, but not both. Marking the fields may require you to specify a Name on the DataMemberAttribute in order for the client-side code generation to create the expected property names.
You don't initialize the properties in some way, so they have their default value assigned. If you assign a value to them, that should be properly send.
Related
In C# and its cousin languages, we always use
public string SomeString { get; set;}
But you can also use ( I found this out only recently and while fooling around with the compiler )
public string SomeString { set; get; }
I do not have any formal training in programming and everything is self-tought. I have been using { get; set; } without any thought just like we use 1 + 1 = 2 Is the order of { get; set; } just a convention or is it necessary to maintain this order or is it some remnant of a bygone era of C history like the way we define conventional electric current flowing from positive to the negative terminal when it is actually the other way around?
It is purely a convention. It makes no difference which order they appear in.
There is no difference.
It is exactly as if you had implemented the getter first in your class body, and the setter after it. The functions would still do exactly the same:
public String getSomeString() { return someString; }
public void setSomeString(String value) { someString=value; }
Whether they are written in that order
public void setSomeString(String value) { someString=value; }
public String getSomeString() { return someString; }
or the opposite. Wouldn't they?
I would however suggest to stick to one order in your code. Less entropy is always better :)
There is no difference.
According to the C# Language Specification http://msdn.microsoft.com/en-us/library/ms228593.aspx, 10.7.2 Accessors (page 324)
The accessor-declarations of a property specify the executable
statements associated with reading and writing that property.
accessor-declarations:
get-accessor-declaration set-accessor-declaration
set-accessor-declaration get-accessor-declaration
As shown it states either order has the same effect
Internally Get and Set are methods like this
private PropertyType Get() {}
private Set(value as PropertyType) {}
Since order of declaration of methods is not important, same case goes here.
MSDN:
The body of the get accessor is similar to that of a method. It must return a value of the property type.
The set accessor is similar to a method that returns void. It uses an implicit parameter called value, whose type is the type of the property.
{ get; set; } is just a shortcut so you don't have to write getters and setters for every field you want to expose. It's the same as when you write
public string GetSomeString() { }
public void SetSomeString(string value) { }
Does it matter, which one you write first? Of course not.
Just a convention you can use any of these when defining parameters:
public string SomeString { get; set; }
public string SomeString2 { set; get; }
public string someString2;
public string SomeString21
{
get { return someString2; }
set { someString2 = value; }
}
public string SomeString22
{
set { someString2 = value; }
get { return someString2; }
}
public string SomeString23
{
set { someString2 = value; }
}
public string SomeString24
{
get { return someString2; }
}
As others have already pointed out, there is no difference and it is just a convention. But to prove that up, you can see how compiler actually treats your code, given the following:
public class C
{
public string SomeString { get; set;}
public string SomeString2 { set; get; }
}
This will be treated as:
public class C
{
[CompilerGenerated]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string <SomeString>k__BackingField;
[CompilerGenerated]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private string <SomeString2>k__BackingField;
public string SomeString
{
[CompilerGenerated]
get
{
return <SomeString>k__BackingField;
}
[CompilerGenerated]
set
{
<SomeString>k__BackingField = value;
}
}
public string SomeString2
{
[CompilerGenerated]
get
{
return <SomeString2>k__BackingField;
}
[CompilerGenerated]
set
{
<SomeString2>k__BackingField = value;
}
}
}
As you can see, in both of them a new BackingField is generated by compiler and the body of two properties are same exactly.
The reference.
I'm looking at Microsoft's How to: Create a Basic Data Contract for a Class or Structure, but it leaves me with lots of questions.
They provide this very simplistic example:
using System;
using System.Runtime.Serialization;
[DataContract]
public class Person
{
// This member is serialized.
[DataMember]
internal string FullName;
// This is serialized even though it is private.
[DataMember]
private int Age;
// This is not serialized because the DataMemberAttribute
// has not been applied.
private string MailingAddress;
// This is not serialized, but the property is.
private string telephoneNumberValue;
[DataMember]
public string TelephoneNumber
{
get { return telephoneNumberValue; }
set { telephoneNumberValue = value; }
}
}
For my case, I need this to also include another custom class object called ADUser (Active Directory User).
I understand that ADUser has to be marked with the DataContractAttribute, but I do not understand how exactly to go about that.
Here is Microsoft's class again, but this time with the ADUser field added:
using System;
using System.Runtime.Serialization;
[DataContract]
public class Person
{
// This member is serialized.
[DataMember]
internal string FullName;
// This is serialized even though it is private.
[DataMember]
private int Age;
// This is not serialized because the DataMemberAttribute
// has not been applied.
private string MailingAddress;
// This is not serialized, but the property is.
private string telephoneNumberValue;
[DataMember]
public string TelephoneNumber
{
get { return telephoneNumberValue; }
set { telephoneNumberValue = value; }
}
[DataMember]
public ADUser UserInfo { get; set; }
}
I don't really understand how or what all needs to be done to my ADUser class, but I feel certain that private stuff can be left untouched.
How would I need to fix this ADUser class example?
public class ADUser
{
private string first, last, loginID;
public ADUser() {
first = null;
last = null;
loginID = null;
}
private void getInfo() {
// code goes here
// which sets loginID;
}
public void SetName(string first, string last) {
this.first = first;
this.last = last;
getInfo();
}
public string LoginID { get { return loginID; } }
}
As #outcoldman and #EthanLi suggested:
Add the [DataContract] attribute to the ADUser class.
Add a public constructor without arguments.
Choose the fields you want to pass through WCF. Mark all of them with the [DataMember] attribute.
Properties with only getters will fail during serialization: all exposed properties should have both a getter and (public!) setter. So, for example, your LoginID property will fail if you'll try to apply the [DataMember] attribute to it. In this case, consider changing it to be the method.
I am using Json.Net to serialize and deserialize an object.
I am experiencing an issue where the deserialized object recordPosted has zero as its Id.
Whereas the Serialized record will contain an Id of 180
JsonSerializerSettings jsSettings = new JsonSerializerSettings();
jsSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
var recordAsJson = JsonConvert.SerializeObject(recordToUpdate,
Formatting.None, jsSettings);
//recordAsJson = {"Id":180,....
var recordPosted = JsonConvert.DeserializeObject<record>(recordAsJson);
//recordPosted = Id : 0
How would I resolve this?
Edit
public virtual int Id { get; private set; }
Json.NET doesn't set private property setters by default. Either make the setter public or place a [JsonProperty] attribute on the property.
You don't show record, but I would wager that you have something like:
private int id;
public int Id { get { return id; } }
there isn't much that the serializer can do here to set Id, so... it doesn't. Note: some serializers (XmlSerializer, for example) will also refuse to serialize such, but JSON serializers tend to be more forgiving, since it is pretty common to use only the serialize, to return data from a web-server to a javascript client, including from anonymous types (which are immutable in C#).
You could try having a private set:
private int id;
public int Id { get { return id; } private set { id = value; } }
(or alternatively)
public int Id { get; private set; }
If that still doesn't work - it may have to be fully public:
private int id;
public int Id { get { return id; } set { id = value; } }
(or alternatively)
public int Id { get; set; }
Is there any difference between accessing a property that has a backing field
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
versus an auto-property?
public int Id { get; set; }
The reason I'm asking is that when letting ReSharper convert a property into an auto property it seems to scan my entire solution, or at least all aspx-files.
I can't see any reason why there should be any difference between the two from outside the class. Is there?
The compiler generates the backing field for Auto-Properties automatically, so no, there shouldn't be any difference.
ReSharper is scanning all the files, because if you have a Partial class defined, it could be using the backing field instead of the public property even though the code exists in physically different files.
For Example:
// MyClass.cs
public partial class MyClass
{
int _id;
public int ID { get { return _id; } set { _id = value; } }
public MyClass(int identifier)
{
ID = identifier;
}
}
// MyClass2.cs
public partial class MyClass
{
public void ChangeID(int newID)
{
_id = newID;
}
}
ReSharper must scan all files, since it has no way to know where a partial class might be defined.
I am trying to serialize some objects using XmlSerializer and inheritance but I am having some problems with ordering the outcome.
Below is an example similar to what I have setup: ~
public class SerializableBase
{
[XmlElement(Order = 1)]
public bool Property1 { get; set;}
[XmlElement(Order = 3)]
public bool Property3 { get; set;}
}
[XmlRoot("Object")]
public class SerializableObject1 : SerializableBase
{
}
[XmlRoot("Object")]
public class SerializableObject2 : SerializableBase
{
[XmlElement(Order = 2)]
public bool Property2 { get; set;}
}
The outcome I want is as follows: ~
<Object>
<Property1></Property1>
<Property2></Property2>
<Property3></Property3>
</Object>
However I am getting an outcome of: ~
<Object>
<Property1></Property1>
<Property3></Property3>
<Property2></Property2>
</Object>
Does anyone know if it is possible or of any alternative?
Thanks
Technically, from a pure xml perspective, I would say that this is probably a bad thing to want to do.
.NET hides much of the complexity of things like XmlSerialization - in this case, it hides the schema to which your serialized xml should conform.
The inferred schema will use sequence elements to describe the base type, and the extension types. This requires strict ordering -- even if the Deserializer is less strict and accepts out of order elements.
In xml schemas, when defining extension types, the additional elements from the child class must come after the elements from the base class.
you would essentially have a schema that looks something like (xml-y tags removed for clarity)
base
sequence
prop1
prop3
derived1 extends base
sequence
<empty>
derived2 extends base
sequence
prop2
There's no way to stick a placeholder in between prop1 and prop3 to indicate where the properties from the derived xml can go.
In the end, you have a mismatch between your data format and your business object. Probably your best alternative is to define an object to deal with your xml serialization.
For example
[XmlRoot("Object")
public class SerializableObjectForPersistance
{
[XmlElement(Order = 1)]
public bool Property1 { get; set; }
[XmlElement(Order = 2, IsNullable=true)]
public bool Property2 { get; set; }
[XmlElement(Order = 3)]
public bool Property3 { get; set; }
}
This separates your xml serialization code from your object model. Copy all the values from SerializableObject1 or SerializableObject2 to SerializableObjectForPersistance, and then serialize it.
Essentially, if you want such specific control over the format of your serialized xml that doesn't quite jive with the expectations xml serialization framework, you need to decouple your business object design (inheritance structure in this case) and the responsibility for serialization of that business object.
EDIT: This approach doesn't work. I've left the post in so that people can avoid this line of thinking.
The serializer acts recursively. There's a benefit to this; on deserialization, the deserialization process can read the base class, then the derived class. This means that a property on the derived class isn't set before the properties on the base, which could lead to problems.
If it really matters (and I'm not sure why it's important to get these in order) then you can try this --
1) make the base class' Property1 and Property3 virtual.
2) override them with trivial properties in your derived class. Eg
public class SerializableBase
{
[XmlElement(Order = 1)]
public virtual bool Property1 { get; set;}
[XmlElement(Order = 3)]
public virtual bool Property3 { get; set;}
}
[XmlRoot("Object")]
public class SerializableObject1 : SerializableBase
{
}
[XmlRoot("Object")]
public class SerializableObject2 : SerializableBase
{
[XmlElement(Order = 1)]
public override bool Property1
{
get { return base.Property1; }
set { base.Property1 = value; }
}
[XmlElement(Order = 2)]
public bool Property2 { get; set;}
[XmlElement(Order = 3)]
public override bool Property3
{
get { return base.Property3; }
set { base.Property3 = value; }
}
}
This puts a concrete implementtion of the property on the most derived class, and the order should be respected.
It looks like the XmlSerializer class serializes the base type and then derived types in that order and is only respecting the Order property within each class individually. Even though the order is not totally what you want, it should still Deserialize properly. If you really must have the order just like that you will need to write a custom xml serializer. I would caution against that beacuse the .NET XmlSerializer does a lot of special handling for you. Can you describe why you need things in the order you mention?
This post is quite old now, but I had a similar problem in WCF recently, and found a solution similar to Steve Cooper's above, but one that does work, and presumably will work for XML Serialization too.
If you remove the XmlElement attributes from the base class, and add a copy of each property with a different name to the derived classes that access the base value via the get/set, the copies can be serialized with the appropriate name assigned using an XmlElementAttribute, and will hopefully then serialize in the default order:
public class SerializableBase
{
public bool Property1 { get; set;}
public bool Property3 { get; set;}
}
[XmlRoot("Object")]
public class SerializableObject : SerializableBase
{
[XmlElement("Property1")]
public bool copyOfProperty1
{
get { return base.Property1; }
set { base.Property1 = value; }
}
[XmlElement]
public bool Property2 { get; set;}
[XmlElement("Property3")]
public bool copyOfProperty3
{
get { return base.Property3; }
set { base.Property3 = value; }
}
}
I also added an Interface to add to the derived classes, so that the copies could be made mandatory:
interface ISerializableObjectEnsureProperties
{
bool copyOfProperty1 { get; set; }
bool copyOfProperty2 { get; set; }
}
This is not essential but means that I can check everything is implemented at compile time, rather than checking the resultant XML. I had originally made these abstract properties of SerializableBase, but these then serialize first (with the base class), which I now realise is logical.
This is called in the usual way by changing one line above:
public class SerializableObject : SerializableBase, ISerializableObjectEnsureProperties
I've only tested this in WCF, and have ported the concept to XML Serialization without compiling, so if this doesn't work, apologies, but I would expect it to behave in the same way - I'm sure someone will let me know if not...
I know this question has expired; however, here is a solution for this problem:
The name of the method should always begin with ShouldSerialize and then end with the property name. Then you simply need to return a boolean based on whatever conditional you want, as to whether to serialize the value or not.
public class SerializableBase
{
public bool Property1 { get; set;}
public bool Property2 { get; set;}
public bool Property3 { get; set;}
public virtual bool ShouldSerializeProperty2 { get { return false; } }
}
[XmlRoot("Object")]
public class SerializableObject1 : SerializableBase
{
}
[XmlRoot("Object")]
public class SerializableObject2 : SerializableBase
{
public override bool ShouldSerializeProperty2 { get { return true; } }
}
The outcome when using SerializableObject2: ~
<Object>
<Property1></Property1>
<Property2></Property2>
<Property3></Property3>
</Object>
The outcome when using SerializableObject1: ~
<Object>
<Property1></Property1>
<Property3></Property3>
</Object>
Hope this helps many others!
Like Nader said, maybe think about making a more loose-coupled design. However, in my case, loose-coupling was not appropriate. Here's my class hierarchy, and how I propose to solve the problem without using custom serialization or DTOs.
In my project, I'm constructing a whole bunch of objects to represent pieces of an XML document that will be submitted via a web service. There are a very large number of pieces. Not all are sent with every request (actually, in this example, I'm modeling a response, but the concepts are the same). These pieces are used much like building blocks to assemble a request (or disassemble a response, in this case). So here's an example of using aggregation/encapsulation to accomplish the desired ordering despite the inheritance hierarchy.
[Serializable]
public abstract class ElementBase
{
// This constructor sets up the default namespace for all of my objects. Every
// Xml Element class will inherit from this class.
internal ElementBase()
{
this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
new XmlQualifiedName(string.Empty, "urn:my-default-namespace:XSD:1")
});
}
[XmlNamespacesDeclaration]
public XmlSerializerNamespaces Namespaces { get { return this._namespaces; } }
private XmlSerializationNamespaces _namespaces;
}
[Serializable]
public abstract class ServiceBase : ElementBase
{
private ServiceBase() { }
public ServiceBase(Guid requestId, Guid? asyncRequestId = null, Identifier name = null)
{
this._requestId = requestId;
this._asyncRequestId = asyncRequestId;
this._name = name;
}
public Guid RequestId
{
get { return this._requestId; }
set { this._requestId = value; }
}
private Guid _requestId;
public Guid? AsyncRequestId
{
get { return this._asyncRequestId; }
set { this._asyncRequestId = value; }
}
private Guid? _asyncRequestId;
public bool AsyncRequestIdSpecified
{
get { return this._asyncRequestId == null && this._asyncRequestId.HasValue; }
set { /* XmlSerializer requires both a getter and a setter.*/ ; }
}
public Identifier Name
{
get { return this._name; }
set { this._name; }
}
private Identifier _name;
}
[Serializable]
public abstract class ServiceResponseBase : ServiceBase
{
private ServiceBase _serviceBase;
private ServiceResponseBase() { }
public ServiceResponseBase(Guid requestId, Guid? asyncRequestId = null, Identifier name = null, Status status = null)
{
this._serviceBase = new ServiceBase(requestId, asyncRequestId, name);
this._status = status;
}
public Guid RequestId
{
get { return this._serviceBase.RequestId; }
set { this._serviceBase.RequestId = value; }
}
public Guid? AsyncRequestId
{
get { return this._serviceBase.AsyncRequestId; }
set { this._serviceBase.AsyncRequestId = value; }
}
public bool AsynceRequestIdSpecified
{
get { return this._serviceBase.AsyncRequestIdSpecified; }
set { ; }
}
public Identifier Name
{
get { return this._serviceBase.Name; }
set { this._serviceBase.Name = value; }
}
public Status Status
{
get { return this._status; }
set { this._status = value; }
}
}
[Serializable]
[XmlRoot(Namespace = "urn:my-default-namespace:XSD:1")]
public class BankServiceResponse : ServiceResponseBase
{
// Determines if the class is being deserialized.
private bool _isDeserializing;
private ServiceResponseBase _serviceResponseBase;
// Constructor used by XmlSerializer.
// This is special because I require a non-null List<T> of items later on.
private BankServiceResponse()
{
this._isDeserializing = true;
this._serviceResponseBase = new ServiceResponseBase();
}
// Constructor used for unit testing
internal BankServiceResponse(bool isDeserializing = false)
{
this._isDeserializing = isDeserializing;
this._serviceResponseBase = new ServiceResponseBase();
}
public BankServiceResponse(Guid requestId, List<BankResponse> responses, Guid? asyncRequestId = null, Identifier name = null, Status status = null)
{
if (responses == null || responses.Count == 0)
throw new ArgumentNullException("The list cannot be null or empty", "responses");
this._serviceResponseBase = new ServiceResponseBase(requestId, asyncRequestId, name, status);
this._responses = responses;
}
[XmlElement(Order = 1)]
public Status Status
{
get { return this._serviceResponseBase.Status; }
set { this._serviceResponseBase.Status = value; }
}
[XmlElement(Order = 2)]
public Guid RequestId
{
get { return this._serviceResponseBase.RequestId; }
set { this._serviceResponseBase.RequestId = value; }
}
[XmlElement(Order = 3)]
public Guid? AsyncRequestId
{
get { return this._serviceResponseBase.AsyncRequestId; }
set { this._serviceResponseBase.AsyncRequestId = value; }
}
[XmlIgnore]
public bool AsyncRequestIdSpecified
{
get { return this._serviceResponseBase.AsyncRequestIdSpecified; }
set { ; } // Must have this for XmlSerializer.
}
[XmlElement(Order = 4)]
public Identifer Name
{
get { return this._serviceResponseBase.Name; }
set { this._serviceResponseBase.Name; }
}
[XmlElement(Order = 5)]
public List<BankResponse> Responses
{
get { return this._responses; }
set
{
if (this._isDeserializing && this._responses != null && this._responses.Count > 0)
this._isDeserializing = false;
if (!this._isDeserializing && (value == null || value.Count == 0))
throw new ArgumentNullException("List cannot be null or empty.", "value");
this._responses = value;
}
}
private List<BankResponse> _responses;
}
So, while I have to create properties for all of the contained classes, I can delegate any custom logic I might have within the contained class(es) property setters/getters by simply using the contained class's properties when the leaf class's properties are accessed. Since there's no inheritance, I can decorate all the properties of the leaf class with the XmlElementAttribute attribute and use any ordering that I see fit.
UPDATE:
I came back to revisit this article because my design decisions about using class inheritance came back to bite me again. While my solution above does work, I'm using it, I really think that Nader's solution is the best and should be considered before the solution I presented. In fact, I'm +1'ing him today! I really like his answer, and if I ever have the opportunity to refactor my current project, I will definitely be separating the business object from the serialization logic for objects that would otherwise benefit greatly from inheritance in order to simplify the code and make it easier for others to use and understand.
Thanks for posting your response Nader, as I think many will find it very instructive and useful.