A little syntactic sugar to have reference semantics for value types

In C#, structs and other data primitives have value semantics. (This includes strings, even though they are technically reference types.) But sometimes it’s useful to have reference semantics when dealing with what would otherwise be a value type. (Referencing primitives in a singleton object, for example.)

Here are two ways of doing that.

Delegates

Delegate syntax can seem a little weird–particularly when you’re working with primitives–because they’re basically typed function pointers. They look more like methods than variables.

Here’s an example:

class Program
{
    static void Main(string[] args)
    {
        var i = SomeInteger.SomeNumber;     //Value type won't change when SomeNumber changes
        Console.WriteLine(i);               //100
        Func<int> del = () => SomeInteger.SomeNumber;
        Console.WriteLine(del());           //100 (Same as del.Invoke())
 
        SomeInteger.SomeNumber = 42;
        Console.WriteLine(i);               //Still 100
        Console.WriteLine(del());           //42
    }
}
 
static class SomeInteger
{
    public static int SomeNumber = 100;
}

Wrapper class using generics

My preferred way is by combining a wrapper class with C# generics. It has nicer syntax, but does require a little more setup. The results are a little clearer, in my opinion.

Here’s an example:

class Program
{
    static void Main(string[] args)
    {
        //Assume SomeInteger.SomeNumber is 100 again
        var foo = new Reference<int>(() => SomeInteger.SomeNumber);
        Console.WriteLine("foo.Value: {0}", foo.Value);     //100
 
        SomeInteger.SomeNumber = 42;
        Console.WriteLine("foo.Value: {0}", foo.Value);     //42
    }
}
 
class Reference<T>
{
    private readonly Func<T> _theValue;
    public T Value
    {
        get
        {
            //If the value is null, return the default initialization of type T
            return _theValue != null ? _theValue.Invoke() : default(T);
        }
    }
 
    public Reference(Func<T> theValue)
    {
        _theValue = theValue;
    }
}

And there we have type-safe, reference semantics for primitives in C#. (Works for nullable types, too.)

Publisher confirms with RabbitMQ and C#

RabbitMQ lets you handle messages that didn’t send successfully, without resorting to full-on transactions. It provides this capability in the form of publisher confirms. Using publisher confirms requires just a couple of extra lines of C#.

If you’re publishing messages, you probably have a method that contains something like this:

using (var connection = FACTORY.CreateConnection())
{
    var channel = connection.CreateModel();
    channel.ExchangeDeclare(QUEUE_NAME, ExchangeType.Fanout, true);
    channel.QueueDeclare(QUEUE_NAME, true, false, false, null);
    channel.QueueBind(QUEUE_NAME, QUEUE_NAME, String.Empty, new Dictionary<string, object>());
 
    for (var i = 0; i < numberOfMessages; i++)
    {
        var message = String.Format("{0}\thello world", i);
        var payload = Encoding.Unicode.GetBytes(message);
        channel.BasicPublish(QUEUE_NAME, String.Empty, null, payload);
    }
}

 

But you’re out of luck if you want:

  1. A guarantee that your message was safely preserved in the event that the broker goes down (i.e. written to disk)
  2. Acknowledgement from the broker that your message was received, and written to disk

For many use cases, you want these guarantees. Fortunately, getting them is relatively straightforward:

//Set the message to persist in the event of a broker shutdown
var messageProperties = channel.CreateBasicProperties();
messageProperties.SetPersistent(true);

 

//Send an acknowledgement that the message was persisted to disk
channel.BasicAcks += channel_BasicAcks;
channel.ConfirmSelect();
 
//...
 
//Begin loop
channel.BasicPublish(QUEUE_NAME, QUEUE_NAME, messageProperties, payload);
channel.WaitForConfirmsOrDie();
//End loop

 

(You’ll have to implement event handlers for acks and nacks.)

The difference between WaitForConfirms and WaitForConfirmsOrDie is not immediately obvious, but after digging through the Javadocs, it seems that WaitForConfirmsOrDie will give you an IOException if a message is nack‘d, whereas WaitForConfirms won’t.

You’ll get an IllegalStateException if you try to use either variation of WaitForConfirms without first setting the Confirms property with ConfirmSelect.

Here’s the complete code for getting an acknowledgement from the RabbitMQ broker, only after the broker has persisted the message to disk:

using (var connection = FACTORY.CreateConnection())
{
    var channel = connection.CreateModel();
    channel.ExchangeDeclare(QUEUE_NAME, ExchangeType.Fanout, true);
    channel.QueueDeclare(QUEUE_NAME, true, false, false, null);
    channel.QueueBind(QUEUE_NAME, QUEUE_NAME, String.Empty, new Dictionary<string, object>());
    channel.BasicAcks += channel_BasicAcks;
    channel.ConfirmSelect();
 
    for (var i = 1; i <= numberOfMessages; i++)
    {
        var messageProperties = channel.CreateBasicProperties();
        messageProperties.SetPersistent(true);
 
        var message = String.Format("{0}\thello world", i);
        var payload = Encoding.Unicode.GetBytes(message);
        Console.WriteLine("Sending message: " + message);
        channel.BasicPublish(QUEUE_NAME, QUEUE_NAME, messageProperties, payload);
        channel.WaitForConfirmsOrDie();
    }
}

Mediawiki “vendor branch” for Mercurial users

I created a “vendor branch” of the MediaWiki stable releases for Mercurial users. (Git is, after all, pretty terrible by comparison.) Commit history goes from 1.21.2 back to 1.19.7.

You’ll do something like this to update:

$ cd your/personal/mediawiki/branch
$ hg pull -u
$ hg pull https://bitbucket.org/rianjs/mediawiki-vendor
$ hg merge tip
$ hg commit
$ hg push

Then deploy however you deploy. Check Special:Version to see that it’s updated.

How to install pip on Windows

This is a distillation of the instructions at The Hitchhiker’s Guide to Python, mostly for my own future benefit when I inevitably forget how to do it:

  1. Install Python, if you haven’t already
  2. Install distribute by running the distribute_setup.py script:
    1. wget http://python-distribute.org/distribute_setup.py
    2. python distribute_setup.py
  3. Use easy_install to install PIP. PIP is actively maintained, and supports package removal (unlike easy_install)
    1. easy_install pip

This took a grand total of about 60 seconds to complete.

Gmail: Find unlabeled mail, and filter by attachment size

If you’ve wanted to filter by attachment size, or find unlabeled emails… you’re now in luck. Gmail has added some search operators recently.

My favorite is the ability to filter by attachment size:

  • size:2m searches for attachments of 2MB
  • larger:3m searches for attachments of 3MB and larger
  • smaller:5m searches for attachments smaller than 5MB

You can combine these searches with the other Gmail search operators:

  • larger:3m older_than:2y
  • larger:5m from:email@example.com

Need to find unlabeled messages?

has:nouserlabels will show you stuff you haven’t labeled.

3 minute tip: Configure a Linux server to send email

It’s useful to be able to send email from a Linux webserver. I do it to get MediaWiki page change notifications and other automated status updates. I wanted something that supported two-factor authentication, and this does.

This guide is for you, if:

  • You don’t want to run a mail server
  • You want to send email, and you don’t care about receiving it
  • You want people to receive the emails that your server sends

I’ve used this method with Linode, and it works perfectly.

Install mailutils

~ sudo apt-get install mailutils

When the setup wizard launches, choose the unconfigured option. You don’t need to do any special configuration to get this to work.

Install and configure sstmp

  1. ~ sudo apt-get install ssmtp
  2. ~ sudo vim /etc/ssmtp/ssmtp.conf
  3. Hit “i” to enter Insert mode.
  4. Uncomment FromLineOverride=YES by deleting the #
  5. Add the following to the file:

     
    AuthUser=<user>@gmail.com
    AuthPass=Your-Gmail-Password
    mailhub=smtp.gmail.com:587
    UseSTARTTLS=YES

  6. Save and close the file:
    1. Hit Escape
    2. Type :wq
    3. Hit Enter

If you’re using two-factor authentication
Create a new application-specific password to use in the config file above. (If you’re using Gmail, you can manage those passwords here.)

Test it out
~ echo "This is a test" | mail -s "Test" <user>@<email>.com

Using a webmail service other than Gmail
You can follow the same pattern that I used above. You’ll need to:

  1. Subsitute the SMTP address and port for your email service (e.g. Yahoo!) where it says smtp.gmail.com:587. (587 is the port number.)
  2. Set up an application-specific password if your webmail provider allows it, and paste that into the password line, the way I did with Gmail. (Yahoo! appears to have something similar.)

An experiment in finishing stuff

One area I’ve struggled with consistently as far back as I can remember has been finishing things. I’ve always been good at having good ideas, and–just as often–not carrying them out. IOW, really good at the R part of R&D, not so great at the D. This is something I’ve resolved to change about myself, and tomorrow (Friday) marks the end of four weeks of a focus on finishing things. Some stuff was important, a lot of it wasn’t. At work, I tried to finish the highest-value tasks, or things I’d promised others, and at home, I tried to finish the most important things, and the things that brought me happiness or satisifaction.

  • Finished two books, on my way to finishing a third
  • Finished 3 different long-term projects that I’d had on my back burner for months
  • Started and finished some high-value policy guidance, from development through socialization
  • A bunch of housekeeping on my Linode backend (more than six months overdue!)
  • My SO and I restructured our finances to better plan for the future
  • Got numerous things with external gating factors back on track

Anyway, this hasn’t been a month where I’ve worked harder. It’s been a month where I’ve worked smarter. I’ve never been an adherent of any particular productivity school, but I do borrow from several (GTD, kanban). Here are a couple of things I did:

  • Didn’t even try to start new things if I could avoid it; I simply added them and added them to my backlog
  • Eliminated some low-value stuff entirely (why do low-value stuff at all?)
  • Carved out calendar time in my day for next steps, immediately after completing pre-requisites. (This ensures adequate time, and a regular delivery cadence.)
  • I’ve always been an inbox zero kind of guy. That didn’t change, and it remained a producitivity (and happiness) multiplier.

It’s not all sunshine and daisies, however. Balancing the reactive, “operational” side of my job with the planful, inside-your-own-head development stuff that provides the real, long-term organizational value remains a challenge.

Here’s a good talk by Adam Savage–of Mythbusters fame–that really resonated with me. I feel like I’m good at (and regularly do) all the stuff, except for maybe the last three minutes. That I saw this video while working on finishing stuff was purely coincidental.

Sonder

The Dictionary of Obscure Sorrows:

n. the realization that each random passerby is living a life as vivid and complex as your own—populated with their own ambitions, friends, routines, worries and inherited craziness—an epic story that continues invisibly around you like an anthill sprawling deep underground, with elaborate passageways to thousands of other lives that you’ll never know existed, in which you might appear only once, as an extra sipping coffee in the background, as a blur of traffic passing on the highway, as a lighted window at dusk.

How to determine how large a mortgage you can afford using Excel

Note: this is applicable to fixed rate mortgages.

Mortgage brokers typically use your gross monthly income to calculate the amount they’re willing to lend you. Frankly, this is a very bad way of calculating what you can actually afford. It is more useful to know what you can reasonably afford each month before you go house shopping.

If you’ve got a monthly payment in mind that you’re comfortable making, you can use a present value calculation to come up with the amount you can afford to finance. In Excel, this is very easy with the pv function:

=pv(interest rate, number of payments, payment, montly payment)

  • Interest rate: If annual percentage rate (APR) is 3.5%, this number will be 3.5%/12 = (0.035/12).
  • Number of payments: 12 months * 30 years = 360
  • Payment: What you’re comfortable paying on a mortgage each month.

Suppose:

  • You’re willing to spend $1,750 a month on a house
  • APR: 3.5%
  • Term: 30 years

=pv((0.035/12), 360, 1750)

You can afford to finance: $389,716.22

When determining what you can afford each month, don’t forget the following:

  • House insurance
  • Mortgage insurance (PMI)
  • House taxes, typically calculated as some amount per thousand dollars of assessed house value
  • Homeowners’ fees, if applicable

These are things that many renters don’t need to pay, and thus forget to think about when buying their first home.