PowerShell: solid password generator

I needed a PowerShell script to generate a random alpha-numeric string. Here were my goals:

  1. The randomness needs to be cryptographically strong.
  2. Having at least some characters of different types is not a concern here.
  3. Small-ish, readable code is a concern.

Here’s what I came up with:

# Generate an random code or password
$code = ""
$codeLength = 26
$allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
$rng = new-object System.Security.Cryptography.RNGCryptoServiceProvider
$randomBytes = new-object "System.Byte[]" 1
# keep unbiased by making sure input range divides evenly by output range
$inputRange = $allowedChars.Length * [Math]::Floor(256 / $allowedChars.Length)
while($code.Length -lt $codeLength) {
    $byte = $randomBytes[0]
    if($byte -lt $inputRange) { # throw away out-of-range inputs
        $code += $allowedChars[$byte % $allowedChars.Length]

# Here's the code/password:

I realize this script throws away more bits than necessary, but improving that while keeping $allowedChars flexible would add quite a few lines, and wasn’t worth the sacrifice to requirement #3. Thanks Dan Jenkins for helping me fix this with only one additional line of code!

I think it’s solid, but am very open to feedback.

Posted in PowerShell, Programming | 7 Comments

Stunning Possibilities with The Growth Mindset

The main message so far* in the book, Mindset (by Carol Dweck) is that your intelligence and mental ability is like a muscle: it’s not a fixed thing that you’re dealt at birth. Like a muscle, if you work hard (enduring some discomfort along the way) it will get stronger.

This can be in areas of math, music, science, and creativity. I’ve generally thought of myself as not a very artistic person — like that particular area is just not very accessible to me. It’s exciting that almost everyone has the raw materials to become creative, or musically proficient, or scientifically thoughtful. I could do almost anything in these areas, and now it’s just a matter of choice. It’s like sitting in the middle of a brand new world, and you can go anywhere you want. When you look over the landscape, you see endless possibilities in every direction. Like in the introduction of the Lion King:

There’s far too much to take in here.
More to do than can ever be done.
More to find than can ever be found.
There’s more to be seen than can ever be seen.

This is true for me, and true for you, too. And it’s true for our spouse, kids, coworkers and friends. Introduce a child to the growth mindset, and the world becomes a pretty exciting place to explore. Curiosity and determination beats apathetic innate talent in everything that matters.

Don’t get stymied in the vastness of possibility; you’re like a kid in a huge toy store. Find something and dig in! Draw a picture, write a story, follow your curiosity about the world into something fascinating. Do something awesome. And invite people close to you do it to.

(*I’m on chapter 3.)

Posted in Leadership | Leave a comment

My own measuring stick

We have a tendency to think that what we’re good at is intrinsically more important or valuable than things others are good at. This alienates the very ones who would be the most help to us (and us to them).

We don’t consciously compare the skill sets’ relative values; we judge people on the axis of performance we know best (the axis that we are good at). We hold them up to a measuring stick and find they fall short, not realizing that this measuring stick is one we’ve artificially constructed to give us every advantage.

With maturity and humility we can learn to see the other measuring sticks, and see people shine in their own natural strengths.

Can you think of people in your regular interactions who are good at things you’re not? When is the last time you gave someone like that some “hearty approbation and lavish praise?”

(Bonus: if you do express this appreciation to someone, make it all about them, not about you. Leave out any contrasts, even favorable. “You’re so much better than me at x,” is not coming from the right heart. “You provide x in a unique and valuable way to our team,” is better.)

Posted in Leadership, Trust | Leave a comment

Sending Email with the Gmail API in .NET / C#

I’ve a .NET web application with several Google API integrations and wanted to send Gmail as well. It took me all day, and I found precious little (useful) documentation, so it seemed worth a blog post.

At the start of the day I already had OAuth2 talking with Google. I did have to tweak my setup a bit, but authentication was already a solved problem with my integration.

I had to pull in two NuGet packages to get it to work:

Install-Package Google.Apis.Gmail.v1
Install-Package AE.Net.Mail

Update: In the comments below, Jon notes that using MimeKit instead of AE.Net.Mail makes it easier to send HTML-formatted email.

And here’s the code that sent an email:

using System.IO;
using System.Net.Mail;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;

public class TestEmail {

  public void SendIt() {
    var msg = new AE.Net.Mail.MailMessage {
      Subject = "Your Subject",
      Body = "Hello, World, from Gmail API!",
      From = new MailAddress("[you]@gmail.com")
    msg.To.Add(new MailAddress("yourbuddy@gmail.com"));
    msg.ReplyTo.Add(msg.From); // Bounces without this!!
    var msgStr = new StringWriter();

    // Context is a separate bit of code that provides OAuth context;
    // your construction of GmailService will be different from mine.
    var gmail = new GmailService(Context.GoogleOAuthInitializer);
    var result = gmail.Users.Messages.Send(new Message {
      Raw = Base64UrlEncode(msgStr.ToString())
    }, "me").Execute();
    Console.WriteLine("Message ID {0} sent.", result.Id);

  private static string Base64UrlEncode(string input) {
    var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
    // Special "url-safe" base64 encode.
    return Convert.ToBase64String(inputBytes)
      .Replace('+', '-')
      .Replace('/', '_')
      .Replace("=", "");


The .NET code samples in the Google documentation don’t tell you how to instantiate the Message class. That’s the hard part. There is a deep and complicated structure to it, and I couldn’t get it to work. The Google Service complained, basically saying, “I want you to use the Raw property.” And the Raw property is, well, raw: “The entire email message in an RFC 2822 formatted and URL-safe base64 encoded string.” Couple tricks here:

  • RFC 2822 is complicated.
  • System.Net.Mail.MailMessage doesn’t give access to the raw data (even though it must implement RFC 2822 internally).
  • URL-safe base64 encoding isn’t exactly what Convert.ToBase64String does.

Thankfully AE.Net.Mail.MailMessage provides the Save() method to get the raw RFC 2822 message, and just a little tweaking is necessary to get a URL-Safe base 64 encoding.

Hope saves someone some time! I did a lot of Googling today, and an article like this one would have saved me a ton of time.

Posted in Programming, REST | 34 Comments

CodeRush Template for INotifyPropertyChanged

Updated 6/6/14: @MarkMiller found my tweet the referred to this blog post and kindly pointed out that I had reinvented the wheel. If your class implements INotifyPropertyChanged, you could use the standard “p(type)” expansion and it’ll put in the property change code for you. You can customize the setter to use your framework by editing the System / Declaration Bodies / #PropertySetter# template. Big kudos to Mark for noticing my tweet and helping me with this!

See this to see what it looks like in action.

Raising a PropertyChanged event for every property in a class is a lot of typing, and if you have CodeRush for Visual Studio the following template should help you out.

(You’ll have to edit the “this.NotifyPropertyChanged” line to fit the way you raise this event in your framework.)

Seems like I need this once every year or so, and have to reinvent it every time. Hopefully this will be a good spot for me to pull this from.

Posted in CodeRush, Programming | 2 Comments

Something anyone trying out NodeJS should know up front

TL;DR – scroll down till you see the heading you’re looking for.

I really love JavaScript as a language, and there were lots of things about NodeJS that appealed to me. So when I had the opportunity to use NodeJS on a significant project about a year ago I went for it. The app pulled data from several web services, mashed them together, and posted results and commands to other services: There was a lot of async. NodeJS should be really good at this.

After two months of serious coding I found my code was littered all over with error checking code — not error handling code as in, “I can compensate for this error,” but simple error checking code: This callback gives me an `err` as first parameter. Hmm, I guess I better not ignore it. If it’s not empty I better that’s set to something, and pass it to my own callback. So I end up with this All. Over. The. Place:

function getCoolResult(x, y, callback) {
   lookupSomeXData(x, function(err, xData) {
      if(err) {
      combineYWithXData(y, xData, function(err, coolResult) {
        if(err) {
        callback(null, coolResult);

To be clear, my beef with NodeJS was that, in order to do it right, I needed those error-checking warts (two in the example above). I found myself thinking, “This is like writing C in the 90’s,” where one is required to check return codes after every function call.

I don’t like it. I want my core business code to be really focused on business concerns, not infrastructure concerns. I want to only worry about errors that I can actually do something intelligent and contextual with.

I ran this project for two months, then decided to rewrite all the server side code in C#. I’m a consultant/contractor and the rewrite was on my own dime, so I didn’t make the decision lightly. I’m really glad I did for this project, because:

  1. Deleting all the error checking code felt great. Like StrongBad-cleaning-his-inbox great. Go ahead, watch that little video and imagine yourself cleansing your code of all these little error-checking warts.
  2. I dropped several flakey and dubious third-party NPM packages and used built-in .NET libraries or more mature Nuget packages instead, resulting in less lines of code and a more stable app.
  3. There were big chunks of code I wrote myself for node that I replaced with a third-party Nuget package. At the time I could find no NPM counter-part for some of these things.

The C# code shrunk drastically, was cleaner and more stable. Probably slower executing, but not enough to be an issue for this project.

TL;DR starts here:

So I think NodeJS is pretty cool, and it may be the right tool for certain kinds of jobs, and if you’re interested in exploring it, you should! But there’s something important that Christopher Langton distilled down for me today (in comments) that I wish I’d known a year ago:

You ultimately will need to conform to the handling of known errors or pass them on, as this has become the only implementation that all modules apply.

My translation: every callback will have a little error checking fragment up front. Yeah, it’s kinda annoying, but just do it and move on. You can live with that.

(Promises can help, but they’re not ubiquitous in NodeJS.)

Posted in JavaScript, Programming | Leave a comment

Fueling Creative Effort

This is something I wrote around 2009. It’s a realization that I’ve kept reflecting on from time to time these past few years, and has influenced the way I encourage my kids in some positive activity. It’s a bit rambling – I’ve bolded the important parts.

Timmy had been working on building comic books for a while, but then lost interest. He still liked to tell stories all the time. He’s invented a super hero named Fireman (with some certain super powers that you might predict). He developed quite a number of episodes, but they’re all in his mind, they change a lot, and from my recollection the stories seem to change each time. Allison and I encourage him to write these stories out. I really felt this would help him develop as a story creator/teller. Understandably our encouragement didn’t turn into immediate action in this area. 🙂

Yesterday he went to the library and picked up a Hulk comic book. This morning I saw by his bookmark that he was almost through. Later I found him on the computer; he was using Notepad to type out a Fireman script. I excitedly read his story, then showed him how to use Word to add a little text style and correct his spelling mistakes. I’m really excited that he took the initiative to do this. I think writing out stories in Word will help with him develop his story creating/telling, help his spelling, get him a jump-start exploring the features of Word, and many other things, I’m sure.

What prompted me to write about this is what stimulated him to take this next step: He experienced something cool that someone else had created, and was moved by it to create his own thing along those same lines.

Now that I think about it, he had the same response over the Christmas break to board games. We played a few games, and before I even knew what he was doing he had created his own board game. It wasn’t very balanced — if you ran out of money you went to jail, and the only way to buy yourself out of jail was for other players to volunteer to give you money. But he’s made refinements since then that I haven’t had the opportunity yet to check out.

I have noticed the same response in myself. I loved board games, and made up a lot of them. One actually turned out pretty well, although it had a bit of a dark twist. The object of the game was to kill all the other players. On the back of a Chutes and Ladders board I drew a clue-like set of rooms with a square grid between rooms to travel. Each room had some game cards in it. The cards were either weapons, defense against weapons, or ammunition for the weapons that needed it. Each weapon had a range, so if you got within 3 squares of another player, and you had a gun and a bullet, you can shoot them. But if they had a bullet-proof vest then they’d remain in the game. Another weapon was the rope. If someone attacked you with the rope you’d be okay if you had the rope-defense card: the neck brace. Kinda silly. I remember playing it with my mom and dad; Mom was concerned, but played anyway. My Dad was less concerned, and I think had to admit that it was actually kinda fun. Since the game was transformed from Chutes and Ladders, I also decorated the game box. I crossed out Chutes and Ladders and wrote Murder for the title. The box originally had a bunch of kids running up the ladder of a slide, sliding down, then running back around to the ladder. I drew in weapons that the kids were carrying, so it became a bunch of kids chasing each other with knives, guns, and ropes.

Although the game definitely had a dark twist to it, I remember having a very clear conscience about the whole thing.

A little later I had the same type of response to video games. After playing a good video game, a fire was kindled in me to create a video game myself. Some of these fires would die out very quickly, stifled by the actual difficulty of creating these things. But a handful of them were seen through to creations of noteworthy significance for someone of my age at the time. These things would be my book, Future Experience, in fifth grade; the Murder board game; and Cirkup’s Quest, a platform video game written in BASICA.

I wandered around a bit with this, so I’ll note the main “breadcrumb” that I wanted to record here: the creative effort of others can inspire creativity in us and or kids.

Posted in Programming for Kids | Leave a comment

Inventing Worlds

I know there are some things about Software Development I really like, while there are other parts that I really don’t like. I’ve often wondered, mostly as fleeting thoughts lost in the bustle of a work day, what causes the difference. Why do some days just fly by, and I can code for a solid work day, and get home and all I want to do is keep coding? Why do other days drag on and on, and I can’t wait to be done?

I was glancing through Chapter One of this book (can read online for free) and this paragraph crystalized some thoughts around this. I really like inventing worlds.

“Every other science deals with the universe as it is. The physicist’s job, for example, is to understand how the world works, not to invent a world in which physical laws would be simpler or more pleasant to follow. Computer scientists, on the other hand, [do].”

That’s why starting new software projects is so fun for me – when you lay the groundwork, you are inventing a world. You’re composing the natural laws for a new universe. The abstractions you create in code become its atoms and molecules.

Not all universes are created equal. If you don’t do a good job creating your universe, it will become overly complex and difficult to operate in. If you do a good job, you can create something like The Architect of The Matrix describes:

“The first matrix I designed was quite naturally perfect, it was a work of art, flawless, sublime.”

It’s the world creation part I really enjoy. It’s where you can “listen to the code tell you what it wants to be.” Generally a new software project has a lot of that up front, then over time it transitions to a more “construction” phase. The opportunity to create new abstractions (new types of atoms and new natural laws) never completely goes away, but it does diminish. Projects where the opportunity for that level of creativity is lowest are the ones that are the least fun for me to work on.

Posted in General PC Usage, Programming | Leave a comment

Securely accessing RavenDB / RavenHQ over HTTP

I want to use a RavenDB database hosted in the cloud by RavenHQ from a NodeJS app. I didn’t find a JavaScript client or NPM package that looked very mature, so I looked into straight HTTP API access. This took me a little time to figure out – I wasn’t able to find a step-by-step guide, so here’s one:

1. Get an API key from the RavenHQ website.

I guess they’re GUIDs. They’re straightforward to set up and configure with the access you’d like. Let’s pretend mine is 19ecad1c-d90e-4a98-a2e7-e79f40881cef.


2. Hit the OAuth server to exchange your API key for an access token.

Make an HTTP GET request to the following URL. Include the two headers shown.

  • HTTP GET https://us-oauth-1.ravenhq.com/ApiKeys/OAuth/AccessToken
  • Api-Key: 19ecad1c-d90e-4a98-a2e7-e79f40881cef
  • grant_type: client_credentials

You should get back a JSON document that looks something like this:

   Body: "{\"UserId\":\"19ecad1c-d90e-4a98-a2e7-e79f40881cef\",\"AuthorizedDatabases\":[{\"Admin\":false,\"TenantId\":\"your-database\",\"ReadOnly\":false}],\"Issued\":63504123456789.6}", 
   Signature: "ABigLongNastyBase64Thing=" 


3. Access your RavenHQ server with the appropriate Authorization Header.

Now you should be able to use the HTTP API as documented, including the entire access token from the previous step in an Authorization header, like this:

  • HTTP GET https://yourbird.ravenhq.com/databases/your-database/docs
  • Authorization: Bearer {“Body”:”{\”UserId\”“, Signature: “ABigLongNastyBase64Thing=“}

To be clear, after the word “Bearer” and a space goes the entire JSON document you got back from the OAuth server, encoded as a string.

When you issue this request you should get an HTTP 200 response with JSON content matching what’s in your database.


4. Expiration

When the token expires your request will get a 401 Unauthorized response. Here are some of the interesting response headers that you’ll also get:

  • OAuth-Source: https://us-oauth-2.ravenhq.com/ApiKeys/OAuth/AccessToken
  • WWW-Authenticate: Bearer realm=”Raven”, error=”invalid_token“,error_description=”The access token is expired

With this information you can detect that your token has expired and get a new one per Step 1 above.

Posted in JavaScript, JSON, RavenDB, REST | 3 Comments

Theodore Roosevelt – amazing story

My family heard a local historian, Steve Stark, talk about Theodore Roosevelt this past Sunday. Mr. Stark seemed to really like the guy, and from listening I found myself liking him as well. Steve briefly mentioned how TR had marched three hoodlums to Dickinson all by himself, and during the long sleepless journey also managed to read the book Anna Karenina. I was interested to look into it further and found this summary of the journey — really interesting:


I like this sentence that TR wrote; found it something to think about. It’s hard to relate, now-a-days, to conditions like these:

[The three criminals] belonged to a class that always holds sway during the raw youth of a frontier community, and the putting down of which is the first step toward decent government.

I wonder: people who would have belonged to “this class” in a frontier community – how do they get on in today’s community, in our community, which has “put down” this class and formed “decent government?”

  • Are they the criminals that our police pretty well protect us from today?
  • Does the influence of this culture redirect them toward a more beneficial course of life?
  • Do they find more sophisticated ways to carry out their basic thievery (white-collar crimes, etc)?

I suppose all three, depending on the combination of luck and ability dealt each individual.

Back to TR, between this story and the one where he boxed down a guy with two six-shooters pointed at him, apparently he really was quite a guy. As busy as he was, even as President he kept regular appointments to play with his children, even if it meant ending meetings with congressmen. That’s a good admonition and reminder for me.

Posted in History | Leave a comment