Data Contracts:
Data contracts are the contractual agreement about the format and structure of the payload data (that is, the SOAP body) in the messages exchanged between a service and its consumer.
Data contracts are the preferred WCF way to enable serialization of complex types included in operation signatures, either as parameters or as return values.
Using a data contract, you can specify exactly how the service expects the data to be formatted as XML. The data contract is used by a data contract serializer in WCF client applications to describe how to serialize the data for parameters into XML, and by a data contract serializer in the service to deserialize the XML back into data values that it can process. Values returned by a service are similarly serialized as XML and transmitted back to the client application, which deserializes them.
DataContract Attribute
The DataContract Attribute, defined in the System.Runtime.Serialization namespace, is used to declare a type as a Data contract.
It can be applied to enums, structs, and classes only.
DataMember Attribute
The DataMember Attribute, also part of the System.Runtime.Serialization namespace, is applied only to members and is used to declare that the member should be included in the serialization of the data structure.
EnumMember Attribute
The final Data contract–related attribute to consider is the EnumMemberAttribute. As the name suggests, it is used to declare that a given element of an enum that has been declared with a DataContractAttribute should be considered as part of the Data contract.
Eg: Create a WCF Service and write the following code in the IService.cs file.
[ServiceContract] public interface IService { [OperationContract] Employee GetEmployee(); } [DataContract] public class Employee { string name, job; [DataMember] public string Name { set { name = value; } get { return name; } } [DataMember] public string Job { set { job = value; } get { return job; } } }
Write the following code in the Service.cs
public class Service : IService { public Employee GetEmployee() { Employee emp = new Employee { Name = "Jobin John", Job = "Software Eng" }; return emp; } }
Add a new website to Solution. Place a button and write the following code.
protected void btnDisplay_Click(object sender, EventArgs e) { EmployeeServiceReference.ServiceClient client = new WebApplication1.EmployeeServiceReference.ServiceClient(); EmployeeServiceReference.Employee emp = client.GetEmployee(); Response.Write("Name : " + emp.Name); Response.Write("
Job : " + emp.Job); }
No comments:
Post a Comment