Create and Read Operations using ASP.NET WCF Services

Description: In this article, we will create a WCF Service that will Insert data into Database and retreive the data from Database. Further we will Consume this service in ASP.NET Web Application and also learn the techniques to generate logs from the client application.

Agenda: In this example, we are having a student table that contains the details of a student and the type of course that he opted for during admission. We will insert student details and retreive them through our client application created in ASP.NET which consumes our WCF service.

Pre-requisite: Knowlege of the Concept of Inheritance, Classes, Interfaces. For a basic knowledge of WCF Services, I recommend to read my previous article which will makes it easy for you to understand this example.

Step 1: Creating Database tables and Stored procedures

Create a database in SQL Server name ‘DEMODB’ and execute the below SQL Commands to generate tables, test data and stored procedures that we will use in WCF service.

CREATE TABLE [dbo].[STUDENTS] ([Student_Id] INT IDENTITY(1, 1) NOT NULL, [Name] NVARCHAR(MAX) NOT NULL, [Gender] NVARCHAR(10) NOT NULL, [Contact_No] NVARCHAR(12) NOT NULL, [Fees] INT NOT NULL, [DateOfJoin] DATETIME NULL, [CourseType] INT NULL, [AnnualFee] INT NULL, [MonthlyFee] INT NULL, PRIMARY KEY CLUSTERED ([Student_Id] ASC));
 
SET IDENTITY_INSERT [dbo].[STUDENTS] ON
 
INSERT INTO [dbo].[STUDENTS] ([Student_Id], [Name], [Gender], [Contact_No], [Fees], [DateOfJoin], [CourseType], [AnnualFee], [MonthlyFee])
VALUES (1, N'John', N'Male', N'2310542310', 250000, N'2016-08-01 09:21:16', 1, NULL, 20000)
 
INSERT INTO [dbo].[STUDENTS] ([Student_Id], [Name], [Gender], [Contact_No], [Fees], [DateOfJoin], [CourseType], [AnnualFee], [MonthlyFee])
VALUES (2, N'James', N'Male', N'2310542310', 250000, N'2016-08-01 09:24:25', 1, NULL, 20000)
 
INSERT INTO [dbo].[STUDENTS] ([Student_Id], [Name], [Gender], [Contact_No], [Fees], [DateOfJoin], [CourseType], [AnnualFee], [MonthlyFee])
VALUES (3, N'Sana', N'Female', N'3302002102', 300000, N'2016-07-22 09:24:25', 2, 300000, NULL)
 
INSERT INTO [dbo].[STUDENTS] ([Student_Id], [Name], [Gender], [Contact_No], [Fees], [DateOfJoin], [CourseType], [AnnualFee], [MonthlyFee])
VALUES (4, N'Albert', N'Male', N'5542103365', 350000, N'2016-07-12 09:24:25', 1, NULL, 30000)
 
INSERT INTO [dbo].[STUDENTS] ([Student_Id], [Name], [Gender], [Contact_No], [Fees], [DateOfJoin], [CourseType], [AnnualFee], [MonthlyFee])
VALUES (5, N'Steve', N'Male', N'8865987455', 450000, N'2016-07-02 09:24:25', 2, 450000, NULL)
 
INSERT INTO [dbo].[STUDENTS] ([Student_Id], [Name], [Gender], [Contact_No], [Fees], [DateOfJoin], [CourseType], [AnnualFee], [MonthlyFee])
VALUES (6, N'Stark', N'Male', N'9988656623', 200000, N'2016-08-11 09:24:25', 1, NULL, 20000)
 
INSERT INTO [dbo].[STUDENTS] ([Student_Id], [Name], [Gender], [Contact_No], [Fees], [DateOfJoin], [CourseType], [AnnualFee], [MonthlyFee])
VALUES (7, N'James', N'Male', N'9899063210', 600000, N'2016-09-01 00:00:00', 2, 600000, NULL)
 
SET IDENTITY_INSERT [dbo].[STUDENTS] OFF
 
CREATE PROCEDURE uspGetStudentDetails @StudentId INT
AS
BEGIN
	SELECT *
	FROM dbo.Students
	WHERE Student_id = @StudentId
END
 
CREATE PROCEDURE [dbo].[uspInsertStudentDetails] (@Name NVARCHAR(max), @Gender NVARCHAR(10), @Contact_No NVARCHAR(12), @Fees INT, @DateOfJoin DATETIME, @CourseType INT, @AnnualFee INT = NULL, @MonthlyFee INT = NULL)
AS
BEGIN
	INSERT INTO [dbo].[STUDENTS]
	VALUES (@Name, @Gender, @Contact_No, @Fees, @DateOfJoin, @CourseType, @AnnualFee, @MonthlyFee)
END

Explanation:

  • We have created a table having Student details and inserted some sample data in it.
  • uspGetStudentDetails will be used in service for fetching the details of students on the basis of his StudentId.
  • uspInsertStudentDetails will be used to insert student details and student id is the Identity column, so, you dont have to pass student id while saving details.

Step 2: Create a new Project in Visual Studio of type Class Library.

We will create our WCF service in this project. Below are the steps to create the new Class Library Project in Visual Studio.

Step 3: Remove any class files that are created by default in this project and Add a new class file named ‘student.cs’ as shown below.

Step 4: Add the following code in this class file.

using System;
using System.Runtime.Serialization;
 
namespace studentService
{
    [KnownType(typeof(ShortTerm)), KnownType(typeof(LongTerm)), DataContract]
    public class Student
    {
        [DataMember(Order = 1)]
        public int StudentId { getset; }
 
        [DataMember(Order = 2)]
        public string Name { getset; }
 
        [DataMember(Order = 3)]
        public string Gender { getset; }
 
        [DataMember(Order = 4)]
        public string ContactNo { getset; }
 
        [DataMember(Order = 5)]
        public int Fees { getset; }
 
        [DataMember(Order = 6)]
        public DateTime DateOfJoin { getset; }
 
        [DataMember(Order = 7)]
        public CourseType Type { getset; }
    }
 
    [DataContract]
    public enum CourseType
    {
        [EnumMember] ShortTerm = 1,
 
        [EnumMember] LongTerm = 2
    }
}

Explanation:

  • We have created a class named Student having 7 DataMembers Ordered in a Serialized format. These DataMembers corresponds to our Database Table Columns.
  • The Student Class is decorated with a KnownType Attribute which will tell the class that it is using the concept of Inheritance.
  • An Enum is created which has two values that corresponds to the type of courses that the student opted for. These enum values are also decorated with EnumMember attributes which tells the service to Serialize them as well.

Step 5: Add two more class files named ‘LongTerm.cs’ and ‘ShortTerm.cs’ and add the below code to them.

namespace studentService
{
    public class LongTerm : Student
    {
        public int AnnualFee { getset; }
    }
}
namespace studentService
{
    public class ShortTerm : Student
    {
        public int MonthlyFee { getset; }
    }
}

Explanation: The above two classes are inherting the base class Student which we created in Step 4. If the student opted for LongTerm CourseType, then AnnualFee will be applicable for him otherwise for ShortTem CourseType, MonthlyFee will be applicable.

Step 6: Now Add a WCF Service Library to this project as shown below. After adding this, 2 files will be added to this project.One is the service file and another is the interface.

After adding the above, your project will look like below.

Step 7: Add the following code to the Interface file.

using System.ServiceModel;
 
namespace studentService
{
    [ServiceContract]
    public interface IStudentService
    {
        [OperationContract]
        Student GetStudentDetails(int studentId);
 
        [OperationContract]
        void InsertStudentDetails(Student student);
    }
}

Explanation: There are two operation contracts. One will fetch the data on the basis of StudentId and Other will insert the data in the Database.

Step 8: Now we will implement these two interface Methods in the Service file. Replace the below code.

namespace studentService
{
    using System;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
 
    public class StudentService : IStudentService
    {
        private readonly string _cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
 
        public Student GetStudentDetails(int studentId)
        {
            try
            {
                var student = new Student();
                using (var con = new SqlConnection(_cs))
                {
                    var cmd = new SqlCommand("uspGetStudentDetails", con) {CommandType = CommandType.StoredProcedure};
                    cmd.Parameters.AddWithValue("@StudentId", studentId);
                    con.Open();
                    var dr = cmd.ExecuteReader();
                    while (dr.Read())
                    {
                        if ((CourseType) dr["CourseType"] == CourseType.LongTerm)
                        {
                            student = new LongTerm
                            {
                                StudentId = Convert.ToInt32(dr["STUDENT_ID"]),
                                Name = dr[1].ToString(),
                                Gender = dr[2].ToString(),
                                ContactNo = dr[3].ToString(),
                                Fees = Convert.ToInt32(dr[4]),
                                DateOfJoin = Convert.ToDateTime(dr[5]),
                                Type = CourseType.LongTerm,
                                AnnualFee = Convert.ToInt32(dr["AnnualFee"])
                            };
                        }
                        else
                        {
                            student = new ShortTerm()
                            {
                                StudentId = Convert.ToInt32(dr["STUDENT_ID"]),
                                Name = dr[1].ToString(),
                                Gender = dr[2].ToString(),
                                ContactNo = dr[3].ToString(),
                                Fees = Convert.ToInt32(dr[4]),
                                DateOfJoin = Convert.ToDateTime(dr[5]),
                                Type = CourseType.ShortTerm,
                                MonthlyFee = Convert.ToInt32(dr["MonthlyFee"])
                            };
                        }
                    }
 
                    return student;
                }
            }
            catch (Exception exception)
            {
                throw exception.InnerException;
            }
        }
 
        public void InsertStudentDetails(Student student)
        {
            try
            {
                using (var con = new SqlConnection(_cs))
                {
                    var cmd = new SqlCommand("uspInsertStudentDetails", con)
                    {
                        CommandType = CommandType.StoredProcedure
                    };
                    cmd.Parameters.AddWithValue("@Name", student.Name);
                    cmd.Parameters.AddWithValue("@Gender", student.Gender);
                    cmd.Parameters.AddWithValue("@Contact_No", student.ContactNo);
                    cmd.Parameters.AddWithValue("@Fees", student.Fees);
                    cmd.Parameters.AddWithValue("@DateOfJoin", student.DateOfJoin);
                    cmd.Parameters.AddWithValue("@CourseType", student.Type);
                    if (student.GetType() == typeof(LongTerm))
                    {
                        cmd.Parameters.AddWithValue("@AnnualFee", ((LongTerm) student).AnnualFee);
                    }
                    else
                    {
                        cmd.Parameters.AddWithValue("@MonthlyFee", ((ShortTerm) student).MonthlyFee);
                    }
 
                    con.Open();
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception exception)
            {
                throw exception.InnerException;
            }
        }
    }
}

Explanation:

  • At the first we are creating the Connection string to the database.
  • In GetStudentDetails Method, we implement the Stored Procedure and pass StudentId as the Parameter. If the course type in Database is of type LongTerm, then service will return AnnualFee field otherwise MonthlyFee.
  • In InsertStudentDetails method, we implement the SP and pass all the details as Parameters and also, if the coursetype is LongTerm, then AnnualFee will be sent to Database otherwise MonthlyFee.

Now, we are done with the Service implementation.

Now, lets host the service using a Console Application.

Step 9: Add a new project to the same solution of type Console Application as shown below.

Step 10: Add reference to the WCF Service project and System.ServiceModel assembly as shown below.

Step 11: Add a config file to add the endpoints for the client application and Database connectionStrings.

Step 12: Add the following Code to Program.cs file.

using System;
using System.ServiceModel;
 
namespace studentServiceHost
{
    public class Program
    {
        public static void Main(string[] args)
        {
            using (var host = new ServiceHost(typeof(studentService.StudentService)))
            {
                host.Open();
                Console.WriteLine($"Host Successfully started at : {DateTime.Now}");
                Console.ReadLine();
            }
        }
    }
}

The above code Starts the host in the Console application.

Step 13: Add the following code to App.config file.

<?xml version="1.0" encoding="utf-8"?>
 
<configuration>
  <connectionStrings>
    <add name="DBCS"
         connectionString="data source=.;Integrated Security=SSPI;database=DEMODB"
         providerName="System.Data.SqlClient" />
  </connectionStrings>
 
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="studentService.StudentService">
        <endpoint address="" binding="basicHttpBinding" contract="studentService.IStudentService">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8733/studentService/StudentService/" />
          </baseAddresses>
        </host>
      </service>
    </services>
  </system.serviceModel>
</configuration>

The above configuration is already explained in detail in my previous article about WCF Services.

Step 14: Now build the project and go to the root directory of the project and move to bin folder as shown below and run the exe file.

Step 15: Now lets Create client application that will consume this WCF Service host. Follow the steps below.

Now add a Webform to it.

Step 16: Add a reference to the service host as shown below. Make sure that Host is running in Console application. This will generate proxy classes to the service.

Step 17: Add the bootstrap reference from Nuget package library to create our webform.

Step 18: Now replace the code of Webform1.aspx with the below code.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="studentApp.WebForm1" %>
 
<!DOCTYPE html>
 
<html lang="en">
<head runat="server">
    <title>Student App</title>
    <link href="Content/bootstrap.css" rel="stylesheet"/>
</head>
<body>
<form id="form1" runat="server">
    <div class="container">
        <div class="jumbotron">
            <div class="form-group" role="form">
                <div class="form-group">
                    <h1>Student Details</h1>
                </div>
                <div class="form-group">
                    <label>Id</label>
                    <asp:TextBox ID="txtId" runat="server" CssClass="form-control"></asp:TextBox>
                </div>
                <div class="form-group">
                    <label>Name</label>
                    <asp:TextBox ID="txtName" runat="server" CssClass="form-control"></asp:TextBox>
                </div>
                <div class="form-group">
                    <label>Gender</label>
                    <asp:TextBox ID="txtGender" runat="server" CssClass="form-control"></asp:TextBox>
                </div>
                <div class="form-group">
                    <label>Contact No</label>
                    <asp:TextBox ID="txtContact" runat="server" CssClass="form-control"></asp:TextBox>
                </div>
                <div class="form-group">
                    <label>Fees</label>
                    <asp:TextBox ID="txtFees" runat="server" CssClass="form-control"></asp:TextBox>
                </div>
                <div class="form-group">
                    <label>Date of Admission</label>
                    <asp:TextBox ID="txtDOJ" runat="server" CssClass="form-control"></asp:TextBox>
                </div>
                <div class="form-group">
                    <label>Course Type</label>
                    <asp:DropDownList ID="ddlCourseType" runat="server" AutoPostBack="True" CssClass="form-control" OnSelectedIndexChanged="ddlCourseType_SelectedIndexChanged">
                        <asp:ListItem Text="Select Course Type" Value="-1">
                        </asp:ListItem>
                        <asp:ListItem Text="Short Term" Value="1">
                        </asp:ListItem>
                        <asp:ListItem Text="Long Term" Value="2">
                        </asp:ListItem>
                    </asp:DropDownList>
                </div>
                <div class="form-group" visible="false" runat="server" id="divAnnualFee">
                    <label>Annual Fee</label>
                    <asp:TextBox ID="txtAnnualFee" runat="server" CssClass="form-control"></asp:TextBox>
                </div>
                <div class="form-group" visible="false" runat="server" id="divMonthlyFee">
                    <label>Monthly Fee</label>
                    <asp:TextBox ID="txtMonthlyFee" runat="server" CssClass="form-control"></asp:TextBox>
                </div>
                <div class="form-group">
                    <asp:Button ID="btnAdd" runat="server" Text="Save" CssClass="btn btn-primary" OnClick="btnAdd_Click"/>
                    <asp:Button ID="btnGet" runat="server" Text="Retreive" CssClass="btn btn-info" OnClick="btnGet_Click"/>
                </div>
                <div runat="server" id="divNotify" visible="False">
                </div>
            </div>
        </div>
    </div>
 
</form>
</body>
</html>

Step 19: Now replace the code of Webform1.aspx.cs file.

using System;
using System.Web.UI;
using studentApp.StudentService;
 
namespace studentApp
{
    public partial class WebForm1 : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
 
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            var client = new StudentServiceClient();
 
            switch ((CourseTypeConvert.ToInt32(ddlCourseType.SelectedValue))
            {
                case CourseType.LongTerm:
                {
                    var student = new LongTerm()
                    {
                        Name = txtName.Text,
                        Gender = txtGender.Text,
                        ContactNo = txtContact.Text,
                        Fees = Convert.ToInt32(txtFees.Text),
                        DateOfJoin = Convert.ToDateTime(txtDOJ.Text),
                        AnnualFee = Convert.ToInt32(txtAnnualFee.Text),
                        Type = CourseType.LongTerm
                    };
                    client.InsertStudentDetails(student);
                    divNotify.Visible = true;
                    divNotify.Attributes.Add("class""alert alert-success visible");
                    divNotify.InnerText = "Hooray! Data Saved Successfully";
                    txtName.Text = "";
                    txtGender.Text = "";
                    txtContact.Text = "";
                    txtFees.Text = "";
                    txtDOJ.Text = "";
                    txtMonthlyFee.Text = "";
                    txtAnnualFee.Text = "";
                }
 
                    break;
                case CourseType.ShortTerm:
                {
                    var student = new ShortTerm()
                    {
                        Name = txtName.Text,
                        Gender = txtGender.Text,
                        ContactNo = txtContact.Text,
                        Fees = Convert.ToInt32(txtFees.Text),
                        DateOfJoin = Convert.ToDateTime(txtDOJ.Text),
                        MonthlyFee = Convert.ToInt32(txtMonthlyFee.Text),
                        Type = CourseType.ShortTerm
                    };
                    client.InsertStudentDetails(student);
                    divNotify.Visible = true;
                    divNotify.Attributes.Add("class""alert alert-success visible");
                    divNotify.InnerText = "Hooray! Data Saved Successfully";
                    txtName.Text = "";
                    txtGender.Text = "";
                    txtContact.Text = "";
                    txtFees.Text = "";
                    txtDOJ.Text = "";
                    txtMonthlyFee.Text = "";
                    txtAnnualFee.Text = "";
                }
 
                    break;
                default:
                    divNotify.Visible = true;
                    divNotify.Attributes.Add("class""alert alert-danger visible");
                    divNotify.InnerText = "Please Select Course Type";
                    break;
            }
        }
 
        protected void btnGet_Click(object sender, EventArgs e)
        {
            var client = new StudentServiceClient();
            var student = client.GetStudentDetails(Convert.ToInt32(txtId.Text));
 
            if (student.Type == CourseType.LongTerm)
            {
                txtAnnualFee.Text = ((LongTerm) student).AnnualFee.ToString();
                divAnnualFee.Visible = true;
                divMonthlyFee.Visible = false;
            }
            else
            {
                txtMonthlyFee.Text = ((ShortTerm) student).MonthlyFee.ToString();
                divMonthlyFee.Visible = true;
                divAnnualFee.Visible = false;
            }
 
            ddlCourseType.SelectedValue = ((int) student.Type).ToString();
            txtName.Text = student.Name;
            txtGender.Text = student.Gender;
            txtContact.Text = student.ContactNo;
            txtFees.Text = student.Fees.ToString();
            txtDOJ.Text = student.DateOfJoin.ToShortDateString();
            divNotify.Visible = true;
            divNotify.Attributes.Add("class""alert alert-success visible");
            divNotify.InnerText = "Hooray! Data Retreived Successfully";
        }
 
        protected void ddlCourseType_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (ddlCourseType.SelectedValue)
            {
                case "-1":
                    divAnnualFee.Visible = false;
                    divMonthlyFee.Visible = false;
                    break;
                case "1":
                    divMonthlyFee.Visible = true;
                    divAnnualFee.Visible = false;
                    break;
                default:
                    divMonthlyFee.Visible = false;
                    divAnnualFee.Visible = true;
                    break;
            }
        }
    }
}

Explanation:

  • In the above code, we are referencing studentService proxy class generated by Service reference.
  • Now, we have all the Members and attributes of the Service.
  • This code simply Invoke the Interface methods and displaying the data in the HTML controls.

Step 20: Now, we can also trace the SOAP messages being exchange by the service between the client and Database. Follow the below steps to enable tracing.

The above steps will add Logging files to the project directory and the path is clearly shown in point 3 and 4 above.

Step 21: Now Press Ctrl + F5 and make sure that the host is running. Below will be the output.

Step 22: Now Lets check the Trace logs.

Below is the Request sent to the database for saving data.

Below is the request send to the server for processing.

Below is the response back from the service. All in XML format.

 

Advertisements