Creating solid classes with AutoFac

Let’s say we’ve encapsulated an operation our application has to perform. I tend to write little classes which express the desired behaviour or which delegate to other classes if the need arises. An example of such an operation is the class illustrated here ‘UpdateCustomerCommand’.

class UpdateCustomerCommand
    : IRequestHandler<UpdateCustomerRequest, UpdateCustomerResponse>
{
    private IDbContext _context;        
 
    public UpdateCustomerCommand(IDbContext context)
    {
        _context = context;
    }
 
    public async Task Handle(UpdateCustomerRequest request)
    {
        var customer = _context.Customers.Single(x => x.Id == request.Id);
        customer.Name = request.Name;
        customer.Address = request.Address.ToModel();          
        await _context.SaveChangesAsync();
        return new UpdateCustomerResponse();
    }
}

In any application of reasonable size you end up with a lot of these classes. You want to keep these small and easy to read and keep any infrastructure out of the way. Let’s say we want to use transactionscope to manage the transaction, perhaps we’re connecting to a bunch of databases or reading from a message queue. You don’t want to modify all these command classes to add this behaviour. One solution is to introduce a base class which has this behaviour, but we all prefer composition over inheritance right? Let’s create a simple transactionalhandler.

class TransactionalCommandHandler<TRequest, TResponse>
    : IRequestHandler<TRequest, TResponse>;
    where TRequest : IRequest
    where TResponse : IResponse
{
    private IRequestHandler<TRequest, TResponse> _innerHandler;
 
    public TransactionalCommandHandler(IRequestHandler<TRequest, TResponse> handler)
    {
        _innerHandler = handler;
    }
 
    public async Task Handle(TRequest request)
    {
        using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
        {
            var response = await _innerHandler.Handle(request);
            scope.Complete();
            return response;
        }
    }
}

This class is short and sweet and allows us to write this code once and not repeat it again and again. We just need to find a way to create the transactionalhandler and then pass in an instance of our class which does actual work as the inner handler. Enter AutoFac (or pretty much any IoC framework).

You can wire this up in AutoFac with the following code (copied and adapted from their website).

var builder = new ContainerBuilder();
 
builder.RegisterGeneric(typeof(IRequestHandler<,>))
    .Named("handler", typeof(IRequestHandler<,>));
 
 
builder.RegisterGenericDecorator(
    typeof(TransactionalCommandHandler<>),
    typeof(IRequestHandler<>),
    fromKey: "handler");
 
var container = builder.Build();
 
// You can then resolve closed generics and they'll be
// wrapped with your decorator.
var updateCustomerHander = container.Resolve<IRequestHandler<UpdateCustomerRequest, UpdateCustomerResponse>>();

This approach is great if you have one cross cutting concern handler (like the transactionalhandler) and want to apply it to every implementation. There is no built in approach though if you want to apply this behaviour only to some classes. If you need more control you need to write some infrastructure code.

I introduce an attribute “NotTransactional” and apply it to some classes that I don’t want to take part in this decorator process. I then change the registration process.

private void RegisterCommandHandlers(ContainerBuilder containerBuilder)
{
    containerBuilder.RegisterGeneric(typeof(TransactionalCommandHandler<,>));
 
    foreach (var handlerType in typeof(CommandModule).Assembly
        .GetTypes().Where(i => i.IsClosedTypeOf(typeof(IRequestHandler<,>))))
    {
        containerBuilder.RegisterType(handlerType);
        var registerAsInterfaceType = handlerType.GetInterfaces().Single(t => t.GetGenericTypeDefinition() == typeof(IRequestHandler<,>));
        containerBuilder.Register(c =>
        {
            var handler = c.Resolve(handlerType);
 
            if (!handlerType.GetCustomAttributes(typeof(NotTransactionalAttribute), true).Any())
            {
                handler = c.Resolve(typeof(TransactionalCommandHandler<,>)
                    .MakeGenericType(registerAsInterfaceType.GetGenericArguments()),
                    new TypedParameter(registerAsInterfaceType, handler));
            }
            return handler;
        }).As(registerAsInterfaceType);
    }
}
  1. First I register the open generic type of the transactionalhandler.
  2. I then loop trough every concrete class that implements the request handler interface and register them in the container.
  3. The classes that will request the concrete handlers will always ask for an instance of the interface IRequestHandler with concrete request and response objects. The UpdateCustomerRequest for instance. So I register that type as well.
  4. The registration mentioned above is done with a lambda. Whenever someone asks for an command handler we resolve the concrete implementation and if it wants to participate in a transaction we also ask for the transactional handler and pass our concrete handler to its constructor.

The same approach can be used to further decorate your commands. Adding a claims check can become pretty trivial.

First create an attribute.

[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
sealed class AuthorizeUserAttribute : Attribute
{  
    public string ClaimType { get; set; }
    public string ClaimValue { get; set; }         
}

Then apply it to the necessary classes.

[AuthorizeUser(ClaimType = AppClaims.Administrator)]
class ManageCustomerCommand
    : IRequestHandler<ManageCustomerRequest, ManageCustomerResponse>
{
    //omitted for brevity
}

Create a handler which does the user authorization.

class AuthorizedUserCommandHandler<TRequest, TResponse>
    : IRequestHandler<TRequest, TResponse>
    where TRequest : IRequest
    where TResponse : IResponse
{
    private IRequestHandler<TRequest, TResponse> _innerHandler;
 
    private string _checkExistingClaim;
    private string _existingClaimValue;        
 
    public AuthorizedUserCommandHandler(IRequestHandler<TRequest, TResponse> handler, string checkExistingClaim, string existingClaimValue)
    {
        _innerHandler = handler;         
        _checkExistingClaim = checkExistingClaim;
        _existingClaimValue = existingClaimValue;
    }
 
    public async Task<TResponse> Handle(TRequest request)
    {            
        CheckAccess(System.Threading.Thread.CurrentPrincipal as ClaimsPrincipal);
        return await _innerHandler.Handle(request);
    }
 
    private void CheckAccess(ClaimsPrincipal principal)
    {
        //omited for brevity
    }
}

And finally wire everything up.

private void RegisterCommandHandlers(ContainerBuilder containerBuilder)
{
    containerBuilder.RegisterGeneric(typeof(TransactionalCommandHandler<,>));
    containerBuilder.RegisterGeneric(typeof(AuthorizedUserCommandHandler<,>));
    foreach (var handlerType in typeof(CommandModule).Assembly.GetTypes().Where(i => i.IsClosedTypeOf(typeof(IRequestHandler<,>))))
    {
        containerBuilder.RegisterType(handlerType);
        var registerAsInterfaceType = handlerType.GetInterfaces().Single(t => t.GetGenericTypeDefinition() == typeof(IRequestHandler<,>));
        containerBuilder.Register(c =>
        {
            var handler = c.Resolve(handlerType);
            handler = ConfigureAuthorizationHandler(c, handlerType, registerAsInterfaceType, handler);
            handler = ConfigureTransactionalHandler(c, handlerType, registerAsInterfaceType, handler);
            return handler;
        }).As(registerAsInterfaceType);
    }
 
}
 
private static object ConfigureTransactionalHandler(IComponentContext c, Type handlerType, Type registerAsInterfaceType, object handler)
{
    if (!handlerType.GetCustomAttributes(typeof(NotTransactionalAttribute), true).Any())
    {
        handler = c.Resolve(typeof(TransactionalCommandHandler<,>).MakeGenericType(registerAsInterfaceType.GetGenericArguments()),
            new TypedParameter(registerAsInterfaceType, handler));
    }
 
    return handler;
}
 
private static object ConfigureAuthorizationHandler(IComponentContext c, Type handlerType, Type registerAsInterfaceType, object handler)
{
    var authorizeAttr = (AuthorizeUserAttribute)handlerType.GetCustomAttributes(typeof(AuthorizeUserAttribute), true).SingleOrDefault();
    if (handlerType.GetCustomAttributes(typeof(AuthorizeUserAttribute), true).Any())
    {
        var parameters = new List<Parameter>{
            new TypedParameter(registerAsInterfaceType, handler),
            new PositionalParameter(1, authorizeAttr.ClaimType),
            new PositionalParameter(2, authorizeAttr.ClaimValue)
        };                
        handler = c.Resolve(typeof(AuthorizedUserCommandHandler<,>).MakeGenericType(registerAsInterfaceType.GetGenericArguments()), parameters);
    }
 
    return handler;
}

And we’re done!

Cocoa Programming for Mac OS X (Ch 19-21)

After a little Cocoa break I’m back, while continuing through the book I seemed to have forgotten some stuff already, not good.

So, next up, Keyboard Events.

This chapter explains how the events are used for handling keystrokes as well as the first responder concept. The first responder being the active view element (button, text area,…) and there’s a whole mechanism working in the background when the first responder changes. Not a lot of ground breaking material here, probably the most important piece of code here is an example of how to code the fuzzy blue box around an active custom view.

Chapter 20, Drawing text with attributes.

Here we are taught how to show strings in various formats, not that interesting. One nice feature however is that all the drawing commands you write can be converted into PDF by the AppKit framework.

Chapter 21, Pasteboards and Nil-Targeted actions.

The clipboard in Windows, pasteboard in OS X. Different name, same concept, although I’ve never read about it in any .Net book I’ve seen but you know what it does :). What you need to remember from this chapter is that you can do a lazy paste. Meaning that you don’t have to put it in the clip errr pasteboard when the user presses the copy command. You can wait until he presses paste, very valuable if you’re working with large quantities of data.

Nil targeted actions are best explained with an example. You can set the selector (method signature for .net people) of a menu item to anything you want, say removeEmployee:, when the menu item’s target is nil and the menu item is invoked, it will traverse the responder tree until someone acts upon it.

Nothing fancy was covered in these past chapters, but you need to know about these things. I did spend quite some time on the applications, probably because there was a two week pause. For those interested I’ve attached all the source code.

As always, you can get the book here .

TypingTutor – Chapter 19.zip (46.44 kb)

TypingTutor – Chapter 20.zip (53.47 kb)

TypingTutor – Chapter 20 Challenge 1.zip (53.73 kb)

TypingTutor – Chapter 20 Challenge 2.zip (57.89 kb)

TypingTutor – Chapter 21.zip (53.58 kb)

TypingTutor – Chapter 21 Challenge 1.zip (53.75 kb)

RaiseMan – Chapter 21 Challenge 2.zip (111.20 kb)

Cocoa Programming for Mac OS X (Ch 17-18)

Euro 2008 and the challenge application on the end of chapter 18 have slowed me down, so only some notes about these two chapters this time.

Chapter 17, Custom Views.

This chapter deals about manipulating views (forms) manually. You can compare it with the .net System.Drawing namespace and subclassing the Control class to create your own controls. It also explains the alignment and docking of controls. Pretty basic stuff.

Chapter 18, Images and Mouse Events.

With the new knowledge on how to draw on views we now will allow the user to interact with the form and allow him to draw figures. This is done by handling mouse events. Also the file open dialog is introduced, but it’s called a NSOpenPanel here, to add images on the view.

The challenge application invites the reader to further customize the application, which draws rectangles when you complete the chapter, to draw ovals, adding undo redo capabilities and implementing archiving.

Most of the time I spend finding out how to hook up the document window to the custom view which handled the drawing of the ovals, as always key-value coding saved the day. You should also watch out that when a document is unarchived this is done before UI controls, I mean views :), are created. So don’t start assigning your saved ovals to a view that does not exist yet, like I did. It’ll save you time.

As always, you can get the book here .

ImageFun – Chapter 17.zip (44.46 kb)

ImageFun – Chapter 18.zip (46.78 kb)

TheOvalApp – Chapter 18 Challenge.zip (65.73 kb)

Cocoa Programming for Mac OS X (Ch 13-16)

I’ve been busy at work so haven’t made as much progress in the book as I wanted, the chapters I did cover however were great!

Chapter 13, User Defaults.

In chapter 12 a preference screen(panel) was introduced, a preference menu item is standard in a default application. In OS X preferences are automatically stored under ~Library/Preferences. To access them you can use the NSUserDefaults class which has a standardUserDefaults method and returns an NSMutableDictionary. When the application starts you need to enter your defaults in that dictionary and call the registerDefaults method. Any changes the user makes are persisted to the location stated above, just make sure whatever you put into it can serialize itself. In the rest of your application you can just read or set values in that dictionary it’s automatically saved.

In .Net you’d use user specific application settings which are stored in the app.config.

Chapter 14, Using Notifications.

Something which is definitely missing in the .Net framework is a Pub/Sub mechanism. There is one available in the EnterpriseLibrary and in Spring.Net but it’s great to see this in Cocoa. Every running application has an instance of NSNotificationCenter, an observer can ask to be notified of certain events, certain events of a certain object or all events of a certain object. A publisher will tell the NotificationCenter about the notification it wants to send. The NotificationCenter will look up the observers and call the method that was supplied when they subscribed. I just recently needed this in a very large application, having it at hand would certainly have saved time.

Chapter 15, Alert Panes.

In the .Net world the MessageBox.The only big difference here is that here they can be run modally, meaning no other windows will receive events until it is closed, or as a sheet, meaning it’s specific to a certain form.

Chapter 16, Localization.

Again this can be compared to the work you need to do in Visual Studio and .Net, the main difference here is that you can pretty easy extract the strings that need to be localized. This is probably possible in the .Net world too with some sort of plugin, but it’s always nice to see it build in, like the notifications.

I’m now half way through the book and can say that it’s a very pleasant one to read, you can get it here . I’ve also adjusted my view on Objective-C and Cocoa, while at first it seemed a bit rough and basic I’m beginning to see that it’s full featured language and framework with very advanced capabilities which don’t require a lot of code. Though the real challenge will be to build a real application after I’ve completed the book. I’m still staring at the screen sometimes wondering why I got three errors when there’s only a missing ) .

Oh yeah, thanks Lemmy for giving me a tilde over IM, I haven’t found that key on the keyboard yet :p.

RaiseMan – Chapter 13.zip (86.38 kb)

RaiseMan – Chapter 14.zip (87.29 kb)

RaiseMan – Chapter 15.zip (87.67 kb)

RaiseMan – Chapter 16.zip (111.13 kb)

Cocoa Programming for Mac OS X (Ch 9-12)

Read part one here, part two here and get the book here .

The plot thickens!

Chapter 9, NSUndoManager.

For those wondering what that NS is doing everywhere, it comes from NeXTSTEP more information about it here.

This chapter is all about adding undo / redo capabilities to your application and maybe it’s because the current sample application is, well, a sample, but it’s rather easy to add this capabilities to your program. Also you get it integrated with the menu bar at no extra cost, the window shows that there are changes, and the undo and redo buttons come to live. The underlying mechanism relies heavy upon Key-Value coding which was discussed in chapter 7 , again demonstrating it power.

- (void)insertObject:(Person *)p inEmployeesAtIndex:(int)index
{
    NSLog(@"adding %@ to %@", p, employees);
    NSUndoManager *undo = [self undoManager];
    [[undo prepareWithInvocationTarget:self] removeObjectFromEmployeesAtIndex:index];
    if(![undo isUndoing])
    {
        [undo setActionName:@"Insert Person"];
    }
    [self startObservingPerson:p];
    [employees insertObject:p atIndex:index];    
}

Chapter 10, Archiving.

The sample application now tracks changes and when you try to close an edited window it asks if it should save its changes. So the logical next chapter is about adding this capability.

In this chapter we learn that the notion of an interface in .Net actually also exists in Objective-C, but it’s called a protocol and unlike .Net and Java you can have optional methods in a protocol so any method marked optional does not need to be implemented.

Archiving is coupled with the NSCoding protocol and the abstract NSCoder class, most of the time you’ll be dealing with the abstracted class which hides the underlying mechanism. Implementing this can be compared to the implementation in .Net. Though it requires less code to write since your object graph is stored automatically in a file. You can configure the extension and the icon from within XCode, it was also nice to see that OS X had automatically associated the extension with my application.

#import <Foundation/Foundation.h>
 
@interface Person : NSObject <NSCoding>{
    NSString *personName;
    float expectedRaise;
}
 
@property (readwrite,copy) NSString *personName;
@property (readwrite) float expectedRaise;
 
@end
 
#import "Person.h"
 
@implementation Person
 
-(id)init
{
    [super init];
    expectedRaise = 5.0;
    personName = @"New Person";
    return self;
}
 
-(void)dealloc
{
    [personName release];
    [super dealloc];
}
 
@synthesize personName;
@synthesize expectedRaise;
 
- (void)setNilValueForKey:(NSString *)key
{
    if([key isEqual:@"expectedRaise"])
    {
        [self setExpectedRaise:0.0];
    }
    else
    {
        [super setNilValueForKey:key];
    }
}
 
- (void)encodeWithCoder:(NSCoder *)coder
{
    [coder encodeObject:personName forKey:@"personName"];
    [coder encodeFloat:expectedRaise forKey:@"expectedRaise"];
}
 
- (id)initWithCoder:(NSCoder *)coder
{
    [super init];
    personName = [[coder decodeObjectForKey:@"personName"] retain];
    expectedRaise = [coder decodeFloatForKey:@"expectedRaise"];
    return self;
}
 
@end

Chapter 11, Basic Core Data.

You thought it was good, well it just gets better. All the code we still had to write to add undo/redo, change tracking and archiving to our application can be done without writing any line as illustrated with this chapter. Again we see the power of Key-Value coding.

Chapter 12, Nib Files and NSWindowController.

Nib files contain the state of the window designed with interface builder, this chapter tells you how you can postpone loading a window/panel to save memory and resources. It also how you can load classes (this includes Windows, custom classes, etc.) by their name. Much like the Activator in .Net.

- (IBAction)showAboutPanel:(id)sender
{
    BOOL successful = [NSBundle loadNibNamed:@"About" owner:self];
    if(successful){
        NSLog(@"Loaded nib from NSBundle");
    }
    else{
        NSLog(@"Unable to load nib");
    }
}

RaiseMan – Chapter 9.zip (72.21 kb)

RaiseMan – Chapter 10.zip (74.18 kb)

CarLot – Chapter 11.zip (43.54 kb)

RaiseMan – Chapter 12.zip (85.23 kb)

Cocoa Programming for Mac OS X (Ch 6-8)

View Chapters (1-5) here, get the book here .

The title of chapter 6 “Helper Objects” did not sound good. Whenever I find classes with the words Helper or Util in their name, this usually indicates a “code smell” and most of time the underlying problem is a leaky domain model. Turns out something completely different is the subject of this chapter, delegates!

They can be compared with delegates in .Net though they are being used in a different way. I’ll illustrate with a sample.

The TableView UI component deals with displaying data like a table, compare this with the .Net grid. What it displays however is not part of his responsibility, this behaviour can be added though by using delegates. The tableView has a delegate member which you can set, if that object implements methods which map to delegate methods of the tableView they will be called, otherwise they won’t. This means that you don’t need to implement everything, just what you need.

I think in .Net this behaviour would be implemented by using interfaces. So if you had your own grid component, it’s datasource could be set to something of type IDatasource which would provide the necessary functionality that would be called by the grid component.

Overall this is off course a powerful feature, though implementing it requires attention, misspelling the method name means that your method won’t be called and you won’t get any errors. The author states that the best way is to look at the documentation and copy paste the method signatures in your code.

Chapter 7 “Key-Value Coding; Key-Value Observing”.

A short chapter, only 12 pages, but it seems to be a core concept. If you have an instance variable foo in class Bar, you can have other objects be notified of changes to it. This can be compared to the .Net INotifyPropertyChanged interface and its interweaving with databinding. Since the observers call the methods valueForKey: and setValue:forKey: you need to make sure your code follows the strict naming convention to get this functionality.

If you are changing the observed instance variable in methods you need to call the methods willChangeValueForKey: before changing it and didChangeValueForKey after you’ve changed it to alert the observers of the change. If you find that too much work just call the setter of the instance instead of changing it directly.

- (int)foo
{
    return foo; 
} 
 
- (void)setFoo(int) x
{
    foo =  x;
}

A handy shortcut to write a property is to use the @property and @synthesize which do all the work for you, the above code can thus be replaced by a simple

@property(readwrite) int foo;

in the header file and

@synthesize foo;

in the implementation.

Overall familiar material, I’ve seen this in .Net and it’s available to me in Objective-C excellent! There even is a valueForKeyPath: method that traverses the object tree i.e: spouse.scooter.modelName.

Chapter 8, NSArrayController.

In this chapter all you’ve seen so far comes back, but in a different way. In the previous chapter you had to write a lot of plumbing to get your list of objects to display and be editable. The NSArrayController however can help you on this, it allows user interface components be bound using chapter 7’s techniques. You can automatically add and delete objects, display them and edit them without writing code, just hook everything up.

To solve challenge 1 for this chapter edit the sortKey to be personName.length and selector to compare:. I’ve attached the code for those interested.

RaiseMan – Chapter 8.zip (69.85 kb)

KVCFun – Chapter 7.zip (53.38 kb)

SpeakLine – Chapter 6.zip (59.93 kb)

DelegateResize – Chapter 6 Challenge 1.zip (47.51 kb)

ToDoApplication – Chapter 6 Challenge 2.zip (57.66 kb)

Cocoa Programming for Mac OS X (Ch 1-5)

Earlier this week I purchased this book: Cocoa Programming for Mac OS X since I wanted to get an introduction on how to develop native applications for OS X. It’s the most recently published one on the issue and got mentioned on MacRumors.

In a series of small posts I’ll put down some notes for myself here and anyone who is interested can read along.

Chapter one gives you some background on the language, what tools will be used throughout the book and explains the different kinds of frameworks available in Cocoa. Nothing special here, I want to write code!?

And there’s chapter two, the author guides you through your first Objective-C program. The interface of XCode and Interface builder (IB) are explained. I was surprised to read that any method you write is public and every instance variable is protected. Also instance fields which are connected through the IB are called outlets and you designate them accordingly in your header file. Methods that can be used by user interface objects are called actions.

#import <Cocoa/Cocoa.h>
 
@interface Foo : NSObject 
{ 
    IBOutlet NSTextField *textField; 	
}  
 
- (IBAction)seed:(id)sender; 
 
- (IBAction)generate:(id)sender;

The – before the two method declarations indicate that it’s an instance method, class methods are designated with a +. The IBAction and IBOutlet are hints for the IB. NSObject is the base class for every other object. The id ‘type’ (don’t know if I am allowed to call it that way) is a pointer to basically anything.

Chapter three digs a little deeper on objects and classes. Calling methods on objects looks a bit different if you come from a Java or C# background.

MyClass* myInstance = [[MyClass alloc] init]; 
 
[myInstance doStuff]; 
 
[myInstance doStuffWith:bar];  
 
[myInstance doStuffWith:bar using:foo];

The first line first calls the constructor and init method. Both are inherited from NSObject and on the second line I call the doStuff method on myInstance. It takes some getting used to, also note the naming convention if you’re a .Net programmer methods start with a capital. Method names are also called selectors. On the third line I assume I’ve an other object called bar and it illustrates how you pass parameters with method calls. Finally the last line illustrated how multiple arguments are passed along.

I raised an eyebrow when I read that if you call a method of on objects which points to nil (null), no exception will be raised. Sure, it allows you to omit those tedious if(!= null) checks but I’ll probably pull out my hair when I’m writing more real life application and it’s not responding the way it should.

One final note for this chapter, calling methods of your base type is done in the Objective-C world by using the super keyword.

Chapter four talks about memory management. This was fairly new for me, I knew about it but I’ve only written programs in .Net (C#, Vb.Net, managed C++) or J2EE (Java) and both environments come with the garbage collector (GC) which manages memory for you. Mac OSX 10.5 introduced the GC as well, but it’s an option. If you turn it on your application will only run on 10.5 and later, so if you want to target previous versions you’ll have to release and retain yourself.

It was an interesting read, I never had seen an example of how memory can be managed in code you write. I’ll probably just turn the GC on for stuff I write. The chapter ends with stating that you should now have a basic understanding of Objective-C and Cocoa and that the next chapters will focus on the different frameworks you can use to build your applications.

Chapter five introduces some user interface components available in the IB (buttons, textboxes,…), nothing big here although I encourage you to write the challenge application. Challenges in the book are exercises which you should be able to write.

Attached you find the challenge exercise from chapter five (countline), the guided application (speakline) also from chapter five and the lottery application from chapter three and four.

CountLine.zip (55.52 kb)

lottery.zip (16.43 kb)

SpeakLine.zip (52.62 kb)

Also I apologize for the layout of the code in this post I’ll fix that as soon as I can, Objective-C isn’t supported by default 🙂 .