WCF Data Contracts and Data Members

Leave a comment

WCF Data Contracts define the contract between client and server over what will be exchanged. Here we will go through creating a WCF service and consuming it, noting the data contracts.

First, create a new WCF project:

In this example we will have a data contract for a Customer class. Add code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace Carl.WCFCRM
{
    [ServiceContract]
    public interface IWCFCRM
    {

        [OperationContract]
        string GetNameByPhoneNumber(string PhoneNumber);

        [OperationContract]
        Customer GetCustomer(int PhoneNumber);
    }

    [DataContract]
    public class Customer
    {
        [DataMember]
        public string FirstName { get; set; }

        [DataMember]
        public string LastName { get; set; }

        [DataMember]
        public string PhoneNumber { get; set; }
    }
}

If we run this in a web browser, we can see the service contracts:

Now we will consume the service. Create a console app. Add a service reference and point to the service above:

Add some code. You will see the properties:

Add code to display the serialized object:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Messaging;
using System.IO;
using Carl.CallWCF.WCFService;
using System.Runtime.Serialization;

namespace Carl.CallWCF
{
    class Program
    {
        static void Main(string[] args)
        {
            Customer c = new Customer();

            using (var stream = new MemoryStream())
            {
                var serializer = new DataContractSerializer(typeof(Customer));
                serializer.WriteObject(stream, c);
                stream.Seek(0, SeekOrigin.Begin);
                var reader = new StreamReader(stream);
                Console.WriteLine(reader.ReadToEnd());
                Console.ReadLine();
            }
        }
    }
}

This produces the output:

Note the additional properties for DataMember:

  • EmitDefaultValue
  • IsRequired
  • Name
  • Order

In our service, if we add:

 [DataMember(EmitDefaultValue = false)]
 public string PhoneNumber { get; set; }

We get a different output:

 

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *

four × 3 =