Skip to content

Instantly share code, notes, and snippets.

@MarkRobertJohnson
Created January 13, 2018 23:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MarkRobertJohnson/cfacd0bdcede9e08ffff3761cf5ec766 to your computer and use it in GitHub Desktop.
Save MarkRobertJohnson/cfacd0bdcede9e08ffff3761cf5ec766 to your computer and use it in GitHub Desktop.
Get sequential GUIDs without using Windows DLL.
$c = @"
using System;
public class SequentialGuid {
Guid _CurrentGuid;
public Guid CurrentGuid {
get {
return _CurrentGuid;
}
}
public SequentialGuid() {
_CurrentGuid = Guid.NewGuid();
}
public SequentialGuid(Guid previousGuid) {
_CurrentGuid = previousGuid;
}
public SequentialGuid Next(SequentialGuid sequentialGuid) {
return NextGuid(sequentialGuid);
}
private static SequentialGuid NextGuid(SequentialGuid sequentialGuid) {
byte[] bytes = sequentialGuid._CurrentGuid.ToByteArray();
for (int mapIndex = 0; mapIndex < 16; mapIndex++) {
int bytesIndex = SqlOrderMap[mapIndex];
bytes[bytesIndex]++;
if (bytes[bytesIndex] != 0) {
break; // No need to increment more significant bytes
}
}
sequentialGuid._CurrentGuid = new Guid(bytes);
return sequentialGuid;
}
public static SequentialGuid operator++(SequentialGuid sequentialGuid) {
return NextGuid(sequentialGuid);
}
private static int[] _SqlOrderMap = null;
private static int[] SqlOrderMap {
get {
if (_SqlOrderMap == null) {
_SqlOrderMap = new int[16] {
3, 2, 1, 0, 5, 4, 7, 6, 9, 8, 15, 14, 13, 12, 11, 10
};
// 3 - the least significant byte in Guid ByteArray [for SQL Server ORDER BY clause]
// 10 - the most significant byte in Guid ByteArray [for SQL Server ORDERY BY clause]
}
return _SqlOrderMap;
}
}
}
"@
Add-Type -TypeDefinition $c -Language CSharp
$sg = New-Object SequentialGuid
$sg.CurrentGuid
$sg.Next($sg.CurrentGuid)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment