Data Contract using WCF Hosted on Web App

Today, in this article let's dig out another concept with its clear implementation. This concept would be highly useful for day to day programming life and its one of the main concept for WCF developers.
 

Question arises: What is Data Contract?

It is type of standardize relationship which can be established between service and client for data exchange.

Question arises: What is Data Member?

It is part of Data Contract, which is used define some methods, properties which mainly plays an active role during data exchange between client and service.

Question arises: How Data Contract differs from message Contract?

Message Contract is that which describes how the SOAP messages are sent to and from services with header and bodies in the envelop. If you are more prescribed about sending message and where by concentrating on layout then I would suggest you go for message contract. On the other hand, the Data Contracts describes the data structure with supported data types how the client can consume the WCF Service. In other words, It is a standardize relationship between service and client to exchange data.

The Complete Code of DataContractClass.cs looks like this:

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

namespace DataContract1
{
    [DataContract]
    public class DataContractClass
    {
        private double _firstNumber;
        private double _secondNumber;
        private double _dataresult;

        public DataContractClass(double firstnum, double secondnum, double result)
        {

            this._firstNumber = firstnum;
            this._secondNumber = secondnum;
            this._dataresult = result;

        }
        public DataContractClass(DataContractClass simple)
        {
            this._firstNumber = simple._firstNumber;
            this._secondNumber = simple._secondNumber;
            this._dataresult = simple._dataresult;
        }

        [DataMember]
        public double FirstNumber
        {
            get { return _firstNumber; }
            set { _firstNumber = value; }

        }

        [DataMember]
        public double SecondNumber
        {
            get { return _secondNumber; }
            set { _secondNumber = value; }
 
        }

        [DataMember]
        public double DataResult
        {
            get { return _dataresult; }
            set { _dataresult = value; }

        }

    }
}

The Complete Code of IService1 looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace DataContract1
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        DataContractClass Add(DataContractClass data);
        [OperationContract]
        DataContractClass Sub(DataContractClass data);
        [OperationContract]
        DataContractClass Mul(DataContractClass data);
        [OperationContract]
        DataContractClass Div(DataContractClass data);
    }
}

The Complete Code of Service1.svc looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace DataContract1
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    public class Service1 : IService1
    {
        public DataContractClass Add(DataContractClass data)
        {
            var result = new DataContractClass(data);
            result.DataResult = result.FirstNumber + result.SecondNumber; return result;
        }
        public DataContractClass Sub(DataContractClass data)
        {
            var result = new DataContractClass(data);
            result.DataResult = result.FirstNumber - result.SecondNumber; return result;
        }
        public DataContractClass Mul(DataContractClass data)
        {
            var result = new DataContractClass(data);
            result.DataResult = result.FirstNumber * result.SecondNumber;
            return result;
        }
        public DataContractClass Div(DataContractClass data)
        {
            var result = new DataContractClass(data);
            result.DataResult = result.FirstNumber / result.SecondNumber; return result;
        }
    }
}

The Complete Code of Web.Config looks like this:

<?xml version="1.0"?>
<configuration>
  <
system.web>
    <
compilation debug="true" targetFramework="4.0" />
  </system.web>
  <
system.serviceModel>
    <
behaviors>
      <
serviceBehaviors>
        <
behavior>
          <!--
To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <
serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
          <
serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </
serviceBehaviors>
    </
behaviors>
    <
serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <
system.webServer>
    <
modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</
configuration>

The Complete Code of WebForm1.aspx looks like this:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="DataContractWCF.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <style type="text/css">
        .div
        {
            font-family: Cambria;
        }
    </style>
</head>
<
body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <div class="div">
                <center>
                    Vijay's Arthimetic<br />
                    <table>
                        <tr>
                            <td>
                                <asp:Label ID="Label1" runat="server" Text="Please Enter First Number" Font-Bold="true"
                                    ForeColor="Brown" Font-Italic="true"></asp:Label>
                            </td>
                            <td>
                                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                <asp:Label ID="Label2" runat="server" Text="Please Enter Second Number" Font-Bold="true"
                                    ForeColor="Brown" Font-Italic="true"></asp:Label>
                            </td>
                            <td>
                                <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                            </td>
                        </tr>
                        <tr>
                            <td>
                            </td>
                            <td>
                                <asp:Button ID="Button1" runat="server" Text="Addition Button" Width="170px" OnClick="Button1_Click" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                            </td>
                            <td>
                                <asp:Button ID="Button2" runat="server" Text="Substraction Button" Width="170px"
                                    OnClick="Button2_Click" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                            </td>
                            <td>
                                <asp:Button ID="Button3" runat="server" Text="Multiplication Button" Width="170px"
                                    OnClick="Button3_Click" />
                            </td>
                        </tr>
                        <tr>
                            <td>
                            </td>
                            <td>
                                <asp:Button ID="Button4" runat="server" Text="Division Button" Width="170px" OnClick="Button4_Click" />
                            </td>
                        </tr>
                    </table>
                    <table>
                        <tr>
                            <td>
                            </td>
                            <td>
                                <asp:Label ID="Label3" runat="server" Visible="false" ForeColor="BlueViolet" Font-Size="Larger"></asp:Label>
                            </td>
                        </tr>
                    </table>
                </center>
        </ContentTemplate>
    </asp:UpdatePanel>
    </div>
    </form>
</body>
</
html>

The Complete Code of WebForm1.aspx.cs looks like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DataContractWCF.ServiceReference1;

namespace DataContractWCF
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            TextBox1.Focus();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (TextBox1.Text == "" || TextBox2.Text == "")
                {
                    Label3.Text = "<b><i>Please Enter Some Values";
                    Label3.Visible = true;

                }
                else
                {
                    var objClient = new Service1Client();
                    var objClass = new DataContractClass();
                    objClass.FirstNumber = Convert.ToDouble(TextBox1.Text);
                    objClass.SecondNumber = Convert.ToDouble(TextBox2.Text);
                    var datares = ((IService1)objClient).Add(objClass);
                    Label3.Text = "The Addition of:&nbsp" + objClass.FirstNumber + "&nbsp and &nbsp" + objClass.SecondNumber + "&nbsp is :<b>&nbsp" + datares.DataResult;
                    Label3.Visible = true;
                    TextBox1.Text = "";
                    TextBox2.Text = "";
                }

            }
            catch (Exception exception)
            {
                exception.Message.ToString();
            }

        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            try
            {
                if (TextBox1.Text == "" || TextBox2.Text == "")
                {
                    Label3.Text = "<b><i>Please Enter Some Values";
                    Label3.Visible = true;

                }
                else
                {
                    var objClient = new Service1Client();
                    var objClass = new DataContractClass();
                    objClass.FirstNumber = Convert.ToDouble(TextBox1.Text);
                    objClass.SecondNumber = Convert.ToDouble(TextBox2.Text);
                    var datares = ((IService1)objClient).Sub(objClass);
                    Label3.Text = "The Substraction of:&nbsp" + objClass.FirstNumber + "&nbsp and &nbsp" + objClass.SecondNumber + "&nbsp is :<b>&nbsp" + datares.DataResult;
                    Label3.Visible = true;
                    TextBox1.Text = "";
                    TextBox2.Text = "";
                }

            }
            catch (Exception exception)
            {
                exception.Message.ToString();

            }
        }

        protected void Button3_Click(object sender, EventArgs e)
        {
            try
            {
                if (TextBox1.Text == "" || TextBox2.Text == "")
                {
                    Label3.Text = "<b><i>Please Enter Some Values";
                    Label3.Visible = true;
 
                }
                else
                {
                    var objClient = new Service1Client();
                    var objClass = new DataContractClass();
                    objClass.FirstNumber = Convert.ToDouble(TextBox1.Text);
                    objClass.SecondNumber = Convert.ToDouble(TextBox2.Text);
                    var datares = ((IService1)objClient).Mul(objClass);
                    Label3.Text = "The Multiplication of:&nbsp" + objClass.FirstNumber + "&nbsp and &nbsp" + objClass.SecondNumber + "&nbsp is :<b>&nbsp" + datares.DataResult;
                    Label3.Visible = true;
                    TextBox1.Text = "";
                    TextBox2.Text = "";
                }
            }
            catch (Exception exception)
            {
                exception.Message.ToString();

            }
        }

        protected void Button4_Click(object sender, EventArgs e)
        {
            try
            {
                if (TextBox1.Text == "" || TextBox2.Text == "")
                {
                    Label3.Text = "<b><i>Please Enter Some Values";
                    Label3.Visible = true;

                }
                else
                {
                    var objClient = new Service1Client();
                    var objClass = new DataContractClass();
                    objClass.FirstNumber = Convert.ToDouble(TextBox1.Text);
                    objClass.SecondNumber = Convert.ToDouble(TextBox2.Text);
                    var datares = ((IService1)objClient).Div(objClass);
                    Label3.Text = "The Division of:&nbsp" + objClass.FirstNumber + "&nbsp and &nbsp" + objClass.SecondNumber + "&nbsp is :<b>&nbsp" + datares.DataResult;
                    Label3.Visible = true;
                    TextBox1.Text = "";
                    TextBox2.Text = "";
                }
            }
            catch (Exception exception)
            {
                exception.Message.ToString();

            }
        }
    }
}

The Output of the Application looks like this:

DataContractOne.png
 

The Addition Operation Output looks like this:

DataContractTwo.png
 

The Invalid Data Results Output looks like this:

DataContractThree.png
 

I hope this article is useful for you.

Up Next
    Ebook Download
    View all
    Learn
    View all
    MVC Corporation is consulting and IT services based company.