Category Archives: Service

Developing a WCF Service – Fault Exceptions AND FAULT Contracts

This next post about WCF will show how to integrate Fault Exceptions and Fault Contracts in your service.

As written in MSDN Fault Exceptions are used for "… mapping managed exception objects to SOAP fault objects and SOAP fault objects to managed exception objects …". This means that if you are looking for interoperability in your service development then you definitely should use this, because no Java client will understand a .NET exception.

You can read some more about it in this link Specifying and Handling Faults in Contracts and Services.

So, when using Fault Exceptions (or SOAP Faults) you have two alternatives:

  • Normal typed (or "un-typed") – You throw a regular FaultException which only contains general information about the SOAP Fault
  • Strongly-typed – You define your own SOAP Fault object, which can contain any kind of information you want about the SOAP Fault

Strongly-typed SOAP Faults are then used when you wish to give to the client some more information and context about the cause of the exception. They also couldn’t be much easier to define in WCF, because they are no more, no less than another Contract in the service definition, which are semantically called Fault Contracts.

As such, you define a Fault Contract in your service definition in the following way:

/// <summary>

/// Strongly-typed fault.

/// </summary>

[DataContract]

public class ArgumentFault

{

    #region Get / Set

 

    /// <summary>

    /// 

    /// </summary>

    [DataMember]

    public String Operation { get; set; }

 

    /// <summary>

    /// 

    /// </summary>

    [DataMember]

    public String Argument { get; set; }

 

    /// <summary>

    /// 

    /// </summary>

    [DataMember]

    public String Message { get; set; }

 

    #endregion

}

You then define that an operation can throw this type of fault contract by appending the following to your operation:

[FaultContract(typeof(ArgumentFault))]

[OperationContract]

Customer GetCustomer(Int32 customerId);

Now in the service implementation when you want to throw the defined fault contract you do like this:

public Customer GetCustomer(int customerId)

{

    if (customerId <= 0)

    { // Not possible

        throw new FaultException<ArgumentFault>(new ArgumentFault()

        {

            Operation = MethodBase.GetCurrentMethod().Name,

            Argument = "customerId",

            Message = "Argument must be greater than zero."

        });

    }

 

    return Customers.First(customer => 

    {

        return customer.Id == customerId;

    });

}

This is better than just doing:

throw new FaultException(MethodBase.GetCurrentMethod().Name + 

               ": customerId - Argument must be greater than zero.");

 

In the client application for catching this Fault Exception, you code should be:

try

{    // Get customer

    Customer singleCustomer = proxy.GetCustomer(customers[0].Id);

    Console.WriteLine("SingleCustomer: Id - {0} / Name - {1}.",

                singleCustomer.Id, singleCustomer.Name);

 

    // Force fault

    singleCustomer = proxy.GetCustomer(0);

}

catch (FaultException<ArgumentFault> ex)

{

    Console.WriteLine("FaultException<ArgumentFault>: {0} - {1} - {2}",

            ex.Detail.Operation, ex.Detail.Argument, ex.Detail.Message);

}

catch (FaultException ex)

{

    Console.WriteLine("FaultException: {0}", ex.Message);

}

 

Again the full code is available here:

 

Related List of articles

Developing a WCF Service

Developing a WCF Service – Calling the hosted service

Developing a WCF Service – Calling the hosted service

In the first part of this topic, I showed you how to develop a WCF service. In this next part I will show how to implement a client application that calls the exposed service methods, and how to make some enhancements to your service hosting.

Ok, so he already have built and deployed our service (either self-hosted, or in IIS for example), and by using a web browser we can see the service welcome page. Now, to call the service methods we must create a client proxy, and to do this we can use the Visual Studio Add Web Reference, which automatically creates the proxy, or we can use the command line svcutil to manually create the proxy. I prefer to do it manually because I like to control things like the generated proxy class namespace.

For example purposes, I created a Console Application that I called Tests.SampleService. There I created a batch file for calling the svcutil with my own parameters, with something similar to this:

svcutil %SERVICE_URL% /namespace:*,%NAMESPACE% /d:%OUT_DIR% /out:%OUT_FILE%

With the service running, I executed the batch file and svcutil generated two files:

  • output.config – Contains the WCF runtime configurations for calling the service (<system.serviceModel>)
  • Sample.Service.Proxy.cs – Contains the service proxy class, and any other classes exposed by the service

The contents of the output.config should be placed in the console application App.Config (if you prefer you can just rename the file).

In your console application main file you can place code like the following:

static void Main(string[] args)

{

   Console.WriteLine("Press any key to start");

   Console.ReadLine();

 

   // Build the service proxy object

   ServiceClient proxy = new ServiceClient();

 

   // Call service methods

 

   // Get total number of customers

   Int32 totalCustomers = proxy.GetTotalNumberOfCustomers();

   Console.WriteLine("Total Customers: {0}", totalCustomers);

 

   // Get list of customers

   List<Customer> customers = new List<Customer>(proxy.GetCustomers());

   foreach (Customer customer in customers)

   {

       Console.WriteLine("Customers");

       Console.WriteLine("Customer: Id - {0} / Name - {1}.", customer.Id, customer.Name);

   }

            

   // Get customer

   Customer singleCustomer = proxy.GetCustomer(customers[0].Id);

   Console.WriteLine("SingleCustomer: Id - {0} / Name - {1}.", singleCustomer.Id, singleCustomer.Name);

 

   Console.WriteLine("Press any key to exit");

   Console.ReadLine();

}

You are know ready to start your service and use your client application to call the service methods.

 

Service Host Enhancements

Regarding the self service hosting there are some steps that you can do to make it more robust to errors and faults. Two of these changes are:

  • Subscribe the service host Faulted event
  • Subscribe the service host Unknown Message Received event

This should be done before opening our service hosting, and the new StartServiceHost method should look like this:

/// <summary>

/// Creates the service host

/// </summary>

private void StartServiceHost()

{

    Logger.Info("StartServiceHost: Starting service hosting...");

 

    // Create service host

    _serviceHost = new ServiceHost(typeof(SampleService.Service));

 

    // Subscribe to the Faulted event of the service host

    _serviceHost.Faulted += new EventHandler(FaultHandler);

 

    // Subscribe to the Unknown message received event of the service host

    _serviceHost.UnknownMessageReceived += new EventHandler<UnknownMessageReceivedEventArgs>(UnknownMessageHandler);

    

    try

    { // Open service host

        _serviceHost.Open();

 

        Logger.Info("StartServiceHost: Service hosting success.");

    }

    catch (Exception ex)

    {

        Logger.Fatal("StartServiceHost: Could not start service hosting.", ex);

    }            

}

 

The event handler’s code can be:

/// <summary>

/// Fault error event handler

/// </summary>

private void FaultHandler(Object sender, EventArgs e)

{

    // Examine the properties of the service host

 

    // Log reason for fault

    Logger.Error("FaultHandler: Host Fault occured. Aborting and restarting the hosting");

 

    // Abort the service (Could use Close, but a service in this state does not responde to requests, and Close takes more time)

    _serviceHost.Abort();

 

    // Re-start service host

    StartServiceHost();

}

 

/// <summary>

/// Unknown message event handler

/// </summary>

private void UnknownMessageHandler(Object sender, UnknownMessageReceivedEventArgs e)

{

    // Log the unknown message

    Logger.Warn("UnknownMessageHandler: Unknown Message Received");

}

 

Take into attention that when the service host goes into a Faulted state, it stops servicing requests. This is why in the FaultHandler we abort the service host and open it again.

You can make a quick test of the event handlers by introducing in your web browser the following address: http://localhost:8080/SampleService/Service.svc.

This makes the service receive an unknown message and the corresponding event handler is called.

I leave here the complete Visual Studio solution.

 

Related list of articles:

Developing a WCF Service

Developing a WCF Service

It is typical to have projects based on a client-server architecture where the server publishes a number of services. These services are normally Web-Services, and as so are available through the SOAP protocol.

The "traditional" way of implementing these services is by using ASMX, but nowadays you have another great alternative – Windows Communication Foundation (WCF) in .NET 3.5.

This, being my first WCF post, intends to demonstrate that developing a simple WCF service is as easy as doing it in ASMX, while allowing us to make future evolutions on our service architecture to support everything that WCF makes available.

 

Well, as always you start out by creating a new Visual Studio project. I chose to use the existent project template ‘WCF Service Library’ (but some of you may want to start by an empty project 😀 ).

This creates a project with the following list of files (I changed the service name to ‘Service’, and I only list the WCF most important files:

  • IService.cs – Describes the exposed service interface. This is where we will namely define the [ServiceContract] (The service itself) and the [OperationContract]‘s (The operations exposed by the service). More information in Designing and Implementing Services.
  • Service.cs – The service interface implementation class. This is where the actual code of the service operations will be contained. More information in Implementing Service Contracts.

There is another important file, App.Config, that contains the service configuration (e.g. service listening url), but I will refer to this file later when talking about the service hosting (creates the service and controls its context and lifetime). More information in Hosting Services.

So a simple service contract could be:

[ServiceContract]
public interface IService
{
    [OperationContract]
    Int32 GetTotalNumberOfCustomers();
 
    [OperationContract]
    Customer GetCustomer(Int32 customerId);
 
    [OperationContract]
    List<Customer> GetCustomers();        
}

This code defines a service contract (IService) that exposes three operations (operation functionality is self explanatory):

  • GetTotalNumberOfCustomers
  • GetCustomer
  • GetCustomers

You will notice that in the code we are referring a custom class that is not contained anywhere in the service contract, that is the Customer class. This class must be described in WCF like a [DataContract] because it is a new, complex data type that WCF does not know how to serialize. More information in Using Data Contracts.

Our data contract is defined like this:

[DataContract]

public class Customer

{

    [DataMember]

    public Int32 Id { get; set; }

 

    [DataMember]

    public String Name { get; set; }

 

    public Customer()

    {

        Id = 0;

        Name = String.Empty;

    }

}

One important aspect of data contracts are the [DataMember] properties, that are properties to be exposed by the data contract.

 

At this point we are ready to implement our service contract, that for this example is very simple, and obviously not production code:

public class Service : IService

{

    private List<Customer> Customers = new List<Customer>()

    {

        new Customer() {Id = 1, Name = "Customer1" },

        new Customer() {Id = 2, Name = "Customer2" },

        new Customer() {Id = 3, Name = "Customer3" }

    };

 

    public int GetTotalNumberOfCustomers()

    {

        return Customers.Count;

    }

 

    public Customer GetCustomer(int customerId)

    {

        return Customers.First(customer => 

        {

            return customer.Id == customerId;

        });

    }

 

    public List<Customer> GetCustomers()

    {

        return Customers;

    }

}

 

Our service is now ready to be hosted and this is one of the beauties of WCF in the sense that the hosting environment can be a:

  • Windows/WPF Application
  • Console application
  • Windows Service
  • IIS/WAS

Each of them has advantages and disadvantages an again I refer you to Hosting Services (look at the Choosing a Hosting Environment table). Take into attention that the Service Library that you develop is always the same regardless of the hosting environment that you choose, and even if you choose one hosting environment now, you can choose another later and easily change between them.

For developing/debugging purposes I normally choose for hosting a simple WPF application with just two buttons (Start and Stop), where I place the following code (the Logger object is of log4net ILog type):

private void StartServiceHost()

{

    Logger.Info("StartServiceHost: Starting service hosting...");

 

    // Create service host

    _serviceHost = new ServiceHost(typeof(SampleService.Service));

    

    try

    { // Open service host

        _serviceHost.Open();

 

        Logger.Info("StartServiceHost: Service hosting success.");

    }

    catch (Exception ex)

    {

        Logger.Fatal("StartServiceHost: Could not start service hosting.", ex);

    }            

}

 
private void StopServiceHost()

{

    // Close service host

    _serviceHost.Close();

}

Now, you just have to properly configure the application configuration file (remember we talked about it earlier), and you are ready to test your service. Note that I configured the service hosting all thru the App.Config file and as simple and compatible as possible with a ASMX (e.g. Basic HTTP binding).

Note: I will differ binding’s and other configuration explanations to another time. Right now I just want you to see how you can get started with WCF.

<configuration>

    <system.serviceModel>

        <services>

        <service behaviorConfiguration="SampleService.Service.Behavior" name="SampleService.Service">

            <host>

                <baseAddresses>

                    <add baseAddress="http://localhost:8080/SampleService"/>

                </baseAddresses>

            </host>

            <endpoint    address="/Service.svc"

                        binding="basicHttpBinding"

                        name="IService_BasicHttpEndpoint"

                        contract="SampleService.IService"

                        bindingConfiguration="IService_BasicHttpBindingConfiguration">

            </endpoint>

        </service>

    </services>

 

    <behaviors>

        <serviceBehaviors>

            <behavior name="SampleService.Service.Behavior">

                <!-- To avoid disclosing metadata information, 

      set the value below to false and remove the metadata endpoint above before deployment -->

                <serviceMetadata httpGetEnabled="True"/>

                <!-- To receive exception details in faults for debugging purposes, 

      set the value below to true.  Set to false before deployment 

      to avoid disclosing exception information -->

                <serviceDebug includeExceptionDetailInFaults="True" />                

            </behavior>

        </serviceBehaviors>

    </behaviors>

 

    <bindings>

        <basicHttpBinding>

            <!-- Service host binding configuration -->

            <binding name="IService_BasicHttpBindingConfiguration"

                             maxBufferSize="65536" maxBufferPoolSize="52428"

                             maxReceivedMessageSize="65536" transferMode="Buffered">            

                <readerQuotas maxDepth="32" maxArrayLength="16384"

                                            maxBytesPerRead="4096" maxNameTableCharCount="16384"

                                            maxStringContentLength="8192"/>

            </binding>

        </basicHttpBinding>

    </bindings>

    

</system.serviceModel>

 

<configuration>

If you now run the WPF application and point your browser to http://localhost:8080/SampleService you should see a welcome page telling you that you have created a service.

You are now ready to start writing a client application that will call your service operation contracts (my next post will be about this part, but you have everything you need in the service welcome page).

To end, I just want to show you how easy it is to change the hosting environment to IIS for example. For hosting in IIS you just have to follow these steps:

  • Create a new web application in IIS
  • Place the presented App.Config <system.serviceModel> tag in a Web.Config file
  • Deploy the service library assembly to the web application bin directory
  • Create a special file, in my example called Service.svc, with the following content:
<%@ServiceHost language="C#" Debug="true"

                             Service="SampleService.Service"%>

<%@Assembly Name="SampleService" %>

The only different part in hosting in IIS is just the need to create the .svc file that tells IIS which service should be instantiated.

Again, if you point your browser to http://localhost:8080/SampleService/Service.svc you should see the same page as before.

I hope that this can get you started in WCF more easily and I will try to show what other capabilities WCF provides in some next posts.

Debugging Windows Services

Recently I had to develop my first Windows
Service in C#. I had already done Services in C++, and I was used to launch and
debug the Services thru Visual Studio (just by normally hitting F5). 

I was surprised to see that the normal C# Windows
Service code base does not allow this to be possible in a "out-of-the-box"
experience, and one had to do things like "Attach to Process", and/or put in
the source code "System.Diagnostics.Debugger.Launch();".

Not satisfied with these solutions, I searched
the web and I found this page that as a "perfect solution".

http://theimes.com/archive/2006/12/28/Debugging-Windows-Services-is-a-Pain.aspx

The author developed a Service Debugger Helper
class, that incorporates a GUI for allowing all the expected Start, Stop, etc,
interaction with the service. It is also possible to automatically start a
service by default, thus allowing the normal F5 experience.

Check out the author article and his source
code if you are interested in knowing how he made this. Also this other link
could be of interest to someone.

Run a Service without a debugger attached (.NET
Windows Service Runner)

http://theimes.com/archive/2007/08/22/net-windows-service-runner.aspx

PS: Regarding the usage of Timers in Windows
Services, be careful to use the ones in System.Timers.Timer, or else the timer may never (or
stop) be (being) fired.