Generate ULIDs in VB.Net

Resources  |  Generate ULIDs in VB.Net

Generating a ULID (Universally Unique Lexicographically Sortable Identifier) in VB.NET requires a bit of manual implementation since there isn't a specific library like in other languages. ULID generation typically involves combining a timestamp and random component, and then encoding it in Base32. Here's a basic example of how you can generate ULIDs in VB.NET:

Example Code in VB.NET

Imports System
Imports System.Text

Module ULIDGenerator

    Private ReadOnly ULIDCharacters As String = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
    Private ReadOnly Random As New Random()

    Sub Main()
        ' Generate a new ULID
        Dim ulid As String = GenerateULID()
        Console.WriteLine(ulid) ' Output: e.g., 01ARZ3NDEKTSV4RRFFQ69G5FAV
    End Sub

    Function GenerateULID() As String
        ' Generate the timestamp part
        Dim timestamp As Long = (DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds
        Dim timestampChars As Char() = New Char(9) {}
        For i As Integer = 9 To 0 Step -1
            timestampChars(i) = ULIDCharacters(CInt(timestamp Mod 32))
            timestamp \= 32
        Next

        ' Generate the random part
        Dim randomChars As Char() = New Char(15) {}
        For i As Integer = 0 To 15
            randomChars(i) = ULIDCharacters(Random.Next(32))
        Next

        ' Combine timestamp and random parts
        Dim ulidBuilder As New StringBuilder()
        ulidBuilder.Append(timestampChars)
        ulidBuilder.Append(randomChars)

        Return ulidBuilder.ToString()
    End Function

End Module

Explanation

  1. Timestamp Generation:

    • The timestamp is generated as the number of milliseconds since the Unix epoch (January 1, 1970, UTC). It is converted into a Base32 string using the ULIDCharacters array.
  2. Random Part Generation:

    • The random part consists of 16 characters randomly chosen from the ULIDCharacters array.
  3. Combining Parts:

    • The timestamp and random parts are concatenated to form the ULID string.
  4. Output:

    • The generated ULID is printed to the console.

Notes

  • This example provides a basic implementation of ULID generation in VB.NET.
  • Ensure to handle concurrency and uniqueness requirements based on your application needs.
  • For more robust and feature-rich solutions, consider implementing additional error checking, uniqueness checks, and handling of clock sequence overflows as specified in the ULID specification.

This implementation follows the basic ULID generation principles and should be adjusted according to specific project requirements and best practices.