Friday, July 22, 2016

Unknown disposables: Disposing of non-disposable interface instances

In coding, it's a good practice to use factory methods (or some other creational design pattern) to abstract away creation of class instances. In most of the cases, the "creator" would return not the actual type being created, but the abstraction - the interface.
To emphasize the problem, let's consider the below example:

For simplicity, let's assume that we're dealing with a factory method, and the interface the factory method returns is called "IContract". Note, that IContract does not implement IDisposable. There are two different implementations of IContract - Impl and DisposableImpl. So here comes the interesting part, the DisposableImpl implementation does implement IDisposable.

So now, if one uses the factory method "Create()" to instantiate IContract, it may get a disposable instance back, and won't ever even know about it:

public class ContractFactory
{
    public IContract Create()
    {
        return new DisposableImpl();
    }
}

Obviously, the responsibility of disposing of the disposable instance is on the caller. A lot of people won't even notice the problem and just use the IContract and never worry about freeing up resources as early as possible. Yes, GC will eventually take care of the unnecessary resources, but that'll happen later than the actual variable becomes unnecessary - during finalization.

So one pattern a client can use is the following:

{
    IContract contract = null;
    try {
        contract = new ContractFactory().Create();
    // all the usage of the contract instance happens here
    }
    finally
    {
        IDisposable disposableContract = contract as IDisposable;
        if (disposableContract != null)
        {
            disposableContract.Dispose();
        }
    }
}


This will ensure safety in case of both disposable and non-disposable implementations.
Another way to go, would be to have a wrapper class, encapsulating the disposal logic and being a disposable itself, as follows:

public sealed class DisposableInterface<T> : IDisposable where T : class
{
    private readonly T interfaceInstance;

    public T Instance
    {
        get { return this.interfaceInstance; }
    }

    public DisposableInterface(T instance)
    {
        if (instance == null)
        {
            throw new ArgumentNullException("instance");
        }
       
        this.interfaceInstance = instance;
    }

    // A better implementation would be the usage of the Dispose pattern here.
    // Not doing that here to keep the sample simple.
    public void Dispose()
    {
        IDisposable disposableInstance = this.Instance as IDisposable;
        if (disposableInstance != null)
        {
            disposableInstance.Dispose();
        }
    }
}

Now, the caller could use the IContract as follows:
{
    using (DisposableInterface<IContract> contract = new DisposableInterface<IContract>(new ContractFactory().Create()))
    {
        IContract instance = contract.Instance;
        // all the interaction now happens with the "instance" reference
    }
}

As you can see, the second example is cleaner and nicer.
Now, as you're familiar with the problem, doesn't it raise a natural question: "should this become a pattern and be used all over the place with factory methods, as one can't know whether the actual implementation the factory methods returns will be disposable or not?"....
Think about this and leave any comments you may have.

Wednesday, June 17, 2015

"RunAs /NetOnly" functionality from C# code

Only recently I've learnt about the "/netonly" flag availability for "runas" command. I was really happy to find it, but the issue came later.
It turns out that the runas.exe command can't be automated, as it accepts passwords only through a prompt. So there is no way to pass in credentials without the prompt.

That made me seek for a custom solution for the problem. What it turned out is that the .Net Process API doesn't expose any functionality to control the process creation the way, which "/netonly" flag would results in.

Long story short, I came up with the following solution:
The CreateProcessWithLogonW Win32 API, which is being called internally by runas.exe, has a number of parameters indicating how exactly the process should be created. One of these parameters is "dwLogonFlags". The set of values it can take has one called "LOGON_NETCREDENTIALS_ONLY". From MSDN documentation for that value: "Log on, but use the specified credentials on the network only. The new process uses the same token as the caller, but the system creates a new logon session within LSA, and the process uses the specified credentials as the default credentials.". This is exactly what I need. After few hours of unsuccessful search for a C# code sample, which would create a process with this flag, I ended up creating my own.
The sample code is available for download at: http://1drv.ms/1LeqKnD

Hope you find this useful !

Thursday, April 9, 2015

The Compatibility Pattern: Designing adaptive classes

Any non-deprecated system, soon or late, faces challenges. Some of these challenges are quite common. The two following items represent just a fraction of those:
  • existing file storage doesn't satisfy current/coming space requirements
  • the data model need to be modified/extended to comply with new requirements

Today I’m going to describe a design pattern, which can be applied in a variety of situations (including the two above) and eliminate the pain of code re-write.

So, for the sake of simplicity let’s concentrate on a single scenario. Let’s assume we have an existing system – which is operational. Let’s also assume that “EntityA” is an entity in the data model of the system, and the records of that entity are processed by some business logic: “LogicA”.  So far the system used to operate just fine. Now – new requirements come in – which introduce changes to “EntityA” and the “LogicA” as well. Specifically, new “EntityA” records should be treated differently than the “old/current” records. For the sake of simplicity, let’s limit the changes in “EntityA” by just one new field “Field2”. So here what “EntityA” will look like:

image

where “Field1” is an existing field on the entity. Note, that I intentionally don’t mention the types here as its irrelevant in this context.

Also, let’s assume that “LogicA” is already encapsulated in a class with the same name, as follows:

image

Now, back to the new requirements, which affect “LogicA”. The simplest way to handle the change would be to modify the “LogicA.ProcessData” method. However that won’t be maintainable. Think about any future changes – affecting the same logic. After several such changes it’ll be really a mess and it won’t be easy to figure out how to change something  to impact only specific version of entities. So the simplest and design-wise proper solution would be to introduce new LogicA_New handler for the new entities and put the decision logic of instantiating the proper logic in some factory class. The following diagram depicts that case:

image

Note, that the abstraction of the handling logic into separate classes is an implementation of the Strategy design pattern.

This model allows future expansion of the system by just defining a new strategy/logic and updating the factory method, to return the proper handler type. Handling logic deprecation is quite straight forward as well, and can be handled in the reverse order: the factory method is updated to remove the obsolete case and the appropriate logic handler is removed.

Hope this will save you some time in the future.