WPF MVVM demystified

December 2nd, 2011 / No Comments » / by Amir Barylko

Motivation

Lately I have been hearing a few discussion about using MVVM as a pattern to work with desktop apps when using .NET and WPF.

The first question usually is about justifying the use of the pattern compared to MVC or MVP. It’s all about responsibilities and how the data and logic is organized.

While I’m not going to describe all the differences I want to highlight some important aspects of the pattern when working with WPF applications.

First Highlight: WPF is not WinForms. Why? NO CODE BEHIND!

Second Highlight: What are the benefits of it? BINDING!

Third Highlight: Is binding important when using WPF? ESSENTIAL!

Fourth Highlight: What about generating the M – V – VM? NOT ENCOURAGED, BE CAREFUL!

The good old days with no binding

Before using WPF there was WinForms.

The “idiomatic” way of making the views update in WinForms was either using code behind or letting the controller manipulate the view by knowing which view (or interface) was using, thus creating a dependency between them.

The problem with that approach is that we are breaking encapsulation and assigning multiple responsibilities to classes that should be dedicated to only one of them. Remember, one source multiple views, and all that jazz. We should be able to create new views with no additional pain.

I remember clearly wondering about :

“Wouldn’t be great to have a way to bind my view to some kind of class so I don’t have to keep having controllers that update the text field view when the text changes, etc?”

So I decided to create my collection of binders to make my life easier and look what happened next…

Binding as a first citizen

The next iteration of MS desktop tools brought WPF and the idiomatic way of building views was using Binding! Yay!

Why is so good? Because the views use reflection to know when your source has changed!

What’s the tradeoff you ask? You need to implement a protocol to notify when change happens. Either using INotifyPropertyChanged interface or dependency properties.

“Awesome!” – You say.

“Now I can just grab my models and add the notification, and no more controllers, and…” – STOP!

Wow, slow down….. take a deep breath, sit down… keep reading.

Modelling, abstraction and everything nice

We have clear responsibilities assigned between view and model.

View is in charge of displaying what the Model represents.

Now, because we want to use WPF we should not litter our classes with other responsibilities. Imagine tomorrow we have a different framework, what are we going to do? Change them again?

And here is why the ViewModel makes so much sense.

The class that matches with a ViewModel will provide all the necessary binding fields so they can be displayed in that view or any other view. Multiples views, same ViewModel. Is just binding after all.

No rule, to rule them all

Now, would that mean the we are going to have always an association one to one between Model, View and ViewModel?

Even more, would that mean that all my “Models” are entities populated from an ORM?

Not at all! There’s no rule, just good design and modelling practices.

A ViewModel may use multiple entities, or no entities at all! The fact that the name is Model does not imply necessarily that is a particular kind of class.

Remember, is a pattern, so we identify the components of the pattern and named them accordingly. However patterns overlap, collaborate and some times use each other (sounds promiscuous, I know).

So be careful! Code generation in my experience will bring you more sorrow than happy days!

What classes are you going to generate anyways? How can you be sure before hand what all the models, etc, look like?

Forcing all the objects to inherit base classes because they are all “ViewModels” or “Models” may produce the same result.

There’s no magic bullet or pill you can take.

So what to do? Use binding, will save you lots of time, write some nice code (with tests to add confidence), and then when you have a very clear idea of what are you building and you can justify it, abstract, refactor and generate code or create base classes if needed.

Tags: , , , ,

Meet the Clojure programming language

October 14th, 2011 / No Comments » / by sgalkin

I have the pleasure to welcome Sebastian Galkin as a guest contributor to my blog. I have known Sebastian for some years, since I used to be his manager in one of his first jobs in a software company. At that time he already had a degree in Electrical Engineering and a Masters in Physics under the belt.

I have been always very impressed with how smart Sebastian is, his uncanny thirst for knowledge and how little time he needs in order to learn and get familiar with new technologies.

Sebastian simply excels at sofware development. He is one of the most knowledgeable developers I know and he has been working with Clojure now for more than a year.

I always enjoy to bounce ideas with him to help me realize how wrong I am.

Please read on, I am positive you are in for a treat!

Introduction

In this post I’ll present you with the Clojure programming language. I hope I’ll be able to show you how writing Clojure code feels, and motivate you to dive deeper into it.

If you want to know more about Clojure, you can’t miss the three days hands-on training I’ll be giving in Winnipeg, November 2011.

What is Clojure

Clojure is a general purpose language that runs on top of the Java Virtual Machine or the Common Language Runtime or, even, JavaScript. So, if you already have systems running Java or .NET you can easily integrate Clojure in your workflow.

Clojure inherits powerful traits from the Lisp family of languages, and its ubiquity from the host platform (JVM, CLR, js). It encourages functional programming style and brings to the table a great set of multithreading primitives to make multithreaded programming easier.

You may be thinking: “But I don’t have the chance to use Clojure at work!”, and wondering why you should keep reading. Read a bit more, you won’t regret it.

Here is the secret: Learning Clojure will greatly improve your toolbox as a programmer. You will find that after spending some time reading about it and using it, the way you write code will change dramatically .

If we look at the market, there is a big wave of interest in functional languages, ranging from Haskell and F#, to Scala and Clojure. This is motivated in part by the increased complexity in our systems and the need to embrace multiple hardware cores.


ruby,java,scala,clojure Job Trends graph

This job trends graph shows relative growth for jobs we find matching your search terms
ruby,java,scala,clojure Job Trends Ruby jobsJava jobsScala jobsClojure jobs

Sounds very nice, but where’s the code?

Instead of enumerating the primitives and syntax constructs of the language, lets look at some examples and go over the explanation in detail togeteher.

We will use a simple problem I just made up to showcase some of Clojure features. Here is the problem:

We have a file with words, one word per line. We want to read that file and print all 10 character words in it.

Simple, artificial and useless; but more than enough to illustrate the traits of the language. Read on… read on….

First lets define a constant holding the path to the file:

(def file-path "words.txt")

What’s going on here:

  • Clojure uses Lisp syntax: function calls begin with an opening parentheses, followed by the function name, followed by the
    arguments separated by spaces and ending with a closing parentheses. So, in this case, we are “calling” def, passing file-path and "words.txt" as arguments.
  • As you can see, Clojure uses prefix notation, if we would want to add two numbers we would write (+ 3 4), again start with “(“, then the function name, then the arguments and finally the ”)”. In Clojure + is just a function name, there is no special behavior for operators.
  • def associates or binds a name with a value, it receives two arguments, first the new name, then the value associated with it. So, file-path is the name of the constant we are defining.
  • "words.txt" is a literal string. In Clojure strings are delimited by double quotes.

Now if we use file-path in our code, it will get “replaced” by its value, the string words.txt.

Back to our problem, how do we read the file contents?

(with-open [reader (clojure.java.io/reader file-path)]
  .....
  .....)

Lets peel this onion (fine, orange for you) from the inside out:

(clojure.java.io/reader file-path)

You already guessed this is a function call, because it conforms to the pattern we saw before with clojure.java.io/reader as the function name.

The part of the name before the “/” is just a namespace, don’t worry about it for now, it’s just a function name. What this line does is open a java.io.Reader pointing to words.txt file in the current directory.

A java.io.Reader is a Java object that allows you to read from a stream, in this case, a file. We will use this reader to get all the words from the file.

(with-open [reader ....(1)....]
  .......(2).....)

with-open is a function that binds a name (in this case reader) to a value (in this case the expression (1)), then executes the nested body (in this case (2)), and finally calls the reader’s close method. Inside the body of with-open, the expression (2), you can use the reader variable.

So, why we use with-open? To make sure that it doesn’t matter what happens inside the body, the reader gets always closed.

Short digression:

We just saw new syntax, the square brackets. Square brackets are the syntax for literal vectors in Clojure. [0 29 "hi" "bye"] is a vector with 4 elements. Also, parentheses are not just the syntax for function calls, it’s also the syntax for
lists, so (1 2 3 4) is a Clojure list. Lists and vectors differ in their complexity guarantees as you would expect.

What we see here, is that Clojure code is written using Clojure data structures!

Think about that for a moment, a function call in Clojure is just a list, and we saw that Clojure vectors also appear as part of Clojure code.

This is a property of all Lisp languages and has fantastic implications!

Back to the problem again, we already have our file opened, we need to read all lines and process them. We’ll create a function to make it easy to reuse:

(def process-lines
  (fn [path f]
    (with-open [reader (clojure.java.io/reader path)]
      (f (line-seq reader)))))

Lots of parenthesis, I know…

Our old friend def helps us bind the name process-lines to a new function. (fn [...] ...) is how we create new functions, [...] is a vector of arguments to the function.

In process-lines we are receiving two arguments: path and f. Anything that comes after the arguments and inside the (fn) call, is called the function’s body.

The result of the function will be the last expression evaluated in its body.

Then, process-lines is a function which takes two arguments. path indicates the location of the file to read, that’s easy, but
what is the f argument?

In Clojure functions are first-class citizens, we can pass them as arguments to other functions return them from function calls, put them inside collections, or whatever we can do with other values such as integers or strings. So, process-lines is taking a function f as argument.

That function will take care of processing all lines in the file.

Do you see how we are reverting the usual flow here?

We don’t expect process-lines to return the files contents, instead, it receives a function that will do the work. is called with the result of line-seq, a sequence of strings read from the file, one string for each line.

Now we need to create this function that will take care of printing the matching words, that is, the function that we will pass to process-lines

(def print-matching
  (fn [words]
    (prn ...)))

print-matching receives the sequence of all words, selects the ones matching and prints the result using prn, we still need to fill the
blanks. In some traditional languages you would use the following scheme to obtain the matching words:

  • Create an empty vector/list
  • loop through all the strings in the line sequence
  • if a string has 10 characters add it to the vector/list and continue with the next step of the loop
  • if a string length is not 10, just go to the next step of the loop
  • when the loop ends, return the populated vector/list

You probably have no problem understanding this, because it’s familiar to you from languages such as C or Java. But it’s not conceptually simple at all.

There are lots of interactions to track, lots of interleaving moving parts. What we want to do is simpler, we just want to filter the list of words, keeping only those with length 10.

Instead, we could write:

(filter length-10? words)

Simple, right? This line express exactly what we have in mind.

Let’s dive in:

  • Of course, this is a call to the Clojure function filter
  • the first argument length-10? is a function we didn’t define yet, which will return true whenever its only argument is a string of length 10. Function names can contain symbols, and the final “?” is just a convention used for functions that return a boolean
  • words is the argument to print-matching: the sequence with all words in the file
  • the result of the filter call will be a new sequence of strings, containing only those string in the input, that make
    length-10? return true. That’s exactly what we wanted.
  • Notice that the original sequence of words is not modified. filter returns a new sequence leaving the input sequence intact.
  • In fact, all Clojure collections are immutable, you can’t modify its contents. Sounds weird? Don’t worry we self impose this constraint to get code that’s easier to reason with, easier to test, to debug and to parallelize.
  • And, to get the cherry on top, we still can do everything you would do with traditional, mutable collections.

Lets write length-10? now:

(def length-10?
  (fn [word]
    (= 10 (count word))))

We are defining a function, that takes one argument word. It returns the result of calling the function = which is the equality comparison function (in some other languages == is used for this).

(count word) returns the length of the word. So this function returns the boolean true value if the argument has length 10 and false otherwise.

Now, we have written all the parts, we just need to call process-lines passing the appropriate arguments. Lets see the whole program

(def file-path "words.txt")

(def process-lines
  (fn [path f]
    (with-open [reader (clojure.java.io/reader path)]
      (f (line-seq reader)))))

(defn length-10? [word]
  (= 10 (count word)))

(def print-matching
  (fn [words]
    (prn (filter length-10? words))))

(process-lines file-path print-matching)

As you can see, we are calling process-lines passing our file path constant and the function print-matching. Passing a function as argument is easy, we already have a constant defined with def (print-matching) pointing to that function, so we just use that
constant, exactly the same thing we are doing with the other argument file-path.

Smelly, smelly, naughty, naughty!

That’s it, that works and it’s easy to understand (once you get used to the parentheses), but let’s improve it a little bit. length-10? smells bad. If the requirements changed to match 15 characters words, we don’t want to change the function name.

We are going to generalize the function. Lets go top-down and write first how we would like to use it:

(filter (length-matcher 10) words)

That’s better, 10 is just an argument to a function call, we could easily change it to other number or read it from the console. Now, we know filter takes as its first argument a boolean function, and that means that the result of the (length-matcher 10) call must be a function.

If you never saw something like this in other languages, your head may be spinning right now.
length-matcher is a function that, when called, will return another function. If you think about it, it’s not as fancy as it sounds, functions are just another type of values, we can do whatever we want with them. Lets right length-matcher then

(def length-matcher
  (fn  [n]
    (fn [word]
      (= n (count word)))))

Wow, there is a lot of functioning there, we are writting functional code after all.

  • length-matcher is a function of 1 argument n, the length of the words we want to match
  • as you should remember (fn) is what we use to create new functions in Clojure, so the result of length-matcher will be
    another function
  • this returned function will also have 1 argument word, and will return a boolean, the result of the equality comparison.

So, length-matcher is a function that, when called with n will return a new function that when called with a word, will
return true if that word has length n. Phew…. I need some water… feel free and get some too….

Little test to make sure you are following so far:

  • What is the type of length-matcher?
  • What is the type of (length-matcher 10)?
  • What is the type of ((length-matcher 10) "hello")?

Solutions:

  • A function of one integer argument that returns a function of one string argument
  • A function of one string argument
  • A boolean. The result of (length-matcher 10) is a function, we are calling that function passing “hello” as argument.

OK, now you understand how our new code works and how easy is to change the length matched.

Here is the full program

(def file-path "words.txt")

(def process-lines
  (fn [path f]
    (with-open [reader (clojure.java.io/reader path)]
      (f (line-seq reader)))))

(def length-matcher
  (fn [n]
    (fn [word]
      (= n (count word)))))

(def print-matching
  (fn [words]
    (prn (filter (length-matcher 10) words))))

(process-lines file-path print-matching)

What else do we get?

Short: Size is a great predictor for number of bugs. Short code has fewer bugs.

Abstract:We are embracing the powerful filter abstraction. To understand and modify the code, you don’t need to understand the details of the iteration mechanism, filtering is an abstract operation that we translate directly to code.

Declarative: We are just expressing what the code must do, not how to do it. For instance, we are not giving details about how the file should be read, nor how the sequence should be traversed, nor how a temporary sequence should be populated. These are details we don’t what to deal with, this allows as to work at a higher level of abstraction.

Testable: You could test length-matcher, print-matching and process-lines in isolation. The result of each of this functions depends only on its arguments, there is no hidden state or side-effects, that makes them much easier to test. This is a huge advantage of the functional style.

Maintainable: If requirements change, and you no longer need to output 10 characters strings, you just need to change the filtering function. Suppose you are asked to match all words with less than 10 characters. That’s easy, change your length-matcher (or create a new function) to:

(defn length-matcher [n]
  (fn [word]
    (< (count word) 10)))

Lazy: This would need a whole new post to explain it but it’s so cool that I need to tell you about it.
Suppose the file were 10 GB in size. Suppose you don’t need to get all 10 character words, but only the first 50. What would you do?

Clearly our code is too naive to deal with this use case. You don’t want to load all 10 GB of words in memory, filter all of them to get a huge sequence of 10 characters words, and then, only keep the first 50 words. That would be awful.

The key here is that our code is not too naive!. Clojure will do it for you:

(take 50
      (filter (length-matcher 10) (read-lines file-path)))

That will get the first 50 words. But the good news is that read-lines and filter are lazy functions (remember that read-lines is our own code, but is lazy anyway).

Those functions will only process information when they are required to. The program will run without a problem on big files, because it won’t process more than it needs to.

Think about how would you do this in your language of choice. Chances are that you will need to change all the design and interfaces. Clojure embraces laziness in their sequence processing functions.

Homework

The code is not fully decoupled, there is a lot of room for improvements. You could try your hand at Clojure by fixing some of the following smells:

  • print-matching has the double responsibility of filtering and
    printing the results
  • print-matching “hardcodes” the length of the matched word
  • We are ugly-printing the matching words. To do a better job we need to
    iterate the result words and print each one individually.

Conclusion

Clojure is an unbelievable expressive language, with some of the most powerful abstractions I have seen in any language. We didn’t even scratch the surface here, there is a lot of awesome features you will want to know about.

If you are interested, hurry up and get the early bird discount to the three days, hands-on Clojure training we are doing in Winnipeg November 6, 7 & 8.

See you there!

Tags: ,

The Bowling Game Kata – First attempt

September 5th, 2011 / No Comments » / by Amir Barylko

Last week I did a presentation about the Bowling Game kata in C#.

I created a repository on GitHub with the code so I can share my first attempt.

You can follow the commit comments to get an idea of the train of thought.

Or if u prefer, just keep reading :)

The Methodology

I used TDD and somehow BDD all the way. Started with an acceptance test and jumped in and out from the unit tests until the feature passed.

Why is a good idea to start with an acceptance test?

When you know where you want to go, what you want to achieve, is easier to keep the focus.

Having a way of identifying if the current feature is finished is a lot of power in your hands, so do the minimum necessary to make it work and then – once the test is passing – do refactoring as you see fit.

In the solution you will find three projects:

  1. BowlingKata: Classes that implement the Kata
  2. BowlingKata.Unit.Tests: Unit tests
  3. BowlingKata.Acceptance.Test: Features that I’m looking for in a bowling game

Design Decisions (fast forward TDD)

As soon as I started to write a unit test for the BowlingGame class I wonder how am I going to design the solution.

My first test was for the method Roll(pins). And right there I had to assign responsibilities.

What should this method do? Do the “registration” only? Do the calculation as well? Is there any other class involved?

I decided on keep things simple and separate two clear responsibilities:

  1. Keeping the number of pins knocked down on each ball (or frames later)
  2. Calculating the score based on the information on each frame
So I created two interfaces with that purpose:
  • IFrameKeeper: In charge of registering the pins down in each frame
  • IScoreCalculator: in charge of calculating the score over a sequence of frames (10 frames + 1 optional extra)
You can follow all the tests to see how the interfaces grew in complexity to fullfil the intended responsibility.

What’s next?

After the first approach I thought that would be nice to refactor again and explore other solutions:

  • Change the frame class IBowlingFrame to be able to calculate the score, maybe having regular frames, spare, and strike.
  • Find a way of registering the pins and also add some kind of bonus to avoid the iteration over the frames to get the score
Which option did you implement? Please share!
Feedback is more than welcome.

Tags: , , , ,

Using multiple sources for Nuget

April 9th, 2011 / No Comments » / by Amir Barylko

Last post I talked about installing a local Nuget server and the benefits. However the implementation wasn’t as simple and straightforward as I expected, here is the roadblocks I found and what I had to do to make it work.

First I installed a local server and then updated the projects to use some of the packages from the local server.

The references were updated. Solution builds fine.

So I decided to update the rake build script and add the  local source.  First roadblock ahead.

More than one source

Now, I run the rake script to get all the packages to make sure it works and I found that when installing the packages the source is not stored in the  packages.config file.

What a disappointment… but don’t let this drag you down… there’s still hope!

First I checked on twitter and confirmed that in the current version the source is not part of the packages config and I started a discussion on the codeplex nuget site to talk about it.

Now, I have to figure out how to identify the local packages…

Using a config file for the local packages

Because I can’t store the source of the packages in the packages.config file I decided to use another file, packages_local.config to store my local packages.

Then, I changed the rakefile task to do the following:


FileList["**/packages_local.config"].each do |file|
	cp file, "packages.config"
	sh "nuget install packages.config /OutputDirectory Packages /source #{local_feed}"
end

If you are wondering why I need to copy the local to “packages.config”, is because the command line only accepts “packages.config” as a configuration file. Yeah, I know….

Thank god for contributors!

Luckily, when I was writing this post I received an updated from the nuget discussion (look at the end) forum talking about using multiple sources.

In the update Dan Turner mentioned a fork he did of the command line project to add two things:

  • Using multiple sources
  • Using repositories.config (file left inside packages folder) to load all the packages.config

Awesome! So I cloned the fork, build the solution, grab the new nuget.exe and voila! It works!

Here is the final version of the rakefile:

desc "Setup dependencies for nuget packages"
task :dep do
	remote_feed = "https://go.microsoft.com/fwlink/?LinkID=206669"
	local_feed = "http://wpgbuild02:8090/dataservices/packages.svc"
	FileList["**/packages.config"].each do |file|
		sh %Q{nuget install #{file} /OutputDirectory Packages /Source "#{remote_feed};#{local_feed}"}
	end
end

I’m still using the FileList to get all the packages.config because the Packages folder is removed and not stored in the repository.

The drawback is that is not the official release, thus getting updates is going to be a problem. Hopefully they will merge them soon.

Hope it works for you, let me know if you have any questions.

Tags: ,

Nuget for local teams

March 26th, 2011 / No Comments » / by Amir Barylko

Two weeks ago I started migrating all my .NET projects to Nuget, you can read more about it in my previous post.

After I was done with my OSS projects, I decided to share the goodness with some of my clients and then came to realize a few issues with my “stop storing dependencies in the repository” crusade.

First, many of the dependencies can’t be published to the public nuget.org server. That means that we need to find a way to store them locally.

Solution: Install local nuget feed.

Why a local Nuget feed is a good idea

Having a local feed allows your company leverage all the benefits of package management internally.

Plus you can use it to cache common used packages in case you have issues downloading them.

How to do this you ask? Well, is not as straightforward as I hoped. Luckily I had the help of @davidalpert to fight IIS configuration and @ferventcoder and @davidfawl to answer all our questions.

After approximately 3 weeks of tinkering with the server, David managed to make it work. (Kudos, yay!)

Here are a few links to follow in order to install the server locally:

Key points:

  • URL should be http://yourserver:port/dataservices/packages.svc
  • Add the .nupkg as mime type with application/zip
  • Remember that the new server is not an MVC application
  • Be patient, very patient…

I got the server running, now what?

Well now we have to tackle a different problem. I found that some of the projects are using libraries that are not yet published to the public feed.

Though I could package and publish them (I have done so with Structuremap.Automocking and others), some of them are a bit out of date and others are the result of downloading the source, modifying it and compiling it locally.

Either case, I thought that I’d like an easy way of packaging and publishing these packages to the local feed in order to keep using them.

Doing so is also a great solution if you don’t have the time to review if an upgrade would work, or is to risky to do it.

If you read my previous post you already know that I’m using Albacore to generate the nuspec file, build the package, etc.

My first thought was to use those tasks for each of the packages in need to create. And I started to do so.

Rake again and again

After creating a rakefile, copying the libs, etc for the third time,  my laziness sense (similar to spider sense without the awesome and the great responsibility thing) started to tingle indicating that should be a way of avoiding this repetitive task.

  • Copy the assemblies to a lib folder
  • Generate the nuspec with the name of the library and the version
  • Compile the nuspec and create the package
  • Copy the package to the destination to be served by the local feed

Instead of writing one rakefile per package, why not just add parameters to the rakefile so I can call it from command line specifying:

  • Name of the package
  • Version of the package
  • Folder where to get all the assemblies

And voila! Here is the result, I hope you find it useful.

To use it, you will have to type something like this:

rake deploy:publish[AvalonDock, 1.0, "c:\project\lib\avalondock"]

Are you doing anything else cool with nuget? Please share!

Tags: ,

Nuget gotcha: Avoid storing packages in the repository

March 13th, 2011 / 2 Comments » / by Amir Barylko

It’s been a while since Nuget project was released. Since the project birth I’ve been watching closely to see when would be a good opportunity to start using it for my projects and recommend using it for my clients.

Basically, the Nuget project solves dependency management for all your .NET projects. That means that you don’t need to search any more for libraries that you need to use like NHibernate or nUnit and just install them from a centralized server.

The path to Nuget

So far I’ve been using Rake for all my builds and I’m super happy with it. Using a DSL specifically designed for building projects is a great advantage, Ruby gives you lots of flexibility and the Albacore gem is the cherry on top.

One of the many things that I like about the Ruby world is gem + bundler combination. For .NET projects I’ve been using also noodle to copy the dependencies to my local folder (usually called lib).

However not everything is ponies and rainbows:

  • Ruby based solutions are not always well received in .NET project (no matter how good they are)
  • Not many developers publish their libraries / frameworks
  • Creating gems with .NET assemblies is discouraged since Nuget was born

All this reasons plus the fact that the .NET community was embracing the idea of package management using Nuget make me consider it as a great option.

However one thing was keeping me from doing the change, and that is the ability of reading a configuration file and use it to download all dependencies (very similar to what Bundler does).

And that was it…. Until a couple of days ago….

Nuget Adoption

Last week I say a tweet by @davidebbo saying that Nuget supports now reading from a config file!

Why is that so important? Because I don’t want to store my dependencies in the repository any more!

The assemblies that we use in a project usually don’t change until we update a newer version. What’s the point of storing them with our code if we can use just a reference to them and download them at our leisure?

It takes way less space to store our repositories and updating the packages quite easier because you just change the references and the configuration file, and that’s it, everyone gets them.

Also imagine sharing in your company all the internal assemblies by publishing them to a local Nuget server instead of having a share drive or similar.  Update the version whenever you want! No more versioning dependencies nightmares! And everything is treated the same way, they are all packages!

So I installed latest version of Nuget (following the link above) and started the conversion:

Step 1: Changing the References

Open your .sln file, remove all your references and add them again by doing right click + Add Package Reference. That would accomplish the following:

  • Find the reference in the package server
  • Install it to a local package folder (usually called Packages)
  • Write a config file with the dependency installed (in the same folder as the project)

Step 2: Modify the Rakefile

I need dependencies in order to build, so I need to make sure that before building all my dependencies are satisfied, to do so I modified the task setup:dep to do the following:

namespace :setup do
	desc "Setup dependencies for nuget packages"
	task :dep do
		FileList["**/packages.config"].each do |file|
			sh "nuget install #{file} /OutputDirectory Packages"
		end
	end
end

And I need to make sure this happens every time before building, so I need a dependency in the build task (remember that I’m using Albacore for the msbuild tasks).

	desc "Build the project"
	msbuild :all, [:config] => [:setup] do |msb, args|
		msb.properties :configuration => args[:config] || : Debug
		msb.targets :Build
		msb.solution = solution_file
	end

Step 3: Enjoy!

That’s it! Super easy! If you want to check the code please go to github and download it.

Tags: , , , , , ,

Testing with random values: is it really dangerous?

March 6th, 2011 / 3 Comments » / by Amir Barylko

Last Saturday I presented a session about automation at the Winnipeg Code Camp.

I’ve been doing presentations a the WPG CC for the past three years, and is always a blast! Great sessions, lots of networking and great food is an awesome combination!

After my session, some of the attendes approached me and started to talk about CI, their gotchas about testing and woes :) .

One of them mentioned that he wasn’t sure about the way they were using “hardcoded” values with the tests. He felt that probably should be a better way of defining valid inputs that could avoid the “smell”.

My suggestions was to consider using auto generated values. Random values are a great tool to avoid hardcoding inputs. Using “factories” to create valid test values helps us to make sure we have better coverage of the domain of valid inputs for our tests.

How do I know what input is valid?

You may wonder “But, if the values are random, the test may pass once and then fail at runtime, that’s really, really, dangerous!!!”.

The answer is No, not at all. The key is to identify the domain that makes your test pass and use the random generation tools to get values that are part of that domain. How to do that? Keep reading …

When you write a unit test you may have more than one scenario. For each scenario you need to find a set of inputs that make it pass.

For example, let’s use a method that verifies if a string is a palindrome. Definition of palindrome in wikipedia:

palindrome is a word, phrase, number or other sequence of units that can be read the same way in either direction

Our method may look something like this in C#:

bool IsPalindrome(string word)

So now, what should we do? Write one test that takes random strings as input, run it once and if we are lucky and passes then we are done? Woah, slow down your horses….. take a deep breath… maybe two….

Preconditions, postconditions and domains

The precondition of the method is the set of values that are valid in order to call the method. Valid means that we don’t get an exception when we use it, no matter what the result of the method is.

So, what are the values that are valid to use for IsPalindrome? It seems to me that any string should work, except null, therefore:

  • Precondition: Any not null string instance.

Great! Now let’s think about the postcondition and discover our scenarios. The postcondition defines what are the expected results and under what conditions are calculated.

Following our definition of what the method does, we can have two possible outputs:

  • True: if the input is palindrome
  • False: if the input is not palindrome

Thus, we have two scenarios:

  • When the word is palindrome it should return true
  • When the word is not palindrome it should return false

Writing the test

We need to test two scenarios and the best way of doing that is to write one test per scenario.

The first test should check the first part of the postcondition, I want to get true as result, and to do that the domain I need to use would be all the words that actually are palindrome. Let’s write the scenario:

Given I have a palindrome phrase

When I check IsPalindrome

Then I should get true

I like to use the Given-When-Then syntax, it’s very descriptive. I’m using the MT Testing library that enforces GWT. Here is the scenario using C# and just one example:

protected override void GivenThat()
{
    this._phrase = "Madam Im adam";
}

protected override void WhenIRun()
{
   this.Actual = PalindromeChecker.IsPalindrome(this._phrase);
}

[It]
public void Should_validate_the_phrase_is_palindrome()
{
    this.Actual.Should().Be.True();
}

The test looks good, a bit of TDD and all green. Don’t worry about the implementation, you can download all the source and check it out at the later ;) .

Using Factories

I’d like to make sure that for any palindrome phrase (that’s the domain we got from the pre and post condition) the test passes, no just for one example.

However, though generating all the palindrome words is a bit ambitious, we could settle for generating a collection of phrases that are palindrome and use that as input.

MbUnit provides an attribute named “Factory” that allows a static method to define a collection of values to be passed to the test, let’s look at the code:

        private readonly string _phrase;

        [Factory("PalindromeFactory")]
        public When_palindrome_checker_checks_a_palindrome_phrase(string phrase)
        {
            _phrase = phrase;
        }

        protected override void WhenIRun()
        {
            this.Actual = PalindromeChecker.IsPalindrome(this._phrase);
        }

        [It]
        public void Should_check_the_word_as_palindrome()
        {
            this.Actual.Should().Be.True();
        }

        protected static IEnumerable<string> PalindromeFactory()
        {
            yield return "Madam I'm adam";
            yield return "Draw pupil's lip upward";
            yield return ....
        }

Using the attribute, we indicate the runner that the test should be run for every value in the collection.

We run the test, and we can see in the result window something like:

### Step When_palindrome_checker_checks_a_palindrome_phrase("Madam I\’m adam"): passed ###
### Step When_palindrome_checker_checks_a_palindrome_phrase("Draw pupil\’s lip upward"): passed ###
### Step When_palindrome_checker_checks_a_palindrome_phrase("Gateman sees name, garageman sees name tag"): passed ###
### Step When_palindrome_checker_checks_a_palindrome_phrase("Go hang a salami; I\’m a lasagna hog"): passed ###
### Step When_palindrome_checker_checks_a_palindrome_phrase("I roamed under it as a tired, nude Maori"): passed ###
### Step When_palindrome_checker_checks_a_palindrome_phrase("Live not on evil"): passed ###

Using random strings

One case covered, one to go.

The second test should verify the second part of the postcondition. I want to get false as result, so the domain I need to use is all the words that are not palindrome. Let’s write the scenario:

Given I don’t have palindrome phrase

When I check IsPalindrome

Then I should get false

And the code:

        private string _phrase;

        protected override void GivenThat()
        {
            this._phrase = "This is not palindrome";
        }

        protected override void WhenIRun()
        {
            this.Actual = PalindromeChecker.IsPalindrome(this._phrase);
        }

        [It]
        public void Should_not_validate_the_phrase_as_palindrome()
        {
            this.Actual.Should().Be.False();
        }

The code works fine. However we have a similar situation as before, I’d like to have more values that belong to the domain that makes the method fail, that means any phrase that is not palindrome.

Factories are a good idea when we have a set of values that we want to use. In this case I don’t want to hardcode non palindrome phrases. I would prefer to have a way of creating those phrases without needing to enumerate all the examples.

Luckily MbUnit has another attribute that we can use to generate random strings. It’s called RandomStrings and it takes a regular expression to describe the string. Adding the attribute the code looks like this:

        private readonly string _phrase;

        public When_palindrome_checker_checks_a_non_palindrome_phrase(
            [RandomStrings(Count=10, Pattern=@"Weird [A-Z]{5,8} [0-9]{2}")]string phrase)
        {
            _phrase = phrase;
        }

        protected override void WhenIRun()
        {
            this.Actual = PalindromeChecker.IsPalindrome(this._phrase);
        }

        [It]
        public void Should_not_validate_the_phrase_as_palindrome()
        {
            this.Actual.Should().Be.False();
        }

I’m using a regular expression that uses numbers at the end to make sure the phrase is not palindrome.

We run the tests, and here is the output:

### Step When_palindrome_checker_checks_a_non_palindrome_phrase("Weird VGSKTTZ 64"): passed ###
### Step When_palindrome_checker_checks_a_non_palindrome_phrase("Weird VLMEWIJ 59"): passed ###
### Step When_palindrome_checker_checks_a_non_palindrome_phrase("Weird NDICJK 08"): passed ###
### Step When_palindrome_checker_checks_a_non_palindrome_phrase("Weird FEMBMSKK 88"): passed ###
### Step When_palindrome_checker_checks_a_non_palindrome_phrase("Weird IHOIOWN 38"): passed ###
### Step When_palindrome_checker_checks_a_non_palindrome_phrase("Weird ITIRCHAA 63"): passed ###

The moral of the story

Random values are a powerful tool, not dangerous per se. They are part of our toolbox as developers. Can we use it wrong? Sure, but that’s a completely different story ….

If you want to get the full code, download it from the examples in MT Testing. Check the Palindrome folder.

Do you have any other stories or comments about random values that you would like to share, please leave a comment, feedback is more than welcome.

Want to see an example with major complexity? Something that fits better your case? Tell me about it and I’ll add it to the MT Testing framework as an example of usage (and I’ll give you credit for it too!).

MVC virtual conference #2

February 20th, 2011 / No Comments » / by admin

On Feb 8th I participated on the MVC Conf #2. It was a great experience, though is still a bit weird not to see the crowd :-) .

My session was about “Quality driven acceptance tests using Capybara” and it was a bit of a shock because many .NET developers weren’t expecting Ruby as a tool and many got confused and thought I was using Ruby on Rails… but I guess that’s material for another post.

Overall I really enjoyed presenting and I hope  to do it again next time.

You can download the slides and source code from presentations. I just updated the README file with some troubleshooting.

If you have any issues running the code, or with the setup let me know.

Tags: , , , ,

Presentation at Codemash

January 13th, 2011 / No Comments » / by Amir Barylko

Wow, first day of CodeMash and so far it’s being great! It’s really an awesome conference!

Yesterday at the precompiler, I went to the ” Getting Published in an Evolving Industry:
How to Survive and Even Thrive” with Jason Gilmore (@wjgilmore) and learnt a lot about writing books and how to publish, I’m really tempted to write an ebook!

Then in the afternoon I went to the “Git Immersion” session and was pretty interesting, is a tough call because for every session I go there is another four I can’t …

Today I’m going to do my presentation about IronRuby. I uploaded the slides and code to the presentation page, please feel free to download it and check it out before the conference.

In order to run ir u need to:
* Install Iron Ruby from http://ironruby.codeplex.com/

* Remember to put it in the path

* Install rake: igem install rake

* Install bundler: igem install bundler

* Check the tasks: rake -T

* Setup dependencies: rake setup

* Build: rake

* Run the tests: rake test

That’s it! Please contact me at @abarylko or amir@barylko.com if you have any issues.

Hope to see you at the session! Say hi if you are at codemash!

Now, in the afternoon, which session to go…. which session to go…..

Microsoft Techdays 2010

December 7th, 2010 / No Comments » / by Amir Barylko

Wow! First day of Techdays is gone and I’ve done both of my presentations:

  • Test Driven Development Patterns
  • Top 10 mistakes in unit testing

The attendance was pretty good and all the attendees were great! Thank you everyone, I had a great time!

I’ve uploaded to presentations the slides and a link to the source. Both presentations using the same code.

Please follow each commit that mimics the steps I did in the presentation.

If u want to run the code please do the following:

  • Download the code
  • Install ruby (if u don’t have it)
  • Install rake: gem install rake
  • Install bundler: gem install bundler
  • Then do setup: rake setup
  • Run the test to make sure: rake tests

Please let me know if you have any issues or questions.

Get Adobe Flash playerPlugin by wpburn.com wordpress themes