Created
April 15, 2018 21:04
-
-
Save tompazourek/264e865c742c941420b39ebd9082f8cc to your computer and use it in GitHub Desktop.
guids
This file contains 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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Runtime.InteropServices; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace Guids | |
{ | |
public static class SequentialGuid | |
{ | |
[DllImport("rpcrt4.dll", SetLastError = true)] | |
private static extern int UuidCreateSequential(out Guid guid); | |
public static Guid NewGuid() | |
{ | |
Guid newGuid; | |
int returnVal = UuidCreateSequential(out newGuid); | |
if (returnVal != 0) | |
throw new Exception("UuidCreateSequential failed with exit code " + returnVal); | |
return newGuid; | |
} | |
public static Guid NewSqlServerFormattedGuid() | |
{ | |
byte[] bytes = NewGuid().ToByteArray(); | |
CopyBigEndianBytes(BitConverter.ToInt32(bytes, 0), 4, bytes, 0); | |
CopyBigEndianBytes(BitConverter.ToInt16(bytes, 4), 2, bytes, 4); | |
CopyBigEndianBytes(BitConverter.ToInt16(bytes, 6), 2, bytes, 6); | |
return new Guid(bytes); | |
} | |
// Tak til Jon Skeet http://www.yoda.arachsys.com/csharp/miscutil | |
private static void CopyBigEndianBytes(long value, int bytes, byte[] buffer, int index) | |
{ | |
int endOffset = index + bytes - 1; | |
for (int i = 0; i < bytes; i++) | |
{ | |
buffer[endOffset - i] = unchecked((byte) (value & 0xff)); | |
value = value >> 8; | |
} | |
} | |
} | |
} |
This file contains 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
using System.Diagnostics; | |
using System.Threading.Tasks; | |
using System.Text; | |
using System.Collections.Generic; | |
using System; | |
using System.Linq; | |
namespace Guids | |
{ | |
public class TimeGuid | |
{ | |
public static Guid NewTimeGuid() | |
{ | |
var resultBytes = new byte[16]; | |
byte[] guidBytes = Guid.NewGuid().ToByteArray(); | |
long time = DateTime.UtcNow.Ticks; | |
Debug.WriteLine(time); | |
byte[] timeBytes = BitConverter.GetBytes(time); | |
byte[] timeBytesReversed = timeBytes.Reverse().ToArray(); | |
// the last 6 bytes are most significant, and to be sorted properly, the time bytes need to be reversed | |
Buffer.BlockCopy(guidBytes, 0, resultBytes, 0, 10); // first 10 bytes are from GUID | |
Buffer.BlockCopy(timeBytesReversed, 0, resultBytes, 10, 6); // last 6 bytes are from time | |
var result = new Guid(resultBytes); | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment