Converting to Base64 in Powershell

There are a variety of ways to send a file to Web end-point and encode it in the the process. For example, using Invoke-RestMethod -InFile (docs):

C:\PS> Invoke-RestMethod -Uri `
  -Method Post -ContentType 'multipart/form-data' `
  -InFile c:\temp\test.txt

However, if we want/need to include one or more files as part of a larger JSON payload, perhaps with other information for each file, we will need to convert the file(s) to Base64.

To do so, we’ll make use of .Net functionality, in particular the System.Convert.ToBase64String method and the System.Web.Script.Serialization.JavaScriptSerializer class (see note).

# define parameters
    [Parameter(Mandatory=$true, Position=0)]

$content = [System.IO.File]::ReadAllBytes($InputFile)
$base64String = [System.Convert]::ToBase64String($content)

# Load System.Web.Extensions
Add-Type -AssemblyName System.Web.Extensions
$jsonSerializer = New-Object System.Web.Script.Serialization.JavaScriptSerializer
$json = $jsonSerializer.Serialize(@{ content = $base64String })

Write-Output -InputObject $json

# writes: {"content":"dGVzdAOK"}

For a full, proper script, with multiple parameters (writing to a file, copying to clipboard) see this ConvertTo-Base64.ps1 gist.

Note: I chose System.Web.Extensions over the more common Json.Net because I didn’t want to have to download/nuget a dependency; JavaScriptSerializer proves sufficient for this task.

Versioning Assemblies with Cake and Git


  1. Given an application, I want to be able to trace its binaries back to the source code “version” it was built from;
  2. As such, I want this identification ability to be automatically employed during the build process;
  3. I want to have easy ways of retrieving this information, as well as the version of code it was built from;
  4. All files built at the same time have the same version;
  5. I use git for VCS and Cake for build scripts;
  6. I don’t want trivial commits, such as those containing only the identifying information.

Proposed solution

  • Employ a way of versioning (duh) that is tied to individual files;
    Satisfies requirement 1;
  • Include the git branch information;
  • Include the commit id (SHA1) of the HEAD as a way of identifying the exact state of the code;
    Satisfies requirements 2 and 5;
  • Only built from committed code (no uncommitted files);
    Satisfies requirements 2, 3, and 4;
  • If files are modified for versioning purposes, roll back the changes at the end of the build, even if the build had errors;
    Satisfies requirement 6.

Technical Details

As far as the versioning goes, there are several version numbers associated with a .Net assembly:

  • Assembly version, important to the .Net loader - set with AssemblyVersion attribute: usually in Properties/AssemblyInfo.cs.
    Must be in format, all numbers, or the compiler throw a CS7034 error:

    error CS7034: The specified version string does not conform to the required format - major[.minor[.build[.revision]]]

  • File version, a property of the file itself and inspect-able in the Details section of the file properties dialog is set using the AssemblyFileVersion attribute.
    There’s a warning, but not an error (unless we have \<TreatErrorsAsWarnings>true\</TreatErrorsAsWarnings>, which we should), if we don’t follow the same format as the assembly version:

    warning CS7035: The specified version string does not conform to the recommended format -

  • Product version is another property of visible in the file properties dialog, is set using the AssemblyInformationalVersion attribute, and is the most permissible of the three as it literally accepts any string, although we should set it to something reasonable and meaningful to whomever inspects it. Product Version with Emoji

This Stack Overflow answer, and the ones that follow, provides really good descriptions of each attribute, its limitations, and intended use.

Because we want to include the branch name and the commit id (SHA1), the AssemblyInformationalVersion is the only we can use.

We propose the following format: Major.minor.branch-sha1.

The assembly version can be dynamically versioned by MSBuild using the format [assembly: AssemblyVersion("1.0.*")] as a way of providing supplemental information about the date and time of build - see the Remarks section of the AssemblyVersion docs.


We’ll make use of the Cake.Git add-in and Cake’s ability to generate the assembly information using CreateAssemblyInfo method.

To simplify matters, we’ll split AssemblyInformationalVersion attribute from the Properties/AssemblyInfo.cs file into its own Properties/AssemblyInfoVersion.cs. Its content is unimportant, but we’ll start with a value of:

[assembly: System.Reflection.AssemblyInformationalVersion("")]

Next we’ll create a Task("Version") in our build.cake file that creates the AssemblyInfoVersion.cs file, we’ll make the Build task depend upon it, and we’ll revert the changes at the end of the build process.

#addin nuget:?package=Cake.Git

var configuration = Argument("configuration", "Debug");
var thisRepo = MakeAbsolute(Directory("./"));
var assemblyInfo = File("./TestAssemblyVersioning/Properties/AssemblyInfoVersion.cs");

    .Does(() => 
    var branch = GitBranchCurrent(thisRepo);

    // The following is not the best approach
    // We should use LibGit2Sharp's ObjectDatabase.ShortenObjectId(),
    // but Cake.Git doesn't currently support it.
    var sha = branch.Tip.Sha.Substring(0, 8);

    // TODO: branch.FriendlyName produces a name too long when using gitflow,
    // e.g. "1.0.12fa582d-feature/MYPROJ-2732-title_of_story_or_defect".
    // There should be an attempt to extract maybe the issue identifier
    // so that we end with something like "1.0.12fa582d-MYPROJ-2732"
    // or "1.0.12fa582d-f-title_of_story"
    CreateAssemblyInfo(assemblyInfo, new AssemblyInfoSettings {
        InformationalVersion = string.Format("1.0.{0}-{1}", branch.FriendlyName, sha)

    .Does(() =>
      MSBuild(sln, settings => settings.SetConfiguration(configuration));
      XBuild(sln, settings => settings.SetConfiguration(configuration));
.Finally(() =>
    // restore assembly.cs files
    GitCheckout(thisRepo, new FilePath[] { assemblyInfo });

That’s it. Now every time we build the project using our build script, the product version will reflect it accordingly:

Product Version with Git Info

Note 1: if we had multiple assemblies, like normal projects do, we would have a single AssemblyInfoVersion.cs, likely in the root of the project, and we would link that file into each project to ensure they all get the same product version:

<Compile Include="..\AssemblyInfoVersion.cs">

Note 2: it seems reasonable that we should maybe perform a check to see if all changes have been committed before the build, otherwise the build would incorporate the changes on disk while still picking up the HEAD SHA1.

Touch Command in PowerShell

The two simplest use cases for the touch command are to:

  1. Create one or more files, if they don’t exist;
  2. Update the access date or modification date of files without changing their content.

To replicate these two cases in PowerShell, we make use of the LastWriteTime property of a FileSystemInfo object, as well as creating an empty file if one does not exist at the specified path.

You can add the following code to the Microsoft.PowerShell_profile.ps1 file in your <Users>\Documents\WindowsPowerShell\ folder:

You can now call it with either: Update-File file1.txt file2.txt or touch file1.txt file2.txt.

Couple of Points Worth Making

We name the function Update-File following the PowerShell pattern or verb-noun pair for commands and the Data Verbs section of Approved Verbs for Windows PowerShell Commands.

We set pass the -Encoding ascii to the Out-File command as the default encoding for Out-File is UTF-16 and some *nix transplant tools have troubles handling UTF-16 files because of the two byte-markers at the beginning of the file (for example webpack when bundling files).

Finally, credit goes to this answer on StackExchange’s superuser.

See Unread Emails in iOS Mail App

I don’t aim for Inbox Zero, but I aim to read all the emails I receive, however, with default setting the iOS Mail app does not make it easy.

For a while, it seemed that the only way to find unread emails and get that red badge to disappear was to scroll through the inboxes and try to find the emails with a blue dot to their left.

Turns out there’s a better way and that indeed the iOS Mail app has a folder aka smart mailbox which tracks all unread emails across all your accounts.

To enable this mailbox:

  1. In the Mailboxes screen (the one with all the folders), tap the Edit button up in the top-right corner;
  2. The screen switches to edit mode, displaying a list of current (visible) and available mailboxes. From this list select the Unread mailbox; I also like to drag it all the way up to the top.
  3. Tap the Done button and you’re done!

Here’s a visual that shows these steps:

Steps to enable smart mailbox

The configuration does not sync across devices, so if you also have an iPad, you’ll need to repeat these steps on those other devices.

PUT and DELETE with HTML Forms in ExpressJS

In trying to send data from an HTML form to an ExpressJS backend I soon discovered two things:

  1. FORM elements only support GET and POST, not PUT, nor DELETE;
  2. ExpressJS does not have a built-in way to address this but fortunately there’s a middleware plugin, method-override, that does.

method-override’s documentation is great and very much on point, except for the FORM post override section, which I found a bit confusing on my first read (although in honesty, now it seems much clear).

As a result, and for my own clarification, I decided to put together as small example that showcases all the ways method-override can be used from within HTML pages.

General approach

Middleware in ExpressJS typically takes place early in the processing pipeline and as such method-override will attempt to identify a specific token in the received data, per configuration, and will, well, override the method aka HTTP verb used.

There are two main approaches we can use to trigger the app.put() and app.delete() route handlers from HTML code:

  1. Using AJAX
  2. Using the form’s method="POST" with a specific token.

Using AJAX

Almost all current versions of browsers support specifying an HTTP method.

// client code
var xhr = new XMLHttpRequest();'PUT', '/resource', true);

// ---
// server code
app.put('/resource', function(req, res) {
    console.log('PUT to /resource');

If you only work with modern browsers, there’s nothing more required.

However, if your front-end needs to be backward compatible with older versions that don’t support HTTP methods (enterprise software developers, I feel you), then method-override can be configured to look for a token in the headers being posted and override the method being used.

// server code
var methodOverride = require('method-override');
app.put('/resource', ...

As such, the client code needs to specify the intended method in a header:

// client code
var xhr = new XMLHttpRequest();'POST', '/resource', true); // method-override needs it to be POST
xhr.setRequestHeader('X-HTTP-Method-Override', 'PUT');

POST-ing with specific token

If instead of AJAX, we intend to use the HTML’s FORM element to PUT or DELETE, method-override can be configured to look for a specific token either in the query string, or, with a tiny bit more code, in the data being submitted.

Specific Token in Query String

In this example we will have the form POST to /resource?_method=PUT and will configure method-override to look for _method in the query string and override the HTTP method with the indicated verb.

// server code
app.put('/resource', ...

On the client side, we’ll POST to the above URL:

// client code
<form method="POST" action="/resource?_method=PUT">

Note: by default method-override only examines POST requests.

You can configure it to look at GET requests:

// server code
app.use(methodOverride('_method', { methods: ['POST', 'GET'] });

but this is a really bad idea for two reasons:

  1. GET-ing /resource?_method=DELETE is downright dangerous as anything unintentionally (or worse, intentionally) crawling your URLs will cause deletion of resources; this could be something as trivial as a browser pre-fetching links in order to speed up pages, or a browser extension investigating URLs for any number of reasons (phishing protection, status checking, statistics, etc).
  2. GET-ing /resource?_method=PUT with a payload makes no sense from an HTTP standard perspective. Payloads are for POST and PUT.

So just don’t.

Specific Token in Form data

The second method involved sending the token with the POST body. The most common approach is to include a hidden field.

<form method="POST" action="/log" enctype="application/x-www-form-urlencoded">
  <input type="hidden" name="_method" value="PUT">
  <button type="submit">Submit</button>

The server-side code is a little bit more involved this time as it requires another library: body-parser, which you’re likely to use anyway if you deal with form data or just HTTP body data in general.

body-parser inteprets the incoming HTTP request body and makes it available as key-value pairs in the body property of the request, req, parameter.

method-override allows one to specify a custom function to be called during the middleware execution. In this custom function we will inspect the request body, req.body, for the presence of the desired token, _method in this case, and return its value to the middleware that will in turn override the request method.

// server code
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(methodOverride(function (req, res) {
  if (req.body && typeof req.body === 'object' && '_method' in req.body) {
    // look in urlencoded POST bodies and delete it
    var method = req.body._method;
    delete req.body._method;
    return method;


As a final note, it’s worth mentioning that you can have multiple method-overrides in your middleware code, thus allowing the handling of all the scenarios presented above.

Except for the GET+DELETE scenario. You should never do that.

// server code
var express = require('express');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');

var app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(methodOverride(function (req, res) {
  if (req.body && typeof req.body === 'object' && '_method' in req.body) {
    var method = req.body._method;
    delete req.body._method;
    return method;

app.get('/resource', ...)
   .get('/resource/:id', ...)
   .post('/resource', ...)
   .put('/resource/:id', ...)
   .delete('/resource/:id', ...);

If you want to see all the examples above in action, clone my method-override-example repo and simply run npm start then navigate to http://localhost:3000/ to play with each of these scenarios.