Wednesday, March 10, 2010

Autohotkey: Wrapping the selection with a tag

Autohotkey is a nice tool to be familiar with—it enables you to create advanced hotkeys. Today, I built a very simple script which saved me a bunch of time. Here’s the skinny:

I’ve been blogging about software a lot and these posts are often heavy with terms or phrases that I wrap in http://www.autohotkey.com/ tags. Unfortunately, my editor (Live Writer), as awesome as it is, doesn’t support something like this. AutoHotKey to the rescue!

Here’s the script:

#c::                       ; fire on WIN+c
AutoTrim Off               ; Retain any leading and trailing whitespace on the clipboard.
ClipSaved := ClipboardAll  ; Save the entire clipboard so we can restore it when we're done
SendInput ^x               ; cut the selection to the clipboard
ClipWait                   ; wait for the clipboard to contain something
SendInput <code>%clipboard%</code> ; Output what was selected, surrounded by <code> tags
Clipboard := ClipSaved     ; Restore the original clipboard
ClipSaved =                ; Free the memory in case the clipboard was very large.
return

Load this into your AHK script, hit reload, and fire away. Select some text, hit WIN+C, and watch in amazement as it is surrounded by <code> tags.

Building URLs for “SRC” Attributes in ASP.NET MVC

I’ve been told that these programming posts are not interesting or funny. For those that have no interest in programming, I offer the following jokes:

“Chuck Norris can divide by zero”

“Chuck Norris can touch MC Hammer”

“Chuck Norris CAN believe it's not butter.”

Chuck Norris Facts

Now would be a good time for you to stop reading.


Dive into ASP.NET MVC and it won’t be long before you do this in a master page:

    <link type="text/css" rel="Stylesheet" href="~/Content/all-src.min.css" />
    <script type="text/javascript" src="~/Scripts/all-src.min.js"></script>

This of course includes a couple global files—one for styles and one for scripts. Here’s the rub: it doesn’t work at all. It’ll seem like it works at first, because you’ll have nice styles and some of your scripts might even work, but it will be a short-lived experience.

Unfortunately something funny is going on here. Those URLs are not valid—they’re more than relative (relative URLs are fine), they’re relative from an application root, denoted by the tilde (~). That tilde means nothing to the browser.

Now the funny business is that ASP.NET will rewrite the link tag automatically to include the correct relative URL by replacing the “~” with the appropriate path. It does not do that with script tags. So you try to be clever and use a web-friendly relative URL syntax like this:

    <script type="text/javascript" src="../../Scripts/all-src.min.js"></script>

Sorry, that doesn’t cut it. The “../../” will only work properly if the content page (which uses the master page) is nested 2-levels deep, which is not likely to be true very often.

The trick is to call into Url.Content or Url.Content like so:

    <script type="text/javascript" src="<%=Url.Content("~/Scripts/all-src.min.js")%>"></script>

This extra step will give me a nice URL, regardless of the page’s depth in my tree. So what’s the difference between Url.Content and Url.Content? ResolveUrl has been around forever as part of Url.Content. On the other hand, Url.Content is relatively new and ships as part of Url.Content. Aside from that, I have no idea—if you do, please share.

Note: these commands work pretty much everywhere—imgs, Url.Content, etc.

Monday, March 8, 2010

+/-20 Years of Computing

In less than 140 characters:

Great new things by decade: 90s: make/save data; 00s: find data; 10s: visualize data, extract greater meaning; 20s: democratize data

In detail:

1990s

The 90s were an incredible time. This was the decade where most computing focused on generating data and saving it. The conventional wisdom of the day seemed to be that, through a magical process, massive amounts of data could be used to solve anything. This was the era of the chess playing super computer, Deep Blue. This was the “anything is possible” childhood of the Internet.

2000s

Then came Google. Google made the 2000s the year of search. By then, what it had started in 1998 had reach a seriously huge critical mass. Early in the decade, though, many people and companies struggled to understand the Internet. This was a scary time for me as I saw some high profile collapses like Pets.com learn some hard lessons in business fundamentals (e.g. 1,000,000 views * $0/view = $0).

It’s during this time that businesses based on good foundations of revenue and purpose really grew. This was the decade of search. Entire generations learned that by typing a few keywords into a box could lead you to damn near anything you wanted to know. Organizations and aspiring individuals learned that by pushing information to the Internet in a public way, they could capitalize on this traffic. This was a cool decade.

That brings us to today.

2010s

We’re starting to feel a little overloaded by the massive amounts of information available to us. The ability to find a dataset, track it over a period of time and compare it to another dataset is a fairly challenging task today. This is where I expect to see some big “Wows” in 2010—visualization of data.

I’ve seen some absolutely amazing things coming from TED lately (go watch those now) and am excited for what fiscally strong companies and universities can create. Enabling non-PhDs to extract meaning and value out of massive amounts of data has been on the radar for the last 20 years—I think we’re finally to a point where it can happen on a grand scale.

Computing power is no longer a limitation.

Connectivity is no longer a limitation.

We will seem some very impressive and innovative ways to make sense and meaning of data very soon.

2020s

I think the success of data visualization will lead to passionate movements to democratize data. Around 2020, it will no longer be acceptable to conceal, hide, or privatize data. There will be a very successful movement to make government data and university data available via extremely accessible means—via APIs or methods that probably don’t exist today. Individuals will adopt the use of standards and contribute—for free—to the pool of data. This long-tail effect will be interesting if not incredible.

Organizations will jump on board and contribute to this stream by dropping the unsuccessful pay-walls they constructed in the 2010s. Vague patents, which will be distorted and abused in the 2010s to monetize data will be invalidated or expire and the flood gates will open.

In 2028, people will start discussing the merits of a conventional census—a reinvigoration of arguments made leading up to the 2020 census. Doing away with the census—which seemed ridiculous in 2018—will have a lot of support. We’ll do one anyway (at great expense) but it’ll be the last time. Around this time (2030), near-real-time data of greater quality than today’s census numbers will be available to all of us.

In Summary

I’m excited.

Thanks to the Internet, I’ll end up back on some future incarnation of this page to see how completely and utterly wrong I was about everything (I can’t wait).

Creating/Submitting a Patch to a Subversion Repo

I’ve been told that these programming posts are not interesting or funny. For those that have no interest in programming, I offer the following jokes:

“I don't think I could stab somebody, cause I'm really bad at a Capri Sun.”

“I hope God speaks English. If I get up to heaven and have to point at a menu, I'm gonna be pissed.”

“I hope we find a cure for every major disease, because I'm tired of walking 5K. I'm pretty sure I don't have to sweat for cancer. I'll write a check.”

Daniel Tosh (via)

Now would be a good time for you to stop reading.


I use Subversion as my primary version control system. It’s awesome. I have a few users that have read-only rights to this repo and only occasionally make changes themselves. In these cases, I can’t provide commit rights to the repo so what are we to do? Patches.

A patch is basically a change set wrapped up into a single tidy file. The patch can be created by one dev and sent to another to be applied to the VCS. SVN, like most VCSs has very good support for patches. This post describes how to create one.

First, you should update your working directory if possible with “SVN Update”:

image

Normally you would go to the Commit screen to apply your changes. Since you don’t have commit access, this won’t work, so instead right-click and go to “TortoiseSVN” > “Create Patch”:

image

A dialog will show you all the changes it has detected; you can double click each file to diff it. Choose the changes you want included in the patch and click “OK”:

image

Save the patch somewhere handy:

image

Send the patch file off to your committer and you’re done! Go ahead and open it up in a text editor if you want to see how these work. It’s basically a snippet of each of the pieces of code you changed, all bundled up into a nice text file.

Applying a Patch to a Subversion Repo

Of course the process of applying patches is simple, too. Right-click on the patch file and choose “TortoiseSVN” > “Apply Patch”:

image

Choose the SVN working directory to which the patch should be applied:

image

You’ll see a list of the patched files and have the opportunity to review each change:

image

Then right click to apply some or all of the changes into the working directory you chose.

The patch has now been applied to your working directory—now would be a good time to commit it via normal means (right-click >  “SVN Commit”):

image

It might seem a little complicated at first, but after you do it once or twice it’ll click as a convenient and effective way to share change sets.

Friday, March 5, 2010

Active Directory Look-Up

I’ve been told that these programming posts are not interesting or funny. For those that have no interest in programming, I offer the following joke:

“I was gonna get a candy bar; the button I was supposed to push was ‘HH’, so I went to the side, I found the ‘H’ button, I pushed it twice. F’in...potato chips came out, man, because they had an ‘HH’ button for Christ's sake! You need to let me know. I'm not familiar with the concept of ‘HH’. I did not learn my AA-BB-CC's. God god, dammit dammit” –Mitch Hedberg (via)

Now would be a good time for you to stop reading.


I’ve been working on an app that’s defers authentication to the company’s Active Directory. Rather than ask user’s to fill in profile info like a display name, I decided to pull this info out of the directory.

This turned out to be ridiculously easy after adding a reference to System.DirectoryServices.AccountManagement to the project:

using (var PC = new PrincipalContext(ContextType.Domain))
{
    var UserPrincipal = Principal.FindByIdentity(PC, userName);
}

In this case, we’re passing along the user’s NT name, including the domain to help make it unique (e.g. “domain\user”) and getting back an object of type System.DirectoryServices.AccountManagement.Principal, which has some nice properties like DisplayName and Sid.

Since I’m running this app as a domain user, I don’t even have to configure the directory connection (which is nice, because that part’s a pain).


OK so I have the user’s name, but I’m rarely a fan of duplicating data. But I need a local copy of the user’s name to keep things nice and speedy (plus hitting the domain for a person’s name all the time is a little silly, too).

My compromise is that I update my local copy with the directory’s profile data each time the user logs in. I’m already hitting the domain to authenticate the user any way so it’s not any extra work. This should take care of the rare situation that someone’s name or profile info changes without requiring anyone to do anything.

HTML/JS: Progressive Enhancement

The great thing about a semantic approach to web development is how nice and easy it can be to make progressive enhancements.

For example, suppose I have a “what’s this” help link beside some potentially confusing statement:

 image

Nothing fancy here—just a link with a _blank target (source, demo):

<p>Hello World 
  <a href="/help/tips"
     target="_blank" 
     title="Hello World Help"
     class="help-link">(what's this?)</a></p>

It’s not very pretty but it gets the job done without any Javascript. Let’s make it sexy:

image

Here we’ve augmented the help link with a nice jQuery UI dialog instead of a browser popup (source, demo):

$(function(){
  
  $('.help-link').click(function(){
    
    $('<div></div>')
      .attr('title', this.title)
      .load(this.href)
      .dialog({
        modal: true,
        buttons: {
          Ok: function () {
            $(this).dialog('close');
          }
        },
        width: 600,
        height: 350    
      });
    
    return false;
  });
  
});​

This doesn’t require any changes to the HTML/CSS—it uses existing attributes like href and title to wire itself up to the link. And, if JS is disabled or broken, the link will still work.

By applying incremental enhancements in this fashion, we can easily maintain decent support for less-capable browsers while keeping our code clean and elegant.

You might notice, too, that this JS snippet is looking at a class (help-link), not an id. Since it infers everything it needs to show the dialog from the link itself, this snippet will work on any link in the page tagged with the help-link class. Nice, right?

Thursday, March 4, 2010

Generating Super Shiny, Hopefully Secure Tokens

I’ve been told that these programming posts are not interesting or funny. For those that have no interest in programming, I offer the following joke:

“My friend had a burrito. The next day he said, ‘That burrito did not agree with me.’ I was like, ‘Was the disagreement over whether or not you’d have diarrhea? Let me guess who won.’” –Demetri Martin (via)

Now would be a good time for you to stop reading.


I was working on a little security related code today which required the generation of unique and random tokens. I’m always nervous working with crypto because it’s so easy to fail.

But here I am, ready to fail.

So like I said, I need to create a bunch of tokens—blocks of text or numbers. They can’t be easily guessed and need to be unique. Let’s see if I can’t screw this up.

        /// <summary>
        /// Generate a decently long string o random characters, suitable for tokens
        /// </summary>
        /// <returns>a string of gobbledygook</returns>
        public static string GenerateKey()
        {
            var RandomBytes = new byte[
                6 * 10 // use a multiple of 6 to get a full base64 output http://en.wikipedia.org/wiki/Base64
                - 16 // compensate for the 16-byte guid we're going to add in 
                ];

            // fill the buffer with garbage (this is threadsafe)
            BetterRandom.GetBytes(RandomBytes);

            // get a guid, which will be unique enough for us
            var UniqueBytes = Guid.NewGuid().ToByteArray();

            // encode the garbage as friendly, printable characters
            var AllBytes = new byte[RandomBytes.Length + UniqueBytes.Length];
            UniqueBytes.CopyTo(AllBytes, 0);
            RandomBytes.CopyTo(AllBytes, UniqueBytes.Length);

            return Convert.ToBase64String(AllBytes);
        }
        static RandomNumberGenerator BetterRandom = new RNGCryptoServiceProvider();

Basically I take two components—a 16-bit GUID, and a 44-byte chunk of random bits. The GUID would normally be enough to satisfy me as they are pretty much unique (and the Win32 algorithm might even guarantee them to be unique when considering a single machine) but, I was afraid they might be predictable as they aren’t actually all that random.

How’d I come up with 44 bytes (352 bits)? It looks nice. I guessed a few numbers until I got the encoded output to be of reasonable size. Which brings me to the Base64 conversion. This just takes the binary blob of bits and turns them into simple, printable characters so I can pass them around in URLs.

If you’re know of any weaknesses with this approach, please share! Something like this will eventually guard something about as valuable as a garden gnome, so I’m not too worried about it yet. It’s certainly more secure than the simple passwords most of us use.