Saturday, June 30, 2012

Generating sequential GUID

It is all over the place and there are many ways to do it. This small post is for my quick reference.

is the Remote Procedure Call (RPC) API, used by Windows applications for network and Internet communication. This is an essential system process and should not be deleted.

UuidCreateSequential function
For security reasons, UuidCreate was modified so that it no longer uses a machine's MAC address to generate UUIDs. UuidCreateSequentialwas introduced to allow creation of UUIDs using the MAC address of a machine's Ethernet card.

The UuidCreateSequential function returns RPC_S_UUID_LOCAL_ONLY when the originating computer does not have an ethernet/token ring (IEEE 802.x) address. In this case, the generated UUID is a valid identifier, and is guaranteed to be unique among all UUIDs generated on the computer. However, the possibility exists that another computer without an ethernet/token ring address generated the identical UUID. Therefore you should never use this UUID to identify an object that is not strictly local to your computer. Computers with ethernet/token ring addresses generate UUIDs that are guaranteed to be globally unique.

Note:  The UuidCreateSequential function tends to be slightly faster than the UuidCreate function. When the performance of the generation of a UUID is a significant consideration, the UuidCreateSequential function may be used.


using System.Runtime.InteropServices;

Initializing objects at class level
[DllImport("rpcrt4.dll", SetLastError = true)]
private static extern int UuidCreateSequential(out Guid value);

private enum RetUuidCodes : int
    RPC_S_OK = 0, //The call succeeded.
    RPC_S_UUID_LOCAL_ONLY = 1824, //The UUID is guaranteed to be unique to this computer only.
    RPC_S_UUID_NO_ADDRESS = 1739 //Cannot get Ethernet or token-ring hardware address for this computer.

Function to create sequencial Guid
public Guid CreateGuid()
   Guid guid;
   int result = UuidCreateSequential(out guid);
   if (result == (int)RetUuidCodes.RPC_S_OK)
      return guid;
      return Guid.NewGuid();

In functions generate sequencial Guid using following
Guid uid = CreateGuid();