Sunday 16 December 2012

WCF Sample


Step  1:
Open  SQL Server management studio, then open new query editor and do the following operations,
--command to create new database
create database BookDB
--Shift to BookDB databse from Master DB
use BookDB
--Query to create new tables with colums
create table BookInfo(
book_id int primary key,
book_name  varchar(25),
book_author varchar(25),
book_publisher varchar(25),
book_price varchar(10),
book_availability bit
)
--Query to check any values in BookInfo table
select * from BookInfo
--Inserting first record into BookInfo table
insert into BookInfo(book_id,book_name,book_author,
            book_publisher,book_price,book_availability)
     values('1','ASP.NET','Michel Angel','TKL Publication',
            '255.50',1)
--Query to check any values in BookInfo table
select * from BookInfo
--Inserting second record into BookInfo table
insert into BookInfo(book_id,book_name,book_author,
            book_publisher,book_price,book_availability)
     values('2','C#.NET','Kuttan Pilla','Pilla Publication',
            '655.50',1)
--Query to check any values in BookInfo table
select * from BookInfo
--Inserting  third record into BookInfo table
insert into BookInfo(book_id,book_name,book_author,
            book_publisher,book_price,book_availability)
     values('3','SQL Server 2012','Moudin Kunjalli','Abud Publication',
            '659.50',1)
--Query to check any values in BookInfo table
select * from BookInfo


Step 2:

Create a WCF service Library and name it as WCFBookService and delete the default IServices interface ,Service class and App.conf files .

Step 3:

Create a new public class called BookReqEntity.cs and add System.Runtime.Serialization reference.

#region Using Statements

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

#endregion

namespace WCFBookService
{
    /// <summary>
    /// BookReqEntity class is used for requesting book info on the criteria BookID
    /// </summary>
    [DataContract]
    public class BookReqEntity
    {
        #region Public Properties
        [DataMember]
        public int BookID
        {
            get;
            set;
        }
        #endregion
    }
}



Step 4:

Create a public class called BookResEntity.cs and add the following

#region Using Statements

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

#endregion

namespace WCFBookService
{
    /// <summary>
    /// BookResEntity class is used for deliver book info on the criteria BookID
    /// </summary>
    [DataContract]
    public class BookResEntity
    {
        #region Public Properties
        [DataMember]
        public int BookID
        {
            get;
            set;
        }
        [DataMember]
        public string BookName
        {
            get;
            set;
        }
        [DataMember]
        public string BookAuthor
        {
            get;
            set;
        }
        [DataMember]
        public string BookPublisher
        {
            get;
            set;
        }
        [DataMember]
        public string BookPrice
        {
            get;
            set;
        }
        [DataMember]
        public bool BookAvailability
        {
            get;
            set;
        }
        #endregion
    }
}

Step 5:
Create an interface named it as  IBook and add  System.ServiceModel
#region Using Statements

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

#endregion

namespace WCFBookService
{
    [ServiceContract]

    interface IBook
    {
        [OperationContract]

        BookResEntity GetBookInfo(BookReqEntity bookReqEntity);
    }
}
Step 6:

Add a application configuration file to the current application and modify to
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
      <connectionStrings>
            <add name="conStr" connectionString="Data Source=.;Initial Catalog=BookDB;User ID=sa;Password=abc"/>
      </connectionStrings>
</configuration>

Step 7:

Create its implemetation and named it as Book.cs also make it as public.
Add three additional namespaces

a) System.ServiceModel
b) System.Configuration
c) System.Data.SqlClient


#region Using Statements

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

#endregion

namespace WCFBookService
{
    [ServiceBehavior]
    public class Book : IBook
    {
        [OperationBehavior]
        public BookResEntity GetBookInfo(BookReqEntity bookReqEntity)
        {
           
            BookResEntity bookResEntity = null;
            string Cstring = ConfigurationManager.ConnectionStrings["conStr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(Cstring))
            {
                con.Open();
                string query = String.Format("select * from BookInfo where book_id ={0}", bookReqEntity.BookID);
                SqlCommand cmd = new SqlCommand(query, con);
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    bookResEntity = new BookResEntity()
                    {
                        BookID = dr.GetInt32(0),
                        BookName = dr.GetString(1),
                        BookAuthor = dr.GetString(2),
                        BookPublisher = dr.GetString(3),
                        BookPrice = dr.GetString(4),
                        BookAvailability = dr.GetBoolean(5)
                    };
                }
            };
            return bookResEntity;
           
        }

    }
}

Step 8:

Add another console application and named it as  CustomerHost and make it as public

Add reference –WCFBookService

#region Using Statements

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WCFBookService;
using System.ServiceModel;
#endregion

namespace BookHost
{
   public class BookHostClass
    {
        static void Main(string[] args)
        {
            ServiceHost sHost = null;
            Type t = null;
            try
            {
                t = typeof(Book);
                sHost = new ServiceHost(t);
                sHost.Opened += delegate(object sender, EventArgs er)
                {
                    Console.WriteLine("Book Service Hosted Successfully");
                };
                sHost.Closed += delegate(object sender, EventArgs er)
                {
                    Console.WriteLine("Book Service closed Successfully");
                };
                sHost.Open();
                Console.ReadLine();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }
            finally
            {
                if (sHost != null && sHost.State != CommunicationState.Closed)
                {
                    sHost.Close();
                    Console.ReadLine();
                }
            }
        }
    }
}


Step 9:
Add a appconfig file and specify connection string


<?xml version="1.0" encoding="utf-8" ?>

<configuration>
      <connectionStrings>
            <add name="conStr" connectionString="Data Source=.;Initial Catalog=BookDB;User ID=sa;Password=abc"/>
      </connectionStrings>
 <system.serviceModel>
  <behaviors>
   <serviceBehaviors>
    <behavior name="BookBehaviour">
     <serviceDebug />
     <serviceMetadata httpGetEnabled="true" httpGetUrl="http://localhost:8811/BookServiceAddress/Mex" />
    </behavior>
   </serviceBehaviors>
  </behaviors>
  <services>
   <service behaviorConfiguration="BookBehaviour" name="WCFBookService.Book">
    <endpoint address="http://localhost:8811/BookServiceAddress"
     binding="basicHttpBinding" bindingConfiguration="" name="BookServiceEndPoint"
     contract="WCFBookService.IBook" />
   </service>
  </services>
 </system.serviceModel>
</configuration>


Then do the proccess same like 


Step 10:


Add another Client Console application which act as UI/Client ,name it as BookClient
Do the steps .
a) Add Service refence  your hosted application.
b)Open debug folder of hosted application.Click BookHost.exe.Do not close it just minimize it.
c) Add service reference ,specify 

http://localhost:8811/BookServiceAddress/Mex


Step 11:

On the client Program.cs file edit code like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ClientConsole.BookServiceReference;
namespace ClientConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            using (BookClient b = new BookClient())
            {
                BookReqEntity bReq = new BookReqEntity();
                Console.WriteLine("Enter the Book Id");
                int bId = Convert.ToInt32(Console.ReadLine());
                bReq.BookID = bId;
                BookResEntity bRes = new BookResEntity();
                bRes = b.GetBookInfo(bReq);
                if (bRes != null)
                {
                    Console.Write("Book Id:{0},\nBook Name:{1},\nBook Author :{2},\nBookPublisher :{3},\nBook Price{4},\nBook Availability:{5}", bRes.BookID, bRes.BookName, bRes.BookAuthor, bRes.BookPublisher,
                        bRes.BookPrice, bRes.BookAvailability);
                    Console.ReadLine();
                }
                Console.WriteLine("Search book not found!");
                Console.ReadLine();
            };
           
        }
    }
}

Debug Operations:

First debug the host application,then your client console application.



6 comments: