Mukarram Mukhtar

LINQ with WCF in .NET

In this tutorial we’ll create two .NET projects:

  1. The WCF service that will use LINQ to SQL and talk with a database.
  2. A web application i.e. the client of the above WCF service.

Creating WCF Service:

Alright then, let’s get started!

  • Start Visual Studio 2010 (2008 will also work)
  • Select New Project from the top left options
  • In the New Project dialogue box, you’ll see a left hand side panel called Installed Templates, expand Visual C# in the tree view and select WCF in it
  • This will change the available options in the middle panel, select WCF Service Application in the middle panel. Your New Project dialogue box should look something like this:

  • Give a decent name and path to the project and hit OK.
  • When you’ll click OK, the Visual Studio 2010 will create a WCF project for you with a default service added to it. Now we’ll quickly add all the files that we need in the solution before we start coding
  • First we’ll add a DBML object in our project that will link with the database. We’ll use SQL Server’s database. So right click the project file in the solution explorer and select Add New Item. In the Add new dialogue box, you’ll see a left hand panel called Installed Templates, select Data in it. The middle panel will get populated with all the available objects for Data related tasks. Select LINQ to SQL Classes, give a decent name (I usually give the same name as database that this object is going to connect with) to it and click Add button. The dialogue box will look something like this:

  • When you’ll click Add in the above dialogue box, a dbUniversity.dbml object will get added in your solution. Double click that object to open it in the design view. In the design view you’ll see a link to Server Explorer. Click it to open the Server Explorer. In the Server Explorer you can add a connection to a SQL Server and from there you can add database objects in your project. For the purpose of this tutorial, I created a database in my local SQL Server with the name University. I also added two tables namely Teacher and Department in the database. I was successfully able to create a connection with the database and add the two tables by drag n’ drop on the design panel of the dbUniversity.dbml. The design view should look something like this:

  • The obvious relationship between Department and Teacher is one-to-many. Now before we start writing LINQ code. I want to finish adding some other files that are required for this project. So let’s quickly add a new WCF service in our project. We know there is already a default service in the project, but we’ll leave it as it is and add a new one so that we can see what the complete process of adding a new service is. So let’s right click the project in Solution Explorer one more time and select Add New Item. In the New Item dialogue box select Web in the Installed Templates panel and select WCF Service in the middle panel. Give your service a decent name and select Add button in the bottom. The dialogue box will look like this:

  • Now when you’ll click Add button in the above dialogue box, you will notice two new files will get added in your solution a). MyService1.svc b).IMyService1.cs Why the two? If you open MyService1.svc.cs you’ll find your answer. Basically MyService1 class extends – I mean – implements the IMyService1 interface. So yeah, IMyService1 is the interface of our service and that’s why it contains keywords like ServiceContracts and OperationContracts. Who are these contracts with? With the clients of our service. See that’s how it works, when our service is published, it signs a contract with all of the prospective client applications that these are my operational methods, and these are the signatures of those methods with their return types. Clients will connect with our service assuming that our service will abide by this contract. As long as our service abides by its contract the communication between client and the service will continue. If at any point service changes its functionality to the extent that it changes the names of its operational methods or their signatures, the communication will become erratic. The complete Service Oriented Architecture concepts are obviously beyond the scope of our little tutorial, so we’ll pass on that and move forward on adding our one last piece of code file in our project
  • Right click the project in the Solution Explorer and add a simple CS class file, name it DAOTeacher.cs
  • Ok now we’ve added all the required files in our project, before we start coding, we’ll take a quick look at our Solution Explorer to see if everything looks good. Our Solution Explorer should look something like this:

Of course the most important files are in the bottom of the list. Anyways, so now we’ve got everything that we needed and we’re ready to start coding and we’ll start with the hardest part first i.e. DAOTeacher.cs. In DAOTeacher class we just want to see how we can query against a database using LINQ to SQL classes and also we want to explore the new language syntax of LINQ class libraries. Therefore, we’ll create a new method called GetTeacherName, pass in a teacher numeric ID to it and query against the database to get the name of the teacher. The code of DAOTeacher.cs looks like as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Web;
namespace prjWCFTest1
{
    public class DAOTeacher
    {
        public string GetTeacherName(int id)
        {
01            dbUniversityDataContext db = new dbUniversityDataContext();
            string teacherName = string.Empty;
            try
            {
02                teacherName = (from vTeachers in db.Teachers
                                   where (vTeachers.teacher_id == id)
                                   select
                           vTeachers.teacher_name).ToList().FirstOrDefault();                                  
            }
            catch (Exception exc) { teacherName = exc.ToString(); }
            return teacherName;
        }
    }
}

In line # 01, we added a database context. This is a new class that .NET created for us with the prefix of the same name that we gave to our DBML object. The data context class contains all the information that we dragged n’ dropped in the design view of the DBML object. The data context has different overloaded functions that we can use, e.g. we can pass the database connection string at the run-time to instantiate the context object, a feature which is sometimes useful if you’re deploying the same application from Dev to QA or Production environments and want to pass the database connection string dynamically (again, this discussion is beyond the scope of the tutorial). So in line # 02 we’re basically querying against the database. The line is pretty much similar to the following SQL query:

SELECT TOP 1 teacher_name FROM Teachers WHERE teacher_id = id

But the beauty of the line # 02 is you get intelliSense here! And since IDE compiles it, you rule out all the chances of writing erroneous SQL queries. Though in this particular example, the query is pretty simple, but don’t think that LINQ is capable of handling only simple ones. I’ve written some very complex LINQ queries lately, and trust me, with all those inner and outer joins, LINQ made it very easy for me as compared to it if I had to write them in SQL as inline queries. Once you’ll get your hands on LINQ queries, you’ll find them really very interesting and easy to use. OK so we’re done with the hardest part, really, that was the hardest part in this project. Now we’ll quickly write code in the MyService1.svc.cs as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace prjWCFTest1
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "MyService1" in code, svc and config file together.
    public class MyService1 : IMyService1
    {
        private DAOTeacher daoTeacher = new DAOTeacher();
        public string GetTeacherName(int id)
        {
            return daoTeacher.GetTeacherName(id);
        }
    }
}

So simple!

Instantiated our DAO class and called its GetTeacherName() in a public method of the service. Now the only piece missing is we haven’t declared the service’s public method in the Interface. Let’s quickly do that, IMyService1’s code will look like as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace prjWCFTest1
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IMyService1" in both code and config file together.
    [ServiceContract]
    public interface IMyService1
    {
        [OperationContract]
        string GetTeacherName(int id);
    }
}

Alrighty, so we’re all set! Let’s build and run our WCF service. Another cool feature with Visual Studio 2010 is that they’ve attached WCF Test Client with the debugger now. WCF Test Client was already there since they introduced WCF in 2008, but now having it automatically attached with our service is one extra benefit that we can enjoy. Ok so when I ran my project I got the following window, I even entered a teacher ID to invoke the method and it returned me the expected results, take a look:

Before we end discussion on this project, we need to make one more change in it, so that it can be used from client project. The change is we need to make this project run as a website from IIS. In order to do that, we need follow few easy steps as described in the following image:

https://mukarrammukhtar.wordpress.com/web-security-in-net-p1/websecurityprojectproperties1/

Creating WCF Client:

Well, this part is really very simple, so I’ll just quickly go through it. Here are the steps we need to follow to create a WCF client:

  1. Create a web application project in Visual Studio 2010 and name it, let’s say prjWCFClient1
  2. Right click the project in the Solution Explorer and select Add Service Reference option in the popup menu
  3. In the Add Service Reference dialogue box, enter the localhost’s address of the WCF service that we just created, give the service reference a decent name and click OK. The dialogue box will look like this:

And that’s all we need to add in this project. Now let’s code our web page, in Default.aspx write the following code:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="prjWCFClient1._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        Welcome to WCF Client!
    </h2>
    <p>
        Enter Teacher ID to search: <asp:TextBox ID="txtTeacherID" runat="server"></asp:TextBox>
        <asp:LinkButton
            ID="lbtnSearch" runat="server" onclick="lbtnSearch_Click">Search</asp:LinkButton><br />
        <asp:Label ID="lblTeacherName" runat="server" Text=""></asp:Label>
    </p>
</asp:Content>

Note that the master page and Content blocks were added automatically by Visual Studio 2010. The code that I added was only inside the BodyContent block. Since the code is very simple and no explanation is needed for it, I’ll jump to the CS part of it. Write the following code in the Default.aspx.cs file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace prjWCFClient1
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void lbtnSearch_Click(object sender, EventArgs e)
        {
01            MyService1.MyService1Client client = new MyService1.MyService1Client();
02            this.lblTeacherName.Text = client.GetTeacherName(int.Parse(this.txtTeacherID.Text));
        }
    }
}

In line # 01 we are creating the client object. The MyService1Client class has been automatically generated by .NET. This is the object that will actually take our request and bring the result back from the service. It has a few overloaded constructors, one of which can be used by passing End Point URL; a feature useful while the web application is being deployed from Dev to QA or Production environments. Once client object is created you can use its intelliSense to find out what web methods are available for the application.

Now our client application is ready to run, and that’s how it looks like:

So that’s all from my side today. Keep me posted, folks. And don’t hesitate if you want source code of the two projects. Until next time, enjoy programming!

2 Comments »

  1. Thanks for Step by step description , easy for beginner to get hands on WCF

    Comment by Sandhya — November 26, 2012 @ 5:57 pm

  2. Very detailed explanation.Thanks a lot 🙂

    Comment by Harika — April 18, 2014 @ 5:48 am


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: