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
- }
- }
- 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; }
- }
- }
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();
- }
- }
- }
- }
















Aashil KatkoriaPosted Apr 1, 2024, 3:24 PM
HI Ankit Its nice Content, can u please share me your number i have same project in my office and i am stuck, can u help me out
Hari ShankerPosted Sep 19, 2016, 6:51 AM
Nice ..Thanks for sharing.
Prasanna MuraliPosted Aug 28, 2016, 9:27 PM
Nice one...
Ramesh PalaniappanPosted Aug 24, 2016, 12:52 AM
Good one
Vignesh ManiPosted Aug 23, 2016, 9:09 AM
Good one
Sinraj VPosted Aug 23, 2016, 6:34 AM
Nice one....