WCF Dynamic Client Proxy – Implementing IDisposable

WCF, WCF Dynamic Proxy 1 Comment

As my good friend and Readify colleague Buddhike observed the generated WCF Dynamic Proxy was not implementing IDisposable. This is a bit scary as I was quite sure I had that implementation prepared done already so all I can image is that for some reason (no source control?) I’ve been working on an older code base.

So, here is a new implementation that is implementation that implements IDisposable. The only trick is that you have to cast the received proxy to IDisposable in order to use it in a using statement. As a difference from the WCF implementation, the dynamic proxy does not throw at all from the implementation of the IDisposable so it’s safe to use in a using statement:

IService1 service = WCFClientProxy<IService1>.GetReusableFaultUnwrappingInstance("Service1");
using (service as IDisposable)
{
    service.MyOperation1("a", 0);
}

Please download the new version of WCF Client Proxy 1.3.1.

WCF Dynamic (ClientBase) Proxy part three: Connection Pooling and Automatic Disposing

.Net, WCF, WCF Dynamic Proxy 1 Comment

A while ago I published a small and neat Dynamic Proxy that could be used to automatically create for you implementation of the (WCF) ClientBase<T> so you would not have to generate that from the service interface and hand-coded or even bother to maintain.

One of it’s great advantages was that you could ask for a “Reusable” proxy which was basically a wrapper around the proxy that you didn’t have to close/dispose in case of a fault.

As you might know WCF requires that you dispose of the proxy if there is any type of fault detected. Doing this is a pain in any type of code as you have to manage that connection life-time while actually all you care most of the times is that you talk to the service and not the life-time of your connection. The WCF Client Proxy was also doing this management for you allowing you so simply focus on your business and not on opening/closing your connections.

However there are moments in which you also want to specifically close your proxy for example using a using statement. Because the WCF Client Proxy was returning you the exact interface that you requested and if that interface was not implementing IDisposable you had to reside on a trick and cast the received proxy to IDisposable (as the proxy generates that behinds the scenes for you anyway) and use it like this:

IService1 service = WCFClientProxy<IService1>.GetReusableInstance("Service1");
using((IDisposable)service)
{
    service.MyOperation1();
}

This was again a bit ugly as you have to care about the connection and you can’t just use it as any other interface. You do have to be aware that your interface represents a WCF service that you want to dispose of.

One other potential scenario that several people hit is in websites that talk to external WCF services and you use the same service from within the same page several times (for example from different controls). In practice in this scenario you will open/close the same proxy multiple times during the lifetime of the page.

Connection Pooling

In order to simplify the management of WCF connections during the lifetime of a webpage or even a WCF Operation Call and reduce the overhead of caring to dispose of proxies I’ve now added a ProxyConnectionPool class to the dynamic proxy that can be enabled to automatically pickup all the created WCF connections and pool them (as in return the same one back to you if you use it from the same thread and it’s safe to reuse).

To enable the connection pooling all you have to do is:

ProxyConnectionPool.EnableConnectionPool = true;

Now every time you do a call do GetReusableInstance or other methods on the WCFClientProxy the connection you receive might be a pooled one (same tread only pooling) or a new one just registered with the pool. This should improve your performance as creating WCF Proxies is an expensive process that you want to avoid as much as possible.

Disposing the pool

Once you finish your work on that thread you can simply ask the connection pool to dispose all the WCF connections from the pool using:

ProxyConnectionPool.Current.Dispose();

Automatic disposing

If you use WCF inside a website to call other WCF services you should then simply include the following module in your web.config so you get automatic disposing of all WCF connections created on each page request (with peace of mind included).

<system.web>
    <httpModules>
        <add name="WcfConnectionPool" type="ACorns.WCF.DynamicClientProxy.Pool.WcfConnectionPoolHandler,ACorns.WCF.DynamicClientProxy"/>
    </httpModules>
</system.web>

This module will automatically enable the connection pool for you and make sure all the WCF proxies created are nicely disposed at the end of each page request. This truly allows you to focus on writing your business code and not bothering about connection management of your WCF services. Your code will now become:

IService1 service = WCFClientProxy<IService1>.GetReusableInstance("Service1");
service.MyOperation1();

Let someone else deal with the fact that you use WCF :)

Licence

I was requested several times about the licence this code is. Here is my official statement:

This package is provided "AS IS," without express or implied warranty of any kind, and may be used and modified.

This package may be used in corporate applications without any pretence.

However I would appreciate if you would drop me a line to let me know you are using it to corneliu at acorns.com.au or even donate some money by PayPal to the same address :)

Download

Here is the latest version of the WCF Client Proxy 1.3.0

WCF Dynamic ClientBase Proxy part two

.Net, Readify, Tools, WCF 23 Comments

A while ago I wrote a Reusable Client Proxy that allows you to reuse the ClientBase proxy even if it faults without the developer having to take care of the complicated lifetime management and make sure it is closing the proxy if it gets into a faulted state.

After several months of using this proxy and some good feedback I started to write a new version of this proxy and do several small changes:

  • Fixed bug that proxy was not correctly generated if there were multiple levels of inheritance on the contract interface.
  • Added an IClientBase interface that gets implemented automatically that gives access from outside to the ClientBase specific properties (ClientCredentials, EndPoint, InnerChannel and State)
  • Added an event on this interface: ProxyCreated that gets triggerd after a new instance of the proxy was created (e.g. due to a fault) so you can reinitialize the proxy, set the ClientCredentials or any other operations you want to do with the IClientBase.
  • Added support to automatically unwrap Exceptions out of FaultExceptions.
  • The assembly is now signed by default so you can start using it immediatelly.

Implementation details:

FIX: Proxy was not correctly generated for multi-inheritance interfaces

Trying to create a proxy on the IService2 was failing as the code was not generating the MyOperation1 method:

[ServiceContract()]
public interface IService1
{
    [OperationContract]
    string MyOperation1(string arg1, int arg2);
}
[ServiceContract()]
public interface IService2 : IService1
{
    [OperationContract]
    void MyOperation2(string value);
}

Added the IClientBase interface to the generated proxies

A new IClientBase interface was added and all the relevant properties and methods from the real ClientBase<T> class are now exposed.

The interface is only exposed on the objects returned by the GetReusableInstance method.

A new event was also added on the interface: ProxyCreated that is fired every time a new proxy had to be created due to the old one failing.

The event can be used to apply custom ClientCredentials or behaviours.

public delegate void ProxyCreatedHandler(IClientBase proxy);

/// <summary>
/// Interface to expose the inner ClientBase properties hidden by the Proxy
/// </summary>
public interface IClientBase
{
    /// <summary>
    /// Fired when a new proxy is created.
    /// In here you can initialize the Credentials and EndPoints.
    /// </summary>
    event ProxyCreatedHandler ProxyCreated;

    /// <summary>
    /// Gets the client credentials used to call an operation.
    /// Returns a System.ServiceModel.Description.ClientCredentials that represents
    /// the proof of identity presented by the client.
    /// </summary>
    ClientCredentials ClientCredentials { get; }

    /// <summary>
    /// Gets the target endpoint for the service to which the WCF client can connect.
    /// </summary>
    ServiceEndpoint Endpoint { get; }

    /// <summary>
    /// Gets the underlying System.ServiceModel.IClientChannel implementation.
    /// </summary>
    /// <value>The client channel for the WCF client object.</value>
    IClientChannel InnerChannel { get; }

    /// <summary>
    /// Gets the current state of the System.ServiceModel.ClientBase<TChannel> object.
    /// </summary>
    CommunicationState State { get; }

    /// <summary>
    /// Causes the System.ServiceModel.ClientBase<TChannel> object to transition
    //     immediately from its current state into the closed state.
    /// </summary>
    void Abort();

    /// <summary>
    /// Causes the System.ServiceModel.ClientBase<TChannel> object to transition
    //     from its current state into the closed state.
    /// </summary>
    void Close();

    /// <summary>
    /// Causes the System.ServiceModel.ClientBase<TChannel> object to transition
    //     from the created state into the opened state.
    /// </summary>
    void Open();
}

Having the new ProxyCreated event allows a much cleaner type of code to be implemented.

For example if you know you need custom username/password authorization you can subscribe to the event:

IService1 service = WCFClientProxy<IService1>.GetReusableInstance("Service1");
(service as IClientBase).ProxyCreated += new ProxyCreatedHandler(Program_ProxyCreated);

Then handle the event to do the custom authorization:

static void Program_ProxyCreated(IClientBase proxy)
{
    proxy.ClientCredentials.UserName.UserName = "myUser";
    proxy.ClientCredentials.UserName.Password = "myPassword";
}

Other changes

  • Renamed GetWrappedInstance to GetReusableInstance.
  • Dropped the references to the Enterprise Library just in case you don’t use them so the assembly has no external references.
  • Set the version number to 1.2.0.

Update: You can find the Readify.WCF.DynamicClientProxy 1.2 including the source code here.

Building a reusable ClientBase proxy.

Hawkeye, Readify, WCF 8 Comments

Following Juwal Lowy’s Programming WCF Services book and great training courses, we know that we are not allowed to reuse a channel after a fault was reported.

This is good however we don’t really feel like writing all the boiler plate code to do that in our own code and close the channel or create a new one after every exception.

We also know that creating WCF Client Proxies is a slow process so we would like to hang on to them for as long as possible (or until they enter a faulted state). We would also like to hang on to the Policy Injection handle that we received for as long as possible to avoid recreating it.

Here is a nice implementation that will do the closing for us however we are still left with disposing the object and creating a new one whenever you need it.

We could implement a policy and inject it in using the Policy Injection however that would mean we would need to reset somehow the object handle inside the PolicyInjection object. Way to complicated when we could all handle it up-front.

To follow the pattern to emitting code (it’s easy to emit and once tested it always works). No need for boring and error prone copy&paste.

The base class for the wrapper class

This would a good base abstract class that we can inherit for all our wrapper classes.

I also included MarshalByRefObject to allow us to easily use these wrappers with EntLib Policy Injection Block.

/// <summary>
/// Class that can be used with PolicyInjection. Dynamically generated classes will inherit from this class.
/// </summary>
public abstract class WCFAbstractClientProxyWrapper<T> : MarshalByRefObject where T : class
{
    protected T cachedProxy;
    private readonly string configName;

    protected WCFAbstractClientProxyWrapper(string configName)
    {
        this.configName = configName;
    }

    /// <summary>
    /// Called to retrieve a cached instance of the proxy.
    /// </summary>
    protected T Proxy
    {
        get
        {
            AssureProxy();
            return cachedProxy;
        }
    }

    /// <summary>
    /// Close the proxy because it was fauled.
    /// http://bloggingabout.net/blogs/erwyn/archive/2006/12/09/WCF-Service-Proxy-Helper.aspx
    /// </summary>
    protected void CloseProxyBecauseOfException()
    {
        if (cachedProxy != null)
        {
            ICommunicationObject wcfProxy = cachedProxy as ICommunicationObject;
            try
            {
                if (wcfProxy != null)
                {
                    if (wcfProxy.State != CommunicationState.Faulted)
                    {
                        wcfProxy.Close();
                    }
                    else
                    {
                        wcfProxy.Abort();
                    }
                }
            }
            catch (CommunicationException)
            {
                wcfProxy.Abort();
            }
            catch (TimeoutException)
            {
                wcfProxy.Abort();
            }
            catch
            {
                wcfProxy.Abort();
                throw;
            }
            finally
            {
                cachedProxy = null;
            }
        }
    }

    /// <summary>
    /// Create a new proxy if there is none already in use.
    /// If the previous proxy was faulted, it will be nulled and a new proxy is created
    /// </summary>
    private void AssureProxy()
    {
        if (cachedProxy == null)
        {
            cachedProxy = WCFClientProxy<T>.GetInstance(configName);
        }
    }
}

This class respects the Erwyn’s recommendations about the correct closing of a faulted WCF Channel.

The wrapper class

In order to allow our code to simply reuse an existing object even if it’s faulted, we need to wrap an existing client proxy  into another class that implements our interface and does all this boiler plate.

For our current interface:

[ServiceContract()]
    public interface IService1
    {
        [OperationContract]
        [FaultContract(typeof(Exception))]
        string MyOperation1(string arg1, int arg2);

        [OperationContract]
        void MyOperation2(string value);
    }

This would be the wrapper class:

public class ClientProxyWrapperIService1 : WCFAbstractClientProxyWrapper<IService1>, IService1
{
    public ClientProxyWrapperIService1(string configName)
        : base ( configName )
    {
    }

    #region IService1 Members

    public string MyOperation1(string arg1, int arg2)
    {
        try
        {
            return Proxy.MyOperation1(arg1, arg2);
        }
        catch
        {
            CloseProxyBecauseOfException();
            throw;
        }
    }

    public void MyOperation2(string value)
    {
        try
        {
            Proxy.MyOperation2(value);
        }
        catch
        {
            CloseProxyBecauseOfException();
            throw;
        }
    }

    #endregion
}

Simple implementation that for every call will try to close the proxy if it was faulted and then create a new one next time it needs it.

There is a fair bit of code that we would need to type for each method so lets try to code emit this method.

protected override void GenerateMethodImpl(System.Reflection.MethodInfo method, Type[] parameterTypes, System.Reflection.Emit.ILGenerator iLGenerator)
{
    bool hasReturn = !IsVoidMethod(method);
    if (hasReturn)
    {
        // declare a variable to contain the return type
        // string returnValue;
        iLGenerator.DeclareLocal(method.ReturnType);
    }

    // try {
    Label tryLabel = iLGenerator.BeginExceptionBlock();
    {
        // this
        iLGenerator.Emit(OpCodes.Ldarg_0);

        // Get the details Property of the ClientBase
        MethodInfo proxyProperty = GetMethodFromBaseClass("get_Proxy");
        // Get the channel: "base.Channel<TInterface>."
        iLGenerator.EmitCall(OpCodes.Call, proxyProperty, null);

        // Prepare the parameters for the call
        ParameterInfo[] parameters = method.GetParameters();
        for (int index = 0; index < parameterTypes.Length; index++)
        {
            iLGenerator.Emit(OpCodes.Ldarg, (int)(((short)index) + 1));
        }

        // Call the Proxy via the interface
        iLGenerator.Emit(OpCodes.Callvirt, method);

        if (hasReturn)
        {
            // returnValue = result of the function call
            iLGenerator.Emit(OpCodes.Stloc_0);
        }
    }
    // catch {
    {
        iLGenerator.BeginCatchBlock(typeof(object));

        iLGenerator.Emit(OpCodes.Pop);    // get the exception from the stack

        // this
        iLGenerator.Emit(OpCodes.Ldarg_0);

        //call base.CloseProxyBecauseOfException();
        MethodInfo closeProxyMethod = GetMethodFromBaseClass("CloseProxyBecauseOfException");
        iLGenerator.Emit(OpCodes.Call, closeProxyMethod);
        // throw;
        iLGenerator.Emit(OpCodes.Rethrow);
    }
    // }
    iLGenerator.EndExceptionBlock();

    if (hasReturn)
    {
        // return returnValue;
        iLGenerator.Emit(OpCodes.Ldloc_0);
    }

    // Thanks, all done
    iLGenerator.Emit(OpCodes.Ret);
}

Plug this together with the Dynamic WCF Client Proxy generator from yesterday and we can now have this easy wrapper:

/// <summary>
/// Returns a new instance for a client proxy over the specified interface with the specified config name used for initialization.
/// </summary>
public static TInterface GetWrappedInstance(string configName)
{
    // Build the type
    WCFProxyWrapperClassBuilder<TInterface> builder = new WCFProxyWrapperClassBuilder<TInterface>();
    Type type = builder.GenerateType();

    // Create new instance
    TInterface instance = (TInterface)Activator.CreateInstance(type, new object[] { configName });

    return instance;
}

It can’t get any simpler.

If we also want to use the EntLib Policy injection to have nice control and to be able to cache the calls to this services we could then add a new method:

/// <summary>
/// Returns a new instance for a client proxy over the specified interface with the specified config name used for initialization.
/// </summary>
public static TInterface GetPolicyInstance(string configName)
{
    // Create new instance
    TInterface instance = WCFProxyWrapperClassBuilder<TInterface>.GetInstance(configName);

    return PolicyInjection.Wrap<TInterface>(instance);
}

How to we use the proxy wrapper

Because our actual proxy now has a wrapper that will correctly close it when it becomes faulted we don’t really need to care about it anymore and we can simply reuse it even after multiple faults.

IService1 service = WCFClientProxy<IService1>.GetWrappedInstance("Service1");

for (int i = 0; i < 10; i++)
{
    try
    {
        Console.WriteLine(i + " ClientTime:" + DateTime.Now.ToString("HH:MM:ss:ffff") + " result -> " + service.MyOperation1("a", 0));
    }
    catch (Exception ex)
    {
        Console.WriteLine(i + " " + ex.Message);
    }

    Thread.Sleep(1000 * rand.Next(20));
}

This time really it won’t get any simpler.

Performance

Creating the wrapper and the proxy:

The dynamic wrappers and the dynamic proxies are emitted only once the very first time you use them. The performance impact is small simply because code emitting is relatively fast and we only use reflection to look at a public interface. Once the wrapper and proxy are generated they types are stored in a dictionary that is referenced every time we need a new wrapper or proxy.

Calling the service via the wrapper and proxy:

Well considering all we introduce in the call is an extra lookup in the dictionary to search for the correct types that we need to instantiate and we only do that when you create them the overall impact is not big.

The wrapper code you have to write anyway in a way or another in your code. The proxy code is the code you would get generated or hand written in the same way.

There are no reflective calls at any time after the two types were generated so the call stacks are simple and not longer than what you would expect. So performance wise it should make the difference. Just give it a try.

I have to say this was one of the nicest piece of code I’ve wrote in ages.

Download code and demos here.

EntLib PolicyInjection, Caching and WCF Services

EntLib, Readify, WCF 5 Comments

PolicyInjection on WCF Services

Yesterday I’ve worked on writing a nice and quick Dynamic WCF Client Proxy using code emitting. Today I’d like to use this together with EntLib 3.1 Policy Injection and Caching Application Block to cache WCF calls and avoid extra calls if they are requested by the application within a specific amount of time.

The simple way to achieve this is by simply changing the GetInstance method of the WCFClientProxy.cs to:

/// <summary>
/// Returns a new instance for a client proxy over the specified interface with the specified config name used for initialization.
/// </summary>
public static TInterface GetInstance(string configName)
{
    // Build the type
    ClassBuilder<TInterface> builder = new ClassBuilder<TInterface>();
    Type type = builder.GenerateType();

    // Create new instance
    TInterface instance = (TInterface)Activator.CreateInstance(type, new object[] { configName });

    // Wrap it in the Policy Injection
    return PolicyInjection.Wrap<TInterface>(instance);
}

Adding Caching Application Block on the WCF service

Using our new WCFClientProxy class, write a quick config file:

<configSections>
    <section name="policyInjection" type="Microsoft.Practices.EnterpriseLibrary.PolicyInjection.Configuration.PolicyInjectionSettings, Microsoft.Practices.EnterpriseLibrary.PolicyInjection, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</configSections>

<policyInjection>
    <policies>
        <add name="IService1Policy">
            <matchingRules>
                <add type="Microsoft.Practices.EnterpriseLibrary.PolicyInjection.MatchingRules.MemberNameMatchingRule, Microsoft.Practices.EnterpriseLibrary.PolicyInjection, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" name="Member Name Matching Rule">
                    <matches>
                        <add match="MyOperation1"/>
                    </matches>
                </add>
                <add type="Microsoft.Practices.EnterpriseLibrary.PolicyInjection.MatchingRules.TypeMatchingRule, Microsoft.Practices.EnterpriseLibrary.PolicyInjection, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" name="Type Matching Rule">
                    <matches>
                        <add match="IService1"/>
                    </matches>
                </add>
            </matchingRules>
            <handlers>
                <add expirationTime="00:00:10"  type="Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers.CachingCallHandler, Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" name="Caching Call Handler"/>
            </handlers>
        </add>
    </policies>
</policyInjection>

To ask the PolicyInjection to load the CachingCallHandler on our method (IService1.MyOperation1) and cache for no more than 10 seconds.

Write a quick test for the above code:

IService1 service = WCFClientProxy<IService1>.GetInstance("Service1");

Random rand = new Random(7);

for (int i = 0; i < 10; i++)
{
    Console.WriteLine(i + " " + DateTime.Now.ToString("HH:MM:ss:ffff") + " result -> " + service.MyOperation1("a", 0));
    Thread.Sleep(1000 * rand.Next(20));
}

Our server implementation simply returns the time the server has when the call was made.

And give it a try to prove it’s working:

First two calls (0 and 1 with red) share the same “10 seconds” limit defined for the Caching Handler and we can see that even if we called the server twice the same result was returned telling us the Caching Handler kicked in and we avoided the call to the server.

The second and third call (1 and 2 with blue) were done at more than 10 seconds difference and we can see the server was called and it returned a new time.

Quick, simple and easy. No code, no bugs.

If you like EntLib with this code you would achive more or less the same as Glav’s WCF Services Caching without having to roll your own Caching implementation.

Dynamic WCF ClientProxy

.Net, Readify, WCF No Comments

These days as part of my yearly PD (Professional Development) I’m playing with WCF trying to get the best out of it and most of all trying to understand it’s limits and limitations.

One of the very cool parts of WCF is the simplistic model for client and servers:

  • Server: Define an interface, Implement, write some config. Done.
  • Client: Define the same interface, write or generate a proxy (using SvcUtil for example), write some config, instantiate and call. Done.

The server is as straight forward as possible. However the “generate a proxy” bit in the client was the extra step that you need to do to get the client working.

As I’m a lazy typer so I don’t feel like writing my own client proxy and calling SvcUtil is not my cup of tea I decided to write my own WCF Dynamic Client Proxy generator that will use a bit of code emitting to generate the proxy for us at runtime just the way it was supposed to be (manually or with a tool) generated.

Using the WCF (Dynamic) Client Proxy:

My simple interface:

[ServiceContract()]
public interface IService1
{
    [OperationContract]
    string MyOperation1(string arg1, int arg2);

    [OperationContract]
    void MyOperation2(string value);
}

Client code calling the server:

IService1 service1 = WCFClientProxy<IService1>.GetInstance("Service1");
Console.WriteLine(service1.MyOperation1("aaa", 1234));
service1.MyOperation2("my string");

Client config (the “Service1″ in the GetInstance call is the name of the EndPoint that will be used):

<system.serviceModel>
    <client>
        <endpoint name="Service1" address="net.tcp://localhost:8000/Service" contract="WCFFactoryCaching.Common.IService1" binding="netTcpBinding" />
    </client>
</system.serviceModel>

As you see there is no need for a client proxy at all:

 Look ma’ no proxy!

(I know, I know, SvcUtil generates complex types, and Data Contracts and so on, but still, for simple things we need simple solutions).

“Advanced” usage of the WCFClientProxy class

With the assumption that for most simple things we have one proxy defined with one end point from the configuration file I created two simpler methods to allow to register a specific interface on a WCF end point and use that as default whenever you need a connection:

Registering the default end point for the specified interface:

WCFClientProxy<IService1>.RegisterEndpoint("Service1");

Requesting a proxy on the interface with on the default end point:

IService1 service1 = WCFClientProxy<IService1>.GetRegisteredInstance();

Console.WriteLine(service1.MyOperation1("aaa", 1234));

Download Source code and demo.

Under the hood

The implementation of the WCF Client Proxy is very straight forward and it all happens in the ClassBuilder.cs class

  • Generate a new assembly
  • Look at the interface and generate a class inheriting from ClientBase<TInterface> implementing TInterface
  • Generate methods to implement the interface and forward all the call so the “base.Channel.<methodName>(<params>)”
  • Optionally save the assembly on the disk (set the boo saveGeneratedAssembly to true to get the assembly saved on the disk).

A “Reflector view” at the emitted class:

Tomorrow I’ll try to push this one more step and emit wrapper classes that inherit from MarshalByRefObject to allow us to use WCF services with the EntLib 3.1 Policy Injection Block in a simple and straight forward way.