ReSharper templates

Posted by Jens Pettersson on August 30th, 2010

I would like to share my small but helpful collection of ReSharper templates. I use ReSharper templates a lot and most specifically while I’m writing tests/specifications or while creating mappings or any other repetitive task that can’t be DRY:ed out. For the moment I only have a couple of Live Templates for MSpec that I use while writing our BDD specifications, but I plan to update this as soon as I need a new template. I lost my old templates in the volcanic ash earlier this year…

This is one example of a template I use when creating a new MSpec class:

image

All this code given to me by writing spec and hitting tab. The duplication of the class name in the FolderSubject attribute is generated as I name my class and is used for our report generator.

Never mind the weird indentation under Establish and Because, it’s Visual Studios way of saying: I don’t like you.

You import the templates by going to ReSharper > Live Templates and then hitting the import-button.

image

You can get the templates from my Github repository. Feel free to contribute with your own ReSharper templates!

//J

Mini-review of Clean Code

Posted by Kenneth Selin on August 29th, 2010

This summer I borrowed the book “Clean Code” from the office (author: Robert C. Martin).

I write this from memory, without cheating and opening the book again.

As the title suggests, it’s about how to write “clean code”, and what this is, is discussed in the beginning of the book. The rule of thumb that I liked, is that clean code looks “pretty much as you expect it”. That is, when you look at someone else’s code and it doesn’t surprise you with ugliness, it is actually clean! I have myself experienced this when I looked (just a little) an the Java SDK source code. I was like “yeah good code, nothing special to it”. But this means that it is clean.

All in all, I really liked this book, much for its great ability to inspire. An experienced developer will have heard about quite a lot of the contents, but probably not all, and together it is a very inspiring  read.

My favorite part is the discussion of 2 of the parts of the SOLID design principles, namely Single Responsibility and Open Closed Principle.

As I feel it, Single Responsibility Principle will take the design of your application very far if you are able to apply it. The rule basically says “A class (or other program entity) shall have just one responsibility, i.e. one reason to change.” The advantages of this are quite obvious: such a class will have a greater chance of being reused since it has a more clean purpose, and it will be easier to maintain, since this class has (by definition) just one reason to change, so you can’t mess anything else up, while you modify it!

The SOLID design principle I think is second best, is “Open/Closed Principle”, meaning the system shall be “open for extension but closed for modification”. If you are able to apply this, you will find that you can add classes and stuff when implementing new functionality, rather than modifying existing code. Again, there is a smaller risk you mess up the existing functionality.

The book contains numerous thoughts and tips and tricks about how to make your code cleaner, for example:

  • A function shall not do stuff on different levels of abstraction.
  • Various patters you can return to if you find your code being ugly, for example if you think exception handling takes to much focus from the reader.

A great read!

More MSpec – ReSharper love

Posted by Jens Pettersson on August 27th, 2010

This is a follow up to the post about how ReSharper and Visual Studio messes with your MSpec specifications.

Resharper has built in support for naming inspections which is great for consistency if everyone in the team follows the same rules, but sometimes you just don’t want it. The most common scenario is when writing BDD specs (with tools like Machine.Specifications or MSpec for short).

image

This is a pretty common specification in our current project, and the class name might seem strange if you haven’t done BDD before. But the beauty of this is that the testing framework generates reports with this convention which is extremely readable for non-techincal people.

It will read something like this:

When an already handled customer is processed
the customer should not be processed further

Or whatever you want to check. Our rake task always generates a html-page with all our specifications in a nice and readable format (more on that in a later post).

Well, back on topic! How do we tell Resharper not to scream WARNING, WARNING! at us all the time. We ARE naming things like this on purpose!

As everything always has been done by someone before, I’m only going to give you a link to the solution: http://www.aspiringcraftsman.com/2010/02/resharper-naming-style-for-machine-specifications/

You can add as many naming styles as you like to suit your specifications.

Happy mspeccing!

//J

PS. If you like the Visual Studio theme I’m using, go grab it from my repository over at github. Be sure to read the readme for the right fonts, otherwise the theme will hurt your eyes and probably your babies or kittens too.

Listen to your tests

Posted by Andreas Öhlund on August 23rd, 2010

We had a discussion today on how a test can tell you that something is off with your design. If a feature is hard to test you should listen carefully because your tests might be telling you something. The piece of code we where discussing is setting up return values for queries against our persistent store.

Stub(x=>x.Query(Arg<Func<Customer,bool>>.Is.Anything)) .Return(new[] { customer });

As you can see we have to specify the input to our query method using some hairy nested generics. Our test was just trying to return a specific customer when the repository was queried so having go through all the generic mumbo jumbo just felt wrong. This lead us into changing our old Query method

IEnumerable<T> Query<T>(Func<T, bool> criteria);


To use the query object pattern

IQueryResult<T> Query<T>(IQuery<T> query);

With this is place we can encapsulate our queries in separate classes implementing IQuery and there by adhering to the Single Responsibility Principle. As an added bonus our queries can now be reused instead of copy and pasted everywhere.

And the test?

This change in design allowed our test to focus on the right thing. That is:  “given the query GetCustomerByCrmIdOrOrgNr return this active customer”.

Stub<IRepository>(x => x.Query(Arg<GetCustomerByCrmIdOrOrgNr>.Is.Anything))
.Return(new List<Customer>{ activeCustomer }.ToLinqResult());


This did also allow us to refactor the test a bit further:

QueryFor<GetCustomerByCrmIdOrOrgNr>()
.Return(activeCustomer.AsLinqResult());

Ah, that’s more like it!

Final note:

We’re packaging our IRepository implementation into a public project that soon will be published on our github account.

More on git – Permission denied

Posted by Jens Pettersson on August 23rd, 2010

In the last post I wrote about getting Permission denied while merging and today Daniel got the same error when pulling from our remote master. This was caused due to a locked file and the pull stopped after a couple of files which resulted in those files being left as “untracked files” on our master, which isn’t correct.

This was solved by doing a

§ git clean -f –d

This stands for “-force” and “remove untracked directories”.

After this you can do a new pull. If it stills fails, use

§ git reset HEAD --hard

and then use clean again if you have to.

//J

Git merge error – Permission denied

Posted by Jens Pettersson on August 20th, 2010

Today when I wanted to merge my branch (after the “pull –> rebase dance” I wrote about yesterday) I got the following error:

error: git checkout-index:
unable to create file src/ProjectName/ClassName.cs (Permission denied)

If I just retried the merge I got another error and if I looked in my local master I didn’t see my branch’s commit messages either. If I did a git status I saw some of my files from my branch, but not all of them as untracked files. I couldn’t go back to my other branch either due to the untracked files in my master.

The solution? Well, it turned out that a

§ git checkout my_branch -f

did the trick. The –f stands for “force” so it just discarded all my untracked changes in master and I was back on track. Now the merge worked again because the file probably wasn’t locked anymore.

Not sure why the file was locked and by what, but this workaround did enable me to merge and later push my changes correctly to github.

//J

Builder Pattern

Posted by Kenneth Selin on August 20th, 2010

I stumbled on a very cute design pattern the other day, and I’d like to share it.

It’s supposed to be used when a Factory doesn’t provide enough flexibility, since the creator of the object wants to control also how many properties to set on the created object.

One of the reasons I liked this pattern is since it can provide so much readability to the code. I spent a few minutes trying to find the example I read the other week, but I couldn’t find it again. Those examples I found on the web this time did not use the readability enhancements, but they were still of course examples of the Builder pattern.

A Builder is a class able to construct another object, much like a Factory.

The feature that I think provided the readability, is that methods are called “withX” and return “this”, which means that it’s possible to repeatedly invoke “withX” methods.

This is how cute it gets:

Car.Builder carBuilder = new Car.Builder();
Car car = carBuilder.withTires(4).
                                           withColor(Car.Red)).
                                           withCylinders(8).
                                           withHorsePower(1000).
                                           build();

In this example, Car.Builder is the Builder class, able to construct Car objects.  How explicit this code is! It’s easy to see that “8″ means “number of cylinders” and so on.

One idea behind the Builder pattern is also that it is able to provide convenience methods for recurring groups of attributes. Let’s assume a Car with 8 cylinders and horse power 1000, is a “sports car engine”. Then the Builder class can provide a method for just this, and the code would loook like:

Car.Builder carBuilder = new Car.Builder();
Car car = carBuilder.withTires(4).
                                           withColor(Car.Red)).
                                           withSportCarEngine().
                                           build();

The build() method returns the Car that was constructed, and may also contain consistency checks, i.e. that the set of properties set was appropriate.

Does ReSharper drive you crazy when using MSpec?

Posted by Jens Pettersson on August 19th, 2010

Ask yourself the question in the topic and if the answer is “Yes damn you, YES!!” then this link tip is for you!

http://codebetter.com/blogs/aaron.jensen/archive/2008/10/19/getting-resharper-and-vs-to-play-nice-with-mspec.aspx

Thank you Aaron Jensen! I was going mad with all the ugly indentations and other noise everywhere.

//J

That’s how we roll (git) in the Shire!

Posted by Jens Pettersson on August 19th, 2010

This post is about how we try to use git in our current project. At the moment we’re three coders involved and we’re pretty early in this project.

Yesterday I was working on my local branch with a couple of features while the others pushed some changes to our remote master wich I wanted to have in my branch. This is how I did it:

First, I made sure I had the latest version on my local master:

§ git pull

Then I did a rebase onto my feature branch:

§ git rebase master my_branch

The following message from git is pretty self explanatory on what’s happening:

First, rewinding head to replay your work on top of it…

Applying: My first commit message

Applying: My second commit message

Applying: Frodo was here!!1!

After that I merged my branch with my local master and then pushed it to github. Of course I didn’t have to push it, but it wouldn’t been nice to loose a days work if something had happened.

We could also have used remote branches for this, but it doesn’t feel necessary at this point.

Feel free to drop us a comment on how you use git in your projects! We aren’t claiming that this is the best way to go, it just works for us right now.

Shire out!

//J

Copied connectionstring caused FluentConfigurationException

Posted by Daniel Kjellqvist on August 18th, 2010

Today I had a problem with a FluentConfigurationException. The day before I’ve used “the same” configuration and it worked. I just couldn’t understand what’s wrong..

Here’s the exception message: “FluentNHibernate.Cfg.FluentConfigurationException: An
invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.”

But I couldn’t see anything wrong in the configuration:

var config = Fluently.Configure()
    .Database(MsSqlConfiguration.MsSql2008.ConnectionString(connectionString)
    .ProxyFactoryFactory(typeof(NHibernate.ByteCode.LinFu.ProxyFactoryFactory)))
    .Mappings(m => m.AutoMappings.Add(AutoMap.AssemblyOf<Customer>(new CrmAutomappingConfiguration())
    .Conventions.AddFromAssemblyOf<ColumnNullabilityConvention>()
    .UseOverridesFromAssemblyOf<CustomerMappingOverride>()
    .IgnoreBase<Entity>));

It’s just a simple fluent nhibernate configuration!!!!

So I debugged and found this connection string: “Data Source=localhost\\sqlexpress;Initial Catalog=TestDB;Integrated Security=SSPI;”

Nothing wrong there I thought… but after a while i saw the double backslash (localhost\\sqlexpress)!!!!!

The day before I had the connection string inside the configuration and the compiler needs the double backslash, but of course that’t not the case when I moved the connectionstring to the app.config.

So I just erased one of the backslashes and everything worked fine.

It remembered me that everything makes a difference. =)


Copyright © 2010 NullReference. Web hosting.