In Revit API, we have to deal with GUIDs sometimes such as the ClientId nodes of manifest files and Revit addin ids.
Obviously we can use the Create GUID tool provided by Visual Studio to create a GUID and copy it over in our code or into the manifest files, but it is not flexible enough. We have to remove the braces most of times, and we also need to generate GUID strings and/or check their validations on the fly sometimes.
To create a new GUID on the fly is pretty straightforward, using the static NewGuid() method of the Guid type of the .NET Framework like so:
string guidString = Guid.NewGuid().ToString();
How to verify a GUID then such as “6F65D2C6-6288-4695-92C3-83C608D3F5B6”?
If we’d like to create one GUID validation method of really our own, it is surely possible.
But is it simple enough?
Not really if we have to cover every detail all appropriately. The length is obviously the first thing; those hyphens goes likely next including both counts and positions; the last but the most important step is to check those characters to see if they are all valid hexadecimal digits (no such things like M, N, X, Y, $, #, etc.).
So, looking simple requests often prove to be hard to be met. Simplest hardest like picking up the moon in water!
In this particular case though, there exists a good, easy, and reliable solution, using the constructor of the Guid type:
try
{
Guid guid = new Guid("6F65D2C6-6288-4695-92C3-83C608D3F5B6");
}
catch(Exception ex)
{
// It isn’t a valid GUID string, so we’d better do something.
MessageBox.Show(ex.Message);
}
try
{
Guid guid = new Guid("6F65D2C6-6288-4695-92C3-83C608D3F5BG");
}
catch (Exception ex)
{
// It isn’t a valid GUID string, so we’d better do something.
MessageBox.Show(ex.Message);
}
try
{
Guid guid = new Guid("6F65D2C6-6288-4695-92C3-83C608D3F5B$");
}
catch (Exception ex)
{
// It isn’t a valid GUID string, so we’d better do something.
MessageBox.Show(ex.Message);
}
try
{
Guid guid = new Guid("6F65D2C6-6288-4695-92C3-83C608D3F5B");
}
catch (Exception ex)
{
// It isn’t a valid GUID string, so we’d better do something.
MessageBox.Show(ex.Message);
}
As expected, only the first case would pass the validation, and all the other three throw out an exception saying ‘Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).’ as shown by the following screenshot:
RevitAddinWizard applies this nice small and native technique in its various wizards, coders, and widgets for Revit API programming such as ClientId generation and validation.
Recent Comments