Friday, May 28, 2010

Yet once more into the breech (of altered programming logic)

Once upon a time, long long ago, I wrote 8-bit programs in Tiny-C with absolute addressing being the only reality.  Then we had Borland Turbo-C with relative addresses and the joys of relative assembly jumps. Enter Windows and the joys of locking and unlocking memory blocks that you must allocated and manage yourself. Then came Visual Basic which evolved into .Net CLR and decreasing awareness of what is happening under the hood.


With VS2010 including F# and enhanced parallelism in .Net4, we actually have to go retro a bit – back to the world of having to understand the hardware. CPU speeds are no longer increasing – I have an old laptop from six+ years ago that ran at 3.2 GHz. This year I updated one of my machines off-the-shelf from, an I7-920 with 4 cores and hyper-threading (8 CPUs appears in Task Manager) and 12 GB of DDR3 RAM. This week I ordered from Costco a Phenom II X6 (Yes – 6 REAL CORES) for one of my daughters.  This CPU will (according to YouTube demos) overclock to 4GHz.


Many developers struggle to do asynchronous calls and threading. The reality for writing high performance software in the future is that writing for parallelism is not an option but should become stock in trade (along with asynchronous calls and threading).


If you are hiring, I would emphasis specifying experience with all three of these strategies in your job requirements. If you are not fluent in these three strategies, start working on learning them.

Tuesday, May 25, 2010

Are baby-boomers better learners/developers than Gen-X and Gen-Y?

Part of software development is learning. Part of learning is being corrected. I read this interesting article the other day, Young adults believe in the age of entitlement, claim researchers in the Telegraph. It reflects similar news pieces that I have seen on CBC’s National and PBS.

“the 20-somethings of today have ‘an automatic, knee-jerk reaction to criticism,’ and just dismiss it.”

It’s explains why I have seen solid advice ignored – the older generations would actually take it, or, enter into a discussion (or argument) about the basis of the advice.  Having a good discussion with supporting documentation is an excellent way to improve software quality – everyone learns. 


The article also cites a separate study due to be published in the Journal of Management,

“Generation Y care most about high salaries and lots of leisure time – two apparently incompatible goals”

So we are talking about a generation of developers that expect a 35-40 work week instead of the tradition 50-60 work week that was typical for the older generation.


Bottom line? A hiring manager that knows the literature should prefer developers over 40 and avoid younger developers. The exception would be fresh out of school developers that are “trainable”, once they get a few years of experience their sense of entitlement will likely lead to them ignoring advice, not working as a team member and working “short weeks with low intensity”. 

Monday, May 24, 2010

500 Words

As a professional blogger on MSDN, I have been contemplating the length of a blog post; I came to the conclusion that they should be right around 500 words.


When mentioning this to another blogger, he told me that the length should match the subject. At first glance makes perfect sense. If you have a more complicated subject, you are going to have a longer post. However, I disagree. If you have a more complicated subject, you need to split it into a multi-part series of posts published over a period of days.


My stance is that the length needs to match the channel not the subject. An analogy is a television commercial on a national network channel. No matter what the message or subject, the channel dictates that the commercial only be 30 seconds.

Some commercials are 60 seconds, and some of my blog posts are 1000 words. However, none of the posts are 5000 words, just like there are no five minute commercials. The audience has an expectation of length and you lose them if the post or commercial does not match the channel.


What about the Home Shopping Channel commercials, which are much longer than the national networks? That is a different channel, much as a book is different from a blog post. Viewers have an expectation of the length of the commercial on the Home Shopping Channel.


Here are some of the techniques that I use to keep my blog post under 1000 words (shooting for 500 words):

  • Serialize the post so that it is multi-part. This requires that I write the post in such a way that it is easily divisible. There is an additional benefit to this approach, readers will return to the site to read the follow-up posts, or subscribe to the RSS feed.
  • Promise a follow-up post. If I am tempted to explain a particular point in more detail and diverge from my core idea, I do not. Instead, I promise a follow-up post on the tangent.
  • If I want to help the reader pursue the subject, however don’t want to write about it as a follow-up post, I off link to more information on another site on the Internet. This is helpful in technical blogs, since there are many lengthy free resources on the Internet to link to.

Of course, my idea of the perfect blog post length could be changed by a persuasive argument, if you have one post it in the comments below.

Tuesday, May 18, 2010

Easy fix for duplicate keys in a resource file (resx)

Today I was cleaning up some RESX files by doing some renaming (to conform to a naming conventions) and ran into the classic duplicate mnemonic problem that arise. With hundreds or thousands of mnemonic in a resource file this can become very time consuming. RESX files are not case sensitive which adds a little joy to the process…


I tossed together a utility that eliminates all of these duplicates and also sorts the mnemonics in the physical RESX file. This made reviewing a lot easier – so here’s the code in case you need it, just provide the folder holding the RESX files and you are done.


using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;

class Program
    static void Main(string[] args)
        if (args.Length < 1)
        DirectoryInfo di = new DirectoryInfo(args[0]);
        foreach (FileInfo fi in di.GetFiles("*.resx"))
            XmlDocument dom = new XmlDocument();
            var list = new SortedList<string, XmlNode>();

            foreach (XmlNode node in dom.SelectNodes("//data[@name]"))
                var key = node.Attributes["name"].Value.ToLower();
                if (!list.ContainsKey(key))
                    list.Add(key, node);
            foreach (string key in list.Keys)

Computers as a Vocation or an Avocation?

My grandfather advocated this advice (and likely further back, perhaps to the 1850's -- since the evidence supports it)... 

"Always separate life-goals into vocation and avocation. An avocation is what you want to do. A vocation is what puts bread and butter on the table. When you mix the two into one, you end up being a starving artist living in an attic in a rooming house. For vocation, look at what you can do better than other folks (you may not like doing it -- that does not matter, being free to do your avocation compensates); look at what is new (there will be less competition, faster promotion and higher pay) and find the best combination. That is where you should focus for your vocation.  Don't ask the older generation for advice here -- they will give you their reality when they were your age."

An example of this is the horde of people that want to become game developers….  they have mixed up vocation and avocation.


So what is your avocation? It’s a good question to ask in an interview. Why? If it’s computers, you may be dealing with a romantic idealist (think of the gamer developer). If something else, then you are likely dealing with a bit of a pragmatist. The next question is attitude towards their vocation. When I started this industry, it was common for employers to ship folks across the continent to do training courses for a few weeks (I had a nice time in Montreal at the IBM training centre in the 1970’s). Today, developers are deemed to be professionals, that is, they are expected to do ongoing training and skill enhancements. One good mile stick is certifications – which is common with most professions. Of course, there are the “Housian” types who are independent learners which can often be detected by the House method – give them a tough problem that is not in any textbook or course material. So consider the question “Do you consider yourself a professional?” get the answer (likely a mom’s apple pie Yes), then ask “What does professional mean to you?” and listen carefully….


When I was interviewed for becoming a blue badge(employee) at Microsoft, the technical interviewer asked me some interesting questions. Later I found out from his wife, was that all of the questions were items that he was trying to solve – he used my answers and I got the job.

Friday, May 14, 2010

Getting a Great Screen Shot

I have been doing a lot of technical blogging and writing lately; in doing this I need to take screen shots of dialog boxes, browser screen, etc… Good screen shots can break up text, make the blog post visually appealing, and help the reader navigate through the task you are writing about. I wanted to share a few of my tricks on getting a good screen shot.

Alt – Print Screen

clip_image001My preferred way of getting a good screen shot is to use the print screen button, usually located at the top right of your keyboard. This is great for capturing the whole screen. However if you just want to capture the active dialog use Alt-Print Screen. This doesn’t require any cropping. It is almost impossible to correctly crop with the Aero theme in Windows Vista or Windows 7, because it is hard to tell where the borders of the dialog end.

Use Notepad as a Background

When taking screen shot on Windows Vista or Windows 7 using the Aero theme you can see the applications behind in your title bar. To avoid this, open notepad and maximize it to full screen. With the default colors, notepad’s background provides a nice white backdrop for the window you are capturing. Move the window (it should never be maximized) you are capturing into the middle of the notepad window and you will have a clear title bar.

Web Screen Shots

The trend these days is to use a fixed width, center align main panel for your web pages; twitter is an example. The standard size for these is 960 pixels, so they appear nicely on a 1024 wide screen. 1024 pixel wide screen is the most prevalent minimum size screen. With this in consideration you don’t want to take a screen shot wider than 900 pixels – it will not fit on the web page. To easily accomplish this, reduce your screen resolution to 1024 width. Most of us are running very large screens, which make lots of text look great, however make for bad screen shots. By reducing your screen resolution you get bigger text, smaller widths and better screen shots.

Embedding the Image in Word

When you embed the image in a Microsoft Word document, word will resize it to fit the width of the page. This is not what you want; you want the original image at the original size. The person publishing the web page will resize the image; resizing it only once keeps its clarity.

When you embed the image in Word, right click on the Image choose Size from the drop down context menu, and then the Reset button in the Size dialog.  It will look big in Word; however it will be saved full size.

Security Considerations

To protect my own security I blur all references in the images of these things: Client hardware address, Magic cookie, Host name, Server host name, Server identifier, Subnet mask, Domain name, Domain Name server, NBOverTCPIPNameServer, Computer name, IP address, logins, and passwords. I usually use the spray can feature in Microsoft Paint.

Edit with Microsoft Paint

Starting in Vista and continuing on to Windows 7, Microsoft Paint will allow you to save your images and jpegs or gifs, which is great for web publishing. Once I press the print screen button the image is stored in the clipboard. Then I:

  • Open Microsoft Paint
  • Reduce the default working area to a very small size (smaller than the screen capture).
  • Paste in the image from clipboard. The working area is automatically expanded to include the whole working around.
  • Make security edits.
  • Use the cropping tool to crop only want I want.
  • Copy the cropped area into clipboard.
  • Paste it into Word document.

Third Party Products

There are many third party products that produce better screen shots than the techniques above, however everything above is free and is installed with Windows.



Thursday, May 13, 2010

Quick check of a developer’s HTML skills

Today, I got pinged to offer some comments on two developers who both coded up one equivalent page as an evaluation of their skills. The question is how to determine their relative skill levels. One approach is to read code and see if they happen to use the style that you like – but that is quasi-nepotism. You may not hire someone with a better style because you just don’t realize it. You will inbreed a specific coding style…


I decided to do push all of the pages through various validation engines. The logic is simple --- someone that codes close to standard is likely the more experienced in conforming to standards and best practices. So I pushed the pages through the URLs below and got the results shown below.


URL Dev #1 Dev#2 9 errors
5 warnings
1 error 0 Errors 50 errors 35% 41% 0 Errors 2 Errors 0 Errors 2 Errors
1 Warning 1 Error 18 Errors


Dev #1 is clearly much stronger with CSS be a potential weakness. Given that several of the above are Section 508 validators – Dev #1 knows what it takes to pass Section 508.


I’m tempted to suggest a final interview question when I interview folks.  “Create a page that…. and email me the code within 24 hours….” Then just grind the code through the above…. and create a table of all of the candidates.


I suspect that the advantage would be:

  • Less time needed to ramp up an individual to a given quality
  • Filtering out people less likely to follow practices – for some it may be laziness, for others it may a lack of self-discipline or an over-entitlement attitude.  Identifying this is very hard to do in an interview.

What “it depends” says about your architecture skills

The other day while reviewing a paper, I came across a classic-developer rhetorical expression “it depends”. I immediately recall David Hill’s prolog in a Pattern and Practices foreword.

“There is an old joke, told amongst mischievous developers, that in order to be considered an architect you just need to answer every technical question with "it depends" – Q: What’s the best way to implement authentication and authorization in my solution? – A: It depends; Q: How should I implement my data access layer? – A: It depends; Q: Which technology should I use for my solution’s UI? – A: It depends. Q: How can I make my application scalable? – A: It depends. You get the general idea.”


I think we can gain some insight on this usage by the following analogy:


There’s the mountain range of it depends ahead of us. We go and hit a local public house ( “Coureur des bois” and talk to the locals about crossing it. With a name like that, you surmise this is the place to find the perfect guide. You open the door and see young fit athletic types – just what you wanted. Being spotted as an out-of-towner, and with alcohol helping their tongues we get a lovely long list such as:

  • “It depends on how much money you have”
  • “It depends on how fast you want to get there”
  • “It depends on if you want to take photos en route”
  • “It depends if you have ice crampons”
  • “It depends if you have anti-bott plates”

All of the information is technically correct, but there may be a power game involved that may include masking ignorance. You may have a beer, sit down with them and hire some of them to lead you (after all they seem to know what is going on). Or, you may feel uncomfortable about the non-specifies and randomness of the answers and head off to more sober company at the local organic co-op grocery. You ask the cashier if she knows anyone that have cross this mountain range. She gives a few name and then adds, “You may wish to talk with Igor, he has a girl friend on the other side of the range and often goes and see his love. He lives down the road in a yurt.”


You head down the road and see a skinny  man of indeterminable age with salt-and-pepper dreadlocks. He’s Igor. You ask about crossing the mountain range and he responds, “I’m heading over on Friday, I may be willing to take you with”. You express interest and then are hit with the following questions:

  1. How many in your party?
  2. Their fitness level and what they are packing with
  3. Do you have $200 for mule hires?

“Ok, I will do it – pay for the mules and give me what you want when we get to the other side”. You are shocked – where are all of the “it depends”? You asked about them – Igor laughs.. “I think one or two of those want-to-be mountain guides have ever cross the mountains. They like hiking up and skiing the nearest mountains only.” What about anti-bott plates etc…. you asked –“Yes, you would need those if it was February and you wanted to avoid the park ranger – a few of the folks at the pub do a bit of poaching….”


The difference between a developer and a seasoned architect is that one knows what questions are relevant and the sequence to ask the questions. The answer for the first question determines what the second question will be. Only the need questions and issues are raised to get from A to B. A second common characteristic is that a developer often will advocate what they wish to learn (to further their skill sets). A seasoned architect wants to be certain of the results and thus keep to the proven unless the unexpected happen (like a forest fire) and then they tend to reorganize themselves to find the safest route given the new information.


So the next time someone uses the expression “it depends” – listen carefully for what they may actually be saying….

Tuesday, May 11, 2010

Enumerating all of the CSS Classes on a site

One of the projects that I’m working on needs to have an appendix listing all of the CSS classes used on the site, ideally with a cross reference for which page(s) it occurs on. There is no utility build into VS that will extract this (and since some of the class elements may be originating on controls, it’s hard to conceive of such a VS utility).

My solution was simple:

  • Create a page that links to all of the pages in the site
  • Create a console utility that walks the pages and then extracts all of the CSS class name found. This is actually very simple to do using:
  • I store the data in a data table and then save is as XML for subsequence use (for example creating a table in an appendix)

Here’s the code – enhance as needed.

using System;
using System.Net;
using System.Data;
using System.Collections.Generic;
using HtmlAgilityPack;

namespace ScanForCssClasses
class Program
    static void Main(string[] args)
        if (args.Length > 0)
            Console.WriteLine("Please supply a url to start from");
    static void GetRoot(string rooturl)
        DataTable results = new DataTable();

        DataRow row;
        string root=rooturl.Substring(0,rooturl.LastIndexOf("/"));
        WebClient wc = new WebClient();
        HtmlAgilityPack.HtmlDocument doc = new HtmlDocument();

        List<string> pagelist = new List<string>();
        foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))
            bool add=false;
            var test=link.Attributes["href"].Value.ToLower();
            if (!test.Contains(":") && test.Length > 3 && !test.StartsWith("#"))
            if(add && !pagelist.Contains(test))
        foreach (string url in pagelist)
            foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//*[@class]"))
                string relurl = url.Substring(root.Length);
                string css=link.Attributes["class"].Value;
                if (results.Select(
                    String.Format("[url]='{0}' and [class]='{1}'",relurl,css)
                    ).Length == 0)
                    results.Rows.Add(row = results.NewRow());
                    row["url"] = relurl;
                    row["class"] = css;
        DataSet set = new DataSet();

Monday, May 10, 2010

Making a Screensaver On Windows

DisplayProperties-ScreenSaverSettings Recently I was tasked with making a screensaver to run on Windows and it had to run on Windows XP, Windows Vista, and Windows 7. I decided to do it with WPF as that is my new favorite technology. So like all good developers I pulled up my browser and searched for somebody who’d done it already. After a little prodding, I found several articles with relevant code samples, a few MSDN pages and some other interesting stuff. I had my screensaver built shortly after.


Then came time to make the installer for the screensaver, a standard Windows installer is no big deal. This one just needed to add a couple of registry entries for the screensaver file to make it the default and copy the output file (an executable renamed with a .scr extension) to the appropriate folder. When I ran this everything worked beautifully, except now the dropdown that lets you choose your screensaver in the display properties only displays the filename of the output file, but on older Windows versions (pre-XP) the registry key only supports making an 8 character filename the default screensaver . Sure, it works fine to have an 8 character filename since this is for XP and above, but I don’t like putting spaces in filenames and I’d never release anything that sloppy so I went digging again.


NewItem-NativeResourceTemplate Turns out that the .scr file needs to have a Win32 native resource embedded in it that has a value in its StringTable. Doing this allowed the drop down to reference the embedded string. In a C++ application that wouldn’t be a big deal but I’m in C# where the resources are usually managed.


NativeResourceTemplate I went digging again. After some time, I found that I was supposed to use a Native Resource Template to create a resource file (.res) to embed into the executable. All the articles showed that clearly was the way to go, But none of them mentioned that you can’t create one of those on a C#/VB.NET project in Visual Studio. You have to create it by adding it as a Solution Item instead. It didn’t take long to figure that out but it would’ve saved me 10-15 minutes if somebody had bothered to mention it.


UseAResourceFile Creating that wasn’t a big deal, and there were examples for how to add a StringTable and the string for the friendly name. Then the next hurdle, How to embed it? Well, Visual Studio has an option to  use a res file instead of the normal manifest it embeds. Of course I’m not sure how this affects the file’s Vista compliance and security NativeResourceTemplate-StringTablesettings that are normally embedded using the manifest, or even if that matters. A point for further study.


In any case, the screensaver now installs and works as expected with the appropriate title in the dropdown so I can’t complain.


Technorati Tags: ,,,

Altering Master Page CSS Class on a page by page basis

The joys of a master page is that it gives uniformity across a website. If the customer wants to alter the look of a master page item on a specific page, it could get painful. Often the solution is the inclusion of additional conditional code in the master page. This solution is a spaghetti code approach.


A better solution is to tag the body of the master page with the name of the page, for example:

<body <%=PageSelector %>>


With this code behind:

public partial class Default : System.Web.UI.MasterPage
    public string PageSelector
            string filename = Request.AppRelativeCurrentExecutionFilePath.Substring(
                Request.AppRelativeCurrentExecutionFilePath.LastIndexOf(@"/") + 1)
                .Replace(".", string.Empty)
            return String.Format("ID='{0}'", filename);

The result is that you will see

<body ID="SiteMapPage">

And you can now customize the CSS on a page by page basis (as needed)


  • H3 { } – used for all pages not customized
  • #SiteMapPage H3 { } – used for only SiteMap.Aspx

There is no need to muck with C# code to make the customer happy.

Adding a similar item around the content place holder, also is a good idea – it allows class name collisions to be easily resolved. i.e.

<div id="Content">
    <asp:ContentPlaceHolder ID="MainContent" runat="server" />
  • H2 { } used for the master page elements
  • #Content H2 {} used for the content elements