im in ur web, enriching ur code

 
 

ShortGuid - A shorter and url friendly GUID class in C#

I like Mads Kristensen, he's often coming up with useful code snippets which he shares with the community AND he heads up the BlogEngine.NET project. He's produced the GuidEncoder helper class, which takes a standard guid like this:

c9a646d3-9c61-4cb7-bfcd-ee2522c8f633

And shortens it to a smaller string like this:

00amyWGct0y_ze4lIsj2Mw

Which is a huge help if you happen to be using guids in your URL's. You can read his article, A shorter and URL friendly GUID, on his website.

I've gone one step further than Mads, and created a struct which encapsulates the GuidEncoder functionality. I've called mine the "ShortGuid", but you could equally call it a "Sguid" if you like how that sounds (and if you pronounce GUID like "squid" and not "goo-id"). Mads's code for en/decoding the guid is still in there as static methods, which you can see further down - I'm pretty sure it hasn't been changed.

I'll jump right into the usage, if you're interested in the code, jump to the bottom and download the source.

Using the ShortGuid

The ShortGuid is compatible with normal Guid's and other ShortGuid strings. Let's see an example:

Guid guid = Guid.NewGuid();

ShortGuid sguid1 = guid; // implicitly cast the guid as a shortguid

Console.WriteLine( sguid1 );

Console.WriteLine( sguid1.Guid );

This produces a new guid, uses that guid to create a ShortGuid, and displays the two equivalent values in the console. Results would be something along the lines of:

FEx1sZbSD0ugmgMAF_RGHw
b1754c14-d296-4b0f-a09a-030017f4461f

Or you can implicitly cast a string to a ShortGuid as well.

string code = "Xy0MVKupFES9NpmZ9TiHcw";

ShortGuid sguid2 = code; // implicitly cast the string as a shortguid

Console.WriteLine( sguid2 );

Console.WriteLine( sguid2.Guid );

Which produces the following:

Xy0MVKupFES9NpmZ9TiHcw
540c2d5f-a9ab-4414-bd36-9999f5388773

Flexible with your other data types

The ShortGuid is made to be easily used with the different types, so you can simplify your code. Take note of the following examples:

// for a new ShortGuid, just like Guid.NewGuid()

ShortGuid sguid = ShortGuid.NewGuid();

 

// to cast the string "myString" as a ShortGuid,

string myString = "Xy0MVKupFES9NpmZ9TiHcw";

 

// the following 3 lines are equivilent

ShortGuid sguid = new ShortGuid( myString ); // traditional

ShortGuid sguid = (ShortGuid)myString; // explicit cast

ShortGuid sguid = myString; // implicit cast

 

// Likewise, to cast the Guid "myGuid" as a ShortGuid

Guid myGuid = new Guid( "540c2d5f-a9ab-4414-bd36-9999f5388773" );

 

// the following 3 lines are equivilent

ShortGuid sguid = new ShortGuid( myGuid ); // traditional

ShortGuid sguid = (ShortGuid)myGuid; // explicit cast

ShortGuid sguid = myGuid; // implicit cast

After you've created your ShortGuid's the 3 members of most interest are the original Guid value, the new short string (the short encoded guid string), and the ToString() method, which also returns the short encoded guid string.

sguid.Guid; // gets the Guid part

sguid.Value; // gets the encoded Guid as a string

sguid.ToString(); // same as sguid.Value

Easy comparison with guid's and strings

You can also do equals comparison against the three types, Guid, string and ShortGuid like in the following example:

Guid myGuid = new Guid( "540c2d5f-a9ab-4414-bd36-9999f5388773" );

ShortGuid sguid = (ShortGuid)"Xy0MVKupFES9NpmZ9TiHcw";

 

if( sguid == myGuid )

  // logic if guid and sguid are equal

 

if( sguid == "Xy0MVKupFES9NpmZ9TiHcw" )

  // logic if string and sguid are equal

ShortGuid Source Code

Following is the full listing in C#, or you can download the source code for the ShortGuid struct.

using System;

 

namespace CSharpVitamins

{

  /// <summary>

  /// Represents a globally unique identifier (GUID) with a

  /// shorter string value. Sguid

  /// </summary>

  public struct ShortGuid

  {

    #region Static

 

    /// <summary>

    /// A read-only instance of the ShortGuid class whose value

    /// is guaranteed to be all zeroes.

    /// </summary>

    public static readonly ShortGuid Empty = new ShortGuid(Guid.Empty);

 

    #endregion

 

    #region Fields

 

    Guid _guid;

    string _value;

 

    #endregion

 

    #region Contructors

 

    /// <summary>

    /// Creates a ShortGuid from a base64 encoded string

    /// </summary>

    /// <param name="value">The encoded guid as a

    /// base64 string</param>

    public ShortGuid(string value)

    {

      _value = value;

      _guid = Decode(value);

    }

 

    /// <summary>

    /// Creates a ShortGuid from a Guid

    /// </summary>

    /// <param name="guid">The Guid to encode</param>

    public ShortGuid(Guid guid)

    {

      _value = Encode(guid);

      _guid = guid;

    }

 

    #endregion

 

    #region Properties

 

    /// <summary>

    /// Gets/sets the underlying Guid

    /// </summary>

    public Guid Guid

    {

      get { return _guid; }

      set

      {

        if (value != _guid)

        {

          _guid = value;

          _value = Encode(value);

        }

      }

    }

 

    /// <summary>

    /// Gets/sets the underlying base64 encoded string

    /// </summary>

    public string Value

    {

      get { return _value; }

      set

      {

        if (value != _value)

        {

          _value = value;

          _guid = Decode(value);

        }

      }

    }

 

    #endregion

 

    #region ToString

 

    /// <summary>

    /// Returns the base64 encoded guid as a string

    /// </summary>

    /// <returns></returns>

    public override string ToString()

    {

      return _value;

    }

 

    #endregion

 

    #region Equals

 

    /// <summary>

    /// Returns a value indicating whether this instance and a

    /// specified Object represent the same type and value.

    /// </summary>

    /// <param name="obj">The object to compare</param>

    /// <returns></returns>

    public override bool Equals(object obj)

    {

      if (obj is ShortGuid)

        return _guid.Equals(((ShortGuid)obj)._guid);

      if (obj is Guid)

        return _guid.Equals((Guid)obj);

      if (obj is string)

        return _guid.Equals(((ShortGuid)obj)._guid);

      return false;

    }

 

    #endregion

 

    #region GetHashCode

 

    /// <summary>

    /// Returns the HashCode for underlying Guid.

    /// </summary>

    /// <returns></returns>

    public override int GetHashCode()

    {

      return _guid.GetHashCode();

    }

 

    #endregion

 

    #region NewGuid

 

    /// <summary>

    /// Initialises a new instance of the ShortGuid class

    /// </summary>

    /// <returns></returns>

    public static ShortGuid NewGuid()

    {

      return new ShortGuid(Guid.NewGuid());

    }

 

    #endregion

 

    #region Encode

 

    /// <summary>

    /// Creates a new instance of a Guid using the string value,

    /// then returns the base64 encoded version of the Guid.

    /// </summary>

    /// <param name="value">An actual Guid string (i.e. not a ShortGuid)</param>

    /// <returns></returns>

    public static string Encode(string value)

    {

      Guid guid = new Guid(value);

      return Encode(guid);

    }

 

    /// <summary>

    /// Encodes the given Guid as a base64 string that is 22

    /// characters long.

    /// </summary>

    /// <param name="guid">The Guid to encode</param>

    /// <returns></returns>

    public static string Encode(Guid guid)

    {

      string encoded = Convert.ToBase64String(guid.ToByteArray());

      encoded = encoded

        .Replace("/", "_")

        .Replace("+", "-");

      return encoded.Substring(0, 22);

    }

 

    #endregion

 

    #region Decode

 

    /// <summary>

    /// Decodes the given base64 string

    /// </summary>

    /// <param name="value">The base64 encoded string of a Guid</param>

    /// <returns>A new Guid</returns>

    public static Guid Decode(string value)

    {

      value = value

        .Replace("_", "/")

        .Replace("-", "+");

      byte[] buffer = Convert.FromBase64String(value + "==");

      return new Guid(buffer);

    }

 

    #endregion

 

    #region Operators

 

    /// <summary>

    /// Determines if both ShortGuids have the same underlying

    /// Guid value.

    /// </summary>

    /// <param name="x"></param>

    /// <param name="y"></param>

    /// <returns></returns>

    public static bool operator ==(ShortGuid x, ShortGuid y)

    {

      if ((object)x == null) return (object)y == null;

      return x._guid == y._guid;

    }

 

    /// <summary>

    /// Determines if both ShortGuids do not have the

    /// same underlying Guid value.

    /// </summary>

    /// <param name="x"></param>

    /// <param name="y"></param>

    /// <returns></returns>

    public static bool operator !=(ShortGuid x, ShortGuid y)

    {

      return !(x == y);

    }

 

    /// <summary>

    /// Implicitly converts the ShortGuid to it's string equivilent

    /// </summary>

    /// <param name="shortGuid"></param>

    /// <returns></returns>

    public static implicit operator string(ShortGuid shortGuid)

    {

      return shortGuid._value;

    }

 

    /// <summary>

    /// Implicitly converts the ShortGuid to it's Guid equivilent

    /// </summary>

    /// <param name="shortGuid"></param>

    /// <returns></returns>

    public static implicit operator Guid(ShortGuid shortGuid)

    {

      return shortGuid._guid;

    }

 

    /// <summary>

    /// Implicitly converts the string to a ShortGuid

    /// </summary>

    /// <param name="shortGuid"></param>

    /// <returns></returns>

    public static implicit operator ShortGuid(string shortGuid)

    {

      return new ShortGuid(shortGuid);

    }

 

    /// <summary>

    /// Implicitly converts the Guid to a ShortGuid

    /// </summary>

    /// <param name="guid"></param>

    /// <returns></returns>

    public static implicit operator ShortGuid(Guid guid)

    {

      return new ShortGuid(guid);

    }

 

    #endregion

  }

}

 

kick it on DotNetKicks.com

Posted on Thursday, December 20, 2007 5:15 PM
Filed Under [ C#, Tips, .NET, Source Code ]

Comments

Gravatar
# Short Guids
Posted by Ross Hawkins
Posted on 2/7/2008 1:50 PM
Short Guids
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted on 2/7/2008 11:04 PM
Excellent work. Thanks for sharing.
Gravatar
# Shrinking Guids to fit on urls
Posted on 2/8/2008 9:53 AM
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by teedyay
Posted on 2/9/2008 12:46 AM
Man! I'm not sure if it's flattering or frustrating when an idea I implemented a while ago gets dotNetKicked when someone else publishes it!

(Not that I'm saying you copied me - clearly great minds do think alike!)

Mine was virtually identical:

public static string PackGuid(Guid guid)
{
// This produces a 22-character string representation of a GUID. It contains
// only alphanumerics, - and _. These characters aren't affected by URL encoding,
// which makes them a tad easier to pass around in query strings and suchlike.

// The Base64 encoded version of the GUID always ends in two equals signs,
// so removing them loses no uniqueness.
return Convert.ToBase64String(guid.ToByteArray()).Replace('+', '_').Replace('/', '-').Replace("=", "");
}
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Dave Transom
Posted on 2/10/2008 10:12 PM
It's not only about the en/decode methods (even though that is the still key piece), but the wrapping class with the _convenience_ of operator overloads.

If it were just the en/decode, I would have left it in Mads' capable hands :)

But I would have to say it's a little frustrating and flattering both.
Gravatar
# Interesting Finds: 2008.02.14
Posted by gOODiDEA
Posted on 3/4/2008 2:46 PM
Web:jQuery1.2CheatSheetFasterJavaScriptTrimSelf-curryingJavaScriptfunctionsFive...
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by argatxa
Posted on 4/22/2009 7:02 AM
Saved me... had to fit a guid on short field and I thought I was screwed...

Thanks for sharing!!
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by geza
Posted on 7/24/2009 2:38 AM
At MVC modelbinding it compares short guid with an empty string "" with the equals function.

Just one line improvement in equals part:

if (obj is string && !String.IsNullOrEmpty(obj.ToString()))
return _guid.Equals(((ShortGuid)obj)._guid);

Great thing actually!
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Alterin
Posted on 3/2/2010 2:23 AM
Thanks for sharing! :)
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by yoshi
Posted on 3/13/2010 7:14 AM
Good job! Nicely done
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Deep
Posted on 5/6/2010 9:21 PM
Please change the link of Mads Kristensen from "http://www.madskristensen.dk/" to "http://madskristensen.net/".
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Rain
Posted on 1/25/2011 11:27 PM
As others have said, thanks for sharing, you saved half an hour on a miserable morning! :)
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Adeel
Posted on 5/5/2011 7:54 PM
This is really useful, thanks!
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Kieran
Posted on 6/30/2011 6:33 AM
Thanks for sharing this, very useful.

If I could suggest a little refactoring on two properties just for a small efficency gain.

Setters for Guid and Value:

public Guid Guid
{
get { return _guid; }
set
{
// Code change
if (value == _guid) return;
_guid = value;
_value = Encode(value);
}
}


public string Value
{
get { return _value; }
set
{
// Code change
if (value == _value) return;
_value = value;
_guid = Decode(value);
}
}

Thanks again
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Dave Transom
Posted on 6/30/2011 10:36 AM
@Kieran: Appreciate the feedback - though I'm unsure why you'd think that provides a gain in efficiency. It's more of a change in coding style isn't it?


If you look at the IL generated between your version and mine, the only difference is "equality" verses "inequality".

IL for original version:
L_0008: call bool [mscorlib]System.Guid::op_Inequality(valuetype [mscorlib]System.Guid, valuetype [mscorlib]System.Guid)

IL for your version:
L_0008: call bool [mscorlib]System.Guid::op_Equality(valuetype [mscorlib]System.Guid, valuetype [mscorlib]System.Guid)


Even decompiling your method (using Reflector, ILSpy may give a different result) to C# it turns out like this:

if (!(value == this._guid))
{
this._guid = value;
this._value = Encode(value);
}

Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by paco
Posted on 9/8/2011 7:40 AM
Thank you! This is great stuff!
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Mike
Posted on 9/23/2011 2:01 AM
I don't see anywhere that you've specified a license for this work. Would you consider releasing it under the MIT license? Thanks.
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Dave Transom
Posted on 9/23/2011 10:21 AM
@Mike: Thanks, you raise an interesting point - I don't currently publish a licence under which snippets and work on this blog can be re-used.

I've intended it to be freely available, customisable and distributable.

I'll choose a license shortly, however, please feel free to use it as you will until I've specified a license.

HTH
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Mike
Posted on 9/24/2011 1:43 AM
@Dave,

Thanks. I'm in a highly regulated industry right now and the lawyers tend to bristle at code without an explicit license. I'll deal with them though.

Thanks again!
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Jon
Posted on 10/5/2011 2:44 AM
Thanks very much for this, it has come in very handy.

I added a TryParse method for my purposes:

public static bool TryParse(string input, out ShortGuid result)
{
try
{
result = new ShortGuid(input);
}
catch (Exception)
{
result = ShortGuid.Empty;
}
return (result != ShortGuid.Empty);
}

I'm being lazy and relying on an exception from the constructor so I'm sure there are better ways (also it would treat an empty ShortGuid as invalid) - but it works for me :)

Thanks again
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Matthew Abbott
Posted on 10/21/2011 9:27 PM
Nice piece of work. The only thing I would change on it, is to make the ShortGuid an immutable struct. That being, remove the setters for the properties.

Structs ideally represent values that don't change. It is easy enough to create a new instance of ShortGuid, you don't really need to change the value of it.
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Saeed Neamati
Posted on 11/29/2011 7:42 PM
If I were you, I would recommend my code to Microsoft, to include in future versions of .NET.

Once we wanted to create random coupons for our products, and we wished for such a utility to produce shorter random strings. But we couldn't find anything, and the .NET's Guid was inefficient (too long) in our case.

Great thought buddy. Thanks.
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Laurynas
Posted on 3/29/2012 10:16 PM
I would chage the property setters from:

if (value != _guid)
{
_guid = value;
_value = Encode(value);
}
if (value != _value)
{
_value = value;
_guid = Decode(value);
}

to:

if (value != _guid)
{
_value = Encode(value);
_guid = value;
}
if (value != _value)
{
_guid = Decode(value);
_value = value;
}

to avoid corrupting object state in case Encode or Decode would throw an exception.

Thanks for the code.
Gravatar
# in case you need just binder
Posted by ILICH
Posted on 4/13/2012 7:28 PM
in case you need just binder:

public class ShortGuidModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).AttemptedValue;
var isShort = value.Length == 22;
var shortGuidValue = isShort ? new ShortGuid(value) : new ShortGuid(Guid.Parse(value));

if (bindingContext.ModelType == typeof(ShortGuid))
return shortGuidValue.Value;

if (bindingContext.ModelType == typeof(Guid))
return shortGuidValue.Guid;

throw new AnelosophyException("can handle guids only");
}
}
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Spyros
Posted on 5/31/2012 2:09 AM
Will definitely use it . Thnx a lot for this clever lib!
Cheers from Greece
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Nicolas
Posted on 7/29/2012 3:30 AM
Unfortunately it won't work with lower case only URLs (often used to optimize SEO).
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Najeeb
Posted on 8/14/2012 11:22 PM
Hi Dave,

Thanks a lot for this! It's really helpful for something that I am working on currently. :)

/Najeeb/
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Boris
Posted on 8/29/2012 10:20 PM
Hi Dave,

Very good work.

Just a question about the short GUID comparisons. Is the string representation of the short GUID case insensitive (as it is for the normal GUID)?
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Dave Transom
Posted on 8/30/2012 1:47 PM
@Boris: It depends.

When comparing a ShortGuid to another ShortGuid, the underlying Guid is used to compared. So case doesn't matter.

When comparing a string or Guid to a ShortGuid, the string (or Guid) will be implicitly converted to a ShortGuid, then the underlying Guids will be compared as above.

If you've compare a string representation of a ShortGuid to something that is _not_ a ShortGuid, case will definitively matter.

HTH

Thanks everyone else for the kind words and contributions.
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Thiago Lemos
Posted on 11/19/2012 1:51 PM
Is possible to match this shortguid with a regex? I'm asking this because I want use ShortGuid in my URLs, but i need the regex to define the routes in my MVC project! original GUID has a pattern who give me a way to validate, thanks for share this code, this is very helpful
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Dave Transom
Posted on 11/19/2012 2:22 PM
@Thiago Lemos:

The problem is that is doesn't _look_ as well structured as a Guid with groups and separators
e.g. 00000000-0000-0000-0000-000000000000

It has the following consistency properties.
1. it's 22 characters long
2. the characters can be any of A-Z, a-z, 0-9, a dash (-) and an underscore (_)

So a regex should use the following pattern to match exactly.
new Regex(@"^[A-Za-z0-9-_]{22}$")

I haven't actually tried it in a routing environment as yet. Might have a look at see the best way to handle this.

Remember you can pass a string (or a Guid) to ShortGuid and it will implicitly convert it.
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Nikhil
Posted on 1/28/2013 1:30 PM
Hi,

Nice post. But I am looking for short unique string Maximum of 10 alpha numeric characters. the above post generate unique but length is more. Could you please suggest any post you have come across for the same?

Regards
Nikhil
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by tester
Posted on 3/21/2013 11:30 PM
How to convert to shortGUID without hyphen?
Gravatar
# Protected Media for Schools
Posted on 5/6/2013 2:35 PM
We use shorter keys for the URLs (we still want to have a GUID in the database) We use the code from
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Wobble
Posted on 5/15/2013 6:29 PM
Mads has changed his domain so the links on this article are wrong now.

Please change Mads Kristensen's links to :
http://madskristensen.net/post/A-shorter-and-URL-friendly-GUID.aspx
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted on 5/17/2013 11:13 PM
new links are not working either... i dont know if its me
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Nicholas Rogoff
Posted on 1/14/2014 1:09 PM
Great stuff. Been hacking my own, but this is much better than my efforts. Much appreciated.
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Anon
Posted on 3/29/2014 5:56 AM
Updated link to Mads Kristensen's post:

http://madskristensen.net/post/A-shorter-and-URL-friendly-GUID
Gravatar
# re: ShortGuid - A shorter and url friendly GUID class in C#
Posted by Rob de Voer
Posted on 5/14/2014 10:47 AM
Hi Dave,

Your code convinced me to switch my standard code for token generation to use ShortGuids.

Saved me time and it works well.

Thanks for sharing this!

Regards,
Rob

Post Comment

Title *
Name *
Email
Url
Comment *  
Please add 2 and 2 and type the answer here:

Recently on C# Vitamins...

Powered By Subtext

 

About C# Vitamins

Dave has been working in the industry for around 14 years, and has a focus on Javascript, C#, ASP.NET and SQL Server web development; not to mention being a standards driven type of guy.

C# Vitamins is the result of his findings while working in the web industry and a desire to share with the community; and if it was traced back far enough, you might say it might not have existed if he hadn't taken such an interest in id Software's original Quake.

Related Links

Below is a list of related links of Dave's other sites.