I am a self-taught developer with knowledge of Azure, C, C++, C#, Typescript/JavaScript, HTML and CSS along with several databases. Having been working in IT for over 30 years and co-founding and selling a successful company I am now working on products for the TV industry.Follow me on twitter @coderanger, Mastodon @coderanger/@dotnet.social and GitHub

ASP.NET MVC Routing Issues

Here is an oddity when creating an ASP.NET MVC/WebApi; you can’t have a route which contains certain words like “con” or “nul”.

This is annoying when trying to create a REST based search API as, for example, if you wanted to search for an actor name as someone typed you would get a 404 error as soon as you typed “con” for someone like “connie”.

There is a solution to this, just add the relaxedUrlToFileSystemMapping attribute to your web.config ‘system.web’ httpRuntime section:

<system.web>
	<httpRuntime targetFramework="4.5" relaxedUrlToFileSystemMapping="true"/>
</system.web>

References: http://bitquabit.com/post/zombie-operating-systems-and-aspnet-mvc/

Separating a Subfolder into its own Git Repo

The Easy Way

It turns out that this is such a common and useful practice that the overlords of git made it really easy, but you have to have a newer version of git (>= 1.7.11 May 2012).

  1. Prepare the old repo

    pushd <big-repo>
    git subtree split -P <name-of-folder> -b <name-of-new-branch>
    popd

    Note: <name-of-folder> must NOT contain leading or trailing characters. For instance, the folder named subproject MUST be passed as subproject, NOT ./subproject/

    Note for windows users: when your folder depth is > 1, <name-of-folder> must have *nix style folder separator (/). For instance, the folder named path4\\path5\\subproject MUST be passed as path4/path5/subproject

  2. Create the new repo

    mkdir <new-repo>
    pushd <new-repo>
    
    
    git init
    git pull </path/to/big-repo> <name-of-new-branch>
    
  3. Link the new repo to Github or wherever

    git remote add origin <[email protected]:my-user/new-repo.git>
    git push origin -u master
  4. Cleanup, if desired

    popd # get out of <new-repo>
    pushd <big-repo>
    
    
    git rm -rf <name-of-folder>

    Note: This leaves all the historical references in the repository.See the Appendix below if you’re actually concerned about having committed a password or you need to decreasing the file size of your .git folder.

Clearing your history

By default removing files from git doesn’t actually remove them from git, it just commits that they aren’t there anymore. If you want to actually remove the historical references (i.e. you have a committed a password), you need to do this:

git filter-branch --tree-filter 'rm -rf <name-of-folder>' HEAD

After that you can check that your file or folder no longer shows up in the git history at all

git log -S<name-of-folder> # should show nothing

However, you can’t “push” deletes to github and the like. If you try you’ll get an error and you’ll have to git pull before you can git push - and then you’re back to having everything in your history.

So if you want to delete history from the “origin” - meaning to delete it from github, bitbucket, etc - you’ll need to delete the repo and re-push a pruned copy of the repo. But wait - there’s more! - If you’re really concerned about getting rid of a password or something like that you’ll need to prune the backup (see below).

Making .git smaller

The aforementioned delete history command still leaves behind a bunch of backup files - because git is all too kind in helping you to not ruin your repo by accident. It will eventually deleted orphaned files over the days and months, but it leaves them there for a while in case you realize that you accidentally deleted something you didn’t want to.

So if you really want to empty the trash to reduce the clone size of a repo immediately you have to do all of this really weird stuff:

rm -rf .git/refs/original/ && \\
git reflog expire --all && \\
git gc --aggressive --prune=now

git reflog expire --all --expire-unreachable=0
git repack -A -d
git prune

That said, I’d recommend not performing these steps unless you know that you need to - just in case you did prune the wrong subdirectory, y'know? The backup files shouldn’t get cloned when you push the repo, they’ll just be in your local copy.

Credit

Merging Two Git Commits

Quite often I make a commit to Git and then realise I missed a change and have to make another commit; they both solve the same issue so I just want to merge them to tidy it up.

Here is an easy way, assuming you want to merge or squash, in Git palance, the last two commits:

# Reset the current branch to the commit just before the last 2:
git reset --hard HEAD~2

# HEAD@{1} is where the branch was just before the previous command.
# This command sets the state of the index to be as it would just
# after a merge from that commit:
git merge --squash HEAD@{1}

# Commit those squashed changes.  The commit message will be helpfully
# prepopulated with the commit messages of all the squashed commits:
git commit  

I found this from one of the answers (not the accepted answer) on Stackoverflow

Useful JavaScript String Format

Quite often I need to create a formatted string with padded numbers or other replacement text so to reproduce a useful function like that which is available in C or C++ (and other languages) I decided to create a simple method on the String class to recreate the following function signature:

var message = String.format('Hello %s, the time is %02d:%02d!', name, hour, minute );

Options:

%s    : replace with a string
%5s   : replace with a string padded with spaces to 5 characters in length

%d    : replace with an integer, throws if not a number
%03d  : replace with an integer padded with zeroes to 3 significant figures
%4d   : replace with integer padded with spaces to4 significant figures

%x    : replace with an integer converted to hex, throws if not a number
%X    : replace with an integer converted to upper case hex, throws if not a number
%03x   : replace with an integer converted to hex padded with zeroes to 3 characters in length
%4x  : replace with an integer converted to hex padded with spaces to 4 characters in length

Here is the code, as you can see it uses a useful array method “reduce” which calls the callback function on each element of the array to produce our results:

String.format = function() {  
  var formatArguments = [].slice.call( arguments );
  var formatDefinition = formatArguments.shift();

  function replacer( text, replacement ) {
    var pad = function(value, size, padValue) {
        var s = value+"";
        while (s.length < size) s = padValue + s;
        return s;
      };

    var type = new RegExp( "%([0-9]*)(d|x|X|s)" );
    var matches = type.exec( text );
    console.log ( matches );

    var replacementValue = replacement;
    if( matches && matches.length >= 1 )
    {
      if( matches[2] === "s" )
      {
        replacementValue = pad( replacement, matches[1], " " );
      }
      else if( matches.length > 2 && (matches[2] === "d" || matches[2].toLowerCase() === "x") )
      {
        if( typeof(replacement) !== "number" )
          throw new Error( "Parameter " + formatArguments.length + " '" + replacement + "' is not a number" );

        replacementValue = matches[2] === "x" ? replacement.toString(16) : (matches[2] === "X" ? replacement.toString(16).toUpperCase() : replacement);
        replacementValue = pad( replacementValue, matches[1], matches[1].length > 0 && matches[1][0] === "0" ? "0" : " " );
      }
      text = text.replace(matches[0], replacementValue );
    }

    return text.replace( /%%/, "%" );
  }

  return formatArguments.reduce( replacer, formatDefinition );
};


// Some testing
var name = 'Dan';  
var date = new Date();  
var hour = date.getHours();  
var minute = date.getMinutes();

var message = String.format("Hello '%5s', the time is %s:%s - is %d:%012d - a hex value %x or upper hex %06X as a percentage %d%% as %% are escaped", name, hour, minute, hour, minute, 95, 95, 23 );

console.log(message);

Would result in the following output:

Hello '  Dan', the time is 11:48 - is 11:000000000048 - a hex value 5f or upper hex 00005F as a percentage 23% as % are escaped

Inserting Items into a JavaScript Array

Due to the nature of arrays, inserting an item into an existing array is not a standard method, by you can fake it if you know you have an array which would benefit.

The native method we can use is:

Array.splice( position, numberOfItemsToRemove, item);

So we can now extend the native Array prototype in JavaScript with something more descriptive:

Array.prototype.insertAt = function ( index, item ) {  
  this.splice( index, 0, item );
};

Automate Microsoft Excel using JavaScript

For a project I needed to do, I required a simple JavaScript object where I could automate some Excel functionality, so I created one.

Here it is if anyone else finds it useful…

/*
  Usage:
    var excel = new Excel( "d:\\testfile.xlsx" );

    excel.openFile();

    // Find a named worksheet, delete the first row then save it out as text
    var sheetNum = excel.findWorkSheetNumber( "Sheet 2" );
    if( sheetNum != -1 )
    {
      var ws = excel.getWorkSheet( sheetNum );

      // Delete a row range
      var range = ws.Range( "A1", "AZ2" );
      var row = range.EntireRow;
      row.Delete();

      // Now save this worksheet as unicode text
      var savedTextFile = excel.saveWorkSheet( sheetNum );
    }

    excel.quit();
*/


var Excel = function ( filePath )  
{
  var _filePath = filePath;

  var _fso = new ActiveXObject( "scripting.filesystemobject" );

  var _excel = new ActiveXObject( "Excel.Application" );
  var _wookbooks, _workbook;

  var _xlTextWindows = 20;
  var _xlUnicodeText = 42;
  var _XlSaveAsAccessModexlNoChange = 1;
  var _xlDoNotSaveChanges = 2;

  return {
    openFile: function ()
    {
      _excel.Visible = true;

      _wookbooks = _excel.Workbooks;

      _workbook = _wookbooks.Open( _filePath );
    },

    findWorkSheetNumber: function ( sheetName )
    {
      var sheets = _workbook.Worksheets;

      var total = sheets.Count;
      for ( var u = 1; u <= total ; u++ )
      {
        var ws = sheets.Item( u );

        ws.Activate();

        var worksheetName = ws.Name;
        if ( worksheetName.toLowerCase() == sheetName.toLowerCase() )
          return u;
      }

      // Not found
      return -1;
    },

    getWorkSheet: function ( sheetNum )
    {
      var sheets = _workbook.Worksheets;

      var ws = sheets.Item( sheetNum );
      ws.Activate();

      return ws;
    },

    trimColumnData: function( str )
    {
      str = str.trim();
      if ( str.length > 0 && str.charAt( 0 ) == "\\"" && str.charAt( str.length - 1 ) == "\\"" )
      {
        str = str.substring( 1, str.length - 1 ).trim();
      }

      return str;
    },

    saveWorkSheet: function ( sheetNum )
    {
      var sheets = _workbook.Worksheets;

      var ws = sheets.Item( sheetNum );
      ws.Activate();

      var worksheetName = ws.Name;

      var saveName = _filePath + "-" + sheetNum + "-(" + worksheetName + ").txt";
      saveName = saveName.replace( /\\?/g, "" );

      // Delete old file
      if ( _fso.fileExists( saveName ) )
      {
        _fso.DeleteFile( saveName );
      }

      _workbook.SaveAs( saveName, _xlUnicodeText, "", "", false, false, _XlSaveAsAccessModexlNoChange );

      return saveName;
    },

    saveAllWorkSheets: function ()
    {
      var sheets = _workbook.Worksheets;

      var total = sheets.Count;
      var sheets = [];
      for ( var u = 1; u <= total; u++ )
      {
        sheets.push( saveWorkSheet( u ) );
      }
      return sheets;
    },

    quit: function ()
    {
      _workbook.Close( false );

      _excel.Quit();
    }
  }
}

Detecting Retina Screens Server-Side

To improve the speed of loading the site I work on at http://digiguide.tv, I would prefer to load retina images into the HTML code from the beginning instead of altering them after the fact using JavaScript. Unfortunately I cannot use CSS media queries as the images are dynamic and determined by the server code.

So what to do? it appears there is no user-agent information for pixel density or device model which seems to be a major oversight and wouldn’t have taken much to just add. So we are stuck with the only two options mentioned above.

A possible solution is to use JavaScript to set a cookie (session or permanent) on very first page load and use this on subsequent page loads, and if you need the first page to use retina images perhaps do a redirect if the cookie doesn’t exist.

So we are left with this bit of code client-side:

 
var isRetina = readCookie( "isretina" );  
if( !isRetina ) {  
  var modern_media_query = window.matchMedia( "screen and (-webkit-min-device-pixel-ratio:2)");     
  if( modern_media_query.matches ) {
    // set our cookie
    var expires = new Date().toUTCString();
    document.cookie = "isretina=true; "+ expires +"; path=/";

    // optionally reload page...
  }
}

function readCookie(name) {  
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

And on the server we can just check for the ‘isretina’ cookie value to determine which images to use.

URI API Do’s and Dont’s

I read this on a Stackoverflow answer and liked its summary, so am posting it more for my own archiving purposes (answer by: Bob Aman)

General principles for good URI design:

  • Don’t use query parameters to alter state
  • Don’t use mixed-case paths if you can help it; lowercase is best
  • Don’t use implementation-specific extensions in your URIs (.php, .py, .pl, etc.)
  • Don’t fall into RPC with your URIs
  • Do limit your URI space as much as possible
  • Do keep path segments short
  • Do prefer either /resource or /resource/; create 301 redirects from the one you don’t use
  • Do use query parameters for sub-selection of a resource; i.e. pagination, search queries
  • Do move stuff out of the URI that should be in an HTTP header or a body

(Note: I did not say “RESTful URI design”; URIs are essentially opaque in REST.)

General principles for HTTP method choice:

  • Don’t ever use GET to alter state; this is a great way to have the Googlebot ruin your day
  • Don’t use PUT unless you are updating an entire resource
  • Don’t use PUT unless you can also legitimately do a GET on the same URI
  • Don’t use POST to retrieve information that is long-lived or that might be reasonable to cache
  • Don’t perform an operation that is not idempotent with PUT
  • Do use GET for as much as possible
  • Do use POST in preference to PUT when in doubt
  • Do use POST whenever you have to do something that feels RPC-like
  • Do use PUT for classes of resources that are larger or hierarchical
  • Do use DELETE in preference to POST to remove resources
  • Do use GET for things like calculations, unless your input is large, in which case use POST

General principles of web service design with HTTP:

  • Don’t put metadata in the body of a response that should be in a header
  • Don’t put metadata in a separate resource unless including it would create significant overhead
  • Do use the appropriate status code:
    • 201 Created after creating a resource; resource must exist at the time the response is sent
    • 202 Accepted after performing an operation successfully or creating a resource asynchronously
    • 400 Bad Request when someone does an operation on data that’s clearly bogus; for your application this could be a validation error; generally reserve 500 for uncaught exceptions
    • 401 Unauthorized when someone accesses your API either without supplying a necessary Authorization header or when the credentials within the Authorization are invalid; don’t use this response code if you aren’t expecting credentials via an Authorization header
    • 403 Forbidden when someone accesses your API in a way that might be malicious or if they aren’t authorized
    • 405 Method Not Allowed when someone uses POST when they should have used PUT, etc
    • 413 Request Entity Too Large when someone attempts to send you an unacceptably large file
    • 418 I'm a teapot when attempting to brew coffee with a teapot
  • Do use caching headers whenever you can:
    • ETag headers are good when you can easily reduce a resource to a hash value
    • Last-Modified should indicate to you that keeping around a timestamp of when resources are updated is a good idea
    • Cache-Control and Expires should be given sensible values

  • Do everything you can to honor caching headers in a request (If-None-Modified, If-Modified-Since)
  • Do use redirects when they make sense, but these should be rare for a web service

Useful JavaScript Date Methods

I needed an easy way to add or subtract months from a JavaScript date and have it do it correctly for situations like the end of the month where the new month has different days, but also for it to roll backward/forward to a different year when necessary.

Here is a simple solution which extends the built-in Date class:

Date.prototype.addMonths = function( months )  
{
    var monthsTotal = this.getMonth() + this.getYear() * 12 + months;
    var day = this.getDate();
    var year = monthsTotal / 12;
    var month = monthsTotal % 12;

    var maxDays = this.getDaysInMonth( year, month );
    if( day > maxDays )
    {
        day = maxDays;
        OutputLog( "day: " + day );
    }

    this.setYear( year );
    this.setDate( day );
    this.setMonth( month );
}

Date.prototype.getDaysInMonth = function( year, month )  
{
    var days = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

    //
    //  Check for leap year
    if( month == 1 && year % 4 == 0 && ( year % 100 || year % 400 == 0 ) )
    {
        return 29;
    }

    return days[ month ];
}

You would use these new methods as follows:

var test = new Date( 2011, 2, 30, 06, 10, 11 );  
test.addMonths( -1 );  
alert( test);

test = new Date( 2011, 1, 30, 06, 10, 11 );  
test.addMonths( 12 );  
alert( test );

And here is an additional useful method to provide a way of returning the month name:

Date.prototype.getMonthName = function()  
{
    var names = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];

    return names[ this.getMonth() ];
}

Learning C#

I thought I would finally take the plunge and start reading that mammoth book on C# and .net 3.5 that I bought ages ago.

Phew, there is a lot to go over but I have found a few things that sound great and a few things that really concern me.

  • Good: No more worrying about Unicode and 64 bit. From what I have read its all Unicode under the hood and the runtime chooses 64 or 32 bit depending on the OS so you dont have to worry about it.
  • Bad: No optional parameters on method calls. WHAT, I was soooo shocked that this wasnt available, are we back to VB days … it appears so. However I have read that .net 4 does have support for optional parameters but what worries me is that I had presumed that this sort of basic thing was a given, so what else am I presuming?
  • Bad: ByRef/ByValue confusion. Now this is something I am totally confused about, it feels like VB where some things are passed by reference and others by value; unless you have read the documentation and thoroughly understand and remember things then you just won’t know. But then you are totally screwed if you have ValueTypes and ReferenceTypes embedded within each other, you just cannot presume any sort of basic understanding of what might happen without a full understanding of any objects you are using. For example, a struct is a ValueType and is passed by value unless you explicitly use the ref keyword, whereas a class is a ReferenceType and is allocated on the heap and is always by reference
  • Bad: No implicit stack/heap allocation. Things are done automatically for you so you do not have to worry; but what if you want to do things like allocate a number on the heap, well tough thats just too advanced for your little brain, sorry! This is where I have the biggest problem; with C/C++ you just always knew what was gonna happen, everything was on the stack and went out of scope unless you allocated it on the heap with new; now in C# new doesn’t do anything but call the default constructor on the object and any embedded objects (huh), why bother with that, why not do that by default and do away with new altogether … I am clearly misunderstanding something here
  • Good: I like the way you can define the type of an enum, whether its a Byte or an Int32 (by default), this is useful for serialisation; I also like the way you can find out the ‘string’ representation of any type value.
  • Good: I like the way you can use int and it will always be an Int32 on all OS’s and languages that support .net; long will always be an Int64 where the OS supports it (e.g. not on embedded devices)

I will carry on reading and learning and see what other things are thrown up … hopefully I will be corrected on the above as I find out more.