Reputation:
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; } }
}
Upvotes: 3
Views: 15092
Reputation: 8107
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.
Upvotes: 5