language
stringclasses
1 value
repo
stringclasses
133 values
path
stringlengths
13
229
class_span
dict
source
stringlengths
14
2.92M
target
stringlengths
1
153
csharp
AvaloniaUI__Avalonia
src/Browser/Avalonia.Browser/Storage/BrowserStorageProvider.cs
{ "start": 10820, "end": 15012 }
internal class ____ : JSStorageItem, IStorageBookmarkFolder { public JSStorageFolder(JSObject fileHandle) : base(fileHandle) { } public async IAsyncEnumerable<IStorageItem> GetItemsAsync() { using var itemsIterator = StorageHelper.GetItemsIterator(FileHandle); if (itemsIterator is null) { yield break; } while (true) { var nextResult = await itemsIterator.CallMethodObjectAsync("next"); if (nextResult is null) { yield break; } var isDone = nextResult.GetPropertyAsBoolean("done"); if (isDone) { yield break; } var valArray = nextResult.GetPropertyAsJSObject("value"); var storageItem = valArray?.GetArrayItem(1); // 0 - item name, 1 - item instance if (storageItem is null) { yield break; } var kind = storageItem.GetPropertyAsString("kind"); var item = StorageHelper.StorageItemFromHandle(storageItem)!; switch (kind) { case "directory": yield return new JSStorageFolder(item); break; case "file": yield return new JSStorageFile(item); break; } } } public async Task<IStorageFile?> CreateFileAsync(string name) { try { var fileHandle = await StorageHelper.CreateFile(FileHandle, name); if (fileHandle is null) { return null; } var storageFile = StorageHelper.StorageItemFromHandle(fileHandle)!; return new JSStorageFile(storageFile); } catch (JSException ex) when (ex.Message == BrowserStorageProvider.NoPermissionsMessage) { throw new UnauthorizedAccessException("User denied permissions to open the file", ex); } } public async Task<IStorageFolder?> CreateFolderAsync(string name) { try { var folderHandler = await StorageHelper.CreateFolder(FileHandle, name); if (folderHandler is null) { return null; } var storageFolder = StorageHelper.StorageItemFromHandle(folderHandler)!; return new JSStorageFolder(storageFolder); } catch (JSException ex) when (ex.Message == BrowserStorageProvider.NoPermissionsMessage) { throw new UnauthorizedAccessException("User denied permissions to open the file", ex); } } public async Task<IStorageFolder?> GetFolderAsync(string name) { try { var folderHandle = await StorageHelper.GetFolder(FileHandle, name); if (folderHandle is null) { return null; } var storageFolder = StorageHelper.StorageItemFromHandle(folderHandle)!; return new JSStorageFolder(storageFolder); } catch (JSException ex) when (ShouldSupressErrorOnFileAccess(ex)) { return null; } } public async Task<IStorageFile?> GetFileAsync(string name) { try { var fileHandle = await StorageHelper.GetFile(FileHandle, name); if (fileHandle is null) { return null; } var storageFile = StorageHelper.StorageItemFromHandle(fileHandle)!; return new JSStorageFile(storageFile); } catch (JSException ex) when (ShouldSupressErrorOnFileAccess(ex)) { return null; } } private static bool ShouldSupressErrorOnFileAccess(JSException ex) => ex.Message == BrowserStorageProvider.NoPermissionsMessage || ex.Message.Contains(BrowserStorageProvider.TypeMissmatchMessage, StringComparison.Ordinal) || ex.Message.Contains(BrowserStorageProvider.FileFolderNotFoundMessage, StringComparison.Ordinal); }
JSStorageFolder
csharp
bitwarden__server
util/MySqlMigrations/Migrations/20240606152409_ProviderInvoiceItem.Designer.cs
{ "start": 452, "end": 100303 }
partial class ____ { /// <inheritdoc /> protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "7.0.16") .HasAnnotation("Relational:MaxIdentifierLength", 64); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<bool>("AllowAdminAccessToAllCollectionItems") .HasColumnType("tinyint(1)") .HasDefaultValue(true); b.Property<string>("BillingEmail") .HasMaxLength(256) .HasColumnType("varchar(256)"); b.Property<string>("BusinessAddress1") .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<string>("BusinessAddress2") .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<string>("BusinessAddress3") .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<string>("BusinessCountry") .HasMaxLength(2) .HasColumnType("varchar(2)"); b.Property<string>("BusinessName") .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<string>("BusinessTaxNumber") .HasMaxLength(30) .HasColumnType("varchar(30)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<bool>("Enabled") .HasColumnType("tinyint(1)"); b.Property<DateTime?>("ExpirationDate") .HasColumnType("datetime(6)"); b.Property<bool>("FlexibleCollections") .HasColumnType("tinyint(1)"); b.Property<byte?>("Gateway") .HasColumnType("tinyint unsigned"); b.Property<string>("GatewayCustomerId") .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<string>("GatewaySubscriptionId") .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<string>("Identifier") .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<string>("LicenseKey") .HasMaxLength(100) .HasColumnType("varchar(100)"); b.Property<bool>("LimitCollectionCreationDeletion") .HasColumnType("tinyint(1)") .HasDefaultValue(true); b.Property<int?>("MaxAutoscaleSeats") .HasColumnType("int"); b.Property<int?>("MaxAutoscaleSmSeats") .HasColumnType("int"); b.Property<int?>("MaxAutoscaleSmServiceAccounts") .HasColumnType("int"); b.Property<short?>("MaxCollections") .HasColumnType("smallint"); b.Property<short?>("MaxStorageGb") .HasColumnType("smallint"); b.Property<string>("Name") .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<DateTime?>("OwnersNotifiedOfAutoscaling") .HasColumnType("datetime(6)"); b.Property<string>("Plan") .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<byte>("PlanType") .HasColumnType("tinyint unsigned"); b.Property<string>("PrivateKey") .HasColumnType("longtext"); b.Property<string>("PublicKey") .HasColumnType("longtext"); b.Property<string>("ReferenceData") .HasColumnType("longtext"); b.Property<DateTime>("RevisionDate") .HasColumnType("datetime(6)"); b.Property<int?>("Seats") .HasColumnType("int"); b.Property<bool>("SelfHost") .HasColumnType("tinyint(1)"); b.Property<int?>("SmSeats") .HasColumnType("int"); b.Property<int?>("SmServiceAccounts") .HasColumnType("int"); b.Property<byte>("Status") .HasColumnType("tinyint unsigned"); b.Property<long?>("Storage") .HasColumnType("bigint"); b.Property<string>("TwoFactorProviders") .HasColumnType("longtext"); b.Property<bool>("Use2fa") .HasColumnType("tinyint(1)"); b.Property<bool>("UseApi") .HasColumnType("tinyint(1)"); b.Property<bool>("UseCustomPermissions") .HasColumnType("tinyint(1)"); b.Property<bool>("UseDirectory") .HasColumnType("tinyint(1)"); b.Property<bool>("UseEvents") .HasColumnType("tinyint(1)"); b.Property<bool>("UseGroups") .HasColumnType("tinyint(1)"); b.Property<bool>("UseKeyConnector") .HasColumnType("tinyint(1)"); b.Property<bool>("UsePasswordManager") .HasColumnType("tinyint(1)"); b.Property<bool>("UsePolicies") .HasColumnType("tinyint(1)"); b.Property<bool>("UseResetPassword") .HasColumnType("tinyint(1)"); b.Property<bool>("UseScim") .HasColumnType("tinyint(1)"); b.Property<bool>("UseSecretsManager") .HasColumnType("tinyint(1)"); b.Property<bool>("UseSso") .HasColumnType("tinyint(1)"); b.Property<bool>("UseTotp") .HasColumnType("tinyint(1)"); b.Property<bool>("UsersGetPremium") .HasColumnType("tinyint(1)"); b.HasKey("Id"); b.HasIndex("Id", "Enabled") .HasAnnotation("Npgsql:IndexInclude", new[] { "UseTotp" }); b.ToTable("Organization", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Policy", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("Data") .HasColumnType("longtext"); b.Property<bool>("Enabled") .HasColumnType("tinyint(1)"); b.Property<Guid>("OrganizationId") .HasColumnType("char(36)"); b.Property<DateTime>("RevisionDate") .HasColumnType("datetime(6)"); b.Property<byte>("Type") .HasColumnType("tinyint unsigned"); b.HasKey("Id"); b.HasIndex("OrganizationId") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("OrganizationId", "Type") .IsUnique() .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Policy", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<string>("BillingEmail") .HasColumnType("longtext"); b.Property<string>("BillingPhone") .HasColumnType("longtext"); b.Property<string>("BusinessAddress1") .HasColumnType("longtext"); b.Property<string>("BusinessAddress2") .HasColumnType("longtext"); b.Property<string>("BusinessAddress3") .HasColumnType("longtext"); b.Property<string>("BusinessCountry") .HasColumnType("longtext"); b.Property<string>("BusinessName") .HasColumnType("longtext"); b.Property<string>("BusinessTaxNumber") .HasColumnType("longtext"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<bool>("Enabled") .HasColumnType("tinyint(1)"); b.Property<byte?>("Gateway") .HasColumnType("tinyint unsigned"); b.Property<string>("GatewayCustomerId") .HasColumnType("longtext"); b.Property<string>("GatewaySubscriptionId") .HasColumnType("longtext"); b.Property<string>("Name") .HasColumnType("longtext"); b.Property<DateTime>("RevisionDate") .HasColumnType("datetime(6)"); b.Property<byte>("Status") .HasColumnType("tinyint unsigned"); b.Property<byte>("Type") .HasColumnType("tinyint unsigned"); b.Property<bool>("UseEvents") .HasColumnType("tinyint(1)"); b.HasKey("Id"); b.ToTable("Provider", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.ProviderOrganization", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("Key") .HasColumnType("longtext"); b.Property<Guid>("OrganizationId") .HasColumnType("char(36)"); b.Property<Guid>("ProviderId") .HasColumnType("char(36)"); b.Property<DateTime>("RevisionDate") .HasColumnType("datetime(6)"); b.Property<string>("Settings") .HasColumnType("longtext"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.HasIndex("ProviderId"); b.ToTable("ProviderOrganization", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.ProviderUser", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("Email") .HasColumnType("longtext"); b.Property<string>("Key") .HasColumnType("longtext"); b.Property<string>("Permissions") .HasColumnType("longtext"); b.Property<Guid>("ProviderId") .HasColumnType("char(36)"); b.Property<DateTime>("RevisionDate") .HasColumnType("datetime(6)"); b.Property<byte>("Status") .HasColumnType("tinyint unsigned"); b.Property<byte>("Type") .HasColumnType("tinyint unsigned"); b.Property<Guid?>("UserId") .HasColumnType("char(36)"); b.HasKey("Id"); b.HasIndex("ProviderId"); b.HasIndex("UserId"); b.ToTable("ProviderUser", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.AuthRequest", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<string>("AccessCode") .HasMaxLength(25) .HasColumnType("varchar(25)"); b.Property<bool?>("Approved") .HasColumnType("tinyint(1)"); b.Property<DateTime?>("AuthenticationDate") .HasColumnType("datetime(6)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("Key") .HasColumnType("longtext"); b.Property<string>("MasterPasswordHash") .HasColumnType("longtext"); b.Property<Guid?>("OrganizationId") .HasColumnType("char(36)"); b.Property<string>("PublicKey") .HasColumnType("longtext"); b.Property<string>("RequestDeviceIdentifier") .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<byte>("RequestDeviceType") .HasColumnType("tinyint unsigned"); b.Property<string>("RequestIpAddress") .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<DateTime?>("ResponseDate") .HasColumnType("datetime(6)"); b.Property<Guid?>("ResponseDeviceId") .HasColumnType("char(36)"); b.Property<byte>("Type") .HasColumnType("tinyint unsigned"); b.Property<Guid>("UserId") .HasColumnType("char(36)"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.HasIndex("ResponseDeviceId"); b.HasIndex("UserId"); b.ToTable("AuthRequest", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.EmergencyAccess", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("Email") .HasMaxLength(256) .HasColumnType("varchar(256)"); b.Property<Guid?>("GranteeId") .HasColumnType("char(36)"); b.Property<Guid>("GrantorId") .HasColumnType("char(36)"); b.Property<string>("KeyEncrypted") .HasColumnType("longtext"); b.Property<DateTime?>("LastNotificationDate") .HasColumnType("datetime(6)"); b.Property<DateTime?>("RecoveryInitiatedDate") .HasColumnType("datetime(6)"); b.Property<DateTime>("RevisionDate") .HasColumnType("datetime(6)"); b.Property<byte>("Status") .HasColumnType("tinyint unsigned"); b.Property<byte>("Type") .HasColumnType("tinyint unsigned"); b.Property<int>("WaitTimeDays") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("GranteeId"); b.HasIndex("GrantorId"); b.ToTable("EmergencyAccess", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.Grant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("ClientId") .IsRequired() .HasMaxLength(200) .HasColumnType("varchar(200)"); b.Property<DateTime?>("ConsumedDate") .HasColumnType("datetime(6)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("Data") .IsRequired() .HasColumnType("longtext"); b.Property<string>("Description") .HasMaxLength(200) .HasColumnType("varchar(200)"); b.Property<DateTime?>("ExpirationDate") .HasColumnType("datetime(6)"); b.Property<string>("Key") .IsRequired() .HasMaxLength(200) .HasColumnType("varchar(200)"); b.Property<string>("SessionId") .HasMaxLength(100) .HasColumnType("varchar(100)"); b.Property<string>("SubjectId") .HasMaxLength(200) .HasColumnType("varchar(200)"); b.Property<string>("Type") .IsRequired() .HasMaxLength(50) .HasColumnType("varchar(50)"); b.HasKey("Id") .HasName("PK_Grant") .HasAnnotation("SqlServer:Clustered", true); b.HasIndex("ExpirationDate") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("Key") .IsUnique(); b.ToTable("Grant", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.SsoConfig", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("Data") .HasColumnType("longtext"); b.Property<bool>("Enabled") .HasColumnType("tinyint(1)"); b.Property<Guid>("OrganizationId") .HasColumnType("char(36)"); b.Property<DateTime>("RevisionDate") .HasColumnType("datetime(6)"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.ToTable("SsoConfig", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.SsoUser", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("ExternalId") .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<Guid?>("OrganizationId") .HasColumnType("char(36)"); b.Property<Guid>("UserId") .HasColumnType("char(36)"); b.HasKey("Id"); b.HasIndex("OrganizationId") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("UserId"); b.HasIndex("OrganizationId", "ExternalId") .IsUnique() .HasAnnotation("Npgsql:IndexInclude", new[] { "UserId" }) .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("OrganizationId", "UserId") .IsUnique() .HasAnnotation("SqlServer:Clustered", false); b.ToTable("SsoUser", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.WebAuthnCredential", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<Guid>("AaGuid") .HasColumnType("char(36)"); b.Property<int>("Counter") .HasColumnType("int"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("CredentialId") .HasMaxLength(256) .HasColumnType("varchar(256)"); b.Property<string>("EncryptedPrivateKey") .HasMaxLength(2000) .HasColumnType("varchar(2000)"); b.Property<string>("EncryptedPublicKey") .HasMaxLength(2000) .HasColumnType("varchar(2000)"); b.Property<string>("EncryptedUserKey") .HasMaxLength(2000) .HasColumnType("varchar(2000)"); b.Property<string>("Name") .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<string>("PublicKey") .HasMaxLength(256) .HasColumnType("varchar(256)"); b.Property<DateTime>("RevisionDate") .HasColumnType("datetime(6)"); b.Property<bool>("SupportsPrf") .HasColumnType("tinyint(1)"); b.Property<string>("Type") .HasMaxLength(20) .HasColumnType("varchar(20)"); b.Property<Guid>("UserId") .HasColumnType("char(36)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("WebAuthnCredential", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Billing.Models.ProviderInvoiceItem", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<int>("AssignedSeats") .HasColumnType("int"); b.Property<string>("ClientName") .HasColumnType("longtext"); b.Property<DateTime>("Created") .HasColumnType("datetime(6)"); b.Property<string>("InvoiceId") .HasColumnType("varchar(255)"); b.Property<string>("InvoiceNumber") .HasColumnType("longtext"); b.Property<string>("PlanName") .HasColumnType("longtext"); b.Property<Guid>("ProviderId") .HasColumnType("char(36)"); b.Property<decimal>("Total") .HasColumnType("decimal(65,30)"); b.Property<int>("UsedSeats") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("ProviderId"); b.HasIndex("Id", "InvoiceId") .IsUnique(); b.ToTable("ProviderInvoiceItem", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Billing.Models.ProviderPlan", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<int?>("AllocatedSeats") .HasColumnType("int"); b.Property<byte>("PlanType") .HasColumnType("tinyint unsigned"); b.Property<Guid>("ProviderId") .HasColumnType("char(36)"); b.Property<int?>("PurchasedSeats") .HasColumnType("int"); b.Property<int?>("SeatMinimum") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("ProviderId"); b.HasIndex("Id", "PlanType") .IsUnique(); b.ToTable("ProviderPlan", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Collection", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("ExternalId") .HasMaxLength(300) .HasColumnType("varchar(300)"); b.Property<string>("Name") .HasColumnType("longtext"); b.Property<Guid>("OrganizationId") .HasColumnType("char(36)"); b.Property<DateTime>("RevisionDate") .HasColumnType("datetime(6)"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.ToTable("Collection", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionCipher", b => { b.Property<Guid>("CollectionId") .HasColumnType("char(36)"); b.Property<Guid>("CipherId") .HasColumnType("char(36)"); b.HasKey("CollectionId", "CipherId"); b.HasIndex("CipherId"); b.ToTable("CollectionCipher", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionGroup", b => { b.Property<Guid>("CollectionId") .HasColumnType("char(36)"); b.Property<Guid>("GroupId") .HasColumnType("char(36)"); b.Property<bool>("HidePasswords") .HasColumnType("tinyint(1)"); b.Property<bool>("Manage") .HasColumnType("tinyint(1)"); b.Property<bool>("ReadOnly") .HasColumnType("tinyint(1)"); b.HasKey("CollectionId", "GroupId"); b.HasIndex("GroupId"); b.ToTable("CollectionGroups"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionUser", b => { b.Property<Guid>("CollectionId") .HasColumnType("char(36)"); b.Property<Guid>("OrganizationUserId") .HasColumnType("char(36)"); b.Property<bool>("HidePasswords") .HasColumnType("tinyint(1)"); b.Property<bool>("Manage") .HasColumnType("tinyint(1)"); b.Property<bool>("ReadOnly") .HasColumnType("tinyint(1)"); b.HasKey("CollectionId", "OrganizationUserId"); b.HasIndex("OrganizationUserId"); b.ToTable("CollectionUsers"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Device", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("char(36)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("EncryptedPrivateKey") .HasColumnType("longtext"); b.Property<string>("EncryptedPublicKey") .HasColumnType("longtext"); b.Property<string>("EncryptedUserKey") .HasColumnType("longtext"); b.Property<string>("Identifier") .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<string>("Name") .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<string>("PushToken") .HasMaxLength(255) .HasColumnType("varchar(255)"); b.Property<DateTime>("RevisionDate") .HasColumnType("datetime(6)"); b.Property<byte>("Type") .HasColumnType("tinyint unsigned"); b.Property<Guid>("UserId") .HasColumnType("char(36)"); b.HasKey("Id"); b.HasIndex("Identifier") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("UserId") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("UserId", "Identifier") .IsUnique() .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Device", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Event", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<Guid?>("ActingUserId") .HasColumnType("char(36)"); b.Property<Guid?>("CipherId") .HasColumnType("char(36)"); b.Property<Guid?>("CollectionId") .HasColumnType("char(36)"); b.Property<DateTime>("Date") .HasColumnType("datetime(6)"); b.Property<byte?>("DeviceType") .HasColumnType("tinyint unsigned"); b.Property<string>("DomainName") .HasColumnType("longtext"); b.Property<Guid?>("GroupId") .HasColumnType("char(36)"); b.Property<Guid?>("InstallationId") .HasColumnType("char(36)"); b.Property<string>("IpAddress") .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<Guid?>("OrganizationId") .HasColumnType("char(36)"); b.Property<Guid?>("OrganizationUserId") .HasColumnType("char(36)"); b.Property<Guid?>("PolicyId") .HasColumnType("char(36)"); b.Property<Guid?>("ProviderId") .HasColumnType("char(36)"); b.Property<Guid?>("ProviderOrganizationId") .HasColumnType("char(36)"); b.Property<Guid?>("ProviderUserId") .HasColumnType("char(36)"); b.Property<Guid?>("SecretId") .HasColumnType("char(36)"); b.Property<Guid?>("ServiceAccountId") .HasColumnType("char(36)"); b.Property<byte?>("SystemUser") .HasColumnType("tinyint unsigned"); b.Property<int>("Type") .HasColumnType("int"); b.Property<Guid?>("UserId") .HasColumnType("char(36)"); b.HasKey("Id"); b.HasIndex("Date", "OrganizationId", "ActingUserId", "CipherId") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Event", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Group", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<bool>("AccessAll") .HasColumnType("tinyint(1)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("ExternalId") .HasMaxLength(300) .HasColumnType("varchar(300)"); b.Property<string>("Name") .HasMaxLength(100) .HasColumnType("varchar(100)"); b.Property<Guid>("OrganizationId") .HasColumnType("char(36)"); b.Property<DateTime>("RevisionDate") .HasColumnType("datetime(6)"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.ToTable("Group", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.GroupUser", b => { b.Property<Guid>("GroupId") .HasColumnType("char(36)"); b.Property<Guid>("OrganizationUserId") .HasColumnType("char(36)"); b.HasKey("GroupId", "OrganizationUserId"); b.HasIndex("OrganizationUserId"); b.ToTable("GroupUser", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Installation", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("Email") .HasMaxLength(256) .HasColumnType("varchar(256)"); b.Property<bool>("Enabled") .HasColumnType("tinyint(1)"); b.Property<string>("Key") .HasMaxLength(150) .HasColumnType("varchar(150)"); b.HasKey("Id"); b.ToTable("Installation", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationApiKey", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<string>("ApiKey") .HasMaxLength(30) .HasColumnType("varchar(30)"); b.Property<Guid>("OrganizationId") .HasColumnType("char(36)"); b.Property<DateTime>("RevisionDate") .HasColumnType("datetime(6)"); b.Property<byte>("Type") .HasColumnType("tinyint unsigned"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.ToTable("OrganizationApiKey", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationConnection", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<string>("Config") .HasColumnType("longtext"); b.Property<bool>("Enabled") .HasColumnType("tinyint(1)"); b.Property<Guid>("OrganizationId") .HasColumnType("char(36)"); b.Property<byte>("Type") .HasColumnType("tinyint unsigned"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.ToTable("OrganizationConnection", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationDomain", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("DomainName") .HasMaxLength(255) .HasColumnType("varchar(255)"); b.Property<int>("JobRunCount") .HasColumnType("int"); b.Property<DateTime?>("LastCheckedDate") .HasColumnType("datetime(6)"); b.Property<DateTime>("NextRunDate") .HasColumnType("datetime(6)"); b.Property<Guid>("OrganizationId") .HasColumnType("char(36)"); b.Property<string>("Txt") .HasColumnType("longtext"); b.Property<DateTime?>("VerifiedDate") .HasColumnType("datetime(6)"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.ToTable("OrganizationDomain", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationSponsorship", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<string>("FriendlyName") .HasMaxLength(256) .HasColumnType("varchar(256)"); b.Property<DateTime?>("LastSyncDate") .HasColumnType("datetime(6)"); b.Property<string>("OfferedToEmail") .HasMaxLength(256) .HasColumnType("varchar(256)"); b.Property<byte?>("PlanSponsorshipType") .HasColumnType("tinyint unsigned"); b.Property<Guid?>("SponsoredOrganizationId") .HasColumnType("char(36)"); b.Property<Guid?>("SponsoringOrganizationId") .HasColumnType("char(36)"); b.Property<Guid>("SponsoringOrganizationUserId") .HasColumnType("char(36)"); b.Property<bool>("ToDelete") .HasColumnType("tinyint(1)"); b.Property<DateTime?>("ValidUntil") .HasColumnType("datetime(6)"); b.HasKey("Id"); b.HasIndex("SponsoredOrganizationId"); b.HasIndex("SponsoringOrganizationId"); b.HasIndex("SponsoringOrganizationUserId") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("OrganizationSponsorship", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<bool>("AccessAll") .HasColumnType("tinyint(1)"); b.Property<bool>("AccessSecretsManager") .HasColumnType("tinyint(1)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("Email") .HasMaxLength(256) .HasColumnType("varchar(256)"); b.Property<string>("ExternalId") .HasMaxLength(300) .HasColumnType("varchar(300)"); b.Property<string>("Key") .HasColumnType("longtext"); b.Property<Guid>("OrganizationId") .HasColumnType("char(36)"); b.Property<string>("Permissions") .HasColumnType("longtext"); b.Property<string>("ResetPasswordKey") .HasColumnType("longtext"); b.Property<DateTime>("RevisionDate") .HasColumnType("datetime(6)"); b.Property<short>("Status") .HasColumnType("smallint"); b.Property<byte>("Type") .HasColumnType("tinyint unsigned"); b.Property<Guid?>("UserId") .HasColumnType("char(36)"); b.HasKey("Id"); b.HasIndex("OrganizationId") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("UserId") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("UserId", "OrganizationId", "Status") .HasAnnotation("Npgsql:IndexInclude", new[] { "AccessAll" }) .HasAnnotation("SqlServer:Clustered", false); b.ToTable("OrganizationUser", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Send", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<int>("AccessCount") .HasColumnType("int"); b.Property<Guid?>("CipherId") .HasColumnType("char(36)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("Data") .HasColumnType("longtext"); b.Property<DateTime>("DeletionDate") .HasColumnType("datetime(6)"); b.Property<bool>("Disabled") .HasColumnType("tinyint(1)"); b.Property<DateTime?>("ExpirationDate") .HasColumnType("datetime(6)"); b.Property<bool?>("HideEmail") .HasColumnType("tinyint(1)"); b.Property<string>("Key") .HasColumnType("longtext"); b.Property<int?>("MaxAccessCount") .HasColumnType("int"); b.Property<Guid?>("OrganizationId") .HasColumnType("char(36)"); b.Property<string>("Password") .HasMaxLength(300) .HasColumnType("varchar(300)"); b.Property<DateTime>("RevisionDate") .HasColumnType("datetime(6)"); b.Property<byte>("Type") .HasColumnType("tinyint unsigned"); b.Property<Guid?>("UserId") .HasColumnType("char(36)"); b.HasKey("Id"); b.HasIndex("DeletionDate") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("OrganizationId"); b.HasIndex("UserId") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("UserId", "OrganizationId") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Send", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.TaxRate", b => { b.Property<string>("Id") .HasMaxLength(40) .HasColumnType("varchar(40)"); b.Property<bool>("Active") .HasColumnType("tinyint(1)"); b.Property<string>("Country") .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<string>("PostalCode") .HasMaxLength(10) .HasColumnType("varchar(10)"); b.Property<decimal>("Rate") .HasColumnType("decimal(65,30)"); b.Property<string>("State") .HasMaxLength(2) .HasColumnType("varchar(2)"); b.HasKey("Id"); b.ToTable("TaxRate", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Transaction", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<decimal>("Amount") .HasColumnType("decimal(65,30)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("Details") .HasMaxLength(100) .HasColumnType("varchar(100)"); b.Property<byte?>("Gateway") .HasColumnType("tinyint unsigned"); b.Property<string>("GatewayId") .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<Guid?>("OrganizationId") .HasColumnType("char(36)"); b.Property<byte?>("PaymentMethodType") .HasColumnType("tinyint unsigned"); b.Property<Guid?>("ProviderId") .HasColumnType("char(36)"); b.Property<bool?>("Refunded") .HasColumnType("tinyint(1)"); b.Property<decimal?>("RefundedAmount") .HasColumnType("decimal(65,30)"); b.Property<byte>("Type") .HasColumnType("tinyint unsigned"); b.Property<Guid?>("UserId") .HasColumnType("char(36)"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.HasIndex("ProviderId"); b.HasIndex("UserId") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("UserId", "OrganizationId", "CreationDate") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Transaction", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.User", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<DateTime>("AccountRevisionDate") .HasColumnType("datetime(6)"); b.Property<string>("ApiKey") .IsRequired() .HasMaxLength(30) .HasColumnType("varchar(30)"); b.Property<string>("AvatarColor") .HasMaxLength(7) .HasColumnType("varchar(7)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("Culture") .HasMaxLength(10) .HasColumnType("varchar(10)"); b.Property<string>("Email") .IsRequired() .HasMaxLength(256) .HasColumnType("varchar(256)"); b.Property<bool>("EmailVerified") .HasColumnType("tinyint(1)"); b.Property<string>("EquivalentDomains") .HasColumnType("longtext"); b.Property<string>("ExcludedGlobalEquivalentDomains") .HasColumnType("longtext"); b.Property<int>("FailedLoginCount") .HasColumnType("int"); b.Property<bool>("ForcePasswordReset") .HasColumnType("tinyint(1)"); b.Property<byte?>("Gateway") .HasColumnType("tinyint unsigned"); b.Property<string>("GatewayCustomerId") .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<string>("GatewaySubscriptionId") .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<byte>("Kdf") .HasColumnType("tinyint unsigned"); b.Property<int>("KdfIterations") .HasColumnType("int"); b.Property<int?>("KdfMemory") .HasColumnType("int"); b.Property<int?>("KdfParallelism") .HasColumnType("int"); b.Property<string>("Key") .HasColumnType("longtext"); b.Property<DateTime?>("LastEmailChangeDate") .HasColumnType("datetime(6)"); b.Property<DateTime?>("LastFailedLoginDate") .HasColumnType("datetime(6)"); b.Property<DateTime?>("LastKdfChangeDate") .HasColumnType("datetime(6)"); b.Property<DateTime?>("LastKeyRotationDate") .HasColumnType("datetime(6)"); b.Property<DateTime?>("LastPasswordChangeDate") .HasColumnType("datetime(6)"); b.Property<string>("LicenseKey") .HasMaxLength(100) .HasColumnType("varchar(100)"); b.Property<string>("MasterPassword") .HasMaxLength(300) .HasColumnType("varchar(300)"); b.Property<string>("MasterPasswordHint") .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<short?>("MaxStorageGb") .HasColumnType("smallint"); b.Property<string>("Name") .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<bool>("Premium") .HasColumnType("tinyint(1)"); b.Property<DateTime?>("PremiumExpirationDate") .HasColumnType("datetime(6)"); b.Property<string>("PrivateKey") .HasColumnType("longtext"); b.Property<string>("PublicKey") .HasColumnType("longtext"); b.Property<string>("ReferenceData") .HasColumnType("longtext"); b.Property<DateTime?>("RenewalReminderDate") .HasColumnType("datetime(6)"); b.Property<DateTime>("RevisionDate") .HasColumnType("datetime(6)"); b.Property<string>("SecurityStamp") .IsRequired() .HasMaxLength(50) .HasColumnType("varchar(50)"); b.Property<long?>("Storage") .HasColumnType("bigint"); b.Property<string>("TwoFactorProviders") .HasColumnType("longtext"); b.Property<string>("TwoFactorRecoveryCode") .HasMaxLength(32) .HasColumnType("varchar(32)"); b.Property<bool>("UsesKeyConnector") .HasColumnType("tinyint(1)"); b.HasKey("Id"); b.HasIndex("Email") .IsUnique() .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("Premium", "PremiumExpirationDate", "RenewalReminderDate") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("User", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("longtext"); b.Property<bool>("Read") .HasColumnType("tinyint(1)"); b.Property<DateTime>("RevisionDate") .HasColumnType("datetime(6)"); b.Property<bool>("Write") .HasColumnType("tinyint(1)"); b.HasKey("Id") .HasAnnotation("SqlServer:Clustered", true); b.ToTable("AccessPolicy", (string)null); b.HasDiscriminator<string>("Discriminator").HasValue("AccessPolicy"); b.UseTphMappingStrategy(); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ApiKey", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<string>("ClientSecretHash") .HasMaxLength(128) .HasColumnType("varchar(128)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("EncryptedPayload") .HasMaxLength(4000) .HasColumnType("varchar(4000)"); b.Property<DateTime?>("ExpireAt") .HasColumnType("datetime(6)"); b.Property<string>("Key") .HasColumnType("longtext"); b.Property<string>("Name") .HasMaxLength(200) .HasColumnType("varchar(200)"); b.Property<DateTime>("RevisionDate") .HasColumnType("datetime(6)"); b.Property<string>("Scope") .HasMaxLength(4000) .HasColumnType("varchar(4000)"); b.Property<Guid?>("ServiceAccountId") .HasColumnType("char(36)"); b.HasKey("Id") .HasAnnotation("SqlServer:Clustered", true); b.HasIndex("ServiceAccountId") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("ApiKey", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<DateTime?>("DeletedDate") .HasColumnType("datetime(6)"); b.Property<string>("Name") .HasColumnType("longtext"); b.Property<Guid>("OrganizationId") .HasColumnType("char(36)"); b.Property<DateTime>("RevisionDate") .HasColumnType("datetime(6)"); b.HasKey("Id") .HasAnnotation("SqlServer:Clustered", true); b.HasIndex("DeletedDate") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("OrganizationId") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Project", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<DateTime?>("DeletedDate") .HasColumnType("datetime(6)"); b.Property<string>("Key") .HasColumnType("longtext"); b.Property<string>("Note") .HasColumnType("longtext"); b.Property<Guid>("OrganizationId") .HasColumnType("char(36)"); b.Property<DateTime>("RevisionDate") .HasColumnType("datetime(6)"); b.Property<string>("Value") .HasColumnType("longtext"); b.HasKey("Id") .HasAnnotation("SqlServer:Clustered", true); b.HasIndex("DeletedDate") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("OrganizationId") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Secret", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("Name") .HasColumnType("longtext"); b.Property<Guid>("OrganizationId") .HasColumnType("char(36)"); b.Property<DateTime>("RevisionDate") .HasColumnType("datetime(6)"); b.HasKey("Id") .HasAnnotation("SqlServer:Clustered", true); b.HasIndex("OrganizationId") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("ServiceAccount", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Cipher", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<string>("Attachments") .HasColumnType("longtext"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("Data") .HasColumnType("longtext"); b.Property<DateTime?>("DeletedDate") .HasColumnType("datetime(6)"); b.Property<string>("Favorites") .HasColumnType("longtext"); b.Property<string>("Folders") .HasColumnType("longtext"); b.Property<string>("Key") .HasColumnType("longtext"); b.Property<Guid?>("OrganizationId") .HasColumnType("char(36)"); b.Property<byte?>("Reprompt") .HasColumnType("tinyint unsigned"); b.Property<DateTime>("RevisionDate") .HasColumnType("datetime(6)"); b.Property<byte>("Type") .HasColumnType("tinyint unsigned"); b.Property<Guid?>("UserId") .HasColumnType("char(36)"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.HasIndex("UserId"); b.ToTable("Cipher", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Folder", b => { b.Property<Guid>("Id") .HasColumnType("char(36)"); b.Property<DateTime>("CreationDate") .HasColumnType("datetime(6)"); b.Property<string>("Name") .HasColumnType("longtext"); b.Property<DateTime>("RevisionDate") .HasColumnType("datetime(6)"); b.Property<Guid>("UserId") .HasColumnType("char(36)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("Folder", (string)null); }); modelBuilder.Entity("ProjectSecret", b => { b.Property<Guid>("ProjectsId") .HasColumnType("char(36)"); b.Property<Guid>("SecretsId") .HasColumnType("char(36)"); b.HasKey("ProjectsId", "SecretsId"); b.HasIndex("SecretsId"); b.ToTable("ProjectSecret"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupProjectAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedProjectId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("char(36)") .HasColumnName("GrantedProjectId"); b.Property<Guid?>("GroupId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("char(36)") .HasColumnName("GroupId"); b.HasIndex("GrantedProjectId"); b.HasIndex("GroupId"); b.HasDiscriminator().HasValue("group_project"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupSecretAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedSecretId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("char(36)") .HasColumnName("GrantedSecretId"); b.Property<Guid?>("GroupId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("char(36)") .HasColumnName("GroupId"); b.HasIndex("GrantedSecretId"); b.HasIndex("GroupId"); b.HasDiscriminator().HasValue("group_secret"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupServiceAccountAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedServiceAccountId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("char(36)") .HasColumnName("GrantedServiceAccountId"); b.Property<Guid?>("GroupId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("char(36)") .HasColumnName("GroupId"); b.HasIndex("GrantedServiceAccountId"); b.HasIndex("GroupId"); b.HasDiscriminator().HasValue("group_service_account"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccountProjectAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedProjectId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("char(36)") .HasColumnName("GrantedProjectId"); b.Property<Guid?>("ServiceAccountId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("char(36)") .HasColumnName("ServiceAccountId"); b.HasIndex("GrantedProjectId"); b.HasIndex("ServiceAccountId"); b.HasDiscriminator().HasValue("service_account_project"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccountSecretAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedSecretId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("char(36)") .HasColumnName("GrantedSecretId"); b.Property<Guid?>("ServiceAccountId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("char(36)") .HasColumnName("ServiceAccountId"); b.HasIndex("GrantedSecretId"); b.HasIndex("ServiceAccountId"); b.HasDiscriminator().HasValue("service_account_secret"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserProjectAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedProjectId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("char(36)") .HasColumnName("GrantedProjectId"); b.Property<Guid?>("OrganizationUserId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("char(36)") .HasColumnName("OrganizationUserId"); b.HasIndex("GrantedProjectId"); b.HasIndex("OrganizationUserId"); b.HasDiscriminator().HasValue("user_project"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserSecretAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedSecretId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("char(36)") .HasColumnName("GrantedSecretId"); b.Property<Guid?>("OrganizationUserId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("char(36)") .HasColumnName("OrganizationUserId"); b.HasIndex("GrantedSecretId"); b.HasIndex("OrganizationUserId"); b.HasDiscriminator().HasValue("user_secret"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserServiceAccountAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedServiceAccountId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("char(36)") .HasColumnName("GrantedServiceAccountId"); b.Property<Guid?>("OrganizationUserId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("char(36)") .HasColumnName("OrganizationUserId"); b.HasIndex("GrantedServiceAccountId"); b.HasIndex("OrganizationUserId"); b.HasDiscriminator().HasValue("user_service_account"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Policy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("Policies") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.ProviderOrganization", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany() .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", "Provider") .WithMany() .HasForeignKey("ProviderId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); b.Navigation("Provider"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.ProviderUser", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", "Provider") .WithMany() .HasForeignKey("ProviderId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany() .HasForeignKey("UserId"); b.Navigation("Provider"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.AuthRequest", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany() .HasForeignKey("OrganizationId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.Device", "ResponseDevice") .WithMany() .HasForeignKey("ResponseDeviceId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); b.Navigation("ResponseDevice"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.EmergencyAccess", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "Grantee") .WithMany() .HasForeignKey("GranteeId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "Grantor") .WithMany() .HasForeignKey("GrantorId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Grantee"); b.Navigation("Grantor"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.SsoConfig", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("SsoConfigs") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.SsoUser", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("SsoUsers") .HasForeignKey("OrganizationId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany("SsoUsers") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.WebAuthnCredential", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Billing.Models.ProviderInvoiceItem", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", "Provider") .WithMany() .HasForeignKey("ProviderId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Provider"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Billing.Models.ProviderPlan", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", "Provider") .WithMany() .HasForeignKey("ProviderId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Provider"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Collection", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("Collections") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionCipher", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Vault.Models.Cipher", "Cipher") .WithMany("CollectionCiphers") .HasForeignKey("CipherId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.Models.Collection", "Collection") .WithMany("CollectionCiphers") .HasForeignKey("CollectionId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Cipher"); b.Navigation("Collection"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionGroup", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Models.Collection", "Collection") .WithMany("CollectionGroups") .HasForeignKey("CollectionId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group") .WithMany() .HasForeignKey("GroupId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Collection"); b.Navigation("Group"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionUser", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Models.Collection", "Collection") .WithMany("CollectionUsers") .HasForeignKey("CollectionId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser") .WithMany("CollectionUsers") .HasForeignKey("OrganizationUserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Collection"); b.Navigation("OrganizationUser"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Device", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Group", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("Groups") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.GroupUser", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group") .WithMany("GroupUsers") .HasForeignKey("GroupId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser") .WithMany("GroupUsers") .HasForeignKey("OrganizationUserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Group"); b.Navigation("OrganizationUser"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationApiKey", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("ApiKeys") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationConnection", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("Connections") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationDomain", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("Domains") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationSponsorship", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "SponsoredOrganization") .WithMany() .HasForeignKey("SponsoredOrganizationId"); b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "SponsoringOrganization") .WithMany() .HasForeignKey("SponsoringOrganizationId"); b.Navigation("SponsoredOrganization"); b.Navigation("SponsoringOrganization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("OrganizationUsers") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany("OrganizationUsers") .HasForeignKey("UserId"); b.Navigation("Organization"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Send", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany() .HasForeignKey("OrganizationId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany() .HasForeignKey("UserId"); b.Navigation("Organization"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Transaction", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("Transactions") .HasForeignKey("OrganizationId"); b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", "Provider") .WithMany() .HasForeignKey("ProviderId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany("Transactions") .HasForeignKey("UserId"); b.Navigation("Organization"); b.Navigation("Provider"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ApiKey", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "ServiceAccount") .WithMany() .HasForeignKey("ServiceAccountId"); b.Navigation("ServiceAccount"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany() .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany() .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany() .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Cipher", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("Ciphers") .HasForeignKey("OrganizationId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany("Ciphers") .HasForeignKey("UserId"); b.Navigation("Organization"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Folder", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany("Folders") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("User"); }); modelBuilder.Entity("ProjectSecret", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", null) .WithMany() .HasForeignKey("ProjectsId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", null) .WithMany() .HasForeignKey("SecretsId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupProjectAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", "GrantedProject") .WithMany("GroupAccessPolicies") .HasForeignKey("GrantedProjectId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group") .WithMany() .HasForeignKey("GroupId") .OnDelete(DeleteBehavior.Cascade); b.Navigation("GrantedProject"); b.Navigation("Group"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupSecretAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", "GrantedSecret") .WithMany("GroupAccessPolicies") .HasForeignKey("GrantedSecretId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group") .WithMany() .HasForeignKey("GroupId") .OnDelete(DeleteBehavior.Cascade); b.Navigation("GrantedSecret"); b.Navigation("Group"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupServiceAccountAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "GrantedServiceAccount") .WithMany("GroupAccessPolicies") .HasForeignKey("GrantedServiceAccountId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group") .WithMany() .HasForeignKey("GroupId") .OnDelete(DeleteBehavior.Cascade); b.Navigation("GrantedServiceAccount"); b.Navigation("Group"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccountProjectAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", "GrantedProject") .WithMany("ServiceAccountAccessPolicies") .HasForeignKey("GrantedProjectId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "ServiceAccount") .WithMany() .HasForeignKey("ServiceAccountId"); b.Navigation("GrantedProject"); b.Navigation("ServiceAccount"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccountSecretAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", "GrantedSecret") .WithMany("ServiceAccountAccessPolicies") .HasForeignKey("GrantedSecretId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "ServiceAccount") .WithMany() .HasForeignKey("ServiceAccountId"); b.Navigation("GrantedSecret"); b.Navigation("ServiceAccount"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserProjectAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", "GrantedProject") .WithMany("UserAccessPolicies") .HasForeignKey("GrantedProjectId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser") .WithMany() .HasForeignKey("OrganizationUserId"); b.Navigation("GrantedProject"); b.Navigation("OrganizationUser"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserSecretAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", "GrantedSecret") .WithMany("UserAccessPolicies") .HasForeignKey("GrantedSecretId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser") .WithMany() .HasForeignKey("OrganizationUserId"); b.Navigation("GrantedSecret"); b.Navigation("OrganizationUser"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserServiceAccountAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "GrantedServiceAccount") .WithMany("UserAccessPolicies") .HasForeignKey("GrantedServiceAccountId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser") .WithMany() .HasForeignKey("OrganizationUserId"); b.Navigation("GrantedServiceAccount"); b.Navigation("OrganizationUser"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", b => { b.Navigation("ApiKeys"); b.Navigation("Ciphers"); b.Navigation("Collections"); b.Navigation("Connections"); b.Navigation("Domains"); b.Navigation("Groups"); b.Navigation("OrganizationUsers"); b.Navigation("Policies"); b.Navigation("SsoConfigs"); b.Navigation("SsoUsers"); b.Navigation("Transactions"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Collection", b => { b.Navigation("CollectionCiphers"); b.Navigation("CollectionGroups"); b.Navigation("CollectionUsers"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Group", b => { b.Navigation("GroupUsers"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", b => { b.Navigation("CollectionUsers"); b.Navigation("GroupUsers"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.User", b => { b.Navigation("Ciphers"); b.Navigation("Folders"); b.Navigation("OrganizationUsers"); b.Navigation("SsoUsers"); b.Navigation("Transactions"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", b => { b.Navigation("GroupAccessPolicies"); b.Navigation("ServiceAccountAccessPolicies"); b.Navigation("UserAccessPolicies"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", b => { b.Navigation("GroupAccessPolicies"); b.Navigation("ServiceAccountAccessPolicies"); b.Navigation("UserAccessPolicies"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", b => { b.Navigation("GroupAccessPolicies"); b.Navigation("UserAccessPolicies"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Cipher", b => { b.Navigation("CollectionCiphers"); }); #pragma warning restore 612, 618 } } }
ProviderInvoiceItem
csharp
jasontaylordev__CleanArchitecture
src/Application/TodoItems/Commands/CreateTodoItem/CreateTodoItemCommandValidator.cs
{ "start": 77, "end": 311 }
public class ____ : AbstractValidator<CreateTodoItemCommand> { public CreateTodoItemCommandValidator() { RuleFor(v => v.Title) .MaximumLength(200) .NotEmpty(); } }
CreateTodoItemCommandValidator
csharp
ServiceStack__ServiceStack
ServiceStack.Blazor/tests/UI.Gallery/Gallery/MyApp/ServiceModel/Talent.cs
{ "start": 4659, "end": 5352 }
public class ____ : AuditBase { [AutoIncrement] public int Id { get; set; } [IntlRelativeTime] public DateTime BookingTime { get; set; } [References(typeof(JobApplication))] public int JobApplicationId { get; set; } [References(typeof(AppUser))] public string AppUserId { get; set; } [Reference, Format(FormatMethods.Hidden)] public AppUser AppUser { get; set; } [ReferenceField(typeof(JobApplication), nameof(JobApplicationId))] public JobApplicationStatus? ApplicationStatus { get; set; } [Input(Type = "textarea"), FieldCss(Field = "col-span-12 text-center")] public string Notes { get; set; } } [Icon(Svg = Icons.Offer)]
Interview
csharp
EventStore__EventStore
src/KurrentDB.Security.EncryptionAtRest/MasterKeySources/IMasterKeySource.cs
{ "start": 282, "end": 355 }
public interface ____ { public string Name { get; } // the
IMasterKeySource
csharp
microsoft__semantic-kernel
dotnet/src/Experimental/Process.IntegrationTestHost.Dapr/HealthActor.cs
{ "start": 264, "end": 633 }
public class ____ : Actor, IHealthActor { /// <summary> /// Initializes a new instance of the <see cref="HealthActor"/> class. /// </summary> /// <param name="host"></param> public HealthActor(ActorHost host) : base(host) { } /// <inheritdoc /> public Task HealthCheckAsync() { return Task.CompletedTask; } }
HealthActor
csharp
dotnet__maui
src/Controls/samples/Controls.Sample/Pages/Controls/CarouselViewGalleries/EmptyCarouselGallery.xaml.cs
{ "start": 366, "end": 584 }
public partial class ____ : ContentPage { public EmptyCarouselGallery() { InitializeComponent(); BindingContext = new EmptyCarouselGalleryViewModel(); } } [Preserve(AllMembers = true)]
EmptyCarouselGallery
csharp
ServiceStack__ServiceStack
ServiceStack.Text/tests/ServiceStack.Text.Tests/AttributeTests.cs
{ "start": 9117, "end": 9196 }
public class ____ { } [RouteDefault("/path")]
TypeIdWithMultipleAttributes
csharp
unoplatform__uno
src/Uno.UI/UI/Xaml/Shapes/Polyline.skia.cs
{ "start": 129, "end": 829 }
public partial class ____ : Shape { /// <inheritdoc /> protected override Size MeasureOverride(Size availableSize) => MeasureAbsoluteShape(availableSize, GetPath()); /// <inheritdoc /> protected override Size ArrangeOverride(Size finalSize) => ArrangeAbsoluteShape(finalSize, GetPath()); private SkiaGeometrySource2D GetPath() { var points = Points; if (points == null || points.Count <= 1) { return null; } var streamGeometry = GeometryHelper.Build(c => { c.BeginFigure(points[0], true); for (var i = 1; i < points.Count; i++) { c.LineTo(points[i], true, false); } }); return streamGeometry.GetGeometrySource2D(); } } }
Polyline
csharp
microsoft__garnet
libs/server/Custom/ExpandableMap.cs
{ "start": 604, "end": 8088 }
internal struct ____<T> { /// <summary> /// Reader-writer lock for the underlying item array pointer /// </summary> internal SingleWriterMultiReaderLock mapLock = new(); /// <summary> /// The underlying array containing the items /// </summary> internal T[] Map { get; private set; } /// <summary> /// The actual size of the map /// i.e. the max index of an inserted item + 1 (not the size of the underlying array) /// </summary> internal int ActualSize => actualSize; // The actual size of the map int actualSize; // The last requested index for assignment int currIndex = -1; // Initial array size readonly int minSize; // Value of min item ID readonly int minId; // Value of max item ID readonly int maxSize; /// <summary> /// Creates a new instance of ExpandableMap /// </summary> /// <param name="minSize">Initial size of underlying array</param> /// <param name="minId">The minimal item ID value</param> /// <param name="maxId">The maximal item ID value (can be smaller than minId for descending order of IDs)</param> public ExpandableMap(int minSize, int minId, int maxId) { Debug.Assert(maxId > minId); this.Map = null; this.minSize = minSize; this.minId = minId; this.maxSize = maxId - minId + 1; } /// <summary> /// Try to get item by ID /// </summary> /// <param name="id">Item ID</param> /// <param name="value">Item value</param> /// <returns>True if item found</returns> public bool TryGetValue(int id, out T value) { value = default; var idx = id - minId; if (idx < 0 || idx >= ActualSize) return false; value = Map[idx]; return true; } /// <summary> /// Try to set item by ID /// </summary> /// <param name="id">Item ID</param> /// <param name="value">Item value</param> /// <returns>True if assignment succeeded</returns> public bool TrySetValueByRef(int id, ref T value) { // Try to perform set without taking a write lock first mapLock.ReadLock(); try { // Try to set value without expanding map if (this.TrySetValueUnsafe(id, ref value, noExpansion: true)) return true; } finally { mapLock.ReadUnlock(); } mapLock.WriteLock(); try { // Try to set value with expanding the map, if needed return this.TrySetValueUnsafe(id, ref value, noExpansion: false); } finally { mapLock.WriteUnlock(); } } /// <summary> /// Try to set item by ID /// </summary> /// <param name="id">Item ID</param> /// <param name="value">Item value</param> /// <returns>True if assignment succeeded</returns> public bool TrySetValue(int id, T value) { // Try to perform set without taking a write lock first mapLock.ReadLock(); try { // Try to set value without expanding map if (this.TrySetValueUnsafe(id, ref value, noExpansion: true)) return true; } finally { mapLock.ReadUnlock(); } mapLock.WriteLock(); try { // Try to set value with expanding the map, if needed return this.TrySetValueUnsafe(id, ref value, noExpansion: false); } finally { mapLock.WriteUnlock(); } } /// <summary> /// Checks if ID is mapped to a value in underlying array /// </summary> /// <param name="id">Item ID</param> /// <returns>True if ID exists</returns> public bool Exists(int id) { var idx = id - minId; return idx >= 0 && idx < ActualSize; } /// <summary> /// Find first ID in map of item that fulfills specified predicate /// </summary> /// <param name="predicate">Predicate</param> /// <param name="id">ID if found, otherwise -1</param> /// <returns>True if ID found</returns> public bool TryGetFirstId(Func<T, bool> predicate, out int id) { id = -1; var actualSizeSnapshot = ActualSize; var mapSnapshot = Map; for (var i = 0; i < actualSizeSnapshot; i++) { if (predicate(mapSnapshot[i])) { id = minId + i; return true; } } return false; } /// <summary> /// Get next item ID for assignment with atomic incrementation of underlying index /// </summary> /// <param name="id">Item ID</param> /// <returns>True if item ID available</returns> public bool TryGetNextId(out int id) { id = -1; var nextIdx = Interlocked.Increment(ref currIndex); if (nextIdx >= maxSize) return false; id = minId + nextIdx; return true; } /// <summary> /// Try to update the actual size of the map based on the inserted item ID /// </summary> /// <param name="id">The inserted item ID</param> /// <returns>True if actual size should be updated (or was updated if noUpdate is false)</returns> private bool TryUpdateActualSize(int id) { var idx = id - minId; // Should not update the size if the index is out of bounds // or if index is smaller than the current actual size if (idx < 0 || idx < ActualSize || idx >= maxSize) return false; var oldActualSize = ActualSize; var updatedActualSize = idx + 1; while (oldActualSize < updatedActualSize) { var currActualSize = Interlocked.CompareExchange(ref actualSize, updatedActualSize, oldActualSize); if (currActualSize == oldActualSize) break; oldActualSize = currActualSize; } return true; } /// <summary> /// Try to set item by ID /// This method should only be called from a thread-safe context /// </summary> /// <param name="id">Item ID</param> /// <param name="value">Item value</param> /// <param name="noExpansion">True if should not attempt to expand the underlying array</param> /// <returns>True if assignment succeeded</returns> internal bool TrySetValueUnsafe(int id, ref T value, bool noExpansion) { var idx = id - minId; if (idx < 0 || idx >= maxSize) return false; // If index within array bounds, set item if (Map != null && idx < Map.Length) { // This
ExpandableMap
csharp
CommunityToolkit__Maui
src/CommunityToolkit.Maui/Behaviors/Validators/TextValidationBehavior.shared.cs
{ "start": 513, "end": 2160 }
public enum ____ { /// <summary>No text decoration will be applied.</summary> None = 0, /// <summary><see cref="string.TrimStart()"/> is applied on the value prior to validation.</summary> TrimStart = 1, /// <summary><see cref="string.TrimEnd()"/> is applied on the value prior to validation.</summary> TrimEnd = 2, /// <summary><see cref="string.Trim()"/> is applied on the value prior to validation.</summary> Trim = TrimStart | TrimEnd, /// <summary>If <see cref="ValidationBehavior.Value"/> is null, replace the value with <see cref="string.Empty"/></summary> NullToEmpty = 4, /// <summary>Excessive white space is removed from <see cref="ValidationBehavior.Value"/> prior to validation. I.e. I.e. "Hello World" will become "Hello World". This applies to whitespace found anywhere.</summary> NormalizeWhiteSpace = 8 } /// <summary> /// The <see cref="TextValidationBehavior"/> is a behavior that allows the user to validate a given text depending on specified parameters. By adding this behavior to an <see cref="InputView"/> inherited control (i.e. <see cref="Entry"/>) it can be styled differently depending on whether a valid or an invalid text value is provided. It offers various built-in checks such as checking for a certain length or whether or not the input value matches a specific regular expression. Additional properties handling validation are inherited from <see cref="ValidationBehavior"/>. /// </summary> [RequiresUnreferencedCode($"{nameof(TextValidationBehavior)} is not trim safe because it uses bindings with string paths.")] [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)]
TextDecorationFlags
csharp
AutoMapper__AutoMapper
src/UnitTests/CollectionMapping.cs
{ "start": 25278, "end": 25428 }
public class ____ { public int Id { get; set; } public HashSet<Detail> Details { get; set; } }
MasterWithNoExistingCollection
csharp
CommunityToolkit__dotnet
src/CommunityToolkit.Mvvm/Messaging/IMessengerExtensions.Observables.cs
{ "start": 4033, "end": 5790 }
private sealed class ____ : IRecipient<TMessage>, IDisposable { /// <summary> /// The <see cref="IMessenger"/> instance to use to register the recipient. /// </summary> private readonly IMessenger messenger; /// <summary> /// The target <see cref="IObserver{T}"/> instance currently in use. /// </summary> private readonly IObserver<TMessage> observer; /// <summary> /// Creates a new <see cref="Recipient"/> instance with the specified parameters. /// </summary> /// <param name="messenger">The <see cref="IMessenger"/> instance to use to register the recipient.</param> /// <param name="observer">The <see cref="IObserver{T}"/> instance to use to create the recipient for.</param> public Recipient(IMessenger messenger, IObserver<TMessage> observer) { this.messenger = messenger; this.observer = observer; messenger.Register(this); } /// <inheritdoc/> public void Receive(TMessage message) { this.observer.OnNext(message); } /// <inheritdoc/> public void Dispose() { this.messenger.Unregister<TMessage>(this); } } } /// <summary> /// An <see cref="IObservable{T}"/> implementations for a given pair of message and token types. /// </summary> /// <typeparam name="TMessage">The type of messages to listen to.</typeparam> /// <typeparam name="TToken">The type of token to identify what channel to use to receive messages.</typeparam>
Recipient
csharp
EventStore__EventStore
src/KurrentDB.Core.Tests/ClientAPI/UserManagement/TestWithUser.cs
{ "start": 324, "end": 704 }
public abstract class ____<TLogFormat, TStreamId> : TestWithNode<TLogFormat, TStreamId> { protected string _username = Guid.NewGuid().ToString(); public override async Task TestFixtureSetUp() { await base.TestFixtureSetUp(); await _manager.CreateUserAsync(_username, "name", new[] { "foo", "admins" }, "password", new UserCredentials("admin", "changeit")); } }
TestWithUser
csharp
MassTransit__MassTransit
tests/MassTransit.Analyzers.Tests/MessageContractAnalyzerWithVariableUnitTest.cs
{ "start": 4792, "end": 5819 }
class ____ { static async Task Main() { await PublishNotification<IProjectionUpdatedNotification>(Guid.Empty); } private static Task PublishNotification<T>(Guid streamId) where T : class, INotification { var bus = Bus.Factory.CreateUsingInMemory(cfg => { }); var msg = new { }; return bus.Publish<T>(msg); } } } "; var expected = new DiagnosticResult { Id = "MCA0003", Message = "Anonymous type is missing properties that are in the message contract 'INotification'. The following properties are missing: StreamId.", Severity = DiagnosticSeverity.Info, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 29, 23) } }; VerifyCSharpDiagnostic(test, expected); var fixtest = Usings + @" namespace ConsoleApplication1 {
Program
csharp
Cysharp__ZLogger
src/ZLogger/KeyNameMutator.cs
{ "start": 270, "end": 1410 }
public static class ____ { /// <summary> /// Returns the last member name of the source. /// </summary> public static readonly IKeyNameMutator LastMemberName = new LastMemberNameMutator(); /// <summary> /// The first character converted to lowercase. /// </summary> public static readonly IKeyNameMutator LowerFirstCharacter = new LowerFirstCharacterMutator(); /// <summary> /// The first character converted to uppercase. /// </summary> public static readonly IKeyNameMutator UpperFirstCharacter = new UpperFirstCharacterMutator(); /// <summary> /// Returns the last member name of the source with the first character converted to lowercase. /// </summary> public static readonly IKeyNameMutator LastMemberNameLowerFirstCharacter = new CombineMutator(LastMemberName, LowerFirstCharacter); /// <summary> /// Returns the last member name of the source with the first character converted to uppercase. /// </summary> public static readonly IKeyNameMutator LastMemberNameUpperFirstCharacter = new CombineMutator(LastMemberName, UpperFirstCharacter); }
KeyNameMutator
csharp
bitwarden__server
test/Infrastructure.IntegrationTest/Services/IMigrationTesterService.cs
{ "start": 203, "end": 549 }
interface ____ responsible for migration execution logic, /// and handling migration history to ensure that migrations can be tested independently and reliably. /// </summary> /// <remarks> /// Each implementation should receive the migration name as a parameter in the constructor /// to specify which migration is to be applied. /// </remarks>
are
csharp
dotnet__aspnetcore
src/Http/Http.Extensions/test/RequestDelegateGenerator/CompileTimeCreationTests.cs
{ "start": 26976, "end": 27393 }
public static class ____ { public static IServiceProvider Map(this IServiceProvider app, int id, Delegate requestDelegate) { return app; } public static IEndpointRouteBuilder Map(this IEndpointRouteBuilder app, int id, Delegate requestDelegate) { return app; } } } namespace Microsoft.AspNetCore.Builder {
EndpointRouteBuilderExtensions
csharp
icsharpcode__ILSpy
ICSharpCode.Decompiler/IL/Instructions/DynamicInstructions.cs
{ "start": 16720, "end": 17731 }
partial class ____ { public IReadOnlyList<CSharpArgumentInfo> ArgumentInfo { get; } public DynamicInvokeInstruction(CSharpBinderFlags binderFlags, IType? context, CSharpArgumentInfo[] argumentInfo, ILInstruction[] arguments) : base(OpCode.DynamicInvokeInstruction, binderFlags, context) { ArgumentInfo = argumentInfo; Arguments = new InstructionCollection<ILInstruction>(this, 0); Arguments.AddRange(arguments); } public override void WriteTo(ITextOutput output, ILAstWritingOptions options) { WriteILRange(output, options); output.Write(OpCode); WriteBinderFlags(output, options); output.Write(' '); WriteArgumentList(output, options, Arguments.Zip(ArgumentInfo)); } public override StackType ResultType => StackType.O; public override CSharpArgumentInfo GetArgumentInfoOfChild(int index) { if (index < 0 || index >= ArgumentInfo.Count) throw new ArgumentOutOfRangeException(nameof(index)); return ArgumentInfo[index]; } }
DynamicInvokeInstruction
csharp
microsoft__garnet
libs/server/AOF/AofHeader.cs
{ "start": 197, "end": 1748 }
struct ____ { // Important: Update version number whenever any of the following change: // * Layout, size, contents of this struct // * Any of the AofEntryType or AofStoreType enums' existing value mappings // * SpanByte format or header const byte AofHeaderVersion = 2; /// <summary> /// Version of AOF /// </summary> [FieldOffset(0)] public byte aofHeaderVersion; /// <summary> /// Padding, for alignment and future use /// </summary> [FieldOffset(1)] public byte padding; /// <summary> /// Type of operation /// </summary> [FieldOffset(2)] public AofEntryType opType; /// <summary> /// Procedure ID /// </summary> [FieldOffset(3)] public byte procedureId; /// <summary> /// Store version /// </summary> [FieldOffset(4)] public long storeVersion; /// <summary> /// Session ID /// </summary> [FieldOffset(12)] public int sessionID; /// <summary> /// Unsafe truncate log (used with FLUSH command) /// </summary> [FieldOffset(1)] public byte unsafeTruncateLog; /// <summary> /// Database ID (used with FLUSH command) /// </summary> [FieldOffset(3)] public byte databaseId; public AofHeader() { this.aofHeaderVersion = AofHeaderVersion; } } }
AofHeader
csharp
RicoSuter__NSwag
src/NSwag.Core.Tests/SwaggerResponseTests.cs
{ "start": 48, "end": 968 }
public class ____ { [Theory] [InlineData("application/octet-stream", true)] [InlineData("undefined", true)] [InlineData("text/plain", false)] [InlineData("application/json", false)] [InlineData("application/vnd.model+json", false)] [InlineData("*/*", true)] [InlineData("application/json;charset=UTF-8", false)] public void When_response_contains_produces_detect_if_binary_response(string contentType, bool expectsBinary) { // Arrange var response = new OpenApiResponse(); var operation = new OpenApiOperation(); operation.Produces = [contentType]; operation.Responses.Add("200", response); // Act var isBinary = response.IsBinary(operation); // Assert Assert.Equal(expectsBinary, isBinary); } } }
SwaggerResponseTests
csharp
Cysharp__MemoryPack
src/MemoryPack.Core/Formatters/CollectionFormatters.cs
{ "start": 9862, "end": 11272 }
public sealed class ____<T> : MemoryPackFormatter<LinkedList<T?>> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, scoped ref LinkedList<T?>? value) { if (value == null) { writer.WriteNullCollectionHeader(); return; } var formatter = writer.GetFormatter<T?>(); writer.WriteCollectionHeader(value.Count); foreach (var item in value) { var v = item; formatter.Serialize(ref writer, ref v); } } [Preserve] public override void Deserialize(ref MemoryPackReader reader, scoped ref LinkedList<T?>? value) { if (!reader.TryReadCollectionHeader(out var length)) { value = null; return; } if (value == null) { value = new LinkedList<T?>(); } else { value.Clear(); } var formatter = reader.GetFormatter<T?>(); for (int i = 0; i < length; i++) { T? v = default; formatter.Deserialize(ref reader, ref v); value.AddLast(v); } } } [Preserve]
LinkedListFormatter
csharp
dotnetcore__Util
src/Util.Ui.NgZorro/Components/Menus/Builders/MenuGroupBuilder.cs
{ "start": 277, "end": 1618 }
public class ____ : AngularTagBuilder { /// <summary> /// 配置 /// </summary> private readonly Config _config; /// <summary> /// 初始化菜单组标签生成器 /// </summary> /// <param name="config">配置</param> public MenuGroupBuilder( Config config ) : base( config,"li" ) { _config = config; base.Attribute( "nz-menu-group" ); } /// <summary> /// 配置标题 /// </summary> public MenuGroupBuilder Title() { SetTitle( _config.GetValue( UiConst.Title ) ); AttributeIfNotEmpty( "[nzTitle]", _config.GetValue( AngularConst.BindTitle ) ); return this; } /// <summary> /// 设置标题 /// </summary> private void SetTitle( string value ) { var options = NgZorroOptionsService.GetOptions(); if ( options.EnableI18n ) { this.AttributeByI18n( "[nzTitle]", value ); return; } AttributeIfNotEmpty( "nzTitle", value ); } /// <summary> /// 配置 /// </summary> public override void Config() { base.Config(); Title(); } /// <summary> /// 配置内容元素 /// </summary> protected override void ConfigContent( Config config ) { var ulBuilder = new UlBuilder(); SetContent( ulBuilder ); _config.Content.AppendTo( ulBuilder ); } }
MenuGroupBuilder
csharp
EventStore__EventStore
src/KurrentDB.Core/Services/Storage/ReaderIndex/IndexReadStreamResult.cs
{ "start": 325, "end": 2782 }
struct ____ { internal static readonly EventRecord[] EmptyRecords = []; public readonly long FromEventNumber; public readonly int MaxCount; public readonly ReadStreamResult Result; public readonly long NextEventNumber; public readonly long LastEventNumber; public readonly bool IsEndOfStream; public readonly EventRecord[] Records; public readonly StreamMetadata Metadata; /// <summary> /// Failure Constructor /// </summary> public IndexReadStreamResult(long fromEventNumber, int maxCount, ReadStreamResult result, StreamMetadata metadata, long lastEventNumber) { if (result == ReadStreamResult.Success) throw new ArgumentException($"Wrong ReadStreamResult provided for failure constructor: {result}.", nameof(result)); FromEventNumber = fromEventNumber; MaxCount = maxCount; Result = result; NextEventNumber = -1; LastEventNumber = lastEventNumber; IsEndOfStream = true; Records = EmptyRecords; Metadata = metadata; } /// <summary> /// Success Constructor /// </summary> /// <param name="fromEventNumber"> /// EventNumber that the read starts from. Usually as specified in the request. /// Sometimes resolved (e.g. from EndOfStream to the actual lastEventNumber) /// This is not returned to the client when reading forwards, only backwards. /// </param> /// <param name="maxCount">The maximum number of events requested</param> /// <param name="records"></param> /// <param name="metadata"></param> /// <param name="nextEventNumber">The event number to start the next _request_</param> /// <param name="lastEventNumber">The last event number of the _stream_</param> /// <param name="isEndOfStream"></param> public IndexReadStreamResult( long fromEventNumber, int maxCount, EventRecord[] records, StreamMetadata metadata, long nextEventNumber, long lastEventNumber, bool isEndOfStream) { FromEventNumber = fromEventNumber; MaxCount = maxCount; Result = ReadStreamResult.Success; Records = Ensure.NotNull(records); Metadata = metadata; NextEventNumber = nextEventNumber; LastEventNumber = lastEventNumber; IsEndOfStream = isEndOfStream; } public override string ToString() { return $"FromEventNumber: {FromEventNumber}, Maxcount: {MaxCount}, Result: {Result}, Record count: {Records.Length}, Metadata: {Metadata}, " + $"NextEventNumber: {NextEventNumber}, LastEventNumber: {LastEventNumber}, IsEndOfStream: {IsEndOfStream}"; } }
IndexReadStreamResult
csharp
bitwarden__server
util/PostgresMigrations/Migrations/20241004154531_AddClientOrganizationMigrationRecordTable.Designer.cs
{ "start": 531, "end": 109890 }
partial class ____ { /// <inheritdoc /> protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Npgsql:CollationDefinition:postgresIndetermanisticCollation", "en-u-ks-primary,en-u-ks-primary,icu,False") .HasAnnotation("ProductVersion", "8.0.8") .HasAnnotation("Relational:MaxIdentifierLength", 63); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<bool>("AllowAdminAccessToAllCollectionItems") .HasColumnType("boolean") .HasDefaultValue(true); b.Property<string>("BillingEmail") .IsRequired() .HasMaxLength(256) .HasColumnType("character varying(256)"); b.Property<string>("BusinessAddress1") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("BusinessAddress2") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("BusinessAddress3") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("BusinessCountry") .HasMaxLength(2) .HasColumnType("character varying(2)"); b.Property<string>("BusinessName") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("BusinessTaxNumber") .HasMaxLength(30) .HasColumnType("character varying(30)"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<bool>("Enabled") .HasColumnType("boolean"); b.Property<DateTime?>("ExpirationDate") .HasColumnType("timestamp with time zone"); b.Property<byte?>("Gateway") .HasColumnType("smallint"); b.Property<string>("GatewayCustomerId") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("GatewaySubscriptionId") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("Identifier") .HasMaxLength(50) .HasColumnType("character varying(50)") .UseCollation("postgresIndetermanisticCollation"); b.Property<string>("LicenseKey") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property<bool>("LimitCollectionCreation") .HasColumnType("boolean"); b.Property<bool>("LimitCollectionCreationDeletion") .HasColumnType("boolean"); b.Property<bool>("LimitCollectionDeletion") .HasColumnType("boolean"); b.Property<int?>("MaxAutoscaleSeats") .HasColumnType("integer"); b.Property<int?>("MaxAutoscaleSmSeats") .HasColumnType("integer"); b.Property<int?>("MaxAutoscaleSmServiceAccounts") .HasColumnType("integer"); b.Property<short?>("MaxCollections") .HasColumnType("smallint"); b.Property<short?>("MaxStorageGb") .HasColumnType("smallint"); b.Property<string>("Name") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<DateTime?>("OwnersNotifiedOfAutoscaling") .HasColumnType("timestamp with time zone"); b.Property<string>("Plan") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<byte>("PlanType") .HasColumnType("smallint"); b.Property<string>("PrivateKey") .HasColumnType("text"); b.Property<string>("PublicKey") .HasColumnType("text"); b.Property<string>("ReferenceData") .HasColumnType("text"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<int?>("Seats") .HasColumnType("integer"); b.Property<bool>("SelfHost") .HasColumnType("boolean"); b.Property<int?>("SmSeats") .HasColumnType("integer"); b.Property<int?>("SmServiceAccounts") .HasColumnType("integer"); b.Property<byte>("Status") .HasColumnType("smallint"); b.Property<long?>("Storage") .HasColumnType("bigint"); b.Property<string>("TwoFactorProviders") .HasColumnType("text"); b.Property<bool>("Use2fa") .HasColumnType("boolean"); b.Property<bool>("UseApi") .HasColumnType("boolean"); b.Property<bool>("UseCustomPermissions") .HasColumnType("boolean"); b.Property<bool>("UseDirectory") .HasColumnType("boolean"); b.Property<bool>("UseEvents") .HasColumnType("boolean"); b.Property<bool>("UseGroups") .HasColumnType("boolean"); b.Property<bool>("UseKeyConnector") .HasColumnType("boolean"); b.Property<bool>("UsePasswordManager") .HasColumnType("boolean"); b.Property<bool>("UsePolicies") .HasColumnType("boolean"); b.Property<bool>("UseResetPassword") .HasColumnType("boolean"); b.Property<bool>("UseScim") .HasColumnType("boolean"); b.Property<bool>("UseSecretsManager") .HasColumnType("boolean"); b.Property<bool>("UseSso") .HasColumnType("boolean"); b.Property<bool>("UseTotp") .HasColumnType("boolean"); b.Property<bool>("UsersGetPremium") .HasColumnType("boolean"); b.HasKey("Id"); b.HasIndex("Id", "Enabled"); NpgsqlIndexBuilderExtensions.IncludeProperties(b.HasIndex("Id", "Enabled"), new[] { "UseTotp" }); b.ToTable("Organization", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Policy", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Data") .HasColumnType("text"); b.Property<bool>("Enabled") .HasColumnType("boolean"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<byte>("Type") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("OrganizationId") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("OrganizationId", "Type") .IsUnique() .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Policy", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<string>("BillingEmail") .HasColumnType("text"); b.Property<string>("BillingPhone") .HasColumnType("text"); b.Property<string>("BusinessAddress1") .HasColumnType("text"); b.Property<string>("BusinessAddress2") .HasColumnType("text"); b.Property<string>("BusinessAddress3") .HasColumnType("text"); b.Property<string>("BusinessCountry") .HasColumnType("text"); b.Property<string>("BusinessName") .HasColumnType("text"); b.Property<string>("BusinessTaxNumber") .HasColumnType("text"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<bool>("Enabled") .HasColumnType("boolean"); b.Property<byte?>("Gateway") .HasColumnType("smallint"); b.Property<string>("GatewayCustomerId") .HasColumnType("text"); b.Property<string>("GatewaySubscriptionId") .HasColumnType("text"); b.Property<string>("Name") .HasColumnType("text"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<byte>("Status") .HasColumnType("smallint"); b.Property<byte>("Type") .HasColumnType("smallint"); b.Property<bool>("UseEvents") .HasColumnType("boolean"); b.HasKey("Id"); b.ToTable("Provider", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.ProviderOrganization", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Key") .HasColumnType("text"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<Guid>("ProviderId") .HasColumnType("uuid"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Settings") .HasColumnType("text"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.HasIndex("ProviderId"); b.ToTable("ProviderOrganization", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.ProviderUser", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Email") .HasColumnType("text"); b.Property<string>("Key") .HasColumnType("text"); b.Property<string>("Permissions") .HasColumnType("text"); b.Property<Guid>("ProviderId") .HasColumnType("uuid"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<byte>("Status") .HasColumnType("smallint"); b.Property<byte>("Type") .HasColumnType("smallint"); b.Property<Guid?>("UserId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("ProviderId"); b.HasIndex("UserId"); b.ToTable("ProviderUser", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.AuthRequest", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<string>("AccessCode") .HasMaxLength(25) .HasColumnType("character varying(25)"); b.Property<bool?>("Approved") .HasColumnType("boolean"); b.Property<DateTime?>("AuthenticationDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Key") .HasColumnType("text"); b.Property<string>("MasterPasswordHash") .HasColumnType("text"); b.Property<Guid?>("OrganizationId") .HasColumnType("uuid"); b.Property<string>("PublicKey") .HasColumnType("text"); b.Property<string>("RequestDeviceIdentifier") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<byte>("RequestDeviceType") .HasColumnType("smallint"); b.Property<string>("RequestIpAddress") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<DateTime?>("ResponseDate") .HasColumnType("timestamp with time zone"); b.Property<Guid?>("ResponseDeviceId") .HasColumnType("uuid"); b.Property<byte>("Type") .HasColumnType("smallint"); b.Property<Guid>("UserId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.HasIndex("ResponseDeviceId"); b.HasIndex("UserId"); b.ToTable("AuthRequest", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.EmergencyAccess", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Email") .HasMaxLength(256) .HasColumnType("character varying(256)"); b.Property<Guid?>("GranteeId") .HasColumnType("uuid"); b.Property<Guid>("GrantorId") .HasColumnType("uuid"); b.Property<string>("KeyEncrypted") .HasColumnType("text"); b.Property<DateTime?>("LastNotificationDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime?>("RecoveryInitiatedDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<byte>("Status") .HasColumnType("smallint"); b.Property<byte>("Type") .HasColumnType("smallint"); b.Property<int>("WaitTimeDays") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("GranteeId"); b.HasIndex("GrantorId"); b.ToTable("EmergencyAccess", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.Grant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer"); NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id")); b.Property<string>("ClientId") .IsRequired() .HasMaxLength(200) .HasColumnType("character varying(200)"); b.Property<DateTime?>("ConsumedDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Data") .IsRequired() .HasColumnType("text"); b.Property<string>("Description") .HasMaxLength(200) .HasColumnType("character varying(200)"); b.Property<DateTime?>("ExpirationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Key") .IsRequired() .HasMaxLength(200) .HasColumnType("character varying(200)"); b.Property<string>("SessionId") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property<string>("SubjectId") .HasMaxLength(200) .HasColumnType("character varying(200)"); b.Property<string>("Type") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.HasKey("Id") .HasName("PK_Grant") .HasAnnotation("SqlServer:Clustered", true); b.HasIndex("ExpirationDate") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("Key") .IsUnique(); b.ToTable("Grant", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.SsoConfig", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id")); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Data") .HasColumnType("text"); b.Property<bool>("Enabled") .HasColumnType("boolean"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.ToTable("SsoConfig", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.SsoUser", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id")); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("ExternalId") .HasMaxLength(50) .HasColumnType("character varying(50)") .UseCollation("postgresIndetermanisticCollation"); b.Property<Guid?>("OrganizationId") .HasColumnType("uuid"); b.Property<Guid>("UserId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("OrganizationId") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("UserId"); b.HasIndex("OrganizationId", "ExternalId") .IsUnique() .HasAnnotation("SqlServer:Clustered", false); NpgsqlIndexBuilderExtensions.IncludeProperties(b.HasIndex("OrganizationId", "ExternalId"), new[] { "UserId" }); b.HasIndex("OrganizationId", "UserId") .IsUnique() .HasAnnotation("SqlServer:Clustered", false); b.ToTable("SsoUser", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.WebAuthnCredential", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<Guid>("AaGuid") .HasColumnType("uuid"); b.Property<int>("Counter") .HasColumnType("integer"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("CredentialId") .HasMaxLength(256) .HasColumnType("character varying(256)"); b.Property<string>("EncryptedPrivateKey") .HasMaxLength(2000) .HasColumnType("character varying(2000)"); b.Property<string>("EncryptedPublicKey") .HasMaxLength(2000) .HasColumnType("character varying(2000)"); b.Property<string>("EncryptedUserKey") .HasMaxLength(2000) .HasColumnType("character varying(2000)"); b.Property<string>("Name") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("PublicKey") .HasMaxLength(256) .HasColumnType("character varying(256)"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<bool>("SupportsPrf") .HasColumnType("boolean"); b.Property<string>("Type") .HasMaxLength(20) .HasColumnType("character varying(20)"); b.Property<Guid>("UserId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("WebAuthnCredential", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Billing.Models.ClientOrganizationMigrationRecord", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime?>("ExpirationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("GatewayCustomerId") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("GatewaySubscriptionId") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<int?>("MaxAutoscaleSeats") .HasColumnType("integer"); b.Property<short?>("MaxStorageGb") .HasColumnType("smallint"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<byte>("PlanType") .HasColumnType("smallint"); b.Property<Guid>("ProviderId") .HasColumnType("uuid"); b.Property<int>("Seats") .HasColumnType("integer"); b.Property<byte>("Status") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("ProviderId", "OrganizationId") .IsUnique(); b.ToTable("ClientOrganizationMigrationRecord", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Billing.Models.ProviderInvoiceItem", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<int>("AssignedSeats") .HasColumnType("integer"); b.Property<Guid?>("ClientId") .HasColumnType("uuid"); b.Property<string>("ClientName") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<DateTime>("Created") .HasColumnType("timestamp with time zone"); b.Property<string>("InvoiceId") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("InvoiceNumber") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("PlanName") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<Guid>("ProviderId") .HasColumnType("uuid"); b.Property<decimal>("Total") .HasColumnType("numeric"); b.Property<int>("UsedSeats") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("ProviderId"); b.ToTable("ProviderInvoiceItem", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Billing.Models.ProviderPlan", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<int?>("AllocatedSeats") .HasColumnType("integer"); b.Property<byte>("PlanType") .HasColumnType("smallint"); b.Property<Guid>("ProviderId") .HasColumnType("uuid"); b.Property<int?>("PurchasedSeats") .HasColumnType("integer"); b.Property<int?>("SeatMinimum") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("ProviderId"); b.HasIndex("Id", "PlanType") .IsUnique(); b.ToTable("ProviderPlan", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Cache", b => { b.Property<string>("Id") .HasMaxLength(449) .HasColumnType("character varying(449)"); b.Property<DateTime?>("AbsoluteExpiration") .HasColumnType("timestamp with time zone"); b.Property<DateTime>("ExpiresAtTime") .HasColumnType("timestamp with time zone"); b.Property<long?>("SlidingExpirationInSeconds") .HasColumnType("bigint"); b.Property<byte[]>("Value") .IsRequired() .HasColumnType("bytea"); b.HasKey("Id") .HasAnnotation("SqlServer:Clustered", true); b.HasIndex("ExpiresAtTime") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Cache", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Collection", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("ExternalId") .HasMaxLength(300) .HasColumnType("character varying(300)"); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.ToTable("Collection", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionCipher", b => { b.Property<Guid>("CollectionId") .HasColumnType("uuid"); b.Property<Guid>("CipherId") .HasColumnType("uuid"); b.HasKey("CollectionId", "CipherId"); b.HasIndex("CipherId"); b.ToTable("CollectionCipher", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionGroup", b => { b.Property<Guid>("CollectionId") .HasColumnType("uuid"); b.Property<Guid>("GroupId") .HasColumnType("uuid"); b.Property<bool>("HidePasswords") .HasColumnType("boolean"); b.Property<bool>("Manage") .HasColumnType("boolean"); b.Property<bool>("ReadOnly") .HasColumnType("boolean"); b.HasKey("CollectionId", "GroupId"); b.HasIndex("GroupId"); b.ToTable("CollectionGroups"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionUser", b => { b.Property<Guid>("CollectionId") .HasColumnType("uuid"); b.Property<Guid>("OrganizationUserId") .HasColumnType("uuid"); b.Property<bool>("HidePasswords") .HasColumnType("boolean"); b.Property<bool>("Manage") .HasColumnType("boolean"); b.Property<bool>("ReadOnly") .HasColumnType("boolean"); b.HasKey("CollectionId", "OrganizationUserId"); b.HasIndex("OrganizationUserId"); b.ToTable("CollectionUsers"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Device", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("EncryptedPrivateKey") .HasColumnType("text"); b.Property<string>("EncryptedPublicKey") .HasColumnType("text"); b.Property<string>("EncryptedUserKey") .HasColumnType("text"); b.Property<string>("Identifier") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("Name") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("PushToken") .HasMaxLength(255) .HasColumnType("character varying(255)"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<byte>("Type") .HasColumnType("smallint"); b.Property<Guid>("UserId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("Identifier") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("UserId") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("UserId", "Identifier") .IsUnique() .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Device", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Event", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<Guid?>("ActingUserId") .HasColumnType("uuid"); b.Property<Guid?>("CipherId") .HasColumnType("uuid"); b.Property<Guid?>("CollectionId") .HasColumnType("uuid"); b.Property<DateTime>("Date") .HasColumnType("timestamp with time zone"); b.Property<byte?>("DeviceType") .HasColumnType("smallint"); b.Property<string>("DomainName") .HasColumnType("text"); b.Property<Guid?>("GroupId") .HasColumnType("uuid"); b.Property<Guid?>("InstallationId") .HasColumnType("uuid"); b.Property<string>("IpAddress") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<Guid?>("OrganizationId") .HasColumnType("uuid"); b.Property<Guid?>("OrganizationUserId") .HasColumnType("uuid"); b.Property<Guid?>("PolicyId") .HasColumnType("uuid"); b.Property<Guid?>("ProviderId") .HasColumnType("uuid"); b.Property<Guid?>("ProviderOrganizationId") .HasColumnType("uuid"); b.Property<Guid?>("ProviderUserId") .HasColumnType("uuid"); b.Property<Guid?>("SecretId") .HasColumnType("uuid"); b.Property<Guid?>("ServiceAccountId") .HasColumnType("uuid"); b.Property<byte?>("SystemUser") .HasColumnType("smallint"); b.Property<int>("Type") .HasColumnType("integer"); b.Property<Guid?>("UserId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("Date", "OrganizationId", "ActingUserId", "CipherId") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Event", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Group", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("ExternalId") .HasMaxLength(300) .HasColumnType("character varying(300)"); b.Property<string>("Name") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.ToTable("Group", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.GroupUser", b => { b.Property<Guid>("GroupId") .HasColumnType("uuid"); b.Property<Guid>("OrganizationUserId") .HasColumnType("uuid"); b.HasKey("GroupId", "OrganizationUserId"); b.HasIndex("OrganizationUserId"); b.ToTable("GroupUser", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Installation", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Email") .IsRequired() .HasMaxLength(256) .HasColumnType("character varying(256)"); b.Property<bool>("Enabled") .HasColumnType("boolean"); b.Property<string>("Key") .IsRequired() .HasMaxLength(150) .HasColumnType("character varying(150)"); b.HasKey("Id"); b.ToTable("Installation", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationApiKey", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<string>("ApiKey") .IsRequired() .HasMaxLength(30) .HasColumnType("character varying(30)"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<byte>("Type") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.ToTable("OrganizationApiKey", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationConnection", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<string>("Config") .HasColumnType("text"); b.Property<bool>("Enabled") .HasColumnType("boolean"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<byte>("Type") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.ToTable("OrganizationConnection", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationDomain", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("DomainName") .IsRequired() .HasMaxLength(255) .HasColumnType("character varying(255)"); b.Property<int>("JobRunCount") .HasColumnType("integer"); b.Property<DateTime?>("LastCheckedDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime>("NextRunDate") .HasColumnType("timestamp with time zone"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<string>("Txt") .IsRequired() .HasColumnType("text"); b.Property<DateTime?>("VerifiedDate") .HasColumnType("timestamp with time zone"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.ToTable("OrganizationDomain", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationSponsorship", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<string>("FriendlyName") .HasMaxLength(256) .HasColumnType("character varying(256)"); b.Property<DateTime?>("LastSyncDate") .HasColumnType("timestamp with time zone"); b.Property<string>("OfferedToEmail") .HasMaxLength(256) .HasColumnType("character varying(256)"); b.Property<byte?>("PlanSponsorshipType") .HasColumnType("smallint"); b.Property<Guid?>("SponsoredOrganizationId") .HasColumnType("uuid"); b.Property<Guid?>("SponsoringOrganizationId") .HasColumnType("uuid"); b.Property<Guid>("SponsoringOrganizationUserId") .HasColumnType("uuid"); b.Property<bool>("ToDelete") .HasColumnType("boolean"); b.Property<DateTime?>("ValidUntil") .HasColumnType("timestamp with time zone"); b.HasKey("Id"); b.HasIndex("SponsoredOrganizationId"); b.HasIndex("SponsoringOrganizationId"); b.HasIndex("SponsoringOrganizationUserId") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("OrganizationSponsorship", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<bool>("AccessSecretsManager") .HasColumnType("boolean"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Email") .HasMaxLength(256) .HasColumnType("character varying(256)"); b.Property<string>("ExternalId") .HasMaxLength(300) .HasColumnType("character varying(300)"); b.Property<string>("Key") .HasColumnType("text"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<string>("Permissions") .HasColumnType("text"); b.Property<string>("ResetPasswordKey") .HasColumnType("text"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<short>("Status") .HasColumnType("smallint"); b.Property<byte>("Type") .HasColumnType("smallint"); b.Property<Guid?>("UserId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("OrganizationId") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("UserId") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("OrganizationUser", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Send", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<int>("AccessCount") .HasColumnType("integer"); b.Property<Guid?>("CipherId") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Data") .HasColumnType("text"); b.Property<DateTime>("DeletionDate") .HasColumnType("timestamp with time zone"); b.Property<bool>("Disabled") .HasColumnType("boolean"); b.Property<DateTime?>("ExpirationDate") .HasColumnType("timestamp with time zone"); b.Property<bool?>("HideEmail") .HasColumnType("boolean"); b.Property<string>("Key") .HasColumnType("text"); b.Property<int?>("MaxAccessCount") .HasColumnType("integer"); b.Property<Guid?>("OrganizationId") .HasColumnType("uuid"); b.Property<string>("Password") .HasMaxLength(300) .HasColumnType("character varying(300)"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<byte>("Type") .HasColumnType("smallint"); b.Property<Guid?>("UserId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("DeletionDate") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("OrganizationId"); b.HasIndex("UserId") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("UserId", "OrganizationId") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Send", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.TaxRate", b => { b.Property<string>("Id") .HasMaxLength(40) .HasColumnType("character varying(40)"); b.Property<bool>("Active") .HasColumnType("boolean"); b.Property<string>("Country") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("PostalCode") .IsRequired() .HasMaxLength(10) .HasColumnType("character varying(10)"); b.Property<decimal>("Rate") .HasColumnType("numeric"); b.Property<string>("State") .HasMaxLength(2) .HasColumnType("character varying(2)"); b.HasKey("Id"); b.ToTable("TaxRate", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Transaction", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<decimal>("Amount") .HasColumnType("numeric"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Details") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property<byte?>("Gateway") .HasColumnType("smallint"); b.Property<string>("GatewayId") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<Guid?>("OrganizationId") .HasColumnType("uuid"); b.Property<byte?>("PaymentMethodType") .HasColumnType("smallint"); b.Property<Guid?>("ProviderId") .HasColumnType("uuid"); b.Property<bool?>("Refunded") .HasColumnType("boolean"); b.Property<decimal?>("RefundedAmount") .HasColumnType("numeric"); b.Property<byte>("Type") .HasColumnType("smallint"); b.Property<Guid?>("UserId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.HasIndex("ProviderId"); b.HasIndex("UserId") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("UserId", "OrganizationId", "CreationDate") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Transaction", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.User", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("AccountRevisionDate") .HasColumnType("timestamp with time zone"); b.Property<string>("ApiKey") .IsRequired() .HasMaxLength(30) .HasColumnType("character varying(30)"); b.Property<string>("AvatarColor") .HasMaxLength(7) .HasColumnType("character varying(7)"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Culture") .IsRequired() .HasMaxLength(10) .HasColumnType("character varying(10)"); b.Property<string>("Email") .IsRequired() .HasMaxLength(256) .HasColumnType("character varying(256)") .UseCollation("postgresIndetermanisticCollation"); b.Property<bool>("EmailVerified") .HasColumnType("boolean"); b.Property<string>("EquivalentDomains") .HasColumnType("text"); b.Property<string>("ExcludedGlobalEquivalentDomains") .HasColumnType("text"); b.Property<int>("FailedLoginCount") .HasColumnType("integer"); b.Property<bool>("ForcePasswordReset") .HasColumnType("boolean"); b.Property<byte?>("Gateway") .HasColumnType("smallint"); b.Property<string>("GatewayCustomerId") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("GatewaySubscriptionId") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<byte>("Kdf") .HasColumnType("smallint"); b.Property<int>("KdfIterations") .HasColumnType("integer"); b.Property<int?>("KdfMemory") .HasColumnType("integer"); b.Property<int?>("KdfParallelism") .HasColumnType("integer"); b.Property<string>("Key") .HasColumnType("text"); b.Property<DateTime?>("LastEmailChangeDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime?>("LastFailedLoginDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime?>("LastKdfChangeDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime?>("LastKeyRotationDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime?>("LastPasswordChangeDate") .HasColumnType("timestamp with time zone"); b.Property<string>("LicenseKey") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property<string>("MasterPassword") .HasMaxLength(300) .HasColumnType("character varying(300)"); b.Property<string>("MasterPasswordHint") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<short?>("MaxStorageGb") .HasColumnType("smallint"); b.Property<string>("Name") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<bool>("Premium") .HasColumnType("boolean"); b.Property<DateTime?>("PremiumExpirationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("PrivateKey") .HasColumnType("text"); b.Property<string>("PublicKey") .HasColumnType("text"); b.Property<string>("ReferenceData") .HasColumnType("text"); b.Property<DateTime?>("RenewalReminderDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<string>("SecurityStamp") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<long?>("Storage") .HasColumnType("bigint"); b.Property<string>("TwoFactorProviders") .HasColumnType("text"); b.Property<string>("TwoFactorRecoveryCode") .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property<bool>("UsesKeyConnector") .HasColumnType("boolean"); b.HasKey("Id"); b.HasIndex("Email") .IsUnique() .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("Premium", "PremiumExpirationDate", "RenewalReminderDate") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("User", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.NotificationCenter.Models.Notification", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<string>("Body") .HasColumnType("text"); b.Property<byte>("ClientType") .HasColumnType("smallint"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<bool>("Global") .HasColumnType("boolean"); b.Property<Guid?>("OrganizationId") .HasColumnType("uuid"); b.Property<byte>("Priority") .HasColumnType("smallint"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Title") .HasMaxLength(256) .HasColumnType("character varying(256)"); b.Property<Guid?>("UserId") .HasColumnType("uuid"); b.HasKey("Id") .HasAnnotation("SqlServer:Clustered", true); b.HasIndex("OrganizationId") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("UserId") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("ClientType", "Global", "UserId", "OrganizationId", "Priority", "CreationDate") .IsDescending(false, false, false, false, true, true) .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Notification", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.NotificationCenter.Models.NotificationStatus", b => { b.Property<Guid>("UserId") .HasColumnType("uuid"); b.Property<Guid>("NotificationId") .HasColumnType("uuid"); b.Property<DateTime?>("DeletedDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime?>("ReadDate") .HasColumnType("timestamp with time zone"); b.HasKey("UserId", "NotificationId") .HasAnnotation("SqlServer:Clustered", true); b.HasIndex("NotificationId"); b.ToTable("NotificationStatus", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Discriminator") .IsRequired() .HasMaxLength(34) .HasColumnType("character varying(34)"); b.Property<bool>("Read") .HasColumnType("boolean"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<bool>("Write") .HasColumnType("boolean"); b.HasKey("Id") .HasAnnotation("SqlServer:Clustered", true); b.ToTable("AccessPolicy", (string)null); b.HasDiscriminator().HasValue("AccessPolicy"); b.UseTphMappingStrategy(); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ApiKey", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<string>("ClientSecretHash") .HasMaxLength(128) .HasColumnType("character varying(128)"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("EncryptedPayload") .IsRequired() .HasMaxLength(4000) .HasColumnType("character varying(4000)"); b.Property<DateTime?>("ExpireAt") .HasColumnType("timestamp with time zone"); b.Property<string>("Key") .IsRequired() .HasColumnType("text"); b.Property<string>("Name") .IsRequired() .HasMaxLength(200) .HasColumnType("character varying(200)"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Scope") .IsRequired() .HasMaxLength(4000) .HasColumnType("character varying(4000)"); b.Property<Guid?>("ServiceAccountId") .HasColumnType("uuid"); b.HasKey("Id") .HasAnnotation("SqlServer:Clustered", true); b.HasIndex("ServiceAccountId") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("ApiKey", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime?>("DeletedDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Name") .HasColumnType("text"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.HasKey("Id") .HasAnnotation("SqlServer:Clustered", true); b.HasIndex("DeletedDate") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("OrganizationId") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Project", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime?>("DeletedDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Key") .HasColumnType("text"); b.Property<string>("Note") .HasColumnType("text"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Value") .HasColumnType("text"); b.HasKey("Id") .HasAnnotation("SqlServer:Clustered", true); b.HasIndex("DeletedDate") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("OrganizationId") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Secret", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Name") .HasColumnType("text"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.HasKey("Id") .HasAnnotation("SqlServer:Clustered", true); b.HasIndex("OrganizationId") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("ServiceAccount", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Cipher", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<string>("Attachments") .HasColumnType("text"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Data") .HasColumnType("text"); b.Property<DateTime?>("DeletedDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Favorites") .HasColumnType("text"); b.Property<string>("Folders") .HasColumnType("text"); b.Property<string>("Key") .HasColumnType("text"); b.Property<Guid?>("OrganizationId") .HasColumnType("uuid"); b.Property<byte?>("Reprompt") .HasColumnType("smallint"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<byte>("Type") .HasColumnType("smallint"); b.Property<Guid?>("UserId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.HasIndex("UserId"); b.ToTable("Cipher", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Folder", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Name") .HasColumnType("text"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<Guid>("UserId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("Folder", (string)null); }); modelBuilder.Entity("ProjectSecret", b => { b.Property<Guid>("ProjectsId") .HasColumnType("uuid"); b.Property<Guid>("SecretsId") .HasColumnType("uuid"); b.HasKey("ProjectsId", "SecretsId"); b.HasIndex("SecretsId"); b.ToTable("ProjectSecret"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupProjectAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedProjectId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("GrantedProjectId"); b.Property<Guid?>("GroupId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("GroupId"); b.HasIndex("GrantedProjectId"); b.HasIndex("GroupId"); b.HasDiscriminator().HasValue("group_project"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupSecretAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedSecretId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("GrantedSecretId"); b.Property<Guid?>("GroupId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("GroupId"); b.HasIndex("GrantedSecretId"); b.HasIndex("GroupId"); b.HasDiscriminator().HasValue("group_secret"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupServiceAccountAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedServiceAccountId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("GrantedServiceAccountId"); b.Property<Guid?>("GroupId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("GroupId"); b.HasIndex("GrantedServiceAccountId"); b.HasIndex("GroupId"); b.HasDiscriminator().HasValue("group_service_account"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccountProjectAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedProjectId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("GrantedProjectId"); b.Property<Guid?>("ServiceAccountId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("ServiceAccountId"); b.HasIndex("GrantedProjectId"); b.HasIndex("ServiceAccountId"); b.HasDiscriminator().HasValue("service_account_project"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccountSecretAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedSecretId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("GrantedSecretId"); b.Property<Guid?>("ServiceAccountId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("ServiceAccountId"); b.HasIndex("GrantedSecretId"); b.HasIndex("ServiceAccountId"); b.HasDiscriminator().HasValue("service_account_secret"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserProjectAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedProjectId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("GrantedProjectId"); b.Property<Guid?>("OrganizationUserId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("OrganizationUserId"); b.HasIndex("GrantedProjectId"); b.HasIndex("OrganizationUserId"); b.HasDiscriminator().HasValue("user_project"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserSecretAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedSecretId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("GrantedSecretId"); b.Property<Guid?>("OrganizationUserId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("OrganizationUserId"); b.HasIndex("GrantedSecretId"); b.HasIndex("OrganizationUserId"); b.HasDiscriminator().HasValue("user_secret"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserServiceAccountAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedServiceAccountId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("GrantedServiceAccountId"); b.Property<Guid?>("OrganizationUserId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("OrganizationUserId"); b.HasIndex("GrantedServiceAccountId"); b.HasIndex("OrganizationUserId"); b.HasDiscriminator().HasValue("user_service_account"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Policy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("Policies") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.ProviderOrganization", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany() .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", "Provider") .WithMany() .HasForeignKey("ProviderId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); b.Navigation("Provider"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.ProviderUser", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", "Provider") .WithMany() .HasForeignKey("ProviderId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany() .HasForeignKey("UserId"); b.Navigation("Provider"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.AuthRequest", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany() .HasForeignKey("OrganizationId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.Device", "ResponseDevice") .WithMany() .HasForeignKey("ResponseDeviceId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); b.Navigation("ResponseDevice"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.EmergencyAccess", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "Grantee") .WithMany() .HasForeignKey("GranteeId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "Grantor") .WithMany() .HasForeignKey("GrantorId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Grantee"); b.Navigation("Grantor"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.SsoConfig", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("SsoConfigs") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.SsoUser", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("SsoUsers") .HasForeignKey("OrganizationId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany("SsoUsers") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.WebAuthnCredential", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Billing.Models.ProviderInvoiceItem", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", "Provider") .WithMany() .HasForeignKey("ProviderId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Provider"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Billing.Models.ProviderPlan", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", "Provider") .WithMany() .HasForeignKey("ProviderId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Provider"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Collection", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("Collections") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionCipher", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Vault.Models.Cipher", "Cipher") .WithMany("CollectionCiphers") .HasForeignKey("CipherId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.Models.Collection", "Collection") .WithMany("CollectionCiphers") .HasForeignKey("CollectionId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Cipher"); b.Navigation("Collection"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionGroup", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Models.Collection", "Collection") .WithMany("CollectionGroups") .HasForeignKey("CollectionId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group") .WithMany() .HasForeignKey("GroupId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Collection"); b.Navigation("Group"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionUser", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Models.Collection", "Collection") .WithMany("CollectionUsers") .HasForeignKey("CollectionId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser") .WithMany("CollectionUsers") .HasForeignKey("OrganizationUserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Collection"); b.Navigation("OrganizationUser"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Device", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Group", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("Groups") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.GroupUser", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group") .WithMany("GroupUsers") .HasForeignKey("GroupId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser") .WithMany("GroupUsers") .HasForeignKey("OrganizationUserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Group"); b.Navigation("OrganizationUser"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationApiKey", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("ApiKeys") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationConnection", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("Connections") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationDomain", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("Domains") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationSponsorship", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "SponsoredOrganization") .WithMany() .HasForeignKey("SponsoredOrganizationId"); b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "SponsoringOrganization") .WithMany() .HasForeignKey("SponsoringOrganizationId"); b.Navigation("SponsoredOrganization"); b.Navigation("SponsoringOrganization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("OrganizationUsers") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany("OrganizationUsers") .HasForeignKey("UserId"); b.Navigation("Organization"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Send", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany() .HasForeignKey("OrganizationId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany() .HasForeignKey("UserId"); b.Navigation("Organization"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Transaction", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("Transactions") .HasForeignKey("OrganizationId"); b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", "Provider") .WithMany() .HasForeignKey("ProviderId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany("Transactions") .HasForeignKey("UserId"); b.Navigation("Organization"); b.Navigation("Provider"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.NotificationCenter.Models.Notification", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany() .HasForeignKey("OrganizationId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany() .HasForeignKey("UserId"); b.Navigation("Organization"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.NotificationCenter.Models.NotificationStatus", b => { b.HasOne("Bit.Infrastructure.EntityFramework.NotificationCenter.Models.Notification", "Notification") .WithMany() .HasForeignKey("NotificationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Notification"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ApiKey", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "ServiceAccount") .WithMany("ApiKeys") .HasForeignKey("ServiceAccountId"); b.Navigation("ServiceAccount"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany() .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany() .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany() .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Cipher", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("Ciphers") .HasForeignKey("OrganizationId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany("Ciphers") .HasForeignKey("UserId"); b.Navigation("Organization"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Folder", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany("Folders") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("User"); }); modelBuilder.Entity("ProjectSecret", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", null) .WithMany() .HasForeignKey("ProjectsId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", null) .WithMany() .HasForeignKey("SecretsId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupProjectAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", "GrantedProject") .WithMany("GroupAccessPolicies") .HasForeignKey("GrantedProjectId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group") .WithMany() .HasForeignKey("GroupId") .OnDelete(DeleteBehavior.Cascade); b.Navigation("GrantedProject"); b.Navigation("Group"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupSecretAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", "GrantedSecret") .WithMany("GroupAccessPolicies") .HasForeignKey("GrantedSecretId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group") .WithMany() .HasForeignKey("GroupId") .OnDelete(DeleteBehavior.Cascade); b.Navigation("GrantedSecret"); b.Navigation("Group"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupServiceAccountAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "GrantedServiceAccount") .WithMany("GroupAccessPolicies") .HasForeignKey("GrantedServiceAccountId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group") .WithMany() .HasForeignKey("GroupId") .OnDelete(DeleteBehavior.Cascade); b.Navigation("GrantedServiceAccount"); b.Navigation("Group"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccountProjectAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", "GrantedProject") .WithMany("ServiceAccountAccessPolicies") .HasForeignKey("GrantedProjectId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "ServiceAccount") .WithMany("ProjectAccessPolicies") .HasForeignKey("ServiceAccountId"); b.Navigation("GrantedProject"); b.Navigation("ServiceAccount"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccountSecretAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", "GrantedSecret") .WithMany("ServiceAccountAccessPolicies") .HasForeignKey("GrantedSecretId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "ServiceAccount") .WithMany() .HasForeignKey("ServiceAccountId"); b.Navigation("GrantedSecret"); b.Navigation("ServiceAccount"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserProjectAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", "GrantedProject") .WithMany("UserAccessPolicies") .HasForeignKey("GrantedProjectId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser") .WithMany() .HasForeignKey("OrganizationUserId"); b.Navigation("GrantedProject"); b.Navigation("OrganizationUser"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserSecretAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", "GrantedSecret") .WithMany("UserAccessPolicies") .HasForeignKey("GrantedSecretId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser") .WithMany() .HasForeignKey("OrganizationUserId"); b.Navigation("GrantedSecret"); b.Navigation("OrganizationUser"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserServiceAccountAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "GrantedServiceAccount") .WithMany("UserAccessPolicies") .HasForeignKey("GrantedServiceAccountId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser") .WithMany() .HasForeignKey("OrganizationUserId"); b.Navigation("GrantedServiceAccount"); b.Navigation("OrganizationUser"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", b => { b.Navigation("ApiKeys"); b.Navigation("Ciphers"); b.Navigation("Collections"); b.Navigation("Connections"); b.Navigation("Domains"); b.Navigation("Groups"); b.Navigation("OrganizationUsers"); b.Navigation("Policies"); b.Navigation("SsoConfigs"); b.Navigation("SsoUsers"); b.Navigation("Transactions"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Collection", b => { b.Navigation("CollectionCiphers"); b.Navigation("CollectionGroups"); b.Navigation("CollectionUsers"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Group", b => { b.Navigation("GroupUsers"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", b => { b.Navigation("CollectionUsers"); b.Navigation("GroupUsers"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.User", b => { b.Navigation("Ciphers"); b.Navigation("Folders"); b.Navigation("OrganizationUsers"); b.Navigation("SsoUsers"); b.Navigation("Transactions"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", b => { b.Navigation("GroupAccessPolicies"); b.Navigation("ServiceAccountAccessPolicies"); b.Navigation("UserAccessPolicies"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", b => { b.Navigation("GroupAccessPolicies"); b.Navigation("ServiceAccountAccessPolicies"); b.Navigation("UserAccessPolicies"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", b => { b.Navigation("ApiKeys"); b.Navigation("GroupAccessPolicies"); b.Navigation("ProjectAccessPolicies"); b.Navigation("UserAccessPolicies"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Cipher", b => { b.Navigation("CollectionCiphers"); }); #pragma warning restore 612, 618 } } }
AddClientOrganizationMigrationRecordTable
csharp
AutoMapper__AutoMapper
src/UnitTests/ConfigurationValidation.cs
{ "start": 22909, "end": 23367 }
public class ____ : IValueResolver<Query, Command, List<KeyValuePair<string, string>>> { public List<KeyValuePair<string, string>> Resolve(Query source, Command destination, List<KeyValuePair<string, string>> destMember, ResolutionContext context) { return source.Details .Select(d => new KeyValuePair<string, string>(d.ToString(), d.ToString())) .ToList(); } }
DetailsValueResolver
csharp
microsoft__semantic-kernel
dotnet/src/Plugins/Plugins.Core/PromptFunctionConstants.cs
{ "start": 1372, "end": 3787 }
record ____ demo for the new feature by Friday" I said: "Great, thanks John. We may not use all of it but it's good to get it out there." EXAMPLE OUTPUT: { "actionItems": [ { "owner": "John Doe", "actionItem": "Record a demo for the new feature", "dueDate": "Friday", "status": "Open", "notes": "" } ] } EXAMPLE INPUT WITH IMPLIED ACTION ITEMS: I need a list of vegan breakfast recipes. Can you get that for me? EXAMPLE OUTPUT: { "actionItems": [ { "owner": "", "actionItem": "Give a list of breakfast recipes that are vegan friendly", "dueDate": "", "status": "Open", "notes": "" } ] } EXAMPLE INPUT WITHOUT ACTION ITEMS: John Doe said: "Hey I'm going to the store, do you need anything?" I said: "No thanks, I'm good." EXAMPLE OUTPUT: { "action_items": [] } CONTENT STARTS HERE. {{$INPUT}} CONTENT STOPS HERE. OUTPUT: """; internal const string GetConversationTopicsDefinition = """ Analyze the following extract taken from a conversation transcript and extract key topics. - Topics only worth remembering. - Be brief. Short phrases. - Can use broken English. - Conciseness is very important. - Topics can include names of memories you want to recall. - NO LONG SENTENCES. SHORT PHRASES. - Return in JSON [Input] My name is Macbeth. I used to be King of Scotland, but I died. My wife's name is Lady Macbeth and we were married for 15 years. We had no children. Our beloved dog Toby McDuff was a famous hunter of rats in the forest. My tragic story was immortalized by Shakespeare in a play. [Output] { "topics": [ "Macbeth", "King of Scotland", "Lady Macbeth", "Dog", "Toby McDuff", "Shakespeare", "Play", "Tragedy" ] } +++++ [Input] {{$INPUT}} [Output] """; }
a
csharp
dotnetcore__WTM
src/WalkingTec.Mvvm.Core/Support/Json/Token.cs
{ "start": 90, "end": 481 }
public class ____ { [JsonPropertyName("access_token")] public string AccessToken { get; set; } [JsonPropertyName("expires_in")] public int ExpiresIn { get; set; } [JsonPropertyName("token_type")] public string TokenType { get; set; } [JsonPropertyName("refresh_token")] public string RefreshToken { get; set; } } }
Token
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore.Recipes.Core/ServiceCollectionExtensions.cs
{ "start": 117, "end": 710 }
public static class ____ { public static IServiceCollection AddRecipes(this IServiceCollection services) { services.AddScoped<IRecipeHarvester, ApplicationRecipeHarvester>(); services.AddScoped<IRecipeHarvester, RecipeHarvester>(); services.AddTransient<IRecipeExecutor, RecipeExecutor>(); services.AddScoped<IRecipeMigrator, RecipeMigrator>(); services.AddScoped<IRecipeReader, RecipeReader>(); services.AddScoped<IRecipeEnvironmentProvider, RecipeEnvironmentFeatureProvider>(); return services; } }
ServiceCollectionExtensions
csharp
dotnet__aspnetcore
src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.Tests/KeyManagement/CacheableKeyRingTests.cs
{ "start": 278, "end": 1871 }
public class ____ { [Fact] public void IsValid_NullKeyRing_ReturnsFalse() { Assert.False(CacheableKeyRing.IsValid(null, DateTime.UtcNow)); } [Fact] public void IsValid_CancellationTokenTriggered_ReturnsFalse() { // Arrange var keyRing = new Mock<IKeyRing>().Object; DateTimeOffset now = DateTimeOffset.UtcNow; var cts = new CancellationTokenSource(); var cacheableKeyRing = new CacheableKeyRing(cts.Token, now.AddHours(1), keyRing); // Act & assert Assert.True(CacheableKeyRing.IsValid(cacheableKeyRing, now.UtcDateTime)); cts.Cancel(); Assert.False(CacheableKeyRing.IsValid(cacheableKeyRing, now.UtcDateTime)); } [Fact] public void IsValid_Expired_ReturnsFalse() { // Arrange var keyRing = new Mock<IKeyRing>().Object; DateTimeOffset now = DateTimeOffset.UtcNow; var cts = new CancellationTokenSource(); var cacheableKeyRing = new CacheableKeyRing(cts.Token, now.AddHours(1), keyRing); // Act & assert Assert.True(CacheableKeyRing.IsValid(cacheableKeyRing, now.UtcDateTime)); Assert.False(CacheableKeyRing.IsValid(cacheableKeyRing, now.AddHours(1).UtcDateTime)); } [Fact] public void KeyRing_Prop() { // Arrange var keyRing = new Mock<IKeyRing>().Object; var cacheableKeyRing = new CacheableKeyRing(CancellationToken.None, DateTimeOffset.Now, keyRing); // Act & assert Assert.Same(keyRing, cacheableKeyRing.KeyRing); } }
CacheableKeyRingTests
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/Diagnostics/ValueStoreDiagnostic.cs
{ "start": 131, "end": 449 }
public class ____ { /// <summary> /// Currently applied frames. /// </summary> public IReadOnlyList<IValueFrameDiagnostic> AppliedFrames { get; } internal ValueStoreDiagnostic(IReadOnlyList<IValueFrameDiagnostic> appliedFrames) { AppliedFrames = appliedFrames; } }
ValueStoreDiagnostic
csharp
dotnet__maui
src/Controls/tests/TestCases.HostApp/Issues/Issue1851.cs
{ "start": 223, "end": 1571 }
public class ____ : TestContentPage { protected override void Init() { var grouping = new Grouping1851<string, string>("number", new List<string> { "1", "2", "3", "4", "5", "6", "7", "8", "9" }); var groupings = new ObservableCollection<Grouping1851<string, string>> { new Grouping1851<string, string>("letters", new List<string> {"a", "b", "c", "d", "e", "f", "g", "h", "i"}), new Grouping1851<string, string>("colours", new List<string> {"red", "green", "blue", "white", "orange", "purple", "grey", "mauve", "pink"}), grouping, }; var listview = new ListView { HasUnevenRows = true, IsGroupingEnabled = true, ItemsSource = groupings, ItemTemplate = new DataTemplate(typeof(CellTemplate1851)), GroupDisplayBinding = new Binding("Key") }; var groupbtn = new Button() { AutomationId = "btn", Text = "add/remove group" }; bool group = true; groupbtn.Clicked += (sender, args) => { listview.GroupShortNameBinding = new Binding("Key"); if (group) { group = false; // ***** Crashes here groupings.Remove(grouping); } else { group = true; groupings.Add(grouping); } }; Content = new ScrollView { Content = new StackLayout { Children = { groupbtn, listview, } } }; }
Issue1851
csharp
grandnode__grandnode2
src/Web/Grand.Web/Models/Media/PictureModel.cs
{ "start": 72, "end": 420 }
public class ____ : BaseEntityModel { public string ImageUrl { get; set; } public string ThumbImageUrl { get; set; } public string FullSizeImageUrl { get; set; } public string Title { get; set; } public string AlternateText { get; set; } public string Style { get; set; } public string ExtraField { get; set; } }
PictureModel
csharp
dotnet__maui
src/Controls/tests/TestCases.HostApp/Issues/Issue28051.cs
{ "start": 2653, "end": 2995 }
public class ____ : PlatformBehavior<Element, UIKit.UIView> { protected override void OnAttachedTo(Element bindable, UIKit.UIView platformView) { BindingContext = bindable.BindingContext; } protected override void OnDetachedFrom(Element bindable, UIKit.UIView platformView) { BindingContext = null; } } #elif WINDOWS
LongPressBehavior
csharp
xunit__xunit
src/xunit.v3.core.tests/ObjectModel/XunitTestClassTests.cs
{ "start": 4086, "end": 4149 }
class ____ : BeforeAfterTestAttribute { }
BeforeAfterOnCollection
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack/Metadata/OperationControl.cs
{ "start": 209, "end": 5086 }
public class ____ { public ServiceEndpointsMetadataConfig MetadataConfig { get; set; } public Format Format { set { this.ContentType = value.ToContentType(); this.ContentFormat = ServiceStack.ContentFormat.GetContentFormat(value); } } public IRequest HttpRequest { get; set; } public string ContentType { get; set; } public string ContentFormat { get; set; } public string Title { get; set; } public string OperationName { get; set; } public string HostName { get; set; } public string RequestMessage { get; set; } public string ResponseMessage { get; set; } public string MetadataHtml { get; set; } public Operation Operation { get; set; } public virtual string RequestUri { get { if (Operation != null && Operation.Routes.Count > 0) { var postRoute = Operation.Routes.FirstOrDefault(x => x.AllowsAllVerbs || x.Verbs.Contains(HttpMethods.Post)); var path = postRoute != null ? postRoute.Path : Operation.Routes[0].Path; return HostContext.Config.HandlerFactoryPath != null ? "/" + HostContext.Config.HandlerFactoryPath.CombineWith(path) : path; } var endpointConfig = MetadataConfig.GetEndpointConfig(ServiceStack.ContentFormat.GetContentFormat(ContentType)); var endpointPath = ResponseMessage != null ? endpointConfig.SyncReplyUri : endpointConfig.AsyncOneWayUri; return $"{endpointPath}/{OperationName}"; } } public virtual Task RenderAsync(Stream output) { var baseUrl = HttpRequest.ResolveAbsoluteUrl("~/"); var sbTags = StringBuilderCache.Allocate(); Operation?.Tags.Each(x => sbTags.Append($"<span><b>{x}</b></span>")); var tagsHtml = sbTags.Length > 0 ? "<div class=\"tags\">" + StringBuilderCache.ReturnAndFree(sbTags) + "</div>" : ""; var renderedTemplate = Templates.HtmlTemplates.Format(Templates.HtmlTemplates.GetOperationControlTemplate(), Title, baseUrl.CombineWith(MetadataConfig.DefaultMetadataUri), ContentFormat.ToUpper(), OperationName, GetHttpRequestTemplate(), ResponseTemplate, MetadataHtml, tagsHtml); return output.WriteAsync(renderedTemplate); } public virtual string GetHttpRequestTemplate() { if (Operation == null || Operation.Routes.Count == 0) return HttpRequestTemplateWithBody(HttpMethods.Post); var allowedVerbs = new HashSet<string>(); foreach (var route in Operation.Routes) { if (route.AllowsAllVerbs) { allowedVerbs.Add(HttpMethods.Post); break; } foreach (var routeVerb in route.Verbs) { allowedVerbs.Add(routeVerb); } } if (allowedVerbs.Contains(HttpMethods.Post)) return HttpRequestTemplateWithBody(HttpMethods.Post); if (allowedVerbs.Contains(HttpMethods.Put)) return HttpRequestTemplateWithBody(HttpMethods.Put); if (allowedVerbs.Contains(HttpMethods.Patch)) return HttpRequestTemplateWithBody(HttpMethods.Patch); if (allowedVerbs.Contains(HttpMethods.Get)) return HttpRequestTemplateWithoutBody(HttpMethods.Get); if (allowedVerbs.Contains(HttpMethods.Delete)) return HttpRequestTemplateWithoutBody(HttpMethods.Delete); return HttpRequestTemplateWithBody(HttpMethods.Post); } public virtual string HttpRequestTemplateWithBody(string httpMethod) => httpMethod + $@" {RequestUri} HTTP/1.1 Host: {HostName} Accept: {ContentType} Content-Type: {ContentType} Content-Length: <span class=""value"">length</span> {PclExportClient.Instance.HtmlEncode(RequestMessage)}"; public virtual string HttpRequestTemplateWithoutBody(string httpMethod) => httpMethod + $@" {RequestUri} HTTP/1.1 Host: {HostName} Accept: {ContentType}"; public virtual string ResponseTemplate { get { var httpResponse = this.HttpResponseTemplate; return string.IsNullOrEmpty(httpResponse) ? null : $@" <div class=""response""> <pre> {httpResponse} </pre> </div> "; } } public virtual string HttpResponseTemplate { get { if (string.IsNullOrEmpty(ResponseMessage)) return null; return $@"HTTP/1.1 200 OK Content-Type: {ContentType} Content-Length: length {PclExportClient.Instance.HtmlEncode(ResponseMessage)}"; } } }
OperationControl
csharp
smartstore__Smartstore
src/Smartstore.Core/Content/Menus/Domain/MenuItemEntity.cs
{ "start": 833, "end": 4763 }
public class ____ : EntityWithAttributes, ILocalizedEntity, IStoreRestricted, IAclRestricted { const string EntityName = "MenuItemRecord"; public override string GetEntityName() => EntityName; /// <summary> /// Gets or sets the menu identifier. /// </summary> [Required] public int MenuId { get; set; } private MenuEntity _menu; /// <summary> /// Gets the menu. /// </summary> [IgnoreDataMember] public MenuEntity Menu { get => _menu ?? LazyLoader.Load(this, ref _menu); set => _menu = value; } /// <summary> /// Gets or sets the parent menu item identifier. 0 if the item has no parent. /// </summary> public int ParentItemId { get; set; } /// <summary> /// Gets or sets the provider name. /// </summary> [StringLength(100)] public string ProviderName { get; set; } /// <summary> /// Gets or sets the model. /// </summary> [MaxLength] public string Model { get; set; } /// <summary> /// Gets or sets the title. /// </summary> [StringLength(400)] [LocalizedProperty] public string Title { get; set; } /// <summary> /// Gets or sets the short description. It is used for the link title attribute. /// </summary> [StringLength(400)] [LocalizedProperty] public string ShortDescription { get; set; } /// <summary> /// Gets or sets permission names. /// </summary> [MaxLength] public string PermissionNames { get; set; } /// <summary> /// Gets or sets a value indicating whether the menu item is published. /// </summary> public bool Published { get; set; } = true; /// <summary> /// Gets or sets the display order. /// </summary> public int DisplayOrder { get; set; } /// <summary> /// Gets or sets a value indicating whether the menu item has a divider or a group header. /// </summary> public bool BeginGroup { get; set; } /// <summary> /// If selected and this menu item has children, the menu will initially appear expanded. /// </summary> public bool ShowExpanded { get; set; } /// <summary> /// Gets or sets the no-follow link attribute. /// </summary> public bool NoFollow { get; set; } /// <summary> /// Gets or sets the blank target link attribute. /// </summary> public bool NewWindow { get; set; } /// <summary> /// Gets or sets fontawesome icon class. /// </summary> [StringLength(100)] public string Icon { get; set; } /// <summary> /// Gets or sets fontawesome icon style. /// </summary> [StringLength(10)] public string Style { get; set; } /// <summary> /// Gets or sets fontawesome icon color. /// </summary> [StringLength(100)] public string IconColor { get; set; } /// <summary> /// Gets or sets HTML id attribute. /// </summary> [StringLength(100)] public string HtmlId { get; set; } /// <summary> /// Gets or sets the CSS class. /// </summary> [StringLength(100)] public string CssClass { get; set; } /// <summary> /// Gets or sets a value indicating whether the entity is limited/restricted to certain stores. /// </summary> public bool LimitedToStores { get; set; } /// <summary> /// Gets or sets a value indicating whether the entity is subject to ACL. /// </summary> public bool SubjectToAcl { get; set; } } }
MenuItemEntity
csharp
LibreHardwareMonitor__LibreHardwareMonitor
LibreHardwareMonitorLib/Interop/IntelGcl.cs
{ "start": 11580, "end": 11850 }
public struct ____ { public uint Data1; public ushort Data2; public ushort Data3; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public byte[] Data4; } [StructLayout(LayoutKind.Sequential)]
ctl_application_id_t
csharp
dotnet__BenchmarkDotNet
tests/BenchmarkDotNet.IntegrationTests/ExceptionHandlingTests.cs
{ "start": 359, "end": 3821 }
public class ____ : BenchmarkTestExecutor { private const string BenchmarkExceptionMessage = "we have a problem in our benchmark method"; private const string IterationCleanupExceptionMessage = "we have a problem in our iteration cleanup method"; private const string GlobalCleanupExceptionMessage = "we have a problem in our global cleanup method"; public ExceptionHandlingTests(ITestOutputHelper output) : base(output) { } [Fact] public void DryJobDoesNotEatExceptions() => SourceExceptionMessageIsDisplayed<AlwaysThrow>(Job.Dry); [Fact] public void DryJobDoesNotEatExceptionsWhenIterationCleanupThrows() => SourceExceptionMessageIsDisplayed<ThrowInBenchmarkAndInIterationCleanup>(Job.Dry); [Fact] public void DryJobDoesNotEatExceptionsWhenGlobalCleanupThrows() => SourceExceptionMessageIsDisplayed<ThrowInBenchmarkAndInGlobalCleanup>(Job.Dry); [Fact] public void DefaultJobDoesNotEatExceptions() => SourceExceptionMessageIsDisplayed<AlwaysThrow>(Job.Default); [Fact] public void DefaultJobDoesNotEatExceptionsWhenIterationCleanupThrows() => SourceExceptionMessageIsDisplayed<ThrowInBenchmarkAndInIterationCleanup>(Job.Default); [Fact] public void DefaultJobDoesNotEatExceptionsWhenGlobalCleanupThrows() => SourceExceptionMessageIsDisplayed<ThrowInBenchmarkAndInGlobalCleanup>(Job.Default); [Fact] public void DryJobWithInProcessToolchainDoesNotEatExceptions() => SourceExceptionMessageIsDisplayed<AlwaysThrow>(Job.Dry.WithToolchain(InProcessEmitToolchain.Instance)); [Fact] public void DryJobWithInProcessToolchainDoesNotEatExceptionsWhenIterationCleanupThrows() => SourceExceptionMessageIsDisplayed<ThrowInBenchmarkAndInIterationCleanup>(Job.Dry.WithToolchain(InProcessEmitToolchain.Instance)); [Fact] public void DryJobWithInProcessToolchainDoesNotEatExceptionsWhenGlobalCleanupThrows() => SourceExceptionMessageIsDisplayed<ThrowInBenchmarkAndInGlobalCleanup>(Job.Dry.WithToolchain(InProcessEmitToolchain.Instance)); [Fact] public void DefaultJobWithInProcessToolchainDoesNotEatExceptions() => SourceExceptionMessageIsDisplayed<AlwaysThrow>(Job.Default.WithToolchain(InProcessEmitToolchain.Instance)); [Fact] public void DefaultJobWithInProcessToolchainDoesNotEatExceptionsWhenIterationCleanupThrows() => SourceExceptionMessageIsDisplayed<ThrowInBenchmarkAndInIterationCleanup>(Job.Default.WithToolchain(InProcessEmitToolchain.Instance)); [Fact] public void DefaultJobWithInProcessToolchainDoesNotEatExceptionsWhenGlobalCleanupThrows() => SourceExceptionMessageIsDisplayed<ThrowInBenchmarkAndInGlobalCleanup>(Job.Default.WithToolchain(InProcessEmitToolchain.Instance)); [AssertionMethod] private void SourceExceptionMessageIsDisplayed<TBenchmark>(Job job) { var logger = new AccumulationLogger(); var config = ManualConfig.CreateEmpty().AddJob(job).AddLogger(logger); CanExecute<TBenchmark>(config, fullValidation: false); // we don't validate here because the report is expected to have no results Assert.Contains(BenchmarkExceptionMessage, logger.GetLog()); }
ExceptionHandlingTests
csharp
DuendeSoftware__IdentityServer
bff/test/Bff.Tests/TestInfra/TestHybridCache.cs
{ "start": 236, "end": 2231 }
internal class ____ : HybridCache { private ConcurrentDictionary<string, ValueTask<object>> _cache = new(); public override async ValueTask<T> GetOrCreateAsync<TState, T>(string key, TState state, Func<TState, CancellationToken, ValueTask<T>> factory, HybridCacheEntryOptions? options = null, IEnumerable<string>? tags = null, CancellationToken cancellationToken = new CancellationToken()) => (T)await _cache.GetOrAdd(key, async _ => (await factory(state, cancellationToken))!); public override ValueTask SetAsync<T>(string key, T value, HybridCacheEntryOptions? options = null, IEnumerable<string>? tags = null, CancellationToken cancellationToken = new CancellationToken()) { _cache[key] = new ValueTask<object>(value!); return ValueTask.CompletedTask; } public override ValueTask RemoveAsync(string key, CancellationToken cancellationToken = new CancellationToken()) { _waitUntilRemoveAsyncCalled.Set(); _cache.TryRemove(key, out _); return ValueTask.CompletedTask; } ManualResetEventSlim _waitUntilRemoveByTagAsyncCalled = new ManualResetEventSlim(); ManualResetEventSlim _waitUntilRemoveAsyncCalled = new ManualResetEventSlim(); public override ValueTask RemoveByTagAsync(string tag, CancellationToken cancellationToken = new CancellationToken()) { _waitUntilRemoveByTagAsyncCalled.Set(); _cache.Clear(); return new ValueTask(); } public void WaitUntilRemoveByTagAsyncCalled(TimeSpan until) { _waitUntilRemoveByTagAsyncCalled.Wait(until); if (!_waitUntilRemoveByTagAsyncCalled.IsSet) { throw new TimeoutException(); } } public void WaitUntilRemoveAsyncCalled(TimeSpan until) { _waitUntilRemoveAsyncCalled.Wait(until); if (!_waitUntilRemoveAsyncCalled.IsSet) { throw new TimeoutException(); } } }
TestHybridCache
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.Queries/Sql/SqlAst.cs
{ "start": 1352, "end": 1560 }
public sealed class ____ : ISqlNode { public IReadOnlyList<CommonTableExpression> CTEs { get; } public WithClause(IReadOnlyList<CommonTableExpression> ctes) { CTEs = ctes; } }
WithClause
csharp
abpframework__abp
modules/identity/test/Volo.Abp.Identity.EntityFrameworkCore.Tests/Volo/Abp/Identity/EntityFrameworkCore/IdentityDataSeeder_Tests.cs
{ "start": 51, "end": 163 }
public class ____ : IdentityDataSeeder_Tests<AbpIdentityEntityFrameworkCoreTestModule> { }
IdentityDataSeeder_Tests
csharp
dotnet__efcore
src/EFCore/Metadata/Internal/QueryFilterCollection.cs
{ "start": 675, "end": 6356 }
public sealed class ____ : IReadOnlyCollection<IQueryFilter> { private IQueryFilter? _anonymousFilter; private Dictionary<string, IQueryFilter>? _filters; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public QueryFilterCollection() { } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public QueryFilterCollection(IEnumerable<IQueryFilter> filters) => SetRange(filters); [MemberNotNullWhen(true, nameof(_anonymousFilter))] private bool HasAnonymousFilter => _anonymousFilter != null; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public int Count => HasAnonymousFilter ? 1 : _filters?.Count ?? 0; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public IEnumerator<IQueryFilter> GetEnumerator() => HasAnonymousFilter ? new AnonymousFilterEnumerator(_anonymousFilter) : _filters?.Values.GetEnumerator() ?? Enumerable.Empty<IQueryFilter>().GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public IQueryFilter? this[string? filterKey] => filterKey == null ? _anonymousFilter : _filters?.GetValueOrDefault(filterKey); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public IQueryFilter? Set(IQueryFilter? filter) { if (filter == null) { Remove(); } else if (filter.Expression == null) { Remove(filter.Key); } else if (filter.IsAnonymous) { if (_filters?.Count > 0) { throw new InvalidOperationException(CoreStrings.AnonymousAndNamedFiltersCombined); } _anonymousFilter = filter; } else { if (HasAnonymousFilter) { throw new InvalidOperationException(CoreStrings.AnonymousAndNamedFiltersCombined); } (_filters ??= [])[filter.Key] = filter; } return filter; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public void SetRange(IEnumerable<IQueryFilter> newFilters) { if (_filters == null && newFilters.TryGetNonEnumeratedCount(out var count) && count > 1) { _filters = new Dictionary<string, IQueryFilter>(count); } foreach (var filter in newFilters) { Set(filter); } } private void Remove(string? key = null) { if (key == null) { _anonymousFilter = null; } else { _filters?.Remove(key); } }
QueryFilterCollection
csharp
dotnet__efcore
test/EFCore.Specification.Tests/ModelBuilding101OneToOneNrtTestBase.cs
{ "start": 3289, "end": 3672 }
public class ____ : BlogContext0 { protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity<Blog>() .HasOne(e => e.Header) .WithOne(e => e.Blog) .HasForeignKey<BlogHeader>(e => e.BlogId) .IsRequired(false); }
BlogContext1
csharp
open-telemetry__opentelemetry-dotnet
src/OpenTelemetry.Shims.OpenTracing/ScopeManagerShim.cs
{ "start": 1755, "end": 2248 }
private sealed class ____ : IScope { private readonly Action? disposeAction; public ScopeInstrumentation(TelemetrySpan span, Action? disposeAction = null) { this.Span = new SpanShim(span); this.disposeAction = disposeAction; } /// <inheritdoc/> public ISpan Span { get; } /// <inheritdoc/> public void Dispose() { this.disposeAction?.Invoke(); } } }
ScopeInstrumentation
csharp
CommunityToolkit__WindowsCommunityToolkit
Microsoft.Toolkit.Uwp/Extensions/TypedEventHandlerExtensions.cs
{ "start": 529, "end": 3266 }
public static class ____ { /// <summary> /// Use to invoke an async <see cref="TypedEventHandler{TSender, TResult}"/> using <see cref="DeferredEventArgs"/>. /// </summary> /// <typeparam name="S">Type of sender.</typeparam> /// <typeparam name="R"><see cref="EventArgs"/> type.</typeparam> /// <param name="eventHandler"><see cref="TypedEventHandler{TSender, TResult}"/> to be invoked.</param> /// <param name="sender">Sender of the event.</param> /// <param name="eventArgs"><see cref="EventArgs"/> instance.</param> /// <returns><see cref="Task"/> to wait on deferred event handler.</returns> public static Task InvokeAsync<S, R>(this TypedEventHandler<S, R> eventHandler, S sender, R eventArgs) where R : DeferredEventArgs { return InvokeAsync(eventHandler, sender, eventArgs, CancellationToken.None); } /// <summary> /// Use to invoke an async <see cref="TypedEventHandler{TSender, TResult}"/> using <see cref="DeferredEventArgs"/> with a <see cref="CancellationToken"/>. /// </summary> /// <typeparam name="S">Type of sender.</typeparam> /// <typeparam name="R"><see cref="EventArgs"/> type.</typeparam> /// <param name="eventHandler"><see cref="TypedEventHandler{TSender, TResult}"/> to be invoked.</param> /// <param name="sender">Sender of the event.</param> /// <param name="eventArgs"><see cref="EventArgs"/> instance.</param> /// <param name="cancellationToken"><see cref="CancellationToken"/> option.</param> /// <returns><see cref="Task"/> to wait on deferred event handler.</returns> public static Task InvokeAsync<S, R>(this TypedEventHandler<S, R> eventHandler, S sender, R eventArgs, CancellationToken cancellationToken) where R : DeferredEventArgs { if (eventHandler == null) { return Task.CompletedTask; } var tasks = eventHandler.GetInvocationList() .OfType<TypedEventHandler<S, R>>() .Select(invocationDelegate => { cancellationToken.ThrowIfCancellationRequested(); invocationDelegate(sender, eventArgs); #pragma warning disable CS0618 // Type or member is obsolete var deferral = eventArgs.GetCurrentDeferralAndReset(); return deferral?.WaitForCompletion(cancellationToken) ?? Task.CompletedTask; #pragma warning restore CS0618 // Type or member is obsolete }) .ToArray(); return Task.WhenAll(tasks); } } }
TypedEventHandlerExtensions
csharp
dotnet__maui
src/Controls/tests/TestCases.HostApp/Issues/Issue29233.xaml.cs
{ "start": 194, "end": 553 }
public partial class ____ : ContentPage { public Issue29233() { InitializeComponent(); } private void WebView_Navigated(object sender, WebNavigatedEventArgs e) { label.IsVisible = true; label.Text = "Failed"; } protected override async void OnAppearing() { base.OnAppearing(); await Task.Delay(2000); waitLabel.Text = "Hello"; } }
Issue29233
csharp
dotnet__aspire
src/Aspire.Hosting.Kubernetes/Resources/ObjectMetaV1.cs
{ "start": 437, "end": 1073 }
class ____ used to define and handle key metadata information associated with Kubernetes objects, such as: /// - Unique identifier (UID) of the resource. /// - Name and namespace of the resource. /// - Labels and annotations for organizing and categorizing resources. /// - Managed fields for tracking changes to the resource. /// - Owner references to define dependencies between resources. /// - Creation and deletion timestamps, along with optional deletion grace period. /// It is a core component for properly managing Kubernetes resources and ensuring compliance with Kubernetes object standards. /// </remarks> [YamlSerializable]
is
csharp
ChilliCream__graphql-platform
src/HotChocolate/Adapters/test/Adapters.Mcp.Tests/TestSchema.cs
{ "start": 8790, "end": 8836 }
public sealed record ____(string Title);
Book
csharp
abpframework__abp
framework/src/Volo.Abp.MongoDB/Volo/Abp/Uow/MongoDB/MongoDbDatabaseApi.cs
{ "start": 59, "end": 263 }
public class ____ : IDatabaseApi { public IAbpMongoDbContext DbContext { get; } public MongoDbDatabaseApi(IAbpMongoDbContext dbContext) { DbContext = dbContext; } }
MongoDbDatabaseApi
csharp
AutoMapper__AutoMapper
src/UnitTests/ForAllMembers.cs
{ "start": 135, "end": 267 }
public class ____ { public DateTime SomeDate { get; set; } public DateTime OtherDate { get; set; } }
Source
csharp
grandnode__grandnode2
src/Web/Grand.Web.Common/Helpers/DataSourceResultHelper.cs
{ "start": 93, "end": 980 }
public static class ____ { public static async Task<DataSourceResult> GetSearchResult<T>( string id, IEnumerable<T> items, Func<T, Task<string>> getName) where T : BaseEntity { var searchModels = new List<SearchModel>(); if (!string.IsNullOrEmpty(id)) { var currentItem = items.FirstOrDefault(item => item.Id == id); if (currentItem != null) { searchModels.Add(new SearchModel(currentItem.Id, await getName(currentItem))); } } foreach (var item in items) { if (item.Id != id) { searchModels.Add(new SearchModel(item.Id, await getName(item))); } } return new DataSourceResult { Data = searchModels, Total = searchModels.Count }; }
DataSourceResultHelper
csharp
ServiceStack__ServiceStack
ServiceStack.Blazor/tests/UI.Gallery/Gallery.Server/ServiceModel/Talent.cs
{ "start": 13236, "end": 13730 }
public class ____ : ICreateDb<Interview>, IReturn<Interview> { [ValidateNotNull] public DateTime? BookingTime { get; set; } [ValidateGreaterThan(0)] public int JobApplicationId { get; set; } [ValidateGreaterThan(0, Message = "An employee to perform interview must be selected.")] public int AppUserId { get; set; } public JobApplicationStatus ApplicationStatus { get; set; } } [Tag("Talent")] [ValidateIsAuthenticated] [AutoApply(Behavior.AuditModify)]
CreateInterview
csharp
CommunityToolkit__WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.UI/Extensions/Markup/EnumValuesExtension.cs
{ "start": 487, "end": 835 }
public sealed class ____ : MarkupExtension { /// <summary> /// Gets or sets the <see cref="System.Type"/> of the target <see langword="enum"/> /// </summary> public Type Type { get; set; } /// <inheritdoc/> protected override object ProvideValue() => Enum.GetValues(Type); } }
EnumValuesExtension
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp/Reflection/ReflectionHelper.cs
{ "start": 5267, "end": 6289 }
class ____ and it's declaring type including inherited attributes. /// Returns default value if it's not declared at all. /// </summary> /// <typeparam name="TAttribute">Type of the attribute</typeparam> /// <param name="memberInfo">MemberInfo</param> /// <param name="defaultValue">Default value (null as default)</param> /// <param name="inherit">Inherit attribute from base classes</param> public static TAttribute GetSingleAttributeOfMemberOrDeclaringTypeOrDefault<TAttribute>(MemberInfo memberInfo, TAttribute defaultValue = default(TAttribute), bool inherit = true) where TAttribute : class { return memberInfo.GetCustomAttributes(true).OfType<TAttribute>().FirstOrDefault() ?? memberInfo.ReflectedType?.GetTypeInfo().GetCustomAttributes(true).OfType<TAttribute>().FirstOrDefault() ?? defaultValue; } /// <summary> /// Tries to gets an of attribute defined for a
member
csharp
CommunityToolkit__WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.UI/Extensions/UIElementExtensions.cs
{ "start": 473, "end": 3937 }
public static class ____ { /// <summary> /// Attached <see cref="DependencyProperty"/> that indicates whether or not the contents of the target <see cref="UIElement"/> should always be clipped to their parent's bounds. /// </summary> public static readonly DependencyProperty ClipToBoundsProperty = DependencyProperty.RegisterAttached( "ClipToBounds", typeof(bool), typeof(UIElementExtensions), new PropertyMetadata(null, OnClipToBoundsPropertyChanged)); /// <summary> /// Gets the value of <see cref="ClipToBoundsProperty"/> /// </summary> /// <param name="element">The <see cref="UIElement"/> to read the property value from</param> /// <returns>The <see cref="bool"/> associated with the <see cref="FrameworkElement"/></returns>. public static bool GetClipToBounds(UIElement element) => (bool)element.GetValue(ClipToBoundsProperty); /// <summary> /// Sets the value of <see cref="ClipToBoundsProperty"/> /// </summary> /// <param name="element">The <see cref="UIElement"/> to set the property to</param> /// <param name="value">The new value of the attached property</param> public static void SetClipToBounds(UIElement element, bool value) => element.SetValue(ClipToBoundsProperty, value); private static void OnClipToBoundsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is UIElement element) { var clipToBounds = (bool)e.NewValue; var visual = ElementCompositionPreview.GetElementVisual(element); visual.Clip = clipToBounds ? visual.Compositor.CreateInsetClip() : null; } } /// <summary> /// Provides the distance in a <see cref="Point"/> from the passed in element to the element being called on. /// For instance, calling child.CoordinatesFrom(container) will return the position of the child within the container. /// Helper for <see cref="UIElement.TransformToVisual(UIElement)"/>. /// </summary> /// <param name="target">Element to measure distance.</param> /// <param name="parent">Starting parent element to provide coordinates from.</param> /// <returns><see cref="Point"/> containing difference in position of elements.</returns> public static Point CoordinatesFrom(this UIElement target, UIElement parent) { return target.TransformToVisual(parent).TransformPoint(default(Point)); } /// <summary> /// Provides the distance in a <see cref="Point"/> to the passed in element from the element being called on. /// For instance, calling container.CoordinatesTo(child) will return the position of the child within the container. /// Helper for <see cref="UIElement.TransformToVisual(UIElement)"/>. /// </summary> /// <param name="parent">Starting parent element to provide coordinates from.</param> /// <param name="target">Element to measure distance to.</param> /// <returns><see cref="Point"/> containing difference in position of elements.</returns> public static Point CoordinatesTo(this UIElement parent, UIElement target) { return target.TransformToVisual(parent).TransformPoint(default(Point)); } } }
UIElementExtensions
csharp
dotnet__efcore
test/EFCore.SqlServer.FunctionalTests/SqlServerEndToEndTest.cs
{ "start": 46065, "end": 46411 }
public class ____ { public virtual int Id { get; set; } public virtual int GameId { get; set; } public virtual Game Game { get; set; } public virtual ICollection<Actor> Actors { get; set; } = new HashSet<Actor>(); public virtual ICollection<Item> Items { get; set; } = new HashSet<Item>(); }
Level
csharp
unoplatform__uno
src/Uno.UWP/UI/Notifications/ScheduledToastNotification.cs
{ "start": 153, "end": 1408 }
public partial class ____ { public ScheduledToastNotification(XmlDocument content, DateTimeOffset deliveryTime) { if (content is null) { // yes, UWP throws here ArgumentException, and not ArgumentNullException throw new ArgumentException("ScheduledToastNotification constructor: XmlDocument content cannot be null"); } Content = content; DeliveryTime = deliveryTime; } public XmlDocument Content { get; internal set; } public DateTimeOffset DeliveryTime { get; internal set; } private string _tag = ""; public string Tag { get { return _tag; } set { if (value is null) { throw new ArgumentNullException("ScheduledToastNotification.Tag cannot be null"); } _tag = value; if (_tag.Length > 64) { // UWP limit: 16 chars, since Creators Update (15063) - 64 characters if (this.Log().IsEnabled(LogLevel.Warning)) { this.Log().LogWarning("Windows.UI.Notifications.ScheduledToastNotification.Tag is set to string longer than UWP limit"); } } } } #if __ANDROID__ public NotificationMirroring NotificationMirroring { get; set; } public global::System.DateTimeOffset? ExpirationTime { get; set; } #endif } }
ScheduledToastNotification
csharp
neuecc__MessagePack-CSharp
src/MessagePack.SourceGenerator/Analyzers/MsgPack002UseConstantOptionsAnalyzer.cs
{ "start": 537, "end": 4164 }
public class ____ : DiagnosticAnalyzer { public const string MutableSharedOptionsId = "MsgPack002"; public static readonly DiagnosticDescriptor MutableSharedOptionsDescriptor = new DiagnosticDescriptor( id: MutableSharedOptionsId, title: new LocalizableResourceString(nameof(Strings.MsgPack002_Title), Strings.ResourceManager, typeof(Strings)), messageFormat: new LocalizableResourceString(nameof(Strings.MsgPack002_MessageFormat), Strings.ResourceManager, typeof(Strings)), category: "Reliability", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: false, description: new LocalizableResourceString(nameof(Strings.MsgPack002_Description), Strings.ResourceManager, typeof(Strings)), helpLinkUri: AnalyzerUtilities.GetHelpLink(MutableSharedOptionsId)); private static readonly ImmutableArray<DiagnosticDescriptor> ReusableSupportedDiagnostics = ImmutableArray.Create(MutableSharedOptionsDescriptor); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ReusableSupportedDiagnostics; public override void Initialize(AnalysisContext context) { context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); context.EnableConcurrentExecution(); context.RegisterCompilationStartAction(compilationStartContext => { ITypeSymbol? messagePackSerializationOptionsTypeSymbol = compilationStartContext.Compilation.GetTypeByMetadataName("MessagePack.MessagePackSerializerOptions"); if (messagePackSerializationOptionsTypeSymbol is object) { compilationStartContext.RegisterOperationAction(c => this.AnalyzeMemberReference(c, messagePackSerializationOptionsTypeSymbol), OperationKind.PropertyReference, OperationKind.FieldReference); } }); } private static bool IsLessWritableThanReadable(ISymbol symbol) { if (symbol is IPropertySymbol property) { if (property.GetMethod is null) { // The property has no getter, so the calling code has other problems. // Don't report a problem. return true; } if (property.SetMethod is null) { // If the property has no setter, we're totally good. return true; } return property.SetMethod.DeclaredAccessibility < property.GetMethod.DeclaredAccessibility; } if (symbol is IFieldSymbol field) { return field.IsReadOnly; } return true; } private void AnalyzeMemberReference(OperationAnalysisContext ctxt, ITypeSymbol messagePackSerializationOptionsTypeSymbol) { var memberReferenceOperation = (IMemberReferenceOperation)ctxt.Operation; var referencedMember = memberReferenceOperation.Member; if (SymbolEqualityComparer.Default.Equals(memberReferenceOperation.Type, messagePackSerializationOptionsTypeSymbol) && referencedMember.IsStatic && referencedMember.DeclaredAccessibility > Accessibility.Private && !IsLessWritableThanReadable(referencedMember)) { // The caller is passing in a value from a mutable static that is as writable as it is readable (a dangerous habit). // TODO: fix ID, message, etc. to describe the problem. ctxt.ReportDiagnostic(Diagnostic.Create(MutableSharedOptionsDescriptor, memberReferenceOperation.Syntax.GetLocation())); } } }
MsgPack002UseConstantOptionsAnalyzer
csharp
dotnet__maui
src/Controls/tests/TestCases.HostApp/FeatureMatrix/RefreshView/RefreshViewControlPage.xaml.cs
{ "start": 324, "end": 3526 }
public partial class ____ : ContentPage { private RefreshViewViewModel _viewModel; public RefreshViewControlMainPage(RefreshViewViewModel viewModel) { InitializeComponent(); _viewModel = viewModel; BindingContext = _viewModel; SetScrollViewContent(); } private async void NavigateToOptionsPage_Clicked(object sender, EventArgs e) { SetScrollViewContent(); BindingContext = _viewModel = new RefreshViewViewModel(); await Navigation.PushAsync(new RefreshViewOptionsPage(_viewModel)); } private void SetScrollViewContent() { RefreshViewContainer.Children.Clear(); // Create BoxView separately var boxView = new BoxView { HeightRequest = 100, WidthRequest = 200, HorizontalOptions = LayoutOptions.Center, AutomationId = "BoxContent" }; // Set binding immediately boxView.SetBinding(BoxView.ColorProperty, "BoxViewColor"); var RefreshView = new RefreshView { AutomationId = "RefreshView", Content = new ScrollView { Content = boxView } }; RefreshView.SetBinding(RefreshView.CommandProperty, "Command"); RefreshView.SetBinding(RefreshView.CommandParameterProperty, "CommandParameter"); RefreshView.SetBinding(RefreshView.FlowDirectionProperty, "FlowDirection"); RefreshView.SetBinding(RefreshView.IsEnabledProperty, "IsEnabled"); RefreshView.SetBinding(RefreshView.IsVisibleProperty, "IsVisible"); RefreshView.SetBinding(RefreshView.IsRefreshingProperty, "IsRefreshing"); RefreshView.SetBinding(RefreshView.RefreshColorProperty, "RefreshColor"); RefreshView.SetBinding(RefreshView.ShadowProperty, "Shadow"); RefreshViewContainer.Children.Add(RefreshView); } private void SetCollectionViewContent() { RefreshViewContainer.Children.Clear(); var RefreshView = new RefreshView { AutomationId = "RefreshView", Content = new CollectionView { ItemsSource = new List<string> { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "Item 9", "Item 10" }, ItemTemplate = new DataTemplate(() => { var label = new Label { HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center, FontSize = 16, Padding = new Thickness(10) }; label.SetBinding(Label.TextProperty, "."); return label; }) } }; RefreshView.SetBinding(RefreshView.CommandProperty, "Command"); RefreshView.SetBinding(RefreshView.CommandParameterProperty, "CommandParameter"); RefreshView.SetBinding(RefreshView.FlowDirectionProperty, "FlowDirection"); RefreshView.SetBinding(RefreshView.IsEnabledProperty, "IsEnabled"); RefreshView.SetBinding(RefreshView.IsVisibleProperty, "IsVisible"); RefreshView.SetBinding(RefreshView.IsRefreshingProperty, "IsRefreshing"); RefreshView.SetBinding(RefreshView.RefreshColorProperty, "RefreshColor"); RefreshView.SetBinding(RefreshView.ShadowProperty, "Shadow"); RefreshViewContainer.Children.Add(RefreshView); } private void OnScrollViewContentClicked(object sender, EventArgs e) { SetScrollViewContent(); } private void OnCollectionViewContentClicked(object sender, EventArgs e) { SetCollectionViewContent(); } }
RefreshViewControlMainPage
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp.ZeroCore.NHibernate/Zero/FluentMigrator/Migrations/_20151221_01_Create_AbpOrganizationUnit_Table.cs
{ "start": 139, "end": 1168 }
public class ____ : AutoReversingMigration { public override void Up() { Create.Table("AbpOrganizationUnits") .WithIdAsInt64() .WithTenantIdAsNullable() .WithColumn("ParentId").AsInt64().Nullable().ForeignKey("AbpOrganizationUnits", "Id") .WithColumn("Code").AsString(128).NotNullable() .WithColumn("DisplayName").AsString(128).NotNullable() .WithFullAuditColumns(); Create.Index("IX_TenantId_Code") .OnTable("AbpOrganizationUnits") .OnColumn("TenantId").Ascending() .OnColumn("Code").Ascending() .WithOptions().NonClustered(); Create.Index("IX_ParentId_Code") .OnTable("AbpOrganizationUnits") .OnColumn("ParentId").Ascending() .OnColumn("Code").Ascending() .WithOptions().NonClustered(); } } }
_20151221_01_Create_AbpOrganizationUnit_Table
csharp
dotnet__orleans
src/Orleans.Serialization/Buffers/Writer.VarInt.cs
{ "start": 96, "end": 2224 }
partial struct ____<TBufferWriter> { /// <summary> /// Writes a variable-width <see cref="sbyte"/>. /// </summary> /// <param name="value">The value.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void WriteVarInt8(sbyte value) => WriteVarUInt28(ZigZagEncode(value)); /// <summary> /// Writes a variable-width <see cref="short"/>. /// </summary> /// <param name="value">The value.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void WriteVarInt16(short value) => WriteVarUInt28(ZigZagEncode(value)); /// <summary> /// Writes a variable-width <see cref="int"/>. /// </summary> /// <param name="value">The value.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void WriteVarInt32(int value) => WriteVarUInt32(ZigZagEncode(value)); /// <summary> /// Writes a variable-width <see cref="long"/>. /// </summary> /// <param name="value">The value.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void WriteVarInt64(long value) => WriteVarUInt64(ZigZagEncode(value)); /// <summary> /// Writes a variable-width <see cref="byte"/>. /// </summary> /// <param name="value">The value.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void WriteVarUInt8(byte value) => WriteVarUInt28(value); /// <summary> /// Writes a variable-width <see cref="ushort"/>. /// </summary> /// <param name="value">The value.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void WriteVarUInt16(ushort value) => WriteVarUInt28(value); [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static uint ZigZagEncode(int value) => (uint)((value << 1) ^ (value >> 31)); [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static ulong ZigZagEncode(long value) => (ulong)((value << 1) ^ (value >> 63)); } }
Writer
csharp
Cysharp__ZLogger
src/ZLogger/Providers/ZLoggerFileLoggerProvider.cs
{ "start": 68, "end": 194 }
public class ____ : ZLoggerOptions { public bool FileShared { get; set; } } [ProviderAlias("ZLoggerFile")]
ZLoggerFileOptions
csharp
dotnet__machinelearning
src/Microsoft.ML.Core/EntryPoints/ModuleArgs.cs
{ "start": 2354, "end": 2614 }
class ____ which this attribute is ascribed. /// </summary> public string DocName { get; set; } } /// <summary> /// An attribute used to annotate the signature interface. /// Effectively, this is a way to associate the signature
on
csharp
MassTransit__MassTransit
tests/MassTransit.NHibernateIntegration.Tests/MissingInstance_Specs.cs
{ "start": 5060, "end": 5430 }
class ____ { public Status(string status, string serviceName) { StatusDescription = status; ServiceName = serviceName; } public string ServiceName { get; set; } public string StatusDescription { get; set; } }
Status
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Driver.Tests/Core/Operations/ListIndexesUsingCommandOperationTests.cs
{ "start": 890, "end": 7381 }
public class ____ : OperationTestBase { // test methods [Fact] public void CollectionNamespace_get_should_return_expected_result() { var subject = new ListIndexesUsingCommandOperation(_collectionNamespace, _messageEncoderSettings); var result = subject.CollectionNamespace; result.Should().BeSameAs(_collectionNamespace); } [Fact] public void constructor_should_initialize_subject() { var subject = new ListIndexesUsingCommandOperation(_collectionNamespace, _messageEncoderSettings); subject.CollectionNamespace.Should().BeSameAs(_collectionNamespace); subject.MessageEncoderSettings.Should().BeSameAs(_messageEncoderSettings); subject.RetryRequested.Should().BeFalse(); } [Fact] public void constructor_should_throw_when_collectionNamespace_is_null() { Action action = () => new ListIndexesUsingCommandOperation(null, _messageEncoderSettings); action.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be("collectionNamespace"); } [Fact] public void BatchSize_get_and_set_should_work() { var subject = new ListIndexesUsingCommandOperation(_collectionNamespace, _messageEncoderSettings); int batchSize = 2; subject.BatchSize = batchSize; var result = subject.BatchSize; result.Should().Be(batchSize); } [Theory] [ParameterAttributeData] public void Execute_should_return_expected_result( [Values(false, true)] bool async) { RequireServer.Check(); EnsureCollectionExists(async); var subject = new ListIndexesUsingCommandOperation(_collectionNamespace, _messageEncoderSettings); var result = ExecuteOperation(subject, async); var list = ReadCursorToEnd(result, async); list.Select(index => index["name"].AsString).Should().BeEquivalentTo("_id_"); } [Theory] [ParameterAttributeData] public void Execute_should_return_the_expected_result_when_batchSize_is_used([Values(false, true)] bool async) { RequireServer.Check(); EnsureCollectionExists(async); int batchSize = 3; var subject = new ListIndexesUsingCommandOperation(_collectionNamespace, _messageEncoderSettings) { BatchSize = batchSize }; using (var result = ExecuteOperation(subject, async) as AsyncCursor<BsonDocument>) { result._batchSize().Should().Be(batchSize); } } [Theory] [ParameterAttributeData] public void Execute_should_return_expected_result_when_collection_does_not_exist( [Values(false, true)] bool async) { RequireServer.Check(); DropCollection(async); var subject = new ListIndexesUsingCommandOperation(_collectionNamespace, _messageEncoderSettings); var result = ExecuteOperation(subject, async); var list = ReadCursorToEnd(result, async); list.Count.Should().Be(0); } [Theory] [ParameterAttributeData] public void Execute_should_return_expected_result_when_database_does_not_exist( [Values(false, true)] bool async) { RequireServer.Check(); DropDatabase(async); var subject = new ListIndexesUsingCommandOperation(_collectionNamespace, _messageEncoderSettings); var result = ExecuteOperation(subject, async); var list = ReadCursorToEnd(result, async); list.Count.Should().Be(0); } [Theory] [ParameterAttributeData] public void Execute_should_throw_when_binding_is_null( [Values(false, true)] bool async) { var subject = new ListIndexesUsingCommandOperation(_collectionNamespace, _messageEncoderSettings); IReadBinding binding = null; Action action = () => ExecuteOperation(subject, binding, async); action.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be("binding"); } [Theory] [ParameterAttributeData] public void Execute_should_send_session_id_when_supported( [Values(false, true)] bool async) { RequireServer.Check(); EnsureCollectionExists(async); var subject = new ListIndexesUsingCommandOperation(_collectionNamespace, _messageEncoderSettings); VerifySessionIdWasSentWhenSupported(subject, "listIndexes", async); } [Fact] public void MessageEncoderSettings_get_should_return_expected_result() { var subject = new ListIndexesUsingCommandOperation(_collectionNamespace, _messageEncoderSettings); var result = subject.MessageEncoderSettings; result.Should().BeSameAs(_messageEncoderSettings); } [Theory] [ParameterAttributeData] public void RetryRequested_get_should_return_expected_result( [Values(false, true)] bool value) { var subject = new ListIndexesUsingCommandOperation(_collectionNamespace, _messageEncoderSettings); subject.RetryRequested = value; var result = subject.RetryRequested; result.Should().Be(value); } // helper methods public void DropCollection(bool async) { var operation = new DropCollectionOperation(_collectionNamespace, _messageEncoderSettings); ExecuteOperation(operation, async); } public void DropDatabase(bool async) { var operation = new DropDatabaseOperation(_collectionNamespace.DatabaseNamespace, _messageEncoderSettings); ExecuteOperation(operation, async); } public void EnsureCollectionExists(bool async) { var requests = new[] { new InsertRequest(new BsonDocument("_id", ObjectId.GenerateNewId())) }; var operation = new BulkInsertOperation(_collectionNamespace, requests, _messageEncoderSettings); ExecuteOperation(operation, async); } } }
ListIndexesUsingCommandOperationTests
csharp
jellyfin__jellyfin
MediaBrowser.Controller/Persistence/MediaAttachmentQuery.cs
{ "start": 99, "end": 487 }
public class ____ { /// <summary> /// Gets or sets the index. /// </summary> /// <value>The index.</value> public int? Index { get; set; } /// <summary> /// Gets or sets the item identifier. /// </summary> /// <value>The item identifier.</value> public Guid ItemId { get; set; } } }
MediaAttachmentQuery
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Driver/IndexKeysDefinition.cs
{ "start": 3615, "end": 4403 }
public sealed class ____<TDocument> : IndexKeysDefinition<TDocument> { private readonly string _json; /// <summary> /// Initializes a new instance of the <see cref="JsonIndexKeysDefinition{TDocument}"/> class. /// </summary> /// <param name="json">The json.</param> public JsonIndexKeysDefinition(string json) { _json = Ensure.IsNotNull(json, nameof(json)); } /// <summary> /// Gets the json. /// </summary> public string Json { get { return _json; } } /// <inheritdoc /> public override BsonDocument Render(RenderArgs<TDocument> args) { return BsonDocument.Parse(_json); } } }
JsonIndexKeysDefinition
csharp
dotnet__BenchmarkDotNet
tests/BenchmarkDotNet.Tests/Validators/ReturnValueValidatorTests.cs
{ "start": 6866, "end": 7324 }
public class ____ : IEquatable<CustomEquatableA> { public bool Equals(CustomEquatableA other) => other != null; public override bool Equals(object obj) => false; // Intentionally bad implementation public override int GetHashCode() => 0; } [Fact] public void ConsistentBenchmarksAlteringParameterAreOmitted() => AssertConsistent<ConsistentAlterParam>();
CustomEquatableB
csharp
pythonnet__pythonnet
tests/domain_tests/TestRunner.cs
{ "start": 4627, "end": 5087 }
public class ____ { public static int After() { return 10; } } }", PythonCode = @" import clr import sys clr.AddReference('DomainTests') import TestNamespace def before_reload(): if not hasattr(sys, 'my_cls'): sys.my_cls = TestNamespace.Cls sys.my_fn = TestNamespace.Cls.Before assert 5 == sys.my_fn() assert 5 == TestNamespace.Cls.Before() def after_reload(): # We should have reloaded the
Cls
csharp
dotnetcore__CAP
test/DotNetCore.CAP.Test/CAP.BuilderTest.cs
{ "start": 237, "end": 1524 }
public class ____ { [Fact] public void CanCreateInstanceAndGetService() { var services = new ServiceCollection(); services.AddSingleton<ICapPublisher, MyProducerService>(); var builder = new CapBuilder(services); Assert.NotNull(builder); var count = builder.Services.Count; Assert.Equal(1, count); var provider = services.BuildServiceProvider(); var capPublisher = provider.GetService<ICapPublisher>(); Assert.NotNull(capPublisher); } [Fact] public void CanAddCapService() { var services = new ServiceCollection(); services.AddCap(x => { }); var builder = services.BuildServiceProvider(); var markService = builder.GetService<CapMarkerService>(); Assert.NotNull(markService); } [Fact] public void CanResolveCapOptions() { var services = new ServiceCollection(); services.AddCap(x => { }); var builder = services.BuildServiceProvider(); var capOptions = builder.GetService<IOptions<CapOptions>>().Value; Assert.NotNull(capOptions); }
CapBuilderTest
csharp
getsentry__sentry-dotnet
src/Sentry.Bindings.Cocoa/ApiDefinitions.cs
{ "start": 24208, "end": 24345 }
interface ____ { [Export("showWidget")] void ShowWidget(); [Export("hideWidget")] void HideWidget(); } // @
SentryFeedbackAPI
csharp
files-community__Files
src/Files.App/Data/Commands/HotKey/HotKey.cs
{ "start": 327, "end": 13936 }
struct ____ : IEquatable<HotKey> { public static FrozenDictionary<KeyModifiers, string> LocalizedModifiers { get; } = new Dictionary<KeyModifiers, string>() { [KeyModifiers.Alt] = GetLocalizedKey("Menu"), [KeyModifiers.Ctrl] = GetLocalizedKey("Control"), [KeyModifiers.Shift] = GetLocalizedKey("Shift"), [KeyModifiers.Win] = GetLocalizedKey("Windows"), }.ToFrozenDictionary(); public static FrozenDictionary<Keys, string> LocalizedKeys { get; } = new Dictionary<Keys, string>() { [Keys.Enter] = GetLocalizedKey("Enter"), [Keys.Space] = GetLocalizedKey("Space"), [Keys.Escape] = GetLocalizedKey("Escape"), [Keys.Back] = GetLocalizedKey("Back"), [Keys.Tab] = GetLocalizedKey("Tab"), [Keys.Insert] = GetLocalizedKey("Insert"), [Keys.Delete] = GetLocalizedKey("Delete"), [Keys.Left] = GetLocalizedKey("Left"), [Keys.Right] = GetLocalizedKey("Right"), [Keys.Down] = GetLocalizedKey("Down"), [Keys.Up] = GetLocalizedKey("Up"), [Keys.Home] = GetLocalizedKey("Home"), [Keys.End] = GetLocalizedKey("End"), [Keys.PageDown] = GetLocalizedKey("PageDown"), [Keys.PageUp] = GetLocalizedKey("PageUp"), [Keys.Separator] = GetLocalizedKey("Separator"), [Keys.Pause] = GetLocalizedKey("Pause"), [Keys.Sleep] = GetLocalizedKey("Sleep"), [Keys.Clear] = GetLocalizedKey("Clear"), [Keys.Print] = GetLocalizedKey("Print"), [Keys.Help] = GetLocalizedKey("Help"), [Keys.Mouse4] = GetLocalizedKey("Mouse4"), [Keys.Mouse5] = GetLocalizedKey("Mouse5"), [Keys.F1] = "F1", [Keys.F2] = "F2", [Keys.F3] = "F3", [Keys.F4] = "F4", [Keys.F5] = "F5", [Keys.F6] = "F6", [Keys.F7] = "F7", [Keys.F8] = "F8", [Keys.F9] = "F9", [Keys.F10] = "F10", [Keys.F11] = "F11", [Keys.F12] = "F12", [Keys.F13] = "F13", [Keys.F14] = "F14", [Keys.F15] = "F15", [Keys.F16] = "F16", [Keys.F17] = "F17", [Keys.F18] = "F18", [Keys.F19] = "F19", [Keys.F20] = "F20", [Keys.F21] = "F21", [Keys.F22] = "F22", [Keys.F23] = "F23", [Keys.F24] = "F24", [Keys.Number0] = "0", [Keys.Number1] = "1", [Keys.Number2] = "2", [Keys.Number3] = "3", [Keys.Number4] = "4", [Keys.Number5] = "5", [Keys.Number6] = "6", [Keys.Number7] = "7", [Keys.Number8] = "8", [Keys.Number9] = "9", [Keys.A] = GetKeyCharacter(Forms.Keys.A).ToUpper(), [Keys.B] = GetKeyCharacter(Forms.Keys.B).ToUpper(), [Keys.C] = GetKeyCharacter(Forms.Keys.C).ToUpper(), [Keys.D] = GetKeyCharacter(Forms.Keys.D).ToUpper(), [Keys.E] = GetKeyCharacter(Forms.Keys.E).ToUpper(), [Keys.F] = GetKeyCharacter(Forms.Keys.F).ToUpper(), [Keys.G] = GetKeyCharacter(Forms.Keys.G).ToUpper(), [Keys.H] = GetKeyCharacter(Forms.Keys.H).ToUpper(), [Keys.I] = GetKeyCharacter(Forms.Keys.I).ToUpper(), [Keys.J] = GetKeyCharacter(Forms.Keys.J).ToUpper(), [Keys.K] = GetKeyCharacter(Forms.Keys.K).ToUpper(), [Keys.L] = GetKeyCharacter(Forms.Keys.L).ToUpper(), [Keys.M] = GetKeyCharacter(Forms.Keys.M).ToUpper(), [Keys.N] = GetKeyCharacter(Forms.Keys.N).ToUpper(), [Keys.O] = GetKeyCharacter(Forms.Keys.O).ToUpper(), [Keys.P] = GetKeyCharacter(Forms.Keys.P).ToUpper(), [Keys.Q] = GetKeyCharacter(Forms.Keys.Q).ToUpper(), [Keys.R] = GetKeyCharacter(Forms.Keys.R).ToUpper(), [Keys.S] = GetKeyCharacter(Forms.Keys.S).ToUpper(), [Keys.T] = GetKeyCharacter(Forms.Keys.T).ToUpper(), [Keys.U] = GetKeyCharacter(Forms.Keys.U).ToUpper(), [Keys.V] = GetKeyCharacter(Forms.Keys.V).ToUpper(), [Keys.W] = GetKeyCharacter(Forms.Keys.W).ToUpper(), [Keys.X] = GetKeyCharacter(Forms.Keys.X).ToUpper(), [Keys.Y] = GetKeyCharacter(Forms.Keys.Y).ToUpper(), [Keys.Z] = GetKeyCharacter(Forms.Keys.Z).ToUpper(), [Keys.Oem1] = GetKeyCharacter(Forms.Keys.Oem1).ToUpper(), [Keys.Oem2] = GetKeyCharacter(Forms.Keys.Oem2).ToUpper(), [Keys.Oem3] = GetKeyCharacter(Forms.Keys.Oem3).ToUpper(), [Keys.Oem4] = GetKeyCharacter(Forms.Keys.Oem4).ToUpper(), [Keys.Oem5] = GetKeyCharacter(Forms.Keys.Oem5).ToUpper(), [Keys.Oem6] = GetKeyCharacter(Forms.Keys.Oem6).ToUpper(), [Keys.Oem7] = GetKeyCharacter(Forms.Keys.Oem7).ToUpper(), [Keys.Oem8] = GetKeyCharacter(Forms.Keys.Oem8).ToUpper(), [Keys.Oem102] = GetKeyCharacter(Forms.Keys.Oem102).ToUpper(), [Keys.OemPlus] = GetKeyCharacter(Forms.Keys.Oemplus).ToUpper(), [Keys.OemComma] = GetKeyCharacter(Forms.Keys.Oemcomma).ToUpper(), [Keys.OemMinus] = GetKeyCharacter(Forms.Keys.OemMinus).ToUpper(), [Keys.OemPeriod] = GetKeyCharacter(Forms.Keys.OemPeriod).ToUpper(), [Keys.OemClear] = GetKeyCharacter(Forms.Keys.OemClear).ToUpper(), [Keys.Application] = GetLocalizedKey("Application"), [Keys.Application1] = GetLocalizedKey("Application1"), [Keys.Application2] = GetLocalizedKey("Application2"), [Keys.Mail] = GetLocalizedKey("Mail"), [Keys.GoHome] = GetLocalizedKey("BrowserGoHome"), [Keys.GoBack] = GetLocalizedKey("BrowserGoBack"), [Keys.GoForward] = GetLocalizedKey("BrowserGoForward"), [Keys.Refresh] = GetLocalizedKey("BrowserRefresh"), [Keys.BrowserStop] = GetLocalizedKey("BrowserStop"), [Keys.Search] = GetLocalizedKey("BrowserSearch"), [Keys.Favorites] = GetLocalizedKey("BrowserFavorites"), [Keys.PlayPause] = GetLocalizedKey("MediaPlayPause"), [Keys.MediaStop] = GetLocalizedKey("MediaStop"), [Keys.PreviousTrack] = GetLocalizedKey("MediaPreviousTrack"), [Keys.NextTrack] = GetLocalizedKey("MediaNextTrack"), [Keys.MediaSelect] = GetLocalizedKey("MediaSelect"), [Keys.Mute] = GetLocalizedKey("MediaMute"), [Keys.VolumeDown] = GetLocalizedKey("MediaVolumeDown"), [Keys.VolumeUp] = GetLocalizedKey("MediaVolumeUp"), // NumPad Keys [Keys.Add] = GetLocalizedNumPadKey("+"), [Keys.Subtract] = GetLocalizedNumPadKey("-"), [Keys.Multiply] = GetLocalizedNumPadKey("*"), [Keys.Divide] = GetLocalizedNumPadKey("/"), [Keys.Decimal] = GetLocalizedNumPadKey("."), [Keys.Pad0] = GetLocalizedNumPadKey("0"), [Keys.Pad1] = GetLocalizedNumPadKey("1"), [Keys.Pad2] = GetLocalizedNumPadKey("2"), [Keys.Pad3] = GetLocalizedNumPadKey("3"), [Keys.Pad4] = GetLocalizedNumPadKey("4"), [Keys.Pad5] = GetLocalizedNumPadKey("5"), [Keys.Pad6] = GetLocalizedNumPadKey("6"), [Keys.Pad7] = GetLocalizedNumPadKey("7"), [Keys.Pad8] = GetLocalizedNumPadKey("8"), [Keys.Pad9] = GetLocalizedNumPadKey("9"), }.ToFrozenDictionary(); /// <summary> /// Gets the none value. /// </summary> public static HotKey None { get; } = new(Keys.None, KeyModifiers.None); /// <summary> /// Gets the value that indicates whether the hotkey is none. /// </summary> public bool IsNone => Key is Keys.None && Modifier is KeyModifiers.None; /// <summary> /// Gets the value that indicates whether the key should be visible. /// </summary> public bool IsVisible { get; init; } /// <summary> /// Gets the key. /// </summary> public Keys Key { get; } /// <summary> /// Gets the modifier. /// </summary> public KeyModifiers Modifier { get; } /// <summary> /// Gets the raw label of the hotkey. /// </summary> /// <remarks> /// For example, this is "Ctrl+A" and "Ctrl+Menu+C" /// </remarks> public string RawLabel { get { return (Key, Modifier) switch { (Keys.None, KeyModifiers.None) => string.Empty, (Keys.None, _) => $"{GetModifierCode(Modifier)}", (_, KeyModifiers.None) => $"{Key}", _ => $"{GetModifierCode(Modifier)}+{Key}", }; static string GetModifierCode(KeyModifiers modifiers) { StringBuilder builder = new(); if (modifiers.HasFlag(KeyModifiers.Alt)) builder.Append($"+{KeyModifiers.Alt}"); if (modifiers.HasFlag(KeyModifiers.Ctrl)) builder.Append($"+{KeyModifiers.Ctrl}"); if (modifiers.HasFlag(KeyModifiers.Shift)) builder.Append($"+{KeyModifiers.Shift}"); if (modifiers.HasFlag(KeyModifiers.Win)) builder.Append($"+{KeyModifiers.Win}"); builder.Remove(0, 1); return builder.ToString(); } } } /// <summary> /// Gets the localized label of the hotkey to shown in the UI. /// </summary> /// <remarks> /// For example, this is "Ctrl+A" and "Ctrl+Alt+C" /// </remarks> public string LocalizedLabel { get { return (Key, Modifier) switch { (Keys.None, KeyModifiers.None) => string.Empty, (Keys.None, _) => GetModifierCode(Modifier), (_, KeyModifiers.None) => LocalizedKeys[Key], _ => $"{GetModifierCode(Modifier)}+{LocalizedKeys[Key]}", }; static string GetModifierCode(KeyModifiers modifier) { StringBuilder builder = new(); if (modifier.HasFlag(KeyModifiers.Alt)) builder.Append($"+{LocalizedModifiers[KeyModifiers.Alt]}"); if (modifier.HasFlag(KeyModifiers.Ctrl)) builder.Append($"+{LocalizedModifiers[KeyModifiers.Ctrl]}"); if (modifier.HasFlag(KeyModifiers.Shift)) builder.Append($"+{LocalizedModifiers[KeyModifiers.Shift]}"); if (modifier.HasFlag(KeyModifiers.Win)) builder.Append($"+{LocalizedModifiers[KeyModifiers.Win]}"); builder.Remove(0, 1); return builder.ToString(); } } } /// <summary> /// Initializes an instance of <see cref="HotKey"/>. /// </summary> /// <param name="key">A key</param> /// <param name="modifier">A modifier</param> /// <param name="isVisible">A value that indicates the hotkey should be available.</param> public HotKey(Keys key, KeyModifiers modifier = KeyModifiers.None, bool isVisible = true) { if (!Enum.IsDefined(key) || !Enum.IsDefined(modifier)) return; IsVisible = isVisible; Key = key; Modifier = modifier; } /// <summary> /// Parses humanized hotkey code with separators. /// </summary> /// <param name="code">Humanized code to parse.</param> /// <param name="localized">Whether the code is localized.</param> /// <returns>Humanized code with a format <see cref="HotKey"/>.</returns> public static HotKey Parse(string code, bool localized = true) { if (string.IsNullOrEmpty(code)) return None; var key = Keys.None; var modifier = KeyModifiers.None; bool isVisible = true; var splitCharacter = '+'; // Remove leading and trailing whitespace from the code string code = code.Trim(); // Split the code by "++" into a list of parts List<string> parts = [.. code.Split(new string(splitCharacter, 2), StringSplitOptions.None)]; if (parts.Count == 2) { // If there are two parts after splitting by "++", split the first part by "+" // and append the second part prefixed with a "+" parts = [.. parts.First().Split(splitCharacter), splitCharacter + parts.Last()]; } else { // Split the code by a single '+' and trim each part parts = [.. code.Split(splitCharacter)]; // If the resulting list has two parts and one of them is empty, use the original code as the single element if (parts.Count == 2 && (string.IsNullOrEmpty(parts.First()) || string.IsNullOrEmpty(parts.Last()))) { parts = [code]; } else if (parts.Count > 1 && string.IsNullOrEmpty(parts.Last())) { // If the last part is empty, remove it and add a "+" to the last non-empty part parts.RemoveAt(parts.Count - 1); parts[^1] += splitCharacter; } } parts = [.. parts.Select(part => part.Trim())]; foreach (var part in parts) { if (localized) { key |= LocalizedKeys.FirstOrDefault(x => x.Value == part).Key; modifier |= LocalizedModifiers.FirstOrDefault(x => x.Value == part).Key; } else { if (Enum.TryParse(part, true, out Keys partKey)) key = partKey; if (Enum.TryParse(part, true, out KeyModifiers partModifier)) modifier |= partModifier; } } return new(key, modifier, isVisible); } /// <summary> /// Converts this <see cref="HotKey"/> instance into a <see cref="HotKeyCollection"/> instance. /// </summary> /// <returns></returns> public HotKeyCollection AsCollection() { return new(this); } // Operator overloads public static implicit operator string(HotKey hotKey) => hotKey.LocalizedLabel; public static bool operator ==(HotKey a, HotKey b) => a.Equals(b); public static bool operator !=(HotKey a, HotKey b) => !a.Equals(b); // Default methods public override string ToString() => LocalizedLabel; public override int GetHashCode() => (Key, Modifier, IsVisible).GetHashCode(); public override bool Equals(object? other) => other is HotKey hotKey && Equals(hotKey); public bool Equals(HotKey other) => (other.Key, other.Modifier, other.IsVisible).Equals((Key, Modifier, IsVisible)); // Private methods private static string GetLocalizedKey(string key) { return $"Key/{key}".GetLocalizedResource(); } private static string GetLocalizedNumPadKey(string key) { return Strings.NumPadTypeName.GetLocalizedResource() + " " + key; } private static string GetKeyCharacter(Forms.Keys key) { var buffer = new StringBuilder(4); var state = new byte[256]; // Get the current keyboard state if (!PInvoke.GetKeyboardState(state)) return buffer.ToString(); // Convert the key to its virtual key code var virtualKey = (uint)key; // Map the virtual key to a scan code var scanCode = PInvoke.MapVirtualKey(virtualKey, 0); // Get the active keyboard layout var keyboardLayout = PInvoke.GetKeyboardLayout(0); if (Win32PInvoke.ToUnicodeEx(virtualKey, scanCode, state, buffer, buffer.Capacity, 0, keyboardLayout) > 0) return buffer[^1].ToString(); return buffer.ToString(); } } }
HotKey
csharp
dotnet__aspnetcore
src/SignalR/common/Http.Connections/test/HttpConnectionDispatcherTests.cs
{ "start": 54650, "end": 113660 }
private class ____ : Stream { private readonly SyncPoint _sync; private bool _isSSE; public BlockingStream(SyncPoint sync, bool isSSE = false) { _sync = sync; _isSSE = isSSE; } public override bool CanRead => throw new NotImplementedException(); public override bool CanSeek => throw new NotImplementedException(); public override bool CanWrite => throw new NotImplementedException(); public override long Length => throw new NotImplementedException(); public override long Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { throw new NotImplementedException(); } public override void Flush() { } public override int Read(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } public override void SetLength(long value) { throw new NotImplementedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (_isSSE) { // SSE does an initial write of :\r\n that we want to ignore in testing _isSSE = false; return; } await _sync.WaitToContinue(); cancellationToken.ThrowIfCancellationRequested(); } public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) { if (_isSSE) { // SSE does an initial write of :\r\n that we want to ignore in testing _isSSE = false; return; } await _sync.WaitToContinue(); cancellationToken.ThrowIfCancellationRequested(); } } [Fact] [LogLevel(LogLevel.Debug)] public async Task LongPollingConnectionClosesWhenSendTimeoutReached() { bool ExpectedErrors(WriteContext writeContext) { return (writeContext.LoggerName == typeof(Internal.Transports.LongPollingServerTransport).FullName && writeContext.EventId.Name == "LongPollingTerminated") || (writeContext.LoggerName == typeof(HttpConnectionManager).FullName && writeContext.EventId.Name == "FailedDispose"); } using (StartVerifiableLog(expectedErrorsFilter: ExpectedErrors)) { var initialTime = TimeSpan.FromMilliseconds(Environment.TickCount64); var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; var dispatcher = CreateDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); services.AddSingleton<TestConnectionHandler>(); var context = MakeRequest("/foo", connection, services); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler<TestConnectionHandler>(); var app = builder.Build(); // First poll completes immediately var options = new HttpConnectionDispatcherOptions(); await dispatcher.ExecuteAsync(context, options, app).DefaultTimeout(); var sync = new SyncPoint(); context.Response.Body = new BlockingStream(sync); var dispatcherTask = dispatcher.ExecuteAsync(context, options, app); await connection.Transport.Output.WriteAsync(new byte[] { 1 }).DefaultTimeout(); await sync.WaitForSyncPoint().DefaultTimeout(); // Try cancel before cancellation should occur connection.TryCancelSend(initialTime + options.TransportSendTimeout); Assert.False(connection.SendingToken.IsCancellationRequested); // Cancel write to response body connection.TryCancelSend(TimeSpan.FromMilliseconds(Environment.TickCount64) + options.TransportSendTimeout + TimeSpan.FromTicks(1)); Assert.True(connection.SendingToken.IsCancellationRequested); sync.Continue(); await dispatcherTask.DefaultTimeout(); // Connection should be removed on canceled write Assert.False(manager.TryGetConnection(connection.ConnectionId, out var _)); } } [Fact] [LogLevel(LogLevel.Debug)] public async Task SSEConnectionClosesWhenSendTimeoutReached() { using (StartVerifiableLog()) { var initialTime = TimeSpan.FromMilliseconds(Environment.TickCount64); var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); var dispatcher = CreateDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); services.AddSingleton<TestConnectionHandler>(); var context = MakeRequest("/foo", connection, services); SetTransport(context, HttpTransportType.ServerSentEvents); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler<TestConnectionHandler>(); var app = builder.Build(); var sync = new SyncPoint(); context.Response.Body = new BlockingStream(sync, isSSE: true); var options = new HttpConnectionDispatcherOptions(); var dispatcherTask = dispatcher.ExecuteAsync(context, options, app); await connection.Transport.Output.WriteAsync(new byte[] { 1 }).DefaultTimeout(); await sync.WaitForSyncPoint().DefaultTimeout(); // Try cancel before cancellation should occur connection.TryCancelSend(initialTime + options.TransportSendTimeout); Assert.False(connection.SendingToken.IsCancellationRequested); // Cancel write to response body connection.TryCancelSend(TimeSpan.FromMilliseconds(Environment.TickCount64) + options.TransportSendTimeout + TimeSpan.FromTicks(1)); Assert.True(connection.SendingToken.IsCancellationRequested); sync.Continue(); await dispatcherTask.DefaultTimeout(); // Connection should be removed on canceled write Assert.False(manager.TryGetConnection(connection.ConnectionId, out var _)); } } [Fact] [LogLevel(LogLevel.Debug)] public async Task WebSocketConnectionClosesWhenSendTimeoutReached() { bool ExpectedErrors(WriteContext writeContext) { return writeContext.LoggerName == typeof(Internal.Transports.WebSocketsServerTransport).FullName && writeContext.EventId.Name == "ErrorWritingFrame"; } using (StartVerifiableLog(expectedErrorsFilter: ExpectedErrors)) { var initialTime = TimeSpan.FromMilliseconds(Environment.TickCount64); var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); var dispatcher = CreateDispatcher(manager, LoggerFactory); var sync = new SyncPoint(); var services = new ServiceCollection(); services.AddSingleton<TestConnectionHandler>(); var context = MakeRequest("/foo", connection, services); SetTransport(context, HttpTransportType.WebSockets, sync); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler<TestConnectionHandler>(); var app = builder.Build(); var options = new HttpConnectionDispatcherOptions(); options.WebSockets.CloseTimeout = TimeSpan.FromSeconds(0); var dispatcherTask = dispatcher.ExecuteAsync(context, options, app); await connection.Transport.Output.WriteAsync(new byte[] { 1 }).DefaultTimeout(); await sync.WaitForSyncPoint().DefaultTimeout(); // Try cancel before cancellation should occur connection.TryCancelSend(initialTime + options.TransportSendTimeout); Assert.False(connection.SendingToken.IsCancellationRequested); // Cancel write to response body connection.TryCancelSend(TimeSpan.FromMilliseconds(Environment.TickCount64) + options.TransportSendTimeout + TimeSpan.FromTicks(1)); Assert.True(connection.SendingToken.IsCancellationRequested); sync.Continue(); await dispatcherTask.DefaultTimeout(); // Connection should be removed on canceled write Assert.False(manager.TryGetConnection(connection.ConnectionId, out var _)); } } [Fact] [LogLevel(LogLevel.Trace)] public async Task WebSocketTransportTimesOutWhenCloseFrameNotReceived() { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.WebSockets; var dispatcher = CreateDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); services.AddSingleton<ImmediatelyCompleteConnectionHandler>(); var context = MakeRequest("/foo", connection, services); SetTransport(context, HttpTransportType.WebSockets); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler<ImmediatelyCompleteConnectionHandler>(); var app = builder.Build(); var options = new HttpConnectionDispatcherOptions(); options.WebSockets.CloseTimeout = TimeSpan.FromSeconds(1); var task = dispatcher.ExecuteAsync(context, options, app); await task.DefaultTimeout(); } } [Theory] [InlineData(HttpTransportType.WebSockets)] [InlineData(HttpTransportType.ServerSentEvents)] public async Task RequestToActiveConnectionId409ForStreamingTransports(HttpTransportType transportType) { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); var dispatcher = CreateDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); services.AddSingleton<TestConnectionHandler>(); var context1 = MakeRequest("/foo", connection, services); var context2 = MakeRequest("/foo", connection, services); SetTransport(context1, transportType); SetTransport(context2, transportType); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler<TestConnectionHandler>(); var app = builder.Build(); var options = new HttpConnectionDispatcherOptions(); var request1 = dispatcher.ExecuteAsync(context1, options, app); await dispatcher.ExecuteAsync(context2, options, app).DefaultTimeout(); Assert.False(request1.IsCompleted); Assert.Equal(StatusCodes.Status409Conflict, context2.Response.StatusCode); Assert.NotSame(connection.HttpContext, context2); var webSocketTask = Task.CompletedTask; var ws = (TestWebSocketConnectionFeature)context1.Features.Get<IHttpWebSocketFeature>(); if (ws != null) { await ws.Client.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); } manager.CloseConnections(); await request1.DefaultTimeout(); } } [Fact] public async Task RequestToActiveConnectionIdKillsPreviousConnectionLongPolling() { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; var dispatcher = CreateDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); services.AddSingleton<TestConnectionHandler>(); var context1 = MakeRequest("/foo", connection, services); var context2 = MakeRequest("/foo", connection, services); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler<TestConnectionHandler>(); var app = builder.Build(); var options = new HttpConnectionDispatcherOptions(); var request1 = dispatcher.ExecuteAsync(context1, options, app); Assert.True(request1.IsCompleted); request1 = dispatcher.ExecuteAsync(context1, options, app); var count = 0; // Wait until the request has started internally while (connection.TransportTask.IsCompleted && count < 50) { count++; await Task.Delay(15); } if (count == 50) { Assert.Fail("Poll took too long to start"); } var request2 = dispatcher.ExecuteAsync(context2, options, app); // Wait for poll to be canceled await request1.DefaultTimeout(); Assert.Equal(StatusCodes.Status204NoContent, context1.Response.StatusCode); AssertResponseHasCacheHeaders(context1.Response); count = 0; // Wait until the second request has started internally while (connection.TransportTask.IsCompleted && count < 50) { count++; await Task.Delay(15); } if (count == 50) { Assert.Fail("Poll took too long to start"); } Assert.Equal(HttpConnectionStatus.Active, connection.Status); Assert.False(request2.IsCompleted); manager.CloseConnections(); await request2; } } [Fact] public async Task MultipleRequestsToActiveConnectionId409ForLongPolling() { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; var dispatcher = CreateDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); services.AddSingleton<TestConnectionHandler>(); var context1 = MakeRequest("/foo", connection, services); var context2 = MakeRequest("/foo", connection, services); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler<TestConnectionHandler>(); var app = builder.Build(); var options = new HttpConnectionDispatcherOptions(); // Prime the polling. Expect any empty response showing the transport is initialized. var request1 = dispatcher.ExecuteAsync(context1, options, app); Assert.True(request1.IsCompleted); // Manually control PreviousPollTask instead of using a real PreviousPollTask, because a real // PreviousPollTask might complete too early when the second request cancels it. var lastPollTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); connection.PreviousPollTask = lastPollTcs.Task; request1 = dispatcher.ExecuteAsync(context1, options, app); var request2 = dispatcher.ExecuteAsync(context2, options, app); Assert.False(request1.IsCompleted); Assert.False(request2.IsCompleted); lastPollTcs.SetResult(); var completedTask = await Task.WhenAny(request1, request2).DefaultTimeout(); if (completedTask == request1) { Assert.Equal(StatusCodes.Status409Conflict, context1.Response.StatusCode); Assert.False(request2.IsCompleted); AssertResponseHasCacheHeaders(context1.Response); } else { Assert.Equal(StatusCodes.Status409Conflict, context2.Response.StatusCode); Assert.False(request1.IsCompleted); AssertResponseHasCacheHeaders(context2.Response); } Assert.Equal(HttpConnectionStatus.Active, connection.Status); manager.CloseConnections(); await request1.DefaultTimeout(); await request2.DefaultTimeout(); } } [Theory] [InlineData(HttpTransportType.ServerSentEvents)] [InlineData(HttpTransportType.LongPolling)] public async Task RequestToDisposedConnectionIdReturns404(HttpTransportType transportType) { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.Status = HttpConnectionStatus.Disposed; var dispatcher = CreateDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); services.AddSingleton<TestConnectionHandler>(); var context = MakeRequest("/foo", connection, services); SetTransport(context, transportType); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler<TestConnectionHandler>(); var app = builder.Build(); var options = new HttpConnectionDispatcherOptions(); await dispatcher.ExecuteAsync(context, options, app); Assert.Equal(StatusCodes.Status404NotFound, context.Response.StatusCode); if (transportType == HttpTransportType.LongPolling) { AssertResponseHasCacheHeaders(context.Response); } } } [Fact] public async Task ConnectionStateSetToInactiveAfterPoll() { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; var dispatcher = CreateDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); services.AddSingleton<TestConnectionHandler>(); var context = MakeRequest("/foo", connection, services); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler<TestConnectionHandler>(); var app = builder.Build(); var options = new HttpConnectionDispatcherOptions(); var task = dispatcher.ExecuteAsync(context, options, app); var buffer = Encoding.UTF8.GetBytes("Hello World"); // Write to the transport so the poll yields await connection.Transport.Output.WriteAsync(buffer); await task; Assert.Equal(HttpConnectionStatus.Inactive, connection.Status); Assert.NotNull(connection.GetHttpContext()); Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode); } } [Fact] public async Task BlockingConnectionWorksWithStreamingConnections() { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); var dispatcher = CreateDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); services.AddSingleton<BlockingConnectionHandler>(); var context = MakeRequest("/foo", connection, services); SetTransport(context, HttpTransportType.ServerSentEvents); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler<BlockingConnectionHandler>(); var app = builder.Build(); var options = new HttpConnectionDispatcherOptions(); var task = dispatcher.ExecuteAsync(context, options, app); var buffer = Encoding.UTF8.GetBytes("Hello World"); // Write to the application await connection.Application.Output.WriteAsync(buffer); await task; Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode); var exists = manager.TryGetConnection(connection.ConnectionToken, out _); Assert.False(exists); } } [Fact] public async Task BlockingConnectionWorksWithLongPollingConnection() { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; var dispatcher = CreateDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); services.AddSingleton<BlockingConnectionHandler>(); var context = MakeRequest("/foo", connection, services); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler<BlockingConnectionHandler>(); var app = builder.Build(); var options = new HttpConnectionDispatcherOptions(); // Initial poll var task = dispatcher.ExecuteAsync(context, options, app); Assert.True(task.IsCompleted); Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode); // Real long running poll task = dispatcher.ExecuteAsync(context, options, app); var buffer = Encoding.UTF8.GetBytes("Hello World"); // Write to the application await connection.Application.Output.WriteAsync(buffer); await task; Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode); AssertResponseHasCacheHeaders(context.Response); var exists = manager.TryGetConnection(connection.ConnectionToken, out _); Assert.False(exists); } } [Fact] public async Task AttemptingToPollWhileAlreadyPollingReplacesTheCurrentPoll() { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; var dispatcher = CreateDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); services.AddSingleton<TestConnectionHandler>(); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler<TestConnectionHandler>(); var app = builder.Build(); var options = new HttpConnectionDispatcherOptions(); var context1 = MakeRequest("/foo", connection, services); // This is the initial poll to make sure things are setup var task1 = dispatcher.ExecuteAsync(context1, options, app); Assert.True(task1.IsCompleted); task1 = dispatcher.ExecuteAsync(context1, options, app); var context2 = MakeRequest("/foo", connection, services); var task2 = dispatcher.ExecuteAsync(context2, options, app); // Task 1 should finish when request 2 arrives await task1.DefaultTimeout(); // Send a message from the app to complete Task 2 await connection.Transport.Output.WriteAsync(Encoding.UTF8.GetBytes("Hello, World")); await task2.DefaultTimeout(); // Verify the results Assert.Equal(StatusCodes.Status204NoContent, context1.Response.StatusCode); Assert.Equal(string.Empty, GetContentAsString(context1.Response.Body)); AssertResponseHasCacheHeaders(context1.Response); Assert.Equal(StatusCodes.Status200OK, context2.Response.StatusCode); Assert.Equal("Hello, World", GetContentAsString(context2.Response.Body)); AssertResponseHasCacheHeaders(context2.Response); } } [Theory] [InlineData(HttpTransportType.LongPolling, null)] [InlineData(HttpTransportType.ServerSentEvents, TransferFormat.Text)] [InlineData(HttpTransportType.WebSockets, TransferFormat.Binary | TransferFormat.Text)] public async Task TransferModeSet(HttpTransportType transportType, TransferFormat? expectedTransferFormats) { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); var dispatcher = CreateDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); services.AddSingleton<ImmediatelyCompleteConnectionHandler>(); var context = MakeRequest("/foo", connection, services); SetTransport(context, transportType); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler<ImmediatelyCompleteConnectionHandler>(); var app = builder.Build(); var options = new HttpConnectionDispatcherOptions(); options.WebSockets.CloseTimeout = TimeSpan.FromSeconds(0); await dispatcher.ExecuteAsync(context, options, app); if (expectedTransferFormats != null) { var transferFormatFeature = connection.Features.Get<ITransferFormatFeature>(); Assert.Equal(expectedTransferFormats.Value, transferFormatFeature.SupportedFormats); } } } [ConditionalFact] [OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)] public async Task LongPollingKeepsWindowsPrincipalAndIdentityBetweenRequests() { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; var dispatcher = CreateDispatcher(manager, LoggerFactory); var context = new DefaultHttpContext(); var services = new ServiceCollection(); services.AddOptions(); services.AddSingleton<TestConnectionHandler>(); services.AddLogging(); var sp = services.BuildServiceProvider(); context.Request.Path = "/foo"; context.Request.Method = "GET"; context.RequestServices = sp; var values = new Dictionary<string, StringValues>(); values["id"] = connection.ConnectionToken; values["negotiateVersion"] = "1"; var qs = new QueryCollection(values); context.Request.Query = qs; var builder = new ConnectionBuilder(sp); builder.UseConnectionHandler<TestConnectionHandler>(); var app = builder.Build(); var options = new HttpConnectionDispatcherOptions(); var windowsIdentity = WindowsIdentity.GetAnonymous(); context.User = new WindowsPrincipal(windowsIdentity); context.User.AddIdentity(new ClaimsIdentity()); // would get stuck if EndPoint was running await dispatcher.ExecuteAsync(context, options, app).DefaultTimeout(); Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode); var currentUser = connection.User; var connectionHandlerTask = dispatcher.ExecuteAsync(context, options, app); await connection.Transport.Output.WriteAsync(Encoding.UTF8.GetBytes("Unblock")).AsTask().DefaultTimeout(); await connectionHandlerTask.DefaultTimeout(); // This is the important check Assert.Same(currentUser, connection.User); Assert.IsType<WindowsPrincipal>(currentUser); Assert.Equal(2, connection.User.Identities.Count()); Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode); } } [ConditionalFact] [OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)] public async Task LongPollingKeepsWindowsIdentityWithoutWindowsPrincipalBetweenRequests() { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; var dispatcher = CreateDispatcher(manager, LoggerFactory); var context = new DefaultHttpContext(); var services = new ServiceCollection(); services.AddOptions(); services.AddSingleton<TestConnectionHandler>(); services.AddLogging(); var sp = services.BuildServiceProvider(); context.Request.Path = "/foo"; context.Request.Method = "GET"; context.RequestServices = sp; var values = new Dictionary<string, StringValues>(); values["id"] = connection.ConnectionToken; values["negotiateVersion"] = "1"; var qs = new QueryCollection(values); context.Request.Query = qs; var builder = new ConnectionBuilder(sp); builder.UseConnectionHandler<TestConnectionHandler>(); var app = builder.Build(); var options = new HttpConnectionDispatcherOptions(); var windowsIdentity = WindowsIdentity.GetAnonymous(); context.User = new ClaimsPrincipal(windowsIdentity); context.User.AddIdentity(new ClaimsIdentity()); // would get stuck if EndPoint was running await dispatcher.ExecuteAsync(context, options, app).DefaultTimeout(); Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode); var currentUser = connection.User; var connectionHandlerTask = dispatcher.ExecuteAsync(context, options, app); await connection.Transport.Output.WriteAsync(Encoding.UTF8.GetBytes("Unblock")).AsTask().DefaultTimeout(); await connectionHandlerTask.DefaultTimeout(); // This is the important check Assert.Same(currentUser, connection.User); Assert.IsNotType<WindowsPrincipal>(currentUser); Assert.Equal(2, connection.User.Identities.Count()); Assert.Equal(StatusCodes.Status200OK, context.Response.StatusCode); } } [ConditionalTheory] [OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)] [InlineData(HttpTransportType.LongPolling)] [InlineData(HttpTransportType.ServerSentEvents)] [InlineData(HttpTransportType.WebSockets)] public async Task WindowsIdentityNotClosed(HttpTransportType transportType) { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = transportType; var dispatcher = CreateDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); services.AddOptions(); services.AddSingleton<TestConnectionHandler>(); services.AddLogging(); var context = MakeRequest("/foo", connection, services); SetTransport(context, transportType); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler<ImmediatelyCompleteConnectionHandler>(); var app = builder.Build(); var options = new HttpConnectionDispatcherOptions(); options.WebSockets.CloseTimeout = TimeSpan.FromSeconds(0); var windowsIdentity = WindowsIdentity.GetAnonymous(); context.User = new WindowsPrincipal(windowsIdentity); context.User.AddIdentity(new ClaimsIdentity()); if (transportType == HttpTransportType.LongPolling) { // first poll effectively noops await dispatcher.ExecuteAsync(context, options, app).DefaultTimeout(); } await dispatcher.ExecuteAsync(context, options, app).DefaultTimeout(); // Identity shouldn't be closed by the connections layer Assert.False(windowsIdentity.AccessToken.IsClosed); if (transportType == HttpTransportType.LongPolling) { // Long polling clones the user, make sure it disposes it too Assert.True(((WindowsIdentity)connection.User.Identity).AccessToken.IsClosed); } } } [Fact] public async Task SetsInherentKeepAliveFeatureOnFirstLongPollingRequest() { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; var dispatcher = CreateDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); services.AddSingleton<TestConnectionHandler>(); var context = MakeRequest("/foo", connection, services); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler<TestConnectionHandler>(); var app = builder.Build(); var options = new HttpConnectionDispatcherOptions(); options.LongPolling.PollTimeout = TimeSpan.FromMilliseconds(1); // We don't care about the poll itself await dispatcher.ExecuteAsync(context, options, app).DefaultTimeout(); Assert.True(connection.HasInherentKeepAlive); // Check via the feature as well to make sure it's there. Assert.True(connection.Features.Get<IConnectionInherentKeepAliveFeature>().HasInherentKeepAlive); } } [Theory] [InlineData(HttpTransportType.ServerSentEvents)] [InlineData(HttpTransportType.WebSockets)] public async Task DeleteEndpointRejectsRequestToTerminateNonLongPollingTransport(HttpTransportType transportType) { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = transportType; var dispatcher = CreateDispatcher(manager, LoggerFactory); var serviceCollection = new ServiceCollection(); serviceCollection.AddSingleton<TestConnectionHandler>(); var context = MakeRequest("/foo", connection, serviceCollection); SetTransport(context, transportType); var services = serviceCollection.BuildServiceProvider(); var builder = new ConnectionBuilder(services); builder.UseConnectionHandler<TestConnectionHandler>(); var app = builder.Build(); var options = new HttpConnectionDispatcherOptions(); _ = dispatcher.ExecuteAsync(context, options, app).DefaultTimeout(); // Issue the delete request var deleteContext = new DefaultHttpContext(); deleteContext.Request.Path = "/foo"; deleteContext.Request.QueryString = new QueryString($"?id={connection.ConnectionToken}"); deleteContext.Request.Method = "DELETE"; var ms = new MemoryStream(); deleteContext.Response.Body = ms; await dispatcher.ExecuteAsync(deleteContext, options, app).DefaultTimeout(); // Verify the response from the DELETE request Assert.Equal(StatusCodes.Status400BadRequest, deleteContext.Response.StatusCode); Assert.Equal("text/plain", deleteContext.Response.ContentType); Assert.Equal("Cannot terminate this connection using the DELETE endpoint.", Encoding.UTF8.GetString(ms.ToArray())); } } [Fact] public async Task DeleteEndpointGracefullyTerminatesLongPolling() { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; var dispatcher = CreateDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); services.AddSingleton<TestConnectionHandler>(); var context = MakeRequest("/foo", connection, services); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler<TestConnectionHandler>(); var app = builder.Build(); var options = new HttpConnectionDispatcherOptions(); var pollTask = dispatcher.ExecuteAsync(context, options, app); Assert.True(pollTask.IsCompleted); // Now send the second poll pollTask = dispatcher.ExecuteAsync(context, options, app); // Issue the delete request and make sure the poll completes var deleteContext = new DefaultHttpContext(); deleteContext.Request.Path = "/foo"; deleteContext.Request.QueryString = new QueryString($"?id={connection.ConnectionToken}"); deleteContext.Request.Method = "DELETE"; Assert.False(pollTask.IsCompleted); await dispatcher.ExecuteAsync(deleteContext, options, app).DefaultTimeout(); await pollTask.DefaultTimeout(); // Verify that everything shuts down await connection.ApplicationTask.DefaultTimeout(); await connection.TransportTask.DefaultTimeout(); // Verify the response from the DELETE request Assert.Equal(StatusCodes.Status202Accepted, deleteContext.Response.StatusCode); Assert.Equal("text/plain", deleteContext.Response.ContentType); await connection.DisposeAndRemoveTask.DefaultTimeout(); // Verify the connection was removed from the manager Assert.False(manager.TryGetConnection(connection.ConnectionToken, out _)); } } [Fact] public async Task DeleteEndpointGracefullyTerminatesLongPollingEvenWhenBetweenPolls() { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = HttpTransportType.LongPolling; var dispatcher = CreateDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); services.AddSingleton<TestConnectionHandler>(); var context = MakeRequest("/foo", connection, services); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler<TestConnectionHandler>(); var app = builder.Build(); var options = new HttpConnectionDispatcherOptions(); options.LongPolling.PollTimeout = TimeSpan.FromMilliseconds(1); await dispatcher.ExecuteAsync(context, options, app).DefaultTimeout(); // Issue the delete request and make sure the poll completes var deleteContext = new DefaultHttpContext(); deleteContext.Request.Path = "/foo"; deleteContext.Request.QueryString = new QueryString($"?id={connection.ConnectionToken}"); deleteContext.Request.Method = "DELETE"; await dispatcher.ExecuteAsync(deleteContext, options, app).DefaultTimeout(); // Verify the response from the DELETE request Assert.Equal(StatusCodes.Status202Accepted, deleteContext.Response.StatusCode); Assert.Equal("text/plain", deleteContext.Response.ContentType); // Verify that everything shuts down await connection.ApplicationTask.DefaultTimeout(); await connection.TransportTask.DefaultTimeout(); Assert.NotNull(connection.DisposeAndRemoveTask); await connection.DisposeAndRemoveTask.DefaultTimeout(); // Verify the connection was removed from the manager Assert.False(manager.TryGetConnection(connection.ConnectionToken, out _)); } } [Fact] public async Task DeleteEndpointTerminatesLongPollingWithHangingApplication() { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var options = new HttpConnectionDispatcherOptions { TransportMaxBufferSize = 2, ApplicationMaxBufferSize = 2 }; var connection = manager.CreateConnection(options); connection.TransportType = HttpTransportType.LongPolling; var dispatcher = CreateDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); services.AddSingleton<NeverEndingConnectionHandler>(); var context = MakeRequest("/foo", connection, services); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler<NeverEndingConnectionHandler>(); var app = builder.Build(); var pollTask = dispatcher.ExecuteAsync(context, options, app); Assert.True(pollTask.IsCompleted); // Now send the second poll pollTask = dispatcher.ExecuteAsync(context, options, app); // Issue the delete request and make sure the poll completes var deleteContext = new DefaultHttpContext(); deleteContext.Request.Path = "/foo"; deleteContext.Request.QueryString = new QueryString($"?id={connection.ConnectionId}"); deleteContext.Request.Method = "DELETE"; Assert.False(pollTask.IsCompleted); await dispatcher.ExecuteAsync(deleteContext, options, app).DefaultTimeout(); await pollTask.DefaultTimeout(); // Verify that transport shuts down await connection.TransportTask.DefaultTimeout(); // Verify the response from the DELETE request Assert.Equal(StatusCodes.Status202Accepted, deleteContext.Response.StatusCode); Assert.Equal("text/plain", deleteContext.Response.ContentType); Assert.Equal(HttpConnectionStatus.Disposed, connection.Status); // Verify the connection not removed because application is hanging Assert.True(manager.TryGetConnection(connection.ConnectionId, out _)); } } [Fact] public async Task PollCanReceiveFinalMessageAfterAppCompletes() { using (StartVerifiableLog()) { var transportType = HttpTransportType.LongPolling; var manager = CreateConnectionManager(LoggerFactory); var dispatcher = CreateDispatcher(manager, LoggerFactory); var connection = manager.CreateConnection(); connection.TransportType = transportType; var waitForMessageTcs1 = new TaskCompletionSource(); var messageTcs1 = new TaskCompletionSource(); var waitForMessageTcs2 = new TaskCompletionSource(); var messageTcs2 = new TaskCompletionSource(); ConnectionDelegate connectionDelegate = async c => { await waitForMessageTcs1.Task.DefaultTimeout(); await c.Transport.Output.WriteAsync(Encoding.UTF8.GetBytes("Message1")).DefaultTimeout(); messageTcs1.TrySetResult(); await waitForMessageTcs2.Task.DefaultTimeout(); await c.Transport.Output.WriteAsync(Encoding.UTF8.GetBytes("Message2")).DefaultTimeout(); messageTcs2.TrySetResult(); }; { var options = new HttpConnectionDispatcherOptions(); var context = MakeRequest("/foo", connection, new ServiceCollection()); await dispatcher.ExecuteAsync(context, options, connectionDelegate).DefaultTimeout(); // second poll should have data waitForMessageTcs1.SetResult(); await messageTcs1.Task.DefaultTimeout(); var ms = new MemoryStream(); context.Response.Body = ms; // Now send the second poll await dispatcher.ExecuteAsync(context, options, connectionDelegate).DefaultTimeout(); Assert.Equal("Message1", Encoding.UTF8.GetString(ms.ToArray())); waitForMessageTcs2.SetResult(); await messageTcs2.Task.DefaultTimeout(); context = MakeRequest("/foo", connection, new ServiceCollection()); ms.Seek(0, SeekOrigin.Begin); context.Response.Body = ms; // This is the third poll which gets the final message after the app is complete await dispatcher.ExecuteAsync(context, options, connectionDelegate).DefaultTimeout(); Assert.Equal("Message2", Encoding.UTF8.GetString(ms.ToArray())); } } } [Fact] public async Task NegotiateDoesNotReturnWebSocketsWhenNotAvailable() { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var dispatcher = CreateDispatcher(manager, LoggerFactory); var context = new DefaultHttpContext(); context.Features.Set<IHttpResponseFeature>(new ResponseFeature()); var services = new ServiceCollection(); services.AddSingleton<TestConnectionHandler>(); services.AddOptions(); var ms = new MemoryStream(); context.Request.Path = "/foo"; context.Request.Method = "POST"; context.Response.Body = ms; context.Request.QueryString = new QueryString("?negotiateVersion=1"); await dispatcher.ExecuteNegotiateAsync(context, new HttpConnectionDispatcherOptions { Transports = HttpTransportType.WebSockets }); var negotiateResponse = JsonConvert.DeserializeObject<JObject>(Encoding.UTF8.GetString(ms.ToArray())); var availableTransports = (JArray)negotiateResponse["availableTransports"]; Assert.Empty(availableTransports); } } [Fact] public async Task NegotiateDoesNotReturnUseStatefulReconnectWhenNotEnabledOnServer() { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var dispatcher = CreateDispatcher(manager, LoggerFactory); var context = new DefaultHttpContext(); context.Features.Set<IHttpResponseFeature>(new ResponseFeature()); var services = new ServiceCollection(); services.AddSingleton<TestConnectionHandler>(); services.AddOptions(); var ms = new MemoryStream(); context.Request.Path = "/foo"; context.Request.Method = "POST"; context.Response.Body = ms; context.Request.QueryString = new QueryString("?negotiateVersion=1&UseStatefulReconnect=true"); await dispatcher.ExecuteNegotiateAsync(context, new HttpConnectionDispatcherOptions { AllowStatefulReconnects = false }); var negotiateResponse = JsonConvert.DeserializeObject<JObject>(Encoding.UTF8.GetString(ms.ToArray())); Assert.False(negotiateResponse.TryGetValue("useStatefulReconnect", out _)); Assert.True(manager.TryGetConnection(negotiateResponse["connectionToken"].ToString(), out var connection)); #pragma warning disable CA2252 // This API requires opting into preview features Assert.Null(connection.Features.Get<IStatefulReconnectFeature>()); #pragma warning restore CA2252 // This API requires opting into preview features } } [Fact] public async Task NegotiateDoesNotReturnUseStatefulReconnectWhenEnabledOnServerButNotRequestedByClient() { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var dispatcher = CreateDispatcher(manager, LoggerFactory); var context = new DefaultHttpContext(); context.Features.Set<IHttpResponseFeature>(new ResponseFeature()); var services = new ServiceCollection(); services.AddSingleton<TestConnectionHandler>(); services.AddOptions(); var ms = new MemoryStream(); context.Request.Path = "/foo"; context.Request.Method = "POST"; context.Response.Body = ms; context.Request.QueryString = new QueryString("?negotiateVersion=1"); await dispatcher.ExecuteNegotiateAsync(context, new HttpConnectionDispatcherOptions { AllowStatefulReconnects = true }); var negotiateResponse = JsonConvert.DeserializeObject<JObject>(Encoding.UTF8.GetString(ms.ToArray())); Assert.False(negotiateResponse.TryGetValue("useStatefulReconnect", out _)); Assert.True(manager.TryGetConnection(negotiateResponse["connectionToken"].ToString(), out var connection)); #pragma warning disable CA2252 // This API requires opting into preview features Assert.Null(connection.Features.Get<IStatefulReconnectFeature>()); #pragma warning restore CA2252 // This API requires opting into preview features } } [Fact] public async Task NegotiateReturnsUseStatefulReconnectWhenEnabledOnServerAndRequestedByClient() { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var dispatcher = CreateDispatcher(manager, LoggerFactory); var context = new DefaultHttpContext(); context.Features.Set<IHttpResponseFeature>(new ResponseFeature()); var services = new ServiceCollection(); services.AddSingleton<TestConnectionHandler>(); services.AddOptions(); var ms = new MemoryStream(); context.Request.Path = "/foo"; context.Request.Method = "POST"; context.Response.Body = ms; context.Request.QueryString = new QueryString("?negotiateVersion=1&UseStatefulReconnect=true"); await dispatcher.ExecuteNegotiateAsync(context, new HttpConnectionDispatcherOptions { AllowStatefulReconnects = true }); var negotiateResponse = JsonConvert.DeserializeObject<JObject>(Encoding.UTF8.GetString(ms.ToArray())); Assert.True((bool)negotiateResponse["useStatefulReconnect"]); Assert.True(manager.TryGetConnection(negotiateResponse["connectionToken"].ToString(), out var connection)); #pragma warning disable CA2252 // This API requires opting into preview features Assert.NotNull(connection.Features.Get<IStatefulReconnectFeature>()); #pragma warning restore CA2252 // This API requires opting into preview features } } [Fact] public async Task ReconnectStopsPreviousConnection() { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var options = new HttpConnectionDispatcherOptions() { AllowStatefulReconnects = true }; options.WebSockets.CloseTimeout = TimeSpan.FromMilliseconds(1); // pretend negotiate occurred var connection = manager.CreateConnection(options, negotiateVersion: 1, useStatefulReconnect: true); connection.TransportType = HttpTransportType.WebSockets; var dispatcher = CreateDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); var context = MakeRequest("/foo", connection, services); SetTransport(context, HttpTransportType.WebSockets); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler<ReconnectConnectionHandler>(); var app = builder.Build(); var initialWebSocketTask = dispatcher.ExecuteAsync(context, options, app); #pragma warning disable CA2252 // This API requires opting into preview features var reconnectFeature = connection.Features.Get<IStatefulReconnectFeature>(); #pragma warning restore CA2252 // This API requires opting into preview features Assert.NotNull(reconnectFeature); var firstMsg = new byte[] { 1, 4, 8, 9 }; await connection.Application.Output.WriteAsync(firstMsg); var websocketFeature = (TestWebSocketConnectionFeature)context.Features.Get<IHttpWebSocketFeature>(); await websocketFeature.Accepted.DefaultTimeout(); // Run the client socket var webSocketMessage = await websocketFeature.Client.GetNextMessageAsync().DefaultTimeout(); Assert.Equal(firstMsg, webSocketMessage.Buffer); var calledOnReconnectedTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); #pragma warning disable CA2252 // This API requires opting into preview features reconnectFeature.OnReconnected((writer) => { calledOnReconnectedTcs.SetResult(); return Task.CompletedTask; }); #pragma warning restore CA2252 // This API requires opting into preview features // New websocket connection with previous connection token context = MakeRequest("/foo", connection, services); SetTransport(context, HttpTransportType.WebSockets); var newWebSocketTask = dispatcher.ExecuteAsync(context, options, app); // New connection with same token will complete previous request await initialWebSocketTask.DefaultTimeout(); await calledOnReconnectedTcs.Task.DefaultTimeout(); Assert.False(newWebSocketTask.IsCompleted); var secondMsg = new byte[] { 7, 6, 3, 2 }; await connection.Application.Output.WriteAsync(secondMsg); websocketFeature = (TestWebSocketConnectionFeature)context.Features.Get<IHttpWebSocketFeature>(); await websocketFeature.Accepted.DefaultTimeout(); webSocketMessage = await websocketFeature.Client.GetNextMessageAsync().DefaultTimeout(); Assert.Equal(secondMsg, webSocketMessage.Buffer); connection.Abort(); await newWebSocketTask.DefaultTimeout(); } } [Fact] public async Task DisableReconnectDisallowsReplacementConnection() { using (StartVerifiableLog()) { var manager = CreateConnectionManager(LoggerFactory); var options = new HttpConnectionDispatcherOptions() { AllowStatefulReconnects = true }; options.WebSockets.CloseTimeout = TimeSpan.FromMilliseconds(1); // pretend negotiate occurred var connection = manager.CreateConnection(options, negotiateVersion: 1, useStatefulReconnect: true); var dispatcher = CreateDispatcher(manager, LoggerFactory); var services = new ServiceCollection(); var context = MakeRequest("/foo", connection, services); SetTransport(context, HttpTransportType.WebSockets); var builder = new ConnectionBuilder(services.BuildServiceProvider()); builder.UseConnectionHandler<ReconnectConnectionHandler>(); var app = builder.Build(); var initialWebSocketTask = dispatcher.ExecuteAsync(context, options, app); #pragma warning disable CA2252 // This API requires opting into preview features var reconnectFeature = connection.Features.Get<IStatefulReconnectFeature>(); #pragma warning restore CA2252 // This API requires opting into preview features Assert.NotNull(reconnectFeature); var firstMsg = new byte[] { 1, 4, 8, 9 }; await connection.Application.Output.WriteAsync(firstMsg); var websocketFeature = (TestWebSocketConnectionFeature)context.Features.Get<IHttpWebSocketFeature>(); await websocketFeature.Accepted.DefaultTimeout(); // Run the client socket var webSocketMessage = await websocketFeature.Client.GetNextMessageAsync().DefaultTimeout(); Assert.Equal(firstMsg, webSocketMessage.Buffer); var called = false; #pragma warning disable CA2252 // This API requires opting into preview features reconnectFeature.OnReconnected((writer) => { called = true; return Task.CompletedTask; }); #pragma warning restore CA2252 // This API requires opting into preview features // Disable will not allow new connection to override existing #pragma warning disable CA2252 // This API requires opting into preview features reconnectFeature.DisableReconnect(); #pragma warning restore CA2252 // This API requires opting into preview features // New websocket connection with previous connection token context = MakeRequest("/foo", connection, services); SetTransport(context, HttpTransportType.WebSockets); await dispatcher.ExecuteAsync(context, options, app).DefaultTimeout(); Assert.Equal(409, context.Response.StatusCode); Assert.False(called); // Connection still works var secondMsg = new byte[] { 7, 6, 3, 2 }; await connection.Application.Output.WriteAsync(secondMsg); webSocketMessage = await websocketFeature.Client.GetNextMessageAsync().DefaultTimeout(); Assert.Equal(secondMsg, webSocketMessage.Buffer); connection.Abort(); await initialWebSocketTask.DefaultTimeout(); } }
BlockingStream
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Driver/Linq/Linq3Implementation/Translators/ExpressionToAggregationExpressionTranslators/MethodTranslators/SubstringMethodToAggregationExpressionTranslator.cs
{ "start": 1019, "end": 4062 }
internal static class ____ { public static TranslatedExpression Translate(TranslationContext context, MethodCallExpression expression) { var method = expression.Method; var arguments = expression.Arguments; if (method.IsOneOf(StringMethod.Substring, StringMethod.SubstringWithLength)) { var stringExpression = expression.Object; var startIndexExpression = arguments[0]; var lengthExpression = arguments.Count == 2 ? arguments[1] : null; return TranslateHelper(context, expression, stringExpression, startIndexExpression, lengthExpression, AstTernaryOperator.SubstrCP); } if (method.Is(StringMethod.SubstrBytes)) { var stringExpression = arguments[0]; var startIndexExpression = arguments[1]; var lengthExpression = arguments[2]; return TranslateHelper(context, expression, stringExpression, startIndexExpression, lengthExpression, AstTernaryOperator.SubstrBytes); } throw new ExpressionNotSupportedException(expression); } private static TranslatedExpression TranslateHelper(TranslationContext context, Expression expression, Expression stringExpression, Expression startIndexExpression, Expression lengthExpression, AstTernaryOperator substrOperator) { var stringTranslation = ExpressionToAggregationExpressionTranslator.Translate(context, stringExpression); var startIndexTranslation = ExpressionToAggregationExpressionTranslator.Translate(context, startIndexExpression); SerializationHelper.EnsureRepresentationIsNumeric(expression, startIndexExpression, startIndexTranslation); AstExpression ast; if (lengthExpression == null) { var strlenOperator = substrOperator == AstTernaryOperator.SubstrCP ? AstUnaryOperator.StrLenCP : AstUnaryOperator.StrLenBytes; var (stringVar, stringAst) = AstExpression.UseVarIfNotSimple("string", stringTranslation.Ast); var (indexVar, indexAst) = AstExpression.UseVarIfNotSimple("index", startIndexTranslation.Ast); var lengthAst = AstExpression.StrLen(strlenOperator, stringAst); var countAst = AstExpression.Subtract(lengthAst, indexAst); var inAst = AstExpression.Substr(substrOperator, stringAst, indexAst, countAst); ast = AstExpression.Let(stringVar, indexVar, inAst); } else { var lengthTranslation = ExpressionToAggregationExpressionTranslator.Translate(context, lengthExpression); ast = AstExpression.Substr(substrOperator, stringTranslation.Ast, startIndexTranslation.Ast, lengthTranslation.Ast); } return new TranslatedExpression(expression, ast, new StringSerializer()); } } }
SubstringMethodToAggregationExpressionTranslator
csharp
atata-framework__atata
test/Atata.UnitTests/LogManagerTests.cs
{ "start": 29, "end": 16446 }
public sealed class ____ { private LogConsumerSpy _consumerSpy = null!; [SetUp] public void SetUp() => _consumerSpy = new(); [Test] public void Info_WithSecretString() { using var sut = CreateSut( [new LogConsumerConfiguration(_consumerSpy)], [new SecretStringToMask("abc123", "***")]); sut.Info(@"Set ""abc123"" to something"); _consumerSpy.CollectedEvents.Should.ContainSingle() .Single().ValueOf(x => x.Message).Should.Be(@"Set ""***"" to something"); } [Test] public async Task ExecuteSectionAsync() { using var sut = CreateSut([new LogConsumerConfiguration(_consumerSpy)]); await sut.ExecuteSectionAsync( new StepLogSection("step section"), async () => await sut.ExecuteSectionAsync( new LogSection("trace sub-section", LogLevel.Trace), () => { sut.Trace("inner trace message"); return Task.CompletedTask; })); _consumerSpy.CollectedEventNestedTextsWithMessages.Should.ConsistSequentiallyOf( x => x == "> step section", x => x == "- > trace sub-section", x => x == "- - inner trace message", x => WildcardPattern.IsMatch(x, "- < trace sub-section (*)"), x => WildcardPattern.IsMatch(x, "< step section (*)")); } [Test] public async Task ExecuteSectionAsync_WithResult() { using var sut = CreateSut([new LogConsumerConfiguration(_consumerSpy)]); var result = (await sut.ExecuteSectionAsync( new StepLogSection("step section"), async () => await sut.ExecuteSectionAsync( new LogSection("trace sub-section", LogLevel.Trace), () => { sut.Trace("inner trace message"); return Task.FromResult("ok"); }))).ToResultSubject(); result.Should.Be("ok"); _consumerSpy.CollectedEventNestedTextsWithMessages.Should.ConsistSequentiallyOf( x => x == "> step section", x => x == "- > trace sub-section", x => x == "- - inner trace message", x => WildcardPattern.IsMatch(x, "- < trace sub-section (*) >> \"ok\""), x => WildcardPattern.IsMatch(x, "< step section (*)")); } [Test] public void WhenConsumerSectionEndIsExclude() { using var sut = CreateSut([new LogConsumerConfiguration(_consumerSpy, LogSectionEndOption.Exclude)]); LogStepSectionWithTraceSubSectionContainingTraceAndInfo(sut); _consumerSpy.CollectedEventNestedTextsWithMessages.Should.EqualSequence( "step section", "- trace sub-section", "- - inner info message", "- - inner trace message"); } [Test] public void WhenConsumerSectionEndIsExclude_AndMinLogLevelIsInfo() { using var sut = CreateSut([new LogConsumerConfiguration(_consumerSpy, LogLevel.Info, LogSectionEndOption.Exclude)]); LogStepSectionWithTraceSubSectionContainingTraceAndInfo(sut); _consumerSpy.CollectedEventNestedTextsWithMessages.Should.EqualSequence( "step section", "- inner info message"); } [Test] public void WhenConsumerSectionEndIsIncludeForBlocks() { using var sut = CreateSut([new LogConsumerConfiguration(_consumerSpy, LogSectionEndOption.IncludeForBlocks)]); LogStepSectionWithTraceSubSectionContainingTraceAndInfo(sut); _consumerSpy.CollectedEventNestedTextsWithMessages.Should.ConsistSequentiallyOf( x => x == "> step section", x => x == "- trace sub-section", x => x == "- - inner info message", x => x == "- - inner trace message", x => x.StartsWith("< step section (")); } [Test] public void WhenConsumerSectionEndIsIncludeForBlocks_AndMinLogLevelIsInfo() { using var sut = CreateSut([new LogConsumerConfiguration(_consumerSpy, LogLevel.Info, LogSectionEndOption.IncludeForBlocks)]); LogStepSectionWithTraceSubSectionContainingTraceAndInfo(sut); _consumerSpy.CollectedEventNestedTextsWithMessages.Should.ConsistSequentiallyOf( x => x == "> step section", x => x == "- inner info message", x => x.StartsWith("< step section (")); } [Test] public void WhenConsumerSectionEndIsInclude() { using var sut = CreateSut([new LogConsumerConfiguration(_consumerSpy, LogSectionEndOption.Include)]); LogStepSectionWithTraceSubSectionContainingTraceAndInfo(sut); _consumerSpy.CollectedEventNestedTextsWithMessages.Should.ConsistSequentiallyOf( x => x == "> step section", x => x == "- > trace sub-section", x => x == "- - inner info message", x => x == "- - inner trace message", x => x.StartsWith("- < trace sub-section ("), x => x.StartsWith("< step section (")); } [Test] public void WhenConsumerSectionEndIsInclude_AndMinLogLevelIsInfo() { using var sut = CreateSut([new LogConsumerConfiguration(_consumerSpy, LogLevel.Info, LogSectionEndOption.Include)]); LogStepSectionWithTraceSubSectionContainingTraceAndInfo(sut); _consumerSpy.CollectedEventNestedTextsWithMessages.Should.ConsistSequentiallyOf( x => x == "> step section", x => x == "- inner info message", x => x.StartsWith("< step section (")); } [Test] public void ForCategory() { using var sut = CreateSut([new LogConsumerConfiguration(_consumerSpy)]); const string category1Name = "cat1"; const string category2Name = "cat2"; sut.ExecuteSection( "root section", () => { var subSut1 = sut.ForCategory(category1Name); LogStepSectionWithTraceSubSectionContainingTraceAndInfo(subSut1); var subSut2 = subSut1.ForCategory(category2Name); subSut2.Trace("trace for sub-category"); }); _consumerSpy.CollectedEvents.Should.ConsistSequentiallyOf( x => x.NestingText == "> " && x.Message == "root section" && x.Category == null, x => x.NestingText == "- > " && x.Message == "step section" && x.Category == category1Name, x => x.NestingText == "- - > " && x.Message == "trace sub-section" && x.Category == category1Name, x => x.NestingText == "- - - " && x.Message == "inner info message" && x.Category == category1Name, x => x.NestingText == "- - - " && x.Message == "inner trace message" && x.Category == category1Name, x => x.NestingText == "- - < " && x.Message!.StartsWith("trace sub-section (") && x.Category == category1Name, x => x.NestingText == "- < " && x.Message!.StartsWith("step section (") && x.Category == category1Name, x => x.NestingText == "- " && x.Message == "trace for sub-category" && x.Category == category2Name, x => x.NestingText == "< " && x.Message!.StartsWith("root section (") && x.Category == null); } [Test] public void ForSource_WhenConsumerEmbedSourceLogIsTrue() { using var sut = CreateSut([new LogConsumerConfiguration(_consumerSpy) { EmbedSourceLog = true }]); const string sourceName = "src1"; sut.ExecuteSection( "root section", () => { var subSut1 = sut.ForSource(sourceName); LogStepSectionWithTraceSubSectionContainingTraceAndInfo(subSut1); var subSut2 = subSut1.ForCategory("cat1"); subSut2.Trace("trace for sub-category"); }); _consumerSpy.CollectedEvents.Should.ConsistSequentiallyOf( x => x.NestingText == "> " && x.Message == "root section" && x.Source == null, x => x.NestingText == "- > " && x.Message == "step section" && x.Source == sourceName, x => x.NestingText == "- - > " && x.Message == "trace sub-section" && x.Source == sourceName, x => x.NestingText == "- - - " && x.Message == "inner info message" && x.Source == sourceName, x => x.NestingText == "- - - " && x.Message == "inner trace message" && x.Source == sourceName, x => x.NestingText == "- - < " && x.Message!.StartsWith("trace sub-section (") && x.Source == sourceName, x => x.NestingText == "- < " && x.Message!.StartsWith("step section (") && x.Source == sourceName, x => x.NestingText == "- " && x.Message == "trace for sub-category" && x.Source == sourceName && x.Category == "cat1", x => x.NestingText == "< " && x.Message!.StartsWith("root section (") && x.Source == null); } [Test] public void ForSource_WhenConsumerEmbedSourceLogIsFalse() { using var sut = CreateSut([new LogConsumerConfiguration(_consumerSpy) { EmbedSourceLog = false }]); const string sourceName = "src1"; sut.ExecuteSection( "root section", () => { var subSut1 = sut.ForSource(sourceName); LogStepSectionWithTraceSubSectionContainingTraceAndInfo(subSut1); subSut1.ForCategory("cat1") .Trace("trace ext"); sut.ForCategory("cat2") .Trace("trace non-ext"); }); _consumerSpy.CollectedEvents.Should.ConsistSequentiallyOf( x => x.NestingText == "> " && x.Message == "root section" && x.Source == null, x => x.NestingText == "> " && x.Message == "step section" && x.Source == sourceName, x => x.NestingText == "- > " && x.Message == "trace sub-section" && x.Source == sourceName, x => x.NestingText == "- - " && x.Message == "inner info message" && x.Source == sourceName, x => x.NestingText == "- - " && x.Message == "inner trace message" && x.Source == sourceName, x => x.NestingText == "- < " && x.Message!.StartsWith("trace sub-section (") && x.Source == sourceName, x => x.NestingText == "< " && x.Message!.StartsWith("step section (") && x.Source == sourceName, x => x.NestingText == null && x.Message == "trace ext" && x.Source == sourceName && x.Category == "cat1", x => x.NestingText == "- " && x.Message == "trace non-ext" && x.Source == null && x.Category == "cat2", x => x.NestingText == "< " && x.Message!.StartsWith("root section (") && x.Source == null); } [Test] public void CreateSubLogForCategory() { using var sut = CreateSut([new LogConsumerConfiguration(_consumerSpy)]); const string category1Name = "cat1"; const string category2Name = "cat2"; sut.ExecuteSection( "root section", () => { var subSut1 = sut.CreateSubLogForCategory(category1Name); var subSut2 = sut.ForCategory(category2Name); subSut1.ExecuteSection( new StepLogSection("CreateSubLogForCategory"), () => subSut2.ExecuteSection( new LogSection("ForCategory", LogLevel.Trace), () => { subSut1.Trace("CreateSubLogForCategory trace message"); subSut2.Trace("ForCategory trace message"); sut.Trace("Root trace message"); })); }); _consumerSpy.CollectedEvents.Should.ConsistSequentiallyOf( x => x.NestingText == "> " && x.Message == "root section" && x.Category == null, x => x.NestingText == "- > " && x.Message == "CreateSubLogForCategory" && x.Category == category1Name, x => x.NestingText == "- > " && x.Message == "ForCategory" && x.Category == category2Name, x => x.NestingText == "- - " && x.Message == "CreateSubLogForCategory trace message" && x.Category == category1Name, x => x.NestingText == "- - " && x.Message == "ForCategory trace message" && x.Category == category2Name, x => x.NestingText == "- " && x.Message == "Root trace message" && x.Category == null, x => x.NestingText == "- < " && x.Message!.StartsWith("ForCategory (") && x.Category == category2Name, x => x.NestingText == "- < " && x.Message!.StartsWith("CreateSubLogForCategory (") && x.Category == category1Name, x => x.NestingText == "< " && x.Message!.StartsWith("root section (") && x.Category == null); } [TestCase(TestResultStatusCondition.Passed)] [TestCase(TestResultStatusCondition.PassedOrInconclusive)] [TestCase(TestResultStatusCondition.PassedOrInconclusiveOrWarning)] public void TryReleasePostponingConsumers_WithFailedStatus_WhenConsumerSkipConditionIs(TestResultStatusCondition condition) { // Arrange using var sut = CreateSut( [ new LogConsumerConfiguration(_consumerSpy, LogSectionEndOption.Exclude) { SkipCondition = condition } ]); LogStepSectionWithTraceSubSectionContainingTraceAndInfo(sut); _consumerSpy.CollectedEventNestedTextsWithMessages.Should.BeEmpty(); // Act sut.TryReleasePostponingConsumers(TestResultStatus.Failed); // Assert _consumerSpy.CollectedEventNestedTextsWithMessages.Should.EqualSequence( "step section", "- trace sub-section", "- - inner info message", "- - inner trace message"); } [TestCase(TestResultStatusCondition.Passed)] [TestCase(TestResultStatusCondition.PassedOrInconclusive)] public void TryReleasePostponingConsumers_WithWarningStatus_WhenConsumerSkipConditionIs(TestResultStatusCondition condition) { // Arrange using var sut = CreateSut( [ new LogConsumerConfiguration(_consumerSpy, LogSectionEndOption.Exclude) { SkipCondition = condition } ]); LogStepSectionWithTraceSubSectionContainingTraceAndInfo(sut); _consumerSpy.CollectedEventNestedTextsWithMessages.Should.BeEmpty(); // Act sut.TryReleasePostponingConsumers(TestResultStatus.Warning); // Assert _consumerSpy.CollectedEventNestedTextsWithMessages.Should.EqualSequence( "step section", "- trace sub-section", "- - inner info message", "- - inner trace message"); } [Test] public void TryReleasePostponingConsumers_WithWarningStatus_WhenConsumerSkipConditionIsPassedOrInconclusiveOrWarning() { // Arrange using var sut = CreateSut( [ new LogConsumerConfiguration(_consumerSpy, LogSectionEndOption.Exclude) { SkipCondition = TestResultStatusCondition.PassedOrInconclusiveOrWarning } ]); LogStepSectionWithTraceSubSectionContainingTraceAndInfo(sut); _consumerSpy.CollectedEventNestedTextsWithMessages.Should.BeEmpty(); // Act sut.TryReleasePostponingConsumers(TestResultStatus.Warning); // Assert _consumerSpy.CollectedEventNestedTextsWithMessages.Should.BeEmpty(); } private static LogManager CreateSut( LogConsumerConfiguration[] consumerConfigurations, SecretStringToMask[]? secretStringsToMask = null) => new( new( consumerConfigurations, secretStringsToMask ?? []), new BasicLogEventInfoFactory()); private static void LogStepSectionWithTraceSubSectionContainingTraceAndInfo(ILogManager sut) => sut.ExecuteSection( new StepLogSection("step section"), () => sut.ExecuteSection( new LogSection("trace sub-section", LogLevel.Trace), () => { sut.Info("inner info message"); sut.Trace("inner trace message"); }));
LogManagerTests
csharp
microsoft__PowerToys
src/common/UITestAutomation/Element/Window.cs
{ "start": 321, "end": 2688 }
public class ____ : Element { /// <summary> /// Maximizes the window. /// </summary> /// <param name="byClickButton">If true, clicks the Maximize button; otherwise, sets the window state.</param> /// <returns>The current Window instance.</returns> public Window Maximize(bool byClickButton = true) { if (byClickButton) { Find<Button>("Maximize").Click(); } else { // TODO: Implement maximizing the window using an alternative method } return this; } /// <summary> /// Restores the window. /// </summary> /// <param name="byClickButton">If true, clicks the Restore button; otherwise, sets the window state.</param> /// <returns>The current Window instance.</returns> public Window Restore(bool byClickButton = true) { if (byClickButton) { Find<Button>("Restore").Click(); } else { // TODO: Implement restoring the window using an alternative method } return this; } /// <summary> /// Minimizes the window. /// </summary> /// <param name="byClickButton">If true, clicks the Minimize button; otherwise, sets the window state.</param> /// <returns>The current Window instance.</returns> public Window Minimize(bool byClickButton = true) { if (byClickButton) { Find<Button>("Minimize").Click(); } else { // TODO: Implement minimizing the window using an alternative method } return this; } /// <summary> /// Closes the window. /// </summary> /// <param name="byClickButton">If true, clicks the Close button; otherwise, closes the window using an alternative method.</param> public void Close(bool byClickButton = true) { if (byClickButton) { Find<Button>("Close").Click(); } else { // TODO: Implement closing the window using an alternative method } } } }
Window
csharp
abpframework__abp
framework/src/Volo.Abp.Ddd.Application.Contracts/Volo/Abp/Application/Dtos/PagedResultDto.cs
{ "start": 280, "end": 1143 }
public class ____<T> : ListResultDto<T>, IPagedResult<T> { /// <inheritdoc /> public long TotalCount { get; set; } //TODO: Can be a long value..? /// <summary> /// Creates a new <see cref="PagedResultDto{T}"/> object. /// </summary> public PagedResultDto() { } /// <summary> /// Creates a new <see cref="PagedResultDto{T}"/> object. /// </summary> /// <param name="totalCount">Total count of Items</param> /// <param name="items">List of items in current page</param> public PagedResultDto(long totalCount, IReadOnlyList<T> items) : base(items) { TotalCount = totalCount; } } /// <summary> /// Implements <see cref="IPagedResult{T}"/>. /// </summary> /// <typeparam name="T">Type of the items in the <see cref="ListResultDto{T}.Items"/> list</typeparam> [Serializable]
PagedResultDto
csharp
dotnet__reactive
Ix.NET/Source/System.Interactive.Async/TaskExt.cs
{ "start": 4914, "end": 10409 }
class ____ supports a single active awaiter at any point in time.</remarks> public Awaiter GetAwaiter() => new Awaiter(this); /// <summary> /// Replaces the (completed) task at the specified <paramref name="index"/> and starts awaiting it. /// </summary> /// <param name="index">The index of the parameter to replace.</param> /// <param name="task">The new task to store and await at the specified index.</param> public void Replace(int index, in ValueTask<T> task) { Debug.Assert(_tasks[index].IsCompleted, "A task shouldn't be replaced before it has completed."); _tasks[index] = task; task.ConfigureAwait(false).GetAwaiter().OnCompleted(_onReady[index]); } /// <summary> /// Called when any task has completed (thus may run concurrently). /// </summary> /// <param name="index">The index of the completed task in <see cref="_tasks"/>.</param> private void OnReady(int index) { Action onCompleted = null; lock (_ready) { // // Store the index of the task that has completed. This will be picked up from GetResult. // _ready.Enqueue(index); // // If there's a current awaiter, we'll steal its continuation action and invoke it. By setting // the continuation action to null, we avoid waking up the same awaiter more than once. Any // task completions that occur while no awaiter is active will end up being enqueued in _ready. // if (_onCompleted != null) { onCompleted = _onCompleted; _onCompleted = null; } } onCompleted?.Invoke(); } /// <summary> /// Invoked by awaiters to check if any task has completed, in order to short-circuit the await operation. /// </summary> /// <returns><c>true</c> if any task has completed; otherwise, <c>false</c>.</returns> private bool IsCompleted() { // REVIEW: Evaluate options to reduce locking, so the single consuming awaiter has limited contention // with the multiple concurrent completing enumerator tasks, e.g. using ConcurrentQueue<T>. lock (_ready) { return _ready.Count > 0; } } /// <summary> /// Gets the index of the earliest task that has completed, used by the awaiter. After stealing an index from /// the ready queue (by means of awaiting the current instance), the user may chose to replace the task at the /// returned index by a new task, using the <see cref="Replace"/> method. /// </summary> /// <returns>Index of the earliest task that has completed.</returns> private int GetResult() { lock (_ready) { return _ready.Dequeue(); } } /// <summary> /// Register a continuation passed by an awaiter. /// </summary> /// <param name="action">The continuation action delegate to call when any task is ready.</param> private void OnCompleted(Action action) { bool shouldInvoke = false; lock (_ready) { // // Check if we have anything ready (which could happen in the short window between checking // for IsCompleted and calling OnCompleted). If so, we should invoke the action directly. Not // doing so would be a correctness issue where a task has completed, its index was enqueued, // but the continuation was never called (unless another task completes and calls the action // delegate, whose subsequent call to GetResult would pick up the lost index). // if (_ready.Count > 0) { shouldInvoke = true; } else { Debug.Assert(_onCompleted == null, "Only a single awaiter is allowed."); _onCompleted = action; } } // // NB: We assume this case is rare enough (IsCompleted and OnCompleted happen right after one // another, and an enqueue should have happened right in between to go from an empty to a // non-empty queue), so we don't run the risk of triggering a stack overflow due to // synchronous completion of the await operation (which may be in a loop that awaits the // current instance again). // if (shouldInvoke) { action(); } } /// <summary> /// Awaiter type used to await completion of any task. /// </summary>
only
csharp
kgrzybek__modular-monolith-with-ddd
src/Modules/Registrations/Application/UserRegistrations/RegisterNewUser/NewUserRegisteredEnqueueEmailConfirmationHandler.cs
{ "start": 331, "end": 1131 }
public class ____ : INotificationHandler<NewUserRegisteredNotification> { private readonly ICommandsScheduler _commandsScheduler; public NewUserRegisteredEnqueueEmailConfirmationHandler(ICommandsScheduler commandsScheduler) { _commandsScheduler = commandsScheduler; } public async Task Handle(NewUserRegisteredNotification notification, CancellationToken cancellationToken) { await _commandsScheduler.EnqueueAsync(new SendUserRegistrationConfirmationEmailCommand( Guid.NewGuid(), notification.DomainEvent.UserRegistrationId, notification.DomainEvent.Email, notification.DomainEvent.ConfirmLink)); } } }
NewUserRegisteredEnqueueEmailConfirmationHandler
csharp
microsoft__garnet
test/Garnet.test.cluster/ReplicationTests/ClusterReplicationDisklessSyncTests.cs
{ "start": 655, "end": 23078 }
public class ____ { ClusterTestContext context; readonly int keyCount = 256; protected bool useTLS = false; protected bool asyncReplay = false; int timeout = (int)TimeSpan.FromSeconds(15).TotalSeconds; int testTimeout = (int)TimeSpan.FromSeconds(120).TotalSeconds; public Dictionary<string, LogLevel> monitorTests = new(){ { "ClusterDisklessSyncFailover", LogLevel.Trace } }; [SetUp] public virtual void Setup() { context = new ClusterTestContext(); context.Setup(monitorTests, testTimeoutSeconds: testTimeout); } [TearDown] public virtual void TearDown() { context?.TearDown(); } void PopulatePrimary(int primaryIndex, bool disableObjects, bool performRMW) { context.kvPairs = context.kvPairs ?? ([]); context.kvPairsObj = context.kvPairsObj ?? ([]); var addCount = 5; var keyLength = 16; var kvpairCount = keyCount; // New insert if (!performRMW) context.PopulatePrimary(ref context.kvPairs, keyLength, kvpairCount, primaryIndex: primaryIndex); else context.PopulatePrimaryRMW(ref context.kvPairs, keyLength, kvpairCount, primaryIndex: 0, addCount); if (!disableObjects) context.PopulatePrimaryWithObjects(ref context.kvPairsObj, keyLength, kvpairCount, primaryIndex: primaryIndex); } void Validate(int primaryIndex, int replicaIndex, bool disableObjects) { // Validate replica data context.ValidateKVCollectionAgainstReplica(ref context.kvPairs, replicaIndex: replicaIndex, primaryIndex: primaryIndex); if (disableObjects) context.ValidateNodeObjects(ref context.kvPairsObj, replicaIndex); } void ResetAndReAttach(int replicaIndex, int primaryIndex, bool soft) { // Soft reset replica _ = context.clusterTestUtils.ClusterReset(replicaIndex, soft: soft, expiry: 1, logger: context.logger); context.clusterTestUtils.BumpEpoch(replicaIndex, logger: context.logger); // Re-introduce node after reset while (!context.clusterTestUtils.IsKnown(replicaIndex, primaryIndex, logger: context.logger)) { ClusterTestUtils.BackOff(cancellationToken: context.cts.Token); context.clusterTestUtils.Meet(replicaIndex, primaryIndex, logger: context.logger); } } void Failover(int replicaIndex, string option = null) { _ = context.clusterTestUtils.ClusterFailover(replicaIndex, option, logger: context.logger); var role = context.clusterTestUtils.RoleCommand(replicaIndex, logger: context.logger); while (!role.Value.Equals("master")) { ClusterTestUtils.BackOff(cancellationToken: context.cts.Token); role = context.clusterTestUtils.RoleCommand(replicaIndex, logger: context.logger); } } /// <summary> /// Attach empty replica after primary has been populated with some data /// </summary> /// <param name="disableObjects"></param> /// <param name="performRMW"></param> [Test, Order(1)] [Category("REPLICATION")] public void ClusterEmptyReplicaDisklessSync([Values] bool disableObjects, [Values] bool performRMW, [Values] bool prePopulate) { var nodes_count = 2; var primaryIndex = 0; var replicaIndex = 1; context.CreateInstances(nodes_count, disableObjects: disableObjects, enableAOF: true, useTLS: useTLS, enableDisklessSync: true, timeout: timeout); context.CreateConnection(useTLS: useTLS); // Setup primary and introduce it to future replica _ = context.clusterTestUtils.AddDelSlotsRange(primaryIndex, [(0, 16383)], addslot: true, logger: context.logger); context.clusterTestUtils.SetConfigEpoch(primaryIndex, primaryIndex + 1, logger: context.logger); context.clusterTestUtils.SetConfigEpoch(replicaIndex, replicaIndex + 1, logger: context.logger); context.clusterTestUtils.Meet(primaryIndex, replicaIndex, logger: context.logger); // Ensure node is known context.clusterTestUtils.WaitUntilNodeIsKnown(primaryIndex, replicaIndex, logger: context.logger); // Populate Primary if (prePopulate) PopulatePrimary(primaryIndex, disableObjects, performRMW); // Attach sync session _ = context.clusterTestUtils.ClusterReplicate(replicaNodeIndex: replicaIndex, primaryNodeIndex: primaryIndex, logger: context.logger); // Populate Primary if (!prePopulate) PopulatePrimary(primaryIndex, disableObjects, performRMW); // Wait for replica to catch up context.clusterTestUtils.WaitForReplicaAofSync(primaryIndex, replicaIndex, logger: context.logger); // Validate replica data Validate(primaryIndex, replicaIndex, disableObjects); } /// <summary> /// Re-attach replica on disconnect after it has received some amount of data. /// The replica should replay only the portion it missed without doing a full sync, /// unless force full sync by setting the full sync AOF threshold to a very low value (1k). /// </summary> /// <param name="disableObjects"></param> /// <param name="performRMW"></param> [Test, Order(2)] [Category("REPLICATION")] public void ClusterAofReplayDisklessSync([Values] bool disableObjects, [Values] bool performRMW, [Values] bool forceFullSync) { var nodes_count = 2; var primaryIndex = 0; var replicaIndex = 1; context.CreateInstances(nodes_count, disableObjects: disableObjects, enableAOF: true, useTLS: useTLS, enableDisklessSync: true, timeout: timeout, replicaDisklessSyncFullSyncAofThreshold: forceFullSync ? "1k" : string.Empty); context.CreateConnection(useTLS: useTLS); // Setup primary and introduce it to future replica _ = context.clusterTestUtils.AddDelSlotsRange(primaryIndex, [(0, 16383)], addslot: true, logger: context.logger); context.clusterTestUtils.SetConfigEpoch(primaryIndex, primaryIndex + 1, logger: context.logger); context.clusterTestUtils.SetConfigEpoch(replicaIndex, replicaIndex + 1, logger: context.logger); context.clusterTestUtils.Meet(primaryIndex, replicaIndex, logger: context.logger); // Ensure node is known context.clusterTestUtils.WaitUntilNodeIsKnown(primaryIndex, replicaIndex, logger: context.logger); // Attach sync session _ = context.clusterTestUtils.ClusterReplicate(replicaNodeIndex: replicaIndex, primaryNodeIndex: primaryIndex, logger: context.logger); // Wait for replica to catch up context.clusterTestUtils.WaitForReplicaAofSync(primaryIndex, replicaIndex, logger: context.logger); // Populate Primary PopulatePrimary(primaryIndex, disableObjects, performRMW); // Validate replica data Validate(primaryIndex, replicaIndex, disableObjects); // Reset and re-attach replica as primary ResetAndReAttach(replicaIndex, primaryIndex, soft: true); // Populate Primary (ahead of replica) PopulatePrimary(primaryIndex, disableObjects, performRMW); // Re-attach sync session _ = context.clusterTestUtils.ClusterReplicate(replicaNodeIndex: replicaIndex, primaryNodeIndex: primaryIndex, logger: context.logger); // Validate replica data Validate(primaryIndex, replicaIndex, disableObjects); // Wait for replica to catch up context.clusterTestUtils.WaitForReplicaAofSync(primaryIndex, replicaIndex, logger: context.logger); } /// <summary> /// Attach one replica and populate it with data through primary. /// Disconnect replica and attach a new empty replica. /// Populate new replica with more data /// Re-attach disconnected replica. /// This should perform a full sync when the old replica is attach because primary will be in version v /// (because of syncing with new empty replica) and old replica will be in version v - 1. /// </summary> /// <param name="disableObjects"></param> /// <param name="performRMW"></param> [Test, Order(3)] [Category("REPLICATION")] public void ClusterDBVersionAlignmentDisklessSync([Values] bool disableObjects, [Values] bool performRMW) { var nodes_count = 3; var primaryIndex = 0; var replicaOneIndex = 1; var replicaTwoIndex = 2; context.CreateInstances(nodes_count, disableObjects: disableObjects, enableAOF: true, useTLS: useTLS, enableDisklessSync: true, timeout: timeout); context.CreateConnection(useTLS: useTLS); // Setup primary and introduce it to future replica _ = context.clusterTestUtils.AddDelSlotsRange(primaryIndex, [(0, 16383)], addslot: true, logger: context.logger); context.clusterTestUtils.SetConfigEpoch(primaryIndex, primaryIndex + 1, logger: context.logger); context.clusterTestUtils.SetConfigEpoch(replicaOneIndex, replicaOneIndex + 1, logger: context.logger); context.clusterTestUtils.SetConfigEpoch(replicaTwoIndex, replicaTwoIndex + 1, logger: context.logger); context.clusterTestUtils.Meet(primaryIndex, replicaOneIndex, logger: context.logger); context.clusterTestUtils.Meet(primaryIndex, replicaTwoIndex, logger: context.logger); // Ensure node everybody knowns everybody context.clusterTestUtils.WaitUntilNodeIsKnown(replicaOneIndex, primaryIndex, logger: context.logger); context.clusterTestUtils.WaitUntilNodeIsKnown(replicaTwoIndex, primaryIndex, logger: context.logger); context.clusterTestUtils.WaitUntilNodeIsKnown(replicaTwoIndex, replicaOneIndex, logger: context.logger); // Populate Primary PopulatePrimary(primaryIndex, disableObjects, performRMW); // Attach first replica _ = context.clusterTestUtils.ClusterReplicate(replicaNodeIndex: replicaOneIndex, primaryNodeIndex: primaryIndex, logger: context.logger); // Wait for replica to catch up context.clusterTestUtils.WaitForReplicaAofSync(primaryIndex, replicaOneIndex, logger: context.logger); // Validate first replica data Validate(primaryIndex, replicaOneIndex, disableObjects); // Validate db version var primaryVersion = context.clusterTestUtils.GetStoreCurrentVersion(primaryIndex, isMainStore: true, logger: context.logger); var replicaOneVersion = context.clusterTestUtils.GetStoreCurrentVersion(replicaOneIndex, isMainStore: true, logger: context.logger); // With unified store, versions increase per scan (main and object) // so expected versions depend on whether objects are disabled or not var expectedVersion1 = disableObjects ? 2 : 3; ClassicAssert.AreEqual(expectedVersion1, primaryVersion); ClassicAssert.AreEqual(primaryVersion, replicaOneVersion); // Reset and re-attach replica as primary ResetAndReAttach(replicaOneIndex, primaryIndex, soft: true); // Attach second replica _ = context.clusterTestUtils.ClusterReplicate(replicaNodeIndex: replicaTwoIndex, primaryNodeIndex: primaryIndex, logger: context.logger); // Populate primary with more data PopulatePrimary(primaryIndex, disableObjects, performRMW); // Wait for replica to catch up context.clusterTestUtils.WaitForReplicaAofSync(primaryIndex, replicaTwoIndex, logger: context.logger); // Validate second replica data Validate(primaryIndex, replicaTwoIndex, disableObjects); // Validate db version primaryVersion = context.clusterTestUtils.GetStoreCurrentVersion(primaryIndex, isMainStore: true, logger: context.logger); replicaOneVersion = context.clusterTestUtils.GetStoreCurrentVersion(replicaOneIndex, isMainStore: true, logger: context.logger); var replicaTwoVersion = context.clusterTestUtils.GetStoreCurrentVersion(replicaTwoIndex, isMainStore: true, logger: context.logger); // With unified store, versions increase per scan (main and object) // so expected versions depend on whether objects are disabled or not var expectedVersion2 = disableObjects ? 3 : 5; ClassicAssert.AreEqual(expectedVersion2, primaryVersion); ClassicAssert.AreEqual(primaryVersion, replicaTwoVersion); ClassicAssert.AreEqual(expectedVersion1, replicaOneVersion); // Re-attach first replica _ = context.clusterTestUtils.ClusterReplicate(replicaNodeIndex: replicaOneIndex, primaryNodeIndex: primaryIndex, logger: context.logger); // Validate second replica data Validate(primaryIndex, replicaOneIndex, disableObjects); primaryVersion = context.clusterTestUtils.GetStoreCurrentVersion(primaryIndex, isMainStore: true, logger: context.logger); replicaOneVersion = context.clusterTestUtils.GetStoreCurrentVersion(replicaOneIndex, isMainStore: true, logger: context.logger); replicaTwoVersion = context.clusterTestUtils.GetStoreCurrentVersion(replicaTwoIndex, isMainStore: true, logger: context.logger); // With unified store, versions increase per scan (main and object) // so expected versions depend on whether objects are disabled or not var expectedVersion3 = disableObjects ? 4 : 7; ClassicAssert.AreEqual(expectedVersion3, primaryVersion); ClassicAssert.AreEqual(primaryVersion, replicaOneVersion); ClassicAssert.AreEqual(primaryVersion, replicaTwoVersion); } [Test, Order(4)] [Category("REPLICATION")] public void ClusterDisklessSyncParallelAttach([Values] bool disableObjects, [Values] bool performRMW) { var nodes_count = 4; var primaryIndex = 0; var replicaOneIndex = 1; var replicaTwoIndex = 2; var replicaThreeIndex = 3; context.CreateInstances(nodes_count, disableObjects: disableObjects, enableAOF: true, useTLS: useTLS, enableDisklessSync: true, timeout: timeout); context.CreateConnection(useTLS: useTLS); // Setup primary and introduce it to future replica _ = context.clusterTestUtils.AddDelSlotsRange(primaryIndex, [(0, 16383)], addslot: true, logger: context.logger); context.clusterTestUtils.SetConfigEpoch(primaryIndex, primaryIndex + 1, logger: context.logger); context.clusterTestUtils.SetConfigEpoch(replicaOneIndex, replicaOneIndex + 1, logger: context.logger); context.clusterTestUtils.SetConfigEpoch(replicaTwoIndex, replicaTwoIndex + 1, logger: context.logger); context.clusterTestUtils.SetConfigEpoch(replicaThreeIndex, replicaThreeIndex + 1, logger: context.logger); context.clusterTestUtils.Meet(primaryIndex, replicaOneIndex, logger: context.logger); context.clusterTestUtils.Meet(primaryIndex, replicaTwoIndex, logger: context.logger); context.clusterTestUtils.Meet(primaryIndex, replicaThreeIndex, logger: context.logger); // Ensure node everybody knowns everybody context.clusterTestUtils.WaitUntilNodeIsKnown(replicaOneIndex, primaryIndex, logger: context.logger); context.clusterTestUtils.WaitUntilNodeIsKnown(replicaTwoIndex, primaryIndex, logger: context.logger); context.clusterTestUtils.WaitUntilNodeIsKnown(replicaThreeIndex, primaryIndex, logger: context.logger); // Populate Primary for (var i = 0; i < 5; i++) PopulatePrimary(primaryIndex, disableObjects, performRMW); // Attach all replicas for (var replica = 1; replica < nodes_count; replica++) _ = context.clusterTestUtils.ClusterReplicate(replicaNodeIndex: replica, primaryNodeIndex: primaryIndex, logger: context.logger); // Validate all replicas for (var replica = 1; replica < nodes_count; replica++) Validate(primaryIndex, replica, disableObjects); } [Test, Order(5)] [Category("REPLICATION")] public void ClusterDisklessSyncFailover([Values] bool disableObjects, [Values] bool performRMW) { var nodes_count = 3; var primary = 0; var replicaOne = 1; var replicaTwo = 2; var populateIter = 1; int[] nOffsets = [primary, replicaOne, replicaTwo]; context.CreateInstances(nodes_count, disableObjects: disableObjects, enableAOF: true, useTLS: useTLS, enableDisklessSync: true, timeout: timeout); context.CreateConnection(useTLS: useTLS); // Setup primary and introduce it to future replica _ = context.clusterTestUtils.AddDelSlotsRange(nOffsets[primary], [(0, 16383)], addslot: true, logger: context.logger); context.clusterTestUtils.SetConfigEpoch(nOffsets[primary], nOffsets[primary] + 1, logger: context.logger); context.clusterTestUtils.SetConfigEpoch(nOffsets[replicaOne], nOffsets[replicaOne] + 1, logger: context.logger); context.clusterTestUtils.SetConfigEpoch(nOffsets[replicaTwo], nOffsets[replicaTwo] + 1, logger: context.logger); context.clusterTestUtils.Meet(nOffsets[primary], nOffsets[replicaOne], logger: context.logger); context.clusterTestUtils.Meet(nOffsets[primary], nOffsets[replicaTwo], logger: context.logger); context.clusterTestUtils.WaitUntilNodeIsKnown(nOffsets[primary], nOffsets[replicaOne], logger: context.logger); context.clusterTestUtils.WaitUntilNodeIsKnown(nOffsets[replicaOne], nOffsets[replicaTwo], logger: context.logger); context.clusterTestUtils.WaitUntilNodeIsKnown(nOffsets[replicaTwo], nOffsets[primary], logger: context.logger); // Populate Primary for (var i = 0; i < populateIter; i++) PopulatePrimary(nOffsets[primary], disableObjects, performRMW); // Attach replicas for (var replica = 1; replica < nodes_count; replica++) _ = context.clusterTestUtils.ClusterReplicate(replicaNodeIndex: replica, primaryNodeIndex: nOffsets[primary], logger: context.logger); // Wait for replica to catch up for (var replica = 1; replica < nodes_count; replica++) context.clusterTestUtils.WaitForReplicaAofSync(nOffsets[primary], nOffsets[replica], logger: context.logger); // Validate all replicas for (var replica = 1; replica < nodes_count; replica++) Validate(nOffsets[primary], nOffsets[replica], disableObjects); // Perform failover and promote replica one Failover(nOffsets[replicaOne]); (nOffsets[replicaOne], nOffsets[primary]) = (nOffsets[primary], nOffsets[replicaOne]); // Wait for replica to catch up for (var replica = 1; replica < nodes_count; replica++) context.clusterTestUtils.WaitForReplicaAofSync(nOffsets[primary], nOffsets[replica], logger: context.logger); // Populate Primary for (var i = 0; i < populateIter; i++) PopulatePrimary(nOffsets[primary], disableObjects, performRMW); // Wait for replica to catch up for (var replica = 1; replica < nodes_count; replica++) context.clusterTestUtils.WaitForReplicaAofSync(nOffsets[primary], nOffsets[replica], logger: context.logger); // Validate all replicas for (var replica = 1; replica < nodes_count; replica++) Validate(nOffsets[primary], nOffsets[replica], disableObjects); } #if DEBUG [Test, Order(6)] [Category("REPLICATION")] public void ClusterDisklessSyncResetSyncManagerCts() { var nodes_count = 2; var primaryIndex = 0; var replicaOneIndex = 1; context.CreateInstances(nodes_count, enableAOF: true, useTLS: useTLS, enableDisklessSync: true, timeout: timeout); context.CreateConnection(useTLS: useTLS); _ = context.clusterTestUtils.AddDelSlotsRange(primaryIndex, [(0, 16383)], addslot: true, logger: context.logger); context.clusterTestUtils.SetConfigEpoch(primaryIndex, primaryIndex + 1, logger: context.logger); context.clusterTestUtils.SetConfigEpoch(replicaOneIndex, replicaOneIndex + 1, logger: context.logger); context.clusterTestUtils.Meet(primaryIndex, replicaOneIndex, logger: context.logger); context.clusterTestUtils.WaitUntilNodeIsKnown(replicaOneIndex, primaryIndex, logger: context.logger); try { ExceptionInjectionHelper.EnableException(ExceptionInjectionType.Replication_Diskless_Sync_Reset_Cts); var _resp = context.clusterTestUtils.ClusterReplicate(replicaNodeIndex: replicaOneIndex, primaryNodeIndex: primaryIndex, failEx: false, logger: context.logger); ClassicAssert.AreEqual("Wait for sync task faulted", _resp); } finally { ExceptionInjectionHelper.DisableException(ExceptionInjectionType.Replication_Diskless_Sync_Reset_Cts); } var resp = context.clusterTestUtils.ClusterReplicate(replicaNodeIndex: replicaOneIndex, primaryNodeIndex: primaryIndex, logger: context.logger); ClassicAssert.AreEqual("OK", resp); } #endif } }
ClusterReplicationDisklessSyncTests
csharp
dotnet__aspnetcore
src/Mvc/test/WebSites/RazorPagesWebSite/Pages/TryUpdateModelPageModel.cs
{ "start": 219, "end": 513 }
public class ____ : PageModel { public UserModel UserModel { get; set; } public bool Updated { get; set; } public async Task OnPost() { var user = new UserModel(); Updated = await TryUpdateModelAsync(user); UserModel = user; } }
TryUpdateModelPageModel
csharp
EduardoPires__EquinoxProject
src/Equinox.UI.Web/Configurations/MvcConfig.cs
{ "start": 80, "end": 885 }
public static class ____ { public static WebApplicationBuilder AddMvcConfiguration(this WebApplicationBuilder builder) { if (builder == null) throw new ArgumentNullException(nameof(builder)); builder.Configuration .SetBasePath(builder.Environment.ContentRootPath) .AddJsonFile("appsettings.json", true, true) .AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", true, true) .AddEnvironmentVariables(); builder.Services.AddControllersWithViews(options => { options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute()); }); builder.Services.AddRazorPages(); return builder; } } }
MvcConfig
csharp
moq__moq4
src/Moq.Tests/ExpressionSplitFixture.cs
{ "start": 12032, "end": 12122 }
public interface ____ { } public delegate IB ADelegate();
IC
csharp
dotnet__efcore
test/EFCore.Specification.Tests/ApiConsistencyTestBase.cs
{ "start": 54744, "end": 67790 }
public abstract class ____ { protected ApiConsistencyFixtureBase() => Initialize(); public virtual HashSet<Type> FluentApiTypes { get; } = []; public virtual Dictionary<Type, Type> GenericFluentApiTypes { get; } = new() { { typeof(CollectionCollectionBuilder), typeof(CollectionCollectionBuilder<,>) }, { typeof(CollectionNavigationBuilder), typeof(CollectionNavigationBuilder<,>) }, { typeof(DataBuilder), typeof(DataBuilder<>) }, { typeof(DiscriminatorBuilder), typeof(DiscriminatorBuilder<>) }, { typeof(EntityTypeBuilder), typeof(EntityTypeBuilder<>) }, { typeof(ComplexPropertyBuilder), typeof(ComplexPropertyBuilder<>) }, { typeof(ComplexCollectionBuilder), typeof(ComplexCollectionBuilder<>) }, { typeof(IndexBuilder), typeof(IndexBuilder<>) }, { typeof(KeyBuilder), typeof(KeyBuilder<>) }, { typeof(NavigationBuilder), typeof(NavigationBuilder<,>) }, { typeof(OwnedNavigationBuilder), typeof(OwnedNavigationBuilder<,>) }, { typeof(OwnedEntityTypeBuilder), typeof(OwnedEntityTypeBuilder<>) }, { typeof(OwnershipBuilder), typeof(OwnershipBuilder<,>) }, { typeof(PropertyBuilder), typeof(PropertyBuilder<>) }, { typeof(PrimitiveCollectionBuilder), typeof(PrimitiveCollectionBuilder<>) }, { typeof(ComplexTypePropertyBuilder), typeof(ComplexTypePropertyBuilder<>) }, { typeof(ComplexTypePrimitiveCollectionBuilder), typeof(ComplexTypePrimitiveCollectionBuilder<>) }, { typeof(ReferenceCollectionBuilder), typeof(ReferenceCollectionBuilder<,>) }, { typeof(ReferenceNavigationBuilder), typeof(ReferenceNavigationBuilder<,>) }, { typeof(ReferenceReferenceBuilder), typeof(ReferenceReferenceBuilder<,>) }, { typeof(DbContextOptionsBuilder), typeof(DbContextOptionsBuilder<>) } }; public virtual Dictionary<Type, Type> MirrorTypes { get; } = new(); public virtual HashSet<MethodInfo> VirtualMethodExceptions { get; } = []; public virtual HashSet<MethodInfo> NotAnnotatedMethods { get; } = []; public virtual HashSet<MethodInfo> AsyncMethodExceptions { get; } = []; public virtual HashSet<MethodInfo> UnmatchedMetadataMethods { get; } = []; public virtual Dictionary<Type, HashSet<MethodInfo>> UnmatchedMirrorMethods { get; } = new(); public virtual Dictionary<MethodInfo, string> MetadataMethodNameTransformers { get; } = new(); public virtual HashSet<MethodInfo> MetadataMethodExceptions { get; } = []; public virtual HashSet<PropertyInfo> ComputedDependencyProperties { get; } = [ typeof(ProviderConventionSetBuilderDependencies).GetProperty( nameof(ProviderConventionSetBuilderDependencies.ContextType)), typeof(QueryCompilationContextDependencies).GetProperty(nameof(QueryCompilationContextDependencies.ContextType)), typeof(QueryCompilationContextDependencies).GetProperty( nameof(QueryCompilationContextDependencies.QueryTrackingBehavior)), typeof(QueryContextDependencies).GetProperty(nameof(QueryContextDependencies.StateManager)) ]; public Dictionary<Type, (Type Mutable, Type Convention, Type ConventionBuilder, Type Runtime)> MetadataTypes { get; } = new() { { typeof(IReadOnlyModel), (typeof(IMutableModel), typeof(IConventionModel), typeof(IConventionModelBuilder), typeof(IModel)) }, { typeof(IReadOnlyAnnotatable), (typeof(IMutableAnnotatable), typeof(IConventionAnnotatable), typeof(IConventionAnnotatableBuilder), typeof(IAnnotatable)) }, { typeof(IAnnotation), (typeof(IAnnotation), typeof(IConventionAnnotation), null, null) }, { typeof(IReadOnlyEntityType), (typeof(IMutableEntityType), typeof(IConventionEntityType), typeof(IConventionEntityTypeBuilder), typeof(IEntityType)) }, { typeof(IReadOnlyComplexType), (typeof(IMutableComplexType), typeof(IConventionComplexType), typeof(IConventionComplexTypeBuilder), typeof(IComplexType)) }, { typeof(IReadOnlyComplexProperty), (typeof(IMutableComplexProperty), typeof(IConventionComplexProperty), typeof(IConventionComplexPropertyBuilder), typeof(IComplexProperty)) }, { typeof(IReadOnlyTypeBase), (typeof(IMutableTypeBase), typeof(IConventionTypeBase), typeof(IConventionTypeBaseBuilder), typeof(ITypeBase)) }, { typeof(IReadOnlyKey), (typeof(IMutableKey), typeof(IConventionKey), typeof(IConventionKeyBuilder), typeof(IKey)) }, { typeof(IReadOnlyForeignKey), (typeof(IMutableForeignKey), typeof(IConventionForeignKey), typeof(IConventionForeignKeyBuilder), typeof(IForeignKey)) }, { typeof(IReadOnlyIndex), (typeof(IMutableIndex), typeof(IConventionIndex), typeof(IConventionIndexBuilder), typeof(IIndex)) }, { typeof(IReadOnlyTrigger), (typeof(IMutableTrigger), typeof(IConventionTrigger), typeof(IConventionTriggerBuilder), typeof(ITrigger)) }, { typeof(IReadOnlyProperty), (typeof(IMutableProperty), typeof(IConventionProperty), typeof(IConventionPropertyBuilder), typeof(IProperty)) }, { typeof(IReadOnlyNavigation), (typeof(IMutableNavigation), typeof(IConventionNavigation), typeof(IConventionNavigationBuilder), typeof(INavigation)) }, { typeof(IReadOnlySkipNavigation), (typeof(IMutableSkipNavigation), typeof(IConventionSkipNavigation), typeof(IConventionSkipNavigationBuilder), typeof(ISkipNavigation)) }, { typeof(IReadOnlyServiceProperty), (typeof(IMutableServiceProperty), typeof(IConventionServiceProperty), typeof(IConventionServicePropertyBuilder), typeof(IServiceProperty)) }, { typeof(IReadOnlyNavigationBase), (typeof(IMutableNavigationBase), typeof(IConventionNavigationBase), null, typeof(INavigationBase)) }, { typeof(IReadOnlyPropertyBase), (typeof(IMutablePropertyBase), typeof(IConventionPropertyBase), typeof(IConventionPropertyBaseBuilder<>), typeof(IPropertyBase)) }, { typeof(IReadOnlyElementType), (typeof(IMutableElementType), typeof(IConventionElementType), typeof(IConventionElementTypeBuilder), typeof(IElementType)) } }; public Dictionary<Type, Type> MutableMetadataTypes { get; } = new(); public Dictionary<Type, Type> ConventionMetadataTypes { get; } = new(); public virtual HashSet<MethodInfo> NonCancellableAsyncMethods { get; } = []; public virtual Dictionary<Type, (Type ReadonlyExtensions, Type MutableExtensions, Type ConventionExtensions, Type ConventionBuilderExtensions, Type RuntimeExtensions)> MetadataExtensionTypes { get; } = new(); public List<(IReadOnlyList<MethodInfo> ReadOnly, IReadOnlyList<MethodInfo> Mutable, IReadOnlyList<MethodInfo> Convention, IReadOnlyList<MethodInfo> ConventionBuilder, IReadOnlyList<MethodInfo> Runtime)> MetadataMethods { get; } = []; protected static MethodInfo GetMethod( Type type, string name, int genericParameterCount, Func<Type[], Type[], Type[]> parameterGenerator) => type.GetGenericMethod( name, genericParameterCount, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly, parameterGenerator); protected virtual void Initialize() { foreach (var typeTuple in MetadataTypes.Values) { MutableMetadataTypes[typeTuple.Mutable] = typeTuple.Convention; ConventionMetadataTypes[typeTuple.Convention] = typeTuple.ConventionBuilder; } foreach (var extensionTypePair in MetadataExtensionTypes) { var type = extensionTypePair.Key; var extensionTypeTuple = extensionTypePair.Value; var (mutableType, conventionType, conventionBuilderType, runtimeType) = MetadataTypes[type]; var readOnlyMethods = extensionTypeTuple.ReadonlyExtensions?.GetMethods(BindingFlags.Public | BindingFlags.Static) .Where(m => !IsObsolete(m) && m.GetParameters().First().ParameterType == type).ToArray() ?? []; var mutableMethods = extensionTypeTuple.MutableExtensions?.GetMethods(BindingFlags.Public | BindingFlags.Static) .Where(m => !IsObsolete(m) && m.GetParameters().First().ParameterType == mutableType).ToArray() ?? []; var conventionMethods = extensionTypeTuple.ConventionExtensions?.GetMethods(BindingFlags.Public | BindingFlags.Static) .Where(m => !IsObsolete(m) && m.GetParameters().First().ParameterType == conventionType).ToArray() ?? []; var conventionBuilderMethods = extensionTypeTuple.ConventionBuilderExtensions ?.GetMethods(BindingFlags.Public | BindingFlags.Static) .Where(m => !IsObsolete(m) && m.GetParameters().First().ParameterType == conventionBuilderType).ToArray() ?? []; var runtimeMethods = extensionTypeTuple.RuntimeExtensions?.GetMethods(BindingFlags.Public | BindingFlags.Static) .Where(m => !IsObsolete(m) && m.GetParameters().First().ParameterType == runtimeType).ToArray() ?? []; MetadataMethods.Add((readOnlyMethods, mutableMethods, conventionMethods, conventionBuilderMethods, runtimeMethods)); } } protected void AddInstanceMethods(Dictionary<Type, (Type Mutable, Type Convention, Type ConventionBuilder, Type Runtime)> types) { foreach (var typeTuple in types) { var readOnlyMethods = GetMethods(typeTuple.Key).ToArray(); var mutableMethods = GetMethods(typeTuple.Value.Mutable).ToArray(); var conventionMethods = GetMethods(typeTuple.Value.Convention).ToArray(); var conventionBuilderMethods = GetMethods(typeTuple.Value.ConventionBuilder).ToArray(); var runtimeMethods = GetMethods(typeTuple.Value.Runtime).ToArray(); MetadataMethods.Add((readOnlyMethods, mutableMethods, conventionMethods, conventionBuilderMethods, runtimeMethods)); } static IEnumerable<MethodInfo> GetMethods(Type type) => type == null ? [] : (IEnumerable<MethodInfo>)type.GetMethods(PublicInstance); } public bool IsObsolete(MethodInfo method) => Attribute.IsDefined(method, typeof(ObsoleteAttribute), inherit: false); } }
ApiConsistencyFixtureBase
csharp
abpframework__abp
framework/src/Volo.Abp.Http/Volo/Abp/Http/Modeling/ActionApiDescriptionModel.cs
{ "start": 195, "end": 2427 }
public class ____ { public string UniqueName { get; set; } = default!; public string Name { get; set; } = default!; public string? HttpMethod { get; set; } public string Url { get; set; } = default!; public IList<string>? SupportedVersions { get; set; } public IList<MethodParameterApiDescriptionModel> ParametersOnMethod { get; set; } = default!; public IList<ParameterApiDescriptionModel> Parameters { get; set; } = default!; public ReturnValueApiDescriptionModel ReturnValue { get; set; } = default!; public bool? AllowAnonymous { get; set; } public string? ImplementFrom { get; set; } public ActionApiDescriptionModel() { } public static ActionApiDescriptionModel Create([NotNull] string uniqueName, [NotNull] MethodInfo method, [NotNull] string url, string? httpMethod, [NotNull] IList<string> supportedVersions, bool? allowAnonymous = null, string? implementFrom = null) { Check.NotNull(uniqueName, nameof(uniqueName)); Check.NotNull(method, nameof(method)); Check.NotNull(url, nameof(url)); Check.NotNull(supportedVersions, nameof(supportedVersions)); return new ActionApiDescriptionModel { UniqueName = uniqueName, Name = method.Name, Url = url, HttpMethod = httpMethod, ReturnValue = ReturnValueApiDescriptionModel.Create(method.ReturnType), Parameters = new List<ParameterApiDescriptionModel>(), ParametersOnMethod = method .GetParameters() .Select(MethodParameterApiDescriptionModel.Create) .ToList(), SupportedVersions = supportedVersions, AllowAnonymous = allowAnonymous, ImplementFrom = implementFrom }; } public ParameterApiDescriptionModel AddParameter(ParameterApiDescriptionModel parameter) { Parameters.Add(parameter); return parameter; } public HttpMethod GetHttpMethod() { return HttpMethodHelper.ConvertToHttpMethod(HttpMethod); } public override string ToString() { return $"[ActionApiDescriptionModel {Name}]"; } }
ActionApiDescriptionModel
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore.ReCaptcha.Core/ActionFilters/ValidateReCaptchaAttribute.cs
{ "start": 324, "end": 1125 }
public class ____ : ActionFilterAttribute { public override async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) { var reCaptchaService = context.HttpContext.RequestServices.GetRequiredService<ReCaptchaService>(); var reCaptchaResponse = context.HttpContext.Request?.Form?[Constants.ReCaptchaServerResponseHeaderName].ToString(); if (string.IsNullOrWhiteSpace(reCaptchaResponse) || !await reCaptchaService.VerifyCaptchaResponseAsync(reCaptchaResponse)) { var S = context.HttpContext.RequestServices.GetService<IStringLocalizer<ReCaptchaService>>(); context.ModelState.AddModelError("ReCaptcha", S["Failed to validate captcha"]); } await next(); } }
ValidateReCaptchaAttribute
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.Autoroute/Handlers/DefaultRouteContentHandler.cs
{ "start": 171, "end": 1176 }
public class ____ : ContentHandlerBase { private readonly ISlugService _slugService; public DefaultRouteContentHandler(ISlugService slugService) { _slugService = slugService; } public override Task GetContentItemAspectAsync(ContentItemAspectContext context) { return context.ForAsync<RouteHandlerAspect>(aspect => { // Only use default aspect if no other handler has set the aspect. if (string.IsNullOrEmpty(aspect.Path)) { // By default contained route is content item id + display text, if present. var path = context.ContentItem.ContentItemId; if (!string.IsNullOrEmpty(context.ContentItem.DisplayText)) { path = path + "-" + context.ContentItem.DisplayText; } aspect.Path = _slugService.Slugify(path); } return Task.CompletedTask; }); } }
DefaultRouteContentHandler
csharp
abpframework__abp
modules/openiddict/src/Volo.Abp.OpenIddict.MongoDB/Volo/Abp/OpenIddict/MongoDB/IOpenIddictMongoDbContext.cs
{ "start": 380, "end": 695 }
public interface ____ : IAbpMongoDbContext { IMongoCollection<OpenIddictApplication> Applications { get; } IMongoCollection<OpenIddictAuthorization> Authorizations { get; } IMongoCollection<OpenIddictScope> Scopes { get; } IMongoCollection<OpenIddictToken> Tokens { get; } }
IOpenIddictMongoDbContext
csharp
MassTransit__MassTransit
src/MassTransit.Newtonsoft/Serialization/NewtonsoftEnvelopeSerializerContext.cs
{ "start": 245, "end": 2852 }
public abstract class ____ : BaseSerializerContext { readonly JsonSerializer _deserializer; readonly object? _message; protected NewtonsoftSerializerContext(JsonSerializer deserializer, IObjectDeserializer objectDeserializer, MessageContext messageContext, object? message, string[] supportedMessageTypes) : base(objectDeserializer, messageContext, supportedMessageTypes) { _deserializer = deserializer; _message = message; } public override bool TryGetMessage<T>(out T? message) where T : class { var messageToken = GetMessageToken(_message); if (typeof(T) == typeof(JToken)) { message = messageToken as T; return message != null; } if (IsSupportedMessageType<T>()) { if (_message is T messageOfT) { message = messageOfT; return true; } using var json = messageToken.CreateReader(); message = _deserializer.Deserialize<T>(json); return message != null; } message = null; return false; } public override bool TryGetMessage(Type messageType, [NotNullWhen(true)] out object? message) { if (_message != null && messageType.IsInstanceOfType(_message)) { message = _message; return true; } var messageToken = GetMessageToken(_message); using var reader = messageToken.CreateReader(); message = _deserializer.Deserialize(reader, messageType); return message != null; } public override Dictionary<string, object> ToDictionary<T>(T? message) where T : class { if (message == null) return new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); var dictionary = JObject.FromObject(message, NewtonsoftJsonMessageSerializer.Serializer); return dictionary.ToObject<Dictionary<string, object>>(_deserializer) ?? new CaseInsensitiveDictionary<object>(); } static JToken GetMessageToken(object? message) { return message is JToken element ? element.Type == JTokenType.Null ? new JObject() : element : new JObject(); } } }
NewtonsoftSerializerContext
csharp
dotnet-architecture__eShopOnWeb
src/ApplicationCore/Entities/OrderAggregate/OrderItem.cs
{ "start": 72, "end": 550 }
public class ____ : BaseEntity { public CatalogItemOrdered ItemOrdered { get; private set; } public decimal UnitPrice { get; private set; } public int Units { get; private set; } #pragma warning disable CS8618 // Required by Entity Framework private OrderItem() {} public OrderItem(CatalogItemOrdered itemOrdered, decimal unitPrice, int units) { ItemOrdered = itemOrdered; UnitPrice = unitPrice; Units = units; } }
OrderItem
csharp
unoplatform__uno
src/Uno.UI/UI/Xaml/Media/Animation/DrillInNavigationTransitionInfo.cs
{ "start": 48, "end": 192 }
public partial class ____ : NavigationTransitionInfo { public DrillInNavigationTransitionInfo() : base() { } } }
DrillInNavigationTransitionInfo
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.Common/Script/Blocks/HtmlScriptBlocks.cs
{ "start": 1673, "end": 1762 }
public class ____ : ScriptHtmlBlock { public override string Tag => "ul"; }
ScriptUlBlock
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack/Auth/IdentityAuth.cs
{ "start": 181, "end": 271 }
public interface ____ { Func<IAuthSession> SessionFactory { get; } }
IIdentityAuthContext
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.ContentLocalization/DefaultContentLocalizationManager.cs
{ "start": 424, "end": 8128 }
public class ____ : IContentLocalizationManager { private readonly IContentManager _contentManager; private readonly ISession _session; private readonly Microsoft.AspNetCore.Http.IHttpContextAccessor _httpContextAccessor; private readonly ILocalizationService _localizationService; private readonly ILogger _logger; private readonly Entities.IIdGenerator _iidGenerator; public IEnumerable<IContentLocalizationHandler> Handlers { get; private set; } public IEnumerable<IContentLocalizationHandler> ReversedHandlers { get; private set; } public DefaultContentLocalizationManager( IContentManager contentManager, ISession session, Microsoft.AspNetCore.Http.IHttpContextAccessor httpContentAccessor, ILocalizationService localizationService, ILogger<DefaultContentLocalizationManager> logger, IEnumerable<IContentLocalizationHandler> handlers, Entities.IIdGenerator iidGenerator) { _contentManager = contentManager; _session = session; _httpContextAccessor = httpContentAccessor; _localizationService = localizationService; Handlers = handlers; _iidGenerator = iidGenerator; ReversedHandlers = handlers.Reverse().ToArray(); _logger = logger; } public Task<ContentItem> GetContentItemAsync(string localizationSet, string culture) { var invariantCulture = culture.ToLowerInvariant(); return _session.Query<ContentItem, LocalizedContentItemIndex>(i => (i.Published || i.Latest) && i.LocalizationSet == localizationSet && i.Culture == invariantCulture) .FirstOrDefaultAsync(); } public Task<IEnumerable<ContentItem>> GetItemsForSetAsync(string localizationSet) { return _session.Query<ContentItem, LocalizedContentItemIndex>(i => (i.Published || i.Latest) && i.LocalizationSet == localizationSet).ListAsync(); } public Task<IEnumerable<ContentItem>> GetItemsForSetsAsync(IEnumerable<string> localizationSets, string culture) { var invariantCulture = culture.ToLowerInvariant(); return _session.Query<ContentItem, LocalizedContentItemIndex>(i => (i.Published || i.Latest) && i.LocalizationSet.IsIn(localizationSets) && i.Culture == invariantCulture).ListAsync(); } public async Task<ContentItem> LocalizeAsync(ContentItem content, string targetCulture) { var supportedCultures = await _localizationService.GetSupportedCulturesAsync(); if (!supportedCultures.Any(c => string.Equals(c, targetCulture, StringComparison.OrdinalIgnoreCase))) { throw new InvalidOperationException("Cannot localize an unsupported culture"); } var localizationPart = content.As<LocalizationPart>(); if (string.IsNullOrEmpty(localizationPart.LocalizationSet)) { // If the source content item is not yet localized, define its defaults. localizationPart.LocalizationSet = _iidGenerator.GenerateUniqueId(); localizationPart.Culture = await _localizationService.GetDefaultCultureAsync(); await _session.SaveAsync(content); } else { var existingContent = await GetContentItemAsync(localizationPart.LocalizationSet, targetCulture); if (existingContent != null) { // Already localized. return existingContent; } } // Cloning the content item. var cloned = await _contentManager.CloneAsync(content); var clonedPart = cloned.As<LocalizationPart>(); clonedPart.Culture = targetCulture; clonedPart.LocalizationSet = localizationPart.LocalizationSet; clonedPart.Apply(); var context = new LocalizationContentContext(cloned, content, localizationPart.LocalizationSet, targetCulture); await Handlers.InvokeAsync((handler, context) => handler.LocalizingAsync(context), context, _logger); await ReversedHandlers.InvokeAsync((handler, context) => handler.LocalizedAsync(context), context, _logger); return cloned; } public async Task<IDictionary<string, ContentItem>> DeduplicateContentItemsAsync(IEnumerable<ContentItem> contentItems) { var contentItemIds = contentItems.Select(c => c.ContentItemId); var indexValues = await _session.QueryIndex<LocalizedContentItemIndex>(i => (i.Published || i.Latest) && i.ContentItemId.IsIn(contentItemIds)).ListAsync(); var currentCulture = _httpContextAccessor.HttpContext.Features.Get<IRequestCultureFeature>().RequestCulture.Culture.Name.ToLowerInvariant(); var defaultCulture = (await _localizationService.GetDefaultCultureAsync()).ToLowerInvariant(); var cleanedIndexValues = GetSingleContentItemIdPerSet(indexValues, currentCulture, defaultCulture); var dictionary = new Dictionary<string, ContentItem>(); foreach (var val in cleanedIndexValues) { dictionary.Add(val.LocalizationSet, contentItems.SingleOrDefault(ci => ci.ContentItemId == val.ContentItemId)); } return dictionary; } public async Task<IDictionary<string, string>> GetFirstItemIdForSetsAsync(IEnumerable<string> localizationSets) { var indexValues = await _session.QueryIndex<LocalizedContentItemIndex>(i => (i.Published || i.Latest) && i.LocalizationSet.IsIn(localizationSets)).ListAsync(); var currentCulture = _httpContextAccessor.HttpContext.Features.Get<IRequestCultureFeature>().RequestCulture.Culture.Name.ToLowerInvariant(); var defaultCulture = (await _localizationService.GetDefaultCultureAsync()).ToLowerInvariant(); var dictionary = new Dictionary<string, string>(); var cleanedIndexValues = GetSingleContentItemIdPerSet(indexValues, currentCulture, defaultCulture); // This loop keeps the original ordering of localizationSets for the LocalizationSetContentPicker. foreach (var set in localizationSets) { var idxValue = cleanedIndexValues.FirstOrDefault(x => x.LocalizationSet == set); if (idxValue == null) { continue; } dictionary.Add(idxValue.LocalizationSet, idxValue.ContentItemId); } return dictionary; } /// <summary> /// ContentItemId chosen with the following rules: /// ContentItemId of the current culture for the set /// OR ContentItemId of the default culture for the set /// OR First ContentItemId found in the set /// OR null if nothing found. /// </summary> /// <returns>List of ContentItemId.</returns> private static List<LocalizedContentItemIndex> GetSingleContentItemIdPerSet(IEnumerable<LocalizedContentItemIndex> indexValues, string currentCulture, string defaultCulture) { return indexValues.GroupBy(l => l.LocalizationSet).Select(set => { var currentCultureContentItem = set.FirstOrDefault(f => f.Culture == currentCulture); if (currentCultureContentItem is not null) { return currentCultureContentItem; } var defaultCultureContentItem = set.FirstOrDefault(f => f.Culture == defaultCulture); if (defaultCultureContentItem is not null) { return defaultCultureContentItem; } if (set.Any()) { return set.FirstOrDefault(); } return null; }).OfType<LocalizedContentItemIndex>().ToList(); } }
DefaultContentLocalizationManager
csharp
VerifyTests__Verify
src/Verify.Tests/Serialization/SerializationTests.cs
{ "start": 84643, "end": 84796 }
class ____ : BaseToIgnoreGeneric<int> { public string Property; } // ReSharper disable once UnusedTypeParameter
ToIgnoreByBaseGeneric
csharp
getsentry__sentry-dotnet
samples/Sentry.Samples.OpenTelemetry.AzureFunctions/SampleTimerTrigger.cs
{ "start": 759, "end": 919 }
public class ____ { public DateTime Last { get; set; } public DateTime Next { get; set; } public DateTime LastUpdated { get; set; } }
MyScheduleStatus
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.Common.Tests/IntlTests.cs
{ "start": 1910, "end": 5165 }
public class ____ { private ServiceStackHost appHost; public IntlTests() => appHost = new BasicAppHost(typeof(IntlServices).Assembly) { Plugins = { new NativeTypesFeature() }, }.Init(); [OneTimeTearDown] public void OneTimeTearDown() => appHost.Dispose(); void AssertFormat(FormatInfo actual, string expectedMethod, string expectedOptions = null, string expectedLocale = null) { Assert.That(actual, Is.Not.Null); Assert.That(actual.Method, Is.EqualTo(expectedMethod)); Assert.That(actual.Options, Is.EqualTo(expectedOptions)); Assert.That(actual.Locale, Is.EqualTo(expectedLocale)); } FormatInfo Format(MetadataType dto, string name) => dto.Properties.First(x => x.Name == name).Format; [Test] public void Does_IntlDateExamples() { var gen = appHost.Resolve<INativeTypesMetadata>().GetGenerator(); var dto = gen.ToType(typeof(IntlDateExamples)); AssertFormat(Format(dto,nameof(IntlDateExamples.Example1)), "Intl.DateTimeFormat"); AssertFormat(Format(dto,nameof(IntlDateExamples.Example2)), "Intl.DateTimeFormat", "{dateStyle:'medium',timeStyle:'short'}", "en-AU"); AssertFormat(Format(dto,nameof(IntlDateExamples.Example3)), "Intl.DateTimeFormat", "{dateStyle:'short'}"); AssertFormat(Format(dto,nameof(IntlDateExamples.Example4)), "Intl.DateTimeFormat", "{year:'2-digit',month:'short',day:'numeric'}"); } [Test] public void Does_IntlNumberExamples() { var gen = appHost.Resolve<INativeTypesMetadata>().GetGenerator(); var dto = gen.ToType(typeof(IntlNumberExamples)); AssertFormat(Format(dto,nameof(IntlNumberExamples.Example1)), "Intl.NumberFormat"); AssertFormat(Format(dto,nameof(IntlNumberExamples.Example2)), "Intl.NumberFormat", "{style:'decimal',roundingMode:'halfCeil',signDisplay:'exceptZero'}", "en-AU"); AssertFormat(Format(dto,nameof(IntlNumberExamples.Example3)), "Intl.NumberFormat", "{style:'currency',currency:'USD'}"); AssertFormat(Format(dto,nameof(IntlNumberExamples.Example4)), "Intl.NumberFormat", "{style:'currency',currency:'USD',currencyDisplay:'narrowSymbol',currencySign:'accounting'}"); AssertFormat(Format(dto,nameof(IntlNumberExamples.Example5)), "Intl.NumberFormat", "{style:'unit',unit:'kilobyte'}"); } [Test] public void Does_IntlRelativeTimeExamples() { var gen = appHost.Resolve<INativeTypesMetadata>().GetGenerator(); var dto = gen.ToType(typeof(IntlRelativeTimeExamples)); AssertFormat(Format(dto,nameof(IntlRelativeTimeExamples.Example1)), "Intl.RelativeTimeFormat"); AssertFormat(Format(dto,nameof(IntlRelativeTimeExamples.Example2)), "Intl.RelativeTimeFormat", "{numeric:'always'}"); } [Test] public void Does_CustomFormatExamples_Examples() { var gen = appHost.Resolve<INativeTypesMetadata>().GetGenerator(); var dto = gen.ToType(typeof(CustomFormatExamples)); AssertFormat(Format(dto,nameof(CustomFormatExamples.Example1)), "currency", expectedLocale:"en-AU"); AssertFormat(Format(dto,nameof(CustomFormatExamples.Example2)), "Intl.NumberFormat", "{style:'currency',currency:'USD'}"); } }
IntlTests
csharp
nunit__nunit
src/NUnitFramework/tests/Constraints/CollectionSupersetConstraintTests.cs
{ "start": 5206, "end": 7551 }
public class ____ { public static IEnumerable TestCases { get { yield return new TestCaseData(new SimpleObjectCollection("z", "Y", "X"), new SimpleObjectCollection("w", "x", "y", "z")); yield return new TestCaseData(new object[] { 'a', 'b', 'c' }, new[] { 'A', 'B', 'C', 'D', 'E' }); yield return new TestCaseData(new object[] { "A", "C", "B" }, new[] { "a", "b", "c", "d", "e" }); yield return new TestCaseData(new Dictionary<int, string> { { 1, "A" } }, new Dictionary<int, string> { { 1, "a" }, { 2, "b" } }); yield return new TestCaseData(new Dictionary<int, char> { { 1, 'a' } }, new Dictionary<int, char> { { 1, 'A' }, { 2, 'B' } }); yield return new TestCaseData(new Dictionary<string, int> { { "b", 2 } }, new Dictionary<string, int> { { "b", 2 }, { "a", 1 } }); yield return new TestCaseData(new Dictionary<char, int> { { 'a', 1 } }, new Dictionary<char, int> { { 'A', 1 }, { 'B', 2 } }); yield return new TestCaseData(new Hashtable { { 1, "A" } }, new Hashtable { { 1, "a" }, { 2, "b" } }); yield return new TestCaseData(new Hashtable { { 2, 'b' } }, new Hashtable { { 1, 'A' }, { 2, 'B' } }); yield return new TestCaseData(new Hashtable { { "A", 1 } }, new Hashtable { { "b", 2 }, { "a", 1 } }); yield return new TestCaseData(new Hashtable { { 'a', 1 } }, new Hashtable { { 'A', 1 }, { 'B', 2 } }); } } } [Test] public void IsSuperSetHonorsUsingWhenCollectionsAreOfDifferentTypes() { ICollection set = new SimpleObjectCollection("2", "3"); ICollection superSet = new SimpleObjectCollection(1, 2, 3, 4, 5); Assert.That(superSet, Is.SupersetOf(set).Using<int, string>((i, s) => i.ToString() == s)); } [Test] public void WorksWithImmutableDictionary() { var numbers = Enumerable.Range(1, 3); var test1 = numbers.ToImmutableDictionary(t => t); var test2 = numbers.ToImmutableDictionary(t => t); Assert.That(test1, Is.SupersetOf(test2)); } } }
IgnoreCaseDataProvider
csharp
dotnet__BenchmarkDotNet
tests/BenchmarkDotNet.Analyzers.Tests/AnalyzerTests/General/BenchmarkClassAnalyzerTests.cs
{ "start": 71006, "end": 73589 }
public class ____ : BenchmarkClassAncestor1 { {{(useLocalConstants ? $""" private const bool _xTrue = {(useConstantsFromOtherClass ? "Constants.Value1" : "true")}; private const bool _xFalse = {(useConstantsFromOtherClass ? "Constants.Value2" : "false")}; """ : "")}} {{emptyBenchmarkCategoryAttributeUsages}} {{baselineBenchmarkAttributeUsage}} public void BaselineBenchmarkMethod1() { } {{emptyBenchmarkCategoryAttributeUsages}} {{(useDuplicateInSameClass ? baselineBenchmarkAttributeUsage : "")}} public void BaselineBenchmarkMethod2() { } [BenchmarkCategory("Category1")] {{nonBaselineBenchmarkAttributeUsage}} public void NonBaselineBenchmarkMethod1() { } [BenchmarkCategory("Category1")] public void DummyMethod() { } [Benchmark] public void NonBaselineBenchmarkMethod2() { } {{nonBaselineBenchmarkAttributeUsage}} public void NonBaselineBenchmarkMethod3() { } } """; var benchmarkClassAncestor1Document = /* lang=c#-test */ $$""" public {{abstractModifier}}
BenchmarkClass