Kalpesh Rajai Kalpesh Rajai - 1 month ago 20
C# Question

CollectionDataContract with the extra property

I am working with the list in the WCF. I want to pass the list between the client and server with the one extra property inside it.

Needed Output

<NumbersList>
<Count>2</Count> //Extra property to parse
<Number>1</Number>
<Number>2</Number>
</NumbersList>


So I follow the tutorial at this link: http://www.borismod.net/2009/04/wcf-collectiondatacontract-and.html

And I wrote the below code to achieve that.

[MessageContract]
public class RequestResponse
{
[MessageBodyMember(Name = "NumbersList")]
public NumbersList NumbersList;
}

[DataContract]
public class NumbersList
{
[DataMember]
public int Count { get; set; }

[DataMember]
public Number Number { get; set; }
}

[CollectionDataContract(ItemName = "Number")]
public class Number : Collection<int>
{
}


So it give me the output like this:

<NumbersList>
<Count>2</Count>
<Number>
<Number>1</Number>
<Number>2</Number>
</Number>
</NumbersList>


If I put the
Count
property decorated with the
DataMember
directly inside the
CollectionDataContract
than the however WCF omit that property.

One more try:

[MessageContract]
public class RequestResponse
{
[MessageBodyMember(Name = "NumbersList")]
public Number NumbersList;
}

[CollectionDataContract(ItemName = "Number")]
public class Number : Collection<int>
{
[DataMember]
public int Count { get; set; } // This will be omited...
}


Than it can be give the output like this:

<NumbersList>
<Number>
<Number>1</Number>
<Number>2</Number>
</Number>
</NumbersList>


Can any one help me to get the output like this:

Needed Output

<NumbersList>
<Count>2</Count>
<Number>1</Number>
<Number>2</Number>
</NumbersList>

Answer

After doing the R&D and study and posting my query at the asp.net forum I get the solution.

In my case CollectionDataContract would not help me, For do that I have to use the XmlSerializerFormat

So I rewrite my code like this:

[MessageContract]
public class Messanger
{
    [MessageBodyMember]
    [XmlElement(ElementName = "NumbersList")]
    public NumbersList NumbersList;
}

[DataContract]
[XmlRoot(ElementName = "NumbersList")]
public class NumbersList
{
    [XmlElement(ElementName = "Count")]
    public int Count { get; set; }

    [XmlElement(ElementName = "Number")]
    public List<int> Number { get; set; }
}

and It will generate the XML for me like this:

<NumbersList>
    <Count>2</Count> //Extra property to parse
    <Number>1</Number>
    <Number>2</Number>
</NumbersList>

Here is the link of the forum: https://social.msdn.microsoft.com/Forums/vstudio/en-US/12ceeae4-0284-4a3b-a913-e69811f41b81/collectiondatacontract-with-the-extra-property?forum=wcf