Unit Testing: Allowing Access to Internal Members of Types in Another Assembly

February 5, 2008

Create a Friend Assembly by adding [assembly: InternalsVisibleTo(“Other.Assembly”)] in AssemblyInfo.cs to allow that Other.Assembly access to this assembly’s types’ internal members.

Good object-oriented design involves guarding access to members of types appropriately. Part of a domain object’s state may only be mutated by other types in the same assembly (for example during creation). Those members will be protected with the internal keyword (in .Net).

This causes issues when trying to achieve 100% coverage during testing. Unit tests are usually located in another assembly (even if the namespace is shared for simplicity). That unit test assembly will not have access to the internal members and therefore some important states of a domain object cannot be tested. Assume you have the following domain object assembly:

// assembly Acme.Model
namespace Acme.Model
{
  public class Stuff
  {
    private List _data = new List();
    public ICollection Data { get { _data; } }
    internal void AddData(string data)
    {
       _data.Add(data);
    }
  }
}

We want to test the above class with 100% coverage, meaning we have to get Data added to it. The associated unit test would pretty much look like this, but not compile, because of the inaccessible internal member:

// assembly Acme.UnitTests.Model
namespace Acme.Model
{
  [TestFixture]
  public class TestStuff
  {
    [Test]
    public void TestData()
    {
       Stuff stuff = new Stuff();
       stuff.AddData("data"); // this is not going to compile
       Assert.AreEqual(1, stuff.Data.Count);
    }
  }
}

Declaring a Friend Assembly is a very quick and simple fix for this problem. In Acme.Model’s AssemblyInfo.cs, just add the following line at the end:

[assembly: InternalsVisibleTo("Acme.UnitTests.Model")]

For more on that topic, see Friend Assemblies on MSDN.


Building My Own HDTV Antenna

February 4, 2008

Synopsis: The self-made antenna worked–for my friend. HDTV antennas are just conventional UHF/VHF antennas. iTunes may turn out to be the cheapest solution for our viewing patterns.

The Self-Made Antenna Experiment

Like any scientist, I consider all experiments carried all the way through a success, even if one negates my initial assumptions and expectations. It is even better if new insights can be gained. In that context, I had success with my DYI HDTV Antenna.

The coaxial cabling in my house is so bad that I cannot receive standard TV channels properly on my HDTV. The latest season of Lost has just started & the wife wants me to make TV happen. My options were

  1. calling the cable company to fix it (accompanied with the hollow threat that I would switch to FIOS if they didn’t, which I had attempted several times but given up on after Verizon’s online application was not able to recognize my address and their sales interactive voice response system gave me a 15-minute run-around asking for my [non-existing] Verizon phone number) or
  2. buying a commercial HDTV in-house antenna.

I picked option 3, which was to build my own antenna according to the instructions in this video on MetaCafe:
Coat Hanger HDTV Antenna

Since I was fresh out of coat hangers, baluns and various other hardware, I spent about $15 on materials from various places, which I considered a decent price to pay for some fun. A friend of mine and I then commenced to leisurely put the antenna together whilst taking care of the kids (the latter causing this to be an hour-long project).

I had purposefully kept my expectations low about whether this contraption would work, so I was positively surprised when the HDTV tuner picked up 20 HDTV channels on our second attempt (after having “straightened out” a few parts of the antenna that apparently were causing some problems). The 11 religious & church channels among those channels found came in crystal-clear without skipped frames, pixelization or missing sound. We were not so lucky with the major networks’ channels, though and even after several more minutes of tweaking the antenna and moving it about the living room, we had to concede defeat (on that end). All the important channels had such poor reception that we often saw nothing but a “receiving data” message that would not go away or the dreaded “no signal” message. If we got a picture, it was a still frame that refreshed every minute with many artifacts. There was no sound.

How could it be that half of the channels found had no issues while the other half was pretty much unusable? I asked my friend to take the antenna with him to his Portland East-Side home and try it there, just to get another data point (of view, literally) for the experiment.

He called the next morning with the good news that for all but two channels, our self-made HDTV antenna was performing better than the commercial, amplified HDTV antenna he had bought a while ago. He gave me his old, commercial antenna to see whether I would have more luck with it (which I didn’t).

Where’s The Tower?

It dawned on me that the awkward location of my house on the south side of a hill in South-West Portland may have something to do with the poor reception. After few minutes of research I found the location of TV transmitters for several major Portland-area networks, which is at the Sylvan Ridge in the West Hills at the corner of SW Barnes Road and SW Skyline Blvd (Map View). The FCC provided a helpful resource to find TV stations, channels and transmitters. Consumer Electronics Association’s AntennaWeb is also helpful for selecting antennas. You can plug the longitude and latitude for locations found into Google Maps using the following format: 45° 31′ 14″ N, 122° 44′ 37″ W (the first one is the latitude, the second the longitude).

Using Google Earth I discovered that even though the towers are only 4.5 miles directly north of my residence, there’s a hill blocking the line-of-sight. I would have to erect a 70 feet tall tower to get line-of-sight.

Electro-magnetic ground-effects can be funny. I once tried to get a high-speed wireless Internet connection over a distance of only 3 miles, but there was a little bump in between the radio tower and my office location. The technician doing the site survey said that even though the station was in line-of-sight, the bump messed with the signal sufficiently enough for it not work. More details about this can be found here: Fading & Multi-path Interference

So, What Now?

In order to overcome the signal limitations I have to deal with, I would have to spend some serious money on a mast and at least two highly directional, high-gain antennas. That’s not really an option, for aesthetic reasons alone.

I will probably call the cable company and have them fix everything. My drop is almost 100 feet long and its using regular R6 when it should be R11. I am just concerned about losing my Internet connection and not getting it back.

In order to get cable HDTV, I would need to pay $6.50/month extra with Comcast and still have to watch commercials during shows.

Maybe the convenience is worth the small premium over all this hassle and iTunes ends up being the best deal? But it’s not HDTV, so I am not sure …

Sweet Memories

This whole experience reminded me of a time during my childhood, growing up in socialist East Germany. The West Germans (and presumably Americans) had put powerful terrestrial TV and radio antennas along the border between East & West Germany, blasting the signal as far into “enemy territory” as they could. East German engineers (privately) devised antennas and amplifiers to pick up those signals.

Together with our duplex neighbors, we put a 10 feet tall mast on top of our 20 feet tall house and attached several 6 to 10 feet long high-gain antennas with amplifiers to it. We then would align the antennas in the direction of the approximate location of the “capitalist” radio & TV towers, turn on the TV, tune for the channel (by hand!) and then slowly move the antenna in 1/4 inch steps (or smaller) until the signal was clear. We would repeat that for each of the 3 (or 4?) antennas. After every major storm.

The towers from which we received the signals were over 80 miles (127 km) away.


Outsourcing with Elance, Guru & GetAFreelancer.com

February 3, 2008

Different freelancer networks have different strengths (duh!). Use them in combination.

I have been using Elance in the past to invite other people to help me on projects. Now I had a very urgent fulfillment request from one of my clients and needed some business research done in less than 3 days from posting the project to final delivery. For all web development-related projects I posted on Elance in the past, I had received bids within minutes of making the project description public, but no-one responded to this research request within a few hours. So I decided to give two other places I knew about a first chance: Guru & GetAFreelancer.com.

I got bids on both within the first hour or so and ended up with 5 or more bids on each. Both providers in the U.S. and abroad had similar prices, with the top-rated ones all bidding essentially the same amount (at the upper end of the limit I had set for the project). I found both sites more cumbersome to use than Elance, but GetAFreelancer seems to have a lot more provider diversity and Guru is more established and mature. GetAFreelancer also makes the buyer pay for transaction fees, which I find inappropriate. But maybe the margins for providers are better there and therefore the providers more motivated? The future will tell.

The real proof is going to be in the pudding, which will be delivered by the end of tomorrow. Lets see whether the project winner can meet expectations. My success with Elance providers has been “mixed.”

Update: The provider I picked with Guru delivered decent work. Not quite what I expected for the money I paid, but the client was happy (which is really all that counts). I read recently (I wish I’d remember where) that in order to successfully delegate, I will have to accept that the job is only going to be done 80% as good as if I had done it myself and account for that gap. In this case it was close. I got maybe 60% to 65% of what I asked for (partially because of the tight deadline), so I had to fudge it a little to make it work.

This experience also teaches me that I need to “train” the client better to not to ask me for stuff “last minute”.


JavaScript: img.src = null; // To Load Or Not To Load?

February 3, 2008

Update: I am getting quite a few page views on this post (for a new blog anyway), but I don’t think it is answering what people are looking for. If you could let me know in the comments WHAT it is you were looking for, maybe I can answer it?

Don’t set image.src to null, otherwise IE tries to load the null image.

I was working on a dynamic image popup that shows a spinning icon until the actual image is loaded and among the few lines of JavaScript code I had this (for reasons not important to this discussion):

// loadImg was created earlier with document.createElement('IMG');
loadImg.src = null;

I did not think about side effects when I wrote this, but expected nothing to happen from this assignment. Turns out Internet Explorer is trying to download an image with the relative path null from the server. I found this during testing when validating expectations of connections made to the server. I guess one could argue that IE is behaving correctly and all the other browsers, which are not requesting anything, are behaving incorrectly. I am not sure. To me null means nothing, which implies that nothing gets loaded.

I changed the logic a bit and removed the offending lines. I should start tracking the amount of time I spend on fixing Internet Explorer-related issues and bill Microsoft, because it is starting to get expensive for me.


Running IE6 and IE7 at the same time on the same machine

February 1, 2008

Synopsis: Get IE 6 & 7 running concurrently on the same machine with this tool: http://tredosoft.com/Multiple_IE

My goal is that websites I work on or are responsible for function properly on at least 98% of all current browsers. At the time of this post, across sites I monitor, I observe the following

Browser Usage Statistics

Browser Version Visitor Share
Internet Explorer 7 40% to 50%
Internet Explorer 6 30% to 40%
Firefox 2 15% to 25%
Safari 3 3% to 5%
Safari 2 around 1%
Others (combined) never more than 2%

This means I will have to test sites and scripts on IE6 & 7, Firefox 2, as well as Safari 2 & 3 to get 98% coverage. For Safari 2, I am keeping an old, cheap Mac around (Safari 3 runs on Windows), but the real issue is testing IE 6 & IE 7 concurrently. I have tried several strategies, of which the last one is by far my preferred approach:

Strategy Pros Cons
Two Computers
RDP (remote desktop) into another computer running a different version of IE from the one on which is the primary development machine.
  • No need to try running two different versions of IE on the same computer
  • If the other computer is already available, the second-quickest way to get going; otherwise, see Cons
  • Needs another computer (which may need to be configured first)
  • Implies that another license of Windows is needed
Virtual Machine
Run a virtual machine with a different browser version. This configuration requires that the virtual machine can “see” the development machine’s IP address on which the site being worked on is running. I solved this by installing the Microsoft Loopback Adapter, assigning a custom IP address in the 10.0.0.* network and running the virtual machine (Virtual PC) in Shared Networking mode. I then configured either Apache or IIS to listen on that IP address. For .Net development, I pointed the IIS web root directory to the same folder I had my solution/project in.
  • Needs only one computer
  • It’s always a good idea to have a “clean-room” environment around for testing
  • Takes more effort to set up
  • Use additional system resources on the development machine compared to just a browser
  • Needs an additional license of Windows
Running Internet Explore 6 & 7 concurrently on the same machine
That is the model I have sought to implement in the past, but have found it cumbersome to get both versions running in parallel. I finally came across a “product” that solves this problem well: A Multiple IE Versions Installer offered for free by TredoSoft (see http://tredosoft.com/Multiple_IE).
  • Needs only one computer
  • No need for a virtual machine
  • Actually the quickest way to get going once everything is said & done (not counting all the time I spent searching for this).
  • Some have reported problems with IE crashing or even their entire Windows installation getting hosed by this.

I am surprised that I was not able to find this last solution earlier. Team members & I spent a lot of time setting up environments to support proper cross-browser testing (which I believe is not optional). I wasted a good amount of time scouting the Internet for a way to get IE 6 & 7 work in parallel and had been successful with the manual steps once in the past (but not in any repeatable fashion). One of the main reasons for this post is therefore to raise link popularity for the above tool and maybe someone else will find this helpful.

I know there are tools available online that take a screen shot of a site as it renders on different browsers, but that’s really not an option during a heavy design cycle, in which one switches back and forth between browser and IDE a lot. Also, only the real thing lets you test script/AJAX interaction–of course.

Update: The menu bar in both browser versions installed on the same machine is apparently shared, leading to the Help > About Internet Explorer command showing the version 7 About dialog even when in IE 6. This can be confusing, but it’s still IE6 (as a simple IE6-specific object detection JavaScript snippet or the observance of IE6-specific rendering bugs will reveal).

BTW, parralel is spelled parallel 😉


Google Maps: Many Markers Slow in IE6

February 1, 2008

Synopsis: Detect IE 6 in script and use GIFs for custom marker images instead of PNGs.

Working on implementing a Google Maps-based search that updates markers as you zoom or pan: Interactively placing and removing more than 50 markers (custom ones or the default) on a Google map using their API makes Internet Explorer 6 grind to a halt–even on a fast computer. Some have identified a caching problem, but even if that’s solved, your visitors will probably experience an awful slowness rendering lots of markers, if they use IE 6. It turns out that this has to do with how the PNG-format-based markers are displayed by Internet Explorer: Google Maps uses the “filter/AlphaImageLoader” hack, since PNGs are not directly supported by that browser. Any other browser renders several hundred markers just fine (and fast). The AlphaImageLoader filter is apparently putting a serious damper on IE’s rendering performance.

The “Workaround”

The only way to not to use PNGs for map markers is, well, not to use them. The following discussion assumes that you know how to create custom map markers. I highly suggest not using icon shadows, because avoiding them cuts the number of transparent images to “paint” in half, which is going to help all browsers. For IE6, we simply select a GIF image instead of a PNG. The entire custom marker definition could thus look like this (JavaScript fragment):

// one way to detect IE6 and IE6 only
var is_ie6 = (
	window.external &&
	typeof window.XMLHttpRequest == "undefined"
);     

// define custom marker
base_icon = new GIcon();
base_icon.image = is_ie6 ?
	"/media/images/map_icon_ie6.gif" :
	"/media/images/map_icon.png";
base_icon.transparent = null; // don't use transparency mask
base_icon.shadow = null; // don't use shadow image
base_icon.iconSize = new GSize(16, 15); // icon size matches image
base_icon.shadowSize = null; // self-explanatory
base_icon.iconAnchor = new GPoint(8, 7); // *center* of the icon
base_icon.infoWindowAnchor = new GPoint(8, 7);
base_icon.infoShadowAnchor = null;
...
// this marker can now be placed on the map
marker_options = { icon:base_icon };
marker = new GMarker(new GLatLng(_lat, _lng), marker_options);
map_obj.addOverlay(marker);

One place to see this in action is on the map search for LamongeRE (which is now defunct).