A small library for converting Guids to Short Guids in .NET
Converts Guids by first converting to base64. Then it replaces '+' and '/' characters in order to create a URL friendly string.
ShGuid
Guid and it's base64 encoded counterpart
ShGuidSettings
Used to set up custom replacement parameters and trim options
The following code will initialize a ShGuid object. Any '/' chars will be replaced by 'i', and any '+' chars will be replaced by '0'. We will trim the last two characters of the ShGuid as it will always be "=="
var guid = "470bf5c0-c746-4f87-b98b-d3e968eabf49";
var settings = new ShGuidSettings('i', '0', true);
var shGuid = new ShGuid(guid, settings);
Console.WriteLine(shGuid.Guid); // output: 470bf5c0-c746-4f87-b98b-d3e968eabf49
Console.WriteLine(shGuid.ShortGuid); // output: wPULR0bHh005i9PpaOqiSQ
ShGuid.NewShGuid();
var stringifiedGuid = "0058c2d5-806d-465c-8560-313db6c054c0";
ShGuid shGuid;
if(ShGuid.TryParse(stringifiedGuid, out shGuid))
{
Console.WriteLine(shGuid.Guid); // output: 0058c2d5-806d-465c-8560-313db6c054c0
Console.WriteLine(shGuid.ShortGuid); // output: 1cJYAG2AXEaFYDE9tsBUwA
}
var shortGuid = "1cJYAG2AXEaFYDE9tsBUwA";
var shGuid = ShGuid.Decode(shortGuid);
Console.WriteLine(shGuid.Guid); // output: 0058c2d5-806d-465c-8560-313db6c054c0
Console.WriteLine(shGuid.ShortGuid); // output: 1cJYAG2AXEaFYDE9tsBUwA
This project was inspired by thinking about how to convert a database entry with a Guid primary key id into a more url friendly manner without altering db schema. It was based off code found at Dave Transom's blog.
However, if I could alter the table structure, I would add an unique identifier
column with a randomly generated string using a package like hashids.net. Or I could use integer primary keys. Or even the value generated by hashids.net as the primary key. You get the point.