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:
I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.
IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.
THANK YOU, AND LET'S KEEP LEARNING TOGETHER.
CARL