mikeobrien.net Curriculum Vitae Blog Labs
Tuesday, February 02, 2010

I’m currently working on an F# library that will be accessed from C#. When doing this the obvious question is; “How will this look from C#?” This wasn't quite clear to me at first so I’ll go through a couple custom F# types and show how they are compiled.

Record type, Fermion.fs:

type Spin = 
    | Up = 0
    | Down = 1

type Class = 
    | Quark = 0
    | Lepton = 1

type Type = 
    ...
    | Electron = 6
    ...
type Fermion = 
    { spin: Spin; particleClass: Class; particleType: Type }
    member yada.Spin = yada.spin
    member v.Class = v.particleClass
    member v.Type = v.particleType
    member stuff.GetDescription() = 
        System.String.Format(
            "This {0} is a spin {1} {2}.", 
            stuff.particleType.ToString(), 
            stuff.spin.ToString(), 
            stuff.particleClass.ToString())

Using the record type in F#

let electron = { 
    spin = Spin.Down; 
    particleClass = Class.Lepton; 
    particleType = Type.Electron }

In Reflector:

public static class Fermion
{
    public sealed class Fermion : 
        IStructuralEquatable, 
        IComparable, 
        IStructuralComparable
    {
        internal Particles.Class particleClass@;
        internal Particles.Type particleType@;
        internal Particles.Spin spin@;

        public Fermion(
            Particles.Spin spin, 
            Particles.Class particleClass, 
            Particles.Type particleType)
        {
            this.spin@ = spin;
            this.particleClass@ = particleClass;
            this.particleType@ = particleType;
        }

        public string GetDescription()
        {
            return string.Format("This {0} is a spin {1} {2}.",
                this.particleType@.ToString(), 
                this.spin@.ToString(), 
                this.particleClass@.ToString());
        }

        public Particles.Class Class { get { return this.particleClass@; } }
        public Particles.Class particleClass { get { return this.particleClass@; } }
        public Particles.Type particleType { get { return this.particleType@; } }
        public Particles.Spin spin { get { return this.spin@; } }
        public Particles.Spin Spin { get { return this.spin@; } }
        public Particles.Type Type { get { return this.particleType@; } }

        public int CompareTo(Particles.Fermion obj);
        public sealed override int CompareTo(object obj);
        public sealed override int CompareTo(object obj, IComparer comp);
        public bool Equals(Particles.Fermion obj);
        public sealed override bool Equals(object obj);
        public sealed override bool Equals(object obj, IEqualityComparer comp);
        public override int GetHashCode();
        public sealed override int GetHashCode(IEqualityComparer comp);
    }
}

Some things to note:

  • This is a “record type” so a constructor is generated to set all the private fields. No initialization is performed other than this. So record types are essentially a DTO.
  • It is sealed.
  • When creating an instance of this type it it not necessary to explicitly specify it because of F# type inference.
  • The IComparable, IStructuralComparable and IStructuralEquatable interfaces are all automatically implemented by the F# compiler.
  • A namespace was not explicitly defined in the example so the type has no namespace and the type is nested in a static class with the name of the file it was declared in. If a namespace had been defined then this would not have been nested in a static class and would have simply resided under said namespace.
  • The identifiers (“v”, “yada”, “stuff”) which are equivalent to the “this” keyword in C# are all converted to "this" in the output. And as an aside they do not need to be the same throughout the type, just in the method or property declaration.
  • Fields are publicly exposed via a property that is named as you named the field in the F# source. The fields are suffixed with an “@”.
  • As an aside, enumerations must explicitly have a value defined or they will be compiled as discriminated unions.

Now lets mix things up a bit…

Constructed type, Fermion.fs:

namespace Particles

    type Spin = 
        | Up = 0
        | Down = 1

    type Class = 
        | Quark = 0
        | Lepton = 1

    type Type = 
        ...
        | Electron = 6
        ...
    type Fermion(spin: Spin, particleClass: Class, particleType: Type) = 
        let _description = System.String.Format(
                                "This {0} is a spin {1} {2}.", 
                                particleType.ToString(), 
                                spin.ToString(), 
                                particleClass.ToString())
        member yada.Spin = spin
        member v.Class = particleClass
        member v.Type = particleType
        member stuff.GetDescription() = _description

Using the constructed type in F#:

let electron = new Fermion(Spin.Down, Class.Lepton, Type.Electron)

In Reflector:

public class Fermion
{
    internal string _description;
    internal Class particleClass;
    internal Type particleType;
    internal Spin spin;

    public Fermion(Spin spin, Class particleClass, Type particleType)
    {
        this.spin = spin;
        this.particleClass = particleClass;
        this.particleType = particleType;
        this._description = string.Format("This {0} is a spin {1} {2}.", 
                    this.particleType.ToString(), 
                    this.spin.ToString(), 
                    this.particleClass.ToString());
    }

    public string GetDescription() { return this._description; }

    public Class Class {  get { return this.particleClass; } }
    public Spin Spin { get { return this.spin; } }
    public Type Type { get { return this.particleType; } }
}

Some things to note:

  • This is a “constructed type” so there is a constructor. You’re constructor code is simply put in the body of the type and not in a special function like C#.
  • Requires you to explicitly new up the type and pass the parameters in.
  • No interfaces get automatically implemented as in the case of the record type.
  • This class is not sealed.
  • This type was defined under a namespace so it is not wrapped in a static class.
C# | F#
Tuesday, February 02, 2010 6:16:27 PM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  |  Trackback
Tuesday, February 02, 2010 2:27:48 AM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  |  Trackback
Friday, January 29, 2010

The following is an implementation of a safe handle for a device info set:

type DeviceInfoSetSafeHandle() = 
    inherit SafeHandleMinusOneIsInvalid(true)
    [<DllImport("setupapi.dll")>]
    static extern bool SetupDiDestroyDeviceInfoList(IntPtr deviceInfoSet)
    override s.ReleaseHandle() = SetupDiDestroyDeviceInfoList(base.DangerousGetHandle())

It’s extremely trivial to set this up that it’s almost not worth blogging about but maybe someone can benefit from the example...

.NET | F#
Friday, January 29, 2010 4:40:39 AM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  |  Trackback

Functional programming never ceases to amaze me. The more I code in F# the more I’ve come to appreciate how succinct and terse you can write your code. I’ll sometimes start out with an imperative solution but there always seems to be a functional one that is fewer lines of code and much clearer. I’m working on rewriting a project in F#, that allows you to interact with USB HID devices, in order to learn F#. One of the things I ran into is creating an enumerable and disposable type that wraps a couple of API calls.

type DeviceInfoSet(connectedOnly:bool) = 
    let handle = GetDeviceInfoSet connectedOnly
    member private c.ToSeq = 
        Seq.unfold (fun index -> 
                            let info, more = GetDeviceInfo handle index
                            match more with
                            | true -> Some (info, index + 1)
                            | _ -> None
                    ) 0
    interface IEnumerable with
        member c.GetEnumerator () = c.ToSeq.GetEnumerator() :> IEnumerator
    interface IEnumerable<SP_DEVINFO_DATA> with
        member c.GetEnumerator () = c.ToSeq.GetEnumerator()
    interface IDisposable with
        member c.Dispose () = handle.Dispose()

Here we have a constructed class type that takes in a parameter required by the native call. Unlike a C# type definition, the construction doesn't occur in a constructor function but in the body of the type. The ToSeq property generates the sequence. I absolutely love the unfold function, it is so powerful. Here the native method requires an integer to be incremented until an error code is returned to indicate that there are no more records (Not shown). As long as there are more records we return the item and increment the index. Once there are no more we return None. Now we get to the interface implementation. This is pretty straight forward, the only thing you have to do with the non generic IEnumerable implementation is downcast it to IEnumerator with the :> operator.

Here is an example of the usage:

let enumerate = 
    use devices = new DeviceInfoSet(false)
    devices |> Seq.iter (fun item -> Console.WriteLine(item.ClassGuid.ToString()))
The “use” keyword is equivalent to a using statement in C#. Once the “devices” value goes out of scope it is disposed of. 
.NET | F#
Friday, January 29, 2010 4:28:40 AM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  |  Trackback
Monday, January 25, 2010

The Studio 1735 does indeed support 8Gb of RAM. The spec says no and there has been some uncertainty on the web about which notebooks based on the Santa Rosa chipset support it. My bios revision is A04 and I’m running Server 2008 R2. You can pick up the RAM here at Newegg for a decent price.

image

image

Monday, January 25, 2010 6:26:02 PM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  |  Trackback
Saturday, January 23, 2010

Our database scripts reside in our SVN repo and when we do an svn update we want to have a friendly reminder if they’ve been modified by another developer (so that we can sync up our local database). Client hook scripts seemed like a perfect choice for this, as did a PowerShell script. I ran into many quirks while trying to make this happen, one of which was that TSVN captures the output of a hook script in order to catch errors. This means that you cant really use hook scripts OOB for displaying a message. If your interested in having a setting in TSVN to change this behavior, please post a comment here.  Although in PowerShell we can issue a command to start up a new PowerShell instance to run our script, freeing us from the shackles of TSVN:

powershell.exe -command "& {start-process powershell.exe (([system.environment]::GetCommandLineArgs()|ForEach-Object -process { '\"{0}\"' -f $_ })[3..([system.environment]::GetCommandLineArgs().Length-1)])}" "-file" "C:\MyScript.ps1"

This command deals with some other quirks that I ran into. One is that the $args variable contains improperly parsed command line arguments when used in a -command. It doesn’t respect quoted qualifiers and splits on spaces even when a parameter is quote qualified. Also they need to be requalified before they are passed to the script or you run into the same issue. The command also drops the first few parameters as these are not needed and cause problems.

So all you have to do is create a hook script under TSVN settings and paste in the above command (With the path to your script) and your good to go. I suggest checking the “Hide the script...” checkbox as this call will cause an initial console window to popup and disappear if you don't.

image

Saturday, January 23, 2010 4:08:48 AM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  |  Trackback
Wednesday, January 13, 2010

Our entities all have modified and created dates associated with them and we wanted these set automatically. I settled on using an interceptor which is discussed by Ray Houston here and a caveat (Actually just some fine print I would have missed) discussed here by Jan Van Ryswyck.

All you do is create a class that inherits from NHibernate.EmptyInterceptor (Which itself implements IInterceptor and allows you to only handle the things you want to handle) and override the the methods you want to handle. In our case we just needed inserts (OnSave) and updates (OnFlushDirty). Return true on those methods only if you made a modification otherwise return false. I created and interface that identifies an entity:

public interface IEntity
{
    Guid Id { get; }
    DateTime Modified { get; set; }
    DateTime Created { get; set; }
}

... and we only operate on entities that implement this interface:

public class EntityInterceptor : EmptyInterceptor
{
    public override bool OnSave(object entity, object id, object[] state, 
        string[] propertyNames, NHibernate.Type.IType[] types)
    {
        if (!(entity is IEntity)) return false;

        var created = DateTime.Now;
        SetState<IEntity>(propertyNames, state, x => x.Created, created);
        SetState<IEntity>(propertyNames, state, x => x.Modified, created);
        return true;
    }

    public override bool OnFlushDirty(object entity, object id, object[] currentState,
         object[] previousState, string[] propertyNames, NHibernate.Type.IType[] types)
    {
        if (!(entity is IEntity)) return false;

        SetState<IEntity>(propertyNames, currentState, x => x.Modified, DateTime.Now);
        return true;
    }

    private void SetState<T>(string[] propertyNames, object[] state, 
        Expression<Func<T, object>> property, object value)
    {
        var index = Array.IndexOf(propertyNames, property.GetPropertyName());
        if (index == -1) return;
        state[index] = value;
    }
}

The key is to set the state in OnSave and the currentState in OnFlushDirty to the new value, do not modify the entity. The names of the values are held in the propertyNames array, thus the need for the SetState method to lookup the index of the property you want to modify. One thing I didn't like about my first incarnation were the magic strings for the property names. So I shamelessly ripped off some code from Gabriel Schenkers post on Dynamic vs Static Reflection (A really good read!) to allow me to pass an expression instead of a magic string. I turned it into extension methods as follows:

public static class ExpressionExtensions
{
    public static string GetPropertyName<T>(this Expression<Func<T, object>> expression)
    {
        var memberExpression = expression.GetMemberExpression();
        var propertyInfo = memberExpression.Member as PropertyInfo;
        return propertyInfo == null ? null : propertyInfo.Name;
    }

    public static MemberExpression GetMemberExpression<T>(
                      this Expression<Func<T, object>> expression)
    {
        MemberExpression memberExpression = null;
        if (expression.Body.NodeType == ExpressionType.Convert)
        {
            var body = (UnaryExpression)expression.Body;
            memberExpression = body.Operand as MemberExpression;
        }
        else if (expression.Body.NodeType == ExpressionType.MemberAccess)
        {
            memberExpression = expression.Body as MemberExpression;
        }
        if (memberExpression == null)
        {
            throw new ArgumentException("Not a member access", "member");
        }
        return memberExpression;
    }
}

Fluently registering the interceptor is as follows:

_sessionFactory =
    Fluently.Configure().
        Database(persistenceConfigurer).
        Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly())).
        ExposeConfiguration(config => config.Interceptor = new EntityInterceptor()).
        BuildSessionFactory();
Wednesday, January 13, 2010 9:41:59 PM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  |  Trackback
Tuesday, January 12, 2010

StructureMap is an excellent IoC tool; very powerful and easy to use. One thing that I think is lacking though is a way to create a custom lifecycle “strategy” (For lack of a better word). Currently you can specify a lifecycle and you can use one the hybrid lifecycles but this isn’t sufficient in some circumstances. In our code base we have ASP.NET web pages, WCF services, Windows services and console applications (And who knows what next, MVC?) and we have one registry for all these applications. We’re using NHibernate so we have different lifecycle needs for ISession in each type of application. Another side of a lifecycle is the end of it. We want to be able to explicitly end a lifecycle in our ASP.NET and WCF apps. So this is what I mean by a “strategy”.

Solution

One thing that’s really nice about StructureMap is that it’s really easy to extend. Jeremy et al have done a great job of creating a codebase that’s really easy to dive into and understand. So the following is a strategic lifecycle API that allows you to define a lifecycle strategy. I’ll first explain how to use it and then further down I’ll explain the code under the covers. Now I do want to give the disclaimer that I’m no StructureMap expert or anything, so there may be better or more “correct” ways to do this. If so, be sure to leave a comment if you know.

You can download the code here. The code that matters is in the StructureMapContrib project.

Lifecycle strategies can be defined with the LifecycleStrategiesAre() method which takes any number of ILifecycleStrategy parameters:

ObjectFactory.Configure(
    config => config.For<INumberGenerator>().
              LifecycleStrategiesAre(...).
              Use<NumberGenerator>());

This is simply a convenience extension method for the following:

ObjectFactory.Configure(
    config => config.For<INumberGenerator>().
              LifecycleIs(new StrategicLifecycle(...)).
              Use<NumberGenerator>());

StrategicLifecycle implements ILifecycle and contains the different lifecycle strategies. Now a LifecycleStrategy can take three pieces of information; first, a lambda that determines if the lifecycle is valid (If this is not specified it defaults to true). Second, a lambda that lazily creates the lifecycle. And third, a lambda that will deterministically dispose of the object cache (If this is not specified then the object cache is not deterministically disposed). The following is a strategy defined for ASP.NET pages:

new LifecycleStrategy(
    () => HttpContextLifecycle.HasContext() && HttpContext.Current.Handler is Page, 
    () => new HttpContextLifecycle(), 
    c => ((Page)HttpContext.Current.Handler).Unload += ((s,e) => c.DisposeAndClear())),

This strategy is only valid when there is a current HttpContext and when the handler is a Web.UI.Page. In this case we would use StructureMap’s HttpContextLifecycle. And we want to deterministically dispose of the object cache by hooking into the page Unload event. We can define other strategies to create a full lifecycle strategy as follows:

ObjectFactory.Configure(
    config => config.For<INumberGenerator>().
              LifecycleStrategiesAre(
                  new LifecycleStrategy(
                        () => HttpContextLifecycle.HasContext() && HttpContext.Current.Handler is Page, 
                        () => new HttpContextLifecycle(), 
                        c => ((Page)HttpContext.Current.Handler).Unload += ((s,e) => c.DisposeAndClear())),

                  new LifecycleStrategy(
                        WcfOperationLifecycle.HasContext, 
                        () => new WcfOperationLifecycle(), 
                        c => OperationContext.Current.OperationCompleted += ((s, e) => c.DisposeAndClear())),

                  new LifecycleStrategy(() => new ThreadLocalStorageLifecycle())).
              Use<NumberGenerator>());

Here we have a strategy that defines lifecycles for ASP.NET pages, WCF services and a fallback or default strategy of thread local storage. BTW, the WcfOperatonLifecycle is explained here. Notice that the thread local storage doesn't specify if it is valid or an explicit dispose handler. Since it’s a fall back strategy it is listed last and is always valid and the object cache will not be deterministically disposed. This registration looks a bit cluttered so I’ve encapsulated these strategies into their own classes which cleans things up a bit:

ObjectFactory.Configure(
    config => config.For<INumberGenerator>().
              LifecycleStrategiesAre(
                  new HttpContextAndPageLifecycleStrategy(),
                  new WcfOperationLifecycleStrategy(),
                  new LifecycleStrategy(() => new ThreadLocalStorageLifecycle())).
              Use<NumberGenerator>());

And that’s it. Now below, if you’re interested, we’ll examine the code behind this.

Implementation

It all starts with the StrategicLifecycle class:

public class StrategicLifecycle : ILifecycle
{
    private IEnumerable<ILifecycleStrategy> _strategies;

    public StrategicLifecycle(params ILifecycleStrategy[] strategies)
    { _strategies = strategies; }

    public void EjectAll()
    { ResolveLifecycle().EjectAll(); }

    public IObjectCache FindCache()
    { return ResolveLifecycle().FindCache(); }

    public string Scope
    { get { return "StrategicLifecycle"; } }

    private ILifecycle ResolveLifecycle()
    {
        var lifecycle = (from strategy in _strategies
                         where strategy.IsValid()
                         select strategy.Lifecycle).FirstOrDefault();
        if (lifecycle == null) throw
            new Exception("Unable to find a suitable lifecycle Strategy.");
        return lifecycle;
    }
}

This lifecycle dynamically chooses a valid lifecycle by calling the IsValid() method on all the ILifecycleStrategy’s passed in. The first one it finds is the winner.

Lifecycle strategies implement the ILifecycleStrategy interface which only has two members; IsValid() to determine it the lifecycle is valid in a particular circumstance and the Lifecycle property to return an instance of a lifecycle:

public interface ILifecycleStrategy
{
    bool IsValid();
    ILifecycle Lifecycle { get;}
}

This is the implementation of ILifecycleStrategy that I’m using:

public class LifecycleStrategy : ILifecycleStrategy
{
    private Func<bool> _isValid;
    private ILifecycle _lifecycle;
    private Func<ILifecycle> _create;
    private Action<IObjectCache> _dispose;

    public LifecycleStrategy(Func<ILifecycle> create, Action<IObjectCache> dispose) : this(() => true, create, dispose) { }
    public LifecycleStrategy(Func<bool> isValid, Func<ILifecycle> create) : this(isValid, create, null) { }
    public LifecycleStrategy(Func<ILifecycle> create) : this(() => true, create, null) { }

    public LifecycleStrategy(Func<bool> isValid, Func<ILifecycle> create, Action<IObjectCache> dispose)
    {
        _isValid = isValid;
        _create = create;
        _dispose = dispose;
    }

    public bool IsValid()
    {
        return _isValid();
    }

    public ILifecycle Lifecycle
    {
        get
        {
            if (_lifecycle == null)
                if (_dispose == null) _lifecycle = _create();
                else _lifecycle = new DisposableLifecycleProxy(_create(), _dispose);
            return _lifecycle;
        }
    }
}

This is simply a container for the lambdas passed in and for the lifecycle. The lifecycle is created lazily and cached. You’ll notice that if a deterministic dispose lambda is passed, the lifecycle is wrapped in a DisposableLifecycleProxy class. Here is that class:

public class DisposableLifecycleProxy : ILifecycle
{
    private ILifecycle _lifecycle;
    private Action<IObjectCache> _dispose;
    private Dictionary<IObjectCache, IObjectCache> _objectCaches = 
        new Dictionary<IObjectCache, IObjectCache>();

    public DisposableLifecycleProxy(ILifecycle lifecycle, Action<IObjectCache> dispose)
    {
        _lifecycle = lifecycle;
        _dispose = dispose;
    }

    public void CacheDisposed(IObjectCache objectCache)
    {
        if (!_objectCaches.ContainsKey(objectCache)) return;
        lock (_objectCaches) { _objectCaches.Remove(objectCache); }
    }

    public void EjectAll() { _lifecycle.EjectAll(); }

    public IObjectCache FindCache()
    {
        IObjectCache objectCache = _lifecycle.FindCache();

        // This is here to ensure the close lambda is only executed once
        // per object cache. Not sure of a better way to handle this.
        if (!_objectCaches.ContainsKey(objectCache))
        {
            ObjectCacheProxy proxy = new ObjectCacheProxy(this, objectCache);
            lock (_objectCaches) { _objectCaches.Add(objectCache, proxy); }
            _dispose(proxy);
        }

        return _objectCaches[objectCache];
    }

    public string Scope { get { return _lifecycle.Scope; } }

    // ────────────────────────── Nested Types ──────────────────────────

    public class ObjectCacheProxy : IObjectCache, IDisposable
    {
        private IObjectCache _objectCache;
        private DisposableLifecycleProxy _lifecycleProxy;
        private bool _disposed;

        public ObjectCacheProxy(DisposableLifecycleProxy lifecycleProxy, IObjectCache objectCache)
        {
            _objectCache = objectCache;
            _lifecycleProxy = lifecycleProxy;
        }

        public void DisposeAndClear() 
        {
            _objectCache.DisposeAndClear(); 
            Dispose();
        }

        public void Dispose()
        {
            if (_disposed) return;

            _disposed = true;
            _lifecycleProxy.CacheDisposed(_objectCache);
        }

        public int Count { get { return _objectCache.Count; } }
        public void Eject(Type pluginType, Instance instance) { _objectCache.Eject(pluginType, instance); }
        public object Get(Type pluginType, Instance instance) { return _objectCache.Get(pluginType, instance); }
        public bool Has(Type pluginType, Instance instance) { return _objectCache.Has(pluginType, instance); }
        public object Locker { get { return _objectCache.Locker; } }
        public void Set(Type pluginType, Instance instance, object value) { _objectCache.Set(pluginType, instance, value); }
    }        
}

This is the part I’m not all that fond of. It’s a bit too much acrobatics to do something really simple and I wasn't able to put any more effort into it because of time constraints. But it’s the only way I could figure out to transparently control the lifetime of an object cache. Essentially the dispose lambda is called the first time the FindCache() method is called. This class maintains a dictionary of all the object caches it’s called the dispose lambda on so that it only ever calls it once per object cache. Plus the object cache that is returned is wrapped in a proxy that will signal back that the object cache has been disposed and can be removed from the mapping. I wish there was something that indicated if the cache existed before you called FindCache(). That way you could tell if it was newly created and in this case call the explicit dispose lambda on it. For now this is my workaround.  

The rest of the classes in the StructureMapContrib project are just simple convenience classes and shouldn’t require any explanation.

Tuesday, January 12, 2010 6:04:12 PM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  |  Trackback

We have a RESTful and SOAPy API so having a WCF operation lifecycle in StructureMap was imperative. Creating lifecycles in StructureMap is cake. You can find some examples under the Pipeline namespace in the StructureMap source code. All you do is create a class that implements StructureMap.Pipeline.ILifecycle. Below is a lifecycle that is based on a WCF operation:

public class WcfOperationLifecycle : ILifecycle
{
    public static readonly string ITEM_NAME = "STRUCTUREMAP-INSTANCES";

    public void EjectAll()
    {
        FindCache().DisposeAndClear();
    }

    public IObjectCache FindCache()
    {
        if (!OperationContext.Current.OutgoingMessageProperties.ContainsKey(ITEM_NAME))
            OperationContext.Current.OutgoingMessageProperties.Add(ITEM_NAME, new MainObjectCache());
        return (IObjectCache)OperationContext.Current.OutgoingMessageProperties[ITEM_NAME]; 
    }

    public string Scope { get { return "WcfOperationLifecycle"; } }
}

I used the existing HttpContextLifecycle class as my starting point. The important part of this class is the FindCache() method which locates the object cache. As you can see above we are stashing the object cache in the outgoing message properties. I’m not sure what the significance of the Scope property is other than debugging perhaps, but from what I can see you just return a descriptive string.

Registering this is also very simple; simply specify this as the lifecycle you’d like to use:

ObjectFactory.Configure(
    config => config.For<INumberGenerator>().
              LifecycleIs(new WcfOperationLifecycle()).
              Use<NumberGenerator>());

That’s all there is to it!

Tuesday, January 12, 2010 4:49:09 PM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  |  Trackback
Saturday, January 09, 2010

Jimmy Bogard has written a couple of posts here and here discussing the registering partially closed generic types with StructureMap. These posts helped me solve a problem I was having which is a little bit different. To set the stage let me explain what we’re doing. First we have a generic repository interface:

public interface IRepository<TEntity> : IQueryable<TEntity> where TEntity : class
{
    TEntity Get(Guid id);
    void Save(TEntity entity);
    void Delete(TEntity entity);
    void DeleteSingle(IQueryable<TEntity> query);
    void DeleteMany(IQueryable<TEntity> query);
}

Then we will have an interface for a specific repository that inherits from the generic repository interface and includes convenience methods:

public interface IAccountRepository : IRepository<Account>
{
    void DeleteInactiveAccountsOlderThanTwoYears();
    void CreateAccountBasedOnExistingAccount(Account account);
    // Etc, etc, etc
}

Then we have the concrete class that implements the repository specific interface (The NHibernateRepositoryBase class implements the members defined by IRepository<TEntity> not show below):

public class AccountRepository : NHibernateRepositoryBase<Account>, IAccountRepository
{
    public void DeleteInactiveAccountsOlderThanTwoYears() {...};
    public void CreateAccountBasedOnExistingAccount(Account account) {...};
    // Etc, etc, etc    
}

So what I wanted is to scan our persistence assembly for any concrete types (IE: AccountRepository) that implement an interface (IE: IAccountRepository) that derives from a closed generic interface (IE: IRepository<Account>) that is of a particular open generic interface type (IE: IRepository<>). Clear as mud?? :) Simply put, I want to scan for IRepository<> and want to map IAccountRepository to AccountRepository. This is cake with StructureMap using a registration convention. BTW, I’m using StructureMap 2.5.4 and from what I understand you may need this version to do what I’m doing here.

I lifted the GenericConnectionScanner class (Which is what the ConnectImplementationsToTypesClosing convenience method uses) from the StructureMap code as my starting point and modified the logic:

public class DerivedOpenGenericInterfaceConnectionScanner : IRegistrationConvention
{
    private readonly Type _openType;

    public DerivedOpenGenericInterfaceConnectionScanner(Type openType)
    {
        _openType = openType;
        if (!_openType.IsInterface || !_openType.IsOpenGeneric())
            throw new ApplicationException(
                "This scanning convention can only be used with open generic interface types");
    }

    public void Process(Type type, StructureMap.Configuration.DSL.Registry registry)
    {
        if (!type.IsConcrete()) return;
        var derivedTypes = type.GetInterfaces().
                            Where(i => i.GetInterfaces().
                                    Any(i2 => i2.IsGenericType && 
                                              i2.GetGenericTypeDefinition() == _openType));
        if (derivedTypes.Count() > 0) registry.For(derivedTypes.First()).Add(type);
    }
}

The constructor takes the open generic interface type. The Process method is called for each type; we only want concrete types. We check the type for interfaces that derive from an interface that has a type definition of our open generic interface type. If one exists we map the derived interface type to the concrete type.

ObjectFactory.Initialize(
    x => x.Scan(
        config => {
             config.AssemblyContainingType(typeof(IRepository<>));
             config.With(new DerivedOpenGenericInterfaceConnectionScanner(typeof(IRepository<>)));
         }));

var accountRepo = ObjectFactory.GetInstance<IAccountRepository>();
System.Diagnostics.Debug.Assert(accountRepo != null && accountRepo is AccountRepository);

The above initialization scans the assembly containing our open generic interface type and specifies our registration convention using the With() method. That’s all there is to it!

Saturday, January 09, 2010 3:18:08 AM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  |  Trackback
Monday, December 28, 2009

Today I had to write some code that had nullable parameters that could filter the results of a Linq query. At first I was doing “if” statements on the nullable parameters to determine if they needed to be applied. This was pretty verbose so I came up with a more succinct approach with conditional Linq extension methods.

First define conditional extension methods on IQueryable<>:

public static class IQueryableExtensions
{
    public static IQueryable<T> Where<T>(this IQueryable<T> query, bool condition, 
        System.Linq.Expressions.Expression<Func<T, bool>> predicate)
    {
        return condition ? query.Where(predicate) : query;
    }

    public static IQueryable<T> Take<T>(this IQueryable<T> query, bool condition, int count)
    {
        return condition ? query.Take(count) : query;
    }

    public static IQueryable<T> Skip<T>(this IQueryable<T> query, bool condition, int count)
    {
        return condition ? query.Skip(count) : query;
    }

    // ...
}

Then you get a nice fluent way to conditionally apply the parameters:

public List<Template> EnumerateTemplates(
    Guid accountId,
    int? startIndex,
    int? maxResults,
    Guid? groupId,
    bool? includeSubGroups,
    DateTime? olderThan,
    DateTime? newerThan)
{
    using (IRepository<Template> templates = Context.Current.Create<IRepository<Template>>())
    {
        var selectedTemplates = templates.
            Where(t => t.Account.Id == accountId).
            Where(groupId.HasValue, t => t.Group.Id == groupId.Value).
            Where(!groupId.HasValue && includeSubGroups.HasValue && 
                  !includeSubGroups.Value, t => t.Group == null).
            Where(olderThan.HasValue, t => t.Created < olderThan.Value).
            Where(newerThan.HasValue, t => t.Created > newerThan.Value).
            Take(maxResults.HasValue, maxResults.Value).
            Skip(startIndex.HasValue, startIndex.Value - 1);

        return selectedTemplates.ToList();
    }
}
C# | Linq | NHibernate
Monday, December 28, 2009 9:34:05 PM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  |  Trackback

If your developing F# applications and using SVN then you’ll be happy to know that the latest version of VisualSVN supports F# in VS2010.

image

One bummer is that it looks like they aren’t considering a Git offering (At least in the “short term” anyways). I inquired about this and here was the answer Olga Dolidze from VisualSVN support gave:

“I regret to say but we do not have short-terms plans for developing a
GIT-version of our products...”

Although I’m not tied to having VCS functionality in the IDE, it is convenient at times.

Monday, December 28, 2009 2:25:03 AM (GMT Standard Time, UTC+00:00)  #   |  Comments [0]  |  Trackback
Creative Commons License