Saturday, 21 January 2017

ASP.NET Web API with Postman and Fiddler

Description: In this article, we will learn about the concept of ASP.NET Web API using Visual Studio 2015. Also, we will learn to test Web API using Fiddler and Postman Clients.

Agenda:
  • Creating the very basic WebApi project in Visual Studio
  • Create methods to perform CRUD (Create, Read, Update and Delete) operations with WebApi Controller using ADO.NET Entity Framework 6.1.3
  • Learn the way to make your WebApi return data in specific formats like JSON, XML etc.
  • Downloading and installing Fiddler tool and testing the WebApi with it
  • Downloading and installing Postman tool and testing the WebApi with it
ASP.NET Web API is a framework that allow us to build HTTP services over the top of .NET Framework. It is so flexible that it can reach a broad range of clients, including browsers and portable devices. It's main feature, which makes it unique, is that it is RESTful (Representational State Transfer) i.e. all that data is passed over HTTP and not on SOAP like that of WCF Services.

Unlike SOAP, a WebApi works on pre-defined standards i.e. it has pre-defined verbs, known as HTTP verbs, to work. These verbs are mentioned below:
  1. GET - It is used to fetch the data
  2. PUT - It is used to update the data
  3. POST - It is used to create the data
  4. DELETE - It is used to delete the data
Note: ASP.NET WebApi works on the MVC (Model-View-Controller) architectural pattern, so MVC is a pre-requisite.

Creating a WebApi Project in Visual Studio:

Step 1: Run Visual studio on your machine and click on New Project.

Step 2: The below dialog box appears, click on Web under Visual C# tab --> ASP.NET Web Application --> Give the name of the project --> OK.



Step 3: Select the WebApi option and click on OK.



Step 4: Create the Database and Insert some sample data using the following SQL script.
CREATE TABLE [dbo].[Product] (
    [Id]       INT           IDENTITY (1, 1) NOT NULL,
    [Name]     VARCHAR (100) NOT NULL,
    [Price]    INT           NOT NULL,
    [Category] VARCHAR (100) NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
)
 
INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (1, N'Mobile', 500, N'Electronics')
INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (2, N'Tablet', 700, N'Electronics')
INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (3, N'Mouse', 200, N'Electronics')
INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (4, N'Keyboard', 340, N'Electronics')
INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (5, N'Speakers', 5000, N'Electronics')
INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (6, N'T-Shirts', 100, N'Wearables')
INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (7, N'Pants', 120, N'Wearables')
INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (8, N'Jeans', 540, N'Wearables')
INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (9, N'Chips', 50, N'Eatables')
INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (10, N'Coke', 30, N'Eatables')
The final table will be like below.



Now we need to do all the CRUD operations on the above table and data.

Step 5: Create a Class Library project that connects to database and provide us with the required classes and properties using ADO.NET Entity framework.





















Step 6: After clicking on Finish Button, you will see the below EDMX file showing the data-entity relationship as defined in database.



Now, we are done with the connectivity to Database.

Step 7: Now, we need to add the reference of the above created project in our Web Api project, so follow the below steps.





Step 8: Now we need to create a new ProductsController.cs file in the Controllers folder of WebApi Project. This file will contain the methods that corresponds to HTTP verbs that we discussed in the very begining of this tutorial.





Step 9: Add the following code to the ProductsController.cs.
public ProductEntities Entities = new ProductEntities();
 
        public HttpResponseMessage Get()
        {
            try
            {
                return Request.CreateResponse(HttpStatusCode.Found, Entities.Products.ToList());
            }
            catch (Exception)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No Data found");
            }
        }
 
        public HttpResponseMessage Get(int id)
        {
            try
            {
                return Request.CreateResponse(HttpStatusCode.Found, Entities.Products.SingleOrDefault(p => p.Id == id));
            }
            catch (Exception)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No Data found");
            }
        }
 
        public HttpResponseMessage Post([FromBody] Product product)
        {
            try
            {
                Entities.Products.Add(product);
                Entities.SaveChanges();
                var response = Request.CreateResponse(HttpStatusCode.Created, product);
                response.Headers.Location = Request.RequestUri;
 
                return response;
            }
            catch (Exception)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Data not inserted");
            }
        }
 
        public HttpResponseMessage Delete(int id)
        {
            try
            {
                var product = Entities.Products.SingleOrDefault(p => p.Id == id);
                if (product == null)
                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Product not found to delete");
                Entities.Products.Remove(product);
                Entities.SaveChanges();
 
                return Request.CreateResponse(HttpStatusCode.OK, "Product Deleted Successfully");
            }
            catch (Exception)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Product not deleted");
            }
        }
 
        public HttpResponseMessage Put(int id, [FromBody] Product product)
        {
            try
            {
                var entity = Entities.Products.SingleOrDefault(p => p.Id == id);
                if (entity == null)
                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Product not found ");
 
                entity.Category = product.Category;
                entity.Name = product.Name;
                entity.Price = product.Price;
                Entities.SaveChanges();
 
                return Request.CreateResponse(HttpStatusCode.OK, "Product Updated Successfully");
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }
Step 10: Go to App_Start folder of the root directory and open WebApiConfig.cs file and add the following code of lines.
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
config.Formatters.Remove(config.Formatters.XmlFormatter);
The above two lines makes the API, only JSON supported. So, by default, now our API will support only JSON Media type format.

Now, our API is ready. Just add the below connection string to the API's web.config file.
<add name="ProductEntities"
connectionString="metadata=res://*/ProductsModel.csdl|res://*/ProductsModel.ssdl|res://*/ProductsModel.msl;
provider=System.Data.SqlClient;provider connection string="
data source=(local);initial catalog=DemoDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />
Press Ctrl + F5 and navigate to http://localhost:26317/api/products. You will see the details of product table in JSON format as below.



Now, as per the Agenda of this article, we will install Fiddler tool and Postman tool to test the API functionality.

Using Fiddler to test Web Api

Step 1: Download the fiddler from the below url and as shown in the screenshot.



Install the downloaded exe file and run it.

Step 2: First we will check the GET functionality. So, follow the steps shown in screenshot below and you will get the result in JSON format.

fiddlerdel1





Step 2: Now we will test POST (Insert) functionality.







Now the data is inserted on 12th row.

Step 3: Now we will update the data on 12th Id using the PUT functionality.







Now, the data is updated successfully.

Step 4: Now we will DELETE the 12th record.







But, using Fiddler to just test the Web Api functionality looks complicated, so instead of using Fiddler, we can use Postman (Google Chrome Extension).

Using Postman to test Web Api

Step 1: Install Postman App in Google Chrome browser as shown below.



Step 2: Run Postman app from the Apps option in Google chrome browser. So, now testing the GET Functionality.



Step 3: Testing the POST functionality.







So, the record is inserted at 13th row.

Step 4: Testing the PUT functionality.







So, data updated in Database.

Step 5: Finally test the Delete functionality.



Conclusion: Personally, I feel using Postman to test Web Api's and WCF services. We can also use fiddler, but if the API is too complex, so I recommend to use Fiddler as it gives more flexibility to test the services.

Hope you liked the above tutorial. If so, do comment with your compliments and queries. I will try to reply ASAP.

Sunday, 21 August 2016

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"])
                         &nbsnbsp;  };
                        }
                        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.