Archive

Archive for the ‘WCF’ Category

Testing and Monitoring WCF Service using soapUI and Fiddler

September 3, 2011 Leave a comment

This article is not about understanding the details of .Net WCF service, soapUI and Fiddler as all these three are quite popular things among .Net developers. And tools like soapUI and Fiddler may already be in the arsenal of many web developers and QA engineers. Those who are new to these two tools should refer to following articles.

However, we will take a look into how Fiddler can be used to Monitor SOAP Request and SOAP Response transmitting behind the soapUI.

Let’s start with a simple WCF service in place. No need to have a WCF .Net Client as of now to test and monitor HTTP traffic of WCF service calls.

1. Open soapUI and set the following settings. Make sure the service’s wsdl path is correct.

Loading wsdl definition

2. After loading the definition of WSDL, service definitions will appear like shown below.

Service requests definitions

3. Double click on Request # node and navigate to the request window on the right.

Submitting the request

4. Fill the method parameters denoted by “?”.

5. Open Fiddler and make sure it is ready to capture HTTP(S) traffic.

6. Submit request to the specified endpoint and SOAP Response can be seen on the right pane.

Service Request-Response in soapUI

7. If you see the Fiddler window, there is no traffic captured. This is really frustrating if you have been testing your services using soapUI when you do not see the underlying details of the SOAP Request and SOAP Response in the wire.

8. All you need to do following proxy settings in the soapUI File –> Preferences –> Proxy Settings window.

soapUI Proxy Settings

9. Re-submit web service request on soapUI.

10. Now you see WCF Request-Response traffic in the Fiddler window Smile. You are now all in your territory to view the details of service request-response headers, body, and many more!

SOAP Request-Response view in Fiddler

But why did we add Port No. 8888 in the proxy settings of soapUI? It is because Fiddler by default listens on port no. 8888.

Fiddler default listening port no.

If you have configured your Fiddler proxy tool to listen on some other port no., then you should use that one.

I hope you enjoyed this testing tip. No need to reiterate how blissful it is to test web services using soapUI and Fiddler if you are a web service developer/provider to remote clients.

Exception Handling in WCF

We have been doing exception handling in managed application using try-catch block with Exception or its derived Custom Exception objects. But this mechanism is very much .Net Technology specific. When we develop SOA applications, our application is not limited to mere one technology or single loyal client. So the communication process of this service or service method level errors to client via wire becomes a little bit tricky. WCF has two types of error handling mechanism: one is by as usual Exception objects, and other is by SOAP fault message. SOAP fault is used to marshall .Net exceptions to client in much readable and convenient way to support interoperability. With use of SOAP fault, the verbose exception message is reduced to Code and Message. For this System.ServiceModel namespace comes FaultException class and FaultContract attribute.

Let’s come to see from example on how to do exception handling in WCF application. Before this, write our service first.

namespace WcfSvc
{
[ServiceContract]
public interface IBasicMathService
{
[OperationContract]
int Subtraction(int x, int y);

[OperationContract]
int Multiplication(int x, int y);

[OperationContract]
[FaultContract(typeof(BasicMathFault))]
int Addition(int x, int y);
}

[DataContract]
public class BasicMathFault
{
//
[DataMember]
public string Source;

[DataMember]
public string ExceptionMessage;

[DataMember]
public string InnerException;

[DataMember]
public string StackTrace;
}
}

And its implementation is as:

public class BasicMath : IBasicMathService
{
public int Addition(int x, int y)
{
//
int result = 0;
try
{
result = (x + y);
}
catch
{
BasicMathFault ex = new BasicMathFault();
ex.Source = "BasicMath.Addition method";
ex.ExceptionMessage = "Could not perform addition operation.";
ex.InnerException = "Inner exception from math service";
ex.StackTrace = "";
//Throwing strongly-typed FaultException
throw new FaultException(ex, new FaultReason("This is an error condition in BasicMath.Addition method")); }

return result;
}

public int Multiplication(int x, int y)
{
//Due to some calculation error condition, let’s assume we are throwing this error.
//Throwing simply FaultException
throw new FaultException(new FaultReason("Error occurred while processing
for the result"), new FaultCode("mutliplication.method.error"));
}

public int Subtraction(int x, int y)
{
//Exception we generally throw in managed application in the form of Exception object
throw new NotImplementedException("Method still not implemented");
}
}

This is our typical service related code. If we see IBasicMathService interface and its implementation in BasicMath class, we have:

Addition(x,y) method decorated with FaultContract attribute in IBasicMathService class,

Subtraction(x,y) method using simple Exception throwing mechanism,

Multiplication(x,y) method using simple FaultException object, and

Addition(x,y) method using strongly-typed fault of type BasicMathFault in FaultException object

So what does all this mean to client, and how exception is transmitted to client? Let’s answer with these three examples in our client code.

A) Throwing Simple Exception

private void SubtractIntegers()
{
try
{
obj = new BasicmathServiceRef.BasicMathServiceClient();
int result = obj.Subtraction(10, 15);
}
catch (Exception ex)
{
Response.Write(ex.Message + "
");
}
}

When this method is called, client receives verbose error message from WCF as:

“The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.”

If we closely see this error information, we come across two things: turn on\off IncludeExceptionDetailInFaults value either through ServiceBehaviorAttribute of the class containing this method, or modify IncludeExceptionDetailInFaults value in configuration file or section of this service.

Either of these two things is pretty easy.

a) Decorate BasicMath class as:

[ServiceBehavior(IncludeExceptionDetailInFaults = false)]
public class BasicMath : IBasicMathService
{

b) Or, modify in config file

By default this key value is false. If we make it true, the verbose error message that we received will be reduced to human readable message that we passed in constructor of NotImplementedException.

“Method still not implemented”

While debugging WCF exception, one may encounter error in the service like “xyz exception unhandled by user code”. This is some what misleading, but no need to worry.

B) Throw exception of FaultException type

private void MultiplyIntegers()
{
try
{
obj = new BasicmathServiceRef.BasicMathServiceClient();
int result = obj.Multiplication(10, 15);
}
catch (FaultException ex)
{
Response.Write(ex.Message + "");
}
}

On calling this method, WCF will serialize the exception as a Fault message and return to the client as:

“Error occurred while processing for the result”

However, client is unlikely to receive verbose error message if we throw exception of type FaultException even key IncludeExceptionDetailInFaults is true or false. If we see the exception thrown code,

throw new FaultException(new FaultReason("Error occurred while processing for the result"), new FaultCode("mutliplication.method.error"));

we have used FaultCode. Client can use this specific fault code contained in FaultException code to take decision, but this approach becomes more of procedural by many if-else condition to branch out code some thing like:

if (ex.Code.Name == "mutliplication.method.error")
{
Response.Write(ex.Message + "");
}

C) Throwing with strongly typed fault

private void AddIntegers()
{
try
{
obj = new BasicmathServiceRef.BasicMathServiceClient();
int result = obj.Addition(10, 15);
}
catch (FaultException ex)
{
Response.Write(ex.Message + " ");
}
}

With this approach, client will be able to explicitly handle fault of only that type whose service method is to be used by client. Here, we are using BasicMathFault type. At the service level, the specific method has to be decorated with FaultContract attribute so that exception can be serialized as:

[OperationContract]
[FaultContract(typeof(BasicMathFault))]
int Addition(int x, int y);

The detail of fault type is up to our convenient level to let WCF serialize only needful information to client.

When we call this Addition(x,y) method, one may receive this error message if an exception occurs.

“This is an error condition in BasicMath.Addition method”

Thus, we see how we can do exception handling in WCF.

Learning WCF By Example

We will start our first WCF service example using a WCF Service Library template. Using this project type has some useful benefits. Firstly, it will automatically set references to required assemblies and generate some starter code to understand basics of the service. Secondly, it adds an App.config file in the project. Do not get surprised by this *.config file in a .Net *.dll! We will certainly reap benefit from this file when we will test our first WCF service.

Let’s follow these simple steps.
Open Visual Studio 2008. Add a project template as shown in the figure.

Add Temp
Fig 1: Visual Studio 2008 WCF Service Library project template

After adding, you will see two classes: IService1.cs and Service1.cs in the solution explorer. Rename these two files as IBasicMath.cs and MathService.cs respectively. Delete the starter code found in these files, and replace as follows.

In the first file,

namespace MathServiceLibrary
{
//
[ServiceContract]
public interface IBasicMath
{
//
[OperationContract]
int AddIntValues(int x, int y);

[OperationContract]
int SubtractIntValues(int x, int y);
}
}

In the second file,

namespace MathServiceLibrary
{
//
public class MathService : IBasicMath
{
//
#region IBasicMath Members
public int AddIntValues(int x, int y)
{
//
return x + y;
}
public int SubtractIntValues(int x, int y)
{
//
return x – y;
}
#endregion
}
}

Then, lets come to App.config file. We have to remove references of all IService1 and Service1 with IBasicMath and MathService respectively.

This way our first WCF service is ready. Now, let’s recall we have said we will reap benefit from App.config file in a library type project. We have mostly seen App.config in windows .Net *.exe only.

Visual Studio 2008 provides WcfTestClient.exe to test a WCF service. It is a GUI based application to test each member of service interface by reading settings values from App.config. This saves our time to manually build a host and client applications to test the service.

Once you run the application by pressing [F5], WcfTestClient will run.

TestClient
Fig 2: Testing the WCF service using WcfTestClient.exe

By clicking each method, we see the right view where we can supply input values and click “Invoke” button to get result. Also, note the message in the status bar of this window: “Service added successfully”.  If you do not see this status bar message when the WcfTestClient first loaded, chances are that we have made some mistakes in App.config.

I hope you got the result.
Let’s dig more into App.config file. Right click on it from the solution explorer and click Edit WCF Configuration menu item. Another GUI based WCF configuration editor opens. This is a SvcConfigEditor.exe. This utility is used to edit or create configuration files.

Svc
Fig 3: Exploring App.config settings using SvcConfigEditor.exe

I like to explain one more thing in the IBasicMath code. We see two attributes: ServiceContract and OperationContract. A WCF service is basically a collection of endpoints where each endpoint implements a service contract and contains a binding and an address. In short we call ABCs of WCF. A service contract is typically defined by applying attributes to a class or interface. It describes what the service does. OperationContract attribute is analogous to WebMethod attribute and marks the attached method as an exposed operation. See the class MathService, it has no such attribute and only IBasicMath has these attributes. In our current application, these ABCs can be seen in App.config <endpoint/> section.

I hope this tutorial helped us to understand the WCF service in a simple manner. In the next series, we will see how to host this service and test from a separate client application.

Follow

Get every new post delivered to your Inbox.