Feb 19, 2013

Online training from DevelopMentor

Just wanted to post a quick note to introduce a compelling new product from the team at DevelopMentor. I have been teaching with DM for a while now and have been and have been working with them to bring the future of training to the web. Learning Line is the new online training platform from DevelopMentor. Michael Kennedy did a great introduction to the system. I have authored a good portion of the WPF content (and more will be coming online in the future) and will be teaching some of the WPF classes that are upcoming. Check it out and let us know what you think.

Labels: , , ,

Jun 26, 2012

So Cal Code Camp Materials

Sorry to those who tried to make it to my ninja talk in the morning. I was stuck in the wonderful state of Minnesota waiting for a flight home and just couldn’t make it back in time for the session. As it was I barely made my 4pm session.

For those in my cloud session here are a collection of links and a PDF of my notes that I used for the talk.

Laser Sharks: http://www.facebook.com/photo.php?v=10150853722681956

We didn’t get to see these other two videos but they are still very cool to watch

In depth about MSFT data center technology: http://www.youtube.com/watch?v=hOxA1l1pQIw&feature=youtu.be

Video from PDC showing off the Azure hardware container system: http://blog.syntaxc4.net/post/2011/02/08/A-Walk-Through-of-a-Windows-Azure-Data-Center.aspx

Here is the Keynote talk from Scott Guthrie at the meet azure event where they announced all the new Azure features that we talked about: http://www.meetwindowsazure.com/Conversations#ScottGuthrieMeet

PDF of my notes: http://files.bradcunningham.net/PDFs/StopHostingYourOwnWebsites.pdf

Thanks again for coming and hope you learned at least one thing new.

Labels: , , ,

Apr 26, 2012

Ruby for the C# developer–Open Classes & method_missing

In the last post we covered the basics of the Ruby language from a C# developers perspective. We left off with a short discussion about one major fundamental difference between Ruby and C#: Mutable Types

In this post I wanted to cover the subject in a bit more depth and explain what Open classes are and what the method_missing method is used for.

Open classes means you can change the definition of any class at any time. Usually this would be done to add behavior to a class. Notice I am saying class here not object. In the classic cookie and cookie cutter example you think of a class as the cookie cutter and the object as the cookie (the instance that the cookie cutter just stamped out). Now you can see why this idea is very foreign to a C# developer. It means classes can be extending at any time. This sounds a bit like extension methods but you will see as we dig deeper that there is more to it in Ruby.

Let’s first look at an example in Ruby:

class String
def blank?
self.size == 0
end
end


This is adding the method named “blank” which returns a boolean to the String class in Ruby. Now that is almost exactly like an extension method. We could get the same behavior in C# like this:



public static class StringExtensions
{
public static Boolean Blank(this string value)
{
return String.IsNullOrEmpty(value);
}
}


But there is another way to add behavior to a class in Ruby. This is via the method_missing method. Since all method calls in Ruby are really just messages there is a chance that a particular object won’t be able to handle the message it is given. In these cases Ruby will call a special “debugging method” if it cannot find a method with the specified name.



What does this mean for you? It means that you have a hook to handle any unknown method that gets called on your object at runtime. This is really cool but may not be totally clear without an example. The 7 Languages in 7 weeks book does about the best example I could think of so I will shamelessly steal that one to illustrate the point.



class Roman
def self.method_missing name, *args
roman = name.to_s
roman.gsub("IV","IIII")
roman.gsub("IX","VIIII")
roman.gsub("XL","XXXX")
roman.gsub("XC","LXXXX")

(roman.count("I") +
roman.count("V") * 5 +
roman.count("X") * 10 +
roman.count("L") * 50 +
roman.count("C") * 100)
end
end


Ok so what the heck is this thing doing? First it is defining the method_missing method on a class called Roman. It is then doing logic in the method_missing method to handle the name of the method that the user tried to call. Let’s look at what the call site would look like



puts Roman.X
puts Roman.XC


Now maybe it makes more sense. You can see someone tried to call a method named “X” on the Roman class. Instead of defining each permutation of possible Romans numerals as their own method we can simple catch the method_missing method and then do string based logic to figure out the method name and convert that to the correct integer value. Make sense? This is a core feature of Ruby and a very valuable concept to understand.



This is part of a larger series of posts inspired by the 7 languages in 7 weeks book. Use the7LangIn7Weeks tag to find the other related posts

Labels: , ,

Apr 4, 2012

Ruby for the C# developer–The Basics

I have been reading 7 languages in 7 weeks recently and I decided to to start a series of posts that focusing on learning the languages discussed in the book from the point of view of a C# / .NET developer.

So let’s get started. First we are going to start with Ruby. This is the one language in the book that I already had some familiarity with. I have read Design Patterns in Ruby by Russ Olsen and The Well Grounded Rubyist by David A Black. Both are really good books that focus more on the Ruby the language and less on Ruby in the context of Rails.

So let’s talk about the basics of the Ruby language.

Type System

Ruby has a strong dynamic type system. This means a few things

  1. You will receive an error if types collide. (This is the “strong” part)
  2. You will get this error at runtime not at compile time (This is the “dynamic” part)

Let’s look at some code examples of this. First C#

int foo = 10 + "bar";

In C# this results in a compile time error:



Now the same thing in Ruby


foo = 10 + “bar”

Since Ruby does type checking at runtime this will not cause any errors until you try to call it. Then you will receive the following error (also notice the lack of type information to the left of foo):



Classes


Ruby is an object oriented language with a single inheritance model like C#.


Let’s define a class in each language. First C#


public class Foo
{
public int Bar { get; set; }
public Foo()
{
Bar = 10;
}
}

This is a simple C# class that defines one public read / write property called Bar and has a constructor that sets Bar = 10. And now the same thing in Ruby


class Foo
attr_accessor :bar

def initialize()
@bar = 10
end
end

This is the same as the C# class above. The initialize method is the constructor for this class. The attr_accessor keyword defines a read / write property called bar (as opposed to att_reader which is a read only property). In the initialize method you see we reference the bar variable with an @ sign. This is the syntax for referencing instance variables in Ruby.


Interfaces vs Modules


Both Ruby and C# are single inheritance languages. To propagate non-similar behaviors to classes C# uses Interfaces whereas Ruby uses “mixin’s” via the module keyword.


Let’s first look at an Interface in C#


public interface IBaz
{
void DoSomething();
}

Here we define an interface called IBaz that defines one method DoSomething(). If we want to make sure our Foo class implements this “behavior” in C# we make Foo implement IBaz. This ensures that our object satisfies the IBaz contract (meaning we can call DoSomething() on an instance of foo)


public class Foo: IBaz
{
public int Bar { get; set; }
public Foo()
{
Bar = 10;
}

public void DoSomething()
{
//elided
}
}

Now lets look at how this is done in Ruby via “mixin’s”. First lets define our “mixin”


module IBaz
def do_something
#elided
end
end

Notice the subtle difference here? In the C# version we were simply defining a contract which our class must implement itself. In Ruby the implementation actually lives in the module (I named the module IBaz to keep with the C# example but that isn’t a Ruby naming convention).


And then to make sure our Ruby class can call the IBaz DoSomething we need to “include” it like this:


class Foo
include IBaz
attr_accessor :bar

def initialize()
@bar = 10
end
end

There is a key fundamental concept happening here. Modules can implement behaviors directly in Ruby. This means that a given type doesn’t implement “included” behaviors natively.


Duck Typing and Mutable Types


This is simply a fundamental difference between C# and Ruby. Many thanks to Arne for working through these thoughts with me.


Types in Ruby are mutable, even at runtime. This means that method dispatch cannot be resolved at compile time. This means that method dispatch is resolved at call time.


Call time method dispatch might sound similar to how the dynamic keyword works in C#. However, in Ruby there is a difference to be aware of.


The “method call” is simply a message that is sent to a given type instance. That message is then sent up the type hierarchy to see if there is any thing that can handle the message. This process involves looking at native methods on the type, “included” methods from mixins and checking the method_missing method.


In C# by using the dynamic type you can get past compile time checking of method call sites. However, at runtime if the object doesn’t contain the called method in it’s inheritance hierarchy the call will fail. In Ruby there is a language construct called method_missing that allows you to hook an unknown method call and do something with it.


This is where we will pick up in the next post. Open classes and the method_missing method


This is part of a larger series of posts inspired by the 7 languages in 7 weeks book. Use the 7LangIn7Weeks tag to find the other related posts

Labels: , ,

Mar 27, 2012

Courier updates

I have found myself with a bit of free time on my hands the past few weeks as I get my consulting business up and running (http://www.bradcunningham.net). When I am not focusing on the consulting side of things I have spent some time updating a few of my projects.

Courier has benefitted from this free time I have found. I have released version 2.0 to codeplex with support for Windows Phone 7.1 Mango (WP7). I have also put a slew of other minor fixes in place and updated the binaries and the xml documentation files. You can download the 2.0 release direct from codeplex

Or, if you want to be super fresh you can:

Install-Package Courier

from the NuGet Console. It was actually surprisingly easy to get courier on NuGet. So check out the new release and let me know what you think. I have a few more things in the works for Courier in the near future so keep an eye out for updates. I will keep the NuGet package update as well with any new releases.

Labels: , ,

Jun 25, 2011

So Cal Code Camp Materials

Thanks to everyone who came out to my sessions at code camp. Below are links to all the materials for my different sessions.

Blend 101
Notes
Source Code

Tips to become a better ninja
Notes

.NET Running on Linux
Notes

I couldn't export the VM image cleanly so you will have build it yourself but it is pretty straight forward to do.

I use Virtual Box and use a CentOS 5.5 guest image. You can get the CentOS ISO's here

My steps will work on any VM software with any red hat like linux distro.

Once you have the virtual machine up and running refer to the document to get mono installed.


I hope you enjoyed it. If you could take a moment and rate my sessions on speaker rate I would appreciate it. I always want to get better at giving these sessions so any feedback you have is welcome.

SpeakerRate for Blend

SpeakerRate for Ninja Talk

SpeakerRate for Mono Talk

Jun 21, 2011

Code from SD UI Developers meeting

Thanks to all those that came out tonight to the SD UI Developers meeting. Below is a link to the project we built in Blend.

Source Code


If you have any problems with the samples or have any questions please post a comment


If you are interested in the Tech Immersion group you can get all the details here.

http://www.sdtig.com

Labels: , ,

Nov 8, 2010

November Nerd Dinner

Just a quick note. The November nerd dinner is this Thursday (November 11th) at 6pm. Once again I moved the location, I am still trying to find the ideal spot that can accommodate people from both ends of county, has enough parking, and is easy to get to off the freeway.  For this month we are meeting near the Champagne Bakery in Del Mar, 12955 El Camino Real San Diego, CA 92130, USA (Map). There are a couple other food choices in the same center as well if you would like something else.

This will probably be the last Nerd Dinner this year since we are getting into the holiday season and it will be difficult to schedule one over the next few months.

If you are in the area feel free to come by and nerd out with us. Everyone is welcome and it is FREE! 

If you are planning on attending please RSVP with the nerd dinner site: http://nerddinner.com/3621. It helps me to gauge how many people will be attending so I can secure enough seating.

Hope to see you there.

Labels:

Aug 20, 2010

What I learned at Nerd Dinner

1. Nerd dinner organizers like to wear orange shirts (strange)

2. K Scott is actually awake during Herding Code podcasts despite the evidence to the contrary.

3. Paul just released a neat 3D iPhone game. Peril Canyon

4. When pair programming the key is gain the trust of the person you are pairing with, otherwise you are fighting a losing battle. To chemically induce trust you can use Oxytocin apparently. Thank you Llewellyn

5. Web Metrics is doing some really interesting things with web site testing / monitoring and load testing. Particularly around cloud based (EC2 I believe) load testing.

6. Agile Open sounds like a killer “conference.” September 13-14 at UC Irvine.

7. Lynn and Llewellyn and putting together a “Code Retreat” event at the Hive in downtown SD on September 19th. It should be a great way to learn new languages and experience pair programming.

8. Startup Weekend San Diego is this weekend. Thanks again to John for putting on the dinner and buying beer. You can catch him and his company Twillio at the Startup weekend

9. The Ignite Talk from the recent San Diego Ignite event titled “Your Chair Is Killing You” by Ernesto Ramirez was actually impactful enough to make some stand more this week instead of sitting while working. I am very interested to hear this talk. I can’t find a link to it online. If anybody has one please leave a comment and I will update.

10. The Mono project farther along then I thought. Getting close to .NET 4.0 parity. Thanks Arne

I am sure there is more things I have already forgotten or just simply missed. There were a few groups of people I didn’t get the chance to talk with. Hopefully everyone can make it out to next months nerd dinner. Stay tuned for an update on the date and location (I will blog the details when they are finalized or you can follow me on twitter to get updates)

If anyone has other interesting things they heard about at the dinner please do leave a comment.

Labels:

Jun 2, 2010

Nerd Dinner Part II

We had a lot fun doing the first event and we all wanted to do it on a monthly basis. So here is part two (Revenge of the Nerds part II if you will).

Same place and same time as last month. I am still thinking about switching up the location (somewhere with alcohol seems to be a preference) but for now I will keep it at the same location.  If the location changes I will post an update so everyone is aware.

http://www.nerddinner.com/2379 

Feel free to bring friends and colleagues that you think would be interested. To find out about what we talked about before see the other posts under the Nerd Dinner category on my blog.

Hope to see you there.

Labels:

May 14, 2010

Nerd Dinner was a hit!

A big thanks to the people who came out to the inaugural San Diego Nerd Dinner event. We had a great time and chatted about a really diverse set of topics from the rock and roll school in Vista  to DVCS systems like Git and mercurial.

I am going to keep these events going on a monthly basis so please feel free to come to one in the future and bring anyone who might be interested along. I will post and update when the next event is planned.

There was so much content covered at this first one that I wanted to post a quick list of links to the things we chatted about (mainly for my own knowledge). I am sure I missed some things and this is only a condensed slice of what we discussed.

First (and really most importantly):

Kimchi HotDogs

IoC Stuff

Unity OR MEF or Unity AND MEF?
Autofac now in Mindtouch

Parallel / Async stuff

Reactive Extensions (Rx)
ThreadPool in .NET 3.5 sucks but not in .NET 4.0?
IsAsync for WPF bindings rocks

Database / NoSQL stuff

Good uses for Key / Value stores like mongo or Firkin?
When is a relational data store (SQL Server) appropriate? required?
Oracle sucks… period.

Open Source Web stuff

The state of .NET open source is painfully inept currently. Looking for good, open source shopping cart code is a losing effort. Switching to ruby for the vibrant open source community. .NET, from a language perspective, is suited for this type of code (shopping cart) obviously, the problem is the community is lacking. 

Version Control / Project Management Tools

Rally
Agilezen
TFS
Perforce
Git (TortiseGit and gitorious)
Mecurial (TortiseHg and VisualHG)
SVN

Podcasts

Herding Code
Stanford course on cuda development (taught by nvidia employees)

 

I hope to see everyone again next month and hopefully some new faces. Stay tuned for an update with the details for next months get together.

Labels:

May 4, 2010

Hosting a nerd dinner event in San Diego

If you are in the San Diego area (or will be on May 13th) and want to geek out with total strangers then you should come to my nerd dinner event.

The idea is to get a group of nerds in a casual setting to chat about anything and everything. Some things I am interested in chatting about are NoSQL, Natural Language Processing, SaaS (especially cloud based ideas), C# 4.0 Parallel computing etc. So you can see, it is really all over the map. In general I think it will lean towards the .NET side as most of the people in my network that I am inviting are .NET guys but really I would love to get people from other areas to come out and share their ideas and experiences. 

To RSVP for the event go here: http://nrddnr.com/2159

Hope to see you there.

Labels:

Apr 30, 2010

5 Things you should be doing in your code but probably aren’t

This blog post is long overdue since I did the leg work for it months ago. I did a little experiment with my coworkers effectively crowd sourcing the information gathering step and I am finally distilling my findings.

At InterKnowlogy, the nature of our work changes rapidly. We are effectively a collection of custom software consultants. This means we get exposed to various different technologies, methodologies, and coding styles. Our projects range in duration from short term (4-5 weeks) to very long term (1-2 years or more). Across all these different projects I wanted to find common patterns that appear in the code. I was looking for things that could easily be changed to increase clarity, performance, and maintainability.

While the science of my approach could be debated endlessly let me preface this with “it is only a first pass.” Very simply, I asked my colleagues to take the project they were currently working on and run the built in Visual Studio code analysis tool. I asked them to send me the top one or two Code Analysis warnings that showed up most often. In some cases people ran this across multiple projects within a solution and in some cases they just ran it on the largest or most complex project in the solution. From this decidedly unscientific study I have found five common warnings that showed up consistently across projects.

All of these are simple fixes and generally acceptable, low impact fixes that would only increase clarity, robustness, or performance of your code. Now, that doesn’t mean you should blindly implement these suggestions without considering the impact of them. However, you likely have these “errors” in your codebase right now and might benefit from implementing these fixes.

1. CA1823Avoid Unused private fields

This one is easy to spot using a tool like ReSharper (R# for short). R# will gray out fields that aren’t being used anywhere (it will do the same for local variables and methods). In our case some people here are not R# fans so they don’t get this visual cue. Often times this is the result a refactoring. You will change some code in a method and the private field you were using is obsolete now but you never go back and clean up the field definition. This is a simple fix and won’t negatively affect anything. Of course it also doesn’t really hurt anything to not remove the fields but in a very large project it can help increase code clarity and reduce the work the compiler has to do to optimize away the unused fields at compile time

2. CA1305Specify IFormatProvider

This one is something I have become accustomed to doing just out of force of habit. If you call a method that has an override that accepts an IFormatProvider and don’t explicitly specify the IFormatProvider or the CultureInfo you will get this warning. Most often I see this in String.Format, String.Compare, and DateTime.Parse calls. The MSDN help has a very succinct explanation of how to deal with this error (emphasis mine):

.NET Framework members choose default culture and formatting based on assumptions that might not be correct for your code. To ensure the code works as expected for your scenarios, you should supply culture-specific information according to the following guidelines:

  • If the value will be displayed to the user, use the current culture. See CultureInfo.CurrentCulture.

  • If the value will be stored and accessed by software (persisted to a file or database), use the invariant culture. See CultureInfo.InvariantCulture.

  • If you do not know the destination of the value, have the data consumer or provider specify the culture.

Even if the default behavior of the overloaded member is appropriate for your needs, it is better to explicitly call the culture-specific overload so that your code is self-documenting and more easily maintained.

3. CA1709 & CA1704 Identifiers should be cased correctly & Identifiers should be spelled correctly

This is probably the main reason I started running CodeAnalysis consistently on my projects. I am notoriously a terrible speller and typo king (if you suffer through my blog I am sure you have noticed). CodeAnalysis does a good job detecting spelling errors in identifiers and can help you increase your code clarity and ensure you are exposing public API members with proper spelling and casing (I violated my own rule and forgot to run it on Courier and got busted as soon as someone used it and noticed on the of the public methods was misspelled). The MSDN link I provided explains how the spell checking is accomplished and how it breaks identifiers apart into logical words.

The argument on proper casing is more controversial so I will leave it up to you if you want to listen to what Code Analysis has to say about that. Is “id” or “Id” or “ID” ? (For the record it is “Id” according to Code Analysis)

4. CA1062Validate arguments of public methods

I am surprised by how often I see this one. Plain and simple, straight from MSDN: “All reference arguments that are passed to externally visible methods should be checked against null.”  Again, R# to the rescue here. It very clearly points out when you should be checking for null and gives a quick key stroke to implement the boiler plate code for you. Do you see a pattern here? R# gives you better programming habits. If you are passing in a reference argument put in a null check before you do anything else. How many times have you gotten a NullReferenceException at runtime? About a billion times and a good portion of those could be prevented by simply getting in the habit of null checking reference arguments. From MSDN:

// This method violates the rule.
public void DoNotValidate(string input)
{
if (input.Length != 0)
{
Console.WriteLine(input);
}
}

// This method satisfies the rule.
public void Validate(string input)
{
if (input == null)
{
throw new ArgumentNullException("input");
}
if (input.Length != 0)
{
Console.WriteLine(input);
}
}


5. CA1805Do not initialize unnecessarily



This one is mostly a pet peeve of mine. Again R# to the rescue here. It will simply gray out redundant initialization code. Often times, when I see redundant initialization it points out to me a fundamental misunderstanding  of how the CLR works. Again, from MSDN:



The common language runtime initializes all fields to their default values before running the constructor. In most cases, initializing a field to its default value in a constructor is redundant



If you are declaring private fields there is no need to initialize them (either in line or in the constructor) if you are just setting them to their default value. This just adds code bloat and the compiler will optimize this away anyways. To be sure you know what your fields default value is you can use the handy Default Values Table from MSDN.



 



Again, most of these issues are minor and won’t cause you grief if you don’t fix them (although CA1305 has the potential to cause some nasty issues). However, if you get in the habit of at least considering these issues and writing the code the “correct” way from the start you will reduce the overall noise in your code and increase the overall “correctness” of your codebase. Also, if you do intend to run Code Analysis on your project, fixing these five issues first will greatly reduce the number of warnings you see (at least according to my highly unscientific study).



If you didn’t notice the other pattern that emerged here it is that I am a fan of R#. It proactively helps you fix these types of issues at the time you write the code. For me, R# makes me a better programmer and helps instill better habits. Without sounding like too much of a shill for R# (too late?) I highly recommend at least trying it out and seeing if you like it. It took me about 8 months of using it before I finally “saw the light.” Now that I have I can’t live without it.



*Full Disclosure: As a Microsoft MVP JetBrains does provide me with complimentary licenses of their software, including R#. I have been using R# prior to being awarded MVP and my experience has been consistently solid throughout.

Labels: , , ,

Apr 27, 2010

Enterprise Library 5.0 Released

I am a little late to the party but I wanted to send out a quick note to congratulate the Patterns and Practices team at Microsoft on their release of Enterprise Library 5.0. I got the chance to work with the team on overhauling the configuration tool and had a blast. These guys are seriously talented engineers. If you haven’t checked out the library lately it is worth a look. We use it in almost all of our applications in one way or another and have been very satisfied with it. P&P is also nearing the release of Unity 2.0 which is also very exciting to see.  So congrats guys and keep up the good work!

Labels: , ,

Apr 26, 2010

Aliph (Jawbone) Customer Support For the Win

I purchased a Jawbone prime about 6 months ago. I have been a jawbone user since V1 and have been a huge fan of the product. By far it is the best Bluetooth headset I have owned. However, my beloved Jawbone prime decided to call it quits about a month ago. After fiddling with the charger and the headset I just couldn’t get it charge any more. I tried a different charging cable and I tried a colleagues jawbone prime in my charging cable. It became clear that my headset was dead. I contacted jawbone support to see what could be done. Honestly, I wasn’t sure what to expect. I figured the customer support would probably be outsourced to somewhere and be pretty much worthless. This has been my experience with most other tech companies so I didn’t expect different.

To my surprise I got right through to a real person and she was very knowledgeable. I explained the situation to her and she quickly offered to replace the unit, no questions asked. I was stoked. All I needed to do is send her my receipt to prove I purchased the unit and she would send me the RMA number and start the process. It gets better, she said I could simply attach a JPG of the receipt to my e-mail and off we go. That is huge for me, while I have a scanner I typically don’t save paper copies of receipts. Especially in this case, where I bought the product online. So in a matter of minutes I opened my e-mail found the original receipt and took a quick screen shot of it and away it went. Within an hour I had a response back from the same customer service rep. She gave me the RMA number and the shipping instructions and I was all set. Total phone call time was less than 5 minutes from dialing to hang up.

I couldn’t be happier. Finally a company that understands customer support. Now, I haven’t shipped my headset back to them yet (will be sending out shortly) so I can’t comment on the actual hardware RMA process but if the first impression means anything I expect this process to go very smoothly. I will update this post as soon as I finish that process and share my experiences.

UPDATE: 5/6 Seriously, these guys rock! I shipped my headset back to them via UPS. Once they received the unit they processed the return within 3 days. I had a few E-mails back and fourth with them just to send them the incoming tracking number and to let them know it was on the way. Once they processed the return they contacted me to tell me the color I originally had (black)  was out of stock but they didn’t want me to have to wait so they offered to let me chose any of the other colors they had in stock. I selected a different color and the unit was shipped out the next day. Totally awesome. All the communication was handled via e-mail, other than the the original phone call I never had to pick up a phone again. My various e-mails were responded to by 3 different customer service people, all of which were fast to respond and very accommodating. The entire thread of the conversation was kept intact across all the customer service agents and the process went incredibly smoothly. Why can’t all companies customer service be this effective?

Moral of the story? Aliph Customer Support For the Win!

Labels: , ,

Updates to Courier

I finally managed to get a few colleagues of  mine to use the Courier framework in one of their projects.  The great thing about this is I get some free testing from them. Overall things seems to be working well for them (at least that is what they tell me). However, there were a few small changes they were interested in. So I obliged and added some minor features to the framework.

1. Opt out of cached messages – Previously, there was no way to opt out of receiving cached messages. If there was a copy of a message in cache and you registered for that message you would receive the cached message. This worked for me but the suggestion was to offer a way to opt out of receiving the cache. So I added a few overrides in the Register method to allow you to specify if you want cached messages or not.

2. Broadcast / Register for “no payload” messages - This one was a bit trickier to support. The idea is you want to simply send a “notification” that something happened but you don’t actually have data to pass. After some debate on where this scenario makes sense, and why you would use Courier for this operation I decided it was best to implement the feature. So now you can do something like this:

Int32 callCount = 0;
Messenger.RegisterForMessage("Foo", () => callCount++);
Messenger.BroadcastMessage("Foo");
Assert.Equal(1, callCount);


The arguments in favor of using Courier for this (as opposed to a normal .NET event) were. One, to keep consistency throughout the project as far as message passing. If you are doing Courier in some places why not do it everywhere. Two, Courier has the advantage of being able to broadcast messages across assembly boundaries without having to couple the two assemblies tightly. With a typical .NET event you would have to know about the type of event you want, which would mean you would need a reference to the assembly where the type is defined for both the sender and the receiver. In Courier, since the messaging model is decoupled, you can leverage it to send messages without needing the type definition in each assembly.



Also, one of my colleagues contributed a Visual Studio 2008 solution so you can build 2008 assemblies in stead of the 2010.



With these updates I have decided to make this the official v 1.0 release of the framework. The 1.0 release zip file contains the release builds of Courier.dll and Courier.Rx.dll assemblies compiled against .NET4.0 and the release build of Courier.dll compiled against .NET3.5 (called Courier-vs8.dll). PDB’s are also included for all assemblies.  

Labels: ,

Apr 3, 2010

MediaRss libraries now on codeplex

I have just published a new Codeplex project: http://mediarss.codeplex.com/. This project has grown out of a larger effort I am currently working on. I had a need to read and write MediaRss files. If you aren’t familiar with the MediaRss spec it is an RSS spec originally developed by Yahoo for their video search engine. It has since been adopted by the wider community and is becoming more standardized. For details on the spec itself see here and here.

For what I am working on this format worked well for me. However, there wasn’t much out there in the way of C# libraries that did any of the heavy lifting for me. In general parsing RSS is trivial in .NET but there are a few oddities about this spec that lead me down the path of building my own library. It took a little tedious work to complete but now it as at point where it is useful to me and I felt it could be valuable to others looking for a quick solution to dealing with MediaRss files.

I leveraged the SyndicationFeed object model from .NET 3.5 to make consuming the feed feel natural to those already familiar with this model. The usage looks like this

var reader = XmlReader.Create("SampleMedia.rss");
var feed = SyndicationFeed.Load<MediaRssFeed>(reader);


What you get back is a strongly typed MediaRssFeed object. You can then treat it like you would any other SyndicationFeed object. I have also included an extension method to easily cast the Items property of the MediaRssFeed to the MediaRssItem object. To do that you would do:



var feed = SyndicationFeed.Load<MediaRssFeed>(reader);
IEnumerable<MediaRssItem> feedItems = feed.Items.AsMediaRssItems();


This lets you dive into all the properties on the items that are specific to the MediaRss spec. I still have a little more work to do to fully support the spec but it is most of the way there. The unit test project is best the place to see the samples of how to read and write using the library and how to inspect the different properties of the object. You can get the compiled binaries and / or the full source code from here. Enjoy.

Labels: , ,

Apr 2, 2010

Speaking at San Diego .NET Developers Group on 4/6

Please excuse this bit of shameless self promotion:

I will be speaking at the San Diego .NET Developers Group on April 6th, 2010. I am going to be giving a talk about technical interviewing. If you follow my blog you will recognize the topic :).

The semi ranting post I published a few months back got a lot more traffic then I expected. I thought I was just blowing off steam. However, it seemed that many other people had similar experiences and agreed, at least in part, with what I was saying.

That gave me the idea to filter out the ranting and distill down the useful bits of advice and build a talk out of it. So this talk will be my first attempt at formalizing the advice and hopefully sharing some knowledge and experience with others.

If you are local to San Diego or going to be in the area on April 6th please drop by and check out the group. The meetings are free and are always fun.

Labels:

Feb 18, 2010

Adding Rx Framework to Courier

In a previous series of posts I introduced the Courier framework. Recently I have been doing some refactoring on the project and feature enhancements. The refactoring was fairly straight forward.

I was never quite happy with the way that you unregistered for a message so I changed the model of message registration to return a token and then subsequently changed the signature of unregister to take in this token. That change was pretty straight forward and badly needed.

The big feature in this update is the integration with the Rx Framework. If you don’t understand Rx I suggest diving into these videos. Be forewarned, the Rx guys are incredibly smart and tend to blaze through things very quickly. Much is left “up to the reader” to figure out and play with on their own. This makes it pretty difficult to grok. I am not sure I really understand all the moving parts of Rx.

One of my main goals in adding Rx to the Courier project was to allow you do include or exclude the Rx features with minimal pain. I also wanted to avoid a deep dependency on the Rx extension assembly. So I created a separate assembly for the Rx features that introduces an extension method to the Messenger class. This gives you an additional way to subscribe to a message and get an IObservable back. Since it is in a separate assembly you should be able to omit the assembly (and any dependency on Rx) pretty easily if you wanted to.

So what does this change let you do? Essentially I have added one extension method to the messenger that gives you different method to subscribe for a message. Syntactically it looks like this

IObservable myObservable = MyMessenger.RegisterForMessage("Foo");


This tells the messenger that you want to listen for the “Foo” message and get the result pushed into your myObservable sequence. So why is this cool? LINQ.



Plain and simple IObservable is queryable with LINQ and that makes for very interesting scenarios when you are dealing with a message pump that is very active and you want to filter out messages based on a criteria. I have added an example of how to use the new Rx extension method and tried to model the scenario into a real world situation.



Imagine you are listening to WCF service that is sending messages from a Blood Pressure monitor. Imagine the Messenger is broadcasting messages each time the Blood Pressure monitor sends some data.   This can lead to a flood of messages firing through the Messenger. Using this new extension method you can write a simple LINQ query to filter these messages and only “react” to the ones you care about.



In the scenario I show in the sample project I only care about messages when the blood pressure is outside of the “normal” range. In those cases I want to “react” and show some alert. I have written a quick and dirty simulation that will fire messages every second and randomize the pressure. When the pressure is outside of the predefined range I will get a message “pushed” into my IObservable sequence. When this happens I have a delegate that “reacts” to this “push” and does something (in my case I raise an alert)



So, from the snippet above I can take it one step further and do this:



IObservable<Object> observable = from msg in Mediator.RegisterForMessage("BloodPressureMessage")
where (((BloodPressure)msg).Systolic < 90 || ((BloodPressure)msg).Systolic > 119)
&& (((BloodPressure)msg).Diastolic < 60 || ((BloodPressure)msg).Diastolic > 79)
select msg;

observable.Subscribe(OnAlertReceived);


Notice how I am now writing a LINQ query on the IObservable that the messenger is returning from the RegisterForMessage method. The line after the LINQ query is how I subscribe to the “push” events that happen on the observable sequence. OnAlertReceived is the delegate I want invoked when a new message is “pushed” on the IObservavle sequence.



Cool? I think so. Also, this check in I am going to promote to Beta 2 status. I have added unit tests and done some other small cleanup work. I think it is getting close to being ready for a true release. I would like to buff out the sample application a bit more and get some more API documentation in place and work out and remaining bugs.



one little nit that I want to clean up in the next version is the casting of the “msg” in the LINQ Query. There are some internal issues with how I am implementing Rx under the covers that makes strong typing of the resulting observable challenging, I don’t have a solution for this yet given my current implementation, so if you find one please contribute it back to the project or let me know.

Labels: , ,

Google Reader: Tip of the day – Mark as Unread

I may well be the only one who didn’t know about this (and possibly the only one who cares about this) but I just found the holy grail for google reader. The list of keyboard shortcuts.

I stumbled across this because I have been wanting a “mark as unread” option in reader like you have in Gmail. When I read through blogs I often will be interrupted in the middle of reading and need to go do something else. I haven’t determined if the blog is “star” worthy yet but I want to remind myself to go back and finish reading the blog entry. Hence the need for “mark as unread” in Google reader.

It turns out this feature does exist but is hidden as a keyboard shortcut. Behold the letter “M”. With a blog entry highlighted simply press the letter M and ta-da! unread. Sweet. 

There is a trove of other nice shortcuts in the list as well. Like toggle full screen mode “U” and open the e-mail form “E”.

Enjoy.

Labels: ,

Jan 11, 2010

How to not suck at a technical interview*

This is partially a rant and partially an honest to goodness attempt to raise the overall bar in our industry. Given that there are about 4 people who read this blog the latter is mostly a pipe dream but still.

I have been involved in the interview process at my last couple companies. In the last few years I have picked up on a few things that I see consistently in interviewees. My hope is to distill these things in this post and try to offer some insight into what we, as interviewers, think of these traits and what we would really like to see from an interviewee.

Ok enough altruism about helping the industry. Bottom line is MOST applicants in the software development industry suck. Yeah yeah yeah, bitch all you want about my exaggerations and oversimplifications. The thing is, it’s true. Interviewing is painful. It is the exception not the rule that I find someone who is even worth more than 5 minutes of my time.

For a while I honestly thought I was a bad interviewer and that my questions were too complicated or convoluted to be understood. I still don’t think I am the best interviewer by any means. I have however changed my approach to asking questions and try to work with the interviewee to get them talking and make them comfortable. But it isn’t my style that is broken it is the overall level of skill in the industry that is broken.

I am not talking about  personality quirks, nervousness, or any other interview related issues. Look, I get it, programmers are a strange bunch. It is expected that you are going to interview odd balls, eccentrics, type A assholes whatever. I can deal with that. One piece of interviewing that I like to think I am ok at is filtering out these types of things and trying to identify the applicants true skill set. Sure, personality is part of an interview and certainly a vital part to team chemistry. I take a person’s personality traits very seriously in determining my opinion of the applicant. But, none of that matters if they don’t have the fundamental skill set needed.

So here are a few things I see repeatedly during interviews.

1. Stretching your skill set: Ok, I get this one. I understand how it works, you need to throw the buzzwords on the resume to get your foot in the door. If you copy and paste a laundry list of the current buzzwords on your resume you better be prepared to answer questions about ANY of the buzzwords on your resume. Don’t tell me you are “an expert in Entity Framework and LinqToSQL” and not expect me to ask you a question about it. If you can’t hold your own in a discussion about a technology don’t put it on your resume. Also, choose the nouns you use to clarify your skill level carefully. If you say you are an “expert” at something then I am going to drill you with deep technical questions. If you are an “expert” you better be able to teach a class on the technology. Don’t be afraid to say you are simply proficient or even that you are a novice. This sets my expectations properly so I can formulate questions. No one is an expert at everything, I don’t expect that. So when I see someone that is an “expert” at every current buzzword I get highly suspicious.

2. Few details about current position: I almost always lead with something like “tell me what you have been working on lately.” One, I am trying to ease the nerves and let the person talk about a subject they should be intimately familiar with. Inevitably I get some high level response with a bunch of superfluous buzz words and very little technical meat. This doesn’t help! If you can’t explain your current position, in detail, I am already out on you. Out of any of the questions I am going to ask this is by far the simplest. Just tell me what you are working on. Talk to me like I am a co-worker and we are chatting in the hallway at work. I am a nerd too, I understand geek speak, I can fill in gaps. Don’t fear losing me or giving me to0 much detail. A solid response to this question frames the entire rest of the interview. It gives me content to build on. It gives me areas to press you on. But, most importantly it give me insight into how you think.

I really can’t stress that last sentence enough. It will be a recurring theme in this post.

3. Unwillingness to say “I don’t know.” Arggggghhh seriously, this one gives me a headache more than anything else. For god’s sake just say “You know, I am not sure I know the answer to that question.” So many people just try to talk themselves out of a corner or give some vague answer hoping I will buy it. Really? Do you really think,  if I ask you a question, that I don’t know the answer? If ask you something I damn well know the answer and I expect you to either give a correct answer or tell me you don’t know. BS’ing the answer or trying to weasel out of the question just pisses me off. Like I said, Arrrgggghhhh. Again, as I said, I have no expectation that people will be experts in everything. I am fine with you admitting you don’t know. Even if the question is related to something on your resume and you don’t know. I would much rather you admit you don’t know then try to fake it. I will often ask questions that I fully expect the person not know the answer to. The reason for this is two fold. One, I want to see if you will admit your lack of understanding and two I want to see how you would go about finding the answer. In almost every programming job you are going to work on problems that you don’t know how to solve, what I want to know is how do you go about finding the answer. If you don’t know the answer to the question tell me you don’t know and add something about how you would go about finding the answer. Would you Google it with Bing. Would you scour blogs, forums, pick a coworkers brain, fire up reflector, read the SDK. Whatever it is explain to me how you would go about it.

4. Not enough use of the whiteboard. This one sounds weird to most I think but it seriously makes a difference. In every single interview I have done the room we are interviewing in has a whiteboard. USE IT. Not just use it but don’t be afraid to jump up and go for it. Every good programming problem requires a white board at some point. We use them daily in our jobs but for some reason we just don’t feel comfortable using them in an interview. I fully expect you to use a white board to solve hard problems in the day to day job so why not use it in the interview. More than anything, watching some one work through a problem on the whiteboard shows me how they think. Seriously, next time a co-worker jumps up to use a whiteboard pay attention to how they organize information on the board. How do they represent different conceptual aspects? How do they move through the flow of information? You can learn a lot things from how someone uses the whiteboard.

5. Thinking too procedurally. If you get nothing else from this rant please understand this. The number one issue I come across with applicants is a fundamental flaw in their problem solving approach. Too often people suffer from tunnel vision when it comes to solving problems. They find a solution to their problem and don’t take the time to understand why the particular solution works or what, conceptually, they have accomplished. I call this “thinking procedurally” because people seem to understand how to get from point A to point B but throw in even the smallest speed bump and they completely fall apart. They understand the “procedure” to get the work done but they fail to see the larger concept in play. This is the number one issue that causes me to end an interview or give a thumbs down on an applicant. This goes back to the previous two points. I don’t expect you to know everything, be willing to say I don’t know, but if the question sounds like something familiar work your way through the answer, out loud. Talk me through your thinking. Explain to me where you are getting your background from and why you feel it might be similar to X. Use the whiteboard to draw it out (remember your high school math teacher “show your work!”). This is eye opening for me. Listening to you work through the problem and explaining how you would approach it shows me if you truly understand the concepts behind the solution or if you have tunnel vision and can’t see the forest for the trees.

Ok I will wrap up my rant now. A few key takeaways if you made it this far.

1. Expect questions about ANYTHING on your resume. If you don’t know it, even if you did long ago but have since forgotten it, take it off your resume.

2. Give me something to go on. Tell me about your recent work, in detail. Tell me why you did things a certain way. Explain the challenges you faced. Explain what worked. Explain what didn’t.

3. Recognize your shortcomings and be honest about them. Explain how you would work to find the answer. Tell me what resources you use to solve these types of problems. What is your workflow? If it sounds sort of like something you are familiar with talk through it. Give me an insight into your thought process.

4. Use all the tools you have at your disposal. Whiteboards are readily available during an interview. Use it. Draw it out, organize your thoughts on the board. Don’t be afraid to scribble, erase, cross out or generally make a mess of the board (you should see mine right now)

5. Think outside the box. Ok that cliché makes me vomit but in all seriousness understand the concepts. If you don’t understand why your solution is actually working, spend time on it. Use reflector, step through the framework source, do whatever it takes for you to understand the fundamentals happening under the hood to solve your problem.

Feel free to give me feedback on this. Am I being too harsh? Am I a dick? (I already know the answer to that one) Do you totally disagree? Praise, flame, bash whatever I am open to it.

*NOTE: This is a personal blog. The opinions expressed here represent my own and not those of my employer.

Labels: ,

Jan 1, 2010

Nice New Year’s surprise

I got a very cool E-mail from Microsoft last week:

“Congratulations! We are pleased to present you with the 2010 Microsoft® MVP Award! This award is given to exceptional technical community leaders who actively share their high quality, real world expertise with others. We appreciate your outstanding contributions in Visual C# technical communities during the past year.”

w00t!

I would have posted sooner about it but you wouldn’t believe the amount of NDA’s I had to sign just to be able to use the official MVP seal (see sidebar).

I have updated my MVP Profile and made it public for the masses.

Who wants to touch me? :)

Labels:

Dec 21, 2009

Decoupled ViewModel Messaging (Part 3)

NOTE: All the code shown in this series has been published to codeplex. If you would like to download the framework or the sample application that uses the framework you can find it here: http://courier.codeplex.com/

    In this part of our saga we find or intrepid hero trapped in a ……. Wait where was I? So far in this series we have covered decoupled messaging between ViewModels at a high level and we have looked at one specific enhancement that I have added to my courier framework that is lacking in other implementations.

     In this final post I am going to cover one more feature that I have added to the courier framework that I think provides a very nice addition to the overall process of decoupled ViewModel messaging and that is message caching.

    When I first started with this framework I really just set out to wrap my head around what others had done (CoreMVVM,Cinch, Prism, MVVM Foundation). Once I had gotten to that point I wanted to add a little something more to make the framework my own. What I found was that, in my scenarios, I found myself needing to cache messages for later retrieval. 

    The most obvious case for this is in the “Wizard” type scenario. When a user is performing a sequential set of actions I often have the need to pass data from one screen to the next. In this scenario the next screen is not created until after the previous screen is destroyed. This means that the message broadcast from screen one would happen before screen two is around to listen for it. With me so far?

    So, to solve this problem I figured I would implement some sort of caching mechanism that would allow me to:

  • Broadcast a message from View one
  • Save the message for re-broadcast
  • Destroy View one
  • Create View two
  • Register for that message from View two
  • Receive any, valid, cached copies of the message I registered for

The first thing I did was to implement an internal List<T> inside the mediator class that would store these CachedMessage objects. When a message is broadcast with caching options I will save a copy of the message to this List<T>. Any subsequent registrations for this message will receive any valid cached copies of the messages.

    So I added the following to the mediator

private readonly List<CachedMessage> cachedMessages = new List<CachedMessage>();


Where the CachedMessage class is defined like this:



[DebuggerDisplay("Message: {Message}, Parameter: {Parameter}")]
internal class CachedMessage
{
public String Message { get; private set; }
public Object Parameter { get; private set; }
public CacheSettings CacheOptions { get; private set;}
public Int32 ResendCount { get; set; }

public CachedMessage(String message, Object parameter)
{
Message = message;
Parameter = parameter;
}

public CachedMessage(String message, Object parameter, CacheSettings cacheOptions)
{
CacheOptions = cacheOptions;
Message = message;
Parameter = parameter;
}
}


    Two things to note here. First the CachedMessage class has a public property of type CacheSettings. This gives us the details of how long to keep the message for. Currently I am supporting two types of caching, time based and recurrence based. This means you can specify a specific DateTime when the message will expire or you can specify how many re-broadcasts before the message expires. The CacheSettings class looks like this:



[DebuggerDisplay("Expiration Date: {ExpirationDate}, NumberOfResends: {NumberOfResends}")]
public class CacheSettings
{
public DateTime ExpirationDate { get; private set; }
public Int32 NumberOfResends { get; private set; }

public CacheSettings(DateTime expiration)
{
ExpirationDate = expiration;
NumberOfResends = Int32.MaxValue;
}

public CacheSettings(Int32 timesToResend)
{
NumberOfResends = timesToResend;
ExpirationDate = DateTime.MaxValue;
}
}


    The second thing to note about both of these classes (CachedMessage and CacheSettings) is the use of the DebuggerDisplay attribute. I have just recently got in the habit of using this attribute religiously and I don’t know what I ever did without it. I won’t dive too in depth here about it, but suffice it to say, if you aren’t using it right now you should be. If you don’t know what it is stop reading here and jump over to my colleague, Adam Calderon’s, excellent post about it (don’t worry I will wait for you to come back).



    Ok, now that we are all writing Debugger friendly classes thanks to Adam, let’s wrap this post up with some usage scenarios. In the “Wizard” like case I talked about above I really just want to be able to broadcast a message and cache it for one re-broadcast. This allows me to broadcast the message from view one and then destroy view one and create view two. view two then registers for the message like it would normally and will immediately receive any messages that are in the cache. Once the message is dispatched from the cache we want to clean it out to prevent further re-broadcast. So first, two examples of how to call BroadcastMessage<T> with caching options



//NumberOfResend based caching example
Mediator.BroadcastMessage("Content1Message",messageContent,new CacheSettings(1));

//Time Based caching example
Mediator.BroadcastMessage("Content1Message", messageContent, new CacheSettings(DateTime.Now.Add(TimeSpan.FromSeconds(30))));


The first example show how to broadcast a message and specify that it should be cached for one re-broadcast. The second example shows how to broadcast a message and store it in the cache for 30 seconds after the first broadcast. Pretty straightforward so far. Now the two key methods in the Mediator class that handle keeping the cache clean and dispatching messages from cache:



private void GetMessagesFromCache(String message, Delegate callback)
{
CleanOutCache();
//Search the cache for matches messages
List<CachedMessage> matches = cachedMessages.FindAll(action => action.Message == message);
//If we find matches invoke the delegate passed in and pass the message payload
matches.ForEach(delegate(CachedMessage action)
{
callback.DynamicInvoke(action.Parameter);
action.ResendCount++;
});
}

private void CleanOutCache()
{
//Remove any expired messages from the cache
cachedMessages.RemoveAll(message => (message.CacheOptions.ExpirationDate < DateTime.Now) || (message.ResendCount >= message.CacheOptions.NumberOfResends));
}


    You can see in the GetMessagesFromCache method the first thing it does is clean out any expired messages from the cache. The CleanOutCache method uses the RemoveAll method on List<T> and an lambda to do a particularly elegant line of code. This code checks two properties of the CachedMessage objects (is it’s expiration date in the past OR has it been re-broadcast the max number of times?). If either is true it is removed from the CachedMessages list. A very succinct line of code for a normally cumbersome task.



    After the cache has been cleaned we call FindAll (again, using a simple lambda) to get all the messages from cache that match the one we are looking for (There could be multiple messages from different senders in the cache and we want to dispatch them all). Once we have the matching messages we invoke the callback that is registered and we increment the re-send count on the message. Overall, a pretty simple process, but it turns out to be very powerful.



    That wraps up this 3 part series ( I, II, III) on the Courier framework. As I add new features to the framework I will post specific updates about the features. If anyone else is interested in joining the codeplex project and adding their ideas to the framework please feel free to contact me through this blog.  



NOTE: All the code shown in this series has been published to codeplex. If you would like to download the framework or the sample application that uses the framework you can find it here: http://courier.codeplex.com/

Labels: , , , , ,

Dec 12, 2009

Decoupled ViewModel Messaging (Part 2)

NOTE: All the code shown in this series has been published to codeplex. If you would like to download the framework or the sample application that uses the framework you can find it here: http://courier.codeplex.com/

In my previous post I discussed the ViewModel messaging framework at a high level and went over the basics of the implementation. Most of this is review if you are familiar with the other frameworks that I borrowed ideas from.

In this post I want to touch on the two specific features I wanted to add to the other frameworks I had seen (hence the motivation behind this framework and this series of blog posts). Specifically, the two features I felt would be useful is the ability to explicitly unsubscribe from a particular message and the ability to cache messages for re-broadcast at a later date.

The first feature seems obvious enough. There are times when you want to listen for messages and there are times that you want to stop listening for that message. Many of the frameworks mentioned previously use WeakReferences to store the pointer to the message handler method. This works great when object are being destroyed. The Mediator object, which is responsible for delegating messages to their proper handlers, stores only a WeakReference to the handler and checks just prior to dispatching the message if the endpoint IsAlive. If it is then the message is dispatched. If it isn’t alive, then the endpoint is removed from the list of subscribers. This check looks something like this:

for (int i = weakSubscribers.Count - 1; i > -1; --i)
{
WeakSubscriber weakSubscriber = weakSubscribers[i];
if (!weakSubscriber.IsAlive)
weakSubscribers.RemoveAt(i);
else
subscribers.Add(weakSubscriber.CreateAction());
}


What this does is simple. It walks the collection of subscribers backwards and checks the IsAlive property. The IsAlive property on the WeakSubscriber class is simply looking at the underlying WeakReference.IsAlive property. If we find a dead subscriber we remove it from our list so that we don’t try to dispatch the message to an event handler method that has been destroyed.



This pattern works great is your subscriber objects, that is the object that has the event handler for the message in it, is being destroyed. However, I have situations where my object that contains the handler method for a message is still alive but I don’t want to receive any more messages of a given type from the mediator. In this case I need a way to tell the Mediator to remove from it’s list of subscribers.



To help with this I have added a method to the Messenger class call UnRegisterForMessage.



//Method bodies elided for clarity 
public void UnRegisterForMessage(String message, Delegate callback)
{
...
}


This method takes in the message you want to unsubscribe to and the handler you want to remove for that message. For a given message and object can have multiple handlers. This method allows you to unsubscribe a particular handler while, potentially keeping the other handlers subscribed.



On caveat to this approach is how I am passing the reference to the handler method. In the internal unregister process  I need a way to determine which handler I am removing from which message. The only way I could find to make this work was to pass a reference to the delegate itself. The remove method inside the MessageToSubscriberMap class looks like this:



internal void RemoveSubscriber(String message, Delegate callback)
{
lock (map)
{
if (map.ContainsKey(message))
{
map[message].RemoveAll(subscriber => subscriber.Method == callback.Method);
}
}
}


This works fine but the usage is a bit strange and has one glaring issue that I have yet to find a solution for. Let me demonstrate. I if I want to unsubscribe from a message called “UserChanged.” I would write something like this:



Mediator.UnRegisterForMessage("UserChanged", (Action<IUser>)OnUserChanged)


Notice the second parameter here. I am the reference to the delegate OnUserChanged and casting it as an action. This will work just fine. However, in some internal projects I have used this framework and noticed other developers do something like this:



Mediator.UnRegisterForMessage("UserChnaged", new Action<IUser>(OnUserChnaged))


Notice the difference? Subtle maybe, but it is critical to understand the problem here. In the second example the second parameter, instead of being cast as an Action<T> a new instance of an Action<T> is being created and passed in. This will not point to the same instance of the delegate passed in on the Register call. This means the unsubscribe will not find a match and will not remove the handler. This means you will continue to get messages broadcast. In general, I am not completely satisfied with the unsubscribe method signature and may change it in the future.



  This post is getting a bit long winded so I will stop here and in my next post I will describe message caching and how I went about implementing it.



NOTE: All the code shown in this series has been published to codeplex. If you would like to download the framework or the sample application that uses the framework you can find it here: http://courier.codeplex.com/

Labels: , , , ,

Nov 17, 2009

Decoupled ViewModel Messaging (Part 1)

 

NOTE: All the code shown in this series has been published to codeplex. If you would like to download the framework or the sample application that uses the framework you can find it here: http://courier.codeplex.com/

Lately I have been playing around with different ways to decouple the communication between ViewModels in the MVVM pattern. My focus has been in WPF, as this is what the MVVM pattern is suited for however, this messaging technique is not specific to WPF and could be used in any other decoupled solution (MVC, MVP etc..)

I poked around on the tubes looking for examples of how other people have solved this problem and there are many different options out there. My implementation borrows heavily from the CoreMVVM framework on codeplex which itself borrows bits from Cinch, Prism, MVVM Foundation etc.. 

My first goal was to really just get down in the weeds and understand how these other frameworks were handling decoupled messaging between objects. Once I wrapped my head around it I then came up with two features that I thought would be nice to have in a messaging solution that I hadn’t seen in other frameworks.

The ability to manually unsubscribe from messages and the ability cache messages for re-broadcast.

Before I dive in and talk about the new features I wanted to add let me go over the basic implementation of the Mediator pattern I did. Again, this is very similar to how the CoreMVVM framework does it, so if you are familiar with that framework this should review.

The basis of the implementation is a basic mediator pattern. You have a mediator object that stores a mapping of subscribers and messages. This gives the mediator enough information to understand what messages to dispatch to what subscribers. The mediator in my case looks like this 

//Method bodies elided for clarity
public class Mediator
{
private readonly MessageToSubscriberMap subscribers = new MessageToSubscriberMap();
private readonly List<CachedMessage> cachedMessages = new List<CachedMessage>();

public void RegisterForMessage(String message, Delegate callback)
{
...
}

public void UnRegisterForMessage(String message, Delegate callback)
{
...
}

public void BroadcastMessage<T>(String message, Boolean cacheMessage, T parameter)
{
...
}

public void BrodcastMessage<T>(String message, Boolean cacheMessage)
{
...
}

private void GetMessagesFromCache(String message, Delegate callback)
{
...
}
}


From the snippet above you can see there isn’t much going on in the Mediator. The key is really the MessageToSubscriberMap object defined at the top. This object is what stores the (weak) reference to the subscriber (in this case a delegate to be invoked) and the message that subscriber is interested in.



Here are the guts of the MessageToSubscriberMap class



//Method bodies elided for clarity
internal class MessageToSubscriberMap
{
//Store mappings with weak references to prevent leaks
private readonly Dictionary<String, List<WeakSubscriber>> map = new Dictionary<String, List<WeakSubscriber>>();
internal void AddSubscriber(String message, Object target, MethodInfo method, Type subscriberType)
{
...
}

internal void RemoveSubscriber(String message, Delegate callback)
{
...
}

internal List<Delegate> GetSubscribers(String message)
{
...
}
}


The key piece of this map is the private Dictionary field. This is the mapping of Messages to the collection of WeakSubscribers that are listening for that message. I have called the object WeakSubscriber to indicate that a subscriber is really a WeakReference to a delegate. Here is the complete implementation of the WeakSubscriber class



internal class WeakSubscriber
{
private readonly MethodInfo method;

public MethodInfo Method { get { return method; } }

private readonly Type delegateType;
private readonly WeakReference weakReference;

internal WeakSubscriber(Object target, MethodInfo method, Type parameterType)
{
//create a WeakReference to store the instance of the target in which the Method resides
weakReference = new WeakReference(target);
this.method = method;
delegateType = parameterType == null ? typeof(Action) : typeof(Action<>).MakeGenericType(parameterType);
}

internal Delegate CreateAction()
{
Object target = weakReference.Target;
return target != null ? Delegate.CreateDelegate(delegateType,weakReference.Target,method) : null;
}

public Boolean IsAlive
{
get { return weakReference.IsAlive; }
}

}


Ok so now we have seen the extent of my little messaging framework. Again, most of this code is very similar to the CoreMVVM framework implementation of the mediator pattern so, for users of that framework, this should be familiar.



I am going to wrap this post up with a quick example of how you would subscribe to a message and how you would broadcast a message with this framework.



To broadcast a message you would do this:



Mediator.BroadcastMessage("Content1Message",true, messageContent);


Note the second parameter in this method call is for caching the message which I will explain in a following post.



If you wanted to subscribe to this Content1Message you would register for the message like this:



Mediator.RegisterForMessage("Content1Message", (Action<String>)OnContent1MessageReceived);


In the next post I am going to describe the two new features I added to the framework which are the ability to unsubscribe from a message and the ability to cache messages for re-broadcast.



This project was built in Visual Studio 2010 Beta 2, If you haven’t already I highly recommend downloading VS2010



As a side note, the specific reason I using VS2010 is because I plan on parallelizing the dispatching of messages to subscribers in the future and want to use the new parallel framework in .NET 4.0 



NOTE: All the code shown in this series has been published to codeplex. If you would like to download the framework or the sample application that uses the framework you can find it here: http://courier.codeplex.com/

Labels: , , , , ,