Categories
NETCF

Need a GUID in a hurry?

There may be times in your application you need to generate a new unique Guid. The System.Guid class in .NETCF v1.0 doesn’t have the NewGuid method which is what you would normally use on the desktop. There are a couple of proposed alternatives, either generating one yourself by following the standards for Guids – using a few P/Invokes to Crypto API methods to get random numbers, using the GuidEx class which uses the same technique or indirectly using SqlCe to create a new identity value.


An easier way in many cases is to use one of the COM subsystem API methods as this involves only a single P/Invoke call. The only caveat to this is that not all CE based systems have full COM support – there are three varieties Minimal COM, Full COM and DCOM support. Minimal COM doesn’t support Guid generation. However in my brief experimentation with Platform Builder it would appear that among .NETCF’s prerequisites is COM support so this should in theory be supported by any CE device on which .NETCF is supported. It is certainly supported on all Windows Mobile devices:-


namespace InTheHand


{


      ///


      /// Helper class for generating a globally unique identifier (GUID).


      ///


      /// <SEEALSO cref='“System.Guid”/>


      public sealed class ComGuid


      {


            private ComGuid(){}


 


            ///


            /// Initializes a new instance of the <SEE cref='“System.Guid”/> class.


            ///


            /// A new <SEE cref='“System.Guid”/> object


            public static Guid NewGuid()


            {


                  Guid val = Guid.Empty;


 


                  int hresult = 0;


 


                  hresult = CoCreateGuid(ref val);


 


                  if(hresult != 0)


                  {


                        throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), “Error creating new Guid”);


                  }


 


                  return val;


            }


 


            [DllImport(“ole32.dll”, SetLastError=true)]


            private static extern int CoCreateGuid(ref Guid pguid );


      }


}


 

By Peter Foot

Microsoft Windows Development MVP