Created
January 13, 2018 23:18
-
-
Save MarkRobertJohnson/cfacd0bdcede9e08ffff3761cf5ec766 to your computer and use it in GitHub Desktop.
Get sequential GUIDs without using Windows DLL.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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