Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
WCF Multi-layer Services Development with Entity Framework - Fourth Edition
WCF Multi-layer Services Development with Entity Framework - Fourth Edition

WCF Multi-layer Services Development with Entity Framework - Fourth Edition: Create and deploy complete solutions with WCF and Entity Framework

eBook
€8.99 €36.99
Paperback
€45.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

WCF Multi-layer Services Development with Entity Framework - Fourth Edition

Chapter 1. Implementing a Basic HelloWorld WCF Service

Windows Communication Foundation (WCF) is Microsoft's unified programming model to build service-oriented applications. It is built on Microsoft's .NET framework and unifies a broad array of distributed systems capabilities in a composable, extensible architecture that supports multiple transports, messaging patterns, encodings, network topologies, and hosting models.

In this chapter, we will first learn basic WCF concepts and then implement a simple WCF service from scratch. We will build a HelloWorld WCF service by carrying out the following steps:

  • Creating the solution and project
  • Defining the WCF service contract interface
  • Implementing the WCF service
  • Hosting the WCF service in IIS Express
  • Creating a client application to consume the WCF service

The basic WCF concepts

There are many terms and concepts surrounding WCF, such as address, binding, contract, endpoint, behavior, hosting, and channels. Understanding these terms is very helpful when using WCF, so let's first take a look at these terms.

Address

The WCF address is a specific location for a service. It specifies the path where a particular message will be sent. All WCF services are deployed at a specific address, and they listen at that address for incoming requests.

A WCF address is normally specified as a URL, with its first part specifying the transport mechanism and the next part specifying the unique location of the service. For example, http://www.myweb.com/myWCFServices/SampleService.svc is an address for a WCF service. This WCF service uses HTTP as its transport protocol, and it is located on the server, www.myweb.com, with a unique service path of myWCFServices/SampleService.svc.

Binding

Bindings are used to specify the transport, encoding, and protocol details required for clients and services to communicate with each other. Bindings are what WCF uses to generate the underlying representation of the endpoint (an endpoint is a place where clients can communicate with a WCF service; more details will follow). So, most of the details of the binding must be agreed upon by the parties that are communicating. The easiest way to achieve this for clients of a service is to use the same binding that the service uses.

A binding is made up of a collection of binding elements. Each element describes some aspect of how the service communicates with clients. A binding must include at least one transport binding element, at least one message-encoding binding element (which is provided by the transport binding element by default), and any number of other protocol binding elements. The process that builds a runtime out of this description allows each binding element to contribute code to that runtime.

WCF provides bindings that contain common selections of binding elements. These can either be used with their default settings, or the default values can be modified according to user requirements. These system-provided bindings have properties that allow direct control over the binding elements and their settings.

The following are some examples of system-provided bindings: BasicHttpBinding, WSHttpBinding, and NetTcpBinding. Each one of these built-in bindings has the predefined elements required for a common task and is ready to be used in your project. For instance, BasicHttpBinding uses HTTP as the transport to send SOAP 1.1 messages, and it has attributes and elements such as receiveTimeout, sendTimeout, maxMessageSize, and maxBufferSize. You can use the default settings of attributes and elements of BasicHttpBinding, or overwrite them as needed. We will explore all of the three bindings in this book.

Contract

A WCF contract is a set of specifications that defines the interfaces of a WCF service. A WCF service communicates with other applications according to its contracts. There are several types of WCF contract, such as service contract, operation contract, data contract, message contract, and fault contract. We define service contract and operation contract in the following sections of this chapter, and define more contracts throughout this book.

The service contract

A service contract is the interface of the WCF service. Basically, it tells us what the service can do. It can include service-level settings such as the name of the service, the namespace of the service, and the corresponding callback contracts of the service. Inside the interface, it can define a bunch of methods or service operations for specific tasks. A WCF service has to contain at least one service contract to service requests.

The operation contract

An operation contract is defined within a service contract. It defines the parameters and the return type of an operation. An operation can take data of a primitive (native) data type, such as an integer, as a parameter, or it can take a message, which should be defined as a message contract type. Just as a service contract is an interface, an operation contract is the definition of an operation. It has to be implemented in order for the service to function as a WCF service. An operation contract also defines operation-level settings such as the transaction flow of the operation, the direction of the operation (one-way, request/reply, or duplex callbacks), and the fault contract of the operation.

The message contract

If an operation contract needs to pass a message as a parameter or return a message, the type of these messages will be defined as message contracts. A message contract defines the elements of the message as well as any message-related settings, such as the level of message security and also whether an element should go to the header or to the body.

The data contract

Data contracts are the data types of the WCF service. All data types used by the WCF service must be described in the metadata to enable other applications to interoperate with the service. A data contract can be used by an operation contract as a parameter or return type, or it can be used by a message contract to define elements. If a WCF service uses only primitive (native) data types, it is not necessary to define a data contract.

The fault contract

In any WCF service operation contract, if an error is returned to the caller, the caller should be warned of that error. These error types are defined as fault contracts. An operation can have zero or more fault contracts associated with it.

Endpoint

Messages are sent between endpoints. Endpoints are places where messages are sent or received (or both), and they define all the information required for the message exchange. A service exposes one or more application endpoints (as well as zero or more infrastructure endpoints). A service can expose this information in the form of metadata that clients process to generate the appropriate WCF clients and communication stacks. When needed, the client generates an endpoint that is compatible with one of the service's endpoints.

A WCF service endpoint has an address, a binding, and a service contract (sometimes referred to as WCF ABCs).

Behavior

A WCF behavior is a type or setting to extend the functionality of a WCF component. There are many types of behaviors in WCF, such as service behavior, binding behavior, contract behavior, security behavior, and channel behavior. For example, a new service behavior can be defined to specify the transaction timeout of the service, the maximum concurrent instances of the service, and whether the service publishes metadata. Behaviors are configured in the WCF service configuration file. We will configure several specific behaviors in the chapters that follow. We will learn how to extend a WCF service with behaviors in Chapter 13, Extending WCF Services.

Hosting

The WCF service is a component that can be called by other applications. It must be hosted in an environment in order to be discovered and used by others. The WCF host is an application that controls the lifetime of the service. With .NET 3.0 and higher, there are several ways to host the service. We will explore various WCF hosting options in Chapter 2, Hosting the HelloWorld WCF Service.

Channels

As we have seen in previous sections, a WCF service has to be hosted in an application on the server side. On the client side, the client applications have to specify the bindings to connect to the WCF services. The binding elements are interfaces, and they have to be implemented in concrete classes. The concrete implementation of a binding element is called a channel. A binding element represents a configuration and a channel is the implementation associated with that configuration. Therefore, there is a channel associated with each binding element. Channels stack on top of one another to create the concrete implementation of the binding—the channel stack.

The WCF channel stack is a layered communication stack with one or more channels that process messages. At the bottom of the stack is a transport channel that is responsible for adapting the channel stack to the underlying transport (for example TCP, HTTP, SMTP, and other types of transport). Other channels provide a low-level programming model to send and receive messages.

Metadata

The metadata of a service describes the characteristics of the service that an external entity needs to understand in order to communicate with the service. Metadata can be consumed by the ServiceModel metadata utility tool (SvcUtil.exe) to generate a WCF client proxy and the accompanying configuration that a client application can use to interact with the service.

The metadata exposed by the service includes the XML schema documents that define the data contract of the service and WSDL documents that describe the methods of the service.

Though WCF services always have metadata, it is possible to hide the metadata from outsiders. If you do so, you have to pass the metadata to the client side by other means. This practice is not common but it gives your services an extra layer of security. When enabled through the configuration settings from metadata behavior, metadata for the service can be retrieved by inspecting the service and its endpoints. The following configuration setting in a WCF service configuration file will enable metadata publishing for the HTTP transport protocol:

<serviceMetadata httpGetEnabled="true" />

WCF environments

WCF was first introduced in Microsoft's .NET Common Language Runtime (CLR) Version 2.0. The corresponding framework at that time was .NET 3.0. To develop and run WCF services, Microsoft .NET Framework 3.0 or above is required.

Visual Studio is Microsoft's IDE to develop WCF service applications. Visual Studio 2008 and above support WCF service application development.

The following table shows all of the different versions of the .NET runtimes, .NET frameworks, and Visual Studio versions, along with their relationships:

CLR

.NET framework

Components

Visual Studio

 

.NET 4.5.1

.NET 4.5.2

Windows 8.1

Universal App

Type Script

2013

CLR 4.0

.NET 4.5

Windows 8

HTML5

Portable Class Libraries

2012 or above

.NET 4.0

Parallel Computing

Dynamic

Covariance and Contravariance

2010 or above

CLR 2.0

.NET 3.5 SP1

ASP.NET MVC

Entity Framework

LINQ to Entities

Cloud Computing

2008 or above

.NET 3.5

LINQ

ASP .NET AJAX

REST

RSS

2008 or above

LINQ to SQL

LINQ to XML

LINQ to Objects

.NET 3.0

WCF

WPF

WF

CardSpace

.NET 2.0

Winforms

ASP.NET

ADO.NET

2005 or above

CLR 1.0

.NET 1.1

Winforms

ASP.NET

ADO.NET

2003

.NET 1.0

2002

Creating the HelloWorld solution and project

Now that we have a basic understanding of WCF concepts and terminologies, let's start building a simple HelloWorld WCF service. 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 book, we will save our project source codes in the C:\SOAwithWCFandEF\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.

Note

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 2013 (you can use Visual Studio Ultimate, Premium, or Professional throughout this book). 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, as follows:
    Creating the HelloWorld solution and project
  3. From the left-hand side of the window, expand Installed | Templates | 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 in HelloWorld in the Name field and enter C:\SOAwithWCFandEF\Projects\ in the Location field. Note that you should not enter HelloWorld within the location, because Visual Studio will automatically create a new folder for us inside the Projects folder.
  5. Click on the OK button to close this window, and your screen should look like the following screenshot with an empty solution:
    Creating the HelloWorld solution and project
  6. Depending on your settings, the layout might be different. However, you should still have an empty solution in your Solution Explorer. If you don't see the Solution Explorer, navigate to VIEW | Solution Explorer or press Ctrl + Alt + L to bring it up.
  7. In the Solution Explorer, right-click on the solution and select Add | New Project… from the context menu. You can also go to FILE | Add | New Project… to get the same result. The following screenshot shows the context menu to add a new project:
    Creating the HelloWorld solution and project
  8. The New Project window should now appear on your screen. On 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 in HelloWorldService in the Name field. Leave C:\SOAwithWCFandEF\Projects\HelloWorld in the Location field. Again, don't add HelloWorldService to the location, as Visual Studio will create a subfolder for this new project (Visual Studio will use the HelloWorld folder as the default base folder for all the new projects added to the solution). Refer to the following screenshot:
    Creating the HelloWorld solution and project

    You might have noticed that there is already a template for a WCF Service Application in Visual Studio 2013. For this very first example, we will not use this template. Instead, we will create everything by ourselves to understand the purpose of each template. This is an excellent way for you to understand and master this new technology. In the next chapter, 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 our project's 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.

    The window on your screen should now look like the one shown in the following screenshot:

    Creating the HelloWorld solution and project

We have now created a new solution and a new project. Next, we will develop and build this project as a new service. However, before we go any further, we need to do one more thing to this project. Click on the Show All Files button on the Solution Explorer toolbar as shown in the preceding screenshot. Clicking on this button will show all files and directories in your hard disk under your project's folder—even those items that are not included in the project. Make sure that you don't have the solution item selected, otherwise you cannot 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. Perform the following steps:

  1. In the Solution Explorer window, right-click on the HelloWorldService project and select Add | Reference… from the context menu. You can also right-click on References and select Add Reference… or go to PROJECT | Add Reference… to do this. The Reference Manager dialog window will appear on your screen as follows:
    Creating the HelloWorld solution and project
  2. Check the checkbox in front of System.ServiceModel from the Framework tab under Assemblies and click on OK.

Now in Solution Explorer, if you expand the references of the HelloWorldService project, you will see that System.ServiceModel has been added under References. Also, note that System.Xml.Linq is added by default. We will use this later when we query a database.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Defining the HelloWorldService service contract interface

In the previous section, we created the solution and the project for the HelloWorld WCF service. From this section onwards, we will start building the HelloWorld WCF service. First, we need to define the service contract interface. For this, perform the following steps:

  1. In the Solution Explorer, right-click on the HelloWorldService project and select Add | New Item… from the context menu. The Add New Item dialog window shown in the following screenshot will appear on your screen:
    Defining the HelloWorldService service contract interface
  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 the service interface. Follow these steps to customize it:

  1. Add a using statement:
    using System.ServiceModel;
  2. Add a ServiceContract attribute to the interface. This will designate the interface as a WCF service contract interface:
    [ServiceContract]
  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 called OperationContract:
    [OperationContract]
    string GetMessage(string name);
  4. Change the interface to public.

The final content of the file, IHelloWorldService.cs, should look as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;

namespace HelloWorldService
{
    [ServiceContract]
    public interface IHelloWorldService
    {
        [OperationContract]
        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 re-use the empty class file that Visual Studio created for us earlier and modify it 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 Class1.cs file, select Rename from the context menu, and rename it as HelloWorldService.cs. Visual Studio is smart enough to change all the related files that are references to use this new name. You can also select the file and change its name from the Properties window.

Next, perform the following steps to customize the class file:

  1. Open the HelloWorldService.cs file.
  2. Make it implement IHelloWorldService implicitly as follows:
    public class HelloWorldService: IHelloWorldService
  3. 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 HelloWorldService.cs file should look like the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HelloWorldService
{
    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 where client applications can 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 2013. 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 the Solution Explorer, right-click on the solution HelloWorld and select Add | New Web Site… from the context menu (Always show solution must be enabled in DEBUG | Options and Settings... | 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 field set to File System, but change the default address to C:\SOAwithWCFandEF\Projects\HelloWorld\HostExpressServer and click on OK.
    Creating the host application
  3. Now in Solution Explorer, you have one more item (HostExpressServer) within the solution. It will look like the following:
    Creating the host application
  4. Next, we need to set the website as the startup project. In the Solution Explorer, right-click on the HostExpressServer website and select Set as StartUp Project from the context menu (or you can first select the website from Solution Explorer and then select the menu item WEBSITE | Set as StartUp Project). The HostExpressServer website should be highlighted in Solution Explorer, indicating that it is now the startup project.
  5. As we will host HelloWorldService from this website, we need to add a HelloWorldService reference to the website. In the Solution Explorer, right-click on the HostExpressServer website and select Add | Reference… from the context menu. The Reference Manager dialog box should appear, as shown in the following screenshot:
    Creating the host application
  6. In the Reference Manager dialog box, click on the Solutions tab and then click on Projects. Check the HelloWorldService project and then click on OK. You will see that a new directory (bin) has been created under the HostExpressServer 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 the bin directory.

Testing the host application

Now we can run the website inside IIS Express. If you start the HostExpressServer website 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:

Testing the host application

If you press F5 (or select DEBUG | Start Debugging from the menu), you might see a dialog saying Debugging Not Enabled. Choose the Run without debugging (equivalent to Ctrl + F5) option and click on the OK button to continue. We will explore the debugging options of a WCF service later. Until then, we will continue to use Ctrl + F5 to start the website without debugging.

IIS Express

At this point, you should have the HostExpressServer site up and running. This site actually runs 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 window of your website, as shown in the following screenshot:

IIS Express

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 of Visual Studio, you can use a command-line statement in the following format:

"C:\Program Files\IIS Express\iisexpress" /path:c:\myapp\ /port:[your_port] /clr:v4.0

For our website, the statement should be as follows:

"C:\Program Files\IIS Express\iisexpress" /path:C:\SOAwithWCFandEF\Projects\HelloWorld\HostExpressServer /port:55859 /clr:v4.0

Note

iisexpress.exe is located under your Program Files\ IIS Express\ directory. In an x64 system, it should be under your Program Files (x86)\ IIS Express\ directory.

Modifying the Web.config file

Although we can start the website now, it is only an empty site. Currently, it does not host our HelloWorldService website. This is because we haven't specified which service this website should host or an entry point for this website.

To specify which service our website will host, we can add a .svc file to the website. From .NET 4.0 onwards, we can also use the file-less (svc-less) activation service to accomplish this. In this section, we will take the file-less approach to specify the service.

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 the following:

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5"/>
  </system.web>

  <system.serviceModel>
    <serviceHostingEnvironment >
      <serviceActivations>
        <add factory="System.ServiceModel.Activation.ServiceHostFactory" 
         relativeAddress="./HostExpressServer/HelloWorldService.svc" 
         service="HelloWorldService.HelloWorldService"/>
      </serviceActivations>
    </serviceHostingEnvironment>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

</configuration>

Note that the system.serviceModel node is the only code that we have manually added to the Web.config file.

The httpGetEnabled behavior is essential because we want other applications to be able to locate the metadata of this service via HTTP. Without the metadata, the 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:

  • The configuration node is the root node of the file.
  • The system.serviceModel node is the top node for all the WCF service-specific settings.
  • The serviceHostingEnvironment node is used to specify the hosting environment.
  • The serviceActivations node is where you specify the service name and its relative address. This configuration element allows you to define the 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 the menu option DEBUG | Start Debugging until we discuss these later), you will still see the same empty website with the same error. However, this time we have a service hosted within this website, so just append HostExpressServer/HelloWorldService.svc after the address (it should look something like http://localhost:55859/HostExpressServer/HelloWorldService.svc). Then, 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 one shown in the following screenshot:

Starting the host application

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 file 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.

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 the 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 in the following screenshot:
    Creating the client application project
  2. Select Visual C# | Console Application as the template, change the project name from the default value of ConsoleApplication1 to HelloWorldClient, and leave the Location field as C:\SOAwithWCFandEF\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 SOAP 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, address of the service, and contract.

To generate these two files, we can use the SvcUtil.exe tool from the command line. You can follow these steps to generate the two files:

  1. Start the service by pressing Ctrl + F5 or by selecting the menu option DEBUG | Start Without Debugging (at this point, your startup project should still be HostExpressServer; 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 (that is, C:\SOAwithWCFandEF\Projects\HelloWorld\HelloWorldClient), and then run the command-line SvcUtil.exe tool with the following syntax (SvcUtil.exe might be in a different directory in your machine and you need to substitute 55859 with your service hosting port):
    "C:\Program Files\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\SvcUtil.exe" http://localhost:55859/HostExpressServer/HelloWorldService.svc?wsdl /out:HelloWorldServiceRef.cs /config:app.config
    

You will see an output similar to that shown in the following screenshot:

Generating the proxy and configuration files

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.

Note

You can also generate a proxy class within Visual Studio, which we will do later in this book, but behind the scenes the same SvcUtil.exe tool is used by Visual Studio to generate the proxy class.

In addition to generating a static proxy class at design time, 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 might have to share your interface DLL with the clients.

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. When you switch to Visual Studio 2013, you will be asked to reload the App.config file, as it has been changed. Click on Yes to reload it.
  2. Add the proxy file to the project. In the Solution Explorer, first select the HelloWorldClient project and click on 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 the 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. From the Solution Explorer, just right-click on the HelloWorldClient project, select Add | Reference…, and check System.ServiceModel under Assemblies | Framework. 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:
    var client = new HelloWorldServiceClient();

Note

Using the default constructor on HelloWorldServiceClient means that the client runtime will look for the default client endpoint in the App.config file, which is present due to the use of SvcUtil.

Then, we can call the GetMessage method of our newly created object just as we would do for any other object:

Console.WriteLine(client.GetMessage("Mike Liu"));

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 the client program.

First, make sure that the service host application, HostExpressServer, has been started. If you have stopped it previously, start it now (you need to set HostExpressServer as the startup project and press Ctrl + F5 to start it in the non-debugging mode, or you can just right-click on the HostExpressServer project and select View in Browser (Internet Explorer) from the context menu).

Then, from the Solution Explorer, right-click on the HelloWorldClient project, select Set as StartUp Project, and then press Ctrl + F5 to run it.

You will see an output as shown in the following screenshot:

Running the client application

Setting the service application to autostart

As 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 the Solution Explorer, right-click on solution, select Properties from the context menu, and you will see the Solution 'HelloWorld' Property Pages dialog box:

Setting the service application to autostart

On this page, first select the Multiple startup projects option. Then, change the action of HostExpressServer to Start without debugging. Change HelloWorldClient to the same action.

Note

HostExpressServer must be above HelloWorldClient. If it is not, use the arrows to move it to the top.

To test it, first stop the service and then press Ctrl + F5. You will notice that HostExpressServer 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:\SOAwithWCFandEF\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 that says There was no endpoint listening at http://localhost:55859/HostExpressServer/HelloWorldService.svc.

Summary

In this chapter, we 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 of what a WCF service is under the hood. You will benefit from this knowledge when you develop WCF services using Visual Studio WCF templates.

In the next chapter, we will explore more hosting options so that you can choose an appropriate hosting method for your WCF services.

Left arrow icon Right arrow icon

Description

If you are a C#, VB.NET, or C++ developer and want to get started with WCF and Entity Framework, then this book is for you. Competence in Entity Framework will be needed to follow the examples in the book, but experience in creating WCF services using Entity Framework is not necessary. Developers and architects evaluating SOA implementation technologies for their company will find this book useful.

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 31, 2014
Length: 378 pages
Edition : 1st
Language : English
ISBN-13 : 9781784396954
Category :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Oct 31, 2014
Length: 378 pages
Edition : 1st
Language : English
ISBN-13 : 9781784396954
Category :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 87.98
Microsoft Windows Communication Foundation 4.0 Cookbook for Developing SOA Applications
€41.99
WCF Multi-layer Services Development with Entity Framework - Fourth Edition
€45.99
Total 87.98 Stars icon
Banner background image

Table of Contents

14 Chapters
1. Implementing a Basic HelloWorld WCF Service Chevron down icon Chevron up icon
2. Hosting the HelloWorld WCF Service Chevron down icon Chevron up icon
3. Deploying the HelloWorld WCF Service Chevron down icon Chevron up icon
4. Debugging the HelloWorld WCF Service Chevron down icon Chevron up icon
5. Implementing a Three-layer WCF Service Chevron down icon Chevron up icon
6. Adding Database Support and Exception Handling Chevron down icon Chevron up icon
7. LINQ to Entities – Basic Concepts and Features Chevron down icon Chevron up icon
8. LINQ to Entities – Advanced Concepts and Features Chevron down icon Chevron up icon
9. Applying LINQ to Entities to a WCF Service Chevron down icon Chevron up icon
10. Distributed Transaction Support of WCF Chevron down icon Chevron up icon
11. Building a RESTful WCF Service Chevron down icon Chevron up icon
12. WCF Security Chevron down icon Chevron up icon
13. Extending WCF Services Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.2
(13 Ratings)
5 star 61.5%
4 star 7.7%
3 star 23.1%
2 star 0%
1 star 7.7%
Filter icon Filter
Top Reviews

Filter reviews by




frehman Mar 01, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great reference book for any .NET developer working on back end technologies i.e Entity framework and delivering data using web services by the way of WCF. Goes into the details of the layered architecture. Examples are good and to the point. Book is laid out well and contains 13 chapters and explains the concepts very well. Best part is that it is easy to get to the specific information you are looking for while working on your own projects.I urge the author/publisher to come out with another edition of this book that explains the use of EF with the newer "Web API technology".
Amazon Verified review Amazon
Sylwia Dec 24, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Excellent book. This book took me from having little understanding of WCF Web Services to having a great understanding. All the examples were straight-forward, easy to follow, and informative. You'll definitely be glad you bought this book if you're serious about learning WCF Web Services.
Amazon Verified review Amazon
DBO Jan 30, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is an exceptionally good book that teaches real world WCF programming in an easy to read style. The author is really great at explaining, step-by-step, the most important steps to take in this endeavor. I was new to WCF, though not new to programming, and I didn't feel overwhelmed.Just what I needed.
Amazon Verified review Amazon
Gabriel de Oliveira Ferreira Jan 15, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book has a lot of useful information explained in a very concise way.If you wanna learn WCF in a quick and straight-to-the-point way, this is the book.
Amazon Verified review Amazon
Jacqueline Williams Mar 29, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Really good quick guide to WCF services development. Highly recommended.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.