24 June, 2008

WCF FaultExceptions and Best Practice

Just came across a pretty good blogpost on WCF, FaultExceptions and best-practice related to this:
http://blogs.msdn.com/pedram/archive/2008/01/25/wcf-error-handling-and-some-best-practices.aspx

Have a look...

WCF and Custom Exception Handling (custom exceptions), part 1

As this seems a rather popular topic, I’ve decided to rewrite this post in a more “reader friendly” format. Here goes…


I was really under the impression that WCF allowed "any" type to be used as FaultContract<T>, as long as the type was marked with the [Serializable]-attribute. Surprise-surprise - that is not the case!


If you do not want to declare a completely custom type using the [DataContract] attribute on your own class, but instead provide an Exception-derived type (which is quite common in .NET-.NET scenarios where no interoperability is required), you need to take into account a couple of things. In addition - the "exception based" programming model is more in sync with the general .NET paradigm and thereby easier to handle by a programmer.


First of all - the type to be used as <T> in the FaultContract<T>, is to inherit from CommunicationException (not System.Exception); or so the documentation says. In reality System.Exception will actually do, but better to stay current with the documentation. Next is the really important part - Provide a protected constructor allowing for the serialization process taking SerializationInfo and StreamingContext as arguments:

[Serializable]
public class MyCustomException : CommunicationException
{
public MyCustomException()
{ }

public MyCustomException(string msg) : base(msg)
{}

protected MyCustomException(SerializationInfo info, StreamingContext ctxt) : base(info, ctxt)
{}
}
SERVICE: When declaring a type like the above, it will be (re)thrown at the Client-side (by the proxy) correctly when declared in the ServiceContract like this using the FaultContract(type) as seen below:
/// <summary>
///
My service contract
/// </summary>
[ServiceContract(Namespace="UniqueString")]
public interface IMyService
{
/// <summary>
///
Prints the string.
/// </summary>
/// <param name="msg">
The MSG.</param>
[OperationContract]
[FaultContract(typeof(MyCustomException))]
void PrintString(string msg);
}

The service implementation throwing the exception (MyCustomException) looks like this:

public class MyService : IMyService
{
#region IMyService Members

public void PrintString(string msg)
{
if (string.IsNullOrEmpty(msg))
throw new FaultException<MyCustomException>(new MyCustomException("Input was null"));

//to stuff with input, otherwise...
}

#endregion
}

CLIENT: Throwing this exception-derived type in the service implementation will propagate to the Client just fine and can be caught like this in the client:

    void CallService()
{
try
{
proxy.PrintString(null);
}
catch (FaultException<MyCustomException>)
{
Console.WriteLine("The proper exception caught");
}
catch (CommunicationException)
{
Console.WriteLine("The INCORRECT exception caught");
}
}
}
2011.03.16: Update: To be able to convey your own custom data as well, see this post:
http://blog.clauskonrad.net/2011/03/how-to-wcf-and-custom-exception.html
Technorati Tags:

18 June, 2008

Snippet Compiler

I have previously had the Snippet Compiler (Jeff Kay) installed, as I did not all the time want to launch Visual Studio.
I stopped using the snippy-thing as it at this time was not very good in presenting intellisense.

The story seems to have changed as the newest version of Snippet Compiler! It really seems to have picked up on a number of things - and seems far more appealing to use. I for one will give it another chance...

snippet

Link: snippet compiler homepage.

Windows Workflow, DependancyProperties and Complex objects

If you want to use a complex type as a dependencyPropery in e.q. a Workflow, you might run into problems. I today wanted to use a List<T> as a dependencyPropery in Windows Workflow only to find myself in dire straits.

Like any other class that is to be serialized, the complex properties (like collections) need to be explicitly created in the constructor. All workflows are serializable to allow the WF scheduler to "route" them into the appropriate execution thread within the WFRuntime. Below is the dependency property in question.

/// <summary>
///
Gets the workflow ids started by this Activity.
/// </summary>
/// <value>
The workflow ids.</value>
[Description("The workflows started by this activity. This is set automatically.")]
public List<Guid> WorkflowIds
{
get { return (List<Guid>)GetValue(WorkflowIdsProperty); }
set { SetValue(WorkflowIdsProperty, value); }
}

// Using a DependencyProperty as the backing store for WorkflowIds. This enables animation, styling, binding, etc...
/// <summary>
///
/// </summary>
public static readonly DependencyProperty WorkflowIdsProperty =
DependencyProperty.Register("WorkflowIds", typeof(List<Guid>), typeof(ESSMoveToHearingRuntime));


I attempted this with a Workflow Activity only to realize that it was everything but helpful. The Collection was null when I was in the (overridden) Execute method in the workflow activity. So what to do? It turns out that there is a InitializeProperties method to handle this problem. Initialize your complex objects in the method and they are fully functional when you arrive in the Execute method of an Activity.


protected override void InitializeProperties()
{
base.InitializeProperties();
if(WorkflowIds == null)
WorkflowIds = new List<Guid>();
}

StackOverflow Tags:

VPN Connections and Vista

 

Uh - yet again another "wonderful" thing related to Vista.

When wanting to create a VPN-connection, you might experience that this is not possible as the "Connect to a network" dialog box shows the Internet connection as disabled, even though you are having a perfect and live Internet connection!

It seems that Vista does at times not recognize the current connection for some reason. To mitigate that experience, you can actually start the VPN connection "manually" by entering the Network and Sharing Center. From here you can start the connection explicitly:

networksharing

After doing this - you are having a perfect VPN-tunnel.

17 June, 2008

Chain of Responsibility: Using a Factory?

 

I've been debating a bit with colleges lately whether it is worthwhile to introduce a Factory responsible of setting up the Chain (constructing the chain). If you have the principle of Separation of Concerns in mind - it actually makes a lot of sense to make a factory responsible of setting up the chain for you (the client to the system!).

In this way - when extending the system by adding new links in the chain, you include this new link by letting it be known to the system one place only; namely the Factory. If you were to make the Client responsible of setting up the chain every time, which by the way is the way the COR pattern was presented by Gang of Four, I feel that you bring in an undesired correlation/binding in the system. Make your software components/elements as loosely coupled as possible!

  /// <summary>
///
Factory producing Chains of Responsibility.
/// </summary>
static class InfoChainFactory
{
/// <summary>
///
Creates the chain and returns the first link.
/// </summary>
/// <returns></returns>
public static GenericHandlerBase<Table> CreateChain()
{
var h1 = new ServerInfoHandler();
var h2 = new FileInfoHandler();
var h3 = new DirectoryHandler();

h1.SetSuccessor(h2);
h2.SetSuccessor(h3);

return h1;
}
}


The Client towards this system is seen below constructing the complete chain (called h1). How the chain is constructed or what it is built of - I as a Client don't know and I don't care.



protected void Page_Load(object sender, EventArgs e)
{
//build handler chain
var h1 = InfoChainFactory.CreateChain();

if (!string.IsNullOrEmpty(Request.QueryString["q"]))
{
tblServer.Rows.Clear();
h1.Handle("q", Request.QueryString["q"], tblServer);
}
}

Design Patterns: Why use the Open/Close Principle, SOC and COR patterns...

Having read about the "Open/Close" principle (Open for extension/Closed for modification); I kind of found it difficult to grasp initially - but as I've been thinking more and more about it - the better I like it.

It really makes a lot of sense to keep your classes small and focused instead of having a "large" class doing tons of things. The Open/Close principle also supports very well one of my other favorite design principles: "Separation of Concern" (SOC). The SOC design pattern advocates that a class should do one thing only - hence it is focused! The class should have only "one reason to change" - yes, if the class does only one thing then it has only one reason to change :-)

A good example on the small and focused class factoring way of thinking is the pattern: "Chain of Responsibility" (COR). This pattern encompasses the "separation of concerns" very well as every link in the "chain" is responsible of one thing only. In addition it makes it very simple to extend this system by adding a new link to the Chain (can you see the reference to Open/Close here?). Furthermore the existing links are simple and thereby (should be!) closed for modification (again Open/Close is here!).

I've begun using this COR pattern more and more frequently as it makes development more simple in the sense that every link is: One class - One purpose. It does however make the initial setup a bit more complex than having a switch-statement in your code, but it is a good "investment" to factor your logic in focused classes. Every time I attempt to jump over the fence and use a switch-statement, I often find myself changing this code at a later point in time as "unforeseen" changes are emerging.

As principal illustration of the COR is seen below:

COR

12 June, 2008

Parallel Extensions for .NET

I today had a 10 minute rendez-vous with the Parallel Extensions to .NET 3.5. I was somewhat surprised by how easy it actually was using this stuff. There exists no doubt in my mind that this framework will prove useful in a number of scenarios. You can download the latest bits here.

A normal for-loop looks like this:
private static void RunSingle()
{
    DateTime st = DateTime.Now;
    for(int i = 0; i < maxCount; i++)
    {
        Console.WriteLine(i);
    }

    PrintTime(st, DateTime.Now);
}

and the same logic using Parallel looks like this:
private static void RunParallel()
{
    DateTime st = DateTime.Now;

    var action = newAction<int>(delegate(int i) { Console.WriteLine(i); });
    Parallel.For(0, maxCount, action);
   
    PrintTime(st, DateTime.Now);
}

Using Windows Live Writer with Code snippets

Okay - I finally surrendered to the Microsoft tools of the Live universe.
The "Window Live Writer" is a far better editing experience, than that of Google's editor. Even I prefer Googles bloggingspace over Microsoft.

If you in addition download the Insert from Visual Studio plugin to WLW, you are in a far better condition than using Google's native editing environment.
Link: Paste from Visual Studio

iPhone/XCode - not all cases are equal!

This bit me! Having made some changes to an iPhone application (Obj-C); everything worked fine in the simulator. But, when deploying the s...