using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Npgsql; namespace ClassNotify.PostgreSqlE2ESuite { // ========================================================================= // 1. Unified Frozen Production Entities (100% aligned with Turn 97/98/99) // ========================================================================= [Table("TeacherAccounts")] public class TeacherAccount { [Key] public Guid TeacherId { get; set; } = Guid.NewGuid(); [Required, StringLength(11)] public string Mobile { get; set; } = string.Empty; [Required, StringLength(255)] public string PasswordHash { get; set; } = string.Empty; // ASP.NET Core PBKDF2 public DateTime TrialEndsAt { get; set; } public DateTime? VipExpiresAt { get; set; } [StringLength(64)] public string? ActiveSessionToken { get; set; } public DateTime CreatedAt { get; set; } = DateTime.UtcNow; public bool IsVipActive(DateTime now) => VipExpiresAt.HasValue && VipExpiresAt.Value > now; public bool IsTrialActive(DateTime now) => TrialEndsAt > now; } [Table("Devices")] public class Device { [Key] public Guid DeviceId { get; set; } = Guid.NewGuid(); [Required, StringLength(64)] public string HardwareFingerprintSha256 { get; set; } = string.Empty; [StringLength(8)] public string? PairingCode { get; set; } public DateTime? PairingCodeExpiresAt { get; set; } public bool IsOnline { get; set; } = false; public DateTime CreatedAt { get; set; } = DateTime.UtcNow; } [Table("TeacherDeviceBindings")] public class TeacherDeviceBinding { [Key] public Guid Id { get; set; } = Guid.NewGuid(); public Guid TeacherId { get; set; } public Guid DeviceId { get; set; } [StringLength(100)] public string? ClassAlias { get; set; } public bool IsActive { get; set; } = true; public DateTime BoundAt { get; set; } = DateTime.UtcNow; public DateTime? ReleasedAt { get; set; } } [Table("DeviceTrialLedgers")] public class DeviceTrialLedger { [Key] public Guid Id { get; set; } = Guid.NewGuid(); [Required, StringLength(64)] public string DeviceTrialKey { get; set; } = string.Empty; // HMAC-SHA256 public Guid FirstTrialTeacherId { get; set; } public DateTime TrialStartedAt { get; set; } public DateTime TrialExpiresAt { get; set; } public bool IsTrialUsed { get; set; } = true; public DateTime CreatedAt { get; set; } = DateTime.UtcNow; } [Table("SubscriptionVouchers")] public class SubscriptionVoucher { [Key] public Guid Id { get; set; } = Guid.NewGuid(); [Required, StringLength(64)] public string CodeHash { get; set; } = string.Empty; // SHA-256 of card key public int DurationDays { get; set; } = 365; public bool IsUsed { get; set; } = false; public Guid? UsedByTeacherId { get; set; } public DateTime? UsedAt { get; set; } public DateTime CreatedAt { get; set; } = DateTime.UtcNow; } // ========================================================================= // 2. ClassNotifyDbContext with Native PostgreSQL Constraints & Partial Indexes // ========================================================================= public class E2ETestDbContext : DbContext { public E2ETestDbContext(DbContextOptions options) : base(options) { } public DbSet Teachers => Set(); public DbSet Devices => Set(); public DbSet TeacherDeviceBindings => Set(); public DbSet DeviceTrialLedgers => Set(); public DbSet SubscriptionVouchers => Set(); protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity(entity => { entity.HasIndex(t => t.Mobile).IsUnique(); }); modelBuilder.Entity(entity => { entity.HasIndex(l => l.DeviceTrialKey).IsUnique(); }); // PostgreSQL Native Partial Unique Index for Active Bindings modelBuilder.Entity(entity => { entity.HasIndex(b => new { b.TeacherId, b.DeviceId }) .IsUnique() .HasFilter("\"IsActive\" = TRUE"); }); // PostgreSQL Native Partial Unique Index for Devices with non-null pairing code modelBuilder.Entity(entity => { entity.HasIndex(d => d.PairingCode) .IsUnique() .HasFilter("\"PairingCode\" IS NOT NULL"); }); // Subscription Voucher Hash Uniqueness modelBuilder.Entity(entity => { entity.HasIndex(v => v.CodeHash).IsUnique(); }); } } // ========================================================================= // 3. Pairing Code Generator Abstraction & Implementations // ========================================================================= public interface IPairingCodeGenerator { string Generate8DigitCode(); } public class CsprngPairingCodeGenerator : IPairingCodeGenerator { public string Generate8DigitCode() { return RandomNumberGenerator.GetInt32(10000000, 100000000).ToString("D8"); } } public class MockSequencePairingCodeGenerator : IPairingCodeGenerator { private readonly Queue _sequence; public int CallsCount { get; private set; } public MockSequencePairingCodeGenerator(IEnumerable codes) { _sequence = new Queue(codes); } public string Generate8DigitCode() { CallsCount++; if (_sequence.Count > 0) return _sequence.Dequeue(); return "99999999"; } } // ========================================================================= // 4. Production-Grade Services with 40001 Serialization Retries // ========================================================================= public record ClaimDeviceResult(bool Success, string? ErrorCode = null, Guid? DeviceId = null); public class PairingService { private readonly E2ETestDbContext _db; private readonly IPairingCodeGenerator _codeGenerator; private readonly int _personalScreenLimit; public PairingService(E2ETestDbContext db, IPairingCodeGenerator codeGenerator, IConfiguration config) { _db = db; _codeGenerator = codeGenerator; _personalScreenLimit = config.GetValue("Product:PersonalScreenLimit", 4); } public async Task GenerateUniquePairingCodeAsync(Guid deviceId) { const int maxRetries = 10; for (int attempt = 1; attempt <= maxRetries; attempt++) { try { var code = _codeGenerator.Generate8DigitCode(); var device = await _db.Devices.FindAsync(deviceId); if (device == null) throw new InvalidOperationException($"Device {deviceId} not found."); device.PairingCode = code; device.PairingCodeExpiresAt = DateTime.UtcNow.AddMinutes(10); // 10 minutes TTL await _db.SaveChangesAsync(); return code; } catch (DbUpdateException ex) when (IsUniqueViolation(ex)) { _db.ChangeTracker.Clear(); if (attempt == maxRetries) throw; } } throw new InvalidOperationException("Failed to allocate unique pairing code."); } public async Task ClaimDeviceAsync(Guid teacherId, string pairingCode, string? classAlias = null) { const int maxRetries = 5; for (int attempt = 1; attempt <= maxRetries; attempt++) { await using var tx = await _db.Database.BeginTransactionAsync(IsolationLevel.Serializable); try { var now = DateTime.UtcNow; var device = await _db.Devices .FirstOrDefaultAsync(d => d.PairingCode == pairingCode && d.PairingCodeExpiresAt > now); if (device == null) { await tx.RollbackAsync(); return new ClaimDeviceResult(false, "INVALID_OR_EXPIRED_PAIRING_CODE"); } var activeCount = await _db.TeacherDeviceBindings .CountAsync(b => b.TeacherId == teacherId && b.IsActive); if (activeCount >= _personalScreenLimit) { await tx.RollbackAsync(); return new ClaimDeviceResult(false, "SCREEN_LIMIT_REACHED"); } var binding = await _db.TeacherDeviceBindings .FirstOrDefaultAsync(b => b.TeacherId == teacherId && b.DeviceId == device.DeviceId); if (binding == null) { binding = new TeacherDeviceBinding { Id = Guid.NewGuid(), TeacherId = teacherId, DeviceId = device.DeviceId, ClassAlias = classAlias, BoundAt = now, IsActive = true }; _db.TeacherDeviceBindings.Add(binding); } else { binding.IsActive = true; binding.ClassAlias = classAlias; binding.BoundAt = now; binding.ReleasedAt = null; } await _db.SaveChangesAsync(); await tx.CommitAsync(); return new ClaimDeviceResult(true, DeviceId: device.DeviceId); } catch (Exception ex) when (IsSerializationFailure(ex)) { try { await tx.RollbackAsync(); } catch { /* server already aborted tx */ } _db.ChangeTracker.Clear(); if (attempt == maxRetries) { return new ClaimDeviceResult(false, "CONCURRENCY_RETRY_EXHAUSTED"); } await Task.Delay(RandomNumberGenerator.GetInt32(25, 75)); } catch (Exception) { try { await tx.RollbackAsync(); } catch { } throw; } } return new ClaimDeviceResult(false, "CONCURRENCY_RETRY_EXHAUSTED"); } private static bool IsUniqueViolation(DbUpdateException ex) { return ex.InnerException is PostgresException pg && pg.SqlState == PostgresErrorCodes.UniqueViolation; } private static bool IsSerializationFailure(Exception? ex) { while (ex != null) { if (ex is PostgresException pg && pg.SqlState == PostgresErrorCodes.SerializationFailure) return true; ex = ex.InnerException; } return false; } } public record VoucherRedeemResult(bool Success, string? ErrorCode = null, DateTime? NewVipExpiresAt = null); public class VoucherService { private readonly E2ETestDbContext _db; public VoucherService(E2ETestDbContext db) { _db = db; } public static string HashVoucherCode(string voucherCode) { var cleanCode = voucherCode.Trim().Replace("-", "").ToUpperInvariant(); using var sha = SHA256.Create(); var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(cleanCode)); return Convert.ToHexString(bytes).ToLowerInvariant(); } public async Task RedeemVoucherAsync(Guid teacherId, string voucherCode) { var codeHash = HashVoucherCode(voucherCode); const int maxRetries = 5; for (int attempt = 1; attempt <= maxRetries; attempt++) { await using var tx = await _db.Database.BeginTransactionAsync(IsolationLevel.Serializable); try { var voucher = await _db.SubscriptionVouchers .FirstOrDefaultAsync(v => v.CodeHash == codeHash); if (voucher == null) { await tx.RollbackAsync(); return new VoucherRedeemResult(false, "VOUCHER_NOT_FOUND"); } if (voucher.IsUsed) { await tx.RollbackAsync(); return new VoucherRedeemResult(false, "VOUCHER_ALREADY_USED"); } var teacher = await _db.Teachers.FirstOrDefaultAsync(t => t.TeacherId == teacherId); if (teacher == null) { await tx.RollbackAsync(); return new VoucherRedeemResult(false, "TEACHER_NOT_FOUND"); } var now = DateTime.UtcNow; voucher.IsUsed = true; voucher.UsedByTeacherId = teacherId; voucher.UsedAt = now; var baseTime = (teacher.VipExpiresAt.HasValue && teacher.VipExpiresAt.Value > now) ? teacher.VipExpiresAt.Value : now; teacher.VipExpiresAt = baseTime.AddDays(voucher.DurationDays); await _db.SaveChangesAsync(); await tx.CommitAsync(); return new VoucherRedeemResult(true, NewVipExpiresAt: teacher.VipExpiresAt); } catch (Exception ex) when (IsSerializationFailure(ex)) { try { await tx.RollbackAsync(); } catch { /* server already aborted tx */ } _db.ChangeTracker.Clear(); if (attempt == maxRetries) { return new VoucherRedeemResult(false, "CONCURRENCY_RETRY_EXHAUSTED"); } await Task.Delay(RandomNumberGenerator.GetInt32(25, 75)); } catch (Exception) { try { await tx.RollbackAsync(); } catch { } throw; } } return new VoucherRedeemResult(false, "CONCURRENCY_RETRY_EXHAUSTED"); } private static bool IsSerializationFailure(Exception? ex) { while (ex != null) { if (ex is PostgresException pg && pg.SqlState == PostgresErrorCodes.SerializationFailure) return true; ex = ex.InnerException; } return false; } } // ========================================================================= // 5. Real PostgreSQL 5-Test Execution Harness // ========================================================================= public class Program { private static string _connStr = "Host=127.0.0.1;Port=5432;Database=classnotify_test;Username=classnotify;Password=ae86fc448dde3ff771175cf2b9dd5e3a2bab3c31c28259cd2c3719c28bb731ce;"; private static E2ETestDbContext CreateDb() { var options = new DbContextOptionsBuilder() .UseNpgsql(_connStr) .Options; return new E2ETestDbContext(options); } private static IConfiguration CreateConfig() { return new ConfigurationBuilder() .AddInMemoryCollection(new Dictionary { { "Product:PersonalScreenLimit", "4" }, { "Jwt:Secret", "A_Very_Strong_Secret_Key_That_Has_At_Least_32_Bytes_For_Security!" } }) .Build(); } public static async Task Main(string[] args) { Console.WriteLine("================================================================================"); Console.WriteLine(" ClassNotify Turn 100: Real PostgreSQL 16.15 E2E Verification Suite"); Console.WriteLine("================================================================================"); try { // Step 0: Initialize schema against real PostgreSQL Console.WriteLine("\n[INIT] Connecting to PostgreSQL and creating schema..."); await using (var initDb = CreateDb()) { // Clean recreate test tables await initDb.Database.EnsureDeletedAsync(); await initDb.Database.EnsureCreatedAsync(); Console.WriteLine("[INIT] Real PostgreSQL test schema created successfully!"); } int passed = 0; int total = 5; // T1: DeviceTrialKey Concurrent Write (23505 Uniqueness) Console.WriteLine("\n--------------------------------------------------------------------------------"); Console.WriteLine("[RUNNING] T1: DeviceTrialLedger 23505 Uniqueness Under Concurrent Writes..."); await RunTest1(); Console.WriteLine("[PASS] T1 PASSED: PostgreSQL 23505 intercepted, exactly 1 ledger created."); passed++; // T2: 4-Screen Quota Invariant with 40001 Graceful Retry Console.WriteLine("\n--------------------------------------------------------------------------------"); Console.WriteLine("[RUNNING] T2: 4-Screen Quota Invariant with PostgreSQL 40001 Graceful Retry..."); await RunTest2(); Console.WriteLine("[PASS] T2 PASSED: SSI 40001 retried, exactly 4 screens active, 5th got SCREEN_LIMIT_REACHED."); passed++; // T3: Forced Pairing Code Collision with 23505 Catch & ChangeTracker.Clear() Console.WriteLine("\n--------------------------------------------------------------------------------"); Console.WriteLine("[RUNNING] T3: Forced Pairing Code Collision with 23505 Catch & Retry..."); await RunTest3(); Console.WriteLine("[PASS] T3 PASSED: Forced 88888888 collided, caught 23505, cleared tracker, 77777777 succeeded!"); passed++; // T4: Concurrent Voucher Redemption with 40001 Graceful Retry Console.WriteLine("\n--------------------------------------------------------------------------------"); Console.WriteLine("[RUNNING] T4: Concurrent Voucher Redemption with PostgreSQL 40001 Retry..."); await RunTest4(); Console.WriteLine("[PASS] T4 PASSED: One succeeded (+365d), second gracefully got VOUCHER_ALREADY_USED."); passed++; // T5: Native PostgreSQL pg_indexes System Catalog Partial Index Predicate Verification Console.WriteLine("\n--------------------------------------------------------------------------------"); Console.WriteLine("[RUNNING] T5: Native pg_indexes System Catalog Partial Index Verification..."); await RunTest5(); Console.WriteLine("[PASS] T5 PASSED: pg_indexes catalog verified: IsActive = true & PairingCode IS NOT NULL!"); passed++; Console.WriteLine("\n================================================================================"); Console.WriteLine($" ALL TESTS COMPLETED: {passed}/{total} PASSED (0 FAILED, 0 WARNINGS)"); Console.WriteLine("================================================================================"); return 0; } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"\n[FATAL TEST FAILURE]: {ex}"); Console.ResetColor(); return 1; } } private static async Task RunTest1() { var testTrialKey = "trial_key_t1_" + Guid.NewGuid().ToString("N"); async Task TryInsert() { await using var db = CreateDb(); try { db.DeviceTrialLedgers.Add(new DeviceTrialLedger { Id = Guid.NewGuid(), DeviceTrialKey = testTrialKey, FirstTrialTeacherId = Guid.NewGuid(), TrialStartedAt = DateTime.UtcNow, TrialExpiresAt = DateTime.UtcNow.AddDays(7), IsTrialUsed = true }); await db.SaveChangesAsync(); return true; } catch (DbUpdateException ex) when (ex.InnerException is PostgresException pg && pg.SqlState == "23505") { return false; } } var t1 = Task.Run(TryInsert); var t2 = Task.Run(TryInsert); var results = await Task.WhenAll(t1, t2); if (results.Count(r => r == true) != 1 || results.Count(r => r == false) != 1) { throw new Exception($"Expected 1 winner and 1 loser, got {results.Count(r => r == true)} winners."); } await using var verifyDb = CreateDb(); var count = await verifyDb.DeviceTrialLedgers.CountAsync(l => l.DeviceTrialKey == testTrialKey); if (count != 1) throw new Exception($"Expected exactly 1 ledger in DB, found {count}."); } private static async Task RunTest2() { await using var db = CreateDb(); var teacherId = Guid.NewGuid(); db.Teachers.Add(new TeacherAccount { TeacherId = teacherId, Mobile = "13800000002", PasswordHash = "pbkdf2_hash_mock", ActiveSessionToken = "tok_session_1", CreatedAt = DateTime.UtcNow }); // Pre-seed 3 active bindings for (int i = 1; i <= 3; i++) { var dev = new Device { DeviceId = Guid.NewGuid(), HardwareFingerprintSha256 = $"hw_t2_{i}_{Guid.NewGuid():N}" }; db.Devices.Add(dev); db.TeacherDeviceBindings.Add(new TeacherDeviceBinding { Id = Guid.NewGuid(), TeacherId = teacherId, DeviceId = dev.DeviceId, BoundAt = DateTime.UtcNow, IsActive = true }); } // Two candidate screens for slots 4 and 5 var dev4 = new Device { DeviceId = Guid.NewGuid(), HardwareFingerprintSha256 = "hw_dev4", PairingCode = "11112222", PairingCodeExpiresAt = DateTime.UtcNow.AddMinutes(10) }; var dev5 = new Device { DeviceId = Guid.NewGuid(), HardwareFingerprintSha256 = "hw_dev5", PairingCode = "33334444", PairingCodeExpiresAt = DateTime.UtcNow.AddMinutes(10) }; db.Devices.AddRange(dev4, dev5); await db.SaveChangesAsync(); var config = CreateConfig(); async Task ClaimScreen(string code) { await using var clientDb = CreateDb(); var service = new PairingService(clientDb, new CsprngPairingCodeGenerator(), config); return await service.ClaimDeviceAsync(teacherId, code); } var t4Task = Task.Run(() => ClaimScreen("11112222")); var t5Task = Task.Run(() => ClaimScreen("33334444")); var results = await Task.WhenAll(t4Task, t5Task); bool hasSuccess = results.Any(r => r.Success == true); bool hasLimitReached = results.Any(r => r.Success == false && r.ErrorCode == "SCREEN_LIMIT_REACHED"); if (!hasSuccess || !hasLimitReached) { throw new Exception($"Expected 1 success and 1 SCREEN_LIMIT_REACHED, got results: {string.Join(", ", results.Select(r => $"{r.Success}/{r.ErrorCode}"))}"); } await using var verifyDb = CreateDb(); var activeCount = await verifyDb.TeacherDeviceBindings.CountAsync(b => b.TeacherId == teacherId && b.IsActive); if (activeCount != 4) { throw new Exception($"Invariant violated! Active screen count is {activeCount}, expected exactly 4."); } } private static async Task RunTest3() { await using var db = CreateDb(); var collidedCode = "88888888"; var successCode = "77777777"; var existingDevice = new Device { DeviceId = Guid.NewGuid(), HardwareFingerprintSha256 = "hw_t3_existing", PairingCode = collidedCode, PairingCodeExpiresAt = DateTime.UtcNow.AddMinutes(10) }; db.Devices.Add(existingDevice); var newDevice = new Device { DeviceId = Guid.NewGuid(), HardwareFingerprintSha256 = "hw_t3_new" }; db.Devices.Add(newDevice); await db.SaveChangesAsync(); var mockGen = new MockSequencePairingCodeGenerator(new[] { collidedCode, successCode }); var service = new PairingService(db, mockGen, CreateConfig()); var assignedCode = await service.GenerateUniquePairingCodeAsync(newDevice.DeviceId); if (mockGen.CallsCount != 2) { throw new Exception($"Expected generator to be called twice (collision on 1st), but was called {mockGen.CallsCount} times."); } if (assignedCode != successCode) { throw new Exception($"Expected assigned code {successCode}, but got {assignedCode}."); } await using var verifyDb = CreateDb(); var savedDev = await verifyDb.Devices.FindAsync(newDevice.DeviceId); if (savedDev!.PairingCode != successCode) { throw new Exception($"Device PairingCode in DB was {savedDev.PairingCode}, expected {successCode}."); } } private static async Task RunTest4() { await using var db = CreateDb(); var teacherId1 = Guid.NewGuid(); var teacherId2 = Guid.NewGuid(); var now = DateTime.UtcNow; db.Teachers.AddRange( new TeacherAccount { TeacherId = teacherId1, Mobile = "13800000004", PasswordHash = "h", ActiveSessionToken = "s1", CreatedAt = now }, new TeacherAccount { TeacherId = teacherId2, Mobile = "13800000005", PasswordHash = "h", ActiveSessionToken = "s2", CreatedAt = now } ); var cardKey = "CARD-VOUCH-TEST4"; var codeHash = VoucherService.HashVoucherCode(cardKey); db.SubscriptionVouchers.Add(new SubscriptionVoucher { Id = Guid.NewGuid(), CodeHash = codeHash, DurationDays = 365, IsUsed = false, CreatedAt = now }); await db.SaveChangesAsync(); async Task Redeem(Guid tId) { await using var clientDb = CreateDb(); var service = new VoucherService(clientDb); return await service.RedeemVoucherAsync(tId, cardKey); } var r1Task = Task.Run(() => Redeem(teacherId1)); var r2Task = Task.Run(() => Redeem(teacherId2)); var results = await Task.WhenAll(r1Task, r2Task); bool oneSuccess = results.Count(r => r.Success == true) == 1; bool oneAlreadyUsed = results.Count(r => r.Success == false && r.ErrorCode == "VOUCHER_ALREADY_USED") == 1; if (!oneSuccess || !oneAlreadyUsed) { throw new Exception($"Expected exactly 1 success and 1 VOUCHER_ALREADY_USED. Got: {string.Join(", ", results.Select(r => $"{r.Success}/{r.ErrorCode}"))}"); } await using var verifyDb = CreateDb(); var voucher = await verifyDb.SubscriptionVouchers.FirstAsync(v => v.CodeHash == codeHash); if (!voucher.IsUsed) throw new Exception("Voucher was not marked as used in DB."); } private static async Task RunTest5() { await using var db = CreateDb(); var conn = (NpgsqlConnection)db.Database.GetDbConnection(); if (conn.State != ConnectionState.Open) await conn.OpenAsync(); await using var cmd = conn.CreateCommand(); cmd.CommandText = @" SELECT tablename, indexname, indexdef FROM pg_indexes WHERE schemaname = 'public' AND tablename IN ('TeacherDeviceBindings', 'Devices') ORDER BY tablename, indexname;"; var indexDefs = new List<(string Table, string IndexName, string Def)>(); await using (var reader = await cmd.ExecuteReaderAsync()) { while (await reader.ReadAsync()) { indexDefs.Add((reader.GetString(0), reader.GetString(1), reader.GetString(2))); } } var bindingIndex = indexDefs.FirstOrDefault(i => i.Table == "TeacherDeviceBindings" && i.Def.Contains("IsActive", StringComparison.OrdinalIgnoreCase) && i.Def.Contains("UNIQUE", StringComparison.OrdinalIgnoreCase)); if (bindingIndex == default) { throw new Exception("Missing partial unique index on TeacherDeviceBindings with IsActive."); } if (!Regex.IsMatch(bindingIndex.Def, @"WHERE\s+\(?\s*""?IsActive""?\s*=\s*true\)?", RegexOptions.IgnoreCase)) { throw new Exception($"TeacherDeviceBindings indexdef did not match expected regex: {bindingIndex.Def}"); } var pairingIndex = indexDefs.FirstOrDefault(i => i.Table == "Devices" && i.Def.Contains("PairingCode", StringComparison.OrdinalIgnoreCase) && i.Def.Contains("UNIQUE", StringComparison.OrdinalIgnoreCase)); if (pairingIndex == default) { throw new Exception("Missing partial unique index on Devices with PairingCode IS NOT NULL."); } if (!Regex.IsMatch(pairingIndex.Def, @"WHERE\s+\(?\s*""?PairingCode""?\s+IS\s+NOT\s+NULL\)?", RegexOptions.IgnoreCase)) { throw new Exception($"Devices indexdef did not match expected regex: {pairingIndex.Def}"); } } } }