WCF Architecture - A Multi-Layered WCF Architecture using C# and Vb.Net - Service Contract in WCF

← PrevNext →

Building distributed application across the network requires architecture, which is robust, secure, reliable and flexible. We cannot leave anything to chance; therefore, the data exchanged over the network from one endpoint to another must go through a process that will ensure a better understanding and sharing of data (messages).

Windows Communication Foundation is a multi-layered architecture that provides developers with many components.

WCF Architecture

Contracts

WCF contracts define what service and operations would it provide to the clients to consume. A WCF service and its client exchange messages using the provided services, on a network. These contracts, not only defines but also decides if a transaction is at all required between the client and service.

Eventually, the contracts also define the security and set conditions for the clients to communicate with a service.

You can define contracts using a programming language of your choice. The language you choose can either be C#, Visual Basic or C++.

Related: Asp.Net Web API Example – AutoComplete Textbox using JQuery and Web API

The Service Contract

The Service Contract is an Interface that defines what operations the client may call and what the service can do in return. The service contract attribute must have a collection of Operation Contract attributes.

I have previously written an article that explains about Creating a WCF Service and calling it using jQuery Ajax. The article illustrates the practical usage of Service and Operation Contracts.

This is practically the first attribute you will see when you add a WCF service to your project for the first time.

Let us create our first WCF service. We will make it look as simple as possible, since it is our first service. Here is a scenario. We have books store and when a user enters the name of a book, the WCF service will return the price of the book.

At the client, we will add an Input box for entering the name of the book and a label, which will show the price of the book. We will call our WCF interface with the click of a button.

Open visual studio and select New Web Site… from the File menu. Right click the project in the Solution Explorer and select Add New Item. Choose the programming language you are comfortable with and find WCF Service from a list of items.

WCF Service in Asp.Net

Name the service as Books.svc and it will create an interface IBook.cs and a class Book.cs file in the App_Code folder. (IBook.vb and Book.vb for Visual Basic)

It automatically creates App_Code with the two files in the solution folder.

You will see that it has created the Service Contract along with an interface named IBooks.

C# Interface (IBook.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

[ServiceContract]
public interface IBook
{
	[OperationContract()]
	string BookPrice(string sBookName);
}
C# class (Book.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

public class Book : IBook
{
    public string BookPrice(string sBookName)
    {
        string sBookPrice = null;
        if (sBookName == "Asp.Net 4 Blue Book")
        {
            sBookPrice = "$56";
        }

        return sBookPrice;
    }
}
Vb.Net (IBook.vb)
Imports System.ServiceModel

<ServiceContract()>
Public Interface IBook

    <OperationContract()>
    Function BookPrice(ByVal sBookName As String) As String

End Interface
Vb.Net class (Book.vb)
Public Class Book
    Implements IBook

    Public Function BookPrice(ByVal sBookName As String) As String Implements IBook.BookPrice
        If Trim(sBookName) = "Asp.Net 4 Blue Book" Then
            BookPrice = "$56"
        End If

        Return BookPrice
    End Function

End Class

Client Inteface

The Markup
<div style="font:15px Arial;">
        <h2><strong>Calling my first WCF Service</strong></h2><br />
        <div>
            <b>Name of the Book</b>:  <input id="txtName" type="text" runat="server" />
        </div>
        <div>
            <b>Price</b>: <label id="price" runat="server"></label>
        </div>
        <div style="margin:10px auto;">
            <input type="button" value="Submit" runat="server" onserverclick="Submit" />
        </div>
</div>
Code behind (C#)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Submit(object sender, EventArgs e)
    {
        Books objBooks = new Books();
        price.InnerText = "It will cost you " + objBooks.BookPrice(txtName.Value);
    }
}
Vb.Net
Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Submit(sender As Object, e As EventArgs)
        Dim objBooks As New Books
        price.InnerText = "It will cost you " & objBooks.BookPrice(Trim(txtName.Value))
    End Sub
End Class

Wow. We have created our first WCF service using a Service Contract, and it is operational. As we have said earlier, that the service contract is incomplete with Operation Contracts. In the above service, we have declared a function named BookPrice attached to an attribute named [OperationContract()].

Operation Contract

The operation contract attribute under the service contract defines various characteristic of the message. Characteristics such as

a) The data type of the message

b) Whether the method returns any value or it is a one-way operation etc.

If you have worked with Asp.Net web service, you will find Operation Contract attribute has similarities with the WebMethod.

The BookPrice function in above example, accepts a string value, i.e. the name of the book and its return type is a string too. It could have been an integer values, since we have added “$” sign, it is a string.

Data Contract

Data Contract describes the structure of data, using which the client and service will exchange data. The WCF runtime uses a method called the Serializer to serialize and de-serialize the data on the network.

Data converted into an XML format before sharing on the network is serialization. Similarly, when the runtime extracts data from an XML file, it is de-serialization.

We have dedicated an entire article on DataContract, especially for beginners.

← PreviousNext →