Showing posts with label WCF. Show all posts
Showing posts with label WCF. Show all posts

Monday, 28 September 2009

WCF Tracing with Activities

One of the nice features of Windows Communication Foundation (WCF) is that it can generate an excess of trace information that can help us identify issues with our services. All you need to do is turn the tracing on through the app.config like so....

name="System.ServiceModel"
switchValue="Information">
name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "c:\log\Traces.svclog" />
Microsoft even provide a handy tool called Service Trace Viewer Tool (SvcTraceViewer.exe) that can be used to view the trace information that WCF produces.

However, if you have ever looked at one of these traces you will have noticed that it can be difficult to sieve through and find the service call(s) that you are interested in. It becomes especially difficult if the service calls other services. Wading through all this tracing information is time consuming and it can be very frustrating.

Fortunately WCF provides a mechanism called Activities that allow us to correlate related trace information.

Where these Activities start and stop are defined by the developer in code. They can also be propagated across service boundaries and can also be linked together with other related activities.

So, what do you need to do in order to use Activities in your tracing? They are quite simple to use, all you need to do is assign an activity id to the correlation manager. This is a GUID value and is assigned as follows:

Trace.CorrelationManager.ActivityId = Guid.NewGuid();

Now, all the trace messages that are fired after this will be included in this Activity. However, in order for this to appear in the trace log we need to add ActivityTracing to the switchValue of the diagnostics section of the app.config.

name="System.ServiceModel"
switchValue="Information ActivityTracing"
propagateActivity="true">
name="traceListener"
type="System.Diagnostics.XmlWriterTraceListener"
initializeData= "c:\log\Traces.svclog" />
Also, if we want the ActivityId to be passed from one service to another, we can set the propagateActivity attribute to True. This is useful if we are starting the activity in one service operations that is then calling other services operations to achieve it's goals. With propagateActivity set to true, all of the trace information from these services for this particular call would be grouped together.

Wednesday, 25 March 2009

Devweek Day Two

Session 1 - Building applications in the ‘cloud’ with Azure services.

Started the day back with Christian Weyer for another of his amusing style of talks. This time he was introducing how Azure can be used to build applications in the ‘cloud’. The overall impression that I am getting of Azure is that it is a work in-progress. Christian demonstrated this by showing a technology uptake diagram, which well and truly placed ‘cloud’ computing in the emerging technologies section.

Azure is organised into two types of service, web and worker services. The idea is that the services can be up scaled so that the capacity of the application can be increased. For example, if you have a particularly popular web service that starts getting hit by thousands or millions of users you can log into Azure and increase the number of service instances to cover this demand.

Underlying the two core service types is the service bus. This is basically an enterprise service bus in the ‘cloud’. It allows the management and routing of service interactions with services held within the cloud and locally.

Christian also briefly showed the Azure workflow services. These will allow processes or interactions between services to be mapped out visually. Azure workflow's are not based on standard Windows Workflow (WF). They only have a relatively small sub-set of activities that are very ‘cloud’ specific (e.g. connect to cloud service). Although WF seems to be a major part of Microsoft's ‘cloud’ master-plan, they are still far from stable.

Session 2 - The Patterns Dartboard.

For some light entertainment prior to lunch I decided to attend this talk on design patterns. The premise of this talk was that a dart was to be thrown at a ‘dartboard’ of design patterns. Whichever pattern the dart hit one of the presenters, Kevin Jones and Andy Clymery, would present to the group in no more than 15 minutes.

During the next hour and a half they covered the Decorator, Factory, Active Record, State and Mode View Controller (MVC) design patterns. Of these I had particular interest in the Active Record presentation. Actually a first I had no idea what this design pattern was! Then as the presentation moved onwards I realised this is another name for what used to be my favorite design pattern, the Persistence pattern.

I have to say, I very rarely use Active Record (AKA Persistence) anymore, Though it is quite well suited to a small reliable system. I don’t know a great deal about Ruby on Rails but apparently this is the design pattern that it utilises.

For those not familiar with Active Record is that the class should contain the business logic and the code necessary to persist the object in the data store (usually some kind of database). Their interpretation of Active Record suggested that all ‘read’ actions should be static methods and all ‘write’ actions should be instance methods. The example class below demonstrates this:

public class MyClass
{
private int Id;

public static MyClass GetMyClass(int classId)
{
//database select code and return new object with data...
 }

public void Save()
{
//if object does not have ID then INSERT to database else UPDATE...
 }
}

I must admit that in my my years of employing this design pattern it never occurred to me to implement the loading functions as static members.

Session 3 - WCF Security Architecture and Best Practice.

This was one of the ‘must-see’ sessions of the week for me, particularly due to recent issues that I have encountered with security within my WCF applications. Like many features within WCF this can be a confusing area as there is SO much that is configurable.

Dominick Baier ran this session which went into incredible detail about the security options that are available within WCF. I can’t say that I managed to find an exact solution to my particular problem, but I found it a great grounding in the elements of WCF security (it’s all about the Binding!). Plus, I now have his email address - beware Dominick!

As I’m still taking in this wealth of knowledge it is difficult for me to expand any further at the moment.

Session 4 - Visual Studio 2008 IDE Tricks and Tips.

Can I first say that I attended this session purely as my brain couldn't take any more heavy talks on the second day. The WCF security session well and truly finished me off!

Though I have to say that I will be using many of the short-cuts that were introduced in this session. Here is a website that summarises the standard shortcuts in Visual Studio.

Thursday, 5 March 2009

WCF Exceptions and Faults

In Windows Communication Foundation (WCF) exceptions thrown from services have to be converted into Faults - which are basically cross domain friendly exceptions. Custom faults can be created and are just declared using the [DataContract] attribute. The example below shows the declaration of a simple Fault.
[DataContract]
public class MyFault
{
[DataMember]
public string Message { get; set; }

public PasswordFault()
{
}

public PasswordFault(string message)
{
this.Message = message;
}
}
To generate a WCF fault you have to use the FaultException class. The example below shows how we could raise the fault declared in the previous example.
public class myService: IMyContract
{
public void MyMethod
()
{
try
{
......
{
catch (myException exc)
{
MyFault = new MyFault(exc.Message);
throw new FaultException(MyFault, "Failed to run MyMethod");
}
}
}
One other important part of setting up faults in WCF is that the OperationalContract of the method raising the fault needs to define the the FaultContracts that the method can raise. For example we might define the service contract of our service to be as follows:
[ServiceContract]
public interface IMyContract
{
[OperationContract]
[FaultContract(typeof(AuthenticationFault))]
void MyMethod();
}
The FaultContract attribute is telling WCF which faults can be expected. If a fault is thrown that is not defined here, the client will just get an ambiguous FaultException raised and be unable to access the extra data defined in the Fault.

Alternative Fault Handling Techniques

Recently, during the development of quite a large SOA based system I noticed that Faults that are raised by sub-services were not being raised correctly through the next service. The only way to ensure that these faults were received by the client was to recapture the fault (as a FaultException() ) and re throw them!

After a bit of investigation and a very helpful reply to a post on the MSDN WCF forum I was pointed in the direction of this example of using the IErrorHandler interface to add custom error handlers to the individual channel dispatcher. I'm not going to go into any great amount of detail about this, but I strongly recommend reading the article. It gives you a much more elegant way of handling exception to fault conversions in WCF.

Thursday, 23 October 2008

Deep Copies in .NET

A problem that I often have when writing WCF services is that WCF complains when you try to send an Object that has been cast to an ancestor over the wire (as a DataContract). WCF responds by getting confused as to what type of object it is returning.

The only solutions is to create a new instance of the parent class and copy all the fields/properties from the child. This is effectively making a Deep Copy of the object... so it got me thinking about how I could impliment a Deep Copying function in .NET.

My Solution has been implimented as an Exension Method as I want it to be called on a class, but I don't want to have a distant ancestor to all my classes that contains this method. The method itself uses reflection to work out the fields and property values that it needs to copy across.

The code is as follows:
public static object GetDeepCopy(this T originalObject, Type newObjectType)
{
object newObject = Activator.CreateInstance(newObjectType);

//copy fields
FieldInfo[] fields = newObject.GetType().GetFields();
int i = 0;
foreach (FieldInfo field in fields)
{
fields[i].SetValue(newObject, field.GetValue(originalObject));
i++;
}

//copy properties
PropertyInfo[] properties = newObject.GetType().GetProperties();
i = 0;
foreach (PropertyInfo property in properties)
{
properties[i].SetValue(newObject, property.GetValue(originalObject, null), null);
i++;
}
return newObject;
}
This class can be used against any classes if it's namespace is included in the code in which you are using the objects. Here is an example of it in use:

ChildClass one = new ChildClass()
{
Active = true,
Address = "HHWWH",
testone = Testy.two,
otherstuff = "sdsadasd"
};

ParentClass two = (ParentClass)one.GetDeepCopy(typeof(ParentClass));

As you can see, the routine requires that a type is passed in and also the returned value must be cast to the same type.