Accounting for Cost of Sales with Currying

I have a quick question for you. If you’re selling a widget for $100 and the local sales tax is 8%, how much should you add to the cost of the item to cover the sales tax? If you said $8 or 8%, you’re losing money. To the tune of 64 cents a sale. (Do the math, 8% of 108 is $8.64.)

What’s 64 cents you ask? Over a hundred sales it’s $64, over a thousand it’s $640. And over a million sales it’s $640 thousand dollars! Granted, in the process of losing that 640 thousand dollars, you’ve made $108 Million in pre-tax revenue. But more than half a million dollars in lost profit is nothing to scoff at either. But that’s what every POS system out there does. I’ve just checked in the code for Azure POS (the Silverlight/.NET 4/Azure exemplar I’m developing for my Mix content submission) that does it right. The functionality gave me a good opportunity to demonstrate simulated currying in C#.

Indian Food, Lambdas, and Sales Tax

Currying is a feature of most purely functional languages (named after Haskell Curry) whereby a function that takes two parameters is transformed into two functions, the first function takes the first parameter and returns the second which takes the second parameter and returns the result. In fact most functional languages, multi-parameter functions are at their core represented just as that. To clarify let’s look at declaring a multi-parameter function in F#:

let applyTax(taxRate:double) (amount:double)
  //insert computation here and return result (declared as a double
  result;;

In C# this is equivalent to

public double applyTax(double taxRate, double amount)

Well not really. There’s a significant difference between the two and this is where currying comes in. The declaration in F#, when entered into the F# Interactive will give the following output:

val applyTax : double->double->double

This is read as “the value applyTax is a function that takes a double that returns a function that takes a double that returns a double.” So for instance if you know the tax rate (say .08) you can pass it to applyTax and have a handle to a function that will take the amount and apply an 8% tax to it. F# is pretty cool like that.

Getting Func<e> With It

So how can we do that in C#? Simply make an overload of ApplyTax that returns a func<double,double>

public func<double,double> ApplyTax(double taxRate)
{
    return (amount)=>{ApplyTax(taxrate,amount);}
}

Now I can create variables for the different tax rates at my various retail stores

var applyCookCountyTax = ApplyTax(.10);
var applyLakeCountyTax = ApplyTax(.08);

This is the plight of retailers in the Chicagoland area. There is a 10% sales tax in Cook county. That means you’re paying $20 more to buy a $1000 TV in Cook County than in Lake County and retailers close to the county line lose sales to this disparity. In reality you’d probably store the functions in a Dictionary rather than holding them in individual variables.

var taxAmount = store.TaxTable[“Cook”](100);
//taxAmount =8.70

The Secret Sauce

The solution to the question is simple algebra let x equal the amount of the sale and z be the tax rate you need to find y such that when x and y are added, multiplied by z and subtracted from their sum you get x.

x+y – z(x+y) = x
x+y – zx – zy = x
y-zy = zx

Given x and z solving for y is trivial. Now you can wear a smug smile when you make a purchase at Best Buy knowing that you’re not footing the bill for sales tax. That is until you realize that the REAL sales tax is the markup they add over their wholesale price for that TV you just bought.

Extra Credit

Wes Dyer has an interesting post about simulated currying in C# on his blog. Also I’d imagine that using dynamics it might be possible to declare a base class that auto curries any functions declared in

The Pomodoro Technique

I was going to talk about how my digital cleanse reminds me of a macro scale Pomodoro. Then I realized that I never really talked about the Pomodoro Technique. The Pomodoro Technique is a method for getting organized and being focused. It is a time management system created by Franesco Cirillo. I’m going to let him tell you how he came up with the concept:

One day in the classroom on campus where I used to study, I watched my classmates with a critical eye, and then looked even more critically at myself: how I got myself organized, how I interacted with others, how I studied. It was clear to me that the high number of distractions and interruptions and the low level of concentration and motivation were at the root of the confusion I was feeling.

So I made a bet with myself, as helpful as it was humiliating: “Can you study – really study - for 10 minutes?” I needed objective validation, a Time Tutor, and I found one in a kitchen timer shaped like a pomodoro (the Italian for tomato) – in other words, I found my “Pomodoro”.

So the basic concept is to take a block of time and devote it solely to a single task. Rather than saying “I’ll work on this task until it’s done” you say “I’m going to work on this task and ignore all distractions for X minutes. Then I will stop for a quick break. And work on it for another X minutes” The key to the Pomodoro is working within a box of time and then stopping to integrate what you’ve done up to that point. The break is just as important as the time box. Taking a break allows you to evaluate what you’ve done on the task up to this point. Cirillo recommends 25 minute time boxes with a 5 minute break.

Dealing with Interruptions

Invariably, when working on something, an interruption will occur. Someone will stop by your desk, your phone will ring, an IM will pop up, an email will arrive in your inbox, or your twitter client will chirp to alert you to a new tweet. Some of these can be avoided altogether turn off alerts for email and twitter; set your phone to DnD (send straight to voicemail or mute the ringer if you don’t have built in DnD); set your IM client not to disrupt you (use trillian to provide a nice auto-response saying you’re busy to help avoid offending someone who feels you’re ignoring them); and close your office door. Don’t have an office door you say. It’s still possible to address that issue. Just look at your timer and say “I’m busy right now can I get back to you in X minutes” and put your headphones back on that obviously didn’t provide a big enough hint that you didn’t want to be disturbed.

The standing rule is that if you can address the interruption within 15 seconds, you haven’t invalidated your Pomodoro.

That Five Minute Break

Remember that co-worker that tapped you on your shoulder 15 minutes ago? Follow up with him. Check your email, look at twitter, look up the name of that class that you needed to use for the matrix transform, take a five minute stroll around the office, get some water, go take a bathroom break. Do whatever it is you need to do just STOP WORKING ON WHAT YOU WERE DOING!

Multi-Pomodoro Tasks

No one is telling you to break down your tasks so that they all fit within a single Pomodoro. That’s as crazy as a soup sandwich. What the time box allows you to do is switch contexts if need be. Say the annoying co-worker (who sent an Email, IM, and Voice Message within the 25 minutes but still didn’t get the hint) alerts you that the client wants the header to be Teal instead of lime green and they need that update within the next hour (“make it 45 minutes since the hour started when I came to your desk”). You can reprioritize and use the next Pomodoro to make the lime green header teal.

The Activity Inventory

So how do you get these tasks? Just like lean and agile software development processes use a backlog for tasks that aren’t currently being performed, the Pomodoro technique uses an activity inventory. In addition because of the fine grained nature of Pomodoro there is a more localized activity inventory sheet: To Do Today. It’s just like it sounds, it contains the activities that you plan to do today. When a task arises (for instance that lime green header switch) add it to the appropriate activity inventory. For something that must be done today add it to the bottom of the to do today inventory. For something that can wait until another day put it in the general activity inventory.

A Lot More to It

Those are the basics, but there’s a lot more to the Pomodoro Technique. A key point to the technique is to eliminate interruptions. It gets easier with time. Practically everyone I’ve spoken to who uses the technique has marveled at how much more productive they have become. Just as important to the boxed time of focus is the break. The break allows you to “integrate” what you’ve done. Take a breather and note your progress. Think of it as a waking nap. As you advance the technique helps you go from recording how long tasks take in terms of Pomodori to estimating how many Pomodori a task will take. There are even practices to allow you to measure estimates against actuals and adjust your future estimates accordingly. In other words, it allows you to gauge you personal velocity.

Back to the Digital Cleanse

On a larger scale, my digital cleanse is like my break between Pomodori. It allows me to remove myself from my day to day and take a quick breath. I liked it so much that I will be starting each month with a DC. Looking at all I did with my last one, who knows what will happen this round.

Posted by Mike Brown | with no comments

Welcome to 2010

Yes I know I’ve already posted twice on here this year (more on that later). But this is my first post coming out of my Digital Cleanse. What did I do in that week away from twitter, facebook, and all the tech “news” sites like engadget, joystiq, etc.?

  1. Incorporated a company
  2. Finished the second book of the Icewind Dale Trilogy (I started reading that book 3 years ago and was only on the third chapter)
  3. Designed two inventions…one of which I will perform a patent search and if it’s clear file a patent
  4. Wrote high level visions of seven software products two of which I am combining into a single solution and developing
  5. Spent quality time with my girls every evening.
  6. Lost 12 pounds
  7. Got more organized
  8. Got my MVP Award renewed (this wasn’t the result of anything I did this week but rather over the course of last year)
  9. Reconnected with my network
  10. Celebrated my Grandmother in law’s 85th birthday.
  11. Posted twice to my blog in one week. (Three times if you count today).
  12. A few other things I’m not allowed to mention.

All in all it’s been an INCREDIBLE week. I’ve never felt so energized before. And there’s only more to come.

What I Learned

image

By forcing myself to forgo twitter and facebook and essentially “mindless” browsing, my mind had to fill the void somehow. It craved the stimulus that constant updates and bite sized nuggets of news used to provide. Fortunately, just before Christmas, I purchased a bunch of Piccadilly notebooks. I know Moleskines are all the rage, but I have a frugal mindset right now and these guys were heavily discounted at Barnes and Nobles. But I did see a really nice day planner Moleskine that caught my eye, I passed on it. One I selected to be my idea book (a soft covered ruled small notebook), another my journal and meeting note taking book (hard covered small graph paper), and a third is my design book (hard covered large graph paper). I feel naked without them. The first one that makes a Pomodoro notebook has a customer for life.

I bought some extras for my wife as well and showed her the pocket in the back where she can stuff all the receipts she likes to collect. She’s sticking with her other notebooks for the time being. But she does comment when she notices me opening my notebook “Uh-oh he’s pulling out the Piccadilly.”

I’ve decided that going forward, I will confine my usage of twitter to a set time each day. Facebook, it’ll be relegated to pure casual time. There’s not much there for me business wise. Most of my business socializing is through linkedin or Twitter. I’ve never really done the myspace or any of the other pure “social web” sites. Frankly, I don’t have the time.

Right now, I look at my time as an investment that is worth more than money. If I’m not doing something that gives me a return on that investment, I damn sure better enjoy it. Twitter in moderation is a good investment. Spending all day checking out your tweet stream isn’t (not that I really did that, but I spent more time than I care to mention with twitter open and having it closed for seven days made it patently obvious that there are better things that I can do with my time.

What did you do with your Digital Cleanse? If you didn’t do one, what are you waiting for?

Posted by Mike Brown | 3 comment(s)

The Duct Tape Programmer Revisited

Not too long ago, I responded to the reaction that many had to Joel Spolsky’s article “The Duct Tape Programmer”. My belief still remains that people missed the point due to the unfortunate titling (as well as the severe dating of the technologies mentioned). I think it might make the meaning of “duct tape programmer” more apparent to contrast the duct tape programmer with his antithesis: the bright shiny guy. And what better way to do that than with a case study: 3D Realms and Duke Nukem Forever.

Now for those who don’t know, Duke Nukem Forever was originally announced in 1997 as the follow up to wildly successful Duke Nukem 3D. How successful you ask? Duke Nukem 3D was self-published by 3D Realms and sold around 3.5 million copies. It doesn’t take a rocket scientist to realize that 3D Realms was sitting on a boatload of money. And therein lies the problem. Because 3D Realms was self financing development of Prey (which finally saw release a few years ago) and Duke Nukem Forever, they had full control over time and budget. 12 years later, 3D Realms threw in the towel and closed their doors.

The tragic thing is that Duke Nuke Forever had been “completed” five times over in those 12 years. Unfortunately just as they should have been marching toward development, George Broussard would see a new “must have” feature for Duke Forever demonstrated in a new engine. Instead of passing on that bright shiny object for this time and pushing on to release, he would have the team rebuild the game on the new engine. There are at least 4 documented instances of this occurring.

And that my friends is the difference between Joel’s Duct Tape Programmer and the Bright Shiny Guy. The duct tape programmer doesn’t give a damn about that new high resolution snowflake modeling, he wants to ship the product so he can start the next version using the high res snowflakes. That is why I wanted to be the Duct Tape Programmer. You go ahead and use products that are barely released on your enterprise critical system. I’ll use the tools that I’m familiar with. You can argue that the new stuff is sexy. What’s really sexy to me is shipping a product.

And in the end that’s what our job really is. Just ask the former developers at 3D Realms.

Posted by Mike Brown | 2 comment(s)

RIAlity TV

I am creating a video blog designed as a reality TV show called RIAlity TV. (Actually I'm designing it to be a Channel of RIAlity shows). The first show called "The Project Room:Catching the Wave" will document creating a software product from start to finish using the .NET 4 stack top to bottom.

Silverlight 4

MEF

WCF RIA Services

Entity Framework v2

Windows Azure

SQL Azure

The project will be a Point of Sale system (AzurePOS) designed based on the first example from Peter Coad's Object Modeling book. The goal is to have a V1 project ready to launch at Mix10. I've submitted a session to the open call for proposals. I'll recap the season and launch AzurePOS on stage. I’m looking for people interested in joining the fun. Right now I can use the help from people who can fill the following roles:

  • UI Designer: Take a concept and make it reality. Experience with Blend and Sketchflow is a plus. Integrator skills are a huge plus! We're going to put the Developer-Designer workflow through its paces. HTML/CSS/Javascript experience is good as well.
  • UI Developer/Integrator: Work with the designer to bring their vision into the application. Experience with Blend or a crazy XAML skills are a MUST. In addition experience with HTML/CSS/AJAX is helpful. The person in this role should be comfortable with the View Model pattern.
  • Backend Developer: A heads down C# coder who understands good Object Oriented Design. Knowledge of Entity Framework a plus. Experience with RIA Services a HUGE plus.
  • Web Developer: In addition to the main project, there will be some development needed for the RIAlity TV website. ASP.NET MVC 2 is the weapon of choice.
  • Web Content Manager: There’s a lot of content that needs to be edited for the site, experience with video editing is a plus.

If this sounds interesting to you, send me an email (mike.brown at azurecoding dot net) with a subject line “RIAlity TV”. There's a lot of information that I don't want to share publicly but at the very least this will be an opportunity to demonstrate your skills before an audience. I want to have the first episode in the can in time for voting (January 5-15). I’ll explain all privately.

Update:

The sessions are up on the mix site for voting, if you want to see it, add my session to your ballot.

Posted by Mike Brown | 1 comment(s)

What is “Lean”

This one comes from the Lean Startup Circle again. Someone posed the question what is the difference (if any) between capital ‘L’ “Lean” and “lean”. Having had the opportunity to attend a David Anderson presentation on the subject of Lean Software Development, I was sufficiently armed to talk about the subject. Hopefully, I did justice by my instructor but any errors, omissions, or brute handed oversimplifications are purely my own fault. The summary follows. I’ve fleshed out the original email (that I wrote on my G1) to add more background and information.

To understand the origins of “Lean” we need to look at Toyota, for they are the originators of the Toyota Production System which was later referred to as Lean Manufacturing.

Do a quick search on "what we can learn from Toyota". You'll come up with a lot of interesting information. For example, guess how many of Toyota's American employees were laid off over the past decade? Past 20 years? 30? 40? Would you believe that they haven't had a single round of layoffs in half a century (the layoff referenced in the previous link was averted)? We worry so much about preserving "American companies" when in reality Toyota employees more American workers and treats their employees with far greater respect than any of the big three. Rather than laying employees off during thin times they move them to other plants for training and improving their infrastructure (as the Reuters link mentioned, Toyota even went so far as to pay plant workers in San Antonio their FULL SALARY while the lines were shut down). Thus when times are better they have a workforce already trained to face the new challenges of the company.

That’s fine and dandy you may say but what does this have to do with “Lean”? Everything! Toyota’s success goes far beyond their manufacturing processes. It is the entire philosophy at Toyota that still persists to this day even as the largest auto maker in the world. This philosophy can be embodied in one word “Kaizen”. The idea is to make everybody responsible for improving the process instead of dictating how things are done based on theory or “because that’s how we’ve always done things”. To put it simply who is more qualified to identify a better way of laying bricks: the guy baking in the sun who wants to get his work done and doesn’t want to have to fix that section of the wall later; or the manager who hasn’t picked up a trowel in years. Frank Gilbreth, considered the father of Business Process Management based his life’s work answering that very question. Anyway, that’s another post of it’s own we’re talking about the Kaizen philosophy. Enable…correction…encourage employees to take ownership of their work, and opportunities for improved quality AND efficiency will naturally be injected into your process.

Let’s shift gears from Kaizen and talk about Lean Manufacturing. Toyota's approach came from necessity. They had to compete overseas against entrenched competition. There was no way they could establish a dealer network AND a service chain rapidly enough to compete. The solution? Make cars that didn't fail as much. Rather than cut corners to produce cars as rapidly (and cheaply) as possible, they spent the time to make sure they released a quality product that didn't require as much maintenance. There's a reason Toyota has a reputation for making long lasting vehicles...they couldn't afford to do otherwise.

In the same regard, Toyota couldn't afford to pump out cars continuously or build up a large inventory of materials. Thus they devised a system called Kanban to control the flow of supplies. The concept was adopted from observing grocery stores. A grocer can only stock as much product as he thinks his customers will purchase before it spoils or else he wastes the product (and the money spent to purchase it).
Toyota applied this just in time supply to their manufacturing process. And thus Lean manufacturing was born allowing Toyota to go from an upstart foreigner to the largest auto manufacturer in the US. It was a commitment to quality, process, and most importantly PEOPLE that made this possible.

Make no mistake, applying Lean processes alone is not enough to ensure success. You need the right people as well and you need to engender a system of trust and excellence. You need to truly commit to the the principles. Otherwise you're just falling into the cargo cult mentality.

Posted by Mike Brown | 1 comment(s)
Filed under: , ,

Stealth Disease

I am a member of the Lean Startup Circle group (was searching for the Lean Software Group which I still haven’t found). The conversations there are amazing and I highly recommend joining if you’re remotely interested in entrepreneurship (becoming one, helping one, or finding one). Anyway, a fellow group member referenced Eric Ries’ recent interview with tech crunch where he states plain and simple that you’re doing yourself a disservice by having a long term “stealth mode” for your startup. It prompted me to reply as follows:

I think that [keeping your idea a secret] is the first thing to get over as a startup. I see so many people saying, "I'll tell you what I'm doing after you sign an NDA." I'm sorry, I'm not doing that because I might already have the same idea or a similar one and I'm not going to preclude myself from executing on that idea because you might argue I've stolen it from you down the road.

Unless you're talking about some really deep technology that REALLY pushes the bounds of what we do (think Project Natal from Microsof), you most likely aren't the only one doing what you're doing. In fact unless you can name five competitors in your space, you should stop what you're doing and find them. If you are on the lines of Natal, why the hell haven't you filed a patent to protect your work?

The sooner you get a working product that your users can play with. The sooner you can get feedback and in many cases ideas that will significantly improve your product. Going stealth I would argue is a Waterfall startup (opposite of Lean). Think about it in terms of software development. With Lean (or agile) one primary goal is to get a working application in front of your stakeholders quickly so that they can provide feedback as the application is evolving, it avoids the problem of spending a year working on a project only to get feedback at the end from the customer that you totally missed the mark.

If you want to kill a startup, the quickest way is to spend a year developing a product that no one wants because you were in "stealth mode". Especially when your competitor announced their product before it was even available, got feedback on the alpha a week later, and adjusted the trajectory for the beta a month later all the while building a huge viral buzz from previewers who "get the vision" and like it. By the time you've announced a product your competitor has beat you to market without you even knowing they exist.

By letting people know what you're doing, you're likely to get a lot of feedback that you'd pay a lot of money to get otherwise. Such as "this reminds me of...[insert competitor you didn't know of]" or "I'm building something similar, want to team up to make a unified product" or "I like [feature x] but I really wish I could do it by [method y]". All of this feedback can be used to help you adjust your launch trajectory "how can I improve [competitor x's] product", "this guy has a great foundation this would make my product better to integrate our solutions", "it will be simple to add that new method for achieving feature x" to provide a product that better meets your users' needs.

That's the true definition of Lean. And even the largest vendors (think of Google with gMail, Wave, Android, and ChromeOS) can benefit from taking this approach.

Posted by Mike Brown | 1 comment(s)
Filed under: ,

I Want to Be a Duct Tape Programmer

I think people misinterpreted Joel Spolsky's post "The Duct Tape Programmer" (not the best choice of words because of the connotations of using duct tape as a "temporary quick fix" in the developer's mind) but there is one key gem to take away from it.

"Shipping is a feature. A really important feature. Your product must have it"

His point is the same that most of his posts say (and even what the 37Signals guys tout). No one gives a flying fig about how your application uses the latest programming language (or UI engine). What they care about is whether your product solves their problem?

You can spend all day spit shining your API to make it more SOLID, or you can say "the feature works, let's move on to the next one". In the mean time, the company down the road who knows how to get things done has shipped v1 and are getting feedback from customers for V2.

He also makes the distinction between the guy who can pull this off and everyone else. This is the guy who uses techniques at which he is an expert (in the Dreyfus Model sense of the word)  to tackle the task at hand rather than saying "here’s this new wrench (language/Framework) let's see how I can use it on this go cart (enterprise app/web browser) I'm working on." Or to bring it home better would you prefer a surgeon performing an experimental technique on you that he watched some guy perform at a seminar last week when the one he has performed 100 times over will work just as well? That's what Joel means when he says duct tape programming. It might not be made of the shiny new state of the art experimental components. But it sure as hell works like a charm.

No where in the talk did he mention throwing out best practices (okay he does mention not needing unit tests but he also mentions that those were extreme circumstances). In fact he suggests what should be a new best practice: don’t use something you’re not familiar with when your ass is on the line.

I know a few people I would apply the Duct Tape Programmer label to but they would be too modest to accept it. And that’s what I aspire to be.

Posted by Mike Brown | 1 comment(s)

Service Locator Revisited

I guess I have awakened a slumbering giant by writing the post the other day. I went back to add more functionality to the Service Locator (to enable per transaction and per thread services). Before I started breaking stuff by adding new functionality, I decided to make unit tests for the existing stuff. My first test was simple enough, register and retrieve a service from the ServiceContainer (which might need to be renamed because of a collision with System.ComponentModel.Design.ServiceContainer).

[TestMethod]
public void CanRegisterService()
{
    var dummyService = new DummyService();
    ServiceContainer.RegisterService<IDummyService>(dummyService);
    var retrievedService = ServiceContainer.GetService<IDummyService>();
    Assert.IsInstanceOfType(retrievedService, typeof(IDummyService),"The returned service is not of the correct type");
    Assert.AreEqual(dummyService,retrievedService,"The returned service is a different instance.");
}

Simple enough right? Let’s run it and make sure it’s green and move on…to…hey why is it failing? What happened? After a quick bit of investigation, I found that the problem lay in RegisterService overload that takes the Func:

public static void RegisterService<TService>(Func<TService> creator)
{
    _Container.AddService(creator);
}

Do you see it? Maybe the implementation of AddService might make it more obvious

private void AddService<TService>(TService instance)
{
    _ServicesLock.EnterUpgradeableReadLock();
    try
    { 
        if (!_Services.ContainsKey(typeof(TService))) 
        { 
            _ServicesLock.EnterWriteLock(); 
            try 
            { 
                _Services[typeof(TService)] = instance; 
            } 
            finally 
            { 
                _ServicesLock.ExitWriteLock(); 
            } 
        } 
    } 
    finally 
    {
        _ServicesLock.ExitUpgradeableReadLock(); 
    } 
}

Because of type inference, <TService> is Func<TService> when we try to retrieve it we’re looking for TService as the key, and of course we won’t find it. So there’s a lesson to be learned here. Actually there are two.

  1. It’s the simplest of changes that open the door for the most insidious bugs (not that this bug is very insidious)
  2. If it’s worth writing it’s worth testing. No matter how small the functionality is, you should write a test for it because when it breaks you want to know.

Anyway, now that I’ve got the tests in place for the existing functionality, I’m going to go ahead and see about implementing per transaction life management. But not tonight.

Posted by Mike Brown | with no comments

Service Locator Versus DI – A Clarification

Update:

For some reason Community Server decided that it doesn't want to display the style for the code snippet nor the IFrame for the skydrive link. Here is the final file. Read on for explanation of what it is and what it does.

Browsing though the blog of my friend and co-work, Jon Fuller, I noticed this post on Dependency Injection and Service Location. Especially interesting was this quote:

I was having a discussion with a colleague the other day about DI and Service Location in the context of the question (posed by a third person):

Which DI container/framework should I choose?

His answer:

None; just roll your own and use simple Service Location

It definitely sounded like I’m the colleague in question here. He then goes on to argue against my love of the Service Locator pattern. I think I should clarify what I meant with my statement. For reference, here is my code for a simple service locator. The usage is simple, first I register a service with the Container:

ServiceContainer.RegisterService<ICalculatorService>(new ConcreteCalculatorService());

Then anyone who wants an instance of the ICalculatorService can simply ask for it:

var calc = ServiceLocator.GetService<ICalculatorService>();

This method works for a vast majority of the simple cases where you want to provide a Separation of Concerns. In most cases you don’t need advanced lifetime management (e.g. a single instance of a service will do just fine). The reason I suggested rolling their own was that I assumed from the question the person had no experience with an IOC container prior. It takes time to grok an IOC container, there are a lot of moving parts, and for a simple case, this solution works just fine.

So what happens when I want to allow for more intricate cases. Like different lifecycles for service (per request, per transaction, singleton, etc). Well the choice boils down to extending/enhancing your service locator implementation, or using the Common Service Locator library in conjunction with a container of your choice. You have to decide when the cost of maintaining your own outweighs the benefits. Adding support for a per request lifecycle is simple enough as well however. Here are the changes to the Service Container that supports both a single instance and per request lifecycle:

        private TService RetrieveService<TService>()
        {
            Func<TService> retVal;
            _ServicesLock.EnterReadLock();
            try
            {
                retVal = (Func<TService>)_Services[typeof(TService)];
            }
            catch (Exception)
            {
                throw new Exception(
                   String.Format(
                      "Service Type {0} not registered with container.", typeof(TService).Name));
            }
            finally
            {
                _ServicesLock.ExitReadLock();
            }
            return retVal();
        }

        public static void RegisterService<TService>(Func<TService> creator)
        {
            _Container.AddService(creator);
        }

        public static void RegisterService<TService>(TService instance)
        {
            RegisterService(()=>instance);
        }

I just added an overload to the static RegisterService method that takes a Func that returns an instance of the service, I then change the original method to call the new overload and change the private RetrieveService function to do things properly. To register per request, you now make this simple call

ServiceContainer.RegisterService<ICalculatorService>(()=>new ConcreteCalculatorService());

Using the service is the same as before Now let’s address some of Jon’s concerns regarding the alleged shortcomings of the Service Locator pattern.

Some of his concern stems from the API for the service locator. (Why pass in a separate key when you already have a ready made key in the form of the service type. Also, I’m assuming the “movies.txt” is the parameter for creating an instance of the concrete IMovieFinder. Again, this is not an issue because the instance is created at registration (or using the modified version, through the creator delegate).

With regards to testability, when writing a unit test it’s easy enough to configure a Service Locator to return mocks. Just register the mocks in your setup and call clear on your teardown.

That leaves us with discoverability for consumers of your code. Documentation is a good place to start.  Also, to me putting the dependencies in the constructor opens the door for things like this:

var lister = 
  new MovieLister(
    new CsvMovieFinder(
      new AzureBlobFileRetrieval(
        new AzureKey("account","secretKey"));

True this could be caught in a code review. But it can also be outright prevented by using this great thing called encapsulation. When someone creates the MovieLister that uses the ServiceLocator and debugs, they will get a nice friendly message informing them that they need to register an IMovieFinder with the service container (hopefully they know to do so in the Main() function or wherever your project does it’s container configuration).

To me, there is no major detriment to using either style. Rolling your own involves dealing with maintenance of that solution, but it’s easy enough to swap it out with a third-party container once you have the need for it. Here’s the code for my basic service container. A lot of other scenarios are trivial to implement here as well. And I’ll share them with you in a later post.

Posted by Mike Brown | 2 comment(s)
Filed under:

An Elevator Pitch for View Model

I recently gave a presentation on WPF and Silverlight at this year’s Indy Code Camp. During the talk, I gave a brief overview of View Model. After explaining how data binding works within WPF, I had set myself up for the ultimate punch line:

Since we have this rich data binding model within WPF, why not bind our UI to an object that represents exactly what we want our UI to do.

To demonstrate the power of WPF Data Binding and the View Model pattern I walked through a simple RSS Reader that displayed a list of feeds allowing the user to select one and see a list of feed items and selecting one of those select display the page associated with the feed item in a Frame, all using data binding against a View Model object and zero code behind. While one can argue there are easier ways to create a simple feed reader in WPF…the code was tailored to demonstrate the power of the ViewModel pattern. I saw a number of light bulbs turn on in the audience as a result.

Posted by Mike Brown | with no comments

Announcing Alexandria RTW

Release to the World that is. Today at 4:33 PM my wife delivered our newest family member, Khara Alexandria Brown. She weighs in at a healthy 6 pounds 3 ounces and has a modelesque height of 19 and 1/4 inches. Happy Birthday my little princess and many more!

Khara's Birthday 013

Khara's birthday 020

Posted by Mike Brown | with no comments

Blend Behaviors FTW

Update: As promised, here’s the code read below for usage.
AgilityCore.zip

Beyond SketchFlow (THE official coolest thing since sliced bread), Blend 3 has some other great features for improving the designer-developer workflow. Something I like a lot  (and most of my fellow WPF Disciples) are Behaviors.

If you recall, I spent a couple of posts a few years back talking about using attached properties to enable adding functionality to controls without code. Blend Behaviors take the pattern and wrap it in a simple API making it much easier to get down to the business of hacking WPF.

Even more interesting than the standard attached behaviors is the new Trigger system implemented using the pattern. Including the capability of creating custom Trigger Actions. In the initial release of WPF, Trigger Actions were effectively sealed because they are abstract and the function that inheritors need to override is marked internal. This effectively stood in the way of providing a solution to this problem in the MSDN forums.

The new Behavior-based trigger system (which works in Silverlight and WPF) opens the door for custom Trigger Actions. Now that we have custom Trigger Actions, I’m able to create an ExecuteCommandAction that allows you to invoke a Command from any trigger. The code is simple as is its usage.

First we define the trigger action

   1:  using System.Windows;
   2:  using System.Windows.Input;
   3:  using Microsoft.Expression.Interactivity;
   4:  using System.ComponentModel;
   5:   
   6:  namespace AzureCoding.Agility.Core.Behaviors
   7:  {
   8:      public class ExecuteCommandAction : TriggerAction<FrameworkElement>
   9:      {
  10:   
  11:          [Category("ExecuteCommandAction Properties"),
  12:          Description("The name of the Command that will be executed by this Trigger Action")]
  13:          public string TargetCommand
  14:          {
  15:              get { return (string)GetValue(TargetCommandProperty); }
  16:              set { SetValue(TargetCommandProperty, value); }
  17:          }
  18:   
  19:          public static readonly DependencyProperty TargetCommandProperty =
  20:              DependencyProperty.Register("Target Command",
  21:                                          typeof(string),
  22:                                          typeof(ExecuteCommandAction),
  23:                                          new PropertyMetadata
  24:                                              (TargetCommandChanged));
  25:   
  26:          private static void TargetCommandChanged(DependencyObject d,
  27:              DependencyPropertyChangedEventArgs e)
  28:          {
  29:   
  30:          }
  31:   
  32:          protected override void Invoke(object parameter)
  33:          {
  34:              var path = TargetCommand;
  35:              var dc = AssociatedObject.DataContext;
  36:              var targetCommand = 
  37:                  dc.GetType().GetProperty(path).GetValue(dc, null) as ICommand;
  38:   
  39:              if (targetCommand != null && targetCommand.CanExecute(parameter))
  40:              {
  41:                  targetCommand.Execute(parameter);
  42:              }
  43:          }
  44:      }
  45:  }

 

The new Behaviors framework is defined in the Microsoft.Expression.Interactivity namespace (in the assembly by the same name). We inherit from TriggerAction, a descendant of the base behavior class and declare a dependency property for the name of the command we want invoked (lines 11 – 30). Finally, we override the Invoke method from the TriggerAction class. Unfortunately, it appears that Binding does not work for TriggerActions and I haven’t heard if this will be addressed in the final version of the behaviors framework. At least for now we have to get a handle to the target command manually. Once that’s done, we just check that it can execute and then ask it to do so. The code uses the convention that the command resides on the Data Context of the object to which your trigger is attached. I also didn’t bother putting in robust error checking (so if the property doesn’t exist, you’ll get an exception).

image 
Once we’ve built the library and referenced it in a Blend 3 project, we can see our new behavior in the asset library

custombehaviors
Adding it to a target is as simple as dragging it to the objects and timeline panel. From there we’re able to edit the properties using the property editor.

So how do we use it? Well The convention of looking for the Command on the attached control’s data context works very well with the MVVM pattern. So let’s make a simple login control and matching View Model to drive it. Here’s the XAML for the Control

<UserControl
<!-- A bunch of xmlns definitions—> 
> <UserControl.DataContext> <AgVM:LoginViewModel/> </UserControl.DataContext> <Grid x:Name="LayoutRoot" Background="White"> <!-- A bunch of layout definitions--> <Button Margin="0,0,5,0" VerticalAlignment="Bottom" Grid.Column="1" Grid.ColumnSpan="2" Grid.Row="2" Content="Login"> <i:Interaction.Triggers> <i:EventTrigger EventName="Click"> <Ag:ExecuteCommandAction TargetCommand="LoginCommand"/> </i:EventTrigger> </i:Interaction.Triggers> </Button>
<!—More UI code--> </Grid> </UserControl>

There is no custom code-behind for the control. The ViewModel is instantiated in the XAML and all the elements are bound to properties on the ViewModel using data binding. Here is our ViewModel (or the significant parts thereof):

    public class LoginViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public LoginViewModel()
        {
            PropertyChanged += (blank, blank1) => { };
            LoginCommand = new DelegatingCommand
                               {
                                   CanExecuteRequested = param => true,
                                   ExecuteRequested = param => ShowLogin()
                               };
        }

        private void ShowLogin()
        {
            MessageBox.Show(String.Format("Login by {0} successful", _UserName));
        }

Here I’m using the DelegatingCommand to expose an ICommand as a property on my ViewModel. I’ve also exposed a UserName and Password field. Running the application gives us this.

runningthecode

So now we have trigger driven command execution with zero code behind. I’ll upload the code later.

Posted by Mike Brown | 5 comment(s)

Mozilla Lab Concept Series, Aurora, and Flow

Shortly after I started playing around with Flow and put my ideas on paper (or at least digitally), someone pointed me to Adaptive Path’s Aurora Project. The brainstorm that lead to me writing about Flow preceded the publishing of the first Aurora video. I believe that I had created the first prototype before the video was published as well. It was really inspiring to me because I envisioned in Flow many of the concepts demonstrated in that video. What’s very interesting to me is this quote from their site:

This is not a demonstration of a real product. What you see in the video is a visualization of our ideas created by animators. Technologically, much of Aurora would be difficult or impossible to implement today. However, we expect everything you see to be possible in some form in the future.

Their desktop browser concept is definitely feasible, I think the Flow prototype shows this. It wouldn’t be difficult to replace the graphs with  The concept of synchronization across devices is enabled through Live Fx. WPF has a very rich visualization story and almost any data that can be pulled from a web page (for example a table of precipitation data) can be bound and transformed through different visualizations.

I don’t think that “Flow” would ever serve as a primary browser. Or I should say it’s not one of my goals to make Flow a new web browser but rather an Information Browser. In order to make a good browser, Flow would need the capacity of rendering HTML to WPF natively. Hopefully, Microsoft will one day release a native WPF browser control. Or I will attract the attention of an HTML rendering wizard. Until then, web browsing in Flow will be limited by the capabilities of the BrowserControl.

Posted by Mike Brown | with no comments
Filed under:

Static Reflection: Say What?

There’s a new oxymoron going around call Static Reflection. The basic gist is that by using expression trees you can do things that appear to be dynamic but in reality are checked at compile time. Like for instance, getting the name of a property for firing an INotifyPropertyChanged.PropertyChanged event. My colleague, Jon Fuller, showed me his code for Method Guards and my first comment was that this would be a great tool for implementing INotifyPropertyChanged. He informed me that he already went there and showed me that code as well.

I wasn’t too happy with the idea of wasting your sole base class on NotifyPropertyChanged so I suggested that we use extension methods instead. After a bit of finagling with the framework (Events don’t like to be fired from outside their declaring class), here is the result:

        public static void SetProperty<T>(
		this INotifyPropertyChanged source, 
		Expression<Func<T>> propExpr,
		Expression<Func<T>> fieldExpr,
		T value)
        {
            source.SetProperty(
		propExpr, 
		fieldExpr, 
		value, 
		() => { });
        }

        public static void SetProperty<T>(
		this INotifyPropertyChanged source,
		Expression<Func<T>> propExpr,
		Expression<Func<T>> fieldExpr,
		T value,
		Action doIfChanged)
        {
            var prop = 
		(PropertyInfo)
		((MemberExpression)propExpr.Body).Member;
            var field =
		(FieldInfo)
		((MemberExpression)fieldExpr.Body).Member;
            var currVal = (T)prop.GetValue(source, null);
            if (currVal==null && value==null)
                return;
            if (currVal==null || !currVal.Equals(value))
            {
                field.SetValue(source, value);
                var eventDelegate =
			(MulticastDelegate) 
			source.GetType().GetField(
				"PropertyChanged",
				BindingFlags.Instance | 
				BindingFlags.NonPublic).
				GetValue(source);
                Delegate[] delegates = 
			eventDelegate.GetInvocationList();
                var args = new PropertyChangedEventArgs(prop.Name);
                foreach (Delegate dlg in delegates)
                {
                    dlg.Method.Invoke(
			dlg.Target, 
			new object[] 
			{ 
			  source,
			  args 
			});
                }
                doIfChanged();
            }
        }

Now you can use a strongly typed NotifyPropertyChanged declaration without using your base class

    public class PersonStaticReflection : INotifyPropertyChanged
    {
        private string _firstName;
        private string _lastName;
        public string FirstName
        {
            get { return _firstName; }
            set { this.SetProperty(
			() => FirstName, 
			() => _firstName, 
			value); 
		}
        }
        public string LastName
        {
            get { return _lastName; }
            set
            {
                this.SetProperty(() => LastName,
                                 () => _lastName,
                                 value,
                                 () =>
                                     {
		// do something useful here
                                     });
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

For those concerned, you can statically cache the PropertyChanged field in a dictionary mapped to the object type so that you only have to reflect on it one time.

Posted by Mike Brown | 3 comment(s)
More Posts Next page »