Archive

Posts Tagged ‘Debugging’

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.

Advertisements

Visual Studio 2010: Exporting and Importing Break-Points

Coding less and debugging more has always been part of programming. Debugging of code is always accompanied by locating appropriate break-points and inspecting program execution. But locating break points again and again whenever a solution is opened for debugging consumes time. When we feel the program execution is happening as expected, then we either delete break-points or disable them. Overall, programmers spend few minutes for break-points activities.

Visual Studio 2010 comes with new feature of exporting and importing break-points in an xml file. So when we are done with break-points, we can export and save at a physical location. Then, delete the break-points (Ctrl + Shift + F9). Whenever we require break-points again in code, we can import the settings file that we saved last time. This xml file contains all the required settings of break-points in the code like line number, file name, etc.

Snapshots shown below are self-explanatory for .Net programmers.

Open break-point window (Ctrl + Alt + B).

ExportBreakPoints
Fig 1: Exporting break-points

ImportBreakPoints

Fig 2: Importing break-points

After importing break-point xml file, the break-points are again set at lines and files where break-points were set originally.

BreakPoint-XmlStructure
Fig 3: Break-point xml structure

Cheers!

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.

Using DebuggerDisplayAttribute

In .Net, we can view variables contents in different ways like local window, quick watch, etc. In System.Diagnostics namespace, we can see a DebuggerDisplayAttribute class that is used to view variables’ contents in debugger window. This attribute can be applied to class, field, property, enum, delegate, struct, etc.  Using this attribute, we can easily view variable contents in debug mode, and those contents are easily visible as data tip when we move mouse pointer over that variable. This attribute becomes quite useful when we have to view inner contents of custom type object variable when it has collection of values.

For example, we will apply this attribute to a class and watch the collection values in debug window.

[DebuggerDisplay(“Client Name = {CustomerName} Client Type = {CustomerType, nq}”)]
class Customer
{
private string _CustomerName;
private string _CustomerType;
public Customer(string strCustomerName, string strCustomerType)
{
_CustomerName = strCustomerName;
_CustomerType = strCustomerType;
}
public string CustomerName
{
get { return _CustomerName; }
}
public string CustomerType
{
get { return _CustomerType; }
}
}
Now after loading a Customer type collection, we see following view in data tip:
DebuggerDisplayAttribute

Fig 1: DebuggerDisplayAttribute changing the data view.
Had not we used DebuggerDisplayAttribute on Customer class type, we would have to traverse a long hierarchy of tree view of each index value of collection object to view data contents.

Programmers often override ToString() method in the custom class type method to view data. But still DebuggerDisplayAttribute wins the heart!

When ToString() method is overridden inside Customer class, then ToString() method of Customer object will result as:

public new string ToString()
{
return (“Customer Name: ” + _CustomerName + “\n” + “Customer Type: ” + _CustomerType);
}
ToString Method
Fig 2: Result of overridden ToString() method.

DebuggerDisplayAttribute constructor has only one parameter as string. The {} braces contain field or property or method name. In the example above, we have used this way.

[DebuggerDisplay(“Client Name = {CustomerName} Client Type = {CustomerType, nq}”)]

One can also quickly see {CustomerType, nq}. Due to this “nq” specifier, Client Type value is shown without double quotes, whereas Client Name value is still in double quote (see Fig 1). The “nq” specifier is used for string type properties.

Happy debugging for next time!