Wednesday 27 May 2015

What is WCF ? Sample WCF application code in .NET

I  this post will explain very basic sample WCF application with example for beginers.

What is WCF :-

.NET provides various options for creating services under .NET Framework. Before WCF, ASP.NET Web Services are used to ceate service in .NET Framework. Now WCF is the latest programming model for building and developing service-oriented application. WCF allows applications to communicate with each other in distributed environment. WCF is a set of technologies that covers ASMX web services, Web Services Enhancements (WSE), .NET Remoting and MSMQ. In this article, you will learn How to create and consume your WCF application from client app.

Task List

  • WCF application
  • 1 Database Table, 1 Stored Procedure to fetch Employee salary.
  • Client Application(ASP.NET app)

Creating WCF app:-

Open your Visual Studio go to file menu then select new project one window  will open. Now in left tab Select WCF and in right tab select WCF Service Application and choose your app name, location then clock on OK button. See below



























Now your WCF application is ready. It contains one Iterface IService1.cs and one Serive class Service1.cs .


Interface :- 

In the interface I declared one function to fetch Employee salary  see  below

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

namespace WcfServiceDemo
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [FaultContract(typeof(string))]
        [WebInvoke(Method = "POST", UriTemplate = "GetEmpSalary/{EmpId}", RequestFormat = WebMessageFormat.Json,
         ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        string GetEmpSalary(string EmpId);
    }
}


Service class:-

In below Service class I implimented above method see below


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace WcfServiceDemo
{
    public class Service1 : IService1
    {
        // first I will create an Instance of SqlConnection
        static String conString = WebConfigurationManager.ConnectionStrings["TestWebCon"].ConnectionString;
        static SqlConnection con = new SqlConnection(conString);

        public string GetEmpSalary(string EmpId)
        {
            string result = string.Empty;
            SqlCommand cmd = new SqlCommand("[dbo].[getEmployeeSalary]", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@EmpId ", EmpId);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                result = ds.Tables[0].Rows[0].ItemArray[0].ToString();
            }

            else
            {
                result = "Record not found!";
            }
            return result;
        }
    }
}

Note:- You can replace your Interface and service class code  by above code.


Now I will Create a database table  tblEmpMaster.

CREATE TABLE [dbo].[tblEmpMaster](
       [EmpID] [int] NOT NULL,
       [EmpName] [varchar](100) NOT NULL,
       [EmpSalary] [int] NULL,
       [Age] [int] NULL

) ON [PRIMARY]

Let me Insert some records in the above table 

USE [Employee]
GO
INSERT [dbo].[tblEmpMaster] ([EmpID], [EmpName], [EmpSalary], [Age])
 VALUES (101, N'Ram', 50000, 28)
GO
INSERT [dbo].[tblEmpMaster] ([EmpID], [EmpName], [EmpSalary], [Age])
 VALUES (102, N'Naveen', 22000, 25)
GO
INSERT [dbo].[tblEmpMaster] ([EmpID], [EmpName], [EmpSalary], [Age])
 VALUES (103, N'Neetu Singh', 17000, 27)
GO
INSERT [dbo].[tblEmpMaster] ([EmpID], [EmpName], [EmpSalary], [Age])
 VALUES (104, N'R. P Singh', 62000, 23)
GO
INSERT [dbo].[tblEmpMaster] ([EmpID], [EmpName], [EmpSalary], [Age])
 VALUES (105, N'Mohit', 27000, 24)
GO
INSERT [dbo].[tblEmpMaster] ([EmpID], [EmpName], [EmpSalary], [Age])
 VALUES (106, N'Amit', 15000, 26)

GO

And let me create Stored Procedure also

USE [Employee]
GO
Create Procedure [dbo].[getEmployeeSalary]
as
begin
SELECT [EmpSalary] FROM [Employee].[dbo].[tblEmpMaster]

end

Now see final table  with data is below




















Now its time to create client application .

Creating Asp.net Application:-

I hope you are familiar with asp.net application so here I will not tell you how to create it.


.ASPX file

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
     CodeBehind="Default.aspx.cs" Inherits="ClientApp._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <center>
    <div class="jumbotron">
        <h3>Demo App</h3>
        <p class="lead">Client App to Consume WCF service</p>
    </div>
    </center>
<div>
  <table align="center"  width="50%">
      <tr><td>Enter Emp Id</td><td><asp:TextBox ID="TextBox1" runat="server" Width="300px"></asp:TextBox></td></tr>
       <tr><td></td><td></td></tr>
       <tr><td></td><td><asp:Button ID="tbnSubmit" runat="server" Text="Show my Salary"  Width="200px"
            OnClick="tbnSubmit_Click"/></td></tr>

  </table>
    </div>
    <div class="">
        <table align="center"  width="500px"><tr><td>
        <asp:Label ID="lbltxt" runat="server" Text="" style="font-weight: 700"></asp:Label>
            </td></tr></table>

    </div>

</asp:Content>



Design:-

















Now both WCF service and client app are ready. So its a time to onfuigure and consume WCf service.


How Consume or call WCF service from asp.net app(Client app):-


Built your WCF service app and click on Service1.cs class and choose  set as Start Page.
Now click on  run for WCF application one window will display see below














Finally Your WCf service start running and auto hosted on IIs server .


Copy the Service URL and from above window by right click on second node in left tab and the choose the third option Copy Address and add a reference to client app. see below how to copy URL















Open Client app (asp.net app) right click on Add Service Reference..  one window will open past copies addres to Addres text field and click on Go button see below



































Now Service Reference has added to Client app(asp.net app) see below as  ServiceReference1

























Here is the .CS file in which I created a Instance of WCF Service using service reference and then I called a Method GetEmpSalary with EmpId parameter

.CS file:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;


namespace ClientApp
{
    public partial class _Default : Page
    {
       
        protected void Page_Load(object sender, EventArgs e)
        {
         // do do on page load
        }
        protected void tbnSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                if (TextBox1.Text == "")
                {
                    lbltxt.ForeColor = System.Drawing.Color.Red;
                  
                    return;
                }
                // Create an Instance of Service
                ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
                // Call GetEmpDetails method of service and pass EmpId as Parameter
               string salary= client.GetEmpSalary(TextBox1.Text);

                lbltxt.ForeColor = System.Drawing.Color.Blue;
                lbltxt.Text = "Your current salary is (Rs.):-  " + salary;
               
            }
            catch (SystemException ex)
            {
                lbltxt.ForeColor = System.Drawing.Color.Red;
                lbltxt.Text = "Somthing went wrong! Please try again later";
            }

        }
      
    }

}


Now Finally its a time to run Your  client app (asp.net app) and enter any Employee Id from the above table then clock Show my salary button and see result.

See below result:-




















I hope you enjoyed this post and its very useful to you. Please comments your feedback and questions.

No comments:

Post a Comment