Mostly programming and video games.

Recently, I needed to view my website on an iPad in a test environment. My test server is on an internal network, which is impossible to view without write access to a hosts file.

I’m glad to say that I finally managed to bend the iPad to my will, and – although it feels like it may have gotten the best of me – my sanity is mostly intact. Since I am such a generous person, I will spare you from hours of frustration and tell you how to edit the hosts file in iOS. Just follow these instructions, and everything will be okay.

First of all, if you haven’t jailbroken your device, you will need to do that first.

Notice: I do not recommend jailbreaking your device!!!

With that mandatory disclaimer out of the way, if you have to do it, I suggest upgrading (or downgrading, if you made the mistake of upgrading to iOS 6) to iOS 5.1.1 and using Absinthe 2.0.4 to jailbreak. (See here for a tutorial.) The folks at Chronic Dev Team and iPhone Dev Team have done a great job at making it a mostly painless process. (If you want to jailbreak a different version of iOS, then… well, good luck to you.)

EDIT 4/15/2013: Shortly after I wrote this, a tool called Evasi0n made it possible to jailbreak any version of iOS up to and including 6.1.2, but not 6.1.3. (See here.)

Once that’s done, open Cydia (which will appear on the springboard) and download iFile. You can spend a few bucks to get the full-featured version, but you don’t need to for what we’re doing.

Next, launch iFile and navigate to the root (/) directory. Tap on the hosts file, and select the option to open it with Text Viewer. From here, you should be able to edit and save the file.

This is all pretty standard stuff to anyone with Unix experience. However, there is one thing about the hosts file in iOS that tripped me up for HOURS:

Make sure you leave a blank line at the end of the hosts file!

For whatever reason, the operating system simply refuses to read the last line of the hosts file. Anything you put there will be IGNORED.

That’s it. Have fun! And please let me know if you find a decent five row keyboard in Cydia. I literally cannot function in a terminal without ARROW KEYS.

If you’ve been paying attention, you may have noticed that lately I’ve taken an interest in Unixy things. That’s right. Unixy is a word.

I’ve tried Ubuntu a few times but was never very happy with the performance. When I learned that Lubuntu can run the same packages as Ubuntu but is faster, I had to try it out. The difference in performance is noticeable. I’ve been running Lubuntu alongside my Windows 7 install for a week or so now and come to prefer it.

As it turns out, the difference in performance is mostly due to the LXDE desktop environment that comes bundled with the Lubuntu desktop installation. The slowness I experienced with Ubuntu was mostly due to the Unity desktop environment. (I had the same problem with GNOME on Ubuntu, although I liked its UI better than Unity’s.) I think this means that any ‘buntu distribution will be more responsive using LXDE instead of Unity.

I can’t function very well without keyboard shortcuts, and I can’t find a cheat sheet anywhere, so here’s one for you (but mostly for me). Some of these shortcuts are specific to LXDE while others are specific to Openbox – the window manager that comes with LXDE. You can modify any of them by going to ~/.config/openbox/ and opening the file ending with rc.xml. (See this page of the Openbox wiki for details.)

Note: The “super” key is usually bound to the Windows key on keyboards which have one.

Default LXDE/Openbox bindings

Action

Binding

Go to desktop (direction)

ctrl + alt + arrow

Go to desktop (number)

super + f1/f2/f3/f4

Send to desktop

shift + alt + arrow

Toggle show desktop

super + d

Close window

alt + f4

Hide window

alt + esc

Window menu

alt + space

Next window

alt + tab

Previous window

alt + shift + tab

Go to window (direction)

super + shift + arrow

Toggle fullscreen

f11

LXDE specific bindings

Action

Binding

Alt. binding

Window list (sticky)

ctrl + alt + tab

PCMan File Manager

super + e

ctrl + alt + d

LXPanel Run

super + r

alt + f2

LXPanel Menu

alt + f1

ctrl + esc

LXTask (task manager)

ctrl + alt + del

Open terminal

ctrl + alt + t

Lock screen

ctrl + alt + l

Lubuntu specific bindings

Action

Binding

Take a screenshot

alt + print screen

I’m not sure about all of these, so let me know if I missed any or put them in the wrong places.

Over at the Raspberry Pi forums, a lot of people have come up with a lot of great ideas for connecting the Pi to a Motorola Lapdock. There are so many ways to do this, in fact, that I found it really difficult to figure out which one I should go with. I couldn’t even keep all the parts straight in my head, so I made a diagram:

EDIT 9/28/2012: If your Pi is model B revision 1.0 + ECN0001 or revision 2.0, then you don’t need connections 3, 4 or 5. Also, you don’t have to cut the 5v wire in connection 2. This makes things a lot simpler, so it is a good idea to get one of these later boards if you can. See this post for the instructions to find out which revision you have. See this article for the pics.

It’s a little bit confusing so I’ll explain what the various lines mean:

The letter M (for male) denotes a connector on the Pi or Lapdock, whereas the letter F (for female) denotes a port.

The Pi (upper) has three ports that must be connected: a HDMI port for the display, a USB port for the keyboard/trackpad input, and a micro USB port for power.

The Lapdock (lower) must connect to the Pi’s display port via a micro HDMI connector. This is connection 1 in the diagram.

The Lapdock must also connect to the Pi’s keyboard/trackpad port via a micro USB connector. This is connection 2.

The Lapdock can connect to the Pi’s power port via either of its two USB ports, or via its micro USB connector using a Y-adapter. These are connections 4 and 3, respectively. Alternatively, the Lapdock doesn’t have to connect directly to the Pi’s power port at all. Instead, we can power the Pi externally. This is connection 5. These connections are indicated by dotted lines because only one of them must be present.

Once I had a diagram, I set out looking for the parts. What I really wanted was a solution that required the least amount of money, clutter, and effort. Unfortunately, nobody seems to make a micro HDMI female to HDMI male adapter cable or a micro USB female to USB male adapter cable, so every option requires multiple parts from multiple sellers. Hopefully, this guide will make finding the right parts a little easier for you than it was for me.

Note: Some of the parts described below have multiple names. For instance, a coupler is sometimes referred to as a gender changer or a female to female adapter. An extension cable is sometimes referred to as a female to male adapter cable or a port saver (for HDMI). Keep this in mind if you can’t find what you’re searching for.

Disclaimer: I can’t vouch for any of these websites. You should always be careful who you give your information to online. Also, many of these stores are scattered all over the globe. Expect long shipping waits from those that are overseas.

I found this cable at DX in China and at All4Cellular in the US. The latter only sells it bundled with a micro HDMI extension cable, which you might want anyways. It’s also available on eBay from this seller in China, or from this seller in the US.

The adapter, which you’ll see used again and again in the other solutions below, is extremely rare. You can find it at Focalprice or on eBay from this seller and this seller. In any case, it’s shipped from China.

Option 2: Micro USB female to USB male adapter + USB extension cable

This is the second instance where this adapter would come in handy. See option 2 for the link. The cable is very common.

I found this adapter on eBay from this seller in China. There’s also a cable adapter from the same seller right here, and another type of adapter from this seller, also in China. The other cable is standard.

Connection 4/5: Power

EDIT 9/28/2012: In case you’re just skimming, see my edit at the top of this article before you read this section.

You can use a standard phone charging cable (micro USB male to USB male adapter cable) to connect either of the Lapdock’s standard USB ports to the Pi’s micro USB port. This is connection 4 in the diagram. You can find the cable at just about any retail store.

Alternatively, you can plug your standard phone charging cable into any other power source, such as a powered USB hub or an electrical outlet with a 5v 2000mA USB detachable charger. This is connection 5 in the diagram. The charger usually comes bundled with the cable.

Connection 2+3: Keyboard/trackpad/power Y-adapter

EDIT 9/28/2012: In case you’re just skimming, see my edit at the top of this article before you read this section.

If you’d like to have one less cable attached to your Pi, you can use a Y-adapter to connect the Lapdock’s micro USB connector to both the Pi’s standard USB port and the Pi’s micro USB port.

You have a few options that involve splicing and a few that don’t. Here are a couple that don’t:

I found this Y-adapter at Opentip.com in the US. See above for the links to the other adapters.

For the adventurous

If you don’t mind splicing (or even possibly soldering), you can find a multitude of ways to accomplish this at this thread in the Raspberry Pi forums. Some of them are really cool, like this one by user selectnone and this one by kimondouk.

Let me know if you find another “easy” solution and we’ll add it to the list!

If you prefer to use bash over cmd, you can set up a bash tab in Console2 by going to Edit > Settings > Tabs, clicking the Add button, and setting the shell option to the location of your bash executable followed by the -l parameter (or –login). You can set the title to whatever you like, change the background color, etc.

Now, if you added the Console2 context menu entries that I described in my previous post, you might also like to change into the current directory when you invoke it from the context menu. Depending on what version of bash you have, you might need to put the following at the end of your .bashrc file in your home directory:

I found that this step was not necessary if I used the version of bash that comes with Git (located at C:\Program Files (x86)\Git\bin\bash.exe on my system). However, it was necessary if I used the version that comes with cygwin (C:\cygwin\bin\bash.exe). Using the latter, the home directory used by bash was actually located at C:\cygwin\home\dave. This will (obviously) be different on your system.

EDIT 4/14/2015: It appears that Console2 is currently dormant. One alternative I’ve found is ConsoleZ, which is a fork of Console2. You can find it here: https://github.com/cbucher/console.

If you don’t see the solution at the top of the Solution Explorer, go to the Tools menu > Options. In the Options window, ensure “Show all settings” is checked, then go to Projects and Solutions on the left and check “Always show solution” on the right:

This time, you don’t need to create a new ASP.NET MVC 3 web application. Instead, open the solution from last time, right click on the solution at the top of the Solution Explorer and choose Add > New Project…:

Choose Visual C# Class Library as the project template and name it CastleFluentNHibernateMvc3.Tests. Once the project has been added to the solution, delete the Class1 class. Next, right click on the Tests project in the Solution Explorer and choose Manage NuGet Packages… Search the online gallery for NUnit and install it. Also, search for and install Moq.

Once the packages have been downloaded and installed, add a folder to the Tests project named Controllers, then add a class to the Controllers folder named HomeControllerTest. Make this class public and prepend it with the TestFixture attribute, like so:

[TestFixture]
public class HomeControllerTest { }

Finally, we’re ready to write some tests!

Remember, a unit test typically covers a single unit of code. In the case of a MVC application, that means that each action and method deserves its own unit test. Depending on the complexity, some actions and methods deserve several unit tests. Because our application is so simple, however, our unit tests will be relatively simple as well. As you can tell from the previous step, we will be writing unit tests for the actions in our home controller, starting with the Index action. For convenience, here is the code:

We want to make sure that every time the Index action is called the store repository returns a list of stores and the action returns a view. Testing that the action returns a view is simple enough, so at first we might try something like this:

The first thing you’ll notice is that the Tests project requires a reference to CastleFluentNHibernateMvc3, as well as System.Web.Mvc. Once you’ve added these references, Visual Studio will display this compilation error:

'CastleFluentNHibernateMvc3.Controllers.HomeController' does not contain a constructor that takes 0 arguments

The reason we get this error is because we modified the home controller constructor last time to use dependency injection. We did this because we don’t want to use our real repository in our unit tests. Instead, we want to use a fake (or mock) repository. This is where Moq comes in handy, although it does require a little setup before we can use it. First, we need a field to store our fake repository in the HomeControllerTest class, which we need to reset after each test execution:

Download the Visual NUnit extension for Visual Studio. Go to View > Other Windows > Visual NUnit. After compiling the Tests project, select it in Visual NUnit and run the test.

Whichever option you choose, our test should pass with flying colors! Unfortunately, there’s a problem. We’ve made sure our action returns a view, but the view it’s returning is actually the Error view. We can verify this by debugging our test. In Visual Studio, go to Debug > Attach to process… find nunit-agent.exe (if you chose option one above) or VisualNUnitRunner.exe (if you chose option two) in the list of processes and click the Attach button.

Now, we can put a breakpoint in our test and take a closer look at our result. Sure enough, the ViewName is “Error”:

We could have caught this sooner by testing that the view is getting the right model. In this case, our view should be getting a list of stores as its model. We would test for that as follows:

Let’s put a breakpoint in our home controller this time and find out what’s going on. Doing this, we can see that our store repository is not returning any stores. And why should it? Remember, it’s a fake repository! We have to tell our fake repository what to do when it’s queried for a list of stores. But before we do that, make a copy of the Index test and rename it to Index_NoStoresFound. With a little modification, this test can still be useful:

Keeping this test will ensure that the Index action always returns the Error view when our store repository doesn’t return any stores. If this test ever fails (for instance, because the Index action returns the Index view), then something is wrong with our error handling.

Now, let’s fix our Index test. We can use Moq’s Setup method to tell Moq what to return when we ask it for a list of stores:

Previously, I mentioned that dependency injection is important for unit testing. If you are unfamiliar with either of these concepts, then your eyes probably glossed over when you read that sentence. I’m sure you could find many articles that cover unit testing and dependency injection on the interwebs. However, since I try to be newbie friendly (i.e. I am a newbie), I’m going to try to explain – in layman’s terms – the basic ideas behind these concepts. This will also give me a chance to learn more by teaching, which is how I learn best.

NOTE: I won’t be discussing test-driven development here. Some beginners get unit testing and TDD confused, but TDD is a separate topic that deserves its own article at some point in the future.

Unit testing

If you’ve ever done any programming in any language, then you are already familiar with manual testing. You might call it “looking for bugs” or “checking your work,” but it all boils down to launching your software and using it. At first, manual testing is quick and easy. After creating an HTML page, for instance, you would open it in a browser to verify that it looks okay. If it doesn’t, you would have to adjust the HTML until it passes the test. If it does, you might create another page and repeat the process. After that, you would need to add links from each page to the other. Then, you would have to open each page in a browser to verify that the links on each page work.

Here’s what usually happens pretty quickly: you have several pages, each with links to several other pages. Then, without thinking through the ramifications, you change a file name. This tends to happen at the worst possible moments, like right after your pages go live. Of course, it’s possible to test every link on every page every time you make a change like that. But if you are working on a large project, it can become extremely time consuming. Wouldn’t it be nice if there was a way to test every link on every page automatically every time you make a change?

There is a way. It’s called unit testing, and – if implemented correctly – it will save you from breaking changes. The reason it’s called unit testing instead of automatic testing is because it normally involves testing a single unit of code (a method or an action) at a time. To be honest, I don’t have a clue how you would write a unit test for the above scenario – at least not if all we’re dealing with is simple HTML pages. Frameworks such as Zend for PHP and ASP.NET MVC for C# lend themselves to such cases, which is one reason why they’re so popular. Here’s how we might do it in C#:

Of course, the implementation of such a test will vary greatly depending on the framework. Arrange-Act-Assert is a common pattern for unit testing:

Arrange: Set up any variables that will be used in the test

Act: Call the method or execute the action to be tested

Assert: Check that the conditions of the test were met

At the end of the TestLinks method above, we assert that the number of errors is equal to zero. If it’s not, then the test will fail, letting us know that a link is broken. Ideally, you would run this test after making any changes that could affect it. Most importantly, you would run it before committing those changes to source control.

Dependency injection

Dependency injection is often associated with unit testing because it allows you to test a unit of code by passing in a fake implementation rather than a concrete object. The most obvious case where you would want use this is to test a unit of code that needs to save data to a database.

Imagine that, on your website, a user can sign up for an account. To do this, the user must fill out and submit a form, which inserts a record into the database. This is something that needs to be tested – extensively, in fact, if you are a good developer.

If you’re using a data layer such as NHibernate or Entity Framework, you don’t need to test that the data is inserted into the database correctly. Also, you don’t want to insert a bunch of dummy data into the database. Instead, you need to test that the form is submitted, that an account is created, and that the page is redirected. If the user forgets to fill out a required field on the form, the page should be redirected to an error page, or back to the same page so the user can try again.

Now, assume your user controller has an action called NewUser that handles the form submission. In ASP.NET MVC, it might look something like this:

Running that test would insert the dummy data into the database, but we’re not interested in that part. What we’d rather do is skip that part and just test that the page is redirected to the right action. To do that, we need to pass a fake database to the home controller:

Then, we would need to modify the constructor of our user controller to accept a parameter for the repository. In other words, we need to inject our dependency into the constructor. We also remove the instantiation of the database class from the NewUser action:

Instead of saving the data, our fake implementation of the database class just pretends to save the data so we can go on testing the parts we care about.

Conclusion

Hopefully, now you get the basic ideas behind unit testing and dependency injection. As I mentioned before, my next article will cover using NUnit and Moq for unit testing an ASP.NET MVC 3 application with NHibernate and Castle Windsor already implemented.

The title of this article is so long, I briefly considered using an acronym. Unfortunately, FNHAMASPDNMVC3CW doesn’t communicate much except to the nerdiest of nerds.

This is the third article in a series on using Fluent NHibernate with auto mappings. The first one demonstrated its basic functionality in a console application, and the second one showed how to convert the first one into an ASP.NET MVC 3 application. This article will cover how to use Castle Windsor for dependency injection, which is important for unit testing. I won’t include any unit tests in this article, but will lay the foundation that will make unit testing possible for my next article.

Once again, create a new ASP.NET MVC 3 web application in Microsoft Visual Studio 2010 and use the empty project template. This time, call your project CastleFluentNHibernateMvc3. Next, right click on the project in the Solution Explorer and choose Manage NuGet Packages… Search the online gallery for Fluent NHibernate and install it. We also need Castle Windsor, so search for that and install it too.

Once you’ve installed the packages, copy the Controllers, Models and Repositories folders from our previous project to our new project. Also, copy the Views/Home folder to our new project. Make sure you change the namespace in each file accordingly.

The first thing we need is a Windsor controller factory. The Windsor controller factory overrides two methods of the default MVC controller factory and is central to how Castle Windsor resolves controller dependencies. Create this class in a new Windsor directory at the root level of the project:

Next, we need to tell MVC to use the Windsor controller factory instead of the default one. To do that, we’ll add a couple of methods to the MvcApplication class, which resides in the Global.asax.cs file at the root of the project:

Now, we need to tell Windsor about our controllers, including where they reside and how to configure them. In other words, we’ll “register” our controllers with the Windsor “container.” We do this using an “installer.” Create this class in your Windsor directory:

Next, create a new class named PersistenceFacility in your Windsor directory, and move the CreateSessionFactory, CreateDbConfig, CreateMappings and UpdateSchema methods of our NHibernateSessionPerRequest class there:

In the Init method, we’re telling Castle Windsor what to do when it encounters a dependency on ISessionFactory or ISession. If we ask for an ISession, it will resolve the dependency using the OpenSession method. Notice that this method needs an ISessionFactory, which Castle Windsor will resolve by calling CreateSessionFactory.

We’re also telling Castle Windsor that an ISession instance should be bound to a web request. Since we aren’t specifying a lifestyle for ISessionFactory, the default value of singleton will be used. In other words, only one session factory will be instantiated during the lifetime of our app, and it will hang around in memory until our app dies. This is basically the same thing we did before with our custom HTTP module, except the dependencies will only be resolved when needed. We can verify this by placing breakpoints in the OpenSession and CreateSessionFactory methods and running the app.

Now, we need to register our persistence facility with the Windsor container. Again, we do this using an installer. Create this class in your Windsor directory:

Next, we need to add a few more methods to our repository in order to manage NHibernate transactions: BeginTransaction, Commit and Rollback. Previously, we created a custom HTTP module to take care of these operations at the beginning and end of each web request. This time, we’ll manage each transaction ourselves, gaining more control and performance in the process. The GetAll, Get, SaveOrUpdateAll and SaveOrUpdate methods will stay the same:

Notice that the repository constructor has been modified to accept an argument of type ISession. This is called dependency injection, and its benefits will become more clear when we use it in our home controller.

But first, we need to register our repositories with the Windsor container. How do we do that? Right! (You did say “use an installer,” right? Good.) Create this class in your Windsor directory:

The benefit of using dependency injection here is that we no longer have a dependency on a concrete repository. The home controller doesn’t care what the repository does with our data, as long as it implements IRepository. This way, we can change our repository methods without changing our controller actions. Later, when we write unit tests for our controller actions, we’ll be able to create an instance of the home controller using a fake repository so that our tests don’t touch our data.

Because we are no longer using a custom HTTP module to manage NHibernate transactions, we need to call the BeginTransaction method of our repository whenever we get data from or save data to the database. We also need to call the Commit method to flush the NHibernate session, and call the Rollback method if any errors occur:

You can now run your application. If you get any errors, make sure you have an empty database and a valid connection string. In that case, see my previous article for instructions on setting that up. If all you see is the word “Index,” it’s because you don’t have any data in your database yet. In your browser, navigate to the Seed action of the home controller. You should then see “Index” at the top followed by a list of stores, products and employees.

Next time, we’ll look as using NUnit and Moq for unit testing. Surprisingly, it’s relatively easy! As always, let me know if you have any difficulties. Good luck!

This is a just a small distraction. I’m sort of a clean freak when it comes to Windows, so I usually opt not to install things like context menu entries when I’m trying a new program. Unfortunately, I opted not to install them for Git and realized later that I really wanted them. There doesn’t seem to be a way to correct this post-installation, so I did some research and figured out a little registry hack to accomplish the same thing: