Posts
49
Comments
83
Trackbacks
0
November 2009 Entries
Connect to VMWare virtual machines using Remote Desktop

Had a short training on VMWare on Tuesday, the software development department finally got the official permission (read: get a license) to use VMWare Workstation.  I’m no stranger to Virtual Machines (VMs) – started playing with Virtual PC 2005 a fwe years back and I understood the general concepts of hardware virtualization.  The biggest problem I have with VMs in general is the slowness; I’d rather develop directly on my PC, which is faster.  Can’t say I’ve delved deep into it, but I know enough to utilize it and be dangerous .

Regardless, virtual machines provide a way to simulate multiple computers and I’ve done 3-tier software testing (client to app server using WCF and app server to SQL 2005 backend) to verify our framework can support both 2-tier (client –> DB) and 3-tier deployments.  Rarely used it for development, again due to speed.

Fast forward to the current time, I’d like to be able to do some coding on Windows 7; unfortunately Windows 7 is not quite sanctioned yet to be deployed, and it’s a pain to have to dual-boot.  I do have Windows 7 at home, but got way too many experimental stuff on it .  So, I’m setting up a Windows 7 VM so I can do some coding on it.

Now, nothing wrong with running the VM within VMWare, but I always find that it is a bit sluggish unless I go to full screen mode.  If I do so, it’s a bit of a pain to go back and forth between the host and the VM, and it also means that I have to do it at the host.  Ideally, I’d like to remote desktop into it (for whatever reason, I also feel remoting into a VM session makes for a snappier UI response).

However, this is not immediately possible to do without some setup; out of the box VMWare provides VNC connectivity, so you can use that but I am spoiled by remote desktop – it is just way nicer than VNC.  Of course one of the advantages of VNC is that if someone connects to it, the original don’t lose the view of the PC, so different tools for a different job.

In any case, I’d like to be able to remote desktop into my VMs – there are 2 ways to set this up, one is faster but it is considered as ‘nice’ and may cause problems with typical corporate network setups.  Let’s look at the first approach:

image

The first approach is to set up the VM setting to have it’s network adapter be a Bridged connection.  This basically sets the VM to use the host’s network card as if it were its own network card.  This also means that the VM will get an IP based on the host network’s settings (usually DHCP-based).  Essentially it brings the network connectivity of the VM to be at the same level as the host.  Now, in a corporate environment (usually domain-based), this may not be allowed, or you may have trouble with accessing the network at all if your VM is not added to the domain.  On a local (home) network, it also means it can communicate with other computers on the same network (good), but if it gets infected with a worm / virus it can also spread to the other computers (bad).

Depending on your environment, bridging may be fine and if you can do that then by setting it to Bridged mode you can then remote desktop to the VM (you have to remember to turn it on within the VM).

However, in my current situation, setting a VM network in bridged mode is not condoned and we have to set it to NAT setup.  Each VM that you spun will then get a typical internal IP address (192.168.XXX.XXX); but that means you cannot get to it from the outside.  So what to do?  The answer was provided in this post by rsa911– I’m just providing the nice UI snapshots (and also as a reminder for me on how I got it to work in the future).

In NAT mode, each VM is given an internal IP address and VMWare essentially becomes the bridge between the host and the VMs that runs in it.  Fortunately, you can do port forwarding to these internal IP address.  As detailed here, Remote Desktop uses port 3389 to listen to incoming RDP requests.  So what we need to do is forward an unused port to each VM’s port 3389 and we should be able to remote into them.  Let’s see how that’s done.

image

To do port forwarding, we need to access the Virtual Network Editor from VMWare Workstation (under the Edit Menu –> Virtual Network Editor).  The dialog above should show up – select the network adapter that is set to NAT.  Then click on the ‘NAT Settings…’ button, the following dialog will show up:

image

Click on the ‘Add’ button, and a dialog to map incoming port shows up; the dialog below is filled with the following information:

  • Listen to port 9997
  • Any TCP communication to that port, forward it to the VM with IP of 192.168.118.130 on port 3389 (default RDP port)

image

Tweak it to satisfy your setup – the host port just needs to be an unused port (in this example I use 9997), the VM port needs to be 3389 (unless you’ve changed it) and the VM IP address needs to be the IP address assigned to the VM you’re running (in Command Prompt run ipconfig to easily see this); this is what my output looks like:

image

When done, click OK and the NAT Settings dialog will show up your port forward:

image

So now I’ve set up VMWare so any incoming request to port 9997 will be forwarded to port 3389 on the VM that has IP of 192.168.118.130.  Remember that for Remote Desktop to work, you still need to make sure your VM has RDP enabled and you have users with passwords added as Remote Users.

The question is then how do you issue the remote desktop request?  Well, you use the host’s IP (or machine name) as the target, but you provide the port number as well:

image

The VMWare is hosted in my laptop (mbudimane6500) and I’m providing the port RDP should use (9997).  Remember that in a domain environment it’ll try to login as a domain user (DOMAIN_NAME\username format), so if your VM machine is not part of a domain you have to change the username to use to log in.

If you’ve done everything as mentioned above, now you can remote desktop into your VM machines in a NAT environment .  Remember also that you have to do the port forward for every VM that you wanted to remote into – each one will have a different IP address and each one will need to have a different port number.  Hope this helps others.

posted @ Friday, November 13, 2009 8:42 AM | Feedback (0)
Make SQLExpress DB accessible from other computers

When I started using SQLExpress 2005, everything works on my development machine – however when I wanted to access the database from another machine (trying to access the sqlexpress database remotely) I was not successful.  I discovered the solution way back then, also through Google searches, which still yield a valid result.  However, every now and then my peers would ask me this same question again.

Thus I’m creating this blog so I can forward them to this page (instead of talking about it); it’ll also remind me of how to do it if my memory starts to fail me.

By default, SQLExpress installations does not allow remote connections, so we need to change that first.  To change it, you have to run the SQL Server Surface Area Configuration tool – as the name vaguely implied, this tool will allow you to configure SQL Server’s Surface (what gets exposed).  This tool is installed with your SQL installation (express or not); it should be located in the Microsoft SQL Server 2005 / 2008 program group, under the Configuration Tools subgroup.

When you run this, the following dialog appears:

 sac01

Select the ‘Surface Area Configuration for Services and Connections’ (as circled above).  The next dialog should appear:

sac02

Select the Remote Connections node on the tree view (as circled above); the dialog changes to the following:

sac03

As you can see, SQL Express by default does not allow remote connections (the text above it also enforces that); so we’d like to change that – select the ‘Local and remote connections’ radio button, depending on your needs you choose to use TCP/IP or named pipes or both, then click the ‘Apply’ button – an alert should show up telling you that the settings will not take effect until the database engine is restarted, we’ll do this last.

We’re not finished yet; what happens right now is that the system is set up to allow remote connections.  However, there’s another piece of service that needs to be up before we can connect to it remotely.  That service is the SQL Server Browser service.  Select the SQL Server Browser node on the left tree view, and the dialog will change to show the following:

sac04

Again, by default the SQLBrowser service is disabled, so let’s change that to Manual, click ‘Apply’ (which will enable the ‘Start’ button) then click the ‘Start’ button, which will start the service.  OK, we’re almost finished; the last step is to restart the SQL Server service itself, so let’s click on the Service node under the SQLEXPRESS and Database Engine node in the tree view.  The dialog will change to the following:

sac05

Click ‘Stop’ and then wait for the service stoppage to complete, then click ‘Start’ again.  You should be able to connect to your SQLExpress instance from another computer (if it’s the default instance, you would use computername\SQLEXPRESS as the server name).  Good luck!

posted @ Wednesday, November 11, 2009 4:08 AM | Feedback (0)
Putting pictures in Windows Live Writer in their original size

I guess I’m one of those people who rarely reads manual, and outside of technical documentation, I rarely read an application’s user manual.  So I’m using Windows Live Writer, and I’m trying to embed a picture in my draft blog post.  Well, whenever I do that, the picture always come in scaled down (if it’s even a tad large, like 300 pixels wide), like the picture below:

image

Well, obviously with technical and text-heavy images, scaling down is bad (can’t read much).  I can go to the HTML source, but I can’t seem to rescale the image, even when I took out the width and height property.  Pretty weird.  So how do I scale it?  Clicking on the image in Live Writer shows me the following information on the right-hand pane:

image

First off pictures that are inserted into Live Writer automatically gets treated as a clickable link.  If it’s a regular (non-text) picture, most probably that’s desirable; however in most of my cases, I’d like to put in the actual picture itself and don’t want to make it clickable.  So make sure you set the bottom-most combobox (the one under the heading Link to) to None.

On the top side of this info pane, there are 3 tabs; select the ‘Advanced’ tab and the information displayed changes to:

image

The combobox under the Size heading will also list the original size; select that and your picture now gets shown in its original size.  I’m happy ()to have found this since in some of my past blog posts I actually had to set the width/height of the picture manually in the HTML.

Also, with geekswithblogs, to set the tags to associate with your blog post, the bottom part of Live Writer has this ‘Set categories’ combobox – click on it and it’ll show you the tags that you’ve defined in your blog:

image

posted @ Friday, November 06, 2009 9:31 AM | Feedback (1)
My Coding Helpers: Verify exception thrown in Unit Test

Every now and then, I end up writing and re-writing the same code (or very, very similar) to achieve a functionality that I’ve had before.  Sometimes I can remember where I wrote it, so I can just copy and paste.  At other times, I have to redo it again since I forgot where it was.  So I’d like to put it up on my blog so I have access to it.  If anyone else gets to see it and can use it, so much the better for everyone.  Of course, I’d also accept criticism to the code too .

So, this is my first one; because I’ve used it for awhile and I ended up having to rewrite it yet again today for a pet project that I have.  Now, I understand not everyone likes to do Unit Testing, but I enjoy it every now and then.  It is somewhat boring & tedious, but it also gives me some relaxation since I can do very, very simple code and don’t have to think too much – unit test code should not be very complex.  In most unit tests, the code will try to go through the path of the tested code and usually try to handle the happy path.  I don’t do pure Test Driven Development, but I understood some benefit of what TDD can do.

One advantage of doing TDD is that you will end up also writing tests (and code) that will verify arguments.  And since your code has argument checks, then your unit tests also have to verify both success and failure cases of those arguments.  Consider the following very simple code:

public class SomeClass
{
   public double SR(double d)
   {
      return Math.Sqrt(d);
   }
}

Essentially you just wanted a wrapper method, instead of calling the function Math.Sqrt() all the time; simple enough.  But let’s say that you also wanted to change the default behavior; such that the consuming code should never ever actually call this method with a negative number.  If it is a negative number, then you wanted to throw an exception.  Easy enough to do…

public double SR(double d)
{
   if (d < 0)
      throw new ArgumentException("Argument can't be negative!");

   return Math.Sqrt(d);
}

As you can see from the code above, the code is still trivial.  Of course, now you want to write a unit test for it; there are 2 unit tests you have to create: the successful case and the failure case.  So let’s see what the unit tests would look like the following (I’m using Visual Studio’s unit testing framework):

[TestMethod]
public void SRTest_Success()
{
   SomeClass sc = new SomeClass();
   Assert.AreEqual(sc.SR(100), 10.0);
}

[TestMethod]
public void SRTest_Failure()
{
   SomeClass sc = new SomeClass();
   try
   {
      sc.SR(-100);
      Assert.Fail();
   }
   catch (ArgumentException)
   {
   }
}

Again, simple, very trivial methods – however the failure case is rather verbose; you have to create a try-catch block (an empty catch at that too), so another way to do it is to use the ExpectedExceptionAttribute.

[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void SRTest_Failure()
{
   SomeClass sc = new SomeClass();
   sc.SR(-100);
}

The problem with the above approach is that if you want to be able to catch multiple exceptions (not recommended in creating unit tests, but some people may want to cut corners ), you can’t do it – you can’t apply multiple ExpectedException attributes.  Another problem is if your unit test code is rather large, it may have other code paths where there’s an actual failure that will throw an ArgumentException which will pass the test happily but will result in a false positive.

So, I needed a way to be able to catch exceptions in the code itself, but I don’t want to write try-catch blocks all over the place.  So I came up with the following helper method to help me verify exceptions are thrown:

public class UnitTestHelper
{
   // Method accepts an action delegate, and a generic Exception type
   public static void VerifyExceptionThrown<TException>(Action action)
      where TException : Exception
   {
      // Verify arguments - action can't be null
      if (action == null)
         throw new ArgumentException("Action to test cannot be null!");

      // Verify arguments - TException cannot be of type Exception
      if (typeof(TException).Equals(typeof(Exception)))
         throw new ArgumentException("TException type cannot be of type Exception");

      // Actually call it
      try
      {
         action();
      }
      catch (TException)
      {
         return;
      }

      // If it gets here, fail the test
      Assert.Fail("Action does not throw the exception expected");
   }
}

The code above is fairly simple; the helper method accepts an Action delegate as a parameter and a generic TException type to be passed and I put in a constraint that has to derive from Exception class.  To also be nice and proper, the method also checks its parameters: the action parameter can’t be null, and the generic TException type cannot be of type Exception itself (because it’ll catch all exceptions, which won’t prove/disprove the unit test itself, but modify it as you want).  At the end, it’ll fail the unit test, since it should never hit the Assert.Fail method call.

The unit test will look like the following:

[TestMethod]
public void SRTest_Failure()
{
   SomeClass sc = new SomeClass();
   UnitTestHelper.VerifyExceptionThrown<ArgumentException>(() => sc.SR(-100));
}

[TestMethod]
public void SRTest_Failure_AnonymousDelegate()
{
   SomeClass sc = new SomeClass();
   UnitTestHelper.VerifyExceptionThrown<ArgumentException>(delegate() { sc.SR(-100); });
}

I put in 2 methods – the first one uses Lambda Expressions, which may not be used by those that are still using strictly .NET 2.0 framework only, so the second one demonstrates the same call but using anonymous methods.  If you’re strictly using .NET 2.0, the Action delegate is not available in the .NET Framework – you have to create your own. 

After understanding simple Lambda Expressions, personally for me, the unit test code is more readable, since I don’t need to look at any attributes, and the unit test code can contain further verification of exceptions thrown and also it can have further asserts.

For completeness, the code below is the unit test that tests the VerifyExceptionThrown method.  The code demonstrates the ‘eating your own dog food’ mentality: I get to use the method that I’m unit testing itself.

[TestMethod]
public void VerifyExceptionThrown_TestFailure_InvalidExceptionType()
{
   UnitTestHelper.VerifyExceptionThrown<ArgumentException>(() =>
      UnitTestHelper.VerifyExceptionThrown<Exception>(() => { }));
}

[TestMethod]
public void VerifyExceptionThrown_TestFailure_NullAction()
{
   UnitTestHelper.VerifyExceptionThrown<ArgumentException>(() =>
      UnitTestHelper.VerifyExceptionThrown<DivideByZeroException>(null));
}

[TestMethod]
public void VerifyExceptionThrown_TestFailure_ExceptionNotThrown()
{
   UnitTestHelper.VerifyExceptionThrown<AssertFailedException>(() =>
      UnitTestHelper.VerifyExceptionThrown<DivideByZeroException>(() => Debug.Assert(true)));
}

[TestMethod]
public void VerifyExceptionThrown_TestSuccess_DivideByZeroException()
{
   int i = 0;
   UnitTestHelper.VerifyExceptionThrown<DivideByZeroException>(() => i = 5 / i);
}
posted @ Thursday, November 05, 2009 9:22 AM | Feedback (0)
News