David Carradine

kungfu

As with many people, the passing of David Carradine has left me quite shaken.  David Carradine, after all, was the reason I got into consulting in the first place.

Kung Fu, the Ed Spielman TV series in which Mr. Carradine played Kwai Chang Cane, a parapatetic Shaolin monk in the American Old West, left a lasting impression on me.  If you are unfamiliar with the series, it revolved around a half-Chinese half-American man trained in Kung Fu helping people out as he travelled from town to town searching for his American relatives, all the time pursued by the Chinese Emperor’s assassins.

It may be hard to believe, but when I found out about the world of Software Consulting, I realized that it was my opportunity to fulfill my childhood dream of living the life of Kwai Chang Cane.  It’s a bit of a stretch, but think about what a consultant does. He travels from company to company assisting them with difficult technical issues they desperately need help to resolve.

Let me say that the reality has been as good as the dream.  In the past year I’ve managed to:

05/08 – 07/08

Upgrade a billing application for a national furniture chain located just off of Jimmy Carter Boulevard from VB6 Forms to an ASP.NET 3.5 application with limited ajax functionality.  In the process, I helped out a group a beleaguered shopkeepers being extorted by local thugs.

08/08 – 09/08

Gather requirements for a POC Silverlight project while investigating why a beautiful roller derby skater was killed.

10/08 – 11/08

Assist in the data migration of an insurance company’s legacy data – horribly denormalized, unindexed and lacking referential integrity – from a Paradox for DOS system to SQL Server 2008.  At the same time I was able to rescue the office manager’s cousin from a Turkish prison where he was incarcerated under trumped up drug trafficking charges.  I was able to do this with some help from friends who are Vietnam vets in hiding from the US government for crimes they didn’t commit.

12/08 – 03/09

Design a reporting framework for a mortgage company going through hard times that heavily leveraged third party charting tools while also arranging a new life for a protected Federal witness — who was testifying against his mobster brother — and help him to visit his sick mother before she died.

04/09

This was a fairly quick gig.  I had to design and build a WPF point-of-sale application for a cruise liner.  During installation of the software I teamed up with a consultant from a rival firm to defuse two sophisticated bombs aboard the cruise ship while overcoming our mutual animosity and learning to work together and ultimately develop an abiding respect for one another’s abilities.

05/09

I had some down time in June, so I reminisced about my adventures to my colleagues clip-show style while preparing for a certification exam.

If this makes consulting out to be something glamorous, I want to make it clear that this is not always the case – for instance the time I had to scrub crystal reporting data for a client or the time I had to hunt down oversized alligators in the sewers because they were eating neighborhood pets.  But between those times there can, indeed, be quite a bit of excitement. 

Consulting is definitely not for everyone.  It takes a certain mentality, a certain desire to not have the same routine every day, and of course it never hurts if you have the ability to make plastic explosives out of a matchbox and a stick of spearmint gum or can deploy a multi-tier application with only a command line utility and the spring from a ballpoint pen.

At least I look forward to coming in to work each day knowing that there will be something new and unexpected to make it different from the day before.

And I have David Carradine to thank for setting me on this path.

Outsourcing to Sleestak

sleestak1-349x267

I have a mirror blog called ‘Outsourcing to Sleestak’ that is hosted on my company’s corporate site.  It has seen a recent spike in hits for reasons I do not fully understand.  Looking through the search queries that bring people to my mirror site, I have come to the conclusion that there is a lot of interest in the advantages of outsourcing to sleestak, especially in these difficult financial times. 

As the world’s leading authority on outsourcing to sleestak, I thought it might be helpful if I provide the following FAQ.  Bear in mind that these FAQ are solely the result of my personal research and expertise in the area.  My company has its own outsourcing solution that I will decline to comment on – especially as I am offering a competing solution to the problem of providing cheap alternatives for expensive problems.  So without further ado:

The Outsourcing to Sleestak FAQ

1. Isn’t the plural of ‘sleestak’ in fact ‘sleestaks’?

No.  The plural form of ‘sleestak’ is ‘sleestak’, as in “Ten sleestak can do the work of a typical developer without the added cost of health insurance or the hassle of labor laws.” 

2. I have heard that sleestak are not effective developers and often screw up projects, in part due to their lack of fingers.  Is this true?

This is a common lie spread by jealous outsourcing centers in Bangalore.  While the physical disabilities of sleestak are admittedly problematic, they are more than capable of manipulating polyhedral objects called ‘crystals’.  Work stations in the land of the lost are equipped with large keyboards in which the typical key is replaced with these crystals, making the sleestak more than qualified to search MSDN forums for code samples they can paste into their own projects.  Furthermore, I find these attacks on the digitally impaired to be highly prejudicial and unnecessary.

3. What about the language barrier?

While it is true that the sleestak lack vocal cords, per se, I have never found this to be a deal breaker in working with sleestak outsourcing centers.  Each sleestak ‘tribe’, which is made up of 20 to 30 sleestak, has a ‘leader’ which I like to call the ‘project lead’.  Each leader has a magic crystal around his neck that allows him to communicate in a faux English accent.  Software requirements may be given to the ‘project lead’ who will in turn translate them for the sleestak workforce.  You will never personally have to interact with a sleestak developer.

4. What if I want a project lead onsite at my company?  Is there anyone available to do that?

Besides sleestak workers and sleestak leaders, we also have sleestak from the distant past on staff such as Enik who are highly educated and trained in ‘soft’ skills.  They are experts at telling the client what he wants to hear and will keep the project on track, or at least lead the client to believe that everything is on track.  In a pinch, he is also experienced at rationalizing delivery problems and deflecting blame. 

5. Can sleestak outsourcing meet my advanced programming needs in Silverlight, WPF and other complex technologies?

You are clearly looking at this in the wrong way.  If you are concerned with getting work done, you should look to your internal developers, to independent contractors or consulting firms.  If you are concerned with the bottom line, however, then you need to be outsourcing.  At 99 cents an hour, sleestak are the most cost-effective solution for your programming needs.

6. I think you punted on that last question.  If sleestak don’t know these technologies, then my project will never be completed.  Shouldn’t I be concerned with getting working code, as well as cost savings, at the end of an engagement with sleestak?

Apples and oranges.  It is all a question of motivation.

If you simply want to get work done, then you should give it to an internal team of developers.  Internal developers, however, do not always keep up with the latest technology and methodologies and expect companies to provide expensive training.

An alternative is to hire independent contractors or contractors provided by staffing agencies.  While these are frequently more expensive than internal staff, you can typically be assured of hiring someone with the skills you need to complete a project.  Contractors, however, have the following shortcoming – they dread the day they complete a project because this is the day they must look for a new job.  Consequently, they have a tendency to do only what is requested of them, seeing no need to do additional work that might bring their engagement to an end. Alternatively, they will over-architect a project in such a way that they will be needed well past the completion date for a project since they are the only ones who understand the code.

Another alternative is to engage a high-end consulting firm.  High-end consultants are judged by their consulting companies based on their ability to deliver.  Consequently they will work hard to complete a project as quickly and efficiently as possible in a way that leaves the client happy.  They will juggle development speed, code quality and code maintainability in a manner that best meets the client’s objectives.  Their ultimate goal is to complete a project as successfully and quickly as possible so they can move on to their next project and accomplish the same thing.  The main shortcoming of hiring high-end consultants is that they are really expensive.  They know they are the best and charge accordingly.

If money becomes a problem – let’s be frank, when isn’t it? – and you can’t afford the best solution, then you have a moral obligation to choose the cheapest solution.  Why allow yourself to be straight jacketed by the dictum that you get what you pay for.  With sleestak, you’ll be paying for what you get.

7.  Your answer makes brilliant sense.  But I’ve heard there is alot of turnover among sleestak.  Isn’t this a problem?

Perhaps this is a problem for traditional outsourcing but not for sleestak outsourcing.  Sleestak belong to what is known as a ‘hive mind’.  What one sleestak knows, all other sleestak in the vicinity know equally well.  This basically alleviates all the issues of project hand-over and application maintenance that plague the typical software project.

It is common to call developers ‘resources’.  This gives the impression that all developers are commodities and interchangeable.  Sadly this is not the case, and great effort has to be expended on team building, personality management and motivational techniques.

With sleestak outsourcing, we take these soft issues out of the equation.  The hive mind ensures that sleestak are true development commodities.  If one goes off to join a rival firm or is injured in a freak elevator accident, this is not a problem!  We can replace him with someone with identical skills and an identical knowledge of the project the very next day.

8. I love the idea, but this sounds like science fiction.  How can you afford to bill 99 cents an hour for software development?  Aren’t you exploiting your sleestak?

Certainly not.  Sleestak are not motivated by anything as banal as money.  They are motivated by the desire to achieve client satisfaction – as represented by their client satisfaction target numbers for which they are rewarded with papaya and mangos.  Unsatisfactory target numbers garner a half-hour in direct sunlight, which they find physically painful.  This is a win-win situation for everybody. 

And while there are certainly moral dilemmas involved in the employment of sleestak, this is not your problem.  You can leave the worrying to us.

9. Given the recent backlash against foreign workers, isn’t outsourcing to sleestak a PR nightmare?

Let’s face it.  There’s only one opinion you need to be concerned about – the opinion of your shareholders.  Issues such as community backlash, employee morale, code quality and project deadlines are ultimately peripheral.  The purpose of outsourcing is to demonstrate fiscal responsibility to shareholders.  This is why, when a project goes bad or revenue is lost due to missed release dates, the solution is always to outsource even more work to sleestak – thus demonstrating your ability to quickly respond to revenue loss with efficient cost-cutting.

When it comes down to it, what’s good for sleestak is good for America.

Of Friendship: Lover and Beloved on Twitter

Boys_King_Arthur_Wyeth

Friendship and the API

We commonly think of an API as merely a set of performative rules that determine how two systems communicate with each other.  An API is also, however, an implicit carrier of a set of semantic rules that dictate how a client application (or, to be more specific, how the programmer of the client application) is to understand these utilitarian instructions. 

A well designed API, consequently, must not only provide all the tools necessary to accomplish certain tasks on the server but must also do so in a way that is easily understood by the client, either by reusing common software metaphors or, more often, by using analogies from the business domain or culture in general to get across the purpose of the API.

In the case of a social networking API, these semantic metaphors must naturally come from common modes of social relationships.  Not surprisingly, this can be a complicated task when the social networking API actually creates new forms of social interaction that are fundamentally unlike the forms we are familiar with.  This is both the promise and, to some extent, the danger of social networking. 

In forging new manners for people to interact with one another social networking technologies also modify and distort the old ways in which people used to interact.  When an office worker prefers to email the person sitting in the cubicle adjacent to hers rather than walk over for a conversation, the nature of the workplace – not necessarily for the worse – has admittedly been changed.

A case of API semantics meaning something other than what they ought to mean can be found in the Twitter API.  In order to form a social relationship with another user, Twitter provides a REST method called friendships/create.

One would assume that, upon calling this method, the current user becomes the friend of the user that is befriended and that a mutual relationship has been created between the two.  This is not the case.  In the Twitter API, friendship is an asymmetrical relationship merely indicating that the person one befriends is a friend to oneself – that is someone that is followed – while one may not necessarily a friend of the person one is following – that is, they have not reciprocated by following back.

This asymmetric relationship is more clear when one considers two additional methods provided by the Twitter API: statuses/friends and statuses/followers.  Calling the statuses/friends method returns a list of people whom one is following.  By calling the statuses/followers method one retrieves a list of people who are one’s followers. 

Rather than a network of friends, the world of Twitter is made up of these two classes of relationships: friends and followers.  Even on the Twitter website itself, one is not provided a means to view all of one’s relationships.  Instead there is one link, “following”, for viewing one’s friends and another, “followers”, for viewing the people who consider you a friend (even if you don’t feel the same way about them).

This is not the standard usage of friendship.  It falls short of Aristotle’s notion that friendship is a reciprocal relationship between two people.

“Now the friendships that have been discussed consist in an equality, since the same things come from both people and they wish for the same things for one another…”  Nicomachean Ethics, tr. Joe Sachs

It falls even further from the mark when one considers Michel de Montaigne reflections on his friendship with Étienne de La Boétie:

“Beyond all my understanding, beyond what I can say about this in particular, there was I know not what inexplicable and fateful force that was the mediator of this union.  We sought each other before we met because of the reports we heard of each other, which had more effect on our affection than such reports would reasonably have; I think it was by some ordinance from heaven.  We embraced each other by out names.  And at our first meeting, which by chance came at a great feast and gathering in the city, we found ourselves so taken with each other, so well acquainted, so bound together, that from that time on nothing was so close to us as each other.”

. . .

“[W]hat we ordinarily call friends and friendships are nothing but acquaintanceships and familiarities formed by some chance or convenience, by means of which our souls are bound to each other.  In the friendship I speak of, our souls mingle and blend with each other so completely that they efface the seam that joined them, and cannot find it again.  If you press me to tell why I loved him, I feel that this cannot be expressed, except by answering: Because it was he, because it was I.”  Of Friendship, tr. Donald Frame

Practices Ancient and Modern

The two parties in a friendship are traditionally a friend and a friend, not a friend and a follower.  And yet the friend/follower dyad isn’t a completely new social relationship, as one might expect from a mode of communication based on novel technology.  Instead it resembles a social structure endemic to ancient Greece in which the participants were called erastes and eromenos, as often as not translated as ‘lover’ and ‘beloved’.  You can find an interesting treatment of the institution, heavily influenced by Michel Foucault’s History of Sexuality, in this Wikipedia entry.

Like the institution of friendships on Twitter, the ancient practice went by the common name for something it was not.  Aristotle expresses concern over this kind of “friendship”, which sometimes went under the code “lovers of friendship”, as he tries to place it within his already overextended catalog of the types of relationships that are possible between two people, which already include friendships of utility, friendships of pleasure and friendships of virtue (true friendship):

“With these [incomplete friends] also, the friendships are most enduring whenever they get the same thing – pleasure for instance – from each other, and moreover, get it from the same source, as witty people do, in contrast to the erotic lover and the boy he loves.

“For the erotic lover and his beloved do not take pleasure in the same things; the lover takes pleasure in seeing his beloved, but the beloved takes pleasure in being courted by his lover.  When the beloved’s bloom is fading, sometimes the friendship fades too; for the lover no longer finds pleasure in seeing his beloved, and the beloved is no longer courted by the lover.”  Nichomachean Ethics, tr. Terrence Irwin

The asymmetry inherent in the “special” friendship between an erastes and his eromenos is due to the fact that they seek different things from each other, and consequently cannot simply be called “friend” and “friend”.  The erastes seeks pleasure from the eromenos whom he follows, while the eromenos allows the relationship to persist because he sees utility in it – he can get something — whether it be praise or practical gain — out of the relationship.  The most extreme case of this may have occurred in ancient Sparta (somewhat glossed over in 300) where, because children were taken away from their families at an early age to become soldiers, thus dissolving the familial bond, hereditary titles and political advancement were based on the adoption of youths by their more mature elders into these follower/friend relationships.

The asymmetry in these relationships were also a source for amusement in ancient Athens.  Plato writes about it in the Phaedrus, which is at the same time a dialog on seduction as well as a dialog on the nature of the soul.  The humor inherent in Alcibiades’ party crashing in the Symposium and claiming that Socrates is his beloved likewise makes little sense without knowledge of the social context in which it takes place.

“For what is this love of friendship?  Why does no one love an ugly youth, or a handsome old man?”  Cicero

This ancient institution was also the backdrop for the accusation by Mark Antony — reported by Suetonius — that Julius Caesar’s adoption of Octavian, his heir, was based on such a follower/friend relation.

Hell Hath No Fury Like A Lover Scorned

According to Aristotle, the greatest source of instability in erotic friendship occurs when one of the parties misunderstands the nature of the relationship.

“The friendship that seems to arise most from contraries is friendship for utility, of poor to rich, for instance, or ignorant to knowledgeable; for we aim at whatever we find we lack, and give something else in return.  Here we might also include the erotic lover and his beloved, and the beautiful and the ugly.  That is why an erotic lover also sometimes appears ridiculous, when he expects to be loved in the same way as he loves; that would presumably be a proper expectation if he were lovable in the same way, but it is ridiculous when he is not.”

Navigating these relations and understanding how we stand to one another is one of the peculiar games people play on Twitter.  Each user profile provides two numbers that indicate how their role in the Twitter economy: “following” and “followers.”  Today Oprah Winfrey’s Twitter account says she has 1,125,560 followers, but only 14 friends.  She can be considered an extreme object of desire on Twitter – a megalos eromenos.  Other accounts will sometimes show a great disparity in the other direction, with many more friends than followers.  These people might be considered excessive lovers

A third group, exemplifying Aristotle’s notion of moderation, maintain balance between their “following” and “followers” numbers.  These might be thought of as the good citizens of the Twitter economy, since they seek neither to achieve status with the number of their followers, nor infamy through the number of people they are following.  Yet even this third group encounters its own problems.  When the good citizens of Twitter reach out to follow someone, they generally expect to have the favor returned.  If this does not occur, this can cause a certain amount of resentment against the beloved, in part because what was considered an overture of friendship has now been turned into an erotic and asymmetric relationship.

There is also some gaming involved in achieving high “followers” numbers – the number that is the de facto currency on Twitter.  One way to do it is to begin following everyone one can.  If they follow back, then this becomes a solid relationship of sorts.  If they do not, then the follower can later drop the offer of friendship, thus bringing his two numbers back into some sort of balance.

This in turn leads other Twitter account holders to be wary of new offers of friendship.  When it is from someone one does not know, the initial temptation is to simply say yes – and we all have early twitter relationships of this sort with people we do not particularly have any interest in.  Over time, however, we become wiser but less friendly which, in turn, leads to the problem of non-reciprocation resentment on Twitter.

Certain tools offer a way around this.  Rather than feel obliged to read the tweets of all 2000 or so “friends”, some account holders use software like TweetDeck to filter out their friends – in effect forming a circle of close acquaintances within their network of friends.  This isn’t foolproof, however, since if someone following you sends you a quick tweet, they generally expect a reply.  If you don’t reply, this may likewise eventually lead to non-reciprocation resentment – especially if the follower suspects you are filtering them.

The fault is in part due to the technology itself.  A technology that encourages asymmetric friendships will ultimately be based on relations of pleasure and utility rather than on Aristotle’s ideal of friendships based on the admiration of virtues.  This in itself is not a bad thing, but it lacks one of the central aspects of true friendship:

“In this noble relationship, services and benefits, on which other friendships feed, do not even deserve to be taken into account . . . For just as the friendship I feel for myself receives no increase from the help I give myself in time of need, whatever the Stoics say, and as I feel no gratitude to myself for the service I do myself; so the union of such friends, being truly perfect, makes them lose the sense of such duties, and hate and banish from between them these words of separation and distinction: benefit, obligation, gratitude, request, thanks, and the like.” Montaigne

At the same time, these Twitter relationships based on 140 characters at a time may form the basis for true friendships.  The people we follow and are followed by on Twitter may eventually be encountered in real life – at a conference; on vacation – and something more lasting may be formed, much as Montaigne and La Boétie’s friendship began as an acquaintance by reputation.  Even the relationship between the lover and the beloved in that peculiar institution of the ancient Greeks, according to Aristotle, has the potential to bloom into something closer to true friendship, after the initial courtship, if it is based on fondness rather than utility.

“Many, however, remain friends if they have similar characters and come to be fond of each other’s characters from being accustomed to them.  Those who exchange utility rather than pleasure in their erotic relations are friends to a lesser extent and less enduring friends.”  NE, tr. Terrence Irwin

Silverlight 2 and Silverlight 3 side-by-side on Windows 7

I’ve been trying to get Silverlight 2 and Silverlight 3 to run side-by-side on my OS for a while.  Amy Dullard has an interesting set of scripts to facilitate this – in effect, the scripts uninstalls the Silverlight 2 tools and replaces it with Silverlight 3 tools if you want to upswitch, then performs the reverse operation if you want to downswitch from Silverlight 3 to Silverlight 2.

This was time consuming in Windows XP.  It turned out to be impossible for me in Windows 7 (64-bit).  I received one of the mysterious install errors: 0x80070643.

Here are some descriptions of the issues and possible workarounds (which did not work around me):

http://silverlight.net/forums/t/66253.aspx

http://blogs.msdn.com/rjacobs/archive/2009/01/22/windows-7-and-silverlight-installer.aspx

Fortunately, Windows 7 has the XP Mode feature, which is basically a hardware-based virtualization platform with a license for the Windows XP operating system.

It is an add-on for Windows 7 that must be downloaded.  Thanks to a former Magenic colleague, I have a premier subscription to MSDN.  To run XP Mode, you must install two beta products: Windows Virtual PC beta and Windows XP Mode beta.  These can be downloaded from MSDN Subscriber Downloads |Applications | Windows Virtual PC.

Once I had both of these installed, set up the BIOS to support virtualization, and then installed my development software on the XP image, I found that my host OS now had several interesting new entries on the start menu.

startmenu

Besides being able to open up my virtual instance of XP, I also can access each application installed on my virtual PC.  Behind the scenes this is still running my virtual machine, but it appears as if I am running an application in a special “XP Mode” since I never have to log into my XP virtual machine and also never see the desktop for it.  Instead, Visual Studio in “XP Mode” simply appears in my Windows 7 task bar next to my Windows 7 instance of Visual Studio.  Furthermore, since I have Silverlight 3 installed on my host OS and Silverlight 2 on the virtual machine, I in effect have a Silverlight 2 instance and a Silverlight 3 instance of Visual Studio running next to each other.

By default, XP Mode runs with 256 Megs of RAM assigned to it.   I had to pump this up to 2 Gigs before I had decent performance.

Here’s a screenshot of the two instances of Visual Studio running side-by-side.  The one on the left has Silverlight 2 running on XP, while the one on the right has Silverlight 3 running on Windows 7.  Notice the lack of glass effects on the left.  I’ve also circled the Silverlight Tools for Visual Studio version numbers as proof (partly for myself) that I can develop against two versions of Silverlight at the same time:

sidebyside

MVVM: UI design patterns in the wild

The Ascent of Man

Microsoft recently dropped an MVVM Visual Studio project template for the WPF Futures release of the WPF Toolkit on Codeplex.  In giving the history the MVVM UI design pattern, the documentation states that “[t]he origins of this pattern are obscure,” making it perhaps the first cryptozoological design pattern, discovered somewhere in the deep jungles of the Expression Blend development team.

MVVM is peculiar for a variety of reasons but the chief is that it does not originate on Martin Fowler’s Bliki as do the MVP and Presentation Model patterns.  Instead it is a found pattern.  Another peculiarity of the MVVM is that, unlike PM or MVP, it is not technology independent.  It is specifically targeted at XAML-based technologies, WPF in particular, and consequently tends to be described in concrete terms rather than abstract principles.

For me this is a strength of the MVVM pattern, since we don’t have to keep going back to a canonical document to find out if we are implementing the pattern correctly.  In fact, for a long time, if you implemented a UI design pattern in WPF, you could pretty much be assured that you were using a variant of the MVVM.  After all, who is going to correct you?

Without a canonical pattern document, however, we are very dependent on example code to find out how other people are doing it.  Currently my two favorites are Josh Smith’s WPF example http://msdn.microsoft.com/en-us/magazine/dd419663.aspx and Shawn Wildermuth’s Silverlight 2 example http://msdn.microsoft.com/en-us/magazine/dd458800.aspx .  It is especially interesting to contrast these two examples since many implementation details found in Mr. Smith’s example code are either impossible to implement in Mr. Wildermuth’s Silverlight example or simply not implemented.

Two key differences are the way Views are associated with ViewModels and the way the ViewModel encapsulates behavior.

In associating Views with ViewModels, it is important to remember that there are always top level Views and dependent Views as well as top level ModelViews and dependent ModelViews. 

On the UI layer, a WPF Window type serves as a container for various WPF UserControl types.  In the MVVM ontology, both are considered to be Views.  Because the structure of a ViewModel is closely associated with the structure of its View (ViewModel is, after all, intended to mean the Model of the View), this container-dependent object structure must be mirrored in the structure of the ViewModel.  If there is a top level View, then there must also be a top level ViewModel.  The top level ViewModel must, in turn, serve up additional objects and collections that correlate with the UserControl Views contained by the top level Window View.

Associating your ViewModel with the top level View

Gluing Views to ViewModels occurs differently for top level objects and dependent objects.  For top level objects, this binding is accomplished by setting the top level View’s DataContext property to its ViewModel.

Josh Smith’s code does this programmatically in the app class:

    MainWindow window = new MainWindow();

    var viewModel = new MainWindowViewModel();

    window.DataContext = viewModel;

    window.Show();

 

Shawn Wildermuth elegantly accomplishes this in XAML using Binding to set the DataContext of the View to a ViewModel loaded as an object resource:

 

Associating dependent ViewModels with their respective Views

We do not have to set the DataContext of any Views contained in the top level View. Once the top level DataContext is set, any elements on the container View should be aware of any public properties exposed by the top level ViewModel, since they will automatically inspect to visual tree in order to find a DataContext. 

Subsidiary Views are associated with properties on the top level ViewModel using DataTemplates and ContentControls.

In Josh Smith’s code, a  ContentControl is placed on the top level View in order to set an anchor for the association between the UserControl/View belonging to the top level View and the CollectionProperty/ViewModel belonging to the top level VM.  Here is a somewhat simplified version of what he does:

 

The HeaderedContentControl is combined with a TabControl are simply present to control how data is generally displayed.  The significant feature in this code is the binding on the Content property, which anchors the Workspaces property of our main ViewModel to this location.  In this case, the Workspaces property is an ObservableCollection of Workspace ViewModels:

        public ObservableCollection<WorkspaceViewModel> Workspaces

        {

            get

            {

                if (_workspaces == null)

                {

                    _workspaces = new ObservableCollection<WorkspaceViewModel>();

                    _workspaces.CollectionChanged += this.OnWorkspacesChanged;

                }

                return _workspaces;

            }

        }

Once the property is anchored, the appropriate View can be mapped to using a few WPF tricks:

 

In WPF DataTemplates normally have keys and a ContainerControl specifies the DataTemplate that will be applied to it based on those keys. By using the DataType property of a DataTemplate rather than setting a key, we invert this convention and let the DataTemplate determine what types of data it will be applied to.  In this case, we specify that this DataTemplate should be applied for any control with a Data Source of type WorkspaceViewModel.

You will also notice that instead of embedded Xaml inside the DataTemplate definition, we instruct the DataTemplate to apply a UserControl called AllCustomersView to WorkspaceViewModel.

There are some advantages to doing this.  First, Xaml embedded in the DataTemplate has no code-behind file whereas a UserControl does.  If you envision needing additional code to support your View, then this is a good route to go.  Second, UserControls are much easier to find in a Visual Studio solution than blocks of Xaml in a resource dictionary.  This makes UserControls a much better unit of work for organizing and maintaining code.  Finally (and this isn’t as trivial as it sounds) it gives us something we can call a “View” in the MVVM pattern.  WPF is so powerful, and allows us to do so many things in so many places, that it is useful to work with a View that can be treated as a fixed point around which we develop our applications. 

In Silverlight, sadly, DataTemplates can only be applied using named keys.  In Mr. Wildermuth’s code, the GameDetailsView UserControl is simply dropped into a Grid without the indirection of typed DataTemplates.  The Grid’s DataContext is then managed in code behind.

Another interesting feature of Mr. Wildermuth’s sample implementation is that he exposes raw Model objects.  While Mr. Smith’s implementation is careful to never expose Model objects, it could certainly be done without any obvious adverse affects.  For instance, the Workspaces property in Mr. Smith’s code exposes an ObservableCollection of WorkspaceViewModel objects.  It could just as well expose a collection of Customer objects, which is the type that WorkspaceViewModel encapsulates using containment.  This would affect our View code to the extent that we are using a keyless DataTemplate and must specify a type.  Had we chosen to specify a keyed template from the ContainerControl, however, then changes to the type of the collection would be transparent to our view.

The main advantage of wrapping our model objects in ViewModel objects is that we can coerce type conversions in the ViewModel rather than using TypeConverters in the binding in our XAML.  In general, a level of abstraction can always be useful.

The downside to using a ViewModel wrapper around our models is that in simple implementations we are simply duplicating each property of our Model object in the ViewModel.  This is a bit smelly.

How you implement MVVM will likely depend on your general coding tastes.  Some people like to encapsulate as much code as possible, while others prefer not to introduce abstractions unless they are actually required to accomplish a given task.  If you don’t use typed DataTemplates to apply your View to your ViewModel, then you have some flexibility in this regard.  The properties of your top level ViewModel can initially expose raw Model objects.  Should the need arise, you can later encapsulate your Model in a ViewModel without impacting the View.

Adding behavior through the Command infrastructure

Simply associating the View and the ViewModel in WPF takes care of data synchronization, assuming that your ViewModel implements INotifyPropertyChanged.  The other aspect of making the MVVM pattern work involves handling events on the View. 

In the MVP pattern, the Presenter typically handled events thrown by the View and routed them to the correct Presenter methods.

In MVVM binding is used on the View to associate events with actions on the ViewModel.

In Josh Smith’s code, this is accomplished by using DelegateCommands.  A DelegateCommand implements the ICommand interface and has an Execute method.  The Execute method, in turn, calls a delegate that has been associated with a specific DelegateCommand.  In Josh Smith’s code the DelegateCommand is called a RelayCommand.  There is an implementation of it provided in the Prism framework, as well as one in the MVVM Project Template included with WPF Futures.

To use DelegateCommands, you just need to first expose a property on your ViewModel of type ICommand.  Internal to the method a DelegateCommand instance is referenced that delegates to a private method on the ViewModel.  Here is a sample implementation from Josh Smith’s code:

    public ICommand SaveCommand

    {

        get

        {

            if (_saveCommand == null)

            {

                _saveCommand = new RelayCommand(

                    param => this.Save(),

                    param => this.CanSave

                    );

            }

            return _saveCommand;

        }

    }

 

The interesting part is how we bind to this property in our View.  In WPF controls typically have a default event that can be bound to a RoutedCommand by using the Command property.  The Command property, however, can also be bound to a property on the DataContext object that exposes an ICommand instance.

In our case, since the DataContext is already set to the ViewModel, we can simply take advantage of this to set the Command property of a Button to the SaveCommand property on our ViewModel:

There are a few shortcomings with this technique.  First, Silverlight 2 doesn’t support the Command property.  In Mr. Wildermuth’s example of MVVM, in fact, a button.clicked event is simply thrown and handled in code-behind;  the code-behind, in turn, calls a publically scoped method on the ViewModel.

The second shortcoming is that this only works if the default event handled by the Command is the one that you want.  If, in this case, we wanted to handle the right-clicked event, we would be out of luck.

There are several workarounds for this problem all involving creating attached properties to allow binding between control events and ViewModel commands.  John Grossman, who helped to promote the original MVVM pattern, has even dubbed it with its own pattern designation: the Attached Behavior Pattern, which works in WPF as well as Silverlight.

MVVM vs MVP

Technically, most of these binding techniques for data synchronization and behavior binding which are described as “MVVM” could be used in an MVP Supervising Controller implementation.  While traditionally one would hook up events between the View and the Presenter in the Presenter code, this seems a bit unnecessary since the binding works so well.  We aren’t changing responsibility between the Presenter and the View so much as we are simply finding a better way to facilitate this: instead of implementing an event specified in an IView interface, we are specifying the names of certain ICommand properties and allowing WPF to automagically hook it up for us.

As for data synchronization, while MVP Views typically know about model objects, there is no reason we couldn’t wrap model objects in containment objects just as, conversely, there is no reason we can’t expose raw model objects in MVVM rather than wrapped objects.

In the Prism sample implementations of the MVP pattern, moreover, the Presenter is often set as the View’s DataContext.  These similarities can make it difficult to distinguish between the two patterns in their wild habitat.  For instance, if you look at the source code for Scott Hanselman’s BabySmash application, you might be inclined, as I am, to identify it as an implementation of the MVVM pattern rather than the MVP pattern.

The key difference seems to be that in MVP the Presenter holds a reference to its correlate View, while in MVVM this is not the case.  In MVVM the ModelView/Presenter is unaware of the View that is being applied to it.  A typical Prism implementation of the MVP will look something like this:

    EmployeesPresenter presenter = this.container.Resolve<EmployeesPresenter>();

 

    IRegion mainRegion = this.regionManager.Regions[RegionNames.MainRegion];

    mainRegion.Add((UIElement)presenter.View);

In this case, dependency injection is used to pass a View object to the constructor of the Presenter.  The Presenter then sets its View property to this parameter value and ultimately returns it to the UI.

With the public View property on the Presenter, we are in the world of the MVP pattern.  Without it, we are probably in MVVM land.

A good way to differentiate patterns is to consider how and why they were developed in the first place.  The original concept behind the MVP pattern was to separate the View and the Presenter in such a way that the View had as little responsibility as possible. 

In the Passive View flavor of MVP, we weren’t even allowed to use the native binding provided in ASP.NET and WinForm development.  Instead, the Presenter was expected to populate each field on the View manually.

The Supervising Controller flavor of MVP, on the other hand, allowed us to provide a Model property on the View which the Presenter was responsible for populating.  The View itself, however, was able to bind its fields to this View.Model property itself.  This flavor of MVP gained popularity in large measure because it seemed silly not to use built in tools like binding for ideological reasons when it made development so much easier.

In WPF, we also have the ability to bind control events on the View to delegates on the ViewModel.  We could choose to wire these up manually if we wanted to, but again it seems strange to do this – and potentially introduce more errors – when WPF binding makes it unnecessary.

Set side by side, these three patterns resemble a child as it grows up.  In the Passive View pattern we are dealing with an infant and the Presenter is expected to feed and clean it.  I’ve tried letting infants feed themselves and it only leads to disaster.

In the Supervising Controller we allow the View to consume its own data, but we still take care of tying its shoes and any other details of hooking it up that are required.  It is still a toddler, after all.

In the MVVM, our baby has grown up.  Our View not only feeds itself but it also picks out its own food and ties its own shoes.  We don’t even have to keep an eye on it every hour of the day.  We can assume that it has a great degree of autonomy and can just come pull on our shirtsleeves if it runs into any problems.  It still needs to be aware of us, but we don’t need to be constantly aware of it.

For the most part this is where we want to be with regard to Views, but it comes at a cost.  When we place more code in our View we also make that code inaccessible for unit testing.  In WPF this doesn’t seem so bad because our code doesn’t show up in code-behind.  Instead it is marked up declaratively in Xaml.  And it’s mainly the code in code-behind that we care about testing, right? 

MVVM is probably for you if you are comfortable with either of the two following notions: 1) that Xaml isn’t really code, so it doesn’t need to be tested an 2) The whole point of declarative programming is that it behaves predictably, while the goal of unit testing is to capture unexpected behavior, so it doesn’t need to be tested.  If this causes you some discomfort, then MVVM is probably still for you if you feel that the convenience it provides outweighs any testability issues that might be raised – which is where I probably come down on the pattern.

Design Pattern Mutations

Like influenza, a design pattern can mutate over time.  This happens especially when it makes the species jump from one technology to another.

The Prism samples, in addition to the sample MVP implementations, also have an implementation of the MVVM that seems to combine aspects of both patterns.  In this implementation, the View keeps a reference to the PresentationModel, making it look like MVVM, while the PresentationModel also maintains a reference to the View much like a Supervising Controller.

The following code (modified slightly to simplify) can be found in the “Commanding” sample application for Prism:

    public OrdersEditorView View { get; private set; }

 

    public OrdersEditorPresentationModel(OrdersEditorView view)

    {

        View = view;

        view.Model = this;

    }

Best of both worlds?

Gresham’s Law

mox_press

We were working with another consulting group at a client, recently, and to resolve a dispute one of the consultants at the rival firm pulled out his trump card – he had authored a book.  Of the various things that might impress a software developer – certifications, technical blogging, Microsoft ranking, article writing – book authorship is well at the top of the list.  Writing a technical book carries so much metal in part because everyone knows what an extraordinary accomplishment this is.  One not only must demonstrate mastery and facility with one topic, but must be able to maintain this level of loquacity over a dozen or so chapter topics and in the end pull it all together in a fluent manner.  This can be so difficult a feat that for each major Microsoft technology one may find only four or five books each year, each of which, unless it fails completely, becomes a sort of master reference for the topic at hand.

Upon returning to the office, we naturally looked up our friend the author on the Internet.  In researching his bona fides we discovered that he was in fact the thirteenth author on an obsolete Microsoft technology for a technical publisher that, trading on its good reputation, had almost thoroughly trashed its name a few years ago by flipping poorly edited tomes written by laundry lists of authors on hot topics in order to be the first to press.  This publisher at a certain point became notorious for awkwardly photoshopping portraits of the myriad authors of each of their books onto the book covers to give the impression that some of them had ever actually been in the same room together.

This is a shame because many of the early authors with this particular press have gone on to be thought-leaders in the Microsoft programming world and continue to publish important books through other publishers, among them Rocky Lhotka, Dino Esposito, Joe Mayo, Scott Guthrie and Scott Hanselman, to name a few.

This may be a prime example of Gresham’s Law.  Gresham’s Law is a 16th century economic theory concerning currency which states “Bad money drives out the good.”  The general idea is that if a certain currency is in circulation, for instance gold coins, and another is introduced with a lower real value but an equivalent exchange value, for instance copper coins, those with gold coins will end up hording their currency rather than using them to make purchases and consequently the gold coins will be removed from circulation.  For a fuller explanation you might consult the wiki.

I first came across the theory in a book by Albert Jay Nock called The Memoirs of a Superfluous Man (1942) in which the author uses it as the basis for a Rousseauvian theory of cultural decline and progress.  I found out about the book, in turn, from a list Louis Lapham published in Harper’s in the early nineties of his alternatives to the Great Books – Alan Bloom’s pop philosophy book on cultural malaise was a bestseller at the time –  a list which also included Mark Twain’s Life on the Mississippi.  It took me another two years before I was able to track the book down to a small shop in Cambridge, MA where I was visiting my brother (in those times before Amazon.com and the Kindle when tracking down an obscure book was a true labor of love) and read it voraciously as a mimeograph produced for a small class at one of the local universities.

The book is a series of contrarian ruminations on the author’s life and his failure to accomplish anything of general value.  Rather than pursue the sorts of endeavors in public life by which he could have made a name for himself, Nock recounts a dilettantish private life guided by a desire to amuse himself rather than impress others – yet it was a career which left in its wake both a book on Thomas Jefferson as well as one on Rabelais, in addition to various books and essays on politics and pedagogy. 

I have owned two copies of Nock’s memoirs in my life and have managed to give them both away.  Besides the general tone of the book, I remember only two things with any clarity.  The first was Nock’s dismay when he was offered the chair of the newly founded English department of a distinguished university.  Nock regretted turning the position down but he simply found it a bit of a put on to try to teach a subject that anyone could learn by showing up at the public library. 

The second was his attitude towards his alma mater.  He lauded it as possibly the best sort of education any undergraduate could avail himself of – the sort that prepared him for everything and nothing at the same time.  As a sign of his respect for those who taught him, he never returned to his college.  He felt that his teachers would be insulted if, after preparing him to go out into world, he at some point returned to the nest.  Their job, after all, was to push their students forward, not welcome them back.  He consequently found odd the growing trend among his peers and on the part of universities to host sundry homecoming events year after year.

Nock felt himself to be a man out of his own time and, like many people in these circumstances, felt that it was the world that was out of kilter rather than himself.  Because the things valued by the world — specifically America in the 20’s and 30’s — were not the things he valued, he tended to see “progress” as a sort of fool’s errand.  The improvements people tried to make in education and government seemed, through his particular lens, to be merely making things worse and – if those things were the things deemed to be most valuable – then he was a superfluous man.

I lack the skill to evoke Gresham’s Law quite as artfully as Albert Jay Nock does.  I can only apply it in this small case of a particular technical press.  A publisher with a strong reputation, thanks to concerted efforts to cultivate the best young talent available, eventually squandered its capital by going after easy money.   Determining that they could be more successful if they only increased the volume of their output, they lowered the value of their currency by publishing low quality books written in a couple of months by a legion of authors.  In the process they discovered that quality holds its value better than quantity does.

Yet all is not lost.  There is a scene in Elia Kazan’s Viva Zapata! in which Marlon Brando tries to save the Mexican economy by printing his own currency.  While the execution was not the best, the theory appears to be sound, and said publisher can revive its relevance by doing the same.  For instance, there is currently a growing industry of self-publishing on the Internet.  The publisher of the yellow and red technology books can lend its reputation to this trend by publishing the best efforts of would-be authors on Silverlight, Oslo, Azure or any of the other trendy new technologies.  Not only will this help the careers of these authors but, on the evolutionary principle that great things can be achieved given enough time and enough monkeys, something valuable may come of it.  To offset the cost of this effort, the publisher should charge its authors for the right to be published, thus producing a Covey-esque win-win situation.

Even better, said press could do away with the tedium of actually writing a book altogether and offer would-be authors the opportunity, for the right price, to simply have their names appended to the list of authors for one of the books in the back catalog.  After all, in that long list of superfluous authors, what harm would there be in adding just one more?

Alternatives to returning Void: Continued

“If you look long enough into the void the void begins to look back through you." – Nietzsche

Returning types rather than void on methods that do not necessarily require a return value, as occurs in the implementation of the Append methods on the StringBuilder, allows us to do some interesting method chaining in our code.

Bill Wagner suggests doing something similar with collections in More Effective C# .  My examples are a bit more contrived, however.

Suppose – for the sake of the premise if for nothing else – that we have a business requirement to take a decimal collection of prices and then add 6 percent to each collection member.  We could write the following custom collection to do this:

    public class Prices: IEnumerable<decimal>
    {
        private List<decimal> _mySequence;
        public Prices()
        {
            _mySequence = new List<decimal>();
        }
        public Prices Add(decimal d)
        {
            _mySequence.Add(d);
            return this;
        }
        public IEnumerator<decimal> GetEnumerator()
        {
            foreach (decimal d in _mySequence)
                yield return d;
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            foreach (decimal d in _mySequence)
                yield return d;
        }
        public Prices AddSixPercentAndWrite()
        {
            foreach(decimal d in _mySequence)
                Console.WriteLine(string.Format("{0:C}",d * 1.06m));
            return this;
        }
    }

Which we would then call thus:

        var prices = new Prices();
        for(decimal d = 0; d< 20m;d++)
        {
            prices.Add(d);
        }
        prices.AddSixPercentAndWrite();
 

The business is initially happy with this, but then comes back a week later to say that the six percent tax is nine percent in a different store. Additionally, while sometimes the business wants to see the final price, they also sometimes want to see the original price alongside of it. 

Besides our original output, we now also need to be able to push a list that looks something like this:

$0.00 $0.00

$1.00 $1.06

$2.00 $2.12

$3.00 $3.18

$4.00 $4.24

$5.00 $5.30

$6.00 $6.36

$7.00 $7.42

$8.00 $8.48

$9.00 $9.54

$10.00 $10.60

$11.00 $11.66

$12.00 $12.72

. . .

Seeing where this is headed, we realize that to handle all foreseen and unforeseen scenarios, we should come up with a way to chain up our methods in order to make the code more flexible.

We could restructure the AddSixPercent method to take a parameter; we could then break out the Write method so we can call it multiple times if needed.  We could also change the signatures on our methods to return our Prices collection instead of void, allowing us to chain the methods together.

There’s a hitch, however.  While returning Prices would allow us to do some chaining, we still wouldn’t get the right results since each method would iterate through the whole collection before returning.  Consequently we would end up printing out all the items in the first column before getting around to printing the items in the second column (the calculated cost with tax), which isn’t what we want at all.

. . .

$12.00

$13.00

$14.00

$15.00

$16.00

$17.00

$18.00

$19.00

$0.00

$1.06

$2.12

$3.18

$4.24

$5.30

$6.36

$7.42

$8.48

$9.54

$10.60

$11.66

$12.72

. . .

By using iterators, on the other hand, every method in our chain would act on a particular iteration rather than on the whole sequence.  Besides getting the output that we want, this would also happily give us much more efficient code since we only have to iterate through our collection once rather than once per chained method call.

If we are to use iterators, however, we can’t return the Prices type.  Instead we have to return an IEnumerable type.  Leaving the rest of our Prices custom collection class alone, here’s what that new code would look like:

public static IEnumerable<decimal> AddXPercent(IEnumerable<decimal> sequence
    , short percent)
{
    foreach (decimal d in sequence)
        yield return d + (d * percent * .01m);
}
 
public static IEnumerable<decimal> WriteToConsole(IEnumerable<decimal> sequence)
{
    foreach (decimal d in sequence)
    {
        Console.Write(string.Format("{0:C} ", d));
        yield return d;
    }
}

Our calling code, in turn, would look like this:

    foreach (decimal d in Prices.WriteToConsole(
        Prices.AddXPercent(
        Prices.WriteToConsole(
        prices), 6)
            )
        )
        Console.WriteLine();
 

We’ve managed to achieve chaining, but not so elegantly, all things considered.  First, we have to include the name of our Type in order to chain our methods together.  Second, the chaining is done with nested methods instead of the clean With-like syntax I was extolling in the previous post.  Finally, the sequence of activity isn’t particularly clear.  Because we are chaining our methods by using nesting, the innermost nested method occurs first, while the first shall be processed last.

Fortunately extension methods allow us to alter the way our methods are called.  In order to get the sort of syntax we want, we just need to pull our iterator methods into an extension methods class like so:

    public static class PricesExtension
   {
        public static IEnumerable<decimal> AddXPercent(
            this IEnumerable<decimal> sequence
            , short percent
            ) 
        {
            foreach (decimal d in sequence)
                yield return d + (d * percent * .01m);
        }
 
        public static IEnumerable<decimal> WriteToConsole(
            this IEnumerable<decimal> sequence
            )
        {
            foreach (decimal d in sequence)
            {
                Console.Write(string.Format("{0:C} ", d));
                yield return d;
            }
        }
    }

Giving us the results we were looking for:

$0.00 $0.00

$1.00 $1.06

$2.00 $2.12

$3.00 $3.18

$4.00 $4.24

$5.00 $5.30

$6.00 $6.36

$7.00 $7.42

$8.00 $8.48

$9.00 $9.54

$10.00 $10.60

$11.00 $11.66

$12.00 $12.72

. . .

 

We can now call our code like this:

    foreach(var d in prices
            .WriteToConsole()
            .AddXPercent(6)
            .WriteToConsole()
            )
            Console.WriteLine();

This alternative to returning void involves three tricks:

1) Returning an IEnumerable type instead of void.

2) Taking an IEnumerable type as a parameter.

3) Using these signatures in extension methods rather than the custom collection class itself.

If the syntax looks familiar, this is because this is also how LINQ to Objects is implemented.  For that very reason, we could have accomplished similar results by using LINQ:

    foreach(var d in prices
        .Select(d => { Console.Write(string.Format("{0:C} ", d)); return d; })
        .Select(d => d + (d * 6 * .01m))
        .Select(d => { Console.Write(string.Format("{0:C} ", d)); return d; })
        )
    {
        Console.WriteLine();
    }

It’s funky code, no doubt, but I also find it highly compelling.  I know that as I loop through my prices, I am writing out the original price, I add 6 percent to it in the following line, then I write out that result in the final line.  Inside the foreach block, I then perform any follow-up operations: in this case, writing a new line.

Waiting for the Windows 7 Release Candidate

A colleague of mine from Magenic, IM tag Estragon, just IM’d with news that the Windows 7 RC had been released for MSDN subscribers.  I did a quick google search for the official announcement which took me to this Microsoft Partners site https://partner.microsoft.com/US/40084742:

linkpage

I was naturally curious and followed the Download link, which redirects to the MSDN subscription site.  Unfortunately, there was nothing about the RC on the downloads page, which I found very odd.  I kept refreshing the page, hoping something would change, but this is what I continued to see:

downloads

My colleague then IM’d me that he didn’t think he could go on like this.  We’d been waiting for the RC for so long and this was just a remarkable let down.  We began to question our very faith in Windows 7 at this point.  Sure, it looked great in beta, but did we in fact know anything about it?  Was it even worth waiting for anymore.  The rest of the IM chat went something like this:

Estragon says:
I can’t go on like this.
Vladimir says:
That’s what you think.
Estragon says:
If we parted? That might be better for us.
Vladimir says:
We’ll hang ourselves tomorrow.
Vladimir says:
Unless the release candidate comes.
Estragon says:
And if it comes?
Vladimir says:
We’ll be saved.
Estragon says:
Well? Shall we go?
Vladimir says:
Pull on your trousers.
Estragon says:
What?
Vladimir says:
Pull on your trousers.
Estragon says:
You want me to pull off my trousers?
Vladimir says:
Pull _on_ your trousers.
Estragon says:
True.
Vladimir says:
Well? Shall we go?
Estragon says:
Yes, let’s go.

But we didn’t go anywhere.  IM chats are sort of silly that way.  Maybe the RC will come tomorrow.

Alternatives to returning Void

I was playing with the Unity Framework recently when I came across the following C# code sample on msdn:

    IUnityContainer uContainer = new UnityContainer()
        .RegisterType<IMyInterface, FirstObject>()
        .RegisterType<MyBaseClass, SecondObject>();
    MyObject myInstance = uContainer.Resolve<MyObject>();

This looked so much like the VB With syntax that I uncharitably assumed that the authors at MSDN had somehow confused C# and VB.  After all, they had written this the standard C# syntax elsewhere:

    // Create container and register types
    IUnityContainer myContainer = new UnityContainer();
    myContainer.RegisterType<IMyService, DataService>("Data");
    myContainer.RegisterType<IMyService, LoggingService>("Logging");
 
    // Retrieve an instance of each type
    IMyService myDataService = myContainer.Resolve<IMyService>("Data");
    IMyService myLoggingService = myContainer.Resolve<IMyService>("Logging");

C# developers with more than 8 or so years of experience can generally be broken down into two types who are mutually suspicious of one another: those who came up through the VB6 programming ranks and those who came up through C++ or Java.  I did the former, and for the most part have never looked back.  I don’t even get involved in disputes between C# lovers and VB lovers.  They’re both nice language.  I just happen to use the former for most things.

The one thing I do miss from VB, however, is the With command.  It always seemed an elegant piece of syntactic sugar and easier to read when you find code that manipulates the same object repeatedly.  My “you can’t do that on television” moment over the msdn sample code came out of that longing for something I thought I’d simply had to leave behind.

It took me a while to realize that the sample code was taking advantage of a trick that has always been available to C# developers but just not extensively used. (I even had to show it to several colleagues just to make sure I wasn’t just being slow – everyone’s first thought, blessedly, was that it was somehow a VB-to-C# translation mistake.) The trick is that the RegisterType method is returning an IUnityContainer object.  Because a C# statement, unlike a VB statement, can be spread out over multiple lines in the editor until a semicolon delimiter is encountered, the code can be made to take on this VB-ish cast.  In fact, the Append method of the StringBuilder type similarly returns its own container type, making the following code blocks equivalent:

    StringBuilder sb = new StringBuilder();
 
    // this code ...
    sb.AppendLine("one");
    sb.AppendLine("two");
    sb.AppendLine("three");
 
    // is equivalent to this ...
    sb.AppendLine("one").AppendLine("two").AppendLine("three");
 
    // is equivalent to this ...
    sb.AppendLine("one")
      .AppendLine("two")
      .AppendLine("three");

This trick won’t work for properties, of course, but it is still pretty fun, and I’m kicking myself for never having come across it earlier.

WCF REST Starter Kit Complete Twitter Library

 

Source

Binaries

Ingredients: Visual Studio 2008, .NET 3.5 sp1, WCF REST Starter Kit 2

The HttpClient type, included with the WCF REST Starter Kit 2, is intended to make it easier to consume RESTful services.   One of the most widely used publically accessible REST API’s is the one provided by Twitter, making it an obvious target for trying out these new Microsoft bits.

Retrieving statuses from Twitter, as well as sending updates, is extremely easy using the WCF REST Starter Kit, as I posted earlier.  This led me to want to see if I could build out a client library for the rest of the Twitter REST API. 

This projected one night effort ended up taking about a week and a half over several evenings.  For the most part, this was because actually building and testing the various contract objects is remarkably labor intensive.

The Windows Twitter Foundation (source code and binaries above) can be used as a reference application for anyone trying either to build a client on top of twitter or for those simply interested in seeing a relatively complicated implementation of the WCF REST Starter Kit.

If you want to just consume the binaries, you will need to download the WCF REST Starter Kit Preview 2 separately, if you haven’t already done so, and include the following assemblies in your project – Microsoft.Http.dll, Microsoft.Http.Extensions.dll, and Microsoft.ServiceModel.Web.dll .

The Windows Twitter Foundation library has several features I’m rather proud of:

1. It reads both XML and JSON formats.  The client application included with the source code switches between these two API’s with either the /XML command or the /JSON command.

2. The library covers the complete Twitter REST API, including direct messaging and photo uploads.  The photo uploads are particularly finicky and took a couple nights alone just to figure out.

3. The library also consumes the Twitter Search API.  The data contracts for Trending was a bit too strange for me to figure out, however.

4. The CLR classes used for deserializing Twitter messages is included in a separate assembly.  They are decorated for both XML and DataContract deserialization.  If you are building your own Twitter client and are running into problems figuring out how to cast the Twitter messages, then these should help you out without obliging you to sniff out all the messages coming from Twitter in order to figure out their structure.

5. I built most of it in my installation of Windows 7.  Visual Studio worked like a charm.

Things I feel bad about:

1. I couldn’t figure out how to deserialize the Trends service messages. 

2. I used waaaay too many yellows and greens in the Console Application that comes with the source.

Please use this code freely and in any way you like.  Be sure to consult the WCF REST Starter Kit 2 license on codeplex for any rights reserved by Microsoft.

Future plans:

I would like to expand the library with additional wrappers for tinyurl and tweetpics and all the other little services that make up the Twitter ecosystem.

I also plan to add helpers to support caching downloaded tweets and manage service calls to lighten the load on the Twitter servers (as the public API documents recommend).

My immediate goal, however, is to start building a nice WPF UI around the Windows Twitter Foundation library (if you haven’t gotten the joke about the name, yet, just give it a moment).

I’ve been enjoying the TweetDeck client, but so far haven’t seen anything in it that can’t be done using WPF.  I should be able to make a UI that is at least as attractive (glossy black controls are pretty straightforward in PF, right?).  Then I want to extend that design with carousels and some of the more interesting UI concepts that are part of the WPF development world.  Using Prism would also be fun, but we’ll see.

The big gain in building a WPF client is that it can do things with the OS which are much more difficult in Adobe Air – for instance, hooking into the speech recognition features of Vista and Windows 7.  Enabling users to start talking instead of typing their tweets may have interesting ramifications if it ever catches on.  For myself, however, it will simply give me an excuse to start digging into speech recognition in Windows 7, which I hear works extremely well.

The next few posts will cover some of the more interesting things I found while digging through both the Twitter REST API as well as the WCF REST Starter Kit – for instance, that the HttpClient class isn’t actually based on WCF, but is instead a wrapper for the HttpWebRequest and HttpWebResponse objects – or that the Twitter API embodies some strange notions about what a “friend” is and what  a “follower” is.

Again, enjoy the code.