Previous Articles on .NET 4.0/Visual Studio 2010
In my previous articles on CodeProject.com, I have explained the fundamentals of Windows Communication Foundation (WCF), LINQ, LINQ to SQL, Entity Framework, and LINQ to Entities, including:
All above articles are based on .NET 4.0/Visual Studio 2010, so if .NET 4.0/Visual Studio 2010 are good for you, you can open and read any of above articles. For those who are learning WCF/LINQ/EF 4.5 with Visual Studio 2012, above articles are outdated. So from now on, I will update these articles with .NET 4.5/Visual Studio 2012.
New Articles on .NET 4.5/Visual Studio 2012
Following articles are updated ones with .NET 4.5/Visual Studio 2012. I will update the links when I have finished them.
- Implementing a Basic Hello World WCF Service (v4.5) -- this article
- Implementing a WCF Service with Entity Framework (v4.5) -- next article
- Concurrency Control of a WCF Service with Entity Framework (v4.5)
- Introducing LINQ—Language Integrated Query (v4.5)
- LINQ to SQL: Basic Concepts and Features (v4.5)
- LINQ to SQL: Advanced Concepts and Features (v4.5)
- LINQ to Entities: Basic Concepts and Features (v4.5)
In this article, we will implement a basic WCF 4.5 service from scratch. We will build a HelloWorld WCF service by carrying out the following steps:
- Create the solution and project
- Create the WCF service contract interface
- Implement the WCF service
- Host the WCF service in IIS Express
- Create a client application to consume this WCF service
Creating the HelloWorld solution and project
Before we can build the WCF service, we need to create a solution for our service project. We also need a directory in which we will save all the files. Throughout this article, we will save our project source codes in the C:\SOAWithWCFandLINQ\Projects directory. We will have a subfolder for each solution we create, and under this solution folder, we will have one subfolder for each project.
For this HelloWorld solution, the final directory structure is shown in the following image:
You don't need to manually create these directories with Windows Explorer; Visual Studio will create them automatically when you create the solutions and projects.
Now follow these steps to create our first solution and the HelloWorld project:
1. Start Visual Studio 2012 (you can use Visual Studio Ultimate, Premium or Professional throughout this article). If the Open Project dialog box pops up, click on Cancel to close it.
2. Go to menu File | New | Project. The New Project dialog window will appear.
3. From the left-hand side of the window, expand Installed | Other Project Types and then select Visual Studio Solutions as the template. From the middle section of the window, select Blank Solution.
4. At the bottom of the window, type HelloWorld as the Name and C:\SOAWithWCFandLINQ\Projects\ as the Location. Note that you should not enter HelloWorld within the location because Visual Studio will automatically create a folder for a new solution.
5. Click on the OK button to close this window and your screen should look like the following image with an empty solution.
6. Depending on your settings, the layout may be different. But you should still have an empty solution in your Solution Explorer. If you don't see Solution Explorer, go to menu View | Solution Explorer or press Ctrl + Alt + L to bring it up.
7. In Solution Explorer, right-click on the solution and select Add | New Project… from the context menu. You can also go to menu File | Add | New Project… to get the same result. The following image shows the context menu for adding a new project.
8. The Add | New Project window should now appear on your screen. In the left-hand side of this window, select Installed | Visual C# as the template, and in the middle section of the window, select Class Library.
9. At the bottom of the window, type HelloWorldService as the Name. Write C:\SOAWithWCFandLINQ\Projects\HelloWorld as the Location. Again, don't add HelloWorldService to the location, as Visual Studio will create a subfolder for this new project (Visual Studio will use the solution folder as the default base folder for all the new projects added to the solution).
You may have noticed that there is already a template for WCF Service Application in Visual Studio 2012 (actually there are a few WCF templates in Visual Studio). For this very first example, we will not use this template. Instead, we will create everything by ourselves to understand the purpose of each step. This is an excellent way for you to understand and master this new technology. In the next chapter of my new book (see bottom of this article for more details), we will use this template to create the project, so we don't need to manually type a lot of code.
10. Now you can click on the OK button to close this window.
Once you click on the OK button, Visual Studio will create several files for you. The first file is the project file. This is an XML file under the project directory, and it is called HelloWorldService.csproj.
Visual Studio also creates an empty class file called Class1.cs. Later, we will change this default name to a more meaningful one and change its namespace to our own one.
Three directories are created automatically under the project folder—one to hold the binary files, another to hold the object files, and a third one for the properties files of the project.
The window on your screen should now look like the following image:
We have now created a new solution and project. Next, we will develop and build this service. But before we go any further, we need to do two things to this project:
Click on the Show All Files button on the Solution Explorer toolbar, as shown on previous image. Clicking on this button will show all files and directories in your hard disk under the project folder, even those items that are not included in the project. Make sure that you don't have the solution item selected. Otherwise you can't see the Show All Files button.
Lastly, in order to develop a WCF service, we need to add a reference to the System.ServiceModel assembly.
1. In the Solution Explorer window, right-click on the HelloWorldService project, and select Add Reference… from the context menu. You can also go to menu item Project | Add Reference… to do this. The Reference Manager dialog window will appear on your screen.
2. Check System.ServiceModel from the Assemblies\Framework tab and click on OK.
Now, on Solution Explorer, if you expand the references of the HelloWorldService project, you will see that System.ServiceModel has been added. Also, note that System.Xml.Linq is added by default. We will use this later when we query a database.
Creating the HelloWorldService service contract interface
In the previous section, we created the solution and the project for the HelloWorld WCF service. From this section on, we will start building the HelloWorld WCF service. First, we need to create the service contract interface.
1. In Solution Explorer, right-click on the HelloWorldService project, and select Add | New Item… from the context menu. The following Add New Item - HelloWorldService dialog window will appear on your screen.
2. On the left-hand side of the window, select Installed | Visual C# Items as the template, and from the middle section of the window, select Interface.
3. At the bottom of the window, change Name from Interface1.cs to IHelloWorldService.cs.
4. Click on the Add button.
Now an empty service interface file has been added to the project, which we are going to use as service interface.
Follow the steps below to customize it.
1. Add a using statement:
2. Add a ServiceContract attribute to the interface. This will designate the interface as a WCF service contract interface.
3. Add a GetMessage method to the interface. This method will take a string as the input and return another string as the result. It also has an attribute, OperationContract.
string GetMessage(string name);
4. Change the interface to public.
The final content of the file, IHelloWorldService.cs, should look like the following:
public interface IHelloWorldService
string GetMessage(string name);
Implementing the HelloWorldService service contract
Now that we have defined a service contract interface, we need to implement it. For this purpose we will reuse the empty class file that Visual Studio created for us earlier, and modify this to make it the implementation class of our service.
Before we modify this file, we need to rename it. In the Solution Explorer window, right-click on the file, Class1.cs, select rename from the context menu, and rename it HelloWorldService.cs.
Visual Studio is smart enough to change all the related files which are references to use this new name. You can also select the file and change its name from the Properties window.
Next, follow the steps below to customize this class file.
1. Open the file HelloWorldService.cs
2. Change its name from Class1 to HelloWorldService, if this is not done for you.
3. Make it implement the IHelloWorldService implicitly.
public class HelloWorldService: IHelloWorldService
4. Add a GetMessage method to the class. This is an ordinary C# method that returns a string. You can also right click on the interface link, and select Implement Interface to add the skeleton of this method.
public string GetMessage(string name)
return "Hello world from " + name + "!";
The final content of the file, HelloWorldService.cs, should look like the following:
public class HelloWorldService: IHelloWorldService
public String GetMessage(string name)
return "Hello world from " + name + "!";
Now, build the project. If there is no build error, it means that you have successfully created your first WCF service. If you see a compilation error, such as 'ServiceModel' does not exist in the namespace 'System', this is because you didn't add the System.ServiceModel namespace reference correctly. Revisit the previous section to add this reference, and you are all set.
Next, we will host this WCF service in an environment and create a client application to consume it.
Hosting the WCF service in IIS Express
HelloWorldService is a class library. It has to be hosted in an environment so that client applications may access it. In this section, we will learn how to host it using IIS Express. Later, in the next chapter, we will discuss more hosting options for a WCF service.
Creating the host application
There are several built-in host applications for WCF services within Visual Studio 2012. However, in this section, we will manually create the host application so that you can have a better understanding of what a hosting application is really like under the hood. In subsequent chapters, we will learn and use the built-in hosting application.
To host the library using IIS Express, we need to add a new website to the solution. Follow these steps to create this website:
1. In Solution Explorer, right-click on the Solution file and select Add | New Web Site… from the context menu (Always Show Solution must be enabled in Options | Projects and Solutions in order to see the solution file). The Add New Web Site dialog window should pop up.
2. Select Visual C# | ASP.NET Empty Web Site as the template, and leave the Web location as File System. Change the website name from WebSite1 to C:\SOAWithWCFandLINQ\Projects\HelloWorld\HostDevServer and click on OK.
If you cannot find the template ASP.NET Empty Web SIte, make sure you have chosen New Web Site, not New Project in previous step.
3. Now in Solution Explorer, you have one more item (HostDevServer) within the solution. It will look like the following:
4. Next, we need to set the website as the startup project. In Solution Explorer, right-click on the website, HostDevServer, select Set as StartUp Project from the context menu (or you can first select the website from Solution Explorer, and then select menu item Website | Set as StartUp Project). The website, HostDevServer, should be highlighted in Solution Explorer indicating that it is now the startup project.
5. Because we will host HelloWorldService from this website, we need to add a HelloWorldService reference to the website. In Solution Explorer, right-click on the website, HostDevServer, and select Add Reference… from the context menu. The following Reference Manager dialog box should appear:
6. In the Reference Manager dialog box, click on the Solutions\Projects tab, check the HelloWorldService project, and then click on OK. You will see that a new directory (bin) has been created under the HostDevServer website and two files from the HelloWorldService project have been copied to this new directory. Later on, when this website is accessed, the web server (IIS Express) will look for executable code in this bin directory.
Testing the host application
Now we can run the website inside IIS Express. If you start the website, HostDevServer, by pressing Ctrl + F5 or by selecting Debug | Start Without Debugging… in the menu, you will see an empty website in your browser with an error.
If you pressed F5 (or selected Debug | Start Debugging from the menu), you may see a dialog saying, Debugging Not Enabled (as shown below). Choose the option, Run without debugging (equivalent to Ctrl + F5) and click on the OK button to continue. We will explore the debugging options of a WCF service in next chapter. Until then we will continue to use Ctrl + F5 to start the website without debugging.
At this point, you should have the HostDevServer site up and running. This site is actually running inside IIS Express. IIS Express is a lightweight, self-contained version of IIS optimized for developers. This web server is intended to be used by developers only and has functionality similar to that of the Internet Information Services (IIS) server. It also has some limitations, for example, it only supports the HTTP and HTTPS protocols.
When a new website is created within Visual Studio, IIS Express will automatically assign a port for it. You can find your website’s port in the Properties of your website, like in the diagram shown below.
IIS Express is normally started from within Visual Studio when you need to debug or unit test a web project. If you really need to start it from outside Visual Studio, you can use a command line statement in the following format:
C:\Program Files\IIS Express\iisexpress /path:c:\myapp\ /port:1054 /clr:v4.0
For our website, the statement should be like this:
"C:\Program Files\IIS Express\iisexpress"
/path:C:\SOAwithWCFandLINQ\Projects\HelloWorld\HostDevServer /port:1054 /clr:v4.0
IISexpress.exe is located under your program files directory. In x64 system, it should be under your program files (x86) directory.
Modifying the web.config file
Although we can start the web site now, it is only an empty site. Currently, it does not host our HelloWorldService. This is because we haven't specified which service this web site should host, or an entry point for this web site.
To specify which service our web site will host, we can add a svc file to the web site. Since .NET 4.0, we can also use file-less (svc-less) activation service to accomplish this. In this section, we will take the file-less approach to specify the service (please refer to my previous article to see how to do it with a real svc file).
Now let’s modify the web.config file of the website to host our HelloWorldService WCF service. Open the web.config file of the website and change it to be like this:
<compilation debug="false" targetFramework="4.5"/>
Note that the system.serviceModel node is the only code we have added to the config file.
The behavior, httpGetEnabled, is essential because we want other applications to be able to locate the metadata of this service via HTTP. Without the metadata, client applications can't generate the proxy and thus won't be able to use the service.
The following is a brief explanation of the other elements in this configuration file:
- Configuration is the root node of the file.
- system.serviceModel is the top node for all WCF service-specific settings.
- serviceHostingEnvironment is used to specify the hosting environment.
- serviceActivations node is where you specify the service name and its relative address. This configuration element allows you to define virtual service activation settings that map to your WCF service types. This makes it possible to activate services hosted in WAS/IIS without a .svc file.
- Within the serviceBehaviors node, you can define specific behaviors for a service. In our example, we have specified one behavior, which enables the service metadata exchange for the service.
Starting the host application
Now, if you start the website by pressing Ctrl + F5 (don't use F5 or menu option Debug | Start Debugging until we discuss these later), you will still see the same empty website with the same error. However at this time we have a service hosted within this website, so just append HostDevServer/HelloWorldService.svc after the address (it should look like http://localhost:1054/) and you will get the description of this service, that is, how to get the wsdl file of this service and how to create a client to consume this service. You should see a page similar to the following one.
Now, click on the wsdl link on this page and you will get the wsdl xml file for this service. The wsdl file gives all of the contract information for this service. In the next section, we will use this wsdl to generate a proxy for our client application.
Creating a client to consume the WCF service
Now that we have successfully created and hosted a WCF service, we need a client to consume the service. We will create a C# client application to consume HelloWorldService.
In this section, we will create a Windows console application to call the WCF service. Later in this book, we will create other types' applications to test our other WCF services, such as a Winform application, and a WPF application.
Creating the client application project
First, we need to create a console application project and add it to the solution. Follow these steps to create the console application:
1. In Solution Explorer, right-click on the solution, HelloWorld, and select Add | New Project… from the context menu. The Add New Project dialog window should appear, as shown below.
2. Select Visual C# | Console Application as the template, change the project name from the defaulted value of ConsoleApplication1 to HelloWorldClient, and leave the Location as C:\SOAWithWCFandLINQ\Projects\HelloWorld. Click on the OK button. The new client project has now been created and added to the solution.
Generating the proxy and configuration files
In order to consume a non-RESTful WCF service, a client application must first obtain or generate a proxy class.
We also need a configuration file to specify things such as the binding of the service, the address of the service, and the contract.
To generate these two files, we can use the svcutil.exe tool from the command line. You can follow these steps to generate those two files:
1. Start the service by pressing Ctrl + F5 or by selecting menu option Debug | Start Without Debugging (at this point your startup project should still be HostDevServer; if not, you need to set this to be the startup project).
2. After the service has been started, open a command line window, change the directory to your client application folder, then run the command line svcutil.exe tool with the following syntax (SvcUtil.exe may be in a different directory in your machine; and you need to substitute 1054 with your service hosting port):
"C:\Program Files\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools\SvcUtil.exe" http://localhost:1054/HostDevServer/HelloWorldService.svc?wsdl /out:HelloWorldServiceRef.cs /config:app.config
You will see an output similar to that shown in the following screenshot:
Here, two files have been generated: one for the proxy (HelloWorldServiceRef.cs) and the other for the configuration (app.config).
If you open the proxy file, you will see that the interface of the service (IHelloWorldService) is mimicked inside the proxy class and a client class (HelloWorldServiceClient) is created to implement this interface. Inside this client class, the implementation of the service operation (GetMessage) is only a wrapper that delegates the call to the actual service implementation of the operation.
Inside the configuration file, you will see the definitions of HelloWorldService such as the endpoint address, binding, timeout settings, and security behaviors of the service.
You can also create a proxy dynamically at runtime, or call the service through a Channel Factory instead of a proxy. Beware if you go with the Channel Factory approach, you may have to share your interface DLL with the clients.
In a later chapter, we will learn how to generate the proxy and configuration files through Visual Studio when we add a reference to a WCF service (Visual Studio really just calls the same command line tool SvcUtil.exe to do the work).
Customizing the client application
Before we can run the client application, we still have some more work to do. Follow these steps to finish the customization:
1. Reload the app.config file. If you have app.config file open previously, when you switch to Visual Studio 2012, you will be asked to reload app.config file since it has been changed. Click “yes” to reload it.
2. Add the proxy file to the project. In Solution Explorer, first select HelloWorldClient project, click Show All Files to show all the files, now under the HelloWorldClient folder you will see the proxy file (HelloWorldServiceRef.cs). However, this file is not yet included in the project. Right-click on it and select Include In Project to include it in the client project. You can also use menu Project | Add Existing Item … (or the context menu Add | Existing Item …) to add it to the project.
3. Add a reference to the System.ServiceModel namespace. Just as we did for the project, HelloWorldService, we also need to add a reference to the WCF .NET System.ServiceModel assembly. From Solution Explorer, just right-click on the HelloWorldClient project, select Add Reference… and check Assemblies\Framework\System.ServiceModel. Then click on the OK button to add the reference to the project.
4. Modify program.cs to call the service. In program.cs, add the following line to initialize the service client object:
HelloWorldServiceClient client = new HelloWorldServiceClient();
Using the default constructor on the HelloWorldServiceClient means that the client runtime will look for the default client endpoint in the file app.config, which is present due to using the SvcUtil.
Then we can call its method just as we would do for any other object:
Pass your name as the parameter to the GetMessage method so that it prints out a message for you.
Running the client application
We are now ready to run this client program.
First, make sure the service host application HostDevServer has been started. If you previously stopped it, start it now (you need to set HostDevServer as the startup project, and press Ctrl + F5 to start it in non-debugging mode) , or you can just right click on the project HostDevServer and select “View in Browser(Internet Explorer)” from the context menu).
Then, from Solution Explorer, right-click on the project, HelloWorldClient, select Set as StartUp Project, and then press Ctrl + F5 to run it.
You will see output as shown in the following image:
Setting the service application to AutoStart
Because we know we have to start the service host application before we run the client program, we can make some changes to the solution to automate this task, that is, to automatically start the service immediately before we run the client program.
To do this, in Solution Explorer, right-click on Solution, select Properties from the context menu, and you will see the Solution 'HelloWorld' Property Pages dialog box.
On this page, first select the option button, Multiple startup projects. Then change the action of HostDevServer to Start without debugging. Change HelloWorldClient to the same action.
Note HostDevServer must be above HelloWorldClient. If it is not, use the arrows to move it to the top.
Now to test it, first stop the service, and then press Ctrl + F5. You will notice that HostDevServer is started first, and then the client program runs without errors.
Note that this will only work inside Visual Studio IDE. If you start the client program from Windows Explorer (C:\SOAWithWCFandLINQ\Projects\HelloWorld\HelloWorldClient\bin\Debug\HelloWorldClient.exe) without first starting the service, the service won't get started automatically and you will get an error message saying 'There was no endpoint listening at http://localhost:1054/HostDevServer/HelloWorldService.svc'.
In this article, we have implemented a basic WCF service, hosted it within IIS Express, and created a command line program to reference and consume this basic WCF service. At this point, you should have a thorough understanding as to what a WCF service is under the hood. You will benefit from this when you develop WCF services using Visual Studio WCF templates or automation guidance packages. In next chapter, we will explore more hosting options and discuss how to debug a WCF service.
Note: this article is based on chapter 2 of my book "WCF 4.5 Multi-Layer Services Development with Entity Framework (Third Edition)" (ISBN: 1849687668 ISBN 13: 9781849687669). This book is a hands-on guide to learn how to build SOA applications on the Microsoft platform using WCF and Entity Framework. It is updated for VS2012 from my previous book: WCF 4.0 Multi-tier Services Development with LINQ to Entities.
With this book, you can learn how to master WCF, LINQ, Entity Framework and LINQ to Entities concepts by completing practical examples and applying them to your real-world assignments. It is ideal for beginners who want to learn how to build scalable, powerful, easy-to-maintain WCF Services. This book is rich with example code, clear explanations, interesting examples, and practical advice. It is a truly hands-on book for C++ and C# developers.
You don't need to have any experience in WCF, LINQ, Entity Framework or LINQ to Entities to read this book. Detailed instructions and precise screenshots will guide you through the whole process of exploring the new worlds of WCF, LINQ, Entity Framework and LINQ to Entities. This book is distinguished from other WCF, LINQ, Entity Framework and LINQ to Entities books by that, this book focuses on how to do it, not why to do it in such a way, so you won't be overwhelmed by tons of information about WCF, LINQ, Entity Framework and LINQ to Entities. Once you have finished this book, you will be proud that you have been working with WCF, LINQ, Entity Framework and LINQ to Entities in the most straightforward way.
You can buy this book from Amazon, or from the publisher's website at http://www.packtpub.com/windows-communication-foundation-4-5-multi-layer-services-development-framework/book.