DaedTech

Stories about Software

By

How To Put Your Favorite Source Code Goodies on Nuget

A while back, I made a post encouraging people to get fed up every now and then and figure out a better way of doing something. Well, tonight I take my own advice. I am sick and tired of rifling through old projects to find code that I copy and paste into literally every non-trivial .NET solution that I create. There’s a thing for this, and it’s called Nuget. I use it all the time to consume other people’s code, libraries and utilities, but not my own. Nope, for my own, I copy and paste stuff from other projects. Not anymore. This ends now.

My mission tonight is to take a simple bit of code that I add to all my unit test projects and to make it publicly available view Nuget. Below is the code. Pretty straightforward and unremarkable. For about 5 versions of MSTest, I’ve hated the “ExpectedException” attribute for testing that something throws an exception. It’s imprecise. All it tests is that somewhere, anywhere, in the course of execution, an exception of the type in question is thrown. Could be on the first line of the method, could be on the last, could happen in the middle from something nested 8 calls deep in the call stack. Who knows? Well, I want to know and be precise, so here’s what I do instead:

public static class ExtendedAssert
{
    /// Check that a statement throws a specific type of exception
    /// Exception type inheriting from Exception
    /// Action that should throw the exception
    public static void Throws(Action executable) where TException : Exception
    {
        try
        {
            executable();
        }
        catch (Exception ex)
        {
            Assert.IsTrue(ex.GetType() == typeof(TException), String.Format("Expected exception of type {0} but got {1}", typeof(TException), ex.GetType()));
            return;
        }
        Assert.Fail(String.Format("Expected exception of type {0}, but no exception was thrown.", typeof(TException)));
    }

    /// Check that a statement throws some kind of exception
    /// Action that should throw the exception
    /// Optionally specify a message
    public static void Throws(Action executable, string message = null)
    {
        try
        {
            executable();
        }
        catch
        {
            Assert.IsTrue(true);
            return;
        }
        Assert.Fail(message ?? "Expected an exception but none was thrown.");
    }

    /// Check that a statement does not throw an exception
    /// Action to execute
    public static void DoesNotThrow(Action executable)
    {
        try
        {
            executable();
        }
        catch (Exception ex)
        {
            Assert.Fail(String.Format("Expected no exception, but exception of type {0} was thrown.", ex.GetType()));
        }
    }

Now, let’s put this on Nuget somehow. I found my way to this link, with instructions. Having no idea what I’m doing (though I did play with this once, maybe a year and a half ago), I’m going with the GUI option even though there’s also a command line option. So, I downloaded the installer and installed the Nuget package explorer.

From there, I followed the link’s instructions, more or less. I edited the package meta data to include version info, ID, author info, and a description. Then, I started to play around with the “Framework Assemblies” section, but abandoned that after a moment. Instead, I went up to Content->Add->Existing file and added ExtendedAssert. Once I saw the source code pop up, I was pretty content (sorry about the little Grindstone timer in the screenshot — didn’t notice ’til it was too late):

PackageExplorer

Next up, I ran Tools->Analyze Package. No issues found. Not too shabby for someone with no idea what he’s doing! Now, to go for the gusto — let’s publish this sucker. File->Publish and, drumroll please…. ruh roh. I need something called a “Publish Key” to publish it to nuget.org.

PublishKey

But, as it turns out, getting an API key is simple. Just sign up at nuget.org and you get one. I used my Microsoft account to sign up. I uploaded my DaedTech logo for the profile picture and tweaked a few settings and got my very own API key (found by clicking on my account name under the “search packages” text box at the top). There was even a little clipboard logo next to it for handy copying, and I copied it into the window shown above, and, viola! After about 20 seconds, the publish was successful. I’d show you a screenshot, but I’m not sure if I’m supposed to keep the API key a secret. Better safe than sorry. Actually, belay that last thought — you are supposed to keep it a secret. If you click on “More Info” under your API key, it says, and I quote:

Your API key provides you with a token that identifies you to the gallery. Keep this a secret. You can always regenerate your key at any time (invalidating previous keys) if your token is accidentally revealed.

Emphasis mine — turns out my instinct was right. And, sorry for the freewheeling nature of this post, but I’m literally figuring this stuff out as I type, and I thought it might make for an interesting read to see how someone else pokes around at this kind of experimenting.

Okay, now to see if I can actually get that thing. I’m going to create a brand new test project in Visual Studio and see if I can install my beloved ExtendedAssert through Nuget, now.

NugetSuccess

Holy crap, awesome! I’m famous! (Actually, that was so easy that I kind of feel guilty — I thought it’d be some kind of battle, like publishing a phone app or something). But, the moment of truth was a little less exciting. I installed the package, and it really didn’t do anything. My source code file didn’t appear. Hmmm…

After a bit of googling, I found this stack overflow question. Let’s give that a try, optimistically upvoting the question and accepted answer before I forget. I right clicked in the “package contents” window, added a content folder, and then dragged ExtendedAssert into that folder. In order to re-publish, I had to rev the version number, so I revved the patch decimal, since this is a hot patch to cover an embarrassing release if I’ve ever seen one. No time for testing on my machine or a staging environment — let’s slam this baby right into production!

Woohoo! It worked and compiled! Check it out:

NugetInstallSuccess

But, there’s still one sort of embarrassing problem — V1.0.1 has the namespace from whichever project I picked rather than the default namespace for the assembly. That’s kind of awkward. Let’s go back to google and see about tidying that up. First hit was promising. I’m going to try replacing the namespace with a “source code transformation” as shown here:

s

Then, according to the link, I also need to change the filename to ExtendedAssert.cs.pp (this took me another publish to figure out that I won’t bore you with). Let’s rev again and go into production. Jackpot! Don’t believe me? Go grab it yourself.

The Lessons Here

A few things I’ll note at this point. First off, I recall that it’s possible to save these packages locally and for me to try them before I push to Nuget. I should definitely have done that, so there’s a meta-lesson here in that I fell into the classic newbie trap of thinking “oh, this is simple and it’ll just work, so I’ll push it to the server.” I’m three patches in and it’s finally working. Glad I don’t have tens of thousands of users for this thing.

But the biggest thing to take away from this is that Nuget is really easy. I had no idea what I was doing and within an hour I had a package up. For the last 5 years or so, every time I start a new project, I’d shuffle around on the machine to find another ExtendedAssert.cs that I could copy into the new project. If it’s a new machine, I’d email it to myself. A new job? Have a coworker at the old one email it to me. Sheesh, barbaric. And I put up with it for years, but not anymore. Given how simple this is, I’m going to start making little Nuget packages for all my miscellaneous source code goodies that I transport with me from project to project. I encourage you to do the same.

By

Chess TDD 10: A Knight’s Tale

Okay, I promise, no more of these titles after this edition.  But, to make up for it, this time I actually wrote the code and did the audio in the same day, so I remember very well what I was talking about.

Here’s what I accomplish in this clip:

  • Move Queen into it’s own class.
  • Implement Knight with GetMovesFrom()

Here are some lessons to take away:

  • It’s okay to be obtuse for a while in your TDD, if doing so helps your understanding. I started with a hard-coded thing to get the first test pass and then did another for the second. Both tests would need to continue passing, and I was feeling my way through what to do. As long as you get going at some point, this is okay. Whatever helps.
  • Try to avoid getting into a routine. By getting a fresh look, I was able to define a method that I thought improved readability and aided code use. I’d written a number of things like this before, but I always try to think of new ways to approach problems, rather than settling into a routine of semi-mindless work.
  • If you’re not careful, you can get a little ahead of yourself. I was on auto-pilot and didn’t realize I wasn’t compiling for a while before I corrected myself.
  • Get it working first, and then worry about cleanup later. You can always make things more elegant later, when it’s working (at least when you do TDD).

By

The Consultant’s Life: Weird Stuff You Suddenly Need To Think About

I’m going to start off with a quote, though I’ve been warned by someone who knows more about writing than I do that this may be a cheesy thing to do. Oh well, I’m living dangerously these days.

“Gentlemen,” he said
“I don’t need your organization, I’ve shined your shoes
I’ve moved your mountains and marked your cards
But Eden is burning; either brace yourself for elimination
Or else your hearts must have the courage for the Changing of the Guards”

— Bob Dylan (Changing of the Guards)

I’ve made little secret of my opinion that the software developer (and knowledge worker in general) is trending toward a life of increased autonomy and agency.

WalkAway

Anyway, I’ve been on my own for a few weeks now, so I thought I’d share some experiences that I’ve had so far. And, I’m not talking about anything especially profound here such as that I’ve reconsidered my life and found nirvana in controlling my own destiny, or whatever. I’m talking about the kind of things that, should you undertake this particular choice in career, are going to prompt you to say, “holy crap, I have to do what!?” Or maybe that’s just me.

You Need a Company

This is cheating a bit, because I did this some years ago, but if you’re contemplating free agency, this is important. Personally, I’ve formed a limited liability corporation (LLC). There are other corporate structures that you can choose from that differ in various legal and tax-oriented ways, but I won’t really go into those. Instead, I’ll discuss my motivations that I think are probably paramount for you to consider.

(I will qualify what I’m about to say with the standard “I am not a lawyer” caveat, so keep in mind that you’re hearing my understanding and recollection of what lawyers and others have told me. These are my motivations based on my understanding of the world.)

My LLC got me two important things: limited liability and a business entity. By default, if you start moonlighting through something like E-Lance, you’re operating as a “Sole Proprietorship.” In a Sole Proprietorship you are Louis XIV, in that you ARE the business. This makes life easy from an income tax perspective because there’s only you, but it makes things a real bummer from a getting sued perspective, since, if you write software that takes down your client’s business for a week, you can be personally sued for damages. If you don’t have enough money in the bank to cover the tab, the client can come after your car and your house (though you should certainly write verbiage into your contract that limits your liability, however you do business). If you create an LLC, on the other hand, you’re creating a separate entity — a property that you own and that can conduct business. Now, you client can sue the LLC for all that it is worth, but the LLC doesn’t own your car or your house, so those are off limits.

The motivation of having owning a business entity (second thing I listed) extends beyond just the limited liability motivation, however. A huge consideration here is that the business entity makes it a lot easier to classify things as business expenses for tax purposes. Having always done my own taxes and operated both in Sole Proprietorship and LLC capacities, my experience is that you can claim a substantially larger amount of deductions when you have a business entity. It also makes keeping things straight for taxes and accounting easier. My LLC has checking, savings, and credit card accounts, so for bookkeeping purposes, anything that DaedTech needs (supplies, equipment, etc) goes through that channel and anything non-business related is with my normal credit cards and bank accounts. On top of that, the business entity lends legitimacy in your dealings with others. There’s a big difference between telling your clients to mail you a check made out to Joe Smith and invoicing them on corporate letterhead instructing them to make checks payable to Acme Inc, for instance.

Creating an LLC isn’t particularly difficult. It’ll vary some by state in terms of the procedure, but you essentially fill out a form and send it into the appropriate government agency in your state (or, potentially another state — a lot of places incorporate in Delaware because of its favorable tax laws or something, but I don’t know what’s required to be able to do this). There will be a fee to incorporate and then an annual maintenance fee and these also vary by state. When you do this, you also notify the federal government of what you’re doing and you are issued an EIN (Employer Identification Number), which is basically your LLC’s social security number, for all intents and purposes. You’ll need this for tax purposes and for conducting certain kinds of business with other entities.

Now onto the things I’ve stumbled across in the last few weeks…

Tracking Your Time

When moonlighting, it was generally easy to keep track of billable hours, since I’d work 9-5 and then come home and do an hour or two of freelance work. I’d have a spreadsheet or something where I’d log the hours as I went. But boy did I discover how wildly impractical that is when doing this full time.

In the first place, I’m now doing billable work for several different entities, so the spreadsheet would need to be more complicated. But even more importantly, I don’t want to just look back on a week and say, “oh, that’s nice, I billed 30 hours.” I want to be able to audit how much billable work versus total work I did (with the idea of maximizing this ratio). There’s a big difference between billing 30 hours and working 30 hours and billing 30 hours while working 60 (the other 30 going to looking for more business, doing clerical work, taking exploratory meetings, side projects, blog posts, etc). In fact there’s literally a difference of 100% of your pay. If Jane bills $100 per hour, bills 30 hours and works 60 total, she’s really only making $50 per hour and not $100.

Other considerations abound as well, such as searches, filtering, different billing rates, and annotations about the work. I saw immediately that a spreadsheet was going to get way out of control very quickly. A younger, wetter-behind-the-ears Erik would have immediately started building a homegrown database app for this, but, bearing in mind how that would absolutely sink my billable ratio, I did some research and settled on Grindstone for logging hours. It has a lot of nice features to it and it also had the advantage that I’d used it previously. It gives me enough granularity that I can easily look back at the tasks I’ve logged all week or month and any notes I’ve appended to them, and generate invoices for individual customers as appropriate.

Working Too Much or Thrashing

This is kind of a weird one, but it’ll probably creep up on you. When I started on the freelance path my concern was that I’d depart from my schedule and start staying up ’til all hours or sleeping until 9 every day or something. What I didn’t anticipate was what actually happened. I had no problem getting up, keeping focused, sticking to a routine, but I did find that I was logging 9 to 6 hours in Grindstone and then also logging 11 PM to 1 AM hours after I was the only one awake in the house. And also Saturday and Sunday hours.

As your own person, responsible for your own income, there’s a much more intense feeling that every hour you’re not working is an hour that you’re leaving income on the table. Every would-be non-technical startup partner with an idea for an app that you don’t meet for lunch is you missing out. Every recruiter call is an opportunity for you to turn the tables and look for contract work. You can’t pass on anything.

I’ve had to fight tooth and nail to give myself the freedom to pass on leads and not pursue everything. Weird as it sounds, my blog post announcing free agency was met with more recruiters calling me about CTO/Dev Manager type positions by far than it was with people interested in my consulting. I started doing some interviews because I’m open to all sorts of possibilities, but I’ve now had to ramp that back and pass on some offers because between scheduling all of that and also earning my keep, I was logging 80+ hours per week in Grindstone. And, while I’m not averse to hard work, I had to look at the fact that doing job interviews and lots of exploratory meetings are unlikely to be revenue generating for me — I have to focus on the most promising/profitable things going on.

That’s been unexpectedly hard, since I’m very enthusiastic and game for things. Anyone approaching me with a project or an opportunity makes me want to say, “yeah, totally, let’s do that,” but I’m learning there’s no way I can say that to everyone or even the majority of those to whom I talk.

Weird Tax Things (Quarterly Filing and Mileage)

Anything related to taxes is always an odd combination of scary and extremely boring, and that led me to procrastinate a bit when it came to “what do I do with all of this gross income I’m getting with no taxes withheld?” When you work for a company, you fill out a W-4 form and your company then sets up your paychecks such that the IRS takes its pound of flesh before the money ever hits your bank account. At tax time, you then get a “refund,” which is really just them saying, “turns out we held on to too much of your money and, oops, look at that, we earned interest on it, but here ya go.” In a case where your employer didn’t withhold enough from your paycheck, on the other hand, you have to cut the IRS a check for what you owe, come tax time.

But if all your money is coming in via checks for services paid, there are no taxes being withheld at all. And that means, come tax time, you’re going to have to write the IRS a massive check for your entire annual tax burden. However, the IRS, while happy to hold onto and earn interest on your money, gets extremely cranky if you hold onto and earn interest on theirs. So, if you’re a free agent, the normal course of action is that you have to send them quarterly checks in order not to face penalties. (If you’re liquid enough and depending on how you structure your business for tax purposes, there are ways around this, but I’m going to focus on the simplest sort of case — me with my LLC).

I spoke with an accountant, and I have yet to actually do this, but you basically fill out a form Schedule C that calculates the business’s profits and losses and then, based on that, you compute/estimate the tax you owe for the quarter and send them a check for that amount. Then, at tax time each year, like a normal, workaday person, you’ll probably either get a small refund or owe a small amount of money, rather than the entire 30% or whatever of your salary that would go to Fed, SS, Medicare and State taxes.

So be aware that you now have to be an active participant in the tax game, rather than just passively waiting for your W2s each year and firing up Turbo Tax or dropping things off at H&R Block.

Forms, Forms, Forms

I earlier mentioned sending invoices to clients. To do this, you need an invoice form. I also mentioned drawing up contracts for clients. To do this, you need a contract form. You’re going to need a lot of forms, so if you’re contemplating a move to freelancing, I’d get these ready in advance.

I’d say you’ll want the following forms in your arsenal: invoice, contract, statement of work, master services agreement. Invoices are obvious — this is simply the way you enumerate the services rendered and request payment. Contract is an agreement signed by both parties for work, often on an ongoing basis. I’d use this for retainer arrangements or “I’ll work 15 hours per week for you” arrangements. Statement of work is a more project oriented document — “I’m going to build you a website and you’re going to pay me for it.” Master Services agreement is an umbrella agreement that establishes general terms for you to do business with a company (e.g. “we won’t steal each others’ intellectual property, we won’t poach each others’ employees, etc”). Usually you would exchange this with a client for the duration of your relationship and then have individual contracts or SOWs underneath its umbrella. This one is probably not quite as critical for fledgling consultancies/free agencies, but may be worth having around.

Where do you get these? Well, if you know or have a lawyer, the lawyer can probably draft them or perhaps just supply you with a boilerplate one. A lawyer will also be happy to review any specifics and mark them up. But if you don’t want to incur that expense, search your inbox for emails on which you were CCed at your company that may have included these. For instance, if you were CCed on some email where your department reached an agreement with Expensive Consultants Inc to do some web design, grab that and use it as a starting point for creating your own. If they’ve been in business a while, they’re probably doing something right.

Keeping the Books

When you’re on you own, running your company finances isn’t quite the same as whatever you do for your personal finances. You want bookkeeping software. I’m fortunate in that I’ve been using Quicken since my finances were no more complex than a checking account and the occasional paycheck, and so the move to Quicken for Home and Small Business was easy.

Quicken (or Quick Books or whatever you use) will allow you to record invoices that you’ve issued and then to keep track of whether payment has been received. This is important because you’ll send out invoices that require payment within 30 days, and then it’s up to you to keep track of whether clients have paid or not. This is not like W2 employment. Companies will straight up forget to pay you. Or not bother. Because, remember, you’re not dealing with an individual and you’re not dealing with a payroll system — you’re dealing with Accounts Payable departments and people who have jobs of which only a tiny portion is sending out the dozens or hundreds of checks per day that a company has to send out. Stuff falls through the cracks, and you need to be checking back on the status of payments that you’re due. If you have only one client or if you’re missing huge checks, this will be obvious, but if you remoted in and helped a former client for an hour or 2 in June, it’s pretty easy to forget that they owe you $150, unless you have software that reminds you.

Software like this also helps you keep track of things you can deduct but wouldn’t think of. Sure, if you bought a computer or a bunch of printer ink, you’ll file that as “business expense” for tax purposes when recording expenses. But what about the mileage you drove getting to a meeting? Record that! It’s tax deductible at about 50 cents per mile. Quicken lets you keep track of this and other similar non-expsense-per-se-expenses.

That’s All for Now

This has become a pretty long post, so I’m going to wrap up here and save other things that I learn for another post, later. And, while I’m speaking somewhat authoritatively on this stuff, it’s stuff I am truly learning the nuance of as I go. A lot of it falls under the purview of “stuff that I’d have known if I’d thought about, but was kind of surprised by its immediacy.” Other things were news to me. And, since this is a learning experience, please feel free to chime in on the comments section with your experiences, tips, or corrections of anything you feel I’ve gotten wrong.

Cheers, and happy free agency to anyone reading in advance of taking the plunge!

By

Build Your Own Home Automation Server for Cheap

Most of the text for this post is lifted from the script of my Pluralsight course about home automation. If you’d like a free pass to Pluralsight to check it out, please email me at erik at daedtech. But whether you check out the course or not, I’m going to describe exactly what I bought to get going with a home automation setup for, all in, less than $100. In the rest of the course, I describe how I also created a compact, RESTful home automation server that you can send commands to from the language/platform of your choice.

BusyHouse

I personally have been doing projects with home automation for some time now, and have experimented with a variety of different home automation technologies. I’ve settled on the following setup as an introduction to home automation. I’m going to be using a Raspberry Pi to make a REST endpoint for home automation commands, and the programming will be done in Python. By way of hardware, I’m going to show you how control a lamp using X10 brand devices.

I chose the Pi because its small form factor and affordable price make it an ideal candidate for your home automation controller that won’t break the bank or take up a lot of space. I chose the X10 brand for the hardware because it’s been around the longest and tends to be the least expensive, making it a good choice for new home automation enthusiasts. And finally, I chose Python because it is the lingua franca of the Pi, the language of the X10 driver I’ll be using, and a perfectly good language for building a REST server. I am historically a C#, Java and C++ programmer, but I’ve picked up enough Python for this course to make a working endpoint and to show you how to do the same. You’re going to need hardware specifics, so I’m going to list the hardware here that you’ll need as well as some potentially helpful peripherals.

The first category of hardware that you’re going to need is the Raspberry Pi and all of its accessories. The Pi itself is easy to order, but you may not realize that you’ll need some other stuff to get going. The most important thing is a mini SD card that will function as the Pi’s hard drive. It doesn’t come with one on board. Also important is a power supply for the Pi, but you can use any Android phone charger interchangeably. I’ve bought an extra one for each Pi I have because it’s rather annoying to have to cannibalize one of my phone chargers. You might also want to get a HDMI or DVI adapter if you plan to plug the Pi into a monitor while you work with it, assuming your monitor doesn’t have an HDMI port. The Pi’s only video output is HDMI. Also, bear in mind that the Pi is going to need to be on your local network. I’m assuming for the purposes here that you’ll be using a network cable and do not plan to cover getting wireless networking up and running on the Pi. The course was not specifically about the Pi, per se. For a deeper dive into its capabilities, you should check out Jon Flanders course, “Raspberry Pi for Developers.

Now for the X10 equipment. The first thing that you’re going to order is a part that is a wireless transceiver as well as an interface to a computer. To do this, it makes use of a USB cord. The reason I’ve chosen this particular unit is because there is a readily available driver for it and also because the Pi only has a USB connection and not the serial connection that other X10 computer interfaces use. I should note here that we will not, for the purposes of the course, be going the historical X10 route and sending signals over the home electrical. Here, everything will be wireless RF. And this particular part is going to receive signals that you send it from the Pi and transmit them to the other part that I’m about to cover.

The other X10 component that you’re going to need is a regular transceiver module, which, strangely, is around the same price as the computer interface transceiver. You are going to plug a lamp into this transceiver and it is going to receive the signals from the CM19A and turn its lamp on and off accordingly.

If you have none of these parts, the entire setup should cost you around $100. If that seems a bit steep to automate turning a single lamp on and off, take some comfort in the fact that most of this is a one time entry fee, so to speak, for home automation. From here forward, you can simply buy a single module for $20 or even less to automate additional lights or appliances.

Over the coming months, I will have additional posts going through more of the script from the course and talking about home automation. But if you want to get started quickly and have a Pluralsight subscription, the course will be a much faster route to go. And, again, if you don’t have a subscription but want to check out the course, then email me and I’ll send you a 7 day trial so that you can check out my course and any others you want. Happy automating!

By

TDD Chess Game Part 9: God Save the Queen

As always, it seems that I’ve let too much time elapse between iterations of this series. This time my excuse was worse than ever. I actually had this video ready to go last Friday or something and then the post was was queued up on Sunday, but I was too tired when I got home on Sunday night to remember to go publish it. Anyway, it’s live now.

Here’s what I accomplish in this clip:

  • Implement Queen with GetMovesFrom()
  • Add more common functionality to Piece base class.

Here are some lessons to take away:

  • For the most part, in the last number of clips things had gone more or less as I expected.  Here you got to see the value of the test suite indicating to me that I was reasoning about the code incorrectly.  I didn’t realize that the GetRadial methods were returning only moves N spaces away rather than up to and including N spaces.  It took some floundering to figure this out and, without red tests telling me things were going haywire, I probably would have plowed ahead for minutes or hours before I realized things weren’t working.
  • Pulling up functionality into a common base class is a way to avoid duplication and make tests go green rapidly, but beware of creating a base class abstraction that’s awkward just to reuse code.  If it seems awkward, it might be worth creating a class that your ancestors use.  So far, the functionality in Piece seems to make sense, but I’ll keep an eye on this.
  • Use Intellisense in a savvy way.  When you notice a few times that what you’re expecting to happen isn’t happening, that’s a yellow (if not red) flag.  Late in the video, this kept happening to me, and it turned out to be because I had spelled “radial” as “raidal” when defining a method.  Typos, incorrect assumptions, etc — often these things can be revealed by the IDE not behaving as expected.
  • Definitely keep track of refactorings you’d like to do in you list.  Treat these as if they were no different than features you want implemented.