Brendan Enrick

Daily Software Development

Types of ASP.NET MVC 3 Action Results

This will surprise some of you that know me or the company I work for, but not all of our staff are experts with ASP.NET MVC. In fact, I am hoping that the couple who aren’t will read this post and learn a little bit more about the topic.

Since the actions of controllers in MVC are dealt with constantly, I think it is a good place to start. This post is going to briefly describe the different types of results that are available to you in ASP.NET MVC 3. I will show some of the code that makes them work, which should make all of this seem a lot less complicated.

When creating new controllers in ASP.NET MVC 3, they will come with one or more actions by default. This depends on whether you selected a template which includes extras for you. The Empty controller template comes with an Index action with a return value of type ActionResult.

ActionResult

The action result is a very generic return value for an action. This is because it is the abstract base class for other types of actions. It is actually a very simple class having only one method that needs implementing.

public abstract class ActionResult
{
public abstract void
ExecuteResult(ControllerContext context);
}

Inheriting from the ActionResult are the following classes:

  • ContentResult
  • EmptyResult
  • FileResult
  • HttpStatusCodeResult
  • JavaScriptResult
  • RedirectResult
  • RedirectToRouteResult
  • ViewResultBase

These are the classes that inherit from ActionResult indirectly:

  • FileContentResult
  • FilePathResult
  • FileStreamResult
  • HttpNotFoundResult
  • HttpUnauthorizedResult
  • PartialViewResult
  • ViewResult

ViewResultBase, ViewResult, and PartialViewResult

The ViewResult is the most common concrete type you will be returning as a controller action. It has an abstract base class called ViewResultBase, which it shares with PartialViewResult.

It is in the ViewResultBase abstract base class that we get access to all of our familiar data objects like: TempData, ViewData, and ViewBag.

PartialViews are not common as action results. PartialViews are not the primary thing being displayed to the user, that is the View. The partial view is usually a widget or something else on the page. It’s usually not the primary content the user sees.

This is the common return syntax, and it means that you’re returning a ViewResult.

return View();

That is actually a call to the base Controller.View method, which is just going to call through with some defaults.

protected internal ViewResult View()
{
return View(null, null, null);
}

 

The beauty of ASP.NET MVC is actually in its simplicity though, because all that really did was create our ViewResult for us. If we take a look at the method that is being called you can see that we’re just taking a little shortcut and keeping our action clean of this code we would otherwise repeat every time we wanted a ViewResult.

protected internal virtual ViewResult View(
string viewName, string masterName, object model)
{
if (model != null)
{
ViewData.Model = model;
}

return new ViewResult
{
ViewName = viewName,
MasterName = masterName,
ViewData = ViewData,
TempData = TempData
};
}

Notice how simple that really is. All it did was put the model data in if we specified it, give the ViewResult the Controller properties that we set already, and assign the viewName and masterName.

Keep in mind, that we already saw that the abstract method in the ActionResult was the ExecuteResult method. The last two things to look at with the ViewResultBase are the ExecuteResult method and its abstract method FindView, which is being implemented by ViewResult and PartialViewResult.

public override void ExecuteResult(
ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (String.IsNullOrEmpty(ViewName))
{
ViewName = context.RouteData
.GetRequiredString("action");
}

ViewEngineResult result = null;

if (View == null)
{
result = FindView(context);
View = result.View;
}

TextWriter writer = context.HttpContext.Response.Output;
ViewContext viewContext = new ViewContext(
context, View, ViewData, TempData, writer);
View.Render(viewContext, writer);

if (result != null)
{
result.ViewEngine.ReleaseView(context, View);
}
}

This method is also not very complicated. It checks to make sure we have context, and then if we don’t have the ViewName then we get that information from the RouteData. Remember in MVC that the name of action is included in the RouteData, so we can use that as the default view name. This means that in the Index action, if we just call View(), it will give us a ViewName of “Index”.

We then get the view we’re looking for by calling the FindView abstract method, which means we’re calling through to either ViewResult and PartialViewResult. Those I am not going to get into the guts of, but each one is going to try to find the correct view based on the name using its collection of ViewEngines.

Once we have the view, we are able to tell it to render itself using the context and the TextWriter we give to it.

That’s all there is to a ViewResult.

ContentResult

The content result lets you define whatever content you wish to return. You can specify the content type, the encoding, and the content. This gives you control to have the system give whatever response you want. This is a good result to use when you need a lot of control over what you’re returning and it’s not one of the standards.

Its ExecuteResult override is extremely simple.

public override void ExecuteResult(ControllerContext context) 
{
if (context == null)
{
throw new ArgumentNullException("context");
}

HttpResponseBase response = context.HttpContext.Response;

if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Content != null)
{
response.Write(Content);
}
}

It just puts what you specified directly into the response.

EmptyResult

There is no simpler result than the EmptyResult. All it does is override the ExecuteResult method and since that method is void, the method is empty.

I really don’t think I need that code snippet for this one.

FileResult, FileStreamResult, FilePathResult, and FileContentResult

If you want specific actions to send files as the response, then the FileResult is for you. Sadly, the FileResult is abstract, so you’ll need to use one of the inheriting classes instead. Each of these actually just overrides the WriteFile method for the abstract FileResult class.

If you want to just send the contents of the file back with the array of bytes for the file, then you want the FileContentResult. It uses the response’s OutputStream and writes those bytes directly into the stream sending it down to the user.

If you want to transmit the file using its name, you can use FilePathResult, which will call through a whole bunch of layers finally down to the HttpResponse. Once there it is going to create a new FileStream for your file and write the stream to the response allowing the file to be accessed from your action.

If you’ve already got a stream you can use the FileStreamResult, which will read all of the data from your stream and then write it into the OutputStream to be send back in the response.

These really aren’t all that complicated, but if you want to have control over the file downloads in your application, this is a great way to do it. These give you the power to put any code you want in your action before you give back the FileResult.

HttpStatusCodeResult

The HttpStatusCodeResult is as simple as the ContentResult. In fact, the two are quite similar since they both just directly modify the response object.

This one lets you return any StatusCode you want and you can include a StatusDescription for specifics.

public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}

context.HttpContext.Response.StatusCode = StatusCode;
if (StatusDescription != null)
{
context.HttpContext.Response
.StatusDescription = StatusDescription;
}
}

See how simple that is? It’s basically just two lines of code with some null checking included.

HttpNotFoundResult and HttpUnauthorizedResult

These two results are actually just implementing the HttpStatusCodeResult, which means that they are very simple and just set the StatusCode to 404 for the HttpNotFoundResult and 401 for the HttpUnauthorizedResult.

JavaScriptResult

About as simple as plenty of the others, this is just a quick way of getting JavaScript returned from a action. It’s similar to the ContentResult, but it has the ContentType hardcoded to “application/x-javascript” and just writes out the Script property.

public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}

HttpResponseBase response = context.HttpContext.Response;
response.ContentType = "application/x-javascript";

if (Script != null)
{
response.Write(Script);
}
}

JsonResult

This one is a bit more complex, but still not very. It also has hardcoded its ContentType, but what makes it a bit more complex is that it uses a hardcoded JavaScriptSerializer to serialize the JSON data before writing it directly to the response.

public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
String.Equals(context.HttpContext.Request.HttpMethod,
"GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(
MvcResources.JsonRequest_GetNotAllowed);
}

HttpResponseBase response = context.HttpContext.Response;

if (!String.IsNullOrEmpty(ContentType)) {
response.ContentType = ContentType;
}
else {
response.ContentType = "application/json";
}
if (ContentEncoding != null) {
response.ContentEncoding = ContentEncoding;
}
if (Data != null) {
JavaScriptSerializer serializer =
new JavaScriptSerializer();
response.Write(serializer.Serialize(Data));
}
}

RedirectResult and RedirectToRouteResult

These to are a little bit more complex, but both are ways of redirecting. Each one can either be a permanent or temporary redirect and they both just use the Redirect methods on the Response object.

For redirecting to a route, it is going to generate a URL to the route using the UrlHelper’s GenerateUrl method. For the RedirectResult it is instead going to use the UrlHelpers GenerateContentUrl method.

Either of these two are useful, and both will maintain your TempData if you need to pass something along with the redirect, all you have to do is put it in TempData.

Conclusion

I hope you’ve learned that the results of actions in MVC are not actually very complicated, but there is a lot you can do with them. You’re not being forced into just displaying views. You have a lot more control than that. None of them were that complicated were they? The code under the hood is not always complicated, so it’s worth taking a look from time to time. If you examine how something is working, it’s often far easier to use it.

Difference Between ViewBag and ViewData in MVC 3

If you’re new to ASP.NET MVC, you might be wondering what these two things are and when to use each one. If you’ve been using MVC and are just new to version 3 of MVC, you are probably wondering what this new ViewBag is for and if it’s different from the ViewData you’ve been using. In the beginning of the Summer, I had the opportunity to explain this difference to the two NimblePros interns when they started working on ASP.NET MVC 3 for the first time. This post should serve as a reference for them, me, and anyone else who is interested in knowing more about these two objects.

ViewBag and ViewData serve the same purpose in allowing developers to pass data from controllers to views. When you put objects in either one, those objects become accessible in the view. This is one way we interact between the view and the controller in ASP.NET MVC. We pass data from the view to the controller by placing it in these objects.

How ViewData Works

ViewData is a dictionary of objects that are accessible using strings as keys. This means that we will write code like this:

In the Controller

public ActionResult Index()
{
var softwareDevelopers = new List<string>
{
"Brendan Enrick",
"Kevin Kuebler",
"Todd Ropog"
};

ViewData["softwareDevelopers"] = softwareDevelopers;

return View();
}

In the View

<ul>
@foreach (var developer in (List<string>)ViewData["softwareDevelopers"])
{
<li>
@developer
</li>
}
</ul>

Notice that when we go to use out object on the view that we have to cast it since the ViewData is storing everything as object. Also, we need to be careful since we’re using magic strings to access these values.

How ViewBag Works

ViewBag uses the dynamic feature that was added in to C# 4. It allows an object to dynamically have properties added to it. The code we write using ViewBag will look like this:

In the Controller

public ActionResult Index()
{
var softwareDevelopers = new List<string>
{
"Brendan Enrick",
"Kevin Kuebler",
"Todd Ropog"
};

ViewBag.softwareDevelopers = softwareDevelopers;

return View();
}

In the View

<ul>
@foreach (var developer in ViewBag.softwareDevelopers)
{
<li>
@developer
</li>
}
</ul>

Notice here that we did not have to cast our object when using the ViewBag. This is because the dynamic we used lets us know the type. Keep in mind that these dynamics are as the name suggest, dynamic, which means that you need to be careful as these are basically magic properties instead of magic strings.

ViewBag and ViewData Under the Hood

So these two things seem to work almost exactly the same. What’s the difference? The difference is only in how you access the data. ViewBag is actually just a wrapper around the ViewData object, and its whole purpose is to let you use dynamics to access the data instead of using magic strings. Some people prefer one style over the other. You can pick whichever you like. In fact, because they’re the same data just with two different ways of accessing it, you can use them interchangeably. (I don’t recommend this, but you can do it.) If you want you are able to put data into the ViewBag and access it from the ViewData or put stuff in the ViewData and access it in the ViewBag.

This is all that the ViewBag property is. It’s just a DynamicViewDataDictionary with the ViewData as its data.

public dynamic ViewBag 
{
get
{
if (_dynamicViewData == null)
{
_dynamicViewData =
new DynamicViewDataDictionary(() => ViewData);
}
return _dynamicViewData;
}
}

Then when we access the dynamic members of the DynamicViewDataDictionary, we are actually just getting this override of the DynamicObject’s TryGetMember. In this method, it’s just using the name of the member we tried to access as the string key for the ViewData dictionary.
public override bool TryGetMember(
GetMemberBinder binder, out object result)
{
result = ViewData[binder.Name];
return true;
}

So for a short answer:

These two objects are two different ways of accessing the exact same data. The ViewBag is just a dynamic wrapper around the ViewData dictionary.

Developers Give Back

This year’s Cleveland GiveCamp was a great success. The event ended with the completion of 23 software projects for 23 organizations who needed the support of a lot of fantastic developers. The GiveCamp event in Cleveland is one of many events that happen all over.

The event brings together non-profit organizations and charities who need assistance in developing software to fit their needs. These people get together with volunteers to figure out what they need and how to best achieve that over the course of a weekend. When the event begins, hundreds of developers gather, split into teams, and work together to complete these projects over a weekend. That’s right, it all happens in one weekend. That means that the event is fast-paced and delivers a great deal of value to the organizations.

I worked on the Euclid Beach Park Now with a great group of people including one other NimblePros team member. We were building a new, dynamic site for the group. Our main goals were to give the site a fresh new look and make it so that updates could be made easily to the site. We also wanted to allow visitors to the site to write about their experiences and memories of the Euclid Beach Park.

The group started with a lot of great .NET expertise, so they wanted to use a .NET-based CMS to allow them to customize it if needed. They decided to use Orchard CMS, so they asked if anyone at the event knew about Orchard CMS. Caitlin Steinert and I raised our hands as people who had used Orchard before. We joined the team.

The group of people working on that project were fantastic and were able to get up to speed with Orchard in just that weekend. We occasionally called in Kevin Kuebler with a question or two, but other than that the group was able to build the whole project in the course of the weekend. The site is now hosted through DiscountASP.NET who offers free Windows hosting for GiveCamp-created sites.

Without such a fantastic group of people there is no way we could have accomplished so much in the course of just that weekend. I’d like to thank the rest of my team for doing such a fantastic job for Euclid Beach Park Now who seemed to really love the site we built for them.

Our team

EuclidBeachParkNowTeam

Overmocking

One of the most powerful tool available to developers testing a legacy code base is the ability to mock out classes that their code depends on. This is of great importance since our unit tests need to limit the scope, and we do this by trying to limit our dependencies. Through mocking we can exchange one dependency on the infrastructure of our application for an in-memory mock.

Sometimes mocking is overused, and I am not just talking about cases where every objected gets mocked to the point where we’re testing nothing. I am talking about a different issue in mocking. I am talking about where developers put on their mocking blinders when unit testing. It’s an easy thing to do, and I’ve done it plenty of times myself.

Setting Up Our Example

We will start of by defining our example. We will have a method to do some sort of calculation (an ideal and easy testing scenario). It will be a legacy code base, which means that it is untested code and probably hard to test. We’ll start off by making it a private static method and put in a nice dependency that one might try to mock to avoid.

private static decimal CalculateFooOnXyz(Xyz xyzItem, 
decimal calculationParameter1)
{
var numbersInCalculation = Repository.GetNumbers()
.Where(n => n.IsActive);

foreach (Number number in numbersInCalculation)
{
// Some code that executes for each one.
}
}

Now that we have this method, which is scary and really needs some testing we’ll take a look at the simple way of testing it; we will use parameter injection to pass in the dependency since we’re static we not easily able to do any other safe forms of dependency injection. When we do this, we end up with the following code.
 
private static decimal CalculateFooOnXyz(Xyz xyzItem, 
decimal calculationParameter1, IRepository repository)
{
var numbersInCalculation = repository.GetNumbers()
.Where(n => n.IsActive);

foreach (Number number in numbersInCalculation)
{
// Some code that executes for each one.
}
}

This is a pretty simple change. We now mock out the repository and pass in the mock in our test and we tell it instead to return the collection we specify in memory instead of requesting the data from the database.

Why This is Wrong

My first question is, what is the name of the method? CalculateFooOnXyz. Notice that I didn’t say, “GetDataFromTheDatabase”. That’s because we shouldn’t be doing that. It isn’t part of the calculation. The numbers returned from the database are required for calculating, so that means that we should have that object as our dependency instead.

How We Change It

So instead of making the repository our parameter, we should make the collection of numbers our parameter. This way we’re depending on the in-memory collection of CLR objects. This is much less of a dependency, and in is not one that needs to be mocked. By doing this alternative we’re better following the Single Responsibility and Dependency Inversion principles.

Our best code for testing will look like this.

private static decimal CalculateFooOnXyz(Xyz xyzItem, 
decimal calculationParameter1, List<CalcNumbers> numbersInCalculation)
{
foreach (Number number in numbersInCalculation)
{
// Some code that executes for each one.
}
}

Comments? Have a better way of doing it? Did I make a mistake?

Custom Model Binders in ASP.NET MVC

In ASP.NET MVC, our system is built such that the interactions with the user are handled through Actions on our Controllers. We select our actions based on the route the user is using, which is a fancy way of saying that we base it on a pattern found in the URL they’re using. If we were on a page editing an object and we clicked the save button we would be sending the data to a URL somewhat like this one.

 

Notice that in our route that we have specified the name of the object that we’re trying to save. There is a default Model Binder for this in MVC that will take the form data that we’re sending and bind it to a CLR objects for us to use in our action. The standard Edit action on a controller looks like this.

[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here

return RedirectToAction("Index");
}
catch
{
return View();
}
}

If we were to flesh some of this out the way it’s set up here, we would have code that looked a bit like this.

[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
Profile profile = _profileRepository.GetProfileById(id);

profile.FavoriteColor = collection["favorite_color"];
profile.FavoriteBoardGame = collection["FavoriteBoardGame"];

_profileRepository.Add(profile);

return RedirectToAction("Index");
}
catch
{
return View();
}
}


What is bad about this is that we are accessing the FormCollection object which is messy and brittle. Once we start testing this code it means that we are going to be repeating code similar to this elsewhere. In our tests we will need to create objects using these magic strings. What this means is that we are now making our code brittle. If we change the string that is required for this we will have to go through our code correcting them. We will also have to find them in our tests or our tests will fail. This is bad. What we should do instead is have these only appear on one place, our model binder. Then all the code we test is using CLR objects that get compile-time checking. To create our Custom Model Binder this is all we need to do is write some code like this.
public class ProfileModelBinder : IModelBinder
{
ProfileRepository _profileRepository = new ProfileRepository();

public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
int id = (int)controllerContext.RouteData.Values["Id"];
Profile profile = _profileRepository.GetProfileById(id);

profile.FavoriteColor = bindingContext
.ValueProvider
.GetValue("favorite_color")
.ToString();


profile.FavoriteBoardGame = bindingContext
.ValueProvider
.GetValue("FavoriteBoardGame")
.ToString();

return profile;
}
}

 

Notice that we are using the form collection here, but it is limited to this one location. When we test we will just have to pass in the Profile object to our action, which means that we don’t have to worry about these magic strings as much, and we’re also not getting into the situation where our code becomes so brittle that our tests inhibit change. The last thing we need to do is tell MVC that when it is supposed to create a Profile object that it is supposed to use this model binder. To do this, we just need to Add our binder to the collection of binders in the Application_Start method of our GLobal.ascx.cs file. It’s done like this. We say that this binder is for objects of type Profile and give it a binder to use.

ModelBinders.Binders.Add(typeof (Profile), new ProfileModelBinder());

Now we have a model binder that should let us keep the messy code out of our controllers. Now our controller action looks like this.

[HttpPost]
public ActionResult Edit(Profile profile)
{
try
{
_profileRepository.Add(profile);

return RedirectToAction("Index");
}
catch
{
return View();
}
}

That looks a lot cleaner to me, and if there were other things I needed to do during that action, I could do them without all of the ugly binding logic.

July HudsonSC

The Hudson Software Craftsmanship Group will be meeting July 20, 2011 at 6:00 p.m. with people arriving as early as 5:30. As usual, we will be ordering pizza, and some of us will be gathering at Kepner’s Tavern after the event to continue our discussions.

If you haven’t attended HudsonSC yet, I highly recommend the group. We have a fantastic group of software craftsmen who are always trying to improve their skills as developers. If you’re interested, please sign up to let us know you’re attending. We will also not turn people away at the door, so feel free to just show up for the event.

The event is located in downtown Hudson at 102 First Street. When you enter the building, just go to the second floor and turn right. Keep walking straight, and you will arrive in our meeting room.

This month I am going to suggest to the group that we try an AppKata instead of our usual programming exercises. These focus more on real-world scenarios and include changing requirements.

We are very loose with our agenda, so if you want to bring in something to talk about or an activity to do, go for it. In fact, you can show up and suggest topics and ideas for that day’s meeting.

See you there!

Rock Paper Azure Contest Bot Tips

A Rock Paper Scissors tournament is being put on by the Windows Azure team. The competition is a fun challenge designed to be a fun way to compete against other developers for some bragging rights. If bragging rights aren’t enough for you, there are prizes also being given out.

1st: XBox 360 / Kinect bundle
2nd: Kinect
3rd: $50 Gift Card

To join the competition, you just have to download the starting code and set up an Azure account to submit your code. They have detailed instructions on the site. You can use a code to get the Azure account set up for free.

How the Rock Paper Azure Game Works

You might be asking, isn’t Rock Paper Scissors just random? Basically, yes. Against a human opponent there will be trends, but with a computer you can be far more random. There are a couple of adjustments made to the game.

To win the tournament, you have to beat the most number of other bots. Beating a bot means that you play RPS until one player wins at least 1000 points. If there is a tie on a point, then the winner of the next point wins the points for the tie as well. This means that if you can get a few ties in a row and then win, you can win a lot of points.

How do you win ties? They’ve added a new move called “Dynamite” That move beats all of the basic moves: Rock, Paper, and Scissors. You can only throw Dynamite 100 times per match, so use it wisely.

Isn’t the dynamite broken? No. They’ve also added a move called “Water Balloon”, which only beats dynamite. You can use as many Water Balloons as you want, but be careful they’re beaten by all of the standard moves.

Rock Paper Azure Bot Tips

Look at Log Files

When you submit your bot to the Rock Paper Azure competition and view the log file from each match your bot had with each other. It will show each point in the game, what each player did, and who got the point. Make sure you’re checking games you lose to see why you lost and also examine some games that you won. This is important so you can see which decisions you’re making that help you win.

Tell Yourself Why You Made Each Choice

You are able to write to the log yourself. If you decide to use Dynamite or a Water Balloon, print out a log message telling yourself why you did it. Then take a look at the log of a game and see if you made the right or wrong choice and adjust your bot accordingly.

Don’t Throw Too Many Water Balloons

A problem that I’ve seen with a lot of bots is that they throw too many water balloons. If I can make my bot trick yours into throwing Water Balloons, I will. Be careful of these tactics (my bot sometimes uses them).

Tactics to use and watch out for:

  • Use only 99 dynamite, because your opponent’s algorithm will keep throwing water balloons.
  • Have an intentional gap where you don’t use dynamite. If your opponent was trying to predict your dynamites they will throw some water balloons and you will win.
  • Start delaying your dynamite throws if your opponent starts water ballooning you.

Don’t Be Too Predictable

This sounds obvious, but I’ve seen plenty of bots which are not using random move selection, I write code to defuse them specifically. There was one bot which always countered your last move, so if you do the same move twice he beats the second one. I wrote the code to disable him and he only got 1 point against me after that.

Write More Than One Strategy

My bot has more than one strategy. I have Water Balloon strategies and Dynamite Strategies. Essentially, my bot is able to change how it decides on water balloons and how it decides dynamite based on information at runtime. What this lets me do is either change strategies mid game or select certain tactics to face certain opponents. I am able to check the name of the bot I am facing and use the strategy designed to beat them.

Summary

Go give the competition a shot. There are prizes for the next couple of weeks. Go get a free Azure account set up and see how well you do.

NimblePros is Hiring Developers

NimblePros is looking for new team members as passionate about writing great software as we are. We don’t believe in writing crappy code, and our team is always improving in order to write better code. We continually adjust our processes to promote our goals of reducing waste and delivering better software.

I enjoy working with the NimblePros team, because they’re a fun group of individuals working towards the same goals I am.

If you would like to join the NimblePros team, you can contact us directly by emailing careers@nimblepros.com. Please let us know what interests you about joining our team and what you’re really passionate about.

Here are a few tidbits about us:

The NimblePros team was founded by our area’s Microsoft Regional director, Steve Smith.

We believe that board gaming is great way to build a cohesive team.

NimblePros sponsors and its team runs the local Software Craftsmanship group.

Why to Join a Software Craftsmanship Group

Like other professional community groups, a software craftsmanship group is supposed to offer benefits that would make a working professional take time from their schedule to attend. These benefits come in many forms: networking, support, feedback, education, self-improvement, and the list goes on. Not all of these benefits will resonate with everyone, and there are plenty that I did not name applying to many individuals and situations. A software craftsmanship group can supplement or replace an existing group that you’re attending.

A common complaint that I hear from attendees of other groups is about how the discussions at dinner after the meeting is the most worthwhile part of the meeting. When I hear this, my first instinct is that these people need to start going to software craftsmanship meetings in addition to or instead of their current groups.

What is Software Craftsmanship?

Software craftsmanship is often described as a movement in the software industry of like-minded people who believe in a set of values which can improve the software we write. The Software Craftsmanship Manifesto describes in what these like-minded individuals believe.

I’ve often found it interesting how the Software Craftsmanship movement seems to be an extension of the agile software development movement. I and most of the members of the Hudson Software Craftsmanship group are all developers who either work at companies follow some form of agile development or are trying to move towards it. In fact the 4 main values described in the Software Craftsmanship Manifesto specifically describe how in the attempt to achieve the values described by the Agile Software Manifesto these ones were found to be indispensible. It is the idea that pursuing one set of values that have proven to be very useful, another set has been found to be extremely valuable.

Dispelling Misinformation

There are some people who have bad opinions of software craftsmanship, and I’d like to take some time to address some of those concerns incase any readers have heard of them or share them.

It’s not elitist.

I’ve heard software craftsmanship referred to as being elitist. In my experience, this is entirely not the case. I would believe that there are people among the community that fit this description, but those people would be outliers. We are welcoming of people of all skill levels who are looking to write cleaner, better software. I for one don’t even think that everyone will or even should be software craftsmen. If you enjoy the way you’re doing this, by all means continue. I don’t believe that my methods, practices, values, and beliefs are any better than anyone else’s. We are a group that shares our beliefs and want to work together to improve ourselves.

It’s not ALT.NET.

I’ve heard Software Craftsmanship compared to ALT.NET by some people, and I can see why the comparison would be made. Both are movements in the software industry to try to do things better than we have been doing them in the past. The ALT.NET community is like-minded individuals in the .NET community who are against the direction, guidance, and tooling that has/had been coming from Microsoft. While I do not follow that guidance either, I am not openly against it. In fact, I realize that the methods that I believe in and use in my own development will not work for everyone.

Software Craftsmen will help each other move away from that tooling and guidance, because the people we are helping want to move away from it. For many developers the control-based, do everything for me approach that often comes with that tooling is perfectly acceptable. There are many developers who are not going to follow the SOLID principles, and they’re not going to be inverting dependencies and writing unit tests either. That’s OK! Other people are not wrong just because I think I can write better code by doing things differently.

It’s not just about code.

Many developers are afraid that software craftsmanship places too much of a focus on writing code. From looking at software craftsmanship from the outside, this is a very valid argument to make. It is, however, mostly based on what is made visible from outside.

The aspects of a software craftsmanship group meeting which people go home and blog about tend to be the katas, exercises, and techniques. Why? Because it is not as easy to bottle up a great blog post on an open discussion among a large group as it is to post about some cool programming exercise. Our community as a whole also tends to really like posts showing source code, so people return from the meeting and post their exercise results. We’re more about thinking and improving our entire development process than just code.

We focus on the micro through programming as well as the macro through community involvement. We focus on how to improve as a business, how to work better with our clients, customers, and peers, and how to do all of this slowly with manageable, incremental change.

What Happens at a Craftsmanship Group?

Our main focus at a software craftsmanship group is to reinforce the skills, beliefs, values, and principles of our members. We have discussions, which are based on topics in the industry. We want everyone thinking, questioning, and improving. We don’t want you to even accept things that other craftsmen tell you. Go to the meeting ready to question others. We need to back up our thoughts and ideas, and most of all we need to be willing to try new things.

Why lightning talks?

Most user groups feature a single person transferring knowledge to the masses who attend the group. In these situations the knowledge flow is unidirectional, and we don’t find that to be as effective as having people of all skill levels discussing the topic. A lightning talk is a great way to introduce a topic by spending 5 to 10 minutes discussing introducing the topic briefly. These talks then open the floor for immediate continued discussion or become ideas for later open discussions at the group.

Why open discussions?

Discussions allow us to share our ideas and get feedback on them. We will often discuss values and principles of craftsmanship. We also use this as a chance to discuss how we’re each solving some similar challenge we’re all facing. Some topics we’ve done in the past revolve around automated unit testing. These often are focused on some type and how to do them better. I recently was involved in a craftsmanship discussion revolving around the concept of BDD and went from low to high level. Some topics deal less with coding than the infrastructure we as developers depend on like our continuous build implementations and our database change management systems. Other common topics deal with how to get buy-in from a business to follow the practices that we believe to be beneficial.

Why code katas?

A kata is designed to give you a consistent experience doing the right things. Like the martial arts equivalent it is not something you would use in a real-world situation, but it is designed to emulate one. It goes through a set of steps where a master of the art has imparted wisdom by showing the steps to be taken when presented with certain challenges. These katas will let you know how and why the master takes certain steps at certain points and are designed to be repeated so that we immediately respond with the correct solution when presented with a certain challenge.

Why programming exercises?

We have all learned to program, and we need to keep ourselves in practice. No, our day jobs are not practice. Exercises are designed to give us practice so that we have recent experience solving challenging problems to assist in our everyday programming tasks. Many people believe that comparing software developers to musicians or athletes is a stretch, and I will agree with them that there are great differences between these groups. We are, however, all skilled individuals and if we’re even remotely similar to the musician or the athlete, then we need to also be practicing.

I’ve been presented with many real-world challenges where I say, “I can use the same technique here that I use when solving the Greed kata.” That being one example of a programming exercise where I have tried solutions and found some that work very well with the practices and techniques that help me write cleaner code.

What should I do next?

Find a local group of software craftsmen. If there is not one in your area or the one in your area is more than an hour drive to get to, then start one. Gauge the interest, and start making noise about it. Other people interested will join the group, share their ideas, experiences, and trials, and keep the group interesting.

Good luck!

The Software Craftsmanship group that I run is located in Hudson, OH. We are between Cleveland and Akron, and we have members from both of those locations. If you're in the area, we look forward to seeing you at one of our events.

Go Try NuGet. Seriously.

NuGet is best described as the tool from Microsoft that lets you add references to your project directly from the NuGet feed while storing and managing them locally. It lets you keep your references local to your source code, which will help you keep your software project encapsulated. When a package you use gets an update, you can ask NuGet to update your local version of the package.

When telling people about NuGet it is important to explain how powerful it really is. NuGet is not just a collection of libraries to include in your bin folder. It will actually install the package into your project. I will show you what I mean.

Installing NuGet

NuGet can be installed through the Visual Studio Extension Manager. From within Visual Studio, open the Tools menu and select Extension Manager. Once in that window, select the Online Gallery and search for “nuget”. Then you just have to tell it to Download nuget. This will require a restart of Visual Studio.

NugetExtensioinManager

Using NuGet to Install a Package

Now that NuGet is installed we can start using it. There are two ways to do this, and I will start with the one that is the easiest. All we need to do is right click on out project’s references folder and select “Add Library Package Reference…”

NugetAddReferenceContextMenu

From the window that opens, we want to make sure that we select the Online section on the left and select All. Now we use the search box to search for the package that we’re trying to install. And we click the Install button. NuGet will get the package you requested as well as any Dependencies listed. Notice in the following image that WebActivator is listed as a dependency of this package. NuGet packages will often add files other than just dlls to your solution. Isis, which is the package shown here will also include its own bootstrapper, which will allow Isis to have routes mapped for itself, so you can begin using the application immediately.

NugetInstallIsis

Viewing the Results of Installing a Package From NuGet

Thanks to packages being able to includes these files allowing themselves to be automatically configured, I already have the Isis ASP.NET Control Panel installed. It’s not just a reference in my bin folder, it also gave me this bootstrapper file. I don’t have to do any extra work installing Isis.

SolutionAfterIsisInstall

Thanks to NuGet getting me all the files I can navigate to the Isis ASP.NET Control and begin using it immediately.

IsisControlPanel

There is also a command line interface for NuGet. If that is your cup of tea, then I recommend checking it out instead.

The Isis ASP.NET Control Panel

In case you are wondering about the Isis package that I installed, it is a relatively new Open Source project based on a few projects that Steve Smith and I have worked on in the past. We are creating an ASP.NET control panel which can be easily installed (as you’ve seen already) into any ASP.NET application and provide tools to help manage, develop, and diagnose the application.