Jonathan Birkholz

ISubscribe

I believe Jimmy Bogard has a similar technique (IHandler) with ASP .Net MVC but I thought I would still share the convention I’ve been using to wire up subscriptions to the Prism Event Aggregator.

Whenever an object is built with StructureMap, it goes through all the TypeInterceptors. I have a SubscriptionTypeInterceptor:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class SubscriptionInterceptor : TypeInterceptor
{
public object Process(object target, IContext context)
{
var eventAggregator = context.GetInstance<IEventAggregator>();
// Get interface ISubscribe<E>
var interfaces = target.GetType().GetInterfaces().Where(i => i.Name.Contains("ISubscribe"));
foreach (var type in interfaces)
{
// typeof(E)
var eventType = type.GetGenericArguments()[0];
var setupMethod = GetType().GetMethod("Setup");
setupMethod.MakeGenericMethod(eventType).Invoke(this, new[] { target, eventAggregator });
}
return target;
}
public bool MatchesType(Type type)
{
return type.ImplementsInterfaceTemplate(typeof(ISubscribe<>));
}
public void Setup<T>(ISubscribe<T> subscriber, IEventAggregator eventAggregator)
{
eventAggregator
.GetEvent<CompositePresentationEvent<T>>()
.Subscribe(subscriber.Subscribe);
}
}

So it finds all the ISubscribe interfaces the target implements and then subscribes the target to the event T in the event aggregator.

1
2
3
4
public interface ISubscribe<E>
{
void Subscribe(E e);
}

A simple example of usage:

1
2
3
4
5
6
7
8
public class SecurityController : IController,
ISubscribe<RequestUserLoginEvent>
{
public void Subscribe(RequestUserLoginEvent e)
{
Publish.Event().ShowModal<IRequestUserLoginViewModel>();
}
}

View + ViewModel + ViewRegistry

In preparation for the Advanced WPF Workshop on Saturday Feb 20th, I thought I would throw together some blog posts around some techniques / code I will be sharing. JP asked the other day whether Views should have references to their ViewModels or should ViewModels have references to Views. Unfortunately twitter is a great medium for asking this question but not the best medium for answering the question.

I am going to try using the dry marker board as a form of communication with my blogs. I have little patience for lining up pretty lines and colored boxes with Visio or Power Point. A dry marker board is fast and allows for a free flowing expression of my ideas.

Let me try to diagram out how I currently manage my Views and ViewModels.

  1. We ask the StructureMap container for the ViewModel
  2. The VM instance is intercepted by a ViewModelTypeInterceptor
  3. Inside the VMTypeInterceptor
    1. Get the V for out VM from the container
    2. Get the ViewRegistry from the container
    3. Register the V with the VM in the ViewRegistry
    4. Return the VM
  4. And finally our VM is returned being registered with a V in the ViewRegistry

In short my ViewModel has no reference to my View, my View has no reference to my ViewModel (beyond setting the DataContext), and my View Registry registers the mappings between View and ViewModel.

The best code to look for this is in the ViewModelInterceptor:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class ViewModelInterceptor : TypeInterceptor
{
public object Process(object target, IContext context)
{
var name = target.GetType().Name;
var view = context.GetInstance<IView>(name);
context.GetInstance<IViewRegistry>()
.RegisterViewWith(target as IViewModel, view);
return target;
}
public bool MatchesType(Type type)
{
return type.CanBeCastTo(typeof (IViewModel));
}
}

Advanced WPF Workshop

On February 20th from 9 am (central) until we get bored… I guess 1pm, we will be having a free Advanced WPF Workshop here at EPS.

Let me emphasize ….

FREE!!!!!!

When : Feb 20th 9am - 1pm+

Where : EPS Office

6605 Cypresswood Dr, Suite 300 Spring, TX 77379

And online at : https://www2.gotomeeting.com/register/902909498

There will be lunch which at the moment is BBQ, but I might change my mind. ;)

Currently the agenda looks like:

  • INotifyPropertyChange
    • Normal
    • Type Safe
    • Dynamic Proxy
    • AOP
  • View & ViewModel
    • Typical methods
    • IView extensions
    • IView
    • ViewRegistry
    • Also will be covering StructureMap conventions (TypeScanners) and Type Interceptors
  • Event Aggregator
    • using Events
    • Publish extension method
    • ISubscribe
    • Putting it all together with a Region Controller
  • Commands
    • ICommand
    • Action / Delegate Command
    • Decorating with a Named Command
    • might be using commands with a convention
  • Resource Locator
    • Resource Dictionary Convention
    • Image Convention
  • And anything else that comes up during our discussions
  • Potential additions:
    • Paul Stovell’s MicroModel
    • Dependency Property Inheritance
    • Attached Dep Property Behaviors
    • Blend Behaviors
    • Visual State Manager

We will be recording the session so have no fear if you can’t come or join us online.

I am very excited about the workshop! Its a great opportunity to share some stuff I’ve been doing with WPF. User groups and brown bags offer only limited exposure to these techniques. With this workshop we get to dive into code and get rapid interactions. I hope to see you there.

The Goal

With my current mindset that things are broken, I dive into my current readings including The Goal and The Toyota Way.

The Goal: A Process of Ongoing Improvement

I read The Goal back in my business graduate school days (about 5 years ago), but now its reading has a whole new impact. I am seeing more into the book after 5 years of working in software than I did as a fresh college graduate. Some of the mental exercises the protagonist in the book is going through I am going through as well. As he wrestles answering questions concerning his factory, I am wrestling with the questions concerning my software projects.

The first exercise is to define ‘the goal’ for his company and all companies. Of course the protagonist takes a long time to come to the logical conclusion that it’s to make money.

Every company’s goal is to make money.

As a software consulting company, how do we make money?

We make money by winning a bid for a project and then performing the work to complete the project within budget.

That seems pretty simple. Nothing about data access technologies, TDD, user stories, or any sort of architecture or design pattern.

If you need X done and will pay $Y then we should do X for less than $Y.

Why is it so hard to deliver on that?

  1. Define X
  2. Estimate Y
  3. …something
  4. Profit!

If we scope a project then we need to know what X is. Simple to say, but man is it difficult to capture!

X is always in motion, a moving target. The client changes their mind, we have scope creep, and what appears simple always ends up being more complex. We all know this! Its the one constant with software development. Things are going to change.

From my perspective, SOLID and design patterns focus on writing code that is more adaptive to change.

SOLID and design patterns in of themselves do NOT move us towards our goal by reducing the cost of writing software.

SOLID and design patterns move us towards our goal when our software has to change because the cost of the change has been reduced.

The principles and patterns also provide a common language for developers. That common language moves us closer to the goal because current and new developers can grok more of the design in less time. And time = money.

Where does testing fit into all this?

Testing allows us to keep track of the quality of our production. Or.. does it? After some re-examination I want to say testing adds no quality. That will have to be another post.

Testing provides a way to measure our progress towards X. We know we are moving towards X because we can have tests that verify we are delivering towards our promise. When I mention testing I am using a broad definition and including all sorts of tests from UAT testers to automated unit tests.

So what does Test Driven Development (TDD) provide? TDD focuses every bit of code towards satisfying a test. If every test is relevant towards progress towards X, then TDD focuses our development towards productive work. Logically any work not moving us towards delivering X to our clients is unproductive work.

What conclusions have I come to?

The goal of a software consulting company is to make money. We make money by completing X under $Y. One of the important steps is to then define what X is. We know X will change so we should write code that is adaptive to change, but we need to balance that with only writing code that moves us towards delivering X.

  • We achieve more flexible and understandable code by using SOLID and design patterns.
  • We measure our progress towards X by passing tests.
  • TDD focuses our coding towards productive work.

I started to write about estimation in this section but have decided to move it to another post.

After thinking about estimation, it has nothing to do with knowing what X is. Estimation has to do with what we think $Y is. X is what X is regardless if it takes you 3 hours or 3 months to deliver.

Jaded .Net

I love talking with Ryan and others passionate about new technology and languages. Lately though I have been increasingly jaded with anything ‘new’.

How many different data technologies do we need? ADO .Net, Nhibernate, Linq-2-SQL, Entity Framework version.. whatever. We have been connecting to databases for over 20 years so why are we still worrying about this?!

The sheer number of UI frameworks is reaching the point of ridiculousness. I was reading the WPF Disciples Google Group and ran across this post. Paul Stovell listed all the MVVM, MVC, MVC frameworks he knew of (around 11). Then everyone was commenting with their own ‘me too’ response.

Am I the only one who finds that utterly hilarious? How many frameworks do we need?!

Ryan is extremely involved with Ruby, Python, F#, and the other ‘new’ languages to the .Net Framework. I have been delaying learning Ruby for too long, because it’s hard to get motivated to learn a new language. I see the potential and the possibilities, but I quickly get discouraged and uninterested.

I have to ask myself… why am I jaded? Why am I disinterested in things that used to excite me?

The more I thought about it, the more the conclusion became crystal clear. Every project I have been a part of has had the same problems. None of the problems were technology related.

Why would I get excited about a solution to a problem I don’t have?

Reminds me of Karl Pilkington’s comment about this picture of twins on one of the Ricky Gervais podcasts. Karl saw a picture of a set of twins on an office desk (obviously the kids of the guy sitting at the desk). His great idea was since they look alike and are dressed alike, the parent could just have the picture of one of them and save space. Ricky Gervais then commented something like :

What you have there is the best non-solution to a problem that doesn’t exist.

And that is pretty much how I feel about most of the technological innovations these days.

For example: can someone explain to me how Oslo is going to help me? I am also not sold on RIA or anything Cloud related. The technology is interesting, but I can’t justify where I would use any of this stuff.

Sometimes I feel like a lone engineer shoveling coal into a furnace on a runaway train. I don’t know where we are going, where we have been, and all I hear is FASTER, FASTER!

When I scream for help, I get delivered a better shovel.

I don’t want a better shovel, I want to know why I am shoveling so much coal!!!

Can’t we do more with less? Can’t we slow down? Do we even know why we are in this train?!

Lately the murmurings on different blogs, podcasts, and developers has been that software development has gotten too complicated. How can that be true when we have tons of tools and frameworks that should make life easier? jQuery makes Javascript easier. Pick your favorite Data Access tool / ORM makes data access easier. Any number of UI frameworks makes UI construction easier. So why do we think things are more complicated? Shouldn’t our life be easier?

The majority of projects are always behind, always over budgeted, and always unclear on where they are and where they are going. This has been my experience spanning multiple companies and multiple positions on different teams. I am fully humble enough to recognize that “I” might be the problem, but I doubt it. There is enough shared pain through my conversations with other developers to recognize its a industry wide problem.

The only project I was a part of that didn’t feel this way had a full time Project Manager and a team full of very skilled developers. To me it didn’t feel like the project was better run, it was just we had enough skilled team members to overcome any poor execution or poor planning. That isn’t saying our PM wasn’t an all star because he was. My point is that although the project was a ‘success’ I didn’t feel like it was successful because we had a great methodology. We just powered through any complications.

Every project (including that last ‘successful’ one) always had mad dashes of insane hours of work followed by listless lulls as we waited for one thing or another. I never felt I had enough time to do my work and other activities related to work (ie blog, present, create frameworks)

Where am I going with this? I wanted to capture my state of mind and why I am re-examining how and why I develop.

The status quo will burn me out.

The ole definition of insanity : Doing the same thing over and over again expecting different results.

I am tired of doing the same thing, so what can I do different? Why is there this constant pain? I know there are solutions and it’s time for me to document my mental journey as I search for answers. Maybe my breadcrumbs will help those that follow.

Examining How We Develop Software

What I am starting is a mental exercise exploring how my view on software development is changing. Since this is a basically a brain dump, treat it as such. Feel free to comment on what I say… offer advice and opinions. Maybe there is something you can sympathize with.

What has started me thinking along these lines has been my recent readings of The Toyota Way and my re-reading of The Goal.

The Toyota Way

The Goal: A Process of Ongoing Improvement

Both readings have me re-examining my career and software development. Asking questions like, Are we focused on the right things?

Anyway here are the posts:

  • Jaded .Net
  • The Goal
  • Estimating the Impossible

Named Command Decorator

Here is the problem, we have a list of ‘commands’ we wish to show depending on what view model / entity is active. If we just had a collection of ICommands, we could show buttons but what would their content be?

My solution is to use the decorator pattern to decorate commands with a Name that can be used as the content for the buttons.

My decorator looks like :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class NamedCommand : ICommand
{
public NamedCommand(ICommand decoratedCommand, string name)
{
_DecoratedCommand = decoratedCommand;
Name = name;
}
readonly ICommand _DecoratedCommand;
public string Name { get; set; }
public void Execute(object parameter)
{
_DecoratedCommand.Execute(parameter);
}
public bool CanExecute(object parameter)
{
return _DecoratedCommand.CanExecute(parameter);
}
public event EventHandler CanExecuteChanged;
}

I then created an extension method on ICommand :

1
2
3
4
public static ICommand Name(this ICommand command, string name)
{
return new NamedCommand(command, name);
}

So in the code I can now do:

1
Commands.Add(new ActionCommand(OnOpen).Name("Open"));

For my WPF visual, I have a DataTemplate :

1
2
3
4
<DataTemplate DataType="{x:Type Commands:NamedCommand}" >
<Button Content="{Binding Name}"
Command="{Binding }" />
</DataTemplate>

Aop INotifyPropertyChanged StructureMap

Anyone who has worked with INotifyPropertyChanged knows that this simple interface can be a royal pain in the ass.

To try and eliminate the pain, people have created some great solutions using AOP : IL weaving (PostSharp) and using a proxy (Castle Dynamic Proxy).

PostSharp has a little too much voodoo for me atm. I think I will warm up to it though and re-examine using PostSharp on my next solution. But for now, I wanted to use Castle Project’s Dynamic Proxy.

Naturally since Castle also has a very popular IoC container in Windsor, most examples marry Dynamic Proxy and Windsor to form an AOP INotifyPropertyChanged solution.

Since I am using StructureMap for this project, I endeavored to create my own solution using Dynamic Proxy.

My first attempt I shared at the Virtual Brown Bag look liked it worked but in reality I was constructing my objects twice.

Once with SM and once with the Proxy generator.

I had to go back to the drawing board and posted my problem at the SM google group. http://groups.google.com/group/structuremap-users/browse_thread/thread/1a6b19ce8152db1b?hl=en

I believe the syntax given to me was an older version of SM. For the record, I am using version 2.5.3.0

But it did direct me to the general idea on where I should start looking. I ended up needing to create an IBuildInterceptor.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class MyBuildInterceptor : IBuildInterceptor
{
public MyBuildInterceptor(Type concreteType)
{
_ConcreteType = concreteType;
}
readonly Type _ConcreteType;
public object Build(BuildSession buildSession, Type pluginType, Instance instance)
{
var constructorArgs = _ConcreteType
.GetConstructors()
.FirstOrDefault()
.GetParameters()
.Select(p => buildSession.CreateInstance(p.ParameterType))
.ToArray();
var interceptors = new List<IInterceptor>
{
new NotifyInterceptor()
}
.ToArray();
return new ProxyGenerator().CreateClassProxy(_ConcreteType, interceptors, constructorArgs);
}
public IBuildPolicy Clone()
{
return InnerPolicy.Clone();
}
public void EjectAll()
{
InnerPolicy.EjectAll();
}
public IBuildPolicy InnerPolicy { get; set; }
}

To register my ViewModels I created a convention using a TypeScanner

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class MyNotifyConvention : ITypeScanner
{
public void Process(Type type, PluginGraph graph)
{
if (type.GetInterface("IViewModel") == null)
return;
var interfaceType = type.GetInterfaces().FirstOrDefault(i => i.Name.Contains("ViewModel")
&& i.Name != "IViewModel");
if (interfaceType == null)
return;
graph.Configure(r =>
r.ForRequestedType(interfaceType)
.InterceptConstructionWith(new MyBuildInterceptor(type))
.TheDefaultIsConcreteType(type));
}
}

I then used a Dynamic Proxy Interceptor that I basically copy and pasted from Serial Seb’s example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class NotifyInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
// let the original call go through first, so we can notify *after*
invocation.Proceed();
if (invocation.Method.Name.StartsWith("set_"))
{
string propertyName = invocation.Method.Name.Substring(4);
RaisePropertyChangedEvent(invocation, propertyName, invocation.TargetType);
}
}
void RaisePropertyChangedEvent(IInvocation invocation, string propertyName, Type type)
{
// get the field storing the delegate list that are stored by the event.
var methodInfo = type.GetMethod("RaisePropertyChanged");
if (methodInfo == null)
{
if (type.BaseType != null)
RaisePropertyChangedEvent(invocation, propertyName, type.BaseType);
}
else // info != null
{
methodInfo.Invoke(invocation.InvocationTarget, new object[] {propertyName});
}
}
}

Instead of looking for the PropertyChanged Handler, I create a RaisePropertyChanged method and use that. Although I could raise the event using the field method Seb was using, WPF wasn’t updating the binding. I didn’t really bother to investigate and just rolled with this solution.

So that’s my solution and I’ll start using it in my current solution. Naturally I will clean up the code some more etc. Feel free to use this for any of your own projects. You can also get the solution at my GitHub:

http://github.com/RookieOne/StructureMapAopNotify

London Time?

A friend ping’d me on gchat and asked if he had a DateTime object with our time in Texas, how could he get the time in London.

I quickly threw together this example on how I would do it.

1
2
3
4
5
6
7
8
9
10
11
12
DateTime time = DateTime.Now;
TimeZoneInfo londonTimeZone = TimeZoneInfo
.GetSystemTimeZones()
.FirstOrDefault(t => t.DisplayName.Contains("London"));
DateTime londonTime = TimeZoneInfo.ConvertTime(time, londonTimeZone);
Console.WriteLine("Its {0} here", time);
Console.WriteLine("But its {0} in London", londonTime);
Console.WriteLine("Blimey!");
Console.ReadLine();