Display Data From WCF To ASP.NET

Hey there,

I hope that you are able to understand the concept of using WCF  and if you have questions, drop it as a comment. For this post, we’ll concentrate mostly on the website project which we created in the previous post. Our aim is to display result shown in the WCF Test Client into our front-end/website.

Create Home Controller

I hope that you are familiar with the concept of MVC as I am going to refer some terms such as Razor, Controller, View and Model through the post. Well if you are new to ASP.Net, i would suggest you to have a quick look on http://www.asp.net/mvc so as to have an idea of what’s going on here.

In your website project, Right-Click on the Controllers folder and Create a new controller name HomeController with an Empty MVC Controller Template. After the controller has been created, you will be automatically redirected to the Controller codes.

We have created a method for the homepage but homepage is not found in the solution. In order to create the page or View, Right-click on the  line where ActionResult is written and click Add View then once again click Add.

Create View

If you want to verify that your view is successfully created, In your solution explorer, locate View -> Home -> Index.cshtml. The View like Index.cshtml is used to write HTML codes and as we are using Razor, this will allow us to write some simple logic directly inside the HTML codes hence making the website easier to maintain.

Access Service Reference in controller method

Back to our HomeController file, we are now going to tweak the Index method. The method will be used to call the data from the Web Service and send it to the Index page.

First we are going to create an object of  Service Reference named DataService in our method:

ServiceReference1.Service1Client DataService = new ServiceReference1.Service1Client();

From the above line of code, we can deduce that

  • ServiceReference1: Name of Service Reference in our website project
  • Service1Client: Name of Service client in our WCF project (Service1.svc)
  • DataService: Variable defined in the controller.

After creating the object, we are going to call the model from the WCF project in the website project. Actually you can call the model directly or you can define again the model in the website project. It’s up to you ;).

ServiceReference1.TvShows TvShowsLists = new ServiceReference1.TvShows();

We have created an object TvShowsLists having TvShows Attributes which were defined in the WCF project.

Finally we tell our web service to insert all result in the TvShowsList:

TvShowsLists = DataService.DisplayTvShows();

In order to make ActionResult to send the TvShowsLists to the Index.cshtml page, we are going to modify the return View().

Replace the current one with this:

return View(TvShowsLists);

Finally, your codes should be like in the screenshot below:


Logic in Index page

In the Index.cshtml, we are going to call the same model defined in our controller. This is written in the first line itself.

@model mywebsite.ServiceReference1.TvShows

When we return the view in the controller, it was attached with a list of TvShows so in the page we are going to specify which model to take. The above code is know as Razor Syntax which is said to overtake HTML5 very soon. After this step, we go back to basic html which is creating a table. I am going to use bootstrap just to make it quicker.

For Bootstrap: https://www.bootstrapcdn.com/ 


I have created my table in the HTML and as you can see there is commented section. This section will be used to display the result using a Razor loop.

The codes below shows how the result are populated:

@for (int i = 0; i < Model.TVID.Count(); i++)





I have used Razor For Loop and based on the count of TVID, the result will be populated. The use @Model is to get one of the property of the model and display it as HTML.


Time to TEST

We have arrived to the last part of this post. All you need to do is start the project and your WCF Test Client but if your project is not built due to some error , kindly read the post once again to make sure you have not missed any steps.



If you have been able to get the same result as above, Congrats to you 😀 as you have managed to know the basic of using WCF with ASP.Net. 😀 😀

Whats Next?

In my future posts, i will demo you how to add another property from the WCF Project and other logic without writing huge amount of codes in the controller

Good Luck 

Kind Regards 

Harshu K Gaonjur 


Connecting Your WCF To ASP.Net Website


If you have been reading this tutorial from the beginning , you might know have idea whats this post will be on, if not, just have a quick look on the first post and follow the remaining posts. After we have created the wcf and enhanced its performance, now we would like to showcase the results in a real website. For today, we’ll connect our web service to a ASP.NET MVC 4 website but it is also possible to other website architecture.

Create Your ASP.NET Project

Fire up your visual Studio and create a new project based on Asp.Net MVC 4 or you can open the existing solution and add another new project. Thats up to you 🙂

Creating MVC 4 Project

For the next step, I will be using a basic MVC 4 project and Razor as View Engine. Here also you can choose other type to define your project.

Define your template

Connecting Your Web Service

After creating your project, we have arrived at a crucial step, Don’t worry, if you have been following well, this will go as well.

You will need to make sure that your WCF Test Client is running. If you are stuck when trying to run your test client, refer to this post to guide you. Back your website project, Right-Click on your Project and navigate to Add -> Service Reference.

You will have another window pop up like below:

Add Service Reference

In the address textbox, you will have to add your wcf link. The latter appears in your WCF Test Client. Navigate to the test client, right – copy the link and paste in the address field.

WCF Test Client URL 

Once you have the url in the field  (e.g: http://localhost:7482/Service1.svc) , click on Go and you will notice Service1 is shown. You can either rename the namespace or leave it to the default. Click Ok to allow the connection. Make sure your WCF Test Client stays running all the time!!!

Service Reference Added


If you have successfully connected the web service to your website, it means that you only need to display the data from the wcf to the website. No trouble, I’ll show you in the next post which will be a short one. We will use bootstrap to make our website more interactive. 😉

Good Luck 

Kind Regards 

Harshu K Gaonjur

Enhance Your Web Service

Hey there,

To have a recap about the main topic, head over here or if you want to recall the previous post, read it from here. This post will be a short one compared to the previous one. We will be focusing on how to improve your web service for better communication between your database and your website.

First of all, you need to familiar with the term of ConcurrencyMode. In a simple definition, the term is used to tell your web service in what way you want your web service to send its instance. For now, the WCF supports Single-Threaded or multi-Threaded as modes of operation.

A short explanation for each mode based from MSDN:

Member name Description

The service instance is multi-threaded. No synchronization guarantees are made. Because other threads can change your service object at any time, you must handle synchronization and state consistency at all times.


The service instance is single-threaded and accepts reentrant calls. The reentrant service accepts calls when you call another service; it is therefore your responsibility to leave your object state consistent before callouts and you must confirm that operation-local data is valid after callouts. Note that the service instance is unlocked only by calling another service over a WCF channel. In this case, the called service can reenter the first service via a callback. If the first service is not reentrant, the sequence of calls results in a deadlock. For details, seeConcurrencyMode.


The service instance is single-threaded and does not accept reentrant calls. If the InstanceContextMode property is Single, and additional messages arrive while the instance services a call, these messages must wait until the service is available or until the messages time out.


How to Apply ConcurrencyMode?

Don’t stress yourself with all the theories above, the practical is easier 😛 … Open your Service1.svc located in your project.

The codes that you are going to insert will be before defining the class which is:


You will mostly write attributes to define the properties of your web service. The following attribute will make your service a single threaded:

[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single)]

Using the Single Threaded, the WCF will not call again into the object so long as any method is running. It will only be available when the service is at rest. You will need to make that applying a serviceBehaviour might decrease or increase your service performance.

Single Threaded Mode

For this tutorial, i will make my web service as using Multi-Thread might change my objects and also i have not many methods to be called in my service.

Another tweak I would like to point out is InstanceContextMode, which specifies number of service instances available for handling calls located in the incoming request.

There are three types which are available for now:

Member name Description

A new InstanceContext object is created prior to and recycled subsequent to each call. If the channel does not create a session this value behaves as if it were PerCall.


A new InstanceContext object is created for each session.


Only one InstanceContext object is used for all incoming calls and is not recycled subsequent to the calls. If a service object does not exist, one is created.

For my current web service, I will stick to create an instance per call. This can be done by adding another attribute next to the ConcurrencyMode :

InstanceContextMode = InstanceContextMode.PerCall


The aim of this post is to showcase how flexible the WCF can be. There are also many properties which i have not yet tested or worked on it such as tweaking the System.web or removing http module to make it lighter, but i will keep updating you for more properties.

Happy Coding and Time for Game of Thrones 😀 


Harshu Kumar Gaonjur

Customizing The Windows Communication Foundation (WCF)


If you have been following the first part which is Intro To Windows Communication Foundation, it’s time for us to customize our WCF solution according to our requirements. If you seemed lost in this post, please have a quick look at the first part so that you might have an idea how to initialize the WCF solution.

For this part, we are going to display data from our database to the Service itself. This will allow us to check whether our data is being retrieved correctly. I will be using SQL Server 2012 as Database Management System.

I will skip the part of creating the database and inserting data but if you have any problem with the database, drop me a comment and I might guide you for the setup of database. In short, I have created a table named “My_TvShows” with schema “dbo” and database name “JustGetCodes” and inserted some TV shows name with its ratings.

With the following SQL Statement “SELECT * FROM JustGetCodes.dbo.My_TvShows“, the following result will be displayed:

SQL Query

We will now display the same result within the WCF Solution and  also execute same SQL Query using C# Codes.

Create a database connection in Web Config file
  • Head over Web.Config file in your solution
  • Add the following XML Tag after the </appSettings> and save the file.
  • Note: Your connection is different from mine! 
    • <connectionStrings>
      <add name=”myConnectionString” connectionString=”Data Source=HP350G1; Trusted_Connection=Yes; Initial Catalog=JustGetCodes;”/> </connectionStrings>

      Connection String in Web.Config
Create a Model Class named TvShows.cs

The TvShows.cs class will store the details received from the database in the model TvShows

  • Right-Click on the Project and Add new Folder as “Model
  • Right-Click on the Model Folder and Add a new class named “TvShows.cs
  • Insert the following code snippets to declare the properties of the TvShows class
    • public int[] TVID { get; set; }
      public string[] TvShowsName { get; set; }
      public int[] Ratings { get; set; }

Create the method to display in Service1.svc.cs

It’s time to dive into some codes now. We’ll create a method named as DisplayTvShows and return all TvShows just like we saw in the SQL Query

  • Head Over Service1.svc.cs and add the connection string just after the Service1 is declared
    • string connectionString = ConfigurationManager.ConnectionStrings[“myConnectionString”].ConnectionString;

      Connection in Service1.svc.cs
  • Create the method using the following code :
    • public TvShows DisplayTvShows() {
      TvShows AllShows = new TvShows();

      //SQL QUERY goes here

      return AllShows;

      • The above method is expecting a type “TvShows” to return as result
      • An empty list named AllShows is created and is returned just to avoid Visual Studio to show any error. (Tip: If you working in team on the same file, it is better to correct all errors else your team members won’t be able to compile the file)
Configuring the method to execute the SQL Statement

Still on the same file, we are now going to write some codes that will look for the database connection and also calls the SQLClient to execute the statement.

  • Remove the Line “//SQL QUERY goes here” and enter the following:
    • //Define some variable to store data temporarily
      var tvId = new List<int>();
      var TvShows = new List<string>();
      var Ratings = new List<int>();using (SqlConnection con = new SqlConnection(connectionString))
      string Query = “SELECT * FROM JustGetCodes.dbo.My_TvShows”;
      SqlCommand cmd = new SqlCommand(Query, con);
      cmd.CommandType = System.Data.CommandType.Text;
      cmd.CommandTimeout = 0;using (SqlDataReader sdr = cmd.ExecuteReader())
      while (sdr.Read())
      //Make Sure that the columns heading are same as in the SQL Table


      //Attach the Lists to the Model

      AllShows.TVID = tvId.ToArray();
      AllShows.TvShowsName = TvShows.ToArray();
      AllShows.Ratings = Ratings.ToArray();

      catch (Exception ex)
      throw ex;


      //Close the database connection

  • As you might have noticed, the string Query is written directly as SQL Statement, well for now we’ll leave it as it is. We’ll improve later on using parameters and stored procedure. 😛
  • The codes above will execute the SQL Statement and as long as the SQLDataReader is retrieving data, it will attach them to the different small lists. At the end the small list will be attached the Model. I prefer to do this way so that in the future we can do some manipulation before adding to the model.
  • The final codes should appeared as below:
Codes for DisplayTvShows()
Making our method public to the service

The final part is to inform the service that this method is available to connect to any client.

  • Head over to IService1.cs and enter the following code:
    • [OperationContract]
      TvShows DisplayTvShows();

      Declaring Method in IService.cs
  • The [OperationContract] attribute tells the service that the method “TvShows DisplayTvShows()” is a part of the service now. Guess you managed to know the term of OperationContract now. 😀


Time To Test

After we make sure that there is no error on any file after building the solution, it’s time for the verdict :D. Don’t worry, WCF provide an interface for test client so that you can view your results directly in a console.

  • Right-Click on the “Service1.svc” and set as Start Page
  • Run your solution by pressing on the small play icon
  • You will see your method “DisplayTvShows()” in the console, if so, well you are on 50% on completion 😀
WCF Test Client
  • Double click on the method and click invoke and then Ok
  • Watch the Magic 😀
  • You will now be able to view same data from the SQL Statement in the console by expanding the different properties.
Final Results

Note: Your result might be different from mine depending the records inserted in the table

This is pretty much as starting to understand the WCF. For my next post we’ll try to make service more accessible by adding some properties.

Good Luck 😀

Best Wishes 

Harshu Kumar Gaonjur 



Intro To Windows Communication Foundation (WCF)

Hey there,

If you have been developing on ASP.NET 4, you might have an idea of using WCF in your website and if not, Windows Communication Foundation (WCF) is programming platform and runtime system for building and configuring your network-distributed services. In technical terms, it acts as middle layer between your database and your website. It also handles the communication and data between the two ends.

Requirements for creating your first WCF :
  • ASP.NET 4 Framework or Above
  • Visual Studio 2013 or Above
Optional Requirements: 
  • SQL Server 2012 or Above
  • Azure SDKs and Tools
    • Hosting your WCF on Azure
  • IIS 7.0
    • Configuring your WCF on IIS 7.0


Creating Your First WCF Project: 
  • Fire-up your Visual Studio 2013 or Above and Click on New Project
  • Locate WCF in the category and Select WCF Service Application
  • Name your project and Click Ok to create it
Setup WCF Project
Quick look at your project:


Quick look at WCF Project



After Visual Studio has initialize your project, you will be presented with these default classes above. Lets take a quick look at the classes that you will be using:

  • IService1.cs:
    • This class will display the methods created in the Service1.svc.cs to anyone website calling this service by using OperationContract.
    • You will be able to create DataContract (think of it as Model) to pass parameters in your methods.
  • Service1.svc:
    • This class is used to create methods or manipulate data in the WCF.
    • Consider it as the heart of the Service/WCF.
  • Web.Config:
    • All the settings of the project will be stored in this config class.

(Don’t worry if you came across some new terms or keywords, we’ll tackle each of them in the next post) 🙂

Good Luck for this new experience 😀

Kind Regards

Harshu K Gaonjur