Examples - Taiizor/UUID GitHub Wiki

💡 Examples

Basic Usage Examples

1. Web API Usage

[ApiController]
[Route("[controller]")]
public class OrderController : ControllerBase
{
    [HttpPost]
    public ActionResult<Order> CreateOrder(OrderRequest request)
    {
        var order = new Order
        {
            Id = new UUID(),  // Automatic UUID generation
            // ... other properties
        };
        
        return order;
    }
}

2. Entity Framework Usage

public class Order
{
    public UUID Id { get; set; }
    public string CustomerName { get; set; }
    // ... other properties
}

// DbContext configuration
public class AppDbContext : DbContext
{
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Order>()
            .Property(e => e.Id)
            .HasConversion(
                uuid => uuid.ToString(),
                str => UUID.Parse(str)
            );
    }
}

3. Distributed Caching

public class CacheService
{
    private readonly IDistributedCache _cache;

    public CacheService(IDistributedCache cache)
    {
        _cache = cache;
    }

    public async Task<string> GetOrCreateAsync(string key)
    {
        var cacheKey = new UUID().ToBase32();  // Unique cache key
        var value = await _cache.GetStringAsync(cacheKey);
        
        if (value == null)
        {
            value = await ComputeExpensiveOperation();
            await _cache.SetStringAsync(cacheKey, value);
        }
        
        return value;
    }
}

4. Parallel Processing

public class BatchProcessor
{
    public async Task ProcessBatch(IEnumerable<string> items)
    {
        var tasks = items.Select(async item =>
        {
            var batchId = new UUID();  // Unique ID for each batch
            await ProcessItem(item, batchId);
        });

        await Task.WhenAll(tasks);
    }
}

5. Sequential IDs

public class AuditLog
{
    private static readonly List<(UUID Id, string Message)> _logs = new();

    public void AddLog(string message)
    {
        var logEntry = (new UUID(), message);
        _logs.Add(logEntry);
    }

    public IEnumerable<string> GetLogsByTimeRange(DateTimeOffset start, DateTimeOffset end)
    {
        return _logs
            .Where(log => log.Id.Time >= start && log.Id.Time <= end)
            .OrderBy(log => log.Id)  // Time-based sorting
            .Select(log => log.Message);
    }
}

6. Custom Formatter

public class CustomUUIDFormatter
{
    public string FormatWithPrefix(UUID uuid, string prefix)
    {
        return $"{prefix}-{uuid.ToBase32()}";
    }

    public UUID ParseWithPrefix(string formatted, string prefix)
    {
        if (!formatted.StartsWith(prefix + "-"))
            throw new FormatException("Invalid prefix");

        var base32 = formatted.Substring(prefix.Length + 1);
        // Parse implementation for Base32
        // ...
    }
}

7. Bulk UUID Generation

public class UUIDGenerator
{
    public IEnumerable<UUID> GenerateBatch(int count)
    {
        return Enumerable.Range(0, count)
            .Select(_ => new UUID())
            .ToList();
    }

    public async Task<HashSet<UUID>> GenerateUniqueAsync(int count)
    {
        var set = new HashSet<UUID>();
        var tasks = Enumerable.Range(0, count)
            .Select(_ => Task.Run(() =>
            {
                lock (set)
                {
                    UUID id;
                    do
                    {
                        id = new UUID();
                    } while (!set.Add(id));
                }
            }));

        await Task.WhenAll(tasks);
        return set;
    }
}

8. Performance Optimization

public class OptimizedUUIDProcessor
{
    private readonly byte[] _buffer = new byte[16];
    private readonly char[] _stringBuffer = new char[32];

    public void ProcessUUID(UUID uuid)
    {
        // Reusable buffer for byte operations
        if (uuid.TryWriteBytes(_buffer))
        {
            // Process bytes
        }

        // Reusable buffer for string operations
        if (uuid.TryWriteStringify(_stringBuffer))
        {
            // Process string representation
        }
    }
}

9. Format Conversions

public class FormatExample
{
    public void DemonstrateFormats()
    {
        var uuid = new UUID();

        // String formats
        string standard = uuid.ToString();
        string base32 = uuid.ToBase32();  // URL-safe
        string base64 = uuid.ToBase64();  // Most compact

        Console.WriteLine($"Standard: {standard}");
        Console.WriteLine($"Base32: {base32}");
        Console.WriteLine($"Base64: {base64}");

        // Convert back from Base64
        UUID fromBase64 = UUID.FromBase64(base64);
        Console.WriteLine($"Restored from Base64: {fromBase64}");

        // Safe parsing with TryFromBase64
        if (UUID.TryFromBase64(base64, out UUID parsed))
        {
            Console.WriteLine($"Successfully parsed: {parsed}");
        }
    }
}

10. Byte Array Operations

public class ByteArrayExample
{
    public void DemonstrateByteOperations()
    {
        var uuid = new UUID();

        // Convert to byte array
        byte[] bytes = uuid.ToByteArray();
        Console.WriteLine($"As bytes: {BitConverter.ToString(bytes)}");

        // Convert back from bytes
        UUID fromBytes = UUID.FromByteArray(bytes);
        Console.WriteLine($"Restored from bytes: {fromBytes}");

        // Using Span<byte> for better performance
        Span<byte> buffer = stackalloc byte[16];
        if (uuid.TryWriteBytes(buffer))
        {
            Console.WriteLine($"Written to span: {BitConverter.ToString(buffer.ToArray())}");
        }

        // Safe parsing with TryFromByteArray
        if (UUID.TryFromByteArray(bytes, out UUID parsed))
        {
            Console.WriteLine($"Successfully parsed from bytes: {parsed}");
        }
    }
}

11. Guid Conversions

public class GuidExample
{
    public void DemonstrateGuidConversions()
    {
        // Create a new UUID
        var uuid = new UUID();

        // Implicit conversion to Guid
        Guid guid = uuid;
        Console.WriteLine($"As Guid: {guid}");

        // Implicit conversion from Guid
        UUID fromGuid = guid;
        Console.WriteLine($"Back to UUID: {fromGuid}");

        // Using explicit methods if needed
        Guid guidExplicit = uuid.ToGuid();
        UUID uuidExplicit = UUID.FromGuid(guidExplicit);

        // Verify equality
        Console.WriteLine($"Equal after conversion: {uuid == uuidExplicit}");
    }
}
⚠️ **GitHub.com Fallback** ⚠️