Thursday, November 21, 2013

TDD Controller creation from unit test - Part 1

The dev team that I am currently on is making a huge effort to adopt TDD.  One discussion that comes up every now and then is what to do with your MVC controllers when it comes to TDD.  A couple of us say that you should still start with your test and a few say that it is just too easy to create a control without a test and starting from your test is just a waste of time.  This post is going to show you how easy it is to start with your test first and follow TDD the correct way using a few Resharper shortcuts.  These shortcuts are not required and there are other ways to accomplish the same thing, but Resharper does make it easier and quicker.

Do not be intimidated by the number of steps below.  I recorded the steps and it took less than two minutes to perform all steps.  You can see the recording of the steps in this video below.





1. The first thing that you need to do is create a blank solution and then add an ASP.NET MVC 4 Web Application and Unit Test Project.  If you don't know how to do this, you can read my my post about and it here.  When you are done, your solution should look similar to the following:





















2.  Add a Unit Test to your test project by right-clicking on your test project, then selecting Add -> Unit Test...










3.  Delete the provided TestMethod and use the Test Method Snippet that I introduced you to in my first blog post to give you the following test method stub.











4.  After the Assert comment, type the following:

     Assert.IsNotNull(homeController);

5.  With your cursor at the end of the line you just typed, type Alt-Enter and you should see something similar to the following:










6.  Select "Create local variable 'homeController'" by typing Enter






7.  Type the End Key















8.  Type Ctrl-X and move your cursor to just below the Arrange comment and type Ctrl-V to get your method to look like the following:












9.  Change object to var, type End, type Backspace, then type  = new HomeController();  You should now have the following:











10. With your cursor still positioned at the end of the line, type Alt-Enter and then select "Create class 'HomeController'"









11.  A class named HomeController will be created below your test method as seen  below.














12. Type End and then F6 to get the following menu:








13.  Select 'Move to Folder'.  This will open the Resharper Move to Folder dialogue as seen below.




















14.  Change the Target Folder to the Controllers folder in the ASP.NET MVC 4 Web Application that you created in step #1.  In my case, it is Namyaf.WEB\Controllers as seen below.









15.  Click Next and you will see your new file within the location you specified.













16.  Open HomeController.cs

17.  Make the HomeController class inherit from Controller

18.  Add the following using directive

     using System.Web.Mvc;











19.  Build the solution.  If you have errors, correct them.  If you cannot correct them, let me know and I can help.

20.  If you run your test within MSTEST or Resharper, you will see that the test passes.


Resharper test
MSTEST


















I hope you enjoyed this post and learned something.  In part two, I will be adding the controller actions and continuing with a little TDD.

peace yo!


Wednesday, November 13, 2013

F#

I decided recently that I was going to become a better programmer.  Not that I am a bad programmer, but I know that I could be better.  A few things that I think will make me, as well as others, become a better programmer are as follows:

1.  Start this blog
2.  Read more blogs
3.  Watch more technical videos
4.  Attend more live technical events
5.  Write more clean code
6.  Learn more programming languages or programming related technologies.

If you have read any of my posts, you know that I have been doing most of these already.  One item that has been on my list for a while falls into #6 on the list and that is the attempt to learn F#.  This post is not going to teach you F#, but may influence you to at least execute some F# code.  What I wanted to do for this post was to share my first real step in learning F#.

After searching for for a quick tutorial on F#, I found one and decided to open Visual Studio and begin the journey into F# land.  Before I could create a blank solution to determine what project type to add to my blank solution, I noticed a type of project named F# Tutorial.  Not knowing what this really was, I decided to select this one and take a look.












After creating the project, I remembered doing this in the past with Visual Studio 2010, but right away I noticed that the samples provided were a little different.  What I mean by that is that within the first few lines, which are comments, there is mention of something called F# Interactive and how you can highlight a section of the code and execute the code within F# Interactive.  If you are using Visual Studio 2010, the F# Tutorial project does not mention F# Interactive even though it is available to use.  Someone was smart and added the comments below to the Visual Studio 2012 version of the Tutorial.






So, I gave it a try and it was that easy.  The samples were enough to get me started and had simple string examples, lists, classes, recursive functions, and also an example connecting to a database.  Below are the two steps that I took to execute my first F# code within F# Interactive:

1. Highlight the Strings example

















2. Either Press Alt-Enter or right-click and select Execute in Interactive  



















As you can see it is pretty easy to execute F# code in F# Interactive and be on your way to being a better programmer.  I'm not sure when or if I will ever use it, but at least I know a little more about F# than I did yesterday.

peace yo!

Monday, November 11, 2013

dotPeek

I am in the beginning stages of a project where I need to create a class library that sort of acts as a proxy that will call a third party assembly.  The third party assembly is being called directly and I need to sort of duplicate some of the code.  Without going into too much detail, I will explain the issue and how I solved it.  Basically, this third party assembly was being called something similar to the following:

Dim resp As String = SubmitTransaction(req, ThirdPartyUtil.RequestId)

My first issue is that the code is in VB.Net, but that discussion is for a future post.  My next issue was that I needed to know what ThirdPartyUtil.RequestId is and how do I duplicate that in my code.  After doing some more research, I found another project that used the same third party assembly, but a little differently as you can see below:

string resp = SubmitTransaction(req, MainAssembly.GenerateRequestId());

As you can see, this code is much better because it is in C#, but it still has something that I don't know too much about and that is the call to MainAssembly.GenerateRequestId().  What I had to do was look through the VB.Net and C# code to try and figure out what this property and method call did.  Well, after getting lost and going nowhere, I asked a co-worker about it and they sent me some documentation on the assembly.  This didn't help much, so what could I do next?  After thinking about it for a few, I decided to see if dotPeek would provide any details about it.  If you are not familiar with dotPeek, it is a tool by JetBrains that can be used to decompile assemblies and I highly recommend at least installing it and learning what it can do.  This tool can be downloaded for free at http://www.jetbrains.com/decompiler/.  Now, without showing details on that exact assembly loaded in the tool, I was able to pull out the method and property and they ended up looking like the following:

MainAssembly:

public string GenerateRequestId()
{
   return ThirdPartyUtil.RequestId;
}







ThirdPartyUtil:

public static string RequestId
{
   get
   {
      return Guid.NewGuid().ToString("N");
   }
}





This was great news to me and will allow me to move forward without wasting too much time.  All I needed to do was to provide this same functionality which is to return the guid in the same way the code above did.  

For a quick demo on dotPeek, visit the main page of dotPeek and view the video which is only about five minutes long.  Also, if you don't use resharper download the trial version from JetBrains while you are there.  

peace yo!

Sunday, November 10, 2013

Future of Coding?

Last month, I attended a meetup with the group named Software Craftsmanship McHenry County where "Uncle Bob" Martin gave a presentation on Clojure which is a functional programming language.  I don't know much about functional programming languages, but I was able to keep up with Uncle Bob for most of the presentation. Although most of the discussion was on Clojure, Lisp, functional programming, and monads, the beginning was the most important and interesting part for me.  The whole presentation is pretty good but I would recommend watching the video starting from 6:50 through 24:30 if you aren't really interested in functional programming details and functional coding yet.  This  portion of the video discusses the future of threads, cores, solid state drives, databases, data access, no sql, CRUD database, and how writing code may be different in 5 - 10 years.  This portion is basically the lead in to how functional programming might be the solution.

The whole video can be found on YouTube here.

peace yo!

Friday, November 8, 2013

Blank Solution (Visual Studio)

A couple weeks ago, I was reviewing a project that a friend of mine was working on and noticed that he had a solution named similar to ProductName.Web.  This solution had an Asp.Net MVC Application with the same name along with other non web type of projects.  I asked why he didn't have a main solution named ProductName with other projects under that named ProductName.Web and ProductName.Whatever.  He said he didn't know of a way to do that, so I mentioned starting off with a blank solution.  To my surprise he was unaware of how to create a blank solution.  Fast forward a week or so later where I mentioned this to a co-worker and they informed me that they didn't know either.  Knowing that some people do not know that the blank solution exists confirms my belief that nothing is too simple to write about.  There is always something that you know that others don't and always something that others know that you don't know.

To start with, I wanted to list a few benefits of creating a blank solution first and they are as follows:

1.  Better grouping.
2.  Avoid having to rename things (projects, folders, etc.) in the future.
3.  It is clean
4.  It is what the cool kids are doing these days.

Steps for creating a Blank Solution and adding projects to it

1. Open Visual Studio and select File -> New -> Project







2. Expand Templates -> Other Project Types -> Visual Studio Solutions and then add a name to the Name field. In this case, I named it Namyaf and then clicked OK.


3.  As you can see, the blank solution is created with nothing in it.  


4.  If you open Windows Explorer and go to the location of your new solution, you will see one solution file.


5.  One thing that some people don't know that I wanted to mention here is that solution files are just text files and you can view them in notepad as seen below.  This one is very basic as you can imagine, but they will get filled with other stuff as projects are added.














6.  The next step is to add a project to the solution that you just created.  To do this, right click on the solution in Visual Studio and select Add New Project.





7.  Select Asp.Net MVC 4 Web Application, type Namyaf.WEB, and then click OK..


8.  Select the Empty template and also make sure the Create a unit test project is checked because we all know TDD is the way to go.


9.  Now, when you browse to your solution folder in Windows Explorer, it is much cleaner as you can see below.


Once again, I hope you learned something and enjoyed reading and following along.

Peace Yo!


Thursday, October 31, 2013

var object

Last week we were doing some mob programming and a co-worker was telling the person doing the typing to type the following:

var object ...

Now, this obviously doesn't work and intellisense will yell right away, but we all knew that he did not mean what he said.  Either way, it was funny at the time and we got a laugh out of it.

After that meeting, I was working with another co-worker and we were doing some peer programming. One of the statements that we wanted to write something like the following:

var event = GetEvent();

Now, event in this case may be a sporting event so it would make sense to call it event.  The issue is that event is a C# keyword and cannot be used like this.  My question in both examples above is what if I want to call it an event and use event as the name?  The answer is to use the @ symbol in front of it.  For example the following would make the statement legal and will compile.

var @event = GetEvent();

Doing something like this in my opinion, as well as others, is bad practice and should not be done.  If you are wondering what we did, we just changed event to eventRecord and wrote it as follows:

var eventRecord = GetEvent();

Now, most normal people will stop there and call it a night.  I decided to do a few other tests with the var keyword, which after my tests make me think var isn't really a keyword, but some sort of almost keyword.  So, I did the following which is simple and straight forward:

var i = 5;
Console.WriteLine(++i);

For fun, I then changed it to the following and thought it would for sure blow up:

int var = 5;
Console.WriteLine(++var);

To my surprise, it compiled fine and ran fine.  This confused me and I thought it for sure was a bug or something else was wrong.  So, I decided to try something else.  What would happen if I changed int to var and wrote the following:

var var = 5;
Console.WriteLine(++var);

Would this work?  Should it work?

Well, it does work and it may have to do with some sort of backwards compatibility.  Since the var keyword was introduced in C# 3.0, previous code could have something like the following:

int var = 1;

This sort of makes sense because the assembly that is created will change the var to int.  The var is not included in the final assembly code and is just a C# thing.  I will provide another post about what your code looks like after it is compiled and then decompiled in the next couple days.

What's the point of all this?  Nothing, or maybe just to get me, or you, to think about things in more detail and share that knowledge.  Other than that, I think all my code will start off with var var ... just to see if someone complains and tells me to change it.

peace yo!

Monday, October 28, 2013

Bookshelf

Last month, I started a new journey with a new company after being with another company for just shy of four years.  I remember my first few days or so with my previous employer and I remember making separate trips to my car to get some books that I as a developer thought I needed to perform my job effectively and efficiently.  Looking back at those four years, I cannot remember opening any of those books for any of the technical knowledge in them.  I've been at my new company for a little over a month now, and I have yet to bring any of those books to my new cubicle.  The only thought that I had of bringing them was to use them as a monitor stand like many other developers as well as myself who are too cheap to buy a real stand.  One could argue that the need to read a 500 to 1000 page book of if statements is not a need anymore because of the amount of articles, blogs, and videos on the internet.  This statement is false in my opinion and developers should be reading more books than they currently do.  The art that puts chapters full of technical knowledge is getting lost and we may suffer from it.  It is similar to how musicians no longer have to think too much about how their songs tie together in their albums.  We live in a text message/youtube/itunes/google world where texting, watching short videos, downloading one song, and skimming articles is the norm.  With all that said, there is still a need for books, maybe not physical, but books that you can read online.

The way that I continue to read technical books is by subscribing to Safari Books Online.

By doing this, I have replaced this bookshelf:

Physical bookshelf in garage above toolbox
With this bookshelf:

Virtual bookshelf within Safari Books Online

A few great features of Safari Books Online that I like are as follows:


1.  Notes/Tags/Highlighting - You are able to create notes by selecting text within the book.  These notes are available even after you remove your book from the bookshelf.


2.  Bookmarks - You can add bookmarks to the books you are reading.  If you remove a book from your bookshelf, the bookmark will not go away and will stay there if you add the book back to your bookshelf later.


3.  Great Selection - There is a great selection of books new and old.  The following is a book that I plan on reading soon that a co-worker recommended.  I can't remember searching for a book that wasn't available on Safari Books Online.


4. Price - The price is ridiculous, but in a good way.  You can start a free 10 day trial and after that it starts out as a 10 book bookshelf at $19.99.  You can change that like I did to a 5 book bookshelf for $9.99, but if you want to go back to a 10 book, you may have to pay $27.99 for it.  For me, the 5 book is perfect. 



5. Mobile - Everything you do is available on your phone.  


6.  Videos -  I haven't watched any videos yet, but there are some videos to choose from. 


If you are in a technical position and haven't sign up yet or thought about signing up, then you may not be smart. 

peace yo!

Saturday, October 26, 2013

Test Method Snippet (Visual Studio)

If you practice Test-driven Development (TDD) you know there are many standards and patterns that you can use.  One pattern that myself and others on my team like is the Arrange, Act, and Assert pattern when writing our tests.  This pattern is included in the existing tests for you when you create a new ASP.NET MVC 4 Web Application and then select the option to Create a unit test project to it.  What I noticed is that when I use a snippet to create a new test method, the Arrange, Act, and Assert comments are not there.  This is not a big deal to most as they can remember to Arrange, Act, and Assert, but I would like the comments added to my new test methods when I use a snippet.  Along with not liking that my test methods do not have the comments, I also realized that the name of the new test method of MyTestMethod is dumb and should be changed to our naming standards which came from Roy Osherove.  The naming standard we agreed on is [UnitOfWork_StateUnderTest_ExpectedBehavior] and an explanation of this can be found at Roy's site here.  Making these changes in the snippet is simple and the steps to accomplish it are below.

1.  Open Visual Studio.

2.  Go to Tools -> Code Snippets Manager.


3.  Change the Language to Visual C# and expand the Test folder.

4.  Copy the path located in the Location.

5.  Open Windows Explorer and browse to the location copied in the previous step.

6.  Make a Copy of the testmethod.snippet. 

7.  If you want to still use the original snippet in Visual Studio, rename it by adding a prefix.  If you do not want to use the original snippet, you need to make sure it does not end in .snippet and append something to it or change it.  I prefer to keep it so others that are not aware of my new snippet can still use the old one, so I added a prefix of "Orig_".


8.  Open testmethod.snippet in notepad, Visual Studio or any other program that will allow you to edit text.

9.  Change the text within the Shortcut element from testm to testmm.  The reason for the second 'm' is that there are other methods that may show up from IntelliSense and adding the second m will eliminate them from showing up and the snippet will be invoked by typing testmm followed by a tab.

      old: <Shortcut>testm</Shortcut>
      new: <Shortcut>testmm</Shortcut>

10.  Change the text within the Default element from MyTestMethod to to UnitOfWork_StateUnderTest_ExpectedBehavior.

      old: <Default>MyTestMethod</Default> 
      new: <Default>UnitOfWork_StateUnderTest_ExpectedBehavior</Default>

11.  Add the following three lines of comments to the method just before the text  $end$ within public void $name$()
         
          // Arrange          
          var x = false;
          var y = new y();
          
          // Act          
          x = y.DoStuff();
          
          // Assert          
          Assert.IsTrue(x); 


12.  Save the file.

13.  Close all instances Visual Studio if there are any open.

14.  Open a Unit Test Project within Visual Studio and set your cursor within a test class.

15.  Type testmm followed by a [tab].  As you can see, the snippet will now display the following which has our new method name and the comments to help us create good tests.





Hopefully you learned something from this post and it will help you modify or add more snippets to help you code faster and better.

peace yo!