Agenda
In this example, we are having a student table, which contains the details of a student and the type of course, which he opted for during admission. We will insert the student details and retrieve them through our client Application, created in ASP.NET, which consumes our WCF Service.
Pre-requisite
For a basic knowledge of WCF Services, I recommend you read my previous article, which will make it easy for you to understand this example.
Step 1: Create the database tables and stored procedures.
Create a database in SQL Server, name it 'DEMODB' and execute the SQL commands, given below, to generate the tables, test data and stored procedures, which 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 the Service to retrieve the details of the students on the basis of his StudentId.
- uspInsertStudentDetails will be used to insert the student details and student ID is the identity column. Ths, you don't have to pass student ID, while saving the details.
Step 2: Create a new project in Visual Studio of type Class Library.
We will create our WCF Service in this project. The steps are given below to create the new Class Library Project in Visual Studio.
Step 3: Remove any class files, which are created by default in this project and Add a new class file, named 'student.cs', as shown below:
Step 4: Add the code, given below, 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 { get; set; }
-
- [DataMember(Order = 2)]
- public string Name { get; set; }
-
- [DataMember(Order = 3)]
- public string Gender { get; set; }
-
- [DataMember(Order = 4)]
- public string ContactNo { get; set; }
-
- [DataMember(Order = 5)]
- public int Fees { get; set; }
-
- [DataMember(Order = 6)]
- public DateTime DateOfJoin { get; set; }
-
- [DataMember(Order = 7)]
- public CourseType Type { get; set; }
- }
-
- [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, which is using the concept of an Inheritance.
- An Enum is created, which has two values, which 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 code, given below, to them:
- namespace studentService
- {
- public class LongTerm : Student
- {
- public int AnnualFee { get; set; }
- }
- }
- namespace studentService
- {
- public class ShortTerm : Student
- {
- public int MonthlyFee { get; set; }
- }
- }
Explanation
The above two classes are inheriting the base class Student, which we created in Step 4. If the student opted for LongTerm CourseType, AnnualFee will be applicable for him, else for ShortTem CourseType, MonthlyFee will be applicable.
Step 6: Now, add a WCF Service Library to this project, as shown below. After adding this, the two 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, as shown below:
Step 7: Add the code, given below, 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 code, given below:
- 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 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 the database is of type LongTerm, Service will return AnnualFee field, else MonthlyFee.
- In InsertStudentDetails method, we implement the SP and pass all the details as the parameters. Also, if the coursetype is LongTerm, AnnualFee will be sent to the database, else 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 the reference to the WCF Service project and System.ServiceModel assembly is shown below:
Step 11: Add a config file to add the endpoints for the client Application and database connectionStrings.
Step 12: Add the code, given below, 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 code, given above 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 configuration, given above, is already explained in detail in my previous
article about WCF Services.
Step 14: Now, build the project, 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 the client Application, which will consume this WCF Service host. Follow the steps, given 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 code, given below:
- <%@ 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 ((CourseType) Convert.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 invokes the interface methods and displays the data in HTML controls.
Step 20: Now, we can also trace the SOAP messages, being exchanged by the service between the client and database. Follow the steps, given below, to enable the tracing.
The steps, listed above, 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. The output will be given below:
Step 22: Now, lets check the Trace logs.
Below is the Request sent to the database to save the data.
Below, is the request sent to the Server for processing.
Below is the response back from the Service. All are in XML format.