Skip to content

Instantly share code, notes, and snippets.

@andy-uq
Last active September 29, 2015 23:27
Show Gist options
  • Save andy-uq/1685351 to your computer and use it in GitHub Desktop.
Save andy-uq/1685351 to your computer and use it in GitHub Desktop.
Creates GUID combs
using System;
namespace Terabyte.Data
{
/// <summary>Guid utilities</summary>
public static class GuidHelper
{
/// <summary>Given a string returns a Guid. </summary>
/// <remarks> Returns <c>Guid.Empty</c> if s is null.</remarks>
/// <param name="s">Any parsable guid, or the return value from <see cref="GuidToString"/></param>
/// <returns>A Guid you ninny!</returns>
/// <exception cref="ArgumentException">Thrown if s cannot be converted to a guid.</exception>
public static Guid StringToGuid(string s)
{
if (string.IsNullOrEmpty(s))
throw new ArgumentException(string.Format("Could not create Guid from empty or null string", s), "s");
try
{
if (s.Length == 22)
{
s = s.Replace('!', '/').Replace('*', '/').Replace('_', '/').Replace("-", "+") + "==";
return new Guid(Convert.FromBase64String(s));
}
return new Guid(s);
}
catch(FormatException)
{
throw new ArgumentException(string.Format("Could not create Guid from string '{0}'", s), "s");
}
}
/// <summary>
/// Returns a compressed string representation of a guid, which can be
/// extracted again by calling <see cref="GuidHelper.StringToGuid(string)"/>
/// </summary>
/// <remarks>
/// Implementation:
/// <code>return Convert.ToBase64String(g.ToByteArray()).Substring(0, 22).Replace('/', '*');</code>
/// </remarks>
/// <param name="g"></param>
/// <returns></returns>
public static string GuidToString(Guid g)
{
return Convert.ToBase64String(g.ToByteArray()).Substring(0, 22).Replace('/', '_').Replace("+", "-");
}
/// <summary>Creates a database friendly guid (http://www.informit.com/articles/article.aspx?p=25862)</summary>
/// <returns></returns>
public static Guid NewDatabaseGuid()
{
long dateTicks = DateTime.Now.Ticks;
return GenerateSequenceGuid(dateTicks, 0);
}
public static Guid GenerateSequenceGuid(long sequenceNumber, byte guidVersion)
{
Guid baseGuid = Guid.NewGuid();
byte[] guidData = baseGuid.ToByteArray();
guidData[15] = (byte )((sequenceNumber >> 0) & 0xFF);
guidData[14] = (byte )((sequenceNumber >> 8) & 0xFF);
guidData[13] = (byte )((sequenceNumber >> 16) & 0xFF);
guidData[12] = (byte )((sequenceNumber >> 24) & 0xFF);
guidData[11] = (byte )((sequenceNumber >> 32) & 0xFF);
guidData[10] = (byte )((sequenceNumber >> 48) & 0xFF);
guidData[8] = (byte )((guidData[8] & ~(0x3)) + guidVersion);
return new Guid(guidData);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment