Microsoft WCF Service Consumption in a ASP.Net web Application

 

Introduction:

Here I will explain how to use or consume Microsoft WCF (windows communication foundation) service in web application using asp.net.

 

Description:

In this article you will get a good idea to develop a wcf service and some wcf contracts. Microsoft gave us a chance to use a service in all the hosted environments.

 

Creating simple application using WCF:

Open Visual Studio and click file ---> New ---> Website Under that select WCF Service and give name for WCF Service and click OK.

 

       

 

Once you created application you will get default class files including Service.cs and IService.cs. (here I used WCFServiceSample as My webservice solution name)

             

Here IService.cs is an interface it does contain Service contracts and Data Contracts and Service.cs is a normal class inherited by IService where you can all the methods and other stuff.

 

Now open IService.cs add the following namespaces

 

using System.Collections.Generic;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Linq;

using System.Text;

 

 

[ServiceContract]

public interface IService

{

     [OperationContract]

     string GetData(int value);

 

    // TODO: Add your service operations here

    [OperationContract]

    List<UserDetails> GetEmployeeDetails(int EmpID);

 

    [OperationContract]

    string InsertEmployeeDetails(UserDetails userInfo);

}

 

// Use a data contract as illustrated in the sample below to add composite types to service operations.

 [DataContract]

public class UserDetails

{

    string EmpID = string.Empty;

    string firstname = string.Empty;

    string lastname = string.Empty;

    string location = string.Empty;

 

    [DataMember]

    public string EmployeeID

    {

        get { return EmpID; }

        set { EmpID = value; }

    }

 

    [DataMember]

    public string FirstName

    {

        get { return firstname; }

        set { firstname = value; }

    }

 

    [DataMember]

    public string LastName

    {

        get { return lastname; }

        set { lastname = value; }

    }

 

    [DataMember]

    public string Location

    {

        get { return location; }

        set { location = value; }

    }

}

 

After that open Service.cs class file and add the following namespaces

 

using System;

using System.Collections.Generic;

using System.Configuration;

using System.Data;

using System.Data.SqlClient;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

 

After that write the following code:

 

public class Service : IService

{

    private string strConnection = ConfigurationManager.ConnectionStrings["dbconnection"].ToString();

   

    public string GetData(int value)

    {

           return string.Format("You entered: {0}", value);

    }

 

    public List<UserDetails> GetEmployeeDetails(int EmpID)

    {

        List<UserDetails> userdetails = new List<UserDetails>();

        using (SqlConnection con=new SqlConnection(strConnection))

        {

            con.Open();

            SqlCommand cmd = new SqlCommand("Select EmpID, EmpFirstName,EmpLastName,Location from EmployeeDetails where EmpID = @EmpID", con);

            cmd.Parameters.AddWithValue("@EmpID", EmpID);

            SqlDataAdapter da = new SqlDataAdapter(cmd);

            DataTable dtresult = new DataTable();

            da.Fill(dtresult);

 

            if(dtresult.Rows.Count>0)

            {

              for(int i=0;i<dtresult.Rows.Count;i++)

              {

                  UserDetails userInfo = new UserDetails();

 

                  userInfo.EmployeeID = EmpID.ToString();

                  userInfo.EmployeeID = dtresult.Rows[i]["EmpID"].ToString();

                  userInfo.FirstName = dtresult.Rows[i]["EmpFirstName"].ToString();

                  userInfo.LastName = dtresult.Rows[i]["EmpLastName"].ToString();

                  userInfo.Location = dtresult.Rows[i]["Location"].ToString();

 

                  userdetails.Add(userInfo);

              }

            }

            con.Close();

        }

        return userdetails;

    }

 

    public string InsertEmployeeDetails(UserDetails userInfo)

    {

        string strMessage = string.Empty;

        using (SqlConnection con=new SqlConnection(strConnection))

        {

            con.Open();

            SqlCommand cmd = new SqlCommand("insert into EmployeeDetails(EmpFirstName,EmpLastName,Location) values(@FName,@LName,@Location)", con);          

 

            cmd.Parameters.AddWithValue("@FName", userInfo.FirstName);

            cmd.Parameters.AddWithValue("@LName", userInfo.LastName);

            cmd.Parameters.AddWithValue("@Location", userInfo.Location);

 

            int result= cmd.ExecuteNonQuery();

            if(result==1)

            {

                strMessage = userInfo.EmployeeID+ " Details inserted successfully";

            }

            else

            {

                strMessage = userInfo.EmployeeID + " Details not inserted successfully";

            }

            con.Close();

        }

        return strMessage;

    }

}

Now set the database connection string in web.config file because in above I am getting the connection string from web.config file.

 

<connectionStrings>

          <add name="dbconnection" connectionString="Data Source=MYPC;Integrated Security=true;Initial Catalog=testdb"/>

</connectionStrings>

 

Our WCF service ready to use with basicHttpBinding. Now we can call this WCF Service method console applications.


Testing Purpose : For testing, Run this application and put it as is it is and implement the webapplication and run that application also. That’s it your application can consume that wcf service.

 

In my next article we will discuss about how to consume this WCF service in Asp.Net Web Application.