.NET Zone is brought to you in partnership with:

I am Microsoft C# MVP July - 2012 My name is Pranay Rana. Currently, I'm working as senior software engineer in a mid-sized company (Ahmedabad). I have 5 years of the experience in web development with Asp.Net, C# and MS SQL server. For me, the definition of programming is: something that you do once and that gets used by multiple users for many years Pranay is a DZone MVB and is not an employee of DZone and has posted 34 posts at DZone. You can read more from them at their website. View Full User Profile

Responsive WCF Service With an ICallBack Interface

07.22.2012
| 1762 views |
  • submit to reddit
In this post I am going to discuss about the development of a WCF callback service which replies back to its consumer i.e service client, as well as about ICallBack Interface implementation which provides response to the user on screen.

Here I designed WCF service which is place order for client and reply back to client that order placed successfully or not. ICallBack interface implemented on page display response to client. Before I discuss more here is the screen that shows output

Place Order

WCF service placing order
 
Order placed successful or not

To accomplish this whole program get divide in two part
1) Design of callback WCF service
2) Design of WEB page with ICallBack interface to provide response on screen

Design of callback WCF service
Starts with the configuration file of WCF service. To make service reliable i.e send response back to client once task done.
<configuration>
  <system.servicemodel>
    <bindings>
      <wsdualhttpbinding>
        <binding bypassproxyonlocal="true" name="sampleBinding" usedefaultwebproxy="true">
      </binding></wsdualhttpbinding>
    </bindings>
    <services>
      <service behaviorconfiguration="returnFaults" name="Service.DemoService">
        <endpoint binding="wsDualHttpBinding" bindingconfiguration="sampleBinding" contract="Service.IDemoService">
      </endpoint></service>
    </services>
    <behaviors>
      <servicebehaviors>
        <behavior name="returnFaults">
          <servicedebug includeexceptiondetailinfaults="true">
          <servicemetadata httpgetenabled="true">
        </servicemetadata></servicedebug></behavior>
      </servicebehaviors>
    </behaviors>
  </system.servicemodel>
  <system.web>
    <compilation debug="true">
  </compilation></system.web>
</configuration>

Service file

using System;
using System.ServiceModel;
using System.Collections.Generic;
using System.Threading;
using System.Runtime.Serialization;

namespace Service
{
    [ServiceContract(CallbackContract = typeof(IClientCallBack))]
    public interface IDemoService
    {
        
        [OperationContract(IsOneWay = true)]
        void PlaceOrder(OrderItem item);
    }

    public interface IClientCallBack
    {
        
        [OperationContract(IsOneWay = true)]
        void ISOrerPlaceSuccessfully(bool issuccess, float total);
    }

    [DataContract]
    public class OrderItem
    {
        float price;
        string name;
        int qty;
        [DataMember]
        public float Price
        {
            get { return price; }
            set { price = value;}
        }

        [DataMember]
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        [DataMember]
        public int Quantity
        {
            get { return qty; }
            set { qty = value; }
        }
    }

    public class DemoService : IDemoService
    {
        public void PlaceOrder(OrderItem item)
        {
            IClientCallBack callback = OperationContext.Current.GetCallbackChannel();
            bool success = true;
            //process order 
            float total = item.Price * item.Quantity;
            callback.ISOrerPlaceSuccessfully(success, total);
        }
    }
}
Design of WEB page with ICallBack interface to provide response on screen
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebClient.Default" EnableSessionState="True"%>

<!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 runat="server">
    <title></title>
</head>
<body id="formBody" runat="server" >
    <form id="form1" runat="server">
    <div style="text-align:center">
      <h1>Place Order</h1>
    </div>
    <div>
        <table>
           <tr>
             <td><asp:Label ID="lblItemName" runat="server" Text="Label">Item Number :</asp:Label></td>
             <td><asp:Label ID="lblItemValue" runat="server" Text="Label">Test</asp:Label></td>
           </tr>
           <tr>
             <td><asp:Label ID="Label1" runat="server" Text="Label">Price :</asp:Label></td>
             <td><asp:Label ID="Label2" runat="server" Text="Label">500</asp:Label></td>
           </tr>
           <tr>
             <td><asp:Label ID="Label3" runat="server" Text="Label">Qunatity :</asp:Label></td>
             <td><asp:TextBox ID="txtQunatity" runat="server" ></asp:TextBox></td>
           </tr>
        </table>
        <asp:Button ID="Button1" runat="server" Text="Place Order" OnClick="Button1_Click" />
        <asp:Label ID="lblMsg" runat="server"></asp:Label></div>
    
    </form>
</body>
</html>

CS file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebClient.DemoService;
using System.ServiceModel;
using System.Threading;

namespace WebClient
{

    public class CallBack : WebClient.DemoService.IDemoServiceCallback
    {

        public string Message
        {
            get;
            set;
        }
        public void ISOrerPlaceSuccessfully(bool issuccess, float total)
        {
            Thread.Sleep(5000);
            if (issuccess)
                this.Message = "Order with total of : " + total + " placed successfully";
            else
                this.Message = "Order with total of : " + total + " failed to place";
        }
    }

    public partial class Default : System.Web.UI.Page, ICallbackEventHandler
    {
        static CallBack callback;
        DemoServiceClient client;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    //setupClientSideCallback();
                }
                catch
                {
                }
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            setupClientSideCallback();
            callback = new CallBack();
            InstanceContext ic = new InstanceContext(callback);
            client = new DemoServiceClient(ic);
            OrderItem item = new OrderItem();
            item.Name = "Test";
            item.Price = 12;
            item.Quantity = Convert.ToInt32(txtQunatity.Text);
            lblMsg.Text = "Placing Order...";
            client.PlaceOrder(item);
        }

        protected void setupClientSideCallback()
        {
           string ScriptRef = this.ClientScript.GetCallbackEventReference(this, "'" + 0 + "'", "OnCallback", "'" + lblMsg.ClientID + "'");
            formBody.Attributes.Add("onload", ScriptRef);
            string script = " ";
            this.ClientScript.RegisterClientScriptBlock(this.GetType(), "ClientCallback", script);

        }

        string ICallbackEventHandler.GetCallbackResult()
        {
            if (callback!=null && callback.Message != null)
            {
                return  callback.Message;
            }
            return "Placing Order..." ;
        }

        string eventArgument;

        void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
        {
            this.eventArgument = eventArgument;
        } 
    }
}
Published at DZone with permission of Pranay Rana, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)