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
dotnet__maui
src/Controls/src/Core/PlatformConfiguration/iOSSpecific/FlyoutPage.cs
{ "start": 354, "end": 1968 }
public static class ____ { #region ApplyShadow /// <summary>Bindable property for attached property <c>ApplyShadow</c>.</summary> public static readonly BindableProperty ApplyShadowProperty = BindableProperty.Create("ApplyShadow", typeof(bool), typeof(FlyoutPage), false); /// <include file="../../../../docs/Microsoft.Maui.Controls.PlatformConfiguration.iOSSpecific/FlyoutPage.xml" path="//Member[@MemberName='GetApplyShadow'][1]/Docs/*" /> public static bool GetApplyShadow(BindableObject element) { return (bool)element.GetValue(ApplyShadowProperty); } /// <include file="../../../../docs/Microsoft.Maui.Controls.PlatformConfiguration.iOSSpecific/FlyoutPage.xml" path="//Member[@MemberName='SetApplyShadow'][1]/Docs/*" /> public static void SetApplyShadow(BindableObject element, bool value) { element.SetValue(ApplyShadowProperty, value); } /// <include file="../../../../docs/Microsoft.Maui.Controls.PlatformConfiguration.iOSSpecific/FlyoutPage.xml" path="//Member[@MemberName='SetApplyShadow'][2]/Docs/*" /> public static IPlatformElementConfiguration<iOS, FormsElement> SetApplyShadow(this IPlatformElementConfiguration<iOS, FormsElement> config, bool value) { SetApplyShadow(config.Element, value); return config; } /// <include file="../../../../docs/Microsoft.Maui.Controls.PlatformConfiguration.iOSSpecific/FlyoutPage.xml" path="//Member[@MemberName='GetApplyShadow'][2]/Docs/*" /> public static bool GetApplyShadow(this IPlatformElementConfiguration<iOS, FormsElement> config) { return GetApplyShadow(config.Element); } #endregion } }
FlyoutPage
csharp
jellyfin__jellyfin
src/Jellyfin.LiveTv/Listings/XmlTvListingsProvider.cs
{ "start": 671, "end": 11665 }
public class ____ : IListingsProvider { private static readonly TimeSpan _maxCacheAge = TimeSpan.FromHours(1); private readonly IServerConfigurationManager _config; private readonly IHttpClientFactory _httpClientFactory; private readonly ILogger<XmlTvListingsProvider> _logger; public XmlTvListingsProvider( IServerConfigurationManager config, IHttpClientFactory httpClientFactory, ILogger<XmlTvListingsProvider> logger) { _config = config; _httpClientFactory = httpClientFactory; _logger = logger; } public string Name => "XmlTV"; public string Type => "xmltv"; private string GetLanguage(ListingsProviderInfo info) { if (!string.IsNullOrWhiteSpace(info.PreferredLanguage)) { return info.PreferredLanguage; } return _config.Configuration.PreferredMetadataLanguage; } private async Task<string> GetXml(ListingsProviderInfo info, CancellationToken cancellationToken) { _logger.LogInformation("xmltv path: {Path}", info.Path); string cacheFilename = info.Id + ".xml"; string cacheFile = Path.Combine(_config.ApplicationPaths.CachePath, "xmltv", cacheFilename); if (File.Exists(cacheFile) && File.GetLastWriteTimeUtc(cacheFile) >= DateTime.UtcNow.Subtract(_maxCacheAge)) { return cacheFile; } // Must check if file exists as parent directory may not exist. if (File.Exists(cacheFile)) { File.Delete(cacheFile); } else { Directory.CreateDirectory(Path.GetDirectoryName(cacheFile)); } if (info.Path.StartsWith("http", StringComparison.OrdinalIgnoreCase)) { _logger.LogInformation("Downloading xmltv listings from {Path}", info.Path); using var response = await _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(info.Path, cancellationToken).ConfigureAwait(false); var redirectedUrl = response.RequestMessage?.RequestUri?.ToString() ?? info.Path; var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); await using (stream.ConfigureAwait(false)) { return await UnzipIfNeededAndCopy(redirectedUrl, stream, cacheFile, cancellationToken).ConfigureAwait(false); } } else { var stream = AsyncFile.OpenRead(info.Path); await using (stream.ConfigureAwait(false)) { return await UnzipIfNeededAndCopy(info.Path, stream, cacheFile, cancellationToken).ConfigureAwait(false); } } } private async Task<string> UnzipIfNeededAndCopy(string originalUrl, Stream stream, string file, CancellationToken cancellationToken) { var fileStream = new FileStream( file, FileMode.CreateNew, FileAccess.Write, FileShare.None, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous); await using (fileStream.ConfigureAwait(false)) { if (Path.GetExtension(originalUrl.AsSpan().LeftPart('?')).Equals(".gz", StringComparison.OrdinalIgnoreCase) || Path.GetExtension(originalUrl.AsSpan().LeftPart('?')).Equals(".gzip", StringComparison.OrdinalIgnoreCase)) { try { using var reader = new GZipStream(stream, CompressionMode.Decompress); await reader.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false); } catch (Exception ex) { _logger.LogError(ex, "Error extracting from gz file {File}", originalUrl); } } else { await stream.CopyToAsync(fileStream, cancellationToken).ConfigureAwait(false); } return file; } } public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(ListingsProviderInfo info, string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(channelId)) { throw new ArgumentNullException(nameof(channelId)); } _logger.LogDebug("Getting xmltv programs for channel {Id}", channelId); string path = await GetXml(info, cancellationToken).ConfigureAwait(false); _logger.LogDebug("Opening XmlTvReader for {Path}", path); var reader = new XmlTvReader(path, GetLanguage(info)); return reader.GetProgrammes(channelId, startDateUtc, endDateUtc, cancellationToken) .Select(p => GetProgramInfo(p, info)); } private static ProgramInfo GetProgramInfo(XmlTvProgram program, ListingsProviderInfo info) { string episodeTitle = program.Episode.Title; var programCategories = program.Categories.Where(c => !string.IsNullOrWhiteSpace(c)).ToList(); var programInfo = new ProgramInfo { ChannelId = program.ChannelId, EndDate = program.EndDate.UtcDateTime, EpisodeNumber = program.Episode.Episode, EpisodeTitle = episodeTitle, Genres = programCategories, StartDate = program.StartDate.UtcDateTime, Name = program.Title, Overview = program.Description, ProductionYear = program.CopyrightDate?.Year, SeasonNumber = program.Episode.Series, IsSeries = program.Episode.Episode is not null, IsRepeat = program.IsPreviouslyShown && !program.IsNew, IsPremiere = program.Premiere is not null, IsKids = programCategories.Any(c => info.KidsCategories.Contains(c, StringComparison.OrdinalIgnoreCase)), IsMovie = programCategories.Any(c => info.MovieCategories.Contains(c, StringComparison.OrdinalIgnoreCase)), IsNews = programCategories.Any(c => info.NewsCategories.Contains(c, StringComparison.OrdinalIgnoreCase)), IsSports = programCategories.Any(c => info.SportsCategories.Contains(c, StringComparison.OrdinalIgnoreCase)), ImageUrl = string.IsNullOrEmpty(program.Icon?.Source) ? null : program.Icon.Source, HasImage = !string.IsNullOrEmpty(program.Icon?.Source), OfficialRating = string.IsNullOrEmpty(program.Rating?.Value) ? null : program.Rating.Value, CommunityRating = program.StarRating, SeriesId = program.Episode.Episode is null ? null : program.Title?.GetMD5().ToString("N", CultureInfo.InvariantCulture) }; if (string.IsNullOrWhiteSpace(program.ProgramId)) { string uniqueString = (program.Title ?? string.Empty) + (episodeTitle ?? string.Empty); if (programInfo.SeasonNumber.HasValue) { uniqueString = "-" + programInfo.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture); } if (programInfo.EpisodeNumber.HasValue) { uniqueString = "-" + programInfo.EpisodeNumber.Value.ToString(CultureInfo.InvariantCulture); } programInfo.ShowId = uniqueString.GetMD5().ToString("N", CultureInfo.InvariantCulture); // If we don't have valid episode info, assume it's a unique program, otherwise recordings might be skipped if (programInfo.IsSeries && !programInfo.IsRepeat && (programInfo.EpisodeNumber ?? 0) == 0) { programInfo.ShowId += programInfo.StartDate.Ticks.ToString(CultureInfo.InvariantCulture); } } else { programInfo.ShowId = program.ProgramId; } // Construct an id from the channel and start date programInfo.Id = string.Format(CultureInfo.InvariantCulture, "{0}_{1:O}", program.ChannelId, program.StartDate); if (programInfo.IsMovie) { programInfo.IsSeries = false; programInfo.EpisodeNumber = null; programInfo.EpisodeTitle = null; } return programInfo; } public Task Validate(ListingsProviderInfo info, bool validateLogin, bool validateListings) { // Assume all urls are valid. check files for existence if (!info.Path.StartsWith("http", StringComparison.OrdinalIgnoreCase) && !File.Exists(info.Path)) { throw new FileNotFoundException("Could not find the XmlTv file specified:", info.Path); } return Task.CompletedTask; } public async Task<List<NameIdPair>> GetLineups(ListingsProviderInfo info, string country, string location) { // In theory this should never be called because there is always only one lineup string path = await GetXml(info, CancellationToken.None).ConfigureAwait(false); _logger.LogDebug("Opening XmlTvReader for {Path}", path); var reader = new XmlTvReader(path, GetLanguage(info)); IEnumerable<XmlTvChannel> results = reader.GetChannels(); // Should this method be async? return results.Select(c => new NameIdPair() { Id = c.Id, Name = c.DisplayName }).ToList(); } public async Task<List<ChannelInfo>> GetChannels(ListingsProviderInfo info, CancellationToken cancellationToken) { // In theory this should never be called because there is always only one lineup string path = await GetXml(info, cancellationToken).ConfigureAwait(false); _logger.LogDebug("Opening XmlTvReader for {Path}", path); var reader = new XmlTvReader(path, GetLanguage(info)); var results = reader.GetChannels(); // Should this method be async? return results.Select(c => new ChannelInfo { Id = c.Id, Name = c.DisplayName, ImageUrl = string.IsNullOrEmpty(c.Icon?.Source) ? null : c.Icon.Source, Number = string.IsNullOrWhiteSpace(c.Number) ? c.Id : c.Number }).ToList(); } } }
XmlTvListingsProvider
csharp
dotnet__aspnetcore
src/Servers/Kestrel/stress/Program.cs
{ "start": 32759, "end": 33517 }
private sealed class ____ : HttpContent { private readonly byte[] _buffer; public ByteAtATimeNoLengthContent(byte[] buffer) => _buffer = buffer; protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context) { for (int i = 0; i < _buffer.Length; i++) { await stream.WriteAsync(_buffer.AsMemory(i, 1)); await stream.FlushAsync(); } } protected override bool TryComputeLength(out long length) { length = 0; return false; } } /// <summary>EventListener that dumps HTTP events out to either the console or a stream writer.</summary>
ByteAtATimeNoLengthContent
csharp
dotnet__extensions
test/Shared/JsonSchemaExporter/TestTypes.cs
{ "start": 50860, "end": 50985 }
public class ____; [JsonConverter(typeof(CustomConverter<ClassWithCustomConverter2>))]
ClassWithCustomConverter1
csharp
unoplatform__uno
src/Uno.UWP/ApplicationModel/Background/SystemConditionType.cs
{ "start": 167, "end": 393 }
public enum ____ { Invalid, UserPresent, UserNotPresent, InternetAvailable, InternetNotAvailable, SessionConnected, SessionDisconnected, FreeNetworkAvailable, BackgroundWorkCostNotHigh, } }
SystemConditionType
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp/NamedTypeSelector.cs
{ "start": 121, "end": 780 }
public class ____ { /// <summary> /// Name of the selector. /// </summary> public string Name { get; set; } /// <summary> /// Predicate. /// </summary> public Func<Type, bool> Predicate { get; set; } /// <summary> /// Creates new <see cref="NamedTypeSelector"/> object. /// </summary> /// <param name="name">Name</param> /// <param name="predicate">Predicate</param> public NamedTypeSelector(string name, Func<Type, bool> predicate) { Name = name; Predicate = predicate; } } }
NamedTypeSelector
csharp
DuendeSoftware__IdentityServer
identity-server/src/IdentityServer/Configuration/DependencyInjection/PostConfigureApplicationCookieTicketStore.cs
{ "start": 575, "end": 3517 }
public class ____ : IPostConfigureOptions<CookieAuthenticationOptions> { private readonly IHttpContextAccessor _httpContextAccessor; private readonly string _scheme; private readonly ILogger<PostConfigureApplicationCookieTicketStore> _logger; /// <summary> /// ctor /// </summary> /// <param name="httpContextAccessor"></param> /// <param name="identityServerOptions"></param> /// <param name="options"></param> /// <param name="logger"></param> public PostConfigureApplicationCookieTicketStore( IHttpContextAccessor httpContextAccessor, IdentityServerOptions identityServerOptions, IOptions<Microsoft.AspNetCore.Authentication.AuthenticationOptions> options, ILogger<PostConfigureApplicationCookieTicketStore> logger) { _httpContextAccessor = httpContextAccessor; _logger = logger; _scheme = identityServerOptions.Authentication.CookieAuthenticationScheme ?? options.Value.DefaultAuthenticateScheme ?? options.Value.DefaultScheme; } /// <summary> /// ctor /// </summary> /// <param name="httpContextAccessor"></param> /// <param name="scheme"></param> public PostConfigureApplicationCookieTicketStore(IHttpContextAccessor httpContextAccessor, string scheme) { _httpContextAccessor = httpContextAccessor; _scheme = scheme; } /// <inheritdoc /> public void PostConfigure(string name, CookieAuthenticationOptions options) { if (name == _scheme) { if (_httpContextAccessor.HttpContext == null) { _logger?.LogDebug("Failed to configure server side sessions for the authentication cookie scheme \"{scheme}\" because there is no current HTTP request"); return; } IdentityServerLicenseValidator.Instance.ValidateServerSideSessions(); var licenseUsage = _httpContextAccessor.HttpContext?.RequestServices.GetRequiredService<LicenseUsageTracker>(); licenseUsage?.FeatureUsed(LicenseFeature.ServerSideSessions); var sessionStore = _httpContextAccessor.HttpContext!.RequestServices.GetService<IServerSideSessionStore>(); if (sessionStore is InMemoryServerSideSessionStore) { var logger = _httpContextAccessor.HttpContext!.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger("Duende.IdentityServer.Startup"); logger.LogInformation("You are using the in-memory version of the user session store. This will store user authentication sessions server side, but in memory only. If you are using this feature in production, you want to switch to a different store implementation."); } options.SessionStore = new TicketStoreShim(_httpContextAccessor); } } } /// <summary> /// this shim
PostConfigureApplicationCookieTicketStore
csharp
dotnet__orleans
src/api/Orleans.EventSourcing/Orleans.EventSourcing.cs
{ "start": 1328, "end": 1519 }
public partial interface ____ { void DisableStatsCollection(); void EnableStatsCollection(); LogConsistencyStatistics GetStats(); }
ILogConsistencyDiagnostics
csharp
dotnet__aspire
src/Components/Aspire.OpenAI/api/Aspire.OpenAI.cs
{ "start": 2525, "end": 3160 }
partial class ____ { public static Aspire.OpenAI.AspireOpenAIClientBuilder AddKeyedOpenAIClient(this IHostApplicationBuilder builder, string name, System.Action<Aspire.OpenAI.OpenAISettings>? configureSettings = null, System.Action<OpenAI.OpenAIClientOptions>? configureOptions = null) { throw null; } public static Aspire.OpenAI.AspireOpenAIClientBuilder AddOpenAIClient(this IHostApplicationBuilder builder, string connectionName, System.Action<Aspire.OpenAI.OpenAISettings>? configureSettings = null, System.Action<OpenAI.OpenAIClientOptions>? configureOptions = null) { throw null; } } }
AspireOpenAIExtensions
csharp
microsoft__semantic-kernel
dotnet/src/SemanticKernel.UnitTests/Functions/KernelParameterMetadataTests.cs
{ "start": 276, "end": 7233 }
public class ____ { [Fact] public void ItThrowsForInvalidName() { Assert.Throws<ArgumentNullException>(() => new KernelParameterMetadata((string)null!)); Assert.Throws<ArgumentException>(() => new KernelParameterMetadata("")); Assert.Throws<ArgumentException>(() => new KernelParameterMetadata(" ")); Assert.Throws<ArgumentException>(() => new KernelParameterMetadata("\t\r\v ")); } [Fact] public void ItCanBeConstructedWithJustName() { var m = new KernelParameterMetadata("p"); Assert.Equal("p", m.Name); Assert.Empty(m.Description); Assert.Null(m.ParameterType); Assert.Null(m.Schema); Assert.Null(m.DefaultValue); Assert.False(m.IsRequired); } [Fact] public void ItRoundtripsArguments() { var m = new KernelParameterMetadata("p") { Description = "d", DefaultValue = "v", IsRequired = true, ParameterType = typeof(int), Schema = KernelJsonSchema.Parse("{ \"type\":\"object\" }") }; Assert.Equal("p", m.Name); Assert.Equal("d", m.Description); Assert.Equal("v", m.DefaultValue); Assert.True(m.IsRequired); Assert.Equal(typeof(int), m.ParameterType); Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("""{ "type":"object" }""")), JsonSerializer.Serialize(m.Schema)); } [Fact] public void ItInfersSchemaFromType() { Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("{ \"type\":\"integer\" }")), JsonSerializer.Serialize(new KernelParameterMetadata("p") { ParameterType = typeof(int) }.Schema)); Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("{ \"type\":\"number\" }")), JsonSerializer.Serialize(new KernelParameterMetadata("p") { ParameterType = typeof(double) }.Schema)); Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("{ \"type\":\"string\" }")), JsonSerializer.Serialize(new KernelParameterMetadata("p") { ParameterType = typeof(string) }.Schema)); Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("{ \"type\":\"boolean\" }")), JsonSerializer.Serialize(new KernelParameterMetadata("p") { ParameterType = typeof(bool) }.Schema)); Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("{ }")), JsonSerializer.Serialize(new KernelParameterMetadata("p") { ParameterType = typeof(object) }.Schema)); Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("{ \"type\":\"array\",\"items\":{\"type\":\"boolean\"}}")), JsonSerializer.Serialize(new KernelParameterMetadata("p") { ParameterType = typeof(bool[]) }.Schema)); Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("{\"type\":\"object\",\"properties\":{\"Value1\":{\"type\":[\"string\",\"null\"]},\"Value2\":{\"description\":\"Some property that does something.\",\"type\":\"integer\"},\"Value3\":{\"description\":\"This one also does something.\",\"type\":\"number\"}}}")), JsonSerializer.Serialize(new KernelParameterMetadata("p") { ParameterType = typeof(Example) }.Schema)); } [Fact] public void ItCantInferSchemaFromUnsupportedType() { Assert.Null(new KernelParameterMetadata("p") { ParameterType = typeof(void) }.Schema); Assert.Null(new KernelParameterMetadata("p") { ParameterType = typeof(int*) }.Schema); } [Theory] [ClassData(typeof(TestJsonSerializerOptionsForPrimitives))] public void ItIncludesDescriptionInSchema(JsonSerializerOptions? jsos) { var m = jsos is not null ? new KernelParameterMetadata("p", jsos) { Description = "something neat", ParameterType = typeof(int) } : new KernelParameterMetadata("p") { Description = "something neat", ParameterType = typeof(int) }; Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("""{"description":"something neat", "type":"integer"}""")), JsonSerializer.Serialize(m.Schema)); } [Theory] [ClassData(typeof(TestJsonSerializerOptionsForPrimitives))] public void ItIncludesDefaultValueInSchema(JsonSerializerOptions? jsos) { var m = jsos is not null ? new KernelParameterMetadata("p", jsos) { DefaultValue = "42", ParameterType = typeof(int) } : new KernelParameterMetadata("p") { DefaultValue = "42", ParameterType = typeof(int) }; Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("""{"description":"(default value: 42)", "type":"integer"}""")), JsonSerializer.Serialize(m.Schema)); } [Theory] [ClassData(typeof(TestJsonSerializerOptionsForPrimitives))] public void ItIncludesDescriptionAndDefaultValueInSchema(JsonSerializerOptions? jsos) { var m = jsos is not null ? new KernelParameterMetadata("p", jsos) { Description = "something neat", DefaultValue = "42", ParameterType = typeof(int) } : new KernelParameterMetadata("p") { Description = "something neat", DefaultValue = "42", ParameterType = typeof(int) }; Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("""{"description":"something neat (default value: 42)", "type":"integer"}""")), JsonSerializer.Serialize(m.Schema)); } [Fact] public void ItCachesInferredSchemas() { var m = new KernelParameterMetadata("p") { ParameterType = typeof(Example) }; Assert.Same(m.Schema, m.Schema); } [Fact] public void ItCopiesInferredSchemaToCopy() { var m = new KernelParameterMetadata("p") { ParameterType = typeof(Example) }; KernelJsonSchema? schema1 = m.Schema; Assert.NotNull(schema1); m = new KernelParameterMetadata(m); Assert.Same(schema1, m.Schema); } [Fact] public void ItInvalidatesSchemaForNewType() { var m = new KernelParameterMetadata("p") { ParameterType = typeof(Example) }; KernelJsonSchema? schema1 = m.Schema; Assert.NotNull(schema1); m = new KernelParameterMetadata(m) { ParameterType = typeof(int) }; Assert.NotNull(m.Schema); Assert.NotSame(schema1, m.Schema); } [Fact] public void ItInvalidatesSchemaForNewDescription() { var m = new KernelParameterMetadata("p") { ParameterType = typeof(Example) }; KernelJsonSchema? schema1 = m.Schema; Assert.NotNull(schema1); m = new KernelParameterMetadata(m) { Description = "something new" }; Assert.NotNull(m.Schema); Assert.NotSame(schema1, m.Schema); } [Fact] public void ItInvalidatesSchemaForNewDefaultValue() { var m = new KernelParameterMetadata("p") { ParameterType = typeof(Example) }; KernelJsonSchema? schema1 = m.Schema; Assert.NotNull(schema1); m = new KernelParameterMetadata(m) { DefaultValue = "42" }; Assert.NotNull(m.Schema); Assert.NotSame(schema1, m.Schema); } #pragma warning disable CA1812 //
KernelParameterMetadataTests
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/AppSelfHostTests.cs
{ "start": 154, "end": 242 }
public class ____ : IReturn<SpinWait> { public int? Iterations { get; set; } }
SpinWait
csharp
dotnet__efcore
test/EFCore.Design.Tests/Scaffolding/Internal/CSharpEntityTypeGeneratorTest.cs
{ "start": 35666, "end": 36353 }
public partial class ____ { [Key] public int Id { get; set; } [Column("propertyA")] public string A { get; set; } [Column(TypeName = "nchar(10)")] public string B { get; set; } [Column("random", TypeName = "varchar(200)")] public string C { get; set; } [Column(TypeName = "numeric(18, 2)")] public decimal D { get; set; } [StringLength(100)] public string E { get; set; } } """, code.AdditionalFiles.Single(f => f.Path == "Entity.cs")); AssertFileContents( $$""" using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore; namespace TestNamespace;
Entity
csharp
bitwarden__server
bitwarden_license/test/Scim.IntegrationTest/Controllers/v2/GroupsControllerPatchTests.cs
{ "start": 213, "end": 10202 }
public class ____ : IClassFixture<ScimApplicationFactory>, IAsyncLifetime { private readonly ScimApplicationFactory _factory; public GroupsControllerPatchTests(ScimApplicationFactory factory) { _factory = factory; } public Task InitializeAsync() { var databaseContext = _factory.GetDatabaseContext(); _factory.ReinitializeDbForTests(databaseContext); return Task.CompletedTask; } Task IAsyncLifetime.DisposeAsync() => Task.CompletedTask; [Fact] public async Task Patch_ReplaceDisplayName_Success() { var organizationId = ScimApplicationFactory.TestOrganizationId1; var groupId = ScimApplicationFactory.TestGroupId1; var newDisplayName = "Patch Display Name"; var inputModel = new ScimPatchModel { Operations = new List<ScimPatchModel.OperationModel>() { new ScimPatchModel.OperationModel { Op = "replace", Value = JsonDocument.Parse($"{{\"displayName\":\"{newDisplayName}\"}}").RootElement } }, Schemas = new List<string>() { ScimConstants.Scim2SchemaGroup } }; var context = await _factory.GroupsPatchAsync(organizationId, groupId, inputModel); Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode); var databaseContext = _factory.GetDatabaseContext(); var group = databaseContext.Groups.FirstOrDefault(g => g.Id == groupId); Assert.Equal(newDisplayName, group.Name); Assert.Equal(ScimApplicationFactory.InitialGroupUsersCount, databaseContext.GroupUsers.Count()); Assert.True(databaseContext.GroupUsers.Any(gu => gu.OrganizationUserId == ScimApplicationFactory.TestOrganizationUserId1)); Assert.True(databaseContext.GroupUsers.Any(gu => gu.OrganizationUserId == ScimApplicationFactory.TestOrganizationUserId4)); } [Fact] public async Task Patch_ReplaceMembers_Success() { var organizationId = ScimApplicationFactory.TestOrganizationId1; var groupId = ScimApplicationFactory.TestGroupId1; var inputModel = new ScimPatchModel { Operations = new List<ScimPatchModel.OperationModel>() { new ScimPatchModel.OperationModel { Op = "replace", Path = "members", Value = JsonDocument.Parse($"[{{\"value\":\"{ScimApplicationFactory.TestOrganizationUserId2}\"}}]").RootElement } }, Schemas = new List<string>() { ScimConstants.Scim2SchemaGroup } }; var context = await _factory.GroupsPatchAsync(organizationId, groupId, inputModel); Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode); var databaseContext = _factory.GetDatabaseContext(); Assert.Single(databaseContext.GroupUsers); Assert.Equal(ScimApplicationFactory.InitialGroupUsersCount - 1, databaseContext.GroupUsers.Count()); var groupUser = databaseContext.GroupUsers.FirstOrDefault(); Assert.Equal(ScimApplicationFactory.TestOrganizationUserId2, groupUser.OrganizationUserId); } [Fact] public async Task Patch_AddSingleMember_Success() { var organizationId = ScimApplicationFactory.TestOrganizationId1; var groupId = ScimApplicationFactory.TestGroupId1; var inputModel = new ScimPatchModel { Operations = new List<ScimPatchModel.OperationModel>() { new ScimPatchModel.OperationModel { Op = "add", Path = $"members[value eq \"{ScimApplicationFactory.TestOrganizationUserId2}\"]", Value = JsonDocument.Parse("{}").RootElement } }, Schemas = new List<string>() { ScimConstants.Scim2SchemaGroup } }; var context = await _factory.GroupsPatchAsync(organizationId, groupId, inputModel); Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode); var databaseContext = _factory.GetDatabaseContext(); Assert.Equal(ScimApplicationFactory.InitialGroupUsersCount + 1, databaseContext.GroupUsers.Count()); Assert.True(databaseContext.GroupUsers.Any(gu => gu.GroupId == groupId && gu.OrganizationUserId == ScimApplicationFactory.TestOrganizationUserId1)); Assert.True(databaseContext.GroupUsers.Any(gu => gu.GroupId == groupId && gu.OrganizationUserId == ScimApplicationFactory.TestOrganizationUserId2)); Assert.True(databaseContext.GroupUsers.Any(gu => gu.GroupId == groupId && gu.OrganizationUserId == ScimApplicationFactory.TestOrganizationUserId4)); } [Fact] public async Task Patch_AddListMembers_Success() { var organizationId = ScimApplicationFactory.TestOrganizationId1; var groupId = ScimApplicationFactory.TestGroupId2; var inputModel = new ScimPatchModel { Operations = new List<ScimPatchModel.OperationModel>() { new ScimPatchModel.OperationModel { Op = "add", Path = "members", Value = JsonDocument.Parse($"[{{\"value\":\"{ScimApplicationFactory.TestOrganizationUserId2}\"}},{{\"value\":\"{ScimApplicationFactory.TestOrganizationUserId3}\"}}]").RootElement } }, Schemas = new List<string>() { ScimConstants.Scim2SchemaGroup } }; var context = await _factory.GroupsPatchAsync(organizationId, groupId, inputModel); Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode); var databaseContext = _factory.GetDatabaseContext(); Assert.True(databaseContext.GroupUsers.Any(gu => gu.GroupId == groupId && gu.OrganizationUserId == ScimApplicationFactory.TestOrganizationUserId2)); Assert.True(databaseContext.GroupUsers.Any(gu => gu.GroupId == groupId && gu.OrganizationUserId == ScimApplicationFactory.TestOrganizationUserId3)); } [Fact] public async Task Patch_RemoveSingleMember_ReplaceDisplayName_Success() { var organizationId = ScimApplicationFactory.TestOrganizationId1; var groupId = ScimApplicationFactory.TestGroupId1; var newDisplayName = "Patch Display Name"; var inputModel = new ScimPatchModel { Operations = new List<ScimPatchModel.OperationModel>() { new ScimPatchModel.OperationModel { Op = "remove", Path = $"members[value eq \"{ScimApplicationFactory.TestOrganizationUserId1}\"]", Value = JsonDocument.Parse("{}").RootElement }, new ScimPatchModel.OperationModel { Op = "replace", Value = JsonDocument.Parse($"{{\"displayName\":\"{newDisplayName}\"}}").RootElement } }, Schemas = new List<string>() { ScimConstants.Scim2SchemaGroup } }; var context = await _factory.GroupsPatchAsync(organizationId, groupId, inputModel); Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode); var databaseContext = _factory.GetDatabaseContext(); Assert.Equal(ScimApplicationFactory.InitialGroupUsersCount - 1, databaseContext.GroupUsers.Count()); Assert.Equal(ScimApplicationFactory.InitialGroupCount, databaseContext.Groups.Count()); var group = databaseContext.Groups.FirstOrDefault(g => g.Id == groupId); Assert.Equal(newDisplayName, group.Name); } [Fact] public async Task Patch_RemoveListMembers_Success() { var organizationId = ScimApplicationFactory.TestOrganizationId1; var groupId = ScimApplicationFactory.TestGroupId1; var inputModel = new ScimPatchModel { Operations = new List<ScimPatchModel.OperationModel>() { new ScimPatchModel.OperationModel { Op = "remove", Path = "members", Value = JsonDocument.Parse($"[{{\"value\":\"{ScimApplicationFactory.TestOrganizationUserId1}\"}}, {{\"value\":\"{ScimApplicationFactory.TestOrganizationUserId4}\"}}]").RootElement } }, Schemas = new List<string>() { ScimConstants.Scim2SchemaGroup } }; var context = await _factory.GroupsPatchAsync(organizationId, groupId, inputModel); Assert.Equal(StatusCodes.Status204NoContent, context.Response.StatusCode); var databaseContext = _factory.GetDatabaseContext(); Assert.Empty(databaseContext.GroupUsers); } [Fact] public async Task Patch_NotFound() { var organizationId = ScimApplicationFactory.TestOrganizationId1; var groupId = Guid.NewGuid(); var inputModel = new Models.ScimPatchModel { Operations = new List<ScimPatchModel.OperationModel>(), Schemas = new List<string>() { ScimConstants.Scim2SchemaGroup } }; var expectedResponse = new ScimErrorResponseModel { Status = StatusCodes.Status404NotFound, Detail = "Group not found.", Schemas = new List<string> { ScimConstants.Scim2SchemaError } }; var context = await _factory.GroupsPatchAsync(organizationId, groupId, inputModel); Assert.Equal(StatusCodes.Status404NotFound, context.Response.StatusCode); var responseModel = JsonSerializer.Deserialize<ScimErrorResponseModel>(context.Response.Body, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); AssertHelper.AssertPropertyEqual(expectedResponse, responseModel); } }
GroupsControllerPatchTests
csharp
dotnet__aspnetcore
src/Middleware/WebSockets/src/HandshakeHelpers.cs
{ "start": 427, "end": 11403 }
internal static class ____ { // This uses C# compiler's ability to refer to static data directly. For more information see https://vcsjones.dev/2019/02/01/csharp-readonly-span-bytes-static private static ReadOnlySpan<byte> EncodedWebSocketKey => "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"u8; public static void GenerateResponseHeaders(bool isHttp1, IHeaderDictionary requestHeaders, string? subProtocol, IHeaderDictionary responseHeaders) { if (isHttp1) { responseHeaders.Connection = HeaderNames.Upgrade; responseHeaders.Upgrade = Constants.Headers.UpgradeWebSocket; responseHeaders.SecWebSocketAccept = CreateResponseKey(requestHeaders.SecWebSocketKey.ToString()); } if (!string.IsNullOrWhiteSpace(subProtocol)) { responseHeaders.SecWebSocketProtocol = subProtocol; } } /// <summary> /// Validates the Sec-WebSocket-Key request header /// </summary> /// <param name="value"></param> /// <returns></returns> public static bool IsRequestKeyValid(string value) { if (string.IsNullOrWhiteSpace(value)) { return false; } Span<byte> temp = stackalloc byte[16]; var success = Convert.TryFromBase64String(value, temp, out var written); return success && written == 16; } public static string CreateResponseKey(string requestKey) { // "The value of this header field is constructed by concatenating /key/, defined above in step 4 // in Section 4.2.2, with the string "258EAFA5-E914-47DA-95CA-C5AB0DC85B11", taking the SHA-1 hash of // this concatenated value to obtain a 20-byte value and base64-encoding" // https://tools.ietf.org/html/rfc6455#section-4.2.2 // requestKey is already verified to be small (24 bytes) by 'IsRequestKeyValid()' and everything is 1:1 mapping to UTF8 bytes // so this can be hardcoded to 60 bytes for the requestKey + static websocket string Span<byte> mergedBytes = stackalloc byte[60]; Encoding.UTF8.GetBytes(requestKey, mergedBytes); EncodedWebSocketKey.CopyTo(mergedBytes[24..]); Span<byte> hashedBytes = stackalloc byte[20]; var written = SHA1.HashData(mergedBytes, hashedBytes); if (written != 20) { throw new InvalidOperationException("Could not compute the hash for the 'Sec-WebSocket-Accept' header."); } return Convert.ToBase64String(hashedBytes); } // https://datatracker.ietf.org/doc/html/rfc7692#section-7.1 public static bool ParseDeflateOptions(ReadOnlySpan<char> extension, bool serverContextTakeover, int serverMaxWindowBits, out WebSocketDeflateOptions parsedOptions, [NotNullWhen(true)] out string? response) { bool hasServerMaxWindowBits = false; bool hasClientMaxWindowBits = false; bool hasClientNoContext = false; bool hasServerNoContext = false; response = null; parsedOptions = new WebSocketDeflateOptions() { ServerContextTakeover = serverContextTakeover, ServerMaxWindowBits = serverMaxWindowBits }; using var builder = new ValueStringBuilder(WebSocketDeflateConstants.MaxExtensionLength); builder.Append(WebSocketDeflateConstants.Extension); while (true) { int end = extension.IndexOf(';'); ReadOnlySpan<char> value = (end >= 0 ? extension[..end] : extension).Trim(); if (value.Length == 0) { break; } if (value.SequenceEqual(WebSocketDeflateConstants.ClientNoContextTakeover)) { // https://datatracker.ietf.org/doc/html/rfc7692#section-7 // MUST decline if: // The negotiation offer contains multiple extension parameters with // the same name. if (hasClientNoContext) { return false; } hasClientNoContext = true; parsedOptions.ClientContextTakeover = false; builder.Append(';'); builder.Append(' '); builder.Append(WebSocketDeflateConstants.ClientNoContextTakeover); } else if (value.SequenceEqual(WebSocketDeflateConstants.ServerNoContextTakeover)) { // https://datatracker.ietf.org/doc/html/rfc7692#section-7 // MUST decline if: // The negotiation offer contains multiple extension parameters with // the same name. if (hasServerNoContext) { return false; } hasServerNoContext = true; parsedOptions.ServerContextTakeover = false; } else if (value.StartsWith(WebSocketDeflateConstants.ClientMaxWindowBits)) { // https://datatracker.ietf.org/doc/html/rfc7692#section-7 // MUST decline if: // The negotiation offer contains multiple extension parameters with // the same name. if (hasClientMaxWindowBits) { return false; } hasClientMaxWindowBits = true; if (!ParseWindowBits(value, out var clientMaxWindowBits)) { return false; } // 8 is a valid value according to the spec, but our zlib implementation does not support it if (clientMaxWindowBits == 8) { return false; } // https://tools.ietf.org/html/rfc7692#section-7.1.2.2 // the server may either ignore this // value or use this value to avoid allocating an unnecessarily big LZ77 // sliding window by including the "client_max_window_bits" extension // parameter in the corresponding extension negotiation response to the // offer with a value equal to or smaller than the received value. parsedOptions.ClientMaxWindowBits = clientMaxWindowBits ?? 15; // If a received extension negotiation offer doesn't have the // "client_max_window_bits" extension parameter, the corresponding // extension negotiation response to the offer MUST NOT include the // "client_max_window_bits" extension parameter. builder.Append(';'); builder.Append(' '); builder.Append(WebSocketDeflateConstants.ClientMaxWindowBits); builder.Append('='); var len = (parsedOptions.ClientMaxWindowBits > 9) ? 2 : 1; var span = builder.AppendSpan(len); var ret = parsedOptions.ClientMaxWindowBits.TryFormat(span, out var written, provider: CultureInfo.InvariantCulture); Debug.Assert(ret); Debug.Assert(written == len); } else if (value.StartsWith(WebSocketDeflateConstants.ServerMaxWindowBits)) { // https://datatracker.ietf.org/doc/html/rfc7692#section-7 // MUST decline if: // The negotiation offer contains multiple extension parameters with // the same name. if (hasServerMaxWindowBits) { return false; } hasServerMaxWindowBits = true; if (!ParseWindowBits(value, out var parsedServerMaxWindowBits)) { return false; } // 8 is a valid value according to the spec, but our zlib implementation does not support it if (parsedServerMaxWindowBits == 8) { return false; } // https://tools.ietf.org/html/rfc7692#section-7.1.2.1 // A server accepts an extension negotiation offer with this parameter // by including the "server_max_window_bits" extension parameter in the // extension negotiation response to send back to the client with the // same or smaller value as the offer. parsedOptions.ServerMaxWindowBits = Math.Min(parsedServerMaxWindowBits ?? 15, serverMaxWindowBits); } static bool ParseWindowBits(ReadOnlySpan<char> value, out int? parsedValue) { var startIndex = value.IndexOf('='); // parameters can be sent without a value by the client, we'll use the values set by the app developer or the default of 15 if (startIndex < 0) { parsedValue = null; return true; } value = value[(startIndex + 1)..].TrimEnd(); if (value.Length == 0) { parsedValue = null; return false; } // https://datatracker.ietf.org/doc/html/rfc7692#section-5.2 // check for value in quotes and pull the value out without the quotes if (value[0] == '"' && value.EndsWith("\"".AsSpan()) && value.Length > 1) { value = value[1..^1]; } if (!int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int windowBits) || windowBits < 8 || windowBits > 15) { parsedValue = null; return false; } parsedValue = windowBits; return true; } if (end < 0) { break; } extension = extension[(end + 1)..]; } if (!parsedOptions.ServerContextTakeover) { builder.Append(';'); builder.Append(' '); builder.Append(WebSocketDeflateConstants.ServerNoContextTakeover); } if (hasServerMaxWindowBits || parsedOptions.ServerMaxWindowBits != 15) { builder.Append(';'); builder.Append(' '); builder.Append(WebSocketDeflateConstants.ServerMaxWindowBits); builder.Append('='); var len = (parsedOptions.ServerMaxWindowBits > 9) ? 2 : 1; var span = builder.AppendSpan(len); var ret = parsedOptions.ServerMaxWindowBits.TryFormat(span, out var written, provider: CultureInfo.InvariantCulture); Debug.Assert(ret); Debug.Assert(written == len); } response = builder.ToString(); return true; } }
HandshakeHelpers
csharp
ChilliCream__graphql-platform
src/HotChocolate/Fusion-vnext/src/Fusion.Execution/Execution/Nodes/Selection.cs
{ "start": 166, "end": 3817 }
public sealed class ____ : ISelection { private readonly FieldSelectionNode[] _syntaxNodes; private readonly ulong[] _includeFlags; private readonly byte[] _utf8ResponseName; private Flags _flags; public Selection( int id, string responseName, IOutputFieldDefinition field, FieldSelectionNode[] syntaxNodes, ulong[] includeFlags, bool isInternal) { ArgumentNullException.ThrowIfNull(field); if (syntaxNodes.Length == 0) { throw new ArgumentException( "The syntaxNodes collection cannot be empty.", nameof(syntaxNodes)); } Id = id; ResponseName = responseName; Field = field; _syntaxNodes = syntaxNodes; _includeFlags = includeFlags; _flags = isInternal ? Flags.Internal : Flags.None; if (field.Type.NamedType().IsLeafType()) { _flags |= Flags.Leaf; } _utf8ResponseName = Utf8StringCache.GetUtf8String(responseName); } public int Id { get; } public string ResponseName { get; } internal ReadOnlySpan<byte> Utf8ResponseName => _utf8ResponseName; public bool IsInternal => (_flags & Flags.Internal) == Flags.Internal; public bool IsConditional => _includeFlags.Length > 0; public bool IsLeaf => (_flags & Flags.Leaf) == Flags.Leaf; public IOutputFieldDefinition Field { get; } public IType Type => Field.Type; public SelectionSet DeclaringSelectionSet { get; private set; } = null!; ISelectionSet ISelection.DeclaringSelectionSet => DeclaringSelectionSet; public ReadOnlySpan<FieldSelectionNode> SyntaxNodes => _syntaxNodes; internal ResolveFieldValue? Resolver => Field.Features.Get<ResolveFieldValue>(); IEnumerable<FieldNode> ISelection.GetSyntaxNodes() { for (var i = 0; i < SyntaxNodes.Length; i++) { yield return SyntaxNodes[i].Node; } } public bool IsIncluded(ulong includeFlags) { if (_includeFlags.Length == 0) { return true; } if (_includeFlags.Length == 1) { var flags1 = _includeFlags[0]; return (flags1 & includeFlags) == flags1; } if (_includeFlags.Length == 2) { var flags1 = _includeFlags[0]; var flags2 = _includeFlags[1]; return (flags1 & includeFlags) == flags1 || (flags2 & includeFlags) == flags2; } if (_includeFlags.Length == 3) { var flags1 = _includeFlags[0]; var flags2 = _includeFlags[1]; var flags3 = _includeFlags[2]; return (flags1 & includeFlags) == flags1 || (flags2 & includeFlags) == flags2 || (flags3 & includeFlags) == flags3; } var span = _includeFlags.AsSpan(); for (var i = 0; i < span.Length; i++) { if ((span[i] & includeFlags) == span[i]) { return true; } } return false; } public override string ToString() { if (SyntaxNodes[0].Node.Alias is not null) { return $"{ResponseName} : {Field.Name}"; } return Field.Name; } internal void Seal(SelectionSet selectionSet) { if ((_flags & Flags.Sealed) == Flags.Sealed) { throw new InvalidOperationException("Selection is already sealed."); } _flags |= Flags.Sealed; DeclaringSelectionSet = selectionSet; } [Flags]
Selection
csharp
unoplatform__uno
src/Uno.UI/UI/Xaml/Input/Internal/FocusedElementRemovedEventArgs.cs
{ "start": 316, "end": 717 }
internal class ____ : EventArgs { public FocusedElementRemovedEventArgs(DependencyObject? focusedElement, DependencyObject? currentNextFocusableElement) { OldFocusedElement = focusedElement; NewFocusedElement = currentNextFocusableElement; } public DependencyObject? OldFocusedElement { get; } public DependencyObject? NewFocusedElement { get; set; } } }
FocusedElementRemovedEventArgs
csharp
unoplatform__uno
src/SourceGenerators/Uno.UI.SourceGenerators/RemoteControl/RemoteControlGenerator.cs
{ "start": 426, "end": 7460 }
public class ____ : ISourceGenerator { /// <summary> /// This list of properties used to capture the environment of the building project /// so it can be propagated to the remote control server's hot reload workspace. /// The list is derived from a extract of a build log inside Visual Studio and may /// need to be updated if new properties are required. /// </summary> private static readonly string[] AdditionalMSProperties = new[] { "SolutionFileName", "LangName", "Configuration", "LangID", "SolutionDir", "SolutionExt", "BuildingInsideVisualStudio", "UnoRemoteControlPort", "UseHostCompilerIfAvailable", "TargetFramework", "DefineExplicitDefaults", "Platform", "RuntimeIdentifier", "UnoRuntimeIdentifier", "UnoWinRTRuntimeIdentifier", "SolutionPath", "SolutionName", "VSIDEResolvedNonMSBuildProjectOutputs", "DevEnvDir", "MSBuildVersion", "UnoHotReloadDiagnosticsLogPath", "AppendRuntimeIdentifierToOutputPath", "OutputPath", "IntermediateOutputPath" }; public void Initialize(GeneratorInitializationContext context) { } public void Execute(GeneratorExecutionContext context) { var isProjectConfigEnabled = IsMSBuildPropertyTrue("UnoForceIncludeProjectConfiguration"); var isServerProcessorsConfigEnabled = IsMSBuildPropertyTrue("UnoForceIncludeServerProcessorsConfiguration"); if (!DesignTimeHelper.IsDesignTime(context) && context.GetMSBuildPropertyValue("Configuration") == "Debug") { if ((IsRemoteControlClientInstalled(context) // Inside the uno solution we generate the attributes anyways, so // we can test the remote control tooling explicitly. || IsInsideUnoSolution(context)) && PlatformHelper.IsApplication(context)) { var sb = new IndentedStringBuilder(); BuildGeneratedFileHeader(sb); BuildEndPointAttribute(context, sb); BuildProjectConfiguration(context, sb); BuildServerProcessorsPaths(context, sb); context.AddSource("RemoteControl", sb.ToString()); } } else if (isProjectConfigEnabled || isServerProcessorsConfigEnabled) { // This is designed for runtime-tests that wants to test HotReload also in release (i.e. using app built on the CI). // The runtime-test package will add those properties if the dev-server package is referenced so apps will be automatically // configured properly as soon as they reference both the dev-server and the runtime-test package. var sb = new IndentedStringBuilder(); BuildGeneratedFileHeader(sb); if (isProjectConfigEnabled) { BuildProjectConfiguration(context, sb); } if (isServerProcessorsConfigEnabled) { BuildServerProcessorsPaths(context, sb); } context.AddSource("RemoteControl", sb.ToString()); } bool IsMSBuildPropertyTrue(string propertyName) => bool.TryParse(context.GetMSBuildPropertyValue(propertyName), out var value) && value; } private static bool IsInsideUnoSolution(GeneratorExecutionContext context) => context.GetMSBuildPropertyValue("_IsUnoUISolution") == "true"; private static void BuildGeneratedFileHeader(IndentedStringBuilder sb) { sb.AppendLineIndented("// <auto-generated>"); sb.AppendLineIndented("// ***************************************************************************************"); sb.AppendLineIndented("// This file has been generated by the package Uno.UI.DevServer - for Xaml Hot Reload."); sb.AppendLineIndented("// Documentation: https://platform.uno/docs/articles/features/working-with-xaml-hot-reload.html"); sb.AppendLineIndented("// ***************************************************************************************"); sb.AppendLineIndented("// </auto-generated>"); sb.AppendLineIndented("// <autogenerated />"); sb.AppendLineIndented("#pragma warning disable // Ignore code analysis warnings"); sb.AppendLineIndented(""); } private void BuildServerProcessorsPaths(GeneratorExecutionContext context, IndentedStringBuilder sb) { sb.AppendLineIndented($"[assembly: global::Uno.UI.RemoteControl.ServerProcessorsConfigurationAttribute(" + $"@\"{context.GetMSBuildPropertyValue("UnoRemoteControlProcessorsPath")}\"" + $")]"); } private static bool IsRemoteControlClientInstalled(GeneratorExecutionContext context) => context.Compilation.GetTypeByMetadataName("Uno.UI.RemoteControl.RemoteControlClient") != null; /// <summary> /// Generates the attribute used by the remotecontrol client to configure the server. /// </summary> private static void BuildProjectConfiguration(GeneratorExecutionContext context, IndentedStringBuilder sb) { sb.AppendLineIndented($"[assembly: global::Uno.UI.RemoteControl.ProjectConfigurationAttribute("); sb.AppendLineIndented($"@\"{context.GetMSBuildPropertyValue("MSBuildProjectFullPath")}\",\n"); // Provide additional properties so that our hot reload workspace can properly // replicate the original build environment that was used (e.g. VS or dotnet build) var additionalPropertiesValues = AdditionalMSProperties.Select(p => $"@\"{p}={Convert.ToBase64String(Encoding.UTF8.GetBytes(context.GetMSBuildPropertyValue(p)))}\""); sb.AppendLineIndented($"new [] {{ {string.Join(", ", additionalPropertiesValues)} }}"); sb.AppendLineIndented(")]"); } private static void BuildEndPointAttribute(GeneratorExecutionContext context, IndentedStringBuilder sb) { var unoRemoteControlPort = context.GetMSBuildPropertyValue("UnoRemoteControlPort"); if (string.IsNullOrEmpty(unoRemoteControlPort)) { unoRemoteControlPort = "0"; } var unoRemoteControlHost = context.GetMSBuildPropertyValue("UnoRemoteControlHost"); if (string.IsNullOrEmpty(unoRemoteControlHost)) { // Inside the Uno Solution we do not start the remote control // client, as the location of the RC server is not coming from // a nuget package. if (!IsInsideUnoSolution(context)) { var addresses = NetworkInterface.GetAllNetworkInterfaces() .SelectMany(x => x.GetIPProperties().UnicastAddresses) .Where(x => !IPAddress.IsLoopback(x.Address)); //This is not supported on linux yet: .Where(x => x.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred); foreach (var addressInfo in addresses) { var address = addressInfo.Address; string addressStr; if (address.AddressFamily == AddressFamily.InterNetworkV6) { address.ScopeId = 0; // remove annoying "%xx" on IPv6 addresses addressStr = $"[{address}]"; } else { addressStr = address.ToString(); } sb.AppendLineIndented($"[assembly: global::Uno.UI.RemoteControl.ServerEndpointAttribute(\"{addressStr}\", {unoRemoteControlPort})]"); } } } else { sb.AppendLineIndented($"[assembly: global::Uno.UI.RemoteControl.ServerEndpointAttribute(\"{unoRemoteControlHost}\", {unoRemoteControlPort})]"); } } } }
RemoteControlGenerator
csharp
CommunityToolkit__WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.UI.Controls.Core/Loading/Loading.Properties.cs
{ "start": 443, "end": 1608 }
public partial class ____ { /// <summary> /// Identifies the <see cref="IsLoading"/> dependency property. /// </summary> public static readonly DependencyProperty IsLoadingProperty = DependencyProperty.Register( nameof(IsLoading), typeof(bool), typeof(Loading), new PropertyMetadata(default(bool), IsLoadingPropertyChanged)); /// <summary> /// Gets or sets a value indicating whether the control is in the loading state. /// </summary> /// <remarks>Set this to true to show the Loading control, false to hide the control.</remarks> public bool IsLoading { get { return (bool)GetValue(IsLoadingProperty); } set { SetValue(IsLoadingProperty, value); } } private static void IsLoadingPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var control = d as Loading; if (control._presenter == null) { control._presenter = control.GetTemplateChild("ContentGrid") as FrameworkElement; } control?.Update(); } } }
Loading
csharp
ServiceStack__ServiceStack
ServiceStack.OrmLite/tests/ServiceStack.OrmLite.MySql.Tests/LocalizationTests.cs
{ "start": 846, "end": 1603 }
public class ____ { [AutoIncrement] public int Id { get; set; } public short Width { get; set; } public float Height { get; set; } public double Top { get; set; } public decimal Left { get; set; } } [Test] public void Can_query_using_float_in_alernate_culuture() { using var db = OpenDbConnection(); db.CreateTable<Point>(true); db.Insert(new Point { Width = 4, Height = 1.123f, Top = 3.456d, Left = 2.345m}); var points = db.Select<Point>("Height=@height", new { height = 1.123f }); Console.WriteLine(points.Dump()); Assert.That(points[0].Width, Is.EqualTo(4)); Assert.That(points[0].Height, Is.EqualTo(1.123f)); Assert.That(points[0].Top, Is.EqualTo(3.456d)); Assert.That(points[0].Left, Is.EqualTo(2.345m)); } }
Point
csharp
EventStore__EventStore
src/KurrentDB.Core/Bus/Extensions/SystemClient.cs
{ "start": 5009, "end": 5433 }
public interface ____ { Task SubscribeToAll(Position? position, IEventFilter filter, uint maxSearchWindow, Channel<ReadResponse> channel, ResiliencePipeline resiliencePipeline, CancellationToken cancellationToken); Task SubscribeToStream(StreamRevision? revision, string stream, Channel<ReadResponse> channel, ResiliencePipeline resiliencePipeline, CancellationToken cancellationToken); } [PublicAPI]
ISubscriptionsOperations
csharp
grandnode__grandnode2
src/Business/Grand.Business.Core/Interfaces/Catalog/Discounts/IDiscountProviderLoader.cs
{ "start": 62, "end": 1023 }
public interface ____ { /// <summary> /// Loads existing discount provider by rule system name /// </summary> /// <param name="ruleSystemName">Rule system name</param> /// <returns>Discount provider</returns> IDiscountProvider LoadDiscountProviderByRuleSystemName(string ruleSystemName); /// <summary> /// Loads all available discount providers /// </summary> /// <returns>Discount requirement rules</returns> IList<IDiscountProvider> LoadAllDiscountProviders(); /// <summary> /// Load discount amount providers /// </summary> /// <returns></returns> IList<IDiscountAmountProvider> LoadDiscountAmountProviders(); /// <summary> /// Load discount amount providerBySystemName /// </summary> /// <param name="systemName"></param> /// <returns></returns> IDiscountAmountProvider LoadDiscountAmountProviderBySystemName(string systemName); }
IDiscountProviderLoader
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Driver/Core/Bindings/ReadPreferenceBinding.cs
{ "start": 864, "end": 3729 }
internal sealed class ____ : IReadBinding { #pragma warning disable CA2213 // Disposable fields should be disposed private readonly IClusterInternal _cluster; #pragma warning restore CA2213 // Disposable fields should be disposed private bool _disposed; private readonly ReadPreference _readPreference; private readonly IServerSelector _serverSelector; private readonly ICoreSessionHandle _session; public ReadPreferenceBinding(IClusterInternal cluster, ReadPreference readPreference, ICoreSessionHandle session) { _cluster = Ensure.IsNotNull(cluster, nameof(cluster)); _readPreference = Ensure.IsNotNull(readPreference, nameof(readPreference)); _session = Ensure.IsNotNull(session, nameof(session)); _serverSelector = new ReadPreferenceServerSelector(readPreference); } public ReadPreference ReadPreference { get { return _readPreference; } } public ICoreSessionHandle Session { get { return _session; } } public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext) { return GetReadChannelSource(operationContext, null); } public Task<IChannelSourceHandle> GetReadChannelSourceAsync(OperationContext operationContext) { return GetReadChannelSourceAsync(operationContext, null); } public IChannelSourceHandle GetReadChannelSource(OperationContext operationContext, IReadOnlyCollection<ServerDescription> deprioritizedServers) { ThrowIfDisposed(); var server = _cluster.SelectServerAndPinIfNeeded(operationContext, _session, _serverSelector, deprioritizedServers); return GetChannelSourceHelper(server); } public async Task<IChannelSourceHandle> GetReadChannelSourceAsync(OperationContext operationContext, IReadOnlyCollection<ServerDescription> deprioritizedServers) { ThrowIfDisposed(); var server = await _cluster.SelectServerAndPinIfNeededAsync(operationContext, _session, _serverSelector, deprioritizedServers).ConfigureAwait(false); return GetChannelSourceHelper(server); } private IChannelSourceHandle GetChannelSourceHelper(IServer server) { return new ChannelSourceHandle(new ServerChannelSource(server, _session.Fork())); } public void Dispose() { if (!_disposed) { _session.Dispose(); _disposed = true; } } private void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } } } }
ReadPreferenceBinding
csharp
Antaris__RazorEngine
src/source/RazorEngine.Core/Text/HtmlEncodedStringFactory.cs
{ "start": 156, "end": 1329 }
public class ____ : IEncodedStringFactory { #region Methods /// <summary> /// Creates a <see cref="IEncodedString"/> instance for the specified raw string. /// </summary> /// <param name="rawString">The raw string.</param> /// <returns>An instance of <see cref="IEncodedString"/>.</returns> public IEncodedString CreateEncodedString(string rawString) { return new HtmlEncodedString(rawString); } /// <summary> /// Creates a <see cref="IEncodedString"/> instance for the specified object instance. /// </summary> /// <param name="value">The object instance.</param> /// <returns>An instance of <see cref="IEncodedString"/>.</returns> public IEncodedString CreateEncodedString(object value) { if (value == null) return new HtmlEncodedString(string.Empty); var htmlString = value as HtmlEncodedString; if (htmlString != null) return htmlString; return new HtmlEncodedString(value.ToString()); } #endregion } }
HtmlEncodedStringFactory
csharp
MassTransit__MassTransit
tests/MassTransit.Analyzers.Tests/MessageContractAnalyzerWithVariableUnitTest.cs
{ "start": 55517, "end": 57104 }
class ____ { static async Task Main() { var bus = Bus.Factory.CreateUsingInMemory(cfg => { }); var msg = new { Id = NewId.NextGuid(), CustomerId = 1, OrderItems = new[] { new { Id = NewId.NextGuid(), Product = new { Name = ""Product"", Category = 1 }, Quantity = 10, Price = 10.0 } } }; await bus.Publish<OrderSubmitted>(msg); } } } "; var expected = new DiagnosticResult { Id = "MCA0001", Message = "Anonymous type does not map to message contract 'OrderSubmitted'. The following properties of the anonymous type are incompatible: OrderItems.Product.Category, OrderItems.Price.", Severity = DiagnosticSeverity.Error, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 58, 23) } }; VerifyCSharpDiagnostic(test, expected); } [Test] public void WhenTypesAreStructurallyIncompatibleAtNestedArrayTypePropertyAndNoMissingProperties_WithVariable_ShouldHaveDiagnostic() { var test = Usings + MessageContracts + @" namespace ConsoleApplication1 {
Program
csharp
dotnet__efcore
src/EFCore.Relational/Diagnostics/Internal/RelationalCommandDiagnosticsLogger.cs
{ "start": 784, "end": 64770 }
public class ____ : DiagnosticsLogger<DbLoggerCategory.Database.Command>, IRelationalCommandDiagnosticsLogger { private DateTimeOffset _suppressCommandCreateExpiration; private DateTimeOffset _suppressCommandExecuteExpiration; private DateTimeOffset _suppressDataReaderClosingExpiration; private DateTimeOffset _suppressDataReaderDisposingExpiration; private readonly TimeSpan _loggingCacheTime; /// <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 RelationalCommandDiagnosticsLogger( ILoggerFactory loggerFactory, ILoggingOptions loggingOptions, DiagnosticSource diagnosticSource, LoggingDefinitions loggingDefinitions, IDbContextLogger contextLogger, IDbContextOptions contextOptions, IInterceptors? interceptors = null) : base(loggerFactory, loggingOptions, diagnosticSource, loggingDefinitions, contextLogger, interceptors) { var coreOptionsExtension = contextOptions.FindExtension<CoreOptionsExtension>() ?? new CoreOptionsExtension(); _loggingCacheTime = coreOptionsExtension.LoggingCacheTime; } #region CommandCreating /// <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 virtual InterceptionResult<DbCommand> CommandCreating( IRelationalConnection connection, DbCommandMethod commandMethod, DbContext? context, Guid commandId, Guid connectionId, DateTimeOffset startTime, CommandSource commandSource) { _suppressCommandCreateExpiration = startTime + _loggingCacheTime; var definition = RelationalResources.LogCommandCreating(this); if (ShouldLog(definition)) { _suppressCommandCreateExpiration = default; definition.Log(this, commandMethod.ToString()); } if (NeedsEventData<IDbCommandInterceptor>( definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled)) { _suppressCommandCreateExpiration = default; var eventData = BroadcastCommandCreating( connection.DbConnection, context, commandMethod, commandId, connectionId, async: false, startTime, definition, diagnosticSourceEnabled, simpleLogEnabled, commandSource); if (interceptor != null) { return interceptor.CommandCreating(eventData, default); } } return default; } private CommandCorrelatedEventData BroadcastCommandCreating( DbConnection connection, DbContext? context, DbCommandMethod executeMethod, Guid commandId, Guid connectionId, bool async, DateTimeOffset startTime, EventDefinition<string> definition, bool diagnosticSourceEnabled, bool simpleLogEnabled, CommandSource commandSource) { var eventData = new CommandCorrelatedEventData( definition, CommandCreating, connection, context, executeMethod, commandId, connectionId, async, startTime, commandSource); DispatchEventData(definition, eventData, diagnosticSourceEnabled, simpleLogEnabled); return eventData; static string CommandCreating(EventDefinitionBase definition, EventData payload) { var d = (EventDefinition<string>)definition; var p = (CommandCorrelatedEventData)payload; return d.GenerateMessage(p.ExecuteMethod.ToString()); } } #endregion CommandCreating #region CommandCreated /// <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 virtual DbCommand CommandCreated( IRelationalConnection connection, DbCommand command, DbCommandMethod commandMethod, DbContext? context, Guid commandId, Guid connectionId, DateTimeOffset startTime, TimeSpan duration, CommandSource commandSource) { var definition = RelationalResources.LogCommandCreated(this); if (ShouldLog(definition)) { _suppressCommandCreateExpiration = default; definition.Log(this, commandMethod.ToString(), (int)duration.TotalMilliseconds); } if (NeedsEventData<IDbCommandInterceptor>( definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled)) { _suppressCommandCreateExpiration = default; var eventData = BroadcastCommandCreated( connection.DbConnection, command, context, commandMethod, commandId, connectionId, async: false, startTime, duration, definition, diagnosticSourceEnabled, simpleLogEnabled, commandSource); if (interceptor != null) { return interceptor.CommandCreated(eventData, command); } } return command; } private CommandEndEventData BroadcastCommandCreated( DbConnection connection, DbCommand command, DbContext? context, DbCommandMethod executeMethod, Guid commandId, Guid connectionId, bool async, DateTimeOffset startTime, TimeSpan duration, EventDefinition<string, int> definition, bool diagnosticSourceEnabled, bool simpleLogEnabled, CommandSource commandSource) { var eventData = new CommandEndEventData( definition, CommandCreated, connection, command, command.CommandText, context, executeMethod, commandId, connectionId, async, false, startTime, duration, commandSource); DispatchEventData(definition, eventData, diagnosticSourceEnabled, simpleLogEnabled); return eventData; static string CommandCreated(EventDefinitionBase definition, EventData payload) { var d = (EventDefinition<string, int>)definition; var p = (CommandEndEventData)payload; return d.GenerateMessage(p.ExecuteMethod.ToString(), (int)p.Duration.TotalMilliseconds); } } #endregion CommandCreated #region CommandInitialized /// <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 virtual DbCommand CommandInitialized( IRelationalConnection connection, DbCommand command, DbCommandMethod commandMethod, DbContext? context, Guid commandId, Guid connectionId, DateTimeOffset startTime, TimeSpan duration, CommandSource commandSource) { var definition = RelationalResources.LogCommandInitialized(this); if (ShouldLog(definition)) { _suppressCommandCreateExpiration = default; definition.Log(this, commandMethod.ToString(), (int)duration.TotalMilliseconds); } if (NeedsEventData<IDbCommandInterceptor>( definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled)) { _suppressCommandCreateExpiration = default; var eventData = BroadcastCommandInitialized( connection.DbConnection, command, context, commandMethod, commandId, connectionId, async: false, startTime, duration, definition, diagnosticSourceEnabled, simpleLogEnabled, commandSource); if (interceptor != null) { return interceptor.CommandInitialized(eventData, command); } } return command; } private CommandEndEventData BroadcastCommandInitialized( DbConnection connection, DbCommand command, DbContext? context, DbCommandMethod executeMethod, Guid commandId, Guid connectionId, bool async, DateTimeOffset startTime, TimeSpan duration, EventDefinition<string, int> definition, bool diagnosticSourceEnabled, bool simpleLogEnabled, CommandSource commandSource) { var eventData = new CommandEndEventData( definition, CommandInitialized, connection, command, command.CommandText, context, executeMethod, commandId, connectionId, async, false, startTime, duration, commandSource); DispatchEventData(definition, eventData, diagnosticSourceEnabled, simpleLogEnabled); return eventData; static string CommandInitialized(EventDefinitionBase definition, EventData payload) { var d = (EventDefinition<string, int>)definition; var p = (CommandEndEventData)payload; return d.GenerateMessage(p.ExecuteMethod.ToString(), (int)p.Duration.TotalMilliseconds); } } #endregion CommandInitialized #region CommandExecuting /// <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 virtual InterceptionResult<DbDataReader> CommandReaderExecuting( IRelationalConnection connection, DbCommand command, string logCommandText, DbContext? context, Guid commandId, Guid connectionId, DateTimeOffset startTime, CommandSource commandSource) { _suppressCommandExecuteExpiration = startTime + _loggingCacheTime; var definition = RelationalResources.LogExecutingCommand(this); if (ShouldLog(definition)) { _suppressCommandExecuteExpiration = default; definition.Log( this, command.Parameters.FormatParameters(ShouldLogSensitiveData()), command.CommandType, command.CommandTimeout, Environment.NewLine, logCommandText.TrimEnd()); } if (NeedsEventData<IDbCommandInterceptor>( definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled)) { _suppressCommandExecuteExpiration = default; var eventData = BroadcastCommandExecuting( connection.DbConnection, command, logCommandText, context, DbCommandMethod.ExecuteReader, commandId, connectionId, false, startTime, definition, diagnosticSourceEnabled, simpleLogEnabled, commandSource); if (interceptor != null) { return interceptor.ReaderExecuting(command, eventData, default); } } return default; } /// <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 virtual InterceptionResult<object> CommandScalarExecuting( IRelationalConnection connection, DbCommand command, string logCommandText, DbContext? context, Guid commandId, Guid connectionId, DateTimeOffset startTime, CommandSource commandSource) { _suppressCommandExecuteExpiration = startTime + _loggingCacheTime; var definition = RelationalResources.LogExecutingCommand(this); if (ShouldLog(definition)) { _suppressCommandExecuteExpiration = default; definition.Log( this, command.Parameters.FormatParameters(ShouldLogSensitiveData()), command.CommandType, command.CommandTimeout, Environment.NewLine, logCommandText.TrimEnd()); } if (NeedsEventData<IDbCommandInterceptor>( definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled)) { _suppressCommandExecuteExpiration = default; var eventData = BroadcastCommandExecuting( connection.DbConnection, command, logCommandText, context, DbCommandMethod.ExecuteScalar, commandId, connectionId, false, startTime, definition, diagnosticSourceEnabled, simpleLogEnabled, commandSource); if (interceptor != null) { return interceptor.ScalarExecuting(command, eventData, default); } } return default; } /// <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 virtual InterceptionResult<int> CommandNonQueryExecuting( IRelationalConnection connection, DbCommand command, string logCommandText, DbContext? context, Guid commandId, Guid connectionId, DateTimeOffset startTime, CommandSource commandSource) { _suppressCommandExecuteExpiration = startTime + _loggingCacheTime; var definition = RelationalResources.LogExecutingCommand(this); if (ShouldLog(definition)) { _suppressCommandExecuteExpiration = default; definition.Log( this, command.Parameters.FormatParameters(ShouldLogSensitiveData()), command.CommandType, command.CommandTimeout, Environment.NewLine, logCommandText.TrimEnd()); } if (NeedsEventData<IDbCommandInterceptor>( definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled)) { _suppressCommandExecuteExpiration = default; var eventData = BroadcastCommandExecuting( connection.DbConnection, command, logCommandText, context, DbCommandMethod.ExecuteNonQuery, commandId, connectionId, false, startTime, definition, diagnosticSourceEnabled, simpleLogEnabled, commandSource); if (interceptor != null) { return interceptor.NonQueryExecuting(command, eventData, default); } } return default; } /// <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 virtual ValueTask<InterceptionResult<DbDataReader>> CommandReaderExecutingAsync( IRelationalConnection connection, DbCommand command, string logCommandText, DbContext? context, Guid commandId, Guid connectionId, DateTimeOffset startTime, CommandSource commandSource, CancellationToken cancellationToken = default) { _suppressCommandExecuteExpiration = startTime + _loggingCacheTime; var definition = RelationalResources.LogExecutingCommand(this); if (ShouldLog(definition)) { _suppressCommandExecuteExpiration = default; definition.Log( this, command.Parameters.FormatParameters(ShouldLogSensitiveData()), command.CommandType, command.CommandTimeout, Environment.NewLine, logCommandText.TrimEnd()); } if (NeedsEventData<IDbCommandInterceptor>( definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled)) { _suppressCommandExecuteExpiration = default; var eventData = BroadcastCommandExecuting( connection.DbConnection, command, logCommandText, context, DbCommandMethod.ExecuteReader, commandId, connectionId, async: true, startTime, definition, diagnosticSourceEnabled, simpleLogEnabled, commandSource); if (interceptor != null) { return interceptor.ReaderExecutingAsync(command, eventData, default, cancellationToken); } } return default; } /// <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 virtual ValueTask<InterceptionResult<object>> CommandScalarExecutingAsync( IRelationalConnection connection, DbCommand command, string logCommandText, DbContext? context, Guid commandId, Guid connectionId, DateTimeOffset startTime, CommandSource commandSource, CancellationToken cancellationToken = default) { _suppressCommandExecuteExpiration = startTime + _loggingCacheTime; var definition = RelationalResources.LogExecutingCommand(this); if (ShouldLog(definition)) { _suppressCommandExecuteExpiration = default; definition.Log( this, command.Parameters.FormatParameters(ShouldLogSensitiveData()), command.CommandType, command.CommandTimeout, Environment.NewLine, logCommandText.TrimEnd()); } if (NeedsEventData<IDbCommandInterceptor>( definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled)) { _suppressCommandExecuteExpiration = default; var eventData = BroadcastCommandExecuting( connection.DbConnection, command, logCommandText, context, DbCommandMethod.ExecuteScalar, commandId, connectionId, async: true, startTime, definition, diagnosticSourceEnabled, simpleLogEnabled, commandSource); if (interceptor != null) { return interceptor.ScalarExecutingAsync(command, eventData, default, cancellationToken); } } return default; } /// <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 virtual ValueTask<InterceptionResult<int>> CommandNonQueryExecutingAsync( IRelationalConnection connection, DbCommand command, string logCommandText, DbContext? context, Guid commandId, Guid connectionId, DateTimeOffset startTime, CommandSource commandSource, CancellationToken cancellationToken = default) { _suppressCommandExecuteExpiration = startTime + _loggingCacheTime; var definition = RelationalResources.LogExecutingCommand(this); if (ShouldLog(definition)) { _suppressCommandExecuteExpiration = default; definition.Log( this, command.Parameters.FormatParameters(ShouldLogSensitiveData()), command.CommandType, command.CommandTimeout, Environment.NewLine, logCommandText.TrimEnd()); } if (NeedsEventData<IDbCommandInterceptor>( definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled)) { _suppressCommandExecuteExpiration = default; var eventData = BroadcastCommandExecuting( connection.DbConnection, command, logCommandText, context, DbCommandMethod.ExecuteNonQuery, commandId, connectionId, async: true, startTime, definition, diagnosticSourceEnabled, simpleLogEnabled, commandSource); if (interceptor != null) { return interceptor.NonQueryExecutingAsync(command, eventData, default, cancellationToken); } } return default; } private CommandEventData BroadcastCommandExecuting( DbConnection connection, DbCommand command, string logCommandText, DbContext? context, DbCommandMethod executeMethod, Guid commandId, Guid connectionId, bool async, DateTimeOffset startTime, EventDefinition<string, CommandType, int, string, string> definition, bool diagnosticSourceEnabled, bool simpleLogEnabled, CommandSource commandSource) { var eventData = new CommandEventData( definition, CommandExecuting, connection, command, logCommandText, context, executeMethod, commandId, connectionId, async, ShouldLogSensitiveData(), startTime, commandSource); DispatchEventData(definition, eventData, diagnosticSourceEnabled, simpleLogEnabled); return eventData; static string CommandExecuting(EventDefinitionBase definition, EventData payload) { var d = (EventDefinition<string, CommandType, int, string, string>)definition; var p = (CommandEventData)payload; return d.GenerateMessage( p.Command.Parameters.FormatParameters(p.LogParameterValues), p.Command.CommandType, p.Command.CommandTimeout, Environment.NewLine, p.LogCommandText.TrimEnd()); } } #endregion CommandExecuting #region CommandExecuted /// <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 virtual DbDataReader CommandReaderExecuted( IRelationalConnection connection, DbCommand command, string logCommandText, DbContext? context, Guid commandId, Guid connectionId, DbDataReader methodResult, DateTimeOffset startTime, TimeSpan duration, CommandSource commandSource) { var definition = RelationalResources.LogExecutedCommand(this); if (ShouldLog(definition)) { _suppressCommandExecuteExpiration = default; definition.Log( this, string.Format(CultureInfo.InvariantCulture, "{0:N0}", duration.TotalMilliseconds), command.Parameters.FormatParameters(ShouldLogSensitiveData()), command.CommandType, command.CommandTimeout, Environment.NewLine, logCommandText.TrimEnd()); } if (NeedsEventData<IDbCommandInterceptor>( definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled)) { _suppressCommandExecuteExpiration = default; var eventData = BroadcastCommandExecuted( connection.DbConnection, command, logCommandText, context, DbCommandMethod.ExecuteReader, commandId, connectionId, methodResult, async: false, startTime, duration, definition, diagnosticSourceEnabled, simpleLogEnabled, commandSource); if (interceptor != null) { return interceptor.ReaderExecuted(command, eventData, methodResult); } } return methodResult; } /// <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 virtual object? CommandScalarExecuted( IRelationalConnection connection, DbCommand command, string logCommandText, DbContext? context, Guid commandId, Guid connectionId, object? methodResult, DateTimeOffset startTime, TimeSpan duration, CommandSource commandSource) { var definition = RelationalResources.LogExecutedCommand(this); if (ShouldLog(definition)) { _suppressCommandExecuteExpiration = default; definition.Log( this, string.Format(CultureInfo.InvariantCulture, "{0:N0}", duration.TotalMilliseconds), command.Parameters.FormatParameters(ShouldLogSensitiveData()), command.CommandType, command.CommandTimeout, Environment.NewLine, logCommandText.TrimEnd()); } if (NeedsEventData<IDbCommandInterceptor>( definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled)) { _suppressCommandExecuteExpiration = default; var eventData = BroadcastCommandExecuted( connection.DbConnection, command, logCommandText, context, DbCommandMethod.ExecuteScalar, commandId, connectionId, methodResult, async: false, startTime, duration, definition, diagnosticSourceEnabled, simpleLogEnabled, commandSource); if (interceptor != null) { return interceptor.ScalarExecuted(command, eventData, methodResult); } } return methodResult; } /// <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 virtual int CommandNonQueryExecuted( IRelationalConnection connection, DbCommand command, string logCommandText, DbContext? context, Guid commandId, Guid connectionId, int methodResult, DateTimeOffset startTime, TimeSpan duration, CommandSource commandSource) { var definition = RelationalResources.LogExecutedCommand(this); if (ShouldLog(definition)) { _suppressCommandExecuteExpiration = default; definition.Log( this, string.Format(CultureInfo.InvariantCulture, "{0:N0}", duration.TotalMilliseconds), command.Parameters.FormatParameters(ShouldLogSensitiveData()), command.CommandType, command.CommandTimeout, Environment.NewLine, logCommandText.TrimEnd()); } if (NeedsEventData<IDbCommandInterceptor>( definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled)) { _suppressCommandExecuteExpiration = default; var eventData = BroadcastCommandExecuted( connection.DbConnection, command, logCommandText, context, DbCommandMethod.ExecuteNonQuery, commandId, connectionId, methodResult, async: false, startTime, duration, definition, diagnosticSourceEnabled, simpleLogEnabled, commandSource); if (interceptor != null) { return interceptor.NonQueryExecuted(command, eventData, methodResult); } } return methodResult; } /// <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 virtual ValueTask<DbDataReader> CommandReaderExecutedAsync( IRelationalConnection connection, DbCommand command, string logCommandText, DbContext? context, Guid commandId, Guid connectionId, DbDataReader methodResult, DateTimeOffset startTime, TimeSpan duration, CommandSource commandSource, CancellationToken cancellationToken = default) { var definition = RelationalResources.LogExecutedCommand(this); if (ShouldLog(definition)) { _suppressCommandExecuteExpiration = default; definition.Log( this, string.Format(CultureInfo.InvariantCulture, "{0:N0}", duration.TotalMilliseconds), command.Parameters.FormatParameters(ShouldLogSensitiveData()), command.CommandType, command.CommandTimeout, Environment.NewLine, logCommandText.TrimEnd()); } if (NeedsEventData<IDbCommandInterceptor>( definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled)) { _suppressCommandExecuteExpiration = default; var eventData = BroadcastCommandExecuted( connection.DbConnection, command, logCommandText, context, DbCommandMethod.ExecuteReader, commandId, connectionId, methodResult, async: true, startTime, duration, definition, diagnosticSourceEnabled, simpleLogEnabled, commandSource); if (interceptor != null) { return interceptor.ReaderExecutedAsync(command, eventData, methodResult, cancellationToken); } } return ValueTask.FromResult(methodResult); } /// <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 virtual ValueTask<object?> CommandScalarExecutedAsync( IRelationalConnection connection, DbCommand command, string logCommandText, DbContext? context, Guid commandId, Guid connectionId, object? methodResult, DateTimeOffset startTime, TimeSpan duration, CommandSource commandSource, CancellationToken cancellationToken = default) { var definition = RelationalResources.LogExecutedCommand(this); if (ShouldLog(definition)) { _suppressCommandExecuteExpiration = default; definition.Log( this, string.Format(CultureInfo.InvariantCulture, "{0:N0}", duration.TotalMilliseconds), command.Parameters.FormatParameters(ShouldLogSensitiveData()), command.CommandType, command.CommandTimeout, Environment.NewLine, logCommandText.TrimEnd()); } if (NeedsEventData<IDbCommandInterceptor>( definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled)) { _suppressCommandExecuteExpiration = default; var eventData = BroadcastCommandExecuted( connection.DbConnection, command, logCommandText, context, DbCommandMethod.ExecuteScalar, commandId, connectionId, methodResult, async: true, startTime, duration, definition, diagnosticSourceEnabled, simpleLogEnabled, commandSource); if (interceptor != null) { return interceptor.ScalarExecutedAsync(command, eventData, methodResult, cancellationToken); } } return ValueTask.FromResult(methodResult); } /// <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 virtual ValueTask<int> CommandNonQueryExecutedAsync( IRelationalConnection connection, DbCommand command, string logCommandText, DbContext? context, Guid commandId, Guid connectionId, int methodResult, DateTimeOffset startTime, TimeSpan duration, CommandSource commandSource, CancellationToken cancellationToken = default) { var definition = RelationalResources.LogExecutedCommand(this); if (ShouldLog(definition)) { _suppressCommandExecuteExpiration = default; definition.Log( this, string.Format(CultureInfo.InvariantCulture, "{0:N0}", duration.TotalMilliseconds), command.Parameters.FormatParameters(ShouldLogSensitiveData()), command.CommandType, command.CommandTimeout, Environment.NewLine, logCommandText.TrimEnd()); } if (NeedsEventData<IDbCommandInterceptor>( definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled)) { _suppressCommandExecuteExpiration = default; var eventData = BroadcastCommandExecuted( connection.DbConnection, command, logCommandText, context, DbCommandMethod.ExecuteNonQuery, commandId, connectionId, methodResult, async: true, startTime, duration, definition, diagnosticSourceEnabled, simpleLogEnabled, commandSource); if (interceptor != null) { return interceptor.NonQueryExecutedAsync(command, eventData, methodResult, cancellationToken); } } return ValueTask.FromResult(methodResult); } private CommandExecutedEventData BroadcastCommandExecuted( DbConnection connection, DbCommand command, string logCommandText, DbContext? context, DbCommandMethod executeMethod, Guid commandId, Guid connectionId, object? methodResult, bool async, DateTimeOffset startTime, TimeSpan duration, EventDefinition<string, string, CommandType, int, string, string> definition, bool diagnosticSourceEnabled, bool simpleLogEnabled, CommandSource commandSource) { var eventData = new CommandExecutedEventData( definition, CommandExecuted, connection, command, logCommandText, context, executeMethod, commandId, connectionId, methodResult, async, ShouldLogSensitiveData(), startTime, duration, commandSource); DispatchEventData(definition, eventData, diagnosticSourceEnabled, simpleLogEnabled); return eventData; static string CommandExecuted(EventDefinitionBase definition, EventData payload) { var d = (EventDefinition<string, string, CommandType, int, string, string>)definition; var p = (CommandExecutedEventData)payload; return d.GenerateMessage( string.Format(CultureInfo.InvariantCulture, "{0:N0}", p.Duration.TotalMilliseconds), p.Command.Parameters.FormatParameters(p.LogParameterValues), p.Command.CommandType, p.Command.CommandTimeout, Environment.NewLine, p.LogCommandText.TrimEnd()); } } #endregion CommandExecuted #region CommandError /// <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 virtual void CommandError( IRelationalConnection connection, DbCommand command, string logCommandText, DbContext? context, DbCommandMethod executeMethod, Guid commandId, Guid connectionId, Exception exception, DateTimeOffset startTime, TimeSpan duration, CommandSource commandSource) { var definition = RelationalResources.LogCommandFailed(this); LogCommandError(command, logCommandText, duration, definition); if (NeedsEventData<IDbCommandInterceptor>( definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled)) { var eventData = BroadcastCommandError( connection.DbConnection, command, logCommandText, context, executeMethod, commandId, connectionId, exception, false, startTime, duration, definition, diagnosticSourceEnabled, simpleLogEnabled, commandSource); interceptor?.CommandFailed(command, eventData); } } private void LogCommandError( DbCommand command, string logCommandText, TimeSpan duration, EventDefinition<string, string, CommandType, int, string, string> definition) { if (ShouldLog(definition)) { definition.Log( this, string.Format(CultureInfo.InvariantCulture, "{0:N0}", duration.TotalMilliseconds), command.Parameters.FormatParameters(ShouldLogSensitiveData()), command.CommandType, command.CommandTimeout, Environment.NewLine, logCommandText.TrimEnd()); } } /// <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 virtual Task CommandErrorAsync( IRelationalConnection connection, DbCommand command, string logCommandText, DbContext? context, DbCommandMethod executeMethod, Guid commandId, Guid connectionId, Exception exception, DateTimeOffset startTime, TimeSpan duration, CommandSource commandSource, CancellationToken cancellationToken = default) { var definition = RelationalResources.LogCommandFailed(this); LogCommandError(command, logCommandText, duration, definition); if (NeedsEventData<IDbCommandInterceptor>( definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled)) { var eventData = BroadcastCommandError( connection.DbConnection, command, logCommandText, context, executeMethod, commandId, connectionId, exception, true, startTime, duration, definition, diagnosticSourceEnabled, simpleLogEnabled, commandSource); if (interceptor != null) { return interceptor.CommandFailedAsync(command, eventData, cancellationToken); } } return Task.CompletedTask; } private CommandErrorEventData BroadcastCommandError( DbConnection connection, DbCommand command, string logCommandText, DbContext? context, DbCommandMethod executeMethod, Guid commandId, Guid connectionId, Exception exception, bool async, DateTimeOffset startTime, TimeSpan duration, EventDefinition<string, string, CommandType, int, string, string> definition, bool diagnosticSourceEnabled, bool simpleLogEnabled, CommandSource commandSource) { var eventData = new CommandErrorEventData( definition, CommandError, connection, command, logCommandText, context, executeMethod, commandId, connectionId, exception, async, ShouldLogSensitiveData(), startTime, duration, commandSource); DispatchEventData(definition, eventData, diagnosticSourceEnabled, simpleLogEnabled); return eventData; static string CommandError(EventDefinitionBase definition, EventData payload) { var d = (EventDefinition<string, string, CommandType, int, string, string>)definition; var p = (CommandErrorEventData)payload; return d.GenerateMessage( string.Format(CultureInfo.InvariantCulture, "{0:N0}", p.Duration.TotalMilliseconds), p.Command.Parameters.FormatParameters(p.LogParameterValues), p.Command.CommandType, p.Command.CommandTimeout, Environment.NewLine, p.LogCommandText.TrimEnd()); } } #endregion CommandError #region CommandCanceled /// <inheritdoc /> public virtual void CommandCanceled( IRelationalConnection connection, DbCommand command, string logCommandText, DbContext? context, DbCommandMethod executeMethod, Guid commandId, Guid connectionId, DateTimeOffset startTime, TimeSpan duration, CommandSource commandSource) { var definition = RelationalResources.LogCommandCanceled(this); LogCommandCanceled(command, logCommandText, duration, definition); if (NeedsEventData<IDbCommandInterceptor>( definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled)) { var eventData = BroadcastCommandCanceled( connection.DbConnection, command, logCommandText, context, executeMethod, commandId, connectionId, false, startTime, duration, definition, diagnosticSourceEnabled, simpleLogEnabled, commandSource); interceptor?.CommandCanceled(command, eventData); } } /// <inheritdoc /> public virtual Task CommandCanceledAsync( IRelationalConnection connection, DbCommand command, string logCommandText, DbContext? context, DbCommandMethod executeMethod, Guid commandId, Guid connectionId, DateTimeOffset startTime, TimeSpan duration, CommandSource commandSource, CancellationToken cancellationToken = default) { var definition = RelationalResources.LogCommandCanceled(this); LogCommandCanceled(command, logCommandText, duration, definition); if (NeedsEventData<IDbCommandInterceptor>( definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled)) { var eventData = BroadcastCommandCanceled( connection.DbConnection, command, logCommandText, context, executeMethod, commandId, connectionId, true, startTime, duration, definition, diagnosticSourceEnabled, simpleLogEnabled, commandSource); if (interceptor != null) { return interceptor.CommandCanceledAsync(command, eventData, cancellationToken); } } return Task.CompletedTask; } private void LogCommandCanceled( DbCommand command, string logCommandText, TimeSpan duration, EventDefinition<string, string, CommandType, int, string, string> definition) { if (ShouldLog(definition)) { definition.Log( this, string.Format(CultureInfo.InvariantCulture, "{0:N0}", duration.TotalMilliseconds), command.Parameters.FormatParameters(ShouldLogSensitiveData()), command.CommandType, command.CommandTimeout, Environment.NewLine, logCommandText.TrimEnd()); } } private CommandEndEventData BroadcastCommandCanceled( DbConnection connection, DbCommand command, string logCommandText, DbContext? context, DbCommandMethod executeMethod, Guid commandId, Guid connectionId, bool async, DateTimeOffset startTime, TimeSpan duration, EventDefinition<string, string, CommandType, int, string, string> definition, bool diagnosticSourceEnabled, bool simpleLogEnabled, CommandSource commandSource) { var eventData = new CommandEndEventData( definition, CommandCanceled, connection, command, logCommandText, context, executeMethod, commandId, connectionId, async, ShouldLogSensitiveData(), startTime, duration, commandSource); DispatchEventData(definition, eventData, diagnosticSourceEnabled, simpleLogEnabled); return eventData; static string CommandCanceled(EventDefinitionBase definition, EventData payload) { var d = (EventDefinition<string, string, CommandType, int, string, string>)definition; var p = (CommandEndEventData)payload; return d.GenerateMessage( string.Format(CultureInfo.InvariantCulture, "{0:N0}", p.Duration.TotalMilliseconds), p.Command.Parameters.FormatParameters(p.LogParameterValues), p.Command.CommandType, p.Command.CommandTimeout, Environment.NewLine, p.LogCommandText.TrimEnd()); } } #endregion CommandCanceled #region DataReader /// <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 virtual InterceptionResult DataReaderClosing( IRelationalConnection connection, DbCommand command, DbDataReader dataReader, Guid commandId, int recordsAffected, int readCount, DateTimeOffset startTime) { _suppressDataReaderClosingExpiration = startTime + _loggingCacheTime; var definition = RelationalResources.LogClosingDataReader(this); if (ShouldLog(definition)) { _suppressDataReaderClosingExpiration = default; definition.Log(this, connection.DbConnection.Database, connection.DbConnection.DataSource); } if (NeedsEventData<IDbCommandInterceptor>( definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled)) { _suppressDataReaderClosingExpiration = default; var eventData = new DataReaderClosingEventData( definition, CreateDataReaderClosingString, command, dataReader, connection.Context, commandId, connection.ConnectionId, async: false, recordsAffected, readCount, startTime); DispatchEventData(definition, eventData, diagnosticSourceEnabled, simpleLogEnabled); if (interceptor != null) { return interceptor.DataReaderClosing(command, eventData, default); } } return default; } /// <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 virtual ValueTask<InterceptionResult> DataReaderClosingAsync( IRelationalConnection connection, DbCommand command, DbDataReader dataReader, Guid commandId, int recordsAffected, int readCount, DateTimeOffset startTime) { _suppressDataReaderClosingExpiration = startTime + _loggingCacheTime; var definition = RelationalResources.LogClosingDataReader(this); if (ShouldLog(definition)) { _suppressDataReaderClosingExpiration = default; definition.Log(this, connection.DbConnection.Database, connection.DbConnection.DataSource); } if (NeedsEventData<IDbCommandInterceptor>( definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled)) { _suppressDataReaderClosingExpiration = default; var eventData = new DataReaderClosingEventData( definition, CreateDataReaderClosingString, command, dataReader, connection.Context, commandId, connection.ConnectionId, async: true, recordsAffected, readCount, startTime); DispatchEventData(definition, eventData, diagnosticSourceEnabled, simpleLogEnabled); if (interceptor != null) { return interceptor.DataReaderClosingAsync(command, eventData, default); } } return default; } private static string CreateDataReaderClosingString(EventDefinitionBase definition, EventData payload) { var d = (EventDefinition<string, string>)definition; var p = (DataReaderClosingEventData)payload; return d.GenerateMessage( p.Command.Connection?.Database ?? "<Unknown>", p.Command.Connection?.DataSource ?? "<Unknown>"); } /// <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 virtual InterceptionResult DataReaderDisposing( IRelationalConnection connection, DbCommand command, DbDataReader dataReader, Guid commandId, int recordsAffected, int readCount, DateTimeOffset startTime, TimeSpan duration) { _suppressDataReaderDisposingExpiration = startTime + _loggingCacheTime; var definition = RelationalResources.LogDisposingDataReader(this); if (ShouldLog(definition)) { _suppressDataReaderDisposingExpiration = default; definition.Log(this, connection.DbConnection.Database, connection.DbConnection.DataSource, (int)duration.TotalMilliseconds); } if (NeedsEventData<IDbCommandInterceptor>( definition, out var interceptor, out var diagnosticSourceEnabled, out var simpleLogEnabled)) { _suppressDataReaderDisposingExpiration = default; var eventData = new DataReaderDisposingEventData( definition, CreateDataReaderDisposingString, command, dataReader, connection.Context, commandId, connection.ConnectionId, recordsAffected, readCount, startTime, duration); DispatchEventData(definition, eventData, diagnosticSourceEnabled, simpleLogEnabled); if (interceptor != null) { return interceptor.DataReaderDisposing(command, eventData, default); } } return default; } private static string CreateDataReaderDisposingString(EventDefinitionBase definition, EventData payload) { var d = (EventDefinition<string, string, int>)definition; var p = (DataReaderDisposingEventData)payload; return d.GenerateMessage( p.Command.Connection?.Database ?? "<Unknown>", p.Command.Connection?.DataSource ?? "<Unknown>", (int)p.Duration.TotalMilliseconds); } #endregion DataReader #region ShouldLog checks /// <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 virtual bool ShouldLogCommandCreate(DateTimeOffset now) => now > _suppressCommandCreateExpiration; /// <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 virtual bool ShouldLogCommandExecute(DateTimeOffset now) => now > _suppressCommandExecuteExpiration; /// <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 virtual bool ShouldLogDataReaderClose(DateTimeOffset now) => now > _suppressDataReaderClosingExpiration; /// <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 virtual bool ShouldLogDataReaderDispose(DateTimeOffset now) => now > _suppressDataReaderDisposingExpiration; #endregion ShouldLog checks }
RelationalCommandDiagnosticsLogger
csharp
dotnet__maui
src/Controls/src/Core/Tweener.cs
{ "start": 1311, "end": 1956 }
internal class ____ : Animation { readonly Func<long, bool> _step; public TweenerAnimation(Func<long, bool> step) { _step = step; } protected override void OnTick(double millisecondsSinceLastUpdate) { var running = _step.Invoke((long)millisecondsSinceLastUpdate); HasFinished = !running; if (HasFinished) Finished?.Invoke(); } internal override void ForceFinish() { if (HasFinished) { return; } HasFinished = true; // The tweeners use long.MaxValue for in-band signaling that they should // jump to the end of the animation _ = _step.Invoke(long.MaxValue); } }
TweenerAnimation
csharp
abpframework__abp
modules/cms-kit/src/Volo.CmsKit.Domain/Volo/CmsKit/Tags/Tag.cs
{ "start": 160, "end": 1164 }
public class ____ : FullAuditedAggregateRoot<Guid>, IMultiTenant { public virtual Guid? TenantId { get; protected set; } [NotNull] public virtual string EntityType { get; protected set; } [NotNull] public virtual string Name { get; protected set; } protected Tag() { } public Tag( Guid id, [NotNull] string entityType, [NotNull] string name, Guid? tenantId = null) : base(id) { EntityType = Check.NotNullOrEmpty(entityType, nameof(entityType), TagConsts.MaxEntityTypeLength); Name = Check.NotNullOrEmpty(name, nameof(name), TagConsts.MaxNameLength); TenantId = tenantId; } public virtual void SetName([NotNull] string name) { Name = Check.NotNullOrEmpty(name, nameof(name), TagConsts.MaxNameLength); } public virtual void SetEntityType(string entityType) { EntityType = Check.NotNullOrEmpty(entityType, nameof(entityType), TagConsts.MaxEntityTypeLength); } }
Tag
csharp
dotnet__aspnetcore
src/Http/Http.Abstractions/src/Routing/RouteValueDictionary.cs
{ "start": 27916, "end": 28235 }
internal static class ____ { /// <summary> /// Invoked as part of <see cref="MetadataUpdateHandlerAttribute" /> contract for hot reload. /// </summary> internal static void ClearCache(Type[]? _) { _propertyCache.Clear(); } } #endif }
MetadataUpdateHandler
csharp
abpframework__abp
framework/src/Volo.Abp.EventBus/Volo/Abp/EventBus/TransientEventHandlerFactory.cs
{ "start": 945, "end": 1899 }
public class ____ : IEventHandlerFactory { public Type HandlerType { get; } public TransientEventHandlerFactory(Type handlerType) { HandlerType = handlerType; } /// <summary> /// Creates a new instance of the handler object. /// </summary> /// <returns>The handler object</returns> public virtual IEventHandlerDisposeWrapper GetHandler() { var handler = CreateHandler(); return new EventHandlerDisposeWrapper( handler, () => (handler as IDisposable)?.Dispose() ); } public bool IsInFactories(List<IEventHandlerFactory> handlerFactories) { return handlerFactories .OfType<TransientEventHandlerFactory>() .Any(f => f.HandlerType == HandlerType); } protected virtual IEventHandler CreateHandler() { return (IEventHandler)Activator.CreateInstance(HandlerType)!; } }
TransientEventHandlerFactory
csharp
FluentValidation__FluentValidation
src/FluentValidation/Validators/PrecisionScaleValidator.cs
{ "start": 817, "end": 1707 }
class ____ contributed to FluentValidation using code posted on StackOverflow by Jon Skeet // The original code can be found at https://stackoverflow.com/a/764102 /// <summary> /// Allows a decimal to be validated for scale and precision. /// Scale would be the number of digits to the right of the decimal point. /// Precision would be the number of digits. This number includes both the left and the right sides of the decimal point. /// /// It implies certain range of values that will be accepted by the validator. /// It permits up to Precision - Scale digits to the left of the decimal point and up to Scale digits to the right. /// /// It can be configured to use the effective scale and precision /// (i.e. ignore trailing zeros) if required. /// /// 123.4500 has an scale of 4 and a precision of 7, but an effective scale /// and precision of 2 and 5 respectively. /// </summary>
was
csharp
dotnet__reactive
Ix.NET/Source/System.Interactive.Tests/System/Linq/Operators/Max.cs
{ "start": 309, "end": 775 }
public class ____ : Tests { #if !NET6_0_OR_GREATER [Fact] public void Max_Arguments() { AssertThrows<ArgumentNullException>(() => EnumerableEx.Max(null, Comparer<int>.Default)); AssertThrows<ArgumentNullException>(() => EnumerableEx.Max(new[] { 1 }, null)); } [Fact] public void Max1() { Assert.Equal(5, new[] { 2, 5, 3, 7 }.Max(new Mod7Comparer())); }
Max
csharp
microsoft__PowerToys
src/modules/MouseWithoutBorders/App/Form/frmInputCallback.cs
{ "start": 906, "end": 3237 }
internal partial class ____ : System.Windows.Forms.Form { internal FrmInputCallback() { InitializeComponent(); } private void FrmInputCallback_Load(object sender, EventArgs e) { InstallKeyboardAndMouseHook(); Left = 0; Top = 0; Width = 0; Height = 0; } private void FrmInputCallback_Shown(object sender, EventArgs e) { Common.InputCallbackForm = this; Visible = false; } private void FrmInputCallback_FormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason != CloseReason.WindowsShutDown) { // e.Cancel = true; } } internal void InstallKeyboardAndMouseHook() { /* * Install hooks: * According to http://msdn.microsoft.com/en-us/library/ms644986(VS.85).aspx * we need to process the hook callback message fast enough so make the message loop thread a * high priority thread. (Mouse/Keyboard event is important) * */ try { Common.Hook = new InputHook(); Common.Hook.MouseEvent += new InputHook.MouseEvHandler(Event.MouseEvent); Common.Hook.KeyboardEvent += new InputHook.KeybdEvHandler(Event.KeybdEvent); Logger.Log("(((((Keyboard/Mouse hooks installed/reinstalled!)))))"); /* The hook is called in the context of the thread that installed it. * The call is made by sending a message to the thread that installed the hook. * Therefore, the thread that installed the hook must have a message loop!!! * */ } catch (Win32Exception e) { _ = MessageBox.Show( "Error installing Mouse/keyboard hook, error code: " + e.ErrorCode, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error); Common.MainForm.Quit(false, false); // we are [STAThread] :) } // Thread.CurrentThread.Priority = ThreadPriority.Highest; } } }
FrmInputCallback
csharp
Cysharp__UniTask
src/UniTask/Assets/Plugins/UniTask/Runtime/Linq/Where.cs
{ "start": 15591, "end": 16225 }
internal sealed class ____<TSource> : IUniTaskAsyncEnumerable<TSource> { readonly IUniTaskAsyncEnumerable<TSource> source; readonly Func<TSource, int, UniTask<bool>> predicate; public WhereIntAwait(IUniTaskAsyncEnumerable<TSource> source, Func<TSource, int, UniTask<bool>> predicate) { this.source = source; this.predicate = predicate; } public IUniTaskAsyncEnumerator<TSource> GetAsyncEnumerator(CancellationToken cancellationToken = default) { return new _WhereAwait(source, predicate, cancellationToken); }
WhereIntAwait
csharp
cake-build__cake
src/Cake.Common/Tools/GitReleaseManager/Publish/GitReleaseManagerPublisher.cs
{ "start": 453, "end": 5524 }
public sealed class ____ : GitReleaseManagerTool<GitReleaseManagerPublishSettings> { /// <summary> /// Initializes a new instance of the <see cref="GitReleaseManagerPublisher"/> class. /// </summary> /// <param name="fileSystem">The file system.</param> /// <param name="environment">The environment.</param> /// <param name="processRunner">The process runner.</param> /// <param name="tools">The tool locator.</param> public GitReleaseManagerPublisher( IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IToolLocator tools) : base(fileSystem, environment, processRunner, tools) { } /// <summary> /// Creates a Release using the specified and settings. /// </summary> /// <param name="userName">The user name.</param> /// <param name="password">The password.</param> /// <param name="owner">The owner.</param> /// <param name="repository">The repository.</param> /// <param name="tagName">The tag name.</param> /// <param name="settings">The settings.</param> public void Publish(string userName, string password, string owner, string repository, string tagName, GitReleaseManagerPublishSettings settings) { if (string.IsNullOrWhiteSpace(userName)) { throw new ArgumentNullException(nameof(userName)); } if (string.IsNullOrWhiteSpace(password)) { throw new ArgumentNullException(nameof(password)); } if (string.IsNullOrWhiteSpace(owner)) { throw new ArgumentNullException(nameof(owner)); } if (string.IsNullOrWhiteSpace(repository)) { throw new ArgumentNullException(nameof(repository)); } if (string.IsNullOrWhiteSpace(tagName)) { throw new ArgumentNullException(nameof(tagName)); } ArgumentNullException.ThrowIfNull(settings); Run(settings, GetArguments(userName, password, owner, repository, tagName, settings)); } /// <summary> /// Creates a Release using the specified and settings. /// </summary> /// <param name="token">The token.</param> /// <param name="owner">The owner.</param> /// <param name="repository">The repository.</param> /// <param name="tagName">The tag name.</param> /// <param name="settings">The settings.</param> public void Publish(string token, string owner, string repository, string tagName, GitReleaseManagerPublishSettings settings) { if (string.IsNullOrWhiteSpace(token)) { throw new ArgumentNullException(nameof(token)); } if (string.IsNullOrWhiteSpace(owner)) { throw new ArgumentNullException(nameof(owner)); } if (string.IsNullOrWhiteSpace(repository)) { throw new ArgumentNullException(nameof(repository)); } if (string.IsNullOrWhiteSpace(tagName)) { throw new ArgumentNullException(nameof(tagName)); } ArgumentNullException.ThrowIfNull(settings); Run(settings, GetArguments(token, owner, repository, tagName, settings)); } private ProcessArgumentBuilder GetArguments(string userName, string password, string owner, string repository, string tagName, GitReleaseManagerPublishSettings settings) { var builder = new ProcessArgumentBuilder(); builder.Append("publish"); builder.Append("-u"); builder.AppendQuoted(userName); builder.Append("-p"); builder.AppendQuotedSecret(password); ParseCommonArguments(builder, owner, repository, tagName); AddBaseArguments(settings, builder); return builder; } private ProcessArgumentBuilder GetArguments(string token, string owner, string repository, string tagName, GitReleaseManagerPublishSettings settings) { var builder = new ProcessArgumentBuilder(); builder.Append("publish"); builder.Append("--token"); builder.AppendQuotedSecret(token); ParseCommonArguments(builder, owner, repository, tagName); AddBaseArguments(settings, builder); return builder; } private void ParseCommonArguments(ProcessArgumentBuilder builder, string owner, string repository, string tagName) { builder.Append("-o"); builder.AppendQuoted(owner); builder.Append("-r"); builder.AppendQuoted(repository); builder.Append("-t"); builder.AppendQuoted(tagName); } } }
GitReleaseManagerPublisher
csharp
JamesNK__Newtonsoft.Json
Src/Newtonsoft.Json/Linq/JObject.cs
{ "start": 1990, "end": 3187 }
public partial class ____ : JContainer, IDictionary<string, JToken?>, INotifyPropertyChanged #if HAVE_COMPONENT_MODEL , ICustomTypeDescriptor #endif #if HAVE_INOTIFY_PROPERTY_CHANGING , INotifyPropertyChanging #endif { private readonly JPropertyKeyedCollection _properties = new JPropertyKeyedCollection(); /// <summary> /// Gets the container's children tokens. /// </summary> /// <value>The container's children tokens.</value> protected override IList<JToken> ChildrenTokens => _properties; /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler? PropertyChanged; #if HAVE_INOTIFY_PROPERTY_CHANGING /// <summary> /// Occurs when a property value is changing. /// </summary> public event PropertyChangingEventHandler? PropertyChanging; #endif /// <summary> /// Initializes a new instance of the <see cref="JObject"/> class. /// </summary> public JObject() { } /// <summary> /// Initializes a new instance of the <see cref="JObject"/>
JObject
csharp
AutoMapper__AutoMapper
src/UnitTests/Projection/ConstructorTests.cs
{ "start": 12587, "end": 13913 }
record ____(bool Value, bool HasB) : Destination(Value) { } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Source, Destination>() .ForCtorParam(nameof(Destination.Value), o => o.MapFrom(s => s.Value == 5)) .Include<SourceA, DestinationA>() .Include<SourceB, DestinationB>(); cfg.CreateMap<SourceA, DestinationA>() .ForCtorParam(nameof(Destination.Value), o => o.MapFrom(s => s.Value == 5)) .ForCtorParam(nameof(DestinationA.HasA), o => o.MapFrom(s => s.A == "a")); cfg.CreateMap<SourceB, DestinationB>() .ForCtorParam(nameof(Destination.Value), o => o.MapFrom(s => s.Value == 5)) .ForCtorParam(nameof(DestinationB.HasB), o => o.MapFrom(s => s.B == "b")); }); [Fact] public void Should_construct_correctly() { var list = new[] { new Source { Value = 5 }, new SourceA { Value = 5, A = "a" }, new SourceB { Value = 5, B = "b" } }.AsQueryable().ProjectTo<Destination>(Configuration); list.All(p => p.Value).ShouldBeTrue(); list.OfType<DestinationA>().Any(p => p.HasA).ShouldBeTrue(); list.OfType<DestinationB>().Any(p => p.HasB).ShouldBeTrue(); } }
DestinationB
csharp
dotnet__aspnetcore
src/Mvc/test/WebSites/FormatterWebSite/Models/Developer.cs
{ "start": 213, "end": 331 }
public class ____ { [Required] public string Name { get; set; } public string Alias { get; set; } }
Developer
csharp
dotnet__orleans
test/Extensions/TesterAzureUtils/Persistence/PersistenceGrainTests_AzureBlobStore.cs
{ "start": 584, "end": 2770 }
private class ____ : ISiloConfigurator { public void Configure(ISiloBuilder hostBuilder) { hostBuilder.AddAzureBlobGrainStorage("AzureStore", (AzureBlobStorageOptions options) => { options.ConfigureTestDefaults(); }) .AddAzureBlobGrainStorage("AzureStore1", (AzureBlobStorageOptions options) => { options.ConfigureTestDefaults(); }) .AddAzureBlobGrainStorage("AzureStore2", (AzureBlobStorageOptions options) => { options.ConfigureTestDefaults(); }) .AddAzureBlobGrainStorage("AzureStore3", (AzureBlobStorageOptions options) => { options.ConfigureTestDefaults(); }) .AddAzureBlobGrainStorage("GrainStorageForTest", (AzureBlobStorageOptions options) => { options.ConfigureTestDefaults(); }) .AddMemoryGrainStorage("test1") .AddMemoryGrainStorage("MemoryStore"); } } protected override void ConfigureTestCluster(TestClusterBuilder builder) { builder.Options.InitialSilosCount = 4; builder.Options.UseTestClusterMembership = false; builder.AddSiloBuilderConfigurator<SiloBuilderConfigurator>(); builder.AddSiloBuilderConfigurator<StorageSiloBuilderConfigurator>(); builder.AddClientBuilderConfigurator<ClientBuilderConfigurator>(); } } public PersistenceGrainTests_AzureBlobStore(ITestOutputHelper output, Fixture fixture) : base(output, fixture) { fixture.EnsurePreconditionsMet(); } [SkippableTheory, TestCategory("Functional")] [InlineData("AzureStore")] [InlineData("AzureStore1")] [InlineData("AzureStore2")] [InlineData("AzureStore3")] public Task Persistence_Silo_StorageProvider_AzureBlobStore(string providerName) { return base.Persistence_Silo_StorageProvider(providerName); } }
StorageSiloBuilderConfigurator
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Driver/Linq/Linq3Implementation/Translators/ExpressionToAggregationExpressionTranslators/MemberExpressionToAggregationExpressionTranslator.cs
{ "start": 1328, "end": 14014 }
internal static class ____ { public static TranslatedExpression Translate(TranslationContext context, MemberExpression expression) { var containerExpression = expression.Expression; var member = expression.Member; if (member is PropertyInfo property && property.DeclaringType.IsNullable()) { switch (property.Name) { case "HasValue": return HasValuePropertyToAggregationExpressionTranslator.Translate(context, expression); case "Value": return ValuePropertyToAggregationExpressionTranslator.Translate(context, expression); default: break; } } if (TryTranslateDictionaryProperty(context, expression, containerExpression, member, out var translatedDictionaryProperty)) { return translatedDictionaryProperty; } if (typeof(BsonValue).IsAssignableFrom(containerExpression.Type)) { throw new ExpressionNotSupportedException(expression); // TODO: support BsonValue properties } var containerTranslation = ExpressionToAggregationExpressionTranslator.Translate(context, containerExpression); if (containerTranslation.Serializer is IWrappedValueSerializer wrappedValueSerializer) { var unwrappedValueAst = AstExpression.GetField(containerTranslation.Ast, wrappedValueSerializer.FieldName); containerTranslation = new TranslatedExpression(containerExpression, unwrappedValueAst, wrappedValueSerializer.ValueSerializer); } if (containerExpression.Type.IsTupleOrValueTuple()) { return TranslateTupleItemProperty(expression, containerTranslation); } if (!DocumentSerializerHelper.AreMembersRepresentedAsFields(containerTranslation.Serializer, out _)) { if (member is PropertyInfo propertyInfo && propertyInfo.Name == "Length") { return LengthPropertyToAggregationExpressionTranslator.Translate(context, expression); } if (TryTranslateCollectionCountProperty(expression, containerTranslation, member, out var translatedCount)) { return translatedCount; } if (TryTranslateDateTimeProperty(expression, containerTranslation, member, out var translatedDateTimeProperty)) { return translatedDateTimeProperty; } } var serializationInfo = DocumentSerializerHelper.GetMemberSerializationInfo(containerTranslation.Serializer, member.Name); AstExpression ast; if (serializationInfo.ElementPath == null) { ast = AstExpression.GetField(containerTranslation.Ast, serializationInfo.ElementName); } else { ast = containerTranslation.Ast; foreach (var subFieldName in serializationInfo.ElementPath) { ast = AstExpression.GetField(ast, subFieldName); } } return new TranslatedExpression(expression, ast, serializationInfo.Serializer); } private static TranslatedExpression TranslateTupleItemProperty(MemberExpression expression, TranslatedExpression containerTranslation) { if (containerTranslation.Serializer is IBsonTupleSerializer tupleSerializer) { var itemName = expression.Member.Name; if (TupleSerializer.TryParseItemName(itemName, out var itemNumber)) { var ast = AstExpression.ArrayElemAt(containerTranslation.Ast, index: itemNumber - 1); var itemSerializer = tupleSerializer.GetItemSerializer(itemNumber); return new TranslatedExpression(expression, ast, itemSerializer); } throw new ExpressionNotSupportedException(expression, because: $"Item name is not valid: {itemName}"); } throw new ExpressionNotSupportedException(expression, because: $"serializer {containerTranslation.Serializer.GetType().FullName} does not implement IBsonTupleSerializer"); } private static bool TryTranslateCollectionCountProperty(MemberExpression expression, TranslatedExpression container, MemberInfo memberInfo, out TranslatedExpression result) { if (EnumerableProperty.IsCountProperty(expression)) { SerializationHelper.EnsureRepresentationIsArray(expression, container.Serializer); var ast = AstExpression.Size(container.Ast); var serializer = Int32Serializer.Instance; result = new TranslatedExpression(expression, ast, serializer); return true; } result = null; return false; } private static bool TryTranslateDateTimeProperty(MemberExpression expression, TranslatedExpression container, MemberInfo memberInfo, out TranslatedExpression result) { result = null; if (container.Expression.Type == typeof(DateTime) && memberInfo is PropertyInfo propertyInfo) { AstExpression ast; IBsonSerializer serializer; switch (propertyInfo.Name) { case "Date": ast = AstExpression.DateTrunc(container.Ast, "day"); serializer = container.Serializer; break; case "DayOfWeek": ast = AstExpression.Subtract(AstExpression.DatePart(AstDatePart.DayOfWeek, container.Ast), 1); serializer = new EnumSerializer<DayOfWeek>(BsonType.Int32); break; case "TimeOfDay": var endDate = container.Ast; var startDate = AstExpression.DateTrunc(container.Ast, "day"); ast = AstExpression.DateDiff(startDate, endDate, "millisecond"); serializer = new TimeSpanSerializer(BsonType.Int64, TimeSpanUnits.Milliseconds); break; default: var datePart = propertyInfo.Name switch { "Day" => AstDatePart.DayOfMonth, "DayOfWeek" => AstDatePart.DayOfWeek, "DayOfYear" => AstDatePart.DayOfYear, "Hour" => AstDatePart.Hour, "Millisecond" => AstDatePart.Millisecond, "Minute" => AstDatePart.Minute, "Month" => AstDatePart.Month, "Second" => AstDatePart.Second, "Year" => AstDatePart.Year, _ => throw new ExpressionNotSupportedException(expression) }; ast = AstExpression.DatePart(datePart, container.Ast); serializer = new Int32Serializer(); break; } result = new TranslatedExpression(expression, ast, serializer); return true; } return false; } private static bool TryTranslateDictionaryProperty(TranslationContext context, MemberExpression expression, Expression containerExpression, MemberInfo memberInfo, out TranslatedExpression translatedDictionaryProperty) { if (memberInfo is PropertyInfo propertyInfo) { var declaringType = propertyInfo.DeclaringType; var declaringTypeDefinition = declaringType.IsConstructedGenericType ? declaringType.GetGenericTypeDefinition() : null; if (declaringTypeDefinition == typeof(Dictionary<,>) || declaringTypeDefinition == typeof(IDictionary<,>)) { var containerTranslation = ExpressionToAggregationExpressionTranslator.TranslateEnumerable(context, containerExpression); var containerAst = containerTranslation.Ast; if (containerTranslation.Serializer is IBsonDictionarySerializer dictionarySerializer) { var dictionaryRepresentation = dictionarySerializer.DictionaryRepresentation; var keySerializer = dictionarySerializer.KeySerializer; var valueSerializer = dictionarySerializer.ValueSerializer; var kvpVar = AstExpression.Var("kvp"); switch (propertyInfo.Name) { case "Keys": var keysAst = dictionaryRepresentation switch { DictionaryRepresentation.ArrayOfDocuments => AstExpression.Map(containerAst, kvpVar, AstExpression.GetField(kvpVar, "k")), DictionaryRepresentation.ArrayOfArrays => AstExpression.Map(containerAst, kvpVar, AstExpression.ArrayElemAt(kvpVar, 0)), _ => throw new ExpressionNotSupportedException(expression, $"Unexpected dictionary representation: {dictionaryRepresentation}") }; var keysSerializer = declaringTypeDefinition == typeof(Dictionary<,>) ? DictionaryKeyCollectionSerializer.Create(keySerializer, valueSerializer) : ICollectionSerializer.Create(keySerializer); translatedDictionaryProperty = new TranslatedExpression(expression, keysAst, keysSerializer); return true; case "Values": if (declaringTypeDefinition == typeof(Dictionary<,>)) { var kvpPairsAst = dictionaryRepresentation switch { DictionaryRepresentation.ArrayOfDocuments => containerAst, DictionaryRepresentation.ArrayOfArrays => AstExpression.Map(containerAst, kvpVar, AstExpression.ComputedDocument([("k", AstExpression.ArrayElemAt(kvpVar, 0)), ("v", AstExpression.ArrayElemAt(kvpVar, 1))])), _ => throw new ExpressionNotSupportedException(expression, $"Unexpected dictionary representation: {dictionaryRepresentation}") }; var valuesSerializer = DictionaryValueCollectionSerializer.Create(keySerializer, valueSerializer); translatedDictionaryProperty = new TranslatedExpression(expression, kvpPairsAst, valuesSerializer); return true; } else if (declaringTypeDefinition == typeof(IDictionary<,>)) { var valuesAst = dictionaryRepresentation switch { DictionaryRepresentation.ArrayOfArrays => AstExpression.Map(containerAst, kvpVar, AstExpression.ArrayElemAt(kvpVar, 1)), DictionaryRepresentation.ArrayOfDocuments => AstExpression.Map(containerAst, kvpVar, AstExpression.GetField(kvpVar, "v")), _ => throw new ExpressionNotSupportedException(expression, $"Unexpected dictionary representation: {dictionaryRepresentation}") }; var valuesSerializer = ICollectionSerializer.Create(valueSerializer); translatedDictionaryProperty = new TranslatedExpression(expression, valuesAst, valuesSerializer); return true; } break; } } } } translatedDictionaryProperty = null; return false; } } }
MemberExpressionToAggregationExpressionTranslator
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.Contents/Workflows/Activities/UnpublishContentTask.cs
{ "start": 296, "end": 2512 }
public class ____ : ContentTask { public UnpublishContentTask( IContentManager contentManager, IWorkflowScriptEvaluator scriptEvaluator, IStringLocalizer<UnpublishContentTask> localizer) : base(contentManager, scriptEvaluator, localizer) { } public override string Name => nameof(UnpublishContentTask); public override LocalizedString DisplayText => S["Unpublish Content Task"]; public override LocalizedString Category => S["Content"]; public override IEnumerable<Outcome> GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { return Outcomes(S["Unpublished"], S["Noop"]); } public override async Task<ActivityExecutionResult> ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext) { var content = (await GetContentAsync(workflowContext)) ?? throw new InvalidOperationException($"The '{nameof(UnpublishContentTask)}' failed to retrieve the content item."); if (string.Equals(InlineEvent.ContentItemId, content.ContentItem.ContentItemId, StringComparison.OrdinalIgnoreCase)) { return Outcomes("Noop"); } var contentItem = await ContentManager.GetAsync(content.ContentItem.ContentItemId, VersionOptions.Latest); if (contentItem == null) { if (content is ContentItemIdExpressionResult) { throw new InvalidOperationException($"The '{nameof(UnpublishContentTask)}' failed to retrieve the content item."); } contentItem = content.ContentItem; } if (InlineEvent.IsStart && InlineEvent.ContentType == contentItem.ContentType && InlineEvent.Name == nameof(ContentUnpublishedEvent)) { throw new InvalidOperationException($"The '{nameof(UnpublishContentTask)}' can't unpublish the content item as it is executed inline from a starting '{nameof(ContentUnpublishedEvent)}' of the same content type, which would result in an infinitive loop."); } await ContentManager.UnpublishAsync(contentItem); return Outcomes("Unpublished"); } }
UnpublishContentTask
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Driver.Tests/Linq/Linq3ImplementationWithLinq2Tests/IntegrationTestBase.cs
{ "start": 13711, "end": 13795 }
public enum ____ : byte { Zero, One }
Q
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Driver.Tests/Linq/Linq3Implementation/Translators/ExpressionToAggregationExpressionTranslators/MemberInitExpressionToAggregationExpressionTranslatorTests.cs
{ "start": 848, "end": 6180 }
public class ____ : Linq3IntegrationTest { [Fact] public void Should_project_class_via_parameterless_constructor() { var collection = CreateCollection(); var queryable = collection.AsQueryable() .Select(x => new SpawnDataClassParameterless { Identifier = x.Id, SpawnDate = x.Date, SpawnText = x.Text }); var stages = Translate(collection, queryable); AssertStages(stages, "{ $project : { Identifier : '$_id', SpawnDate : '$Date', SpawnText : '$Text', _id : 0 } }"); var results = queryable.Single(); results.SpawnDate.Should().Be(new DateTime(2023, 1, 2, 3, 4, 5, DateTimeKind.Utc)); results.SpawnText.Should().Be("data text"); results.Identifier.Should().Be(1); } [Fact] public void Should_project_struct_via_parameterless_constructor() { var collection = CreateCollection(); var queryable = collection.AsQueryable() .Select(x => new SpawnDataStructParameterless { Identifier = x.Id, SpawnDate = x.Date, SpawnText = x.Text }); var stages = Translate(collection, queryable); AssertStages(stages, "{ $project : { Identifier : '$_id', SpawnDate : '$Date', SpawnText : '$Text', _id : 0 } }"); var results = queryable.Single(); results.SpawnDate.Should().Be(new DateTime(2023, 1, 2, 3, 4, 5, DateTimeKind.Utc)); results.SpawnText.Should().Be("data text"); results.Identifier.Should().Be(1); } [Fact] public void Should_project_class_via_constructor() { var collection = CreateCollection(); var queryable = collection.AsQueryable() .Select(x => new SpawnDataClass(x.Id, x.Date) { SpawnText = x.Text }); var stages = Translate(collection, queryable); AssertStages(stages, "{ $project : { Identifier : '$_id', SpawnDate : '$Date', SpawnText : '$Text', _id : 0 } }"); var results = queryable.Single(); results.SpawnDate.Should().Be(new DateTime(2023, 1, 2, 3, 4, 5, DateTimeKind.Utc)); results.SpawnText.Should().Be("data text"); results.Identifier.Should().Be(1); } [Fact] public void Should_project_struct_via_constructor() { var collection = CreateCollection(); var queryable = collection.AsQueryable() .Select(x => new SpawnDataStruct(x.Id, x.Date) { SpawnText = x.Text }); var stages = Translate(collection, queryable); AssertStages(stages, "{ $project : { Identifier : '$_id', SpawnDate : '$Date', SpawnText : '$Text', _id : 0 } }"); var results = queryable.Single(); results.SpawnDate.Should().Be(new DateTime(2023, 1, 2, 3, 4, 5, DateTimeKind.Utc)); results.SpawnText.Should().Be("data text"); results.Identifier.Should().Be(1); } [Fact] public void Should_project_via_constructor_with_inheritance() { var collection = CreateCollection(); var queryable = collection.AsQueryable() .Select(x => new InheritedSpawnData(x.Id, x.Date) { SpawnText = x.Text }); var stages = Translate(collection, queryable); AssertStages(stages, "{ $project : { Identifier : '$_id', SpawnDate : '$Date', SpawnText : '$Text', _id : 0 } }"); var results = queryable.Single(); results.SpawnDate.Should().Be(new DateTime(2023, 1, 2, 3, 4, 5, DateTimeKind.Utc)); results.SpawnText.Should().Be("data text"); results.Identifier.Should().Be(1); } [Fact] public void Should_project_to_class_with_additional_parameters() { CreateCollection(); var collection = GetCollection<MyDataWithExtraField>("data"); var queryable = collection.AsQueryable() .Select(d => new SpawnDataClassWithAdditionalParameter(d.Id, d.Date, d.AdditionalField)); var stages = Translate(collection, queryable); AssertStages(stages, "{ $project : { Identifier : '$_id', SpawnDate : '$Date', AdditionalField: '$AdditionalField', _id : 0 } }"); var results = queryable.Single(); results.SpawnDate.Should().Be(new DateTime(2023, 1, 2, 3, 4, 5, DateTimeKind.Utc)); results.Identifier.Should().Be(1); results.AdditionalField.Should().Be(0); } private IMongoCollection<MyData> CreateCollection() { var collection = GetCollection<MyData>("data"); CreateCollection( collection, new MyData { Id = 1, Date = new DateTime(2023, 1, 2, 3, 4, 5, DateTimeKind.Utc), Text = "data text" }); return collection; }
MemberInitExpressionToAggregationExpressionTranslatorTests
csharp
dotnet__aspnetcore
src/Servers/Kestrel/Core/src/Internal/Http/HttpHeaders.Generated.cs
{ "start": 2421, "end": 9252 }
internal static class ____ { internal static (int index, bool matchedValue) MatchKnownHeaderQPack(KnownHeaderType knownHeader, string value) { switch (knownHeader) { case KnownHeaderType.Age: switch (value) { case "0": return (2, true); default: return (2, false); } case KnownHeaderType.ContentLength: switch (value) { case "0": return (4, true); default: return (4, false); } case KnownHeaderType.Date: return (6, false); case KnownHeaderType.ETag: return (7, false); case KnownHeaderType.LastModified: return (10, false); case KnownHeaderType.Location: return (12, false); case KnownHeaderType.SetCookie: return (14, false); case KnownHeaderType.AcceptRanges: switch (value) { case "bytes": return (32, true); default: return (32, false); } case KnownHeaderType.AccessControlAllowHeaders: switch (value) { case "cache-control": return (33, true); case "content-type": return (34, true); case "*": return (75, true); default: return (33, false); } case KnownHeaderType.AccessControlAllowOrigin: switch (value) { case "*": return (35, true); default: return (35, false); } case KnownHeaderType.CacheControl: switch (value) { case "max-age=0": return (36, true); case "max-age=2592000": return (37, true); case "max-age=604800": return (38, true); case "no-cache": return (39, true); case "no-store": return (40, true); case "public, max-age=31536000": return (41, true); default: return (36, false); } case KnownHeaderType.ContentEncoding: switch (value) { case "br": return (42, true); case "gzip": return (43, true); default: return (42, false); } case KnownHeaderType.ContentType: switch (value) { case "application/dns-message": return (44, true); case "application/javascript": return (45, true); case "application/json": return (46, true); case "application/x-www-form-urlencoded": return (47, true); case "image/gif": return (48, true); case "image/jpeg": return (49, true); case "image/png": return (50, true); case "text/css": return (51, true); case "text/html; charset=utf-8": return (52, true); case "text/plain": return (53, true); case "text/plain;charset=utf-8": return (54, true); default: return (44, false); } case KnownHeaderType.Vary: switch (value) { case "accept-encoding": return (59, true); case "origin": return (60, true); default: return (59, false); } case KnownHeaderType.AccessControlAllowCredentials: switch (value) { case "FALSE": return (73, true); case "TRUE": return (74, true); default: return (73, false); } case KnownHeaderType.AccessControlAllowMethods: switch (value) { case "get": return (76, true); case "get, post, options": return (77, true); case "options": return (78, true); default: return (76, false); } case KnownHeaderType.AccessControlExposeHeaders: switch (value) { case "content-length": return (79, true); default: return (79, false); } case KnownHeaderType.AltSvc: switch (value) { case "clear": return (83, true); default: return (83, false); } case KnownHeaderType.Server: return (92, false); default: return (-1, false); } } }
HttpHeadersCompression
csharp
fluentassertions__fluentassertions
Src/FluentAssertions/Events/IEventRecording.cs
{ "start": 209, "end": 652 }
public interface ____ : IEnumerable<OccurredEvent> { /// <summary> /// The object events are recorded from /// </summary> object EventObject { get; } /// <summary> /// The name of the event that's recorded /// </summary> string EventName { get; } /// <summary> /// The type of the event handler identified by <see cref="EventName"/>. /// </summary> Type EventHandlerType { get; } }
IEventRecording
csharp
dotnet__efcore
test/EFCore.SqlServer.FunctionalTests/SqlServerDatabaseCreatorTest.cs
{ "start": 19155, "end": 23876 }
public class ____ : SqlServerDatabaseCreatorTestBase { [ConditionalTheory, InlineData(true, true), InlineData(false, false)] public async Task Creates_schema_in_existing_database_test(bool async, bool ambientTransaction) { await using var testDatabase = await SqlServerTestStore.GetOrCreateInitializedAsync("ExistingBlogging" + (async ? "Async" : "")); await using var context = new BloggingContext(testDatabase); var creator = GetDatabaseCreator(context); using (CreateTransactionScope(ambientTransaction)) { if (async) { await creator.CreateTablesAsync(); } else { creator.CreateTables(); } } if (testDatabase.ConnectionState != ConnectionState.Open) { await testDatabase.OpenConnectionAsync(); } var tables = (await testDatabase.QueryAsync<string>( "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE'")).ToList(); Assert.Single(tables); Assert.Equal("Blogs", tables.Single()); var columns = (await testDatabase.QueryAsync<string>( "SELECT TABLE_NAME + '.' + COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Blogs'")).ToList(); Assert.Equal(14, columns.Count); Assert.Contains(columns, c => c == "Blogs.Key1"); Assert.Contains(columns, c => c == "Blogs.Key2"); Assert.Contains(columns, c => c == "Blogs.Cheese"); Assert.Contains(columns, c => c == "Blogs.ErMilan"); Assert.Contains(columns, c => c == "Blogs.George"); Assert.Contains(columns, c => c == "Blogs.TheGu"); Assert.Contains(columns, c => c == "Blogs.NotFigTime"); Assert.Contains(columns, c => c == "Blogs.ToEat"); Assert.Contains(columns, c => c == "Blogs.OrNothing"); Assert.Contains(columns, c => c == "Blogs.Fuse"); Assert.Contains(columns, c => c == "Blogs.WayRound"); Assert.Contains(columns, c => c == "Blogs.On"); Assert.Contains(columns, c => c == "Blogs.AndChew"); Assert.Contains(columns, c => c == "Blogs.AndRow"); } [ConditionalTheory, InlineData(true), InlineData(false)] public async Task Throws_if_database_does_not_exist(bool async) { await using var testDatabase = SqlServerTestStore.GetOrCreate("NonExisting"); var creator = GetDatabaseCreator(testDatabase); var exception = async ? (await Assert.ThrowsAsync<RetryLimitExceededException>(() => creator.CreateTablesAsync())) : Assert.Throws<RetryLimitExceededException>(creator.CreateTables); Assert.Equal(CoreStrings.RetryLimitExceeded(6, "TestSqlServerRetryingExecutionStrategy"), exception.Message); var errorNumber = ((SqlException)exception.InnerException!).Number; if (errorNumber != 233) // skip if no-process transient failure { Assert.Equal( 4060, // Login failed error number errorNumber); } } [ConditionalFact] public void GenerateCreateScript_works() { using var context = new BloggingContext("Data Source=foo"); var script = context.Database.GenerateCreateScript(); Assert.Equal( "CREATE TABLE [Blogs] (" + _eol + " [Key1] nvarchar(450) NOT NULL," + _eol + " [Key2] varbinary(900) NOT NULL," + _eol + " [Cheese] nvarchar(max) NULL," + _eol + " [ErMilan] int NOT NULL," + _eol + " [George] bit NOT NULL," + _eol + " [TheGu] uniqueidentifier NOT NULL," + _eol + " [NotFigTime] datetime2 NOT NULL," + _eol + " [ToEat] tinyint NOT NULL," + _eol + " [OrNothing] float NOT NULL," + _eol + " [Fuse] smallint NOT NULL," + _eol + " [WayRound] bigint NOT NULL," + _eol + " [On] real NOT NULL," + _eol + " [AndChew] varbinary(max) NULL," + _eol + " [AndRow] rowversion NULL," + _eol + " CONSTRAINT [PK_Blogs] PRIMARY KEY ([Key1], [Key2])" + _eol + ");" + _eol + "GO" + _eol + _eol + _eol, script); } private static readonly string _eol = Environment.NewLine; } [SqlServerCondition(SqlServerCondition.IsNotCI)]
SqlServerDatabaseCreatorCreateTablesTest
csharp
simplcommerce__SimplCommerce
src/Modules/SimplCommerce.Module.Core/Data/CoreSeedData.cs
{ "start": 140, "end": 5538 }
public static class ____ { public static void SeedData(ModelBuilder builder) { builder.Entity<AppSetting>().HasData( new AppSetting("Global.AssetVersion") { Module = "Core", IsVisibleInCommonSettingPage = true, Value = "1.0" }, new AppSetting("Global.AssetBundling") { Module = "Core", IsVisibleInCommonSettingPage = true, Value = "false" }, new AppSetting("Theme") { Module = "Core", IsVisibleInCommonSettingPage = false, Value = "Generic" }, new AppSetting("Global.DefaultCultureUI") { Module = "Core", IsVisibleInCommonSettingPage = true, Value = "en-US" }, new AppSetting("Global.DefaultCultureAdminUI") { Module = "Core", IsVisibleInCommonSettingPage = true, Value = "en-US" }, new AppSetting("Global.CurrencyCulture") { Module = "Core", IsVisibleInCommonSettingPage = true, Value = "en-US" }, new AppSetting("Global.CurrencyDecimalPlace") { Module = "Core", IsVisibleInCommonSettingPage = true, Value = "2" } ); builder.Entity<EntityType>().HasData( new EntityType("Vendor") { AreaName = "Core", RoutingController = "Vendor", RoutingAction = "VendorDetail", IsMenuable = false } ); builder.Entity<Role>().HasData( new Role { Id = 1L, ConcurrencyStamp = "4776a1b2-dbe4-4056-82ec-8bed211d1454", Name = "admin", NormalizedName = "ADMIN" }, new Role { Id = 2L, ConcurrencyStamp = "00d172be-03a0-4856-8b12-26d63fcf4374", Name = "customer", NormalizedName = "CUSTOMER" }, new Role { Id = 3L, ConcurrencyStamp = "d4754388-8355-4018-b728-218018836817", Name = "guest", NormalizedName = "GUEST" }, new Role { Id = 4L, ConcurrencyStamp = "71f10604-8c4d-4a7d-ac4a-ffefb11cefeb", Name = "vendor", NormalizedName = "VENDOR" } ); builder.Entity<User>().HasData( new User { Id = 2L, AccessFailedCount = 0, ConcurrencyStamp = "101cd6ae-a8ef-4a37-97fd-04ac2dd630e4", CreatedOn = new DateTimeOffset(new DateTime(2018, 5, 29, 4, 33, 39, 189, DateTimeKind.Unspecified), new TimeSpan(0, 7, 0, 0, 0)), Email = "system@simplcommerce.com", EmailConfirmed = false, FullName = "System User", IsDeleted = true, LockoutEnabled = false, NormalizedEmail = "SYSTEM@SIMPLCOMMERCE.COM", NormalizedUserName = "SYSTEM@SIMPLCOMMERCE.COM", PasswordHash = "AQAAAAEAACcQAAAAEAEqSCV8Bpg69irmeg8N86U503jGEAYf75fBuzvL00/mr/FGEsiUqfR0rWBbBUwqtw==", PhoneNumberConfirmed = false, SecurityStamp = "a9565acb-cee6-425f-9833-419a793f5fba", TwoFactorEnabled = false, LatestUpdatedOn = new DateTimeOffset(new DateTime(2018, 5, 29, 4, 33, 39, 189, DateTimeKind.Unspecified), new TimeSpan(0, 7, 0, 0, 0)), UserGuid = new Guid("5f72f83b-7436-4221-869c-1b69b2e23aae"), UserName = "system@simplcommerce.com" }, new User { Id = 10L, AccessFailedCount = 0, ConcurrencyStamp = "c83afcbc-312c-4589-bad7-8686bd4754c0", CreatedOn = new DateTimeOffset(new DateTime(2018, 5, 29, 4, 33, 39, 190, DateTimeKind.Unspecified), new TimeSpan(0, 7, 0, 0, 0)), Email = "admin@simplcommerce.com", EmailConfirmed = false, FullName = "Shop Admin", IsDeleted = false, LockoutEnabled = false, NormalizedEmail = "ADMIN@SIMPLCOMMERCE.COM", NormalizedUserName = "ADMIN@SIMPLCOMMERCE.COM", PasswordHash = "AQAAAAEAACcQAAAAEAEqSCV8Bpg69irmeg8N86U503jGEAYf75fBuzvL00/mr/FGEsiUqfR0rWBbBUwqtw==", PhoneNumberConfirmed = false, SecurityStamp = "d6847450-47f0-4c7a-9fed-0c66234bf61f", TwoFactorEnabled = false, LatestUpdatedOn = new DateTimeOffset(new DateTime(2018, 5, 29, 4, 33, 39, 190, DateTimeKind.Unspecified), new TimeSpan(0, 7, 0, 0, 0)), UserGuid = new Guid("ed8210c3-24b0-4823-a744-80078cf12eb4"), UserName = "admin@simplcommerce.com" } ); builder.Entity<UserRole>().HasData( new UserRole { UserId = 10, RoleId = 1 } ); builder.Entity<WidgetZone>().HasData( new WidgetZone(1) { Name = "Home Featured" }, new WidgetZone(2) { Name = "Home Main Content" }, new WidgetZone(3) { Name = "Home After Main Content" } ); builder.Entity<Country>().HasData( new Country("VN") { Code3 = "VNM", Name = "Việt Nam", IsBillingEnabled = true, IsShippingEnabled = true, IsCityEnabled = false, IsZipCodeEnabled = false, IsDistrictEnabled = true }, new Country("US") { Code3 = "USA", Name = "United States", IsBillingEnabled = true, IsShippingEnabled = true, IsCityEnabled = true, IsZipCodeEnabled = true, IsDistrictEnabled = false } ); builder.Entity<StateOrProvince>().HasData( new StateOrProvince(1) { CountryId = "VN", Name = "Hồ Chí Minh", Type = "Thành Phố" }, new StateOrProvince(2) { CountryId = "US", Name = "Washington", Code = "WA" } ); builder.Entity<District>().HasData( new District(1) { Name = "Quận 1", StateOrProvinceId = 1, Type = "Quận" }, new District(2) { Name = "Quận 2", StateOrProvinceId = 1, Type = "Quận" } ); builder.Entity<Address>().HasData( new Address(1) { AddressLine1 = "364 Cong Hoa", ContactName = "Thien Nguyen", CountryId = "VN", StateOrProvinceId = 1 } ); } } }
CoreSeedData
csharp
dotnet__maui
src/Controls/src/Core/Platform/Windows/IIconElementHandler.cs
{ "start": 153, "end": 504 }
public interface ____ : IRegisterable { Task<Microsoft.UI.Xaml.Controls.IconSource> LoadIconSourceAsync(ImageSource imagesource, CancellationToken cancellationToken = default(CancellationToken)); Task<IconElement> LoadIconElementAsync(ImageSource imagesource, CancellationToken cancellationToken = default(CancellationToken)); } }
IIconElementHandler
csharp
dotnet__aspnetcore
src/Mvc/Mvc.ViewFeatures/test/Rendering/HtmlHelperValueTest.cs
{ "start": 7428, "end": 8286 }
private sealed class ____ { public string StringProperty { get; set; } public object ObjectProperty { get; set; } public override string ToString() { return string.Format( CultureInfo.InvariantCulture, "{{ StringProperty = {0}, ObjectProperty = {1} }}", StringProperty ?? "(null)", ObjectProperty ?? "(null)"); } } private static HtmlHelper<TestModel> GetHtmlHelper() { var model = new TestModel { StringProperty = "ModelStringPropertyValue", ObjectProperty = new DateTime(1900, 1, 1, 0, 0, 0), }; var helper = DefaultTemplatesUtilities.GetHtmlHelper<TestModel>(model); helper.ViewData["StringProperty"] = "ViewDataValue"; return helper; } }
TestModel
csharp
CommunityToolkit__Maui
src/CommunityToolkit.Maui/Behaviors/MaskedBehavior.shared.cs
{ "start": 469, "end": 5073 }
public partial class ____ : BaseBehavior<InputView>, IDisposable { readonly SemaphoreSlim applyMaskSemaphoreSlim = new(1, 1); bool isDisposed; IReadOnlyDictionary<int, char>? maskPositions; /// <summary> /// Finalizer /// </summary> ~MaskedBehavior() => Dispose(false); /// <summary> /// The mask that the input value needs to match. This is a bindable property. /// </summary> [BindableProperty(PropertyChangedMethodName = nameof(OnMaskPropertyChanged))] public partial string? Mask { get; set; } /// <summary> /// Gets or sets which character in the <see cref="Mask"/> property that will be visible and entered by a user. Defaults to 'X'. This is a bindable property. /// <br/> /// By default, the 'X' character will be unmasked therefore a <see cref="Mask"/> of "XX XX XX" would display "12 34 56". /// If you wish to include 'X' in your <see cref="Mask"/> then you could set this <see cref="UnmaskedCharacter"/> to something else /// e.g. '0' and then use a <see cref="Mask"/> of "00X00X00" which would then display "12X34X56". /// </summary> [BindableProperty(DefaultValueCreatorMethodName = nameof(UnmaskedCharacterValueCreator), PropertyChangedMethodName = nameof(OnUnmaskedCharacterPropertyChanged))] public partial char UnmaskedCharacter { get; set; } /// <inheritdoc/> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <inheritdoc/> protected virtual void Dispose(bool disposing) { if (isDisposed) { return; } if (disposing) { applyMaskSemaphoreSlim.Dispose(); } isDisposed = true; } /// <inheritdoc /> protected override async void OnViewPropertyChanged(InputView sender, PropertyChangedEventArgs e) { base.OnViewPropertyChanged(sender, e); if (e.PropertyName == InputView.TextProperty.PropertyName) { await OnTextPropertyChanged(CancellationToken.None); } } static object UnmaskedCharacterValueCreator(BindableObject bindable) => 'X'; static void OnMaskPropertyChanged(BindableObject bindable, object oldValue, object newValue) { var mask = (string?)newValue; var maskedBehavior = (MaskedBehavior)bindable; maskedBehavior.SetMaskPositions(mask); } static async void OnUnmaskedCharacterPropertyChanged(BindableObject bindable, object oldValue, object newValue) { var maskedBehavior = (MaskedBehavior)bindable; await maskedBehavior.OnMaskChanged(maskedBehavior.Mask, CancellationToken.None).ConfigureAwait(false); } Task OnTextPropertyChanged(CancellationToken token) { // Android does not play well when we update the Text inside the TextChanged event. // Therefore, if we dispatch the mechanism of updating the Text property it solves the issue of the caret position being updated incorrectly. // https://github.com/CommunityToolkit/Maui/issues/460 return View?.Dispatcher.DispatchAsync(() => ApplyMask(View?.Text, token)) ?? Task.CompletedTask; } void SetMaskPositions(in string? mask) { if (string.IsNullOrEmpty(mask)) { maskPositions = null; return; } var list = new Dictionary<int, char>(); for (var i = 0; i < mask.Length; i++) { if (mask[i] != UnmaskedCharacter) { list.Add(i, mask[i]); } } maskPositions = list; } async ValueTask OnMaskChanged(string? mask, CancellationToken token) { if (string.IsNullOrEmpty(mask)) { maskPositions = null; return; } var originalText = RemoveMask(View?.Text); SetMaskPositions(mask); await ApplyMask(originalText, token); } [return: NotNullIfNotNull(nameof(text))] string? RemoveMask(string? text) { if (string.IsNullOrEmpty(text)) { return text; } var maskChars = maskPositions? .Select(c => c.Value) .Distinct() .ToArray(); return string.Join(string.Empty, text.Split(maskChars)); } async Task ApplyMask(string? text, CancellationToken token) { await applyMaskSemaphoreSlim.WaitAsync(token); try { if (!string.IsNullOrWhiteSpace(text) && maskPositions is not null) { if (Mask is not null && text.Length > Mask.Length) { text = text.Remove(text.Length - 1); } text = RemoveMask(text); foreach (var position in maskPositions) { if (text.Length < position.Key + 1) { continue; } var value = position.Value.ToString(); // !important - If user types in masked value, don't add masked value if (text.Substring(position.Key, 1) != value) { text = text.Insert(position.Key, value); } } } if (View is not null) { View.Text = text; } } finally { applyMaskSemaphoreSlim.Release(); } } }
MaskedBehavior
csharp
dotnet__maui
src/Controls/tests/ManualTests/Tests/Editor/D2.xaml.cs
{ "start": 190, "end": 276 }
public partial class ____ : ContentPage { public D2() { InitializeComponent(); } }
D2
csharp
getsentry__sentry-dotnet
src/Sentry/Internal/InitCounter.cs
{ "start": 262, "end": 396 }
internal interface ____ { public int Count { get; } public void Increment(); } /// <inheritdoc cref="IInitCounter"/>
IInitCounter
csharp
microsoft__semantic-kernel
dotnet/src/Plugins/Plugins.UnitTests/Core/HttpPluginTests.cs
{ "start": 333, "end": 4604 }
public sealed class ____ : IDisposable { private readonly string _content = "hello world"; private readonly string _uriString = "http://www.example.com"; private readonly HttpResponseMessage _response = new() { StatusCode = HttpStatusCode.OK, Content = new StringContent("hello world"), }; [Fact] public void ItCanBeInstantiated() { // Act - Assert no exception occurs var plugin = new HttpPlugin(); } [Fact] public void ItCanBeImported() { // Act - Assert no exception occurs e.g. due to reflection Assert.NotNull(KernelPluginFactory.CreateFromType<HttpPlugin>("http")); } [Fact] public async Task ItCanGetAsync() { // Arrange var mockHandler = this.CreateMock(); using var client = new HttpClient(mockHandler.Object); var plugin = new HttpPlugin(client); // Act var result = await plugin.GetAsync(this._uriString); // Assert Assert.Equal(this._content, result); this.VerifyMock(mockHandler, HttpMethod.Get); } [Fact] public async Task ItCanPostAsync() { // Arrange var mockHandler = this.CreateMock(); using var client = new HttpClient(mockHandler.Object); var plugin = new HttpPlugin(client); // Act var result = await plugin.PostAsync(this._uriString, this._content); // Assert Assert.Equal(this._content, result); this.VerifyMock(mockHandler, HttpMethod.Post); } [Fact] public async Task ItCanPutAsync() { // Arrange var mockHandler = this.CreateMock(); using var client = new HttpClient(mockHandler.Object); var plugin = new HttpPlugin(client); // Act var result = await plugin.PutAsync(this._uriString, this._content); // Assert Assert.Equal(this._content, result); this.VerifyMock(mockHandler, HttpMethod.Put); } [Fact] public async Task ItCanDeleteAsync() { // Arrange var mockHandler = this.CreateMock(); using var client = new HttpClient(mockHandler.Object); var plugin = new HttpPlugin(client); // Act var result = await plugin.DeleteAsync(this._uriString); // Assert Assert.Equal(this._content, result); this.VerifyMock(mockHandler, HttpMethod.Delete); } [Fact] public async Task ItThrowsInvalidOperationExceptionForInvalidDomainAsync() { // Arrange var mockHandler = this.CreateMock(); using var client = new HttpClient(mockHandler.Object); var plugin = new HttpPlugin(client) { AllowedDomains = ["www.example.com"] }; var invalidUri = "http://www.notexample.com"; // Act & Assert await Assert.ThrowsAsync<InvalidOperationException>(async () => await plugin.GetAsync(invalidUri)); await Assert.ThrowsAsync<InvalidOperationException>(async () => await plugin.PostAsync(invalidUri, this._content)); await Assert.ThrowsAsync<InvalidOperationException>(async () => await plugin.PutAsync(invalidUri, this._content)); await Assert.ThrowsAsync<InvalidOperationException>(async () => await plugin.DeleteAsync(invalidUri)); } private Mock<HttpMessageHandler> CreateMock() { var mockHandler = new Mock<HttpMessageHandler>(); mockHandler.Protected() .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>()) .ReturnsAsync(this._response); return mockHandler; } private void VerifyMock(Mock<HttpMessageHandler> mockHandler, HttpMethod method) { mockHandler.Protected().Verify( "SendAsync", Times.Exactly(1), // we expected a single external request ItExpr.Is<HttpRequestMessage>(req => req.Method == method // we expected a POST request && req.RequestUri == new Uri(this._uriString) // to this uri ), ItExpr.IsAny<CancellationToken>() ); } public void Dispose() { this._response.Dispose(); } }
HttpPluginTests
csharp
dotnet__aspnetcore
src/Framework/AspNetCoreAnalyzers/test/RouteEmbeddedLanguage/FrameworkParametersCompletionProviderTests.cs
{ "start": 16324, "end": 16461 }
class ____ { static void Main() { EndpointRouteBuilderExtensions.MapGet(null, @""{id}"", (NonParsableType $$ } }
Program
csharp
dotnet__orleans
src/api/Orleans.Runtime/Orleans.Runtime.cs
{ "start": 30265, "end": 32654 }
partial class ____ { public GrainTypeSharedContext(GrainType grainType, IClusterManifestProvider clusterManifestProvider, Orleans.Metadata.GrainClassMap grainClassMap, Placement.PlacementStrategyResolver placementStrategyResolver, Microsoft.Extensions.Options.IOptions<Orleans.Configuration.SiloMessagingOptions> messagingOptions, Microsoft.Extensions.Options.IOptions<Orleans.Configuration.GrainCollectionOptions> collectionOptions, Microsoft.Extensions.Options.IOptions<Orleans.Configuration.SchedulingOptions> schedulingOptions, Microsoft.Extensions.Options.IOptions<Orleans.Configuration.StatelessWorkerOptions> statelessWorkerOptions, IGrainRuntime grainRuntime, Microsoft.Extensions.Logging.ILoggerFactory loggerFactory, GrainReferences.GrainReferenceActivator grainReferenceActivator, System.IServiceProvider serviceProvider, Orleans.Serialization.Session.SerializerSessionPool serializerSessionPool) { } public System.TimeSpan CollectionAgeLimit { get { throw null; } } public Orleans.GrainDirectory.IGrainDirectory? GrainDirectory { get { throw null; } } public GrainReferences.GrainReferenceActivator GrainReferenceActivator { get { throw null; } } public string? GrainTypeName { get { throw null; } } public Microsoft.Extensions.Logging.ILogger Logger { get { throw null; } } public System.TimeSpan MaxRequestProcessingTime { get { throw null; } } public System.TimeSpan MaxWarningRequestProcessingTime { get { throw null; } } public Orleans.Configuration.SiloMessagingOptions MessagingOptions { get { throw null; } } public PlacementStrategy PlacementStrategy { get { throw null; } } public IGrainRuntime Runtime { get { throw null; } } public Orleans.Configuration.SchedulingOptions SchedulingOptions { get { throw null; } } public Orleans.Serialization.Session.SerializerSessionPool SerializerSessionPool { get { throw null; } } public Orleans.Configuration.StatelessWorkerOptions StatelessWorkerOptions { get { throw null; } } public TComponent? GetComponent<TComponent>() { throw null; } public void OnCreateActivation(IGrainContext grainContext) { } public void OnDestroyActivation(IGrainContext grainContext) { } public void SetComponent<TComponent>(TComponent? instance) { } }
GrainTypeSharedContext
csharp
grandnode__grandnode2
src/Web/Grand.Web.Admin/Models/Orders/GiftVoucherModel.cs
{ "start": 2576, "end": 3072 }
public class ____ : BaseEntityModel { [GrandResourceDisplayName("Admin.GiftVouchers.History.UsedValue")] public string UsedValue { get; set; } [GrandResourceDisplayName("Admin.GiftVouchers.History.Order")] public string OrderId { get; set; } public int OrderNumber { get; set; } [GrandResourceDisplayName("Admin.GiftVouchers.History.CreatedOn")] public DateTime CreatedOn { get; set; } } #endregion }
GiftVoucherUsageHistoryModel
csharp
dotnet__efcore
test/EFCore.Relational.Tests/DbSetAsTableNameTest.cs
{ "start": 180, "end": 5147 }
public abstract class ____ { [ConditionalFact] public virtual void DbSet_names_are_used_as_table_names() { using var context = CreateContext(); Assert.Equal("Cheeses", GetTableName<Cheese>(context)); } [ConditionalFact] public virtual void DbSet_name_of_base_type_is_used_as_table_name_for_TPH() { using var context = CreateContext(); Assert.Equal("Chocolates", GetTableName<Chocolate>(context)); Assert.Equal("Chocolates", GetTableName<Galaxy>(context)); Assert.Equal("Chocolates", GetTableName<DairyMilk>(context)); } [ConditionalFact] public virtual void Type_name_of_base_type_is_used_as_table_name_for_TPH_if_not_added_as_set() { using var context = CreateContext(); Assert.Equal("Fruit", GetTableName<Fruit>(context)); Assert.Equal("Fruit", GetTableName<Apple>(context)); Assert.Equal("Fruit", GetTableName<Banana>(context)); } [ConditionalFact] public virtual void DbSet_names_of_derived_types_are_used_as_table_names_when_base_type_not_mapped() { using var context = CreateContext(); Assert.Equal("Triskets", GetTableName<Trisket>(context)); Assert.Equal("WheatThins", GetTableName<WheatThin>(context)); } [ConditionalFact] public virtual void Name_of_duplicate_DbSet_is_not_used_as_table_name() { using var context = CreateContext(); Assert.Equal("Marmite", GetTableName<Marmite>(context)); } [ConditionalFact] public virtual void Explicit_names_can_be_used_as_table_names() { using var context = CreateNamedTablesContext(); Assert.Equal("YummyCheese", GetTableName<Cheese>(context)); } [ConditionalFact] public virtual void DbSet_names_are_not_used_as_shared_entity_type_table_names() { using var context = CreateContext(); Assert.Equal("Bovril", GetTableName<BothEntity>(context, "Bovril")); Assert.Equal("Beefy", GetTableName<BothEntity>(context, "Beefy")); Assert.Equal("Imposter", GetTableName<VeggieEntity>(context, "Imposter")); Assert.Equal("Veggies", GetTableName<VeggieEntity>(context, "Veggies")); } [ConditionalFact] public virtual void Explicit_names_can_be_used_for_shared_type_entity_types() { using var context = CreateNamedTablesContext(); Assert.Equal("MyBovrils", GetTableName<BothEntity>(context, "Bovril")); Assert.Equal("MyBeefies", GetTableName<BothEntity>(context, "Beefy")); Assert.Equal("MyImposter", GetTableName<VeggieEntity>(context, "Imposter")); Assert.Equal("MyVeggies", GetTableName<VeggieEntity>(context, "Veggies")); } [ConditionalFact] public virtual void Explicit_name_of_base_type_can_be_used_as_table_name_for_TPH() { using var context = CreateNamedTablesContext(); Assert.Equal("YummyChocolate", GetTableName<Chocolate>(context)); Assert.Equal("YummyChocolate", GetTableName<Galaxy>(context)); Assert.Equal("YummyChocolate", GetTableName<DairyMilk>(context)); } [ConditionalFact] public virtual void Explicit_name_of_base_type_can_be_used_as_table_name_for_TPH_if_not_added_as_set() { using var context = CreateNamedTablesContext(); Assert.Equal("YummyFruit", GetTableName<Fruit>(context)); Assert.Equal("YummyFruit", GetTableName<Apple>(context)); Assert.Equal("YummyFruit", GetTableName<Banana>(context)); } [ConditionalFact] public virtual void Explicit_names_of_derived_types_can_be_used_as_table_names_when_base_type_not_mapped() { using var context = CreateNamedTablesContext(); Assert.Equal("YummyTriskets", GetTableName<Trisket>(context)); Assert.Equal("YummyWheatThins", GetTableName<WheatThin>(context)); } [ConditionalFact] public virtual void Explicit_name_can_be_used_for_type_with_duplicated_sets() { using var context = CreateNamedTablesContext(); Assert.Equal("YummyMarmite", GetTableName<Marmite>(context)); } [ConditionalFact] public virtual void DbSet_long_name_properly_truncated() { using var context = CreateContext(); var maxLength = context.Model.GetMaxIdentifierLength(); var realLength = GetTableName<ReallyLongNameA>(context).Length; Assert.True(realLength <= maxLength); } [ConditionalFact] public virtual void DbSet_long_name_uniquely_truncated() { using var context = CreateContext(); var nameA = GetTableName<ReallyLongNameA>(context); var nameB = GetTableName<ReallyLongNameB>(context); Assert.NotEqual(nameA, nameB); } protected abstract string GetTableName<TEntity>(DbContext context); protected abstract string GetTableName<TEntity>(DbContext context, string entityTypeName); protected abstract SetsContext CreateContext();
DbSetAsTableNameTest
csharp
nuke-build__nuke
source/Nuke.GlobalTool/Program.Secrets.cs
{ "start": 611, "end": 4274 }
partial class ____ { private const string SaveAndExit = "<Save & Exit>"; private const string DiscardAndExit = "<Discard & Exit>"; private const string DeletePasswordAndExit = "<Delete Password & Exit>"; // ReSharper disable once CognitiveComplexity [UsedImplicitly] public static int Secrets(string[] args, [CanBeNull] AbsolutePath rootDirectory, [CanBeNull] AbsolutePath buildScript) { var secretParameters = CompletionUtility.GetItemsFromSchema( GetBuildSchemaFile(rootDirectory.NotNull("No root directory")), filter: x => x.Value.TryGetProperty("default", out _)) .Select(x => x.Key).ToList(); if (secretParameters.Count == 0) { Host.Information($"There are no parameters marked with {nameof(SecretAttribute)}"); return 0; } var profile = args.SingleOrDefault(); var parametersFile = profile == null ? GetDefaultParametersFile(rootDirectory) : GetParametersProfileFile(rootDirectory, profile); var generatedPassword = false; var credentialStoreName = GetCredentialStoreName(rootDirectory, profile); var password = CredentialStore.TryGetPassword(credentialStoreName); var fromCredentialStore = password != null; password ??= CredentialStore.CreateNewPassword(out generatedPassword); var existingSecrets = LoadSecrets(secretParameters, password, parametersFile); if (EnvironmentInfo.IsOsx && existingSecrets.Count == 0 && !fromCredentialStore) { if (generatedPassword || PromptForConfirmation($"Save password to keychain? (associated with '{rootDirectory}')")) CredentialStore.SavePassword(credentialStoreName, password); } var options = secretParameters .Concat(SaveAndExit, DiscardAndExit) .Concat(fromCredentialStore ? DeletePasswordAndExit : null).WhereNotNull().ToList(); var addedSecrets = new Dictionary<string, string>(); while (true) { var choice = PromptForChoice( "Choose secret parameter to enter value:", options.Select(x => (x, addedSecrets.ContainsKey(x) || existingSecrets.ContainsKey(x) ? $"* {x}" : x)).ToArray()); if (!choice.EqualsAnyOrdinalIgnoreCase(SaveAndExit, DiscardAndExit, DeletePasswordAndExit)) { addedSecrets[choice] = PromptForSecret(choice); } else { if (choice == SaveAndExit) SaveSecrets(addedSecrets, password, parametersFile); if (choice == DeletePasswordAndExit) CredentialStore.DeletePassword(credentialStoreName); if (addedSecrets.Any()) Host.Information("Remember to clear your clipboard!"); return 0; } } } private static Dictionary<string, string> LoadSecrets(IReadOnlyCollection<string> secretParameters, string password, AbsolutePath parametersFile) { var jobject = parametersFile.ReadJson(); return jobject.Properties() .Where(x => secretParameters.Contains(x.Name)) .ToDictionary(x => x.Name, x => Decrypt(x.Value.Value<string>(), password, x.Name)); } private static void SaveSecrets(Dictionary<string, string> secrets, string password, AbsolutePath parametersFile) { parametersFile.UpdateJson(obj => { foreach (var (name, secret) in secrets) obj[name] = Encrypt(secret, password); }); } }
Program
csharp
microsoft__FASTER
cs/src/core/Allocator/BlittableAllocator.cs
{ "start": 11021, "end": 13154 }
record ____ into memory. /// </summary> /// <param name="fromLogical"></param> /// <param name="numBytes"></param> /// <param name="callback"></param> /// <param name="context"></param> /// <param name="result"></param> protected override void AsyncReadRecordObjectsToMemory(long fromLogical, int numBytes, DeviceIOCompletionCallback callback, AsyncIOContext<Key, Value> context, SectorAlignedMemory result = default) { throw new InvalidOperationException("AsyncReadRecordObjectsToMemory invalid for BlittableAllocator"); } /// <summary> /// Retrieve objects from object log /// </summary> /// <param name="record"></param> /// <param name="ctx"></param> /// <returns></returns> protected override bool RetrievedFullRecord(byte* record, ref AsyncIOContext<Key, Value> ctx) { ctx.key = GetKey((long)record); ctx.value = GetValue((long)record); return true; } /// <summary> /// Whether KVS has keys to serialize/deserialize /// </summary> /// <returns></returns> public override bool KeyHasObjects() { return false; } /// <summary> /// Whether KVS has values to serialize/deserialize /// </summary> /// <returns></returns> public override bool ValueHasObjects() { return false; } public override IHeapContainer<Key> GetKeyContainer(ref Key key) => new StandardHeapContainer<Key>(ref key); public override IHeapContainer<Value> GetValueContainer(ref Value value) => new StandardHeapContainer<Value>(ref value); public override long[] GetSegmentOffsets() { return null; } internal override void PopulatePage(byte* src, int required_bytes, long destinationPage) { throw new FasterException("BlittableAllocator memory pages are sector aligned - use direct copy"); } /// <summary> /// Iterator
efficiently
csharp
ChilliCream__graphql-platform
src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs
{ "start": 2457068, "end": 2457467 }
public partial interface ____ { public global::System.Collections.Generic.IReadOnlyList<global::ChilliCream.Nitro.CommandLine.Cloud.Client.ICommitFusionConfigurationPublish_CommitFusionConfigurationPublish_Errors>? Errors { get; } } [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
ICommitFusionConfigurationPublish_CommitFusionConfigurationPublish
csharp
dotnet__machinelearning
src/Microsoft.ML.Data/Commands/EvaluateCommand.cs
{ "start": 1288, "end": 1562 }
enum ____ whether the metric should be maximized or minimized while sweeping. 'Info' should be /// used for metrics that are irrelevant to the model's quality (such as the number of positive/negative /// examples etc.). /// </summary>
specifying
csharp
JoshClose__CsvHelper
tests/CsvHelper.Tests/Mappings/Attribute/TypeConverterTests.cs
{ "start": 587, "end": 2135 }
public class ____ { [Fact] public void TypeConverterTest() { using (var reader = new StringReader("Id,Name\r\n1,one\r\n")) using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) { var records = csv.GetRecords<TypeConverterClass>().ToList(); Assert.Equal(1, records[0].Id); Assert.Equal("two", records[0].Name); } } [Fact] public void TypeConverterOnClassReferenceTest() { var records = new List<AClass> { new AClass { Id = 1, Name = new BClass() }, }; using (var writer = new StringWriter()) using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture)) { csv.WriteRecords(records); var expected = "Id,Name\r\n1,two\r\n"; Assert.Equal(expected, writer.ToString()); } } [Fact] public void TypeConverterOnStructReferenceTest() { var records = new List<AStruct> { new AStruct { Id = 1, Name = new BStruct() }, }; using (var writer = new StringWriter()) using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture)) { csv.WriteRecords(records); var expected = "Id,Name\r\n1,two\r\n"; Assert.Equal(expected, writer.ToString()); } } [Fact] public void Constructor_TypeConverterWithConstructorArgs_Creates() { var attribute = new TypeConverterAttribute(typeof(TypeConverterWithConstructorArgs), 2); Assert.IsType<TypeConverterWithConstructorArgs>(attribute.TypeConverter); Assert.Equal(2, ((TypeConverterWithConstructorArgs)attribute.TypeConverter).Value); }
TypeConverterTests
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore.DisplayManagement/IAsyncViewActionFilter.cs
{ "start": 115, "end": 254 }
public interface ____ : IAsyncActionFilter, IAsyncPageFilter { Task OnActionExecutionAsync(ActionContext context); }
IAsyncViewActionFilter
csharp
CommunityToolkit__WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.UI.Controls.Media/Eyedropper/Eyedropper.cs
{ "start": 765, "end": 12308 }
public partial class ____ : Control { private const string TouchState = "Touch"; private const string MousePenState = "MousePen"; private const int PreviewPixelsPerRawPixel = 10; private const int PixelCountPerRow = 11; private static readonly CoreCursor DefaultCursor = new CoreCursor(CoreCursorType.Arrow, 1); private static readonly CoreCursor MoveCursor = new CoreCursor(CoreCursorType.Cross, 1); private readonly CanvasDevice _device = CanvasDevice.GetSharedDevice(); private readonly TranslateTransform _layoutTransform = new TranslateTransform(); private readonly CanvasImageSource _previewImageSource; private readonly Grid _rootGrid; private readonly Grid _targetGrid; private Popup _popup; private CanvasBitmap _appScreenshot; private Action _lazyTask; private uint? _pointerId = null; private TaskCompletionSource<Color> _taskSource; private double _currentDpi; /// <summary> /// Initializes a new instance of the <see cref="Eyedropper"/> class. /// </summary> public Eyedropper() { DefaultStyleKey = typeof(Eyedropper); _rootGrid = new Grid(); _targetGrid = new Grid { Background = new SolidColorBrush(Color.FromArgb(0x01, 0x00, 0x00, 0x00)) }; RenderTransform = _layoutTransform; _previewImageSource = new CanvasImageSource(_device, PreviewPixelsPerRawPixel * PixelCountPerRow, PreviewPixelsPerRawPixel * PixelCountPerRow, 96f); Preview = _previewImageSource; Loaded += Eyedropper_Loaded; } /// <summary> /// Occurs when the Color property has changed. /// </summary> public event TypedEventHandler<Eyedropper, EyedropperColorChangedEventArgs> ColorChanged; /// <summary> /// Occurs when the eyedropper begins to take color. /// </summary> public event TypedEventHandler<Eyedropper, EventArgs> PickStarted; /// <summary> /// Occurs when the eyedropper stops to take color. /// </summary> public event TypedEventHandler<Eyedropper, EventArgs> PickCompleted; /// <summary> /// Open the eyedropper. /// </summary> /// <param name="startPoint">The initial eyedropper position</param> /// <returns>The picked color.</returns> public async Task<Color> Open(Point? startPoint = null) { _taskSource = new TaskCompletionSource<Color>(); HookUpEvents(); Opacity = 0; if (startPoint.HasValue) { _lazyTask = async () => { await UpdateAppScreenshotAsync(); UpdateEyedropper(startPoint.Value); Opacity = 1; }; } _rootGrid.Children.Add(_targetGrid); _rootGrid.Children.Add(this); if (_popup != null) { _popup.IsOpen = false; } _popup = new Popup { Child = _rootGrid }; if (ControlHelpers.IsXamlRootAvailable && XamlRoot != null) { _popup.XamlRoot = XamlRoot; } if (ControlHelpers.IsXamlRootAvailable && _popup.XamlRoot != null) { _rootGrid.Width = _popup.XamlRoot.Size.Width; _rootGrid.Height = _popup.XamlRoot.Size.Height; } else { _rootGrid.Width = Window.Current.Bounds.Width; _rootGrid.Height = Window.Current.Bounds.Height; } UpdateWorkArea(); _popup.IsOpen = true; var result = await _taskSource.Task; _taskSource = null; _popup = null; _rootGrid.Children.Clear(); return result; } /// <summary> /// Close the eyedropper. /// </summary> public void Close() { if (_taskSource != null && !_taskSource.Task.IsCanceled) { _taskSource.TrySetCanceled(); _rootGrid.Children.Clear(); } } private void HookUpEvents() { Unloaded -= Eyedropper_Unloaded; Unloaded += Eyedropper_Unloaded; if (ControlHelpers.IsXamlRootAvailable && XamlRoot != null) { XamlRoot.Changed -= XamlRoot_Changed; XamlRoot.Changed += XamlRoot_Changed; _currentDpi = XamlRoot.RasterizationScale; } else { var window = Window.Current; window.SizeChanged -= Window_SizeChanged; window.SizeChanged += Window_SizeChanged; var displayInformation = DisplayInformation.GetForCurrentView(); displayInformation.DpiChanged -= Eyedropper_DpiChanged; displayInformation.DpiChanged += Eyedropper_DpiChanged; _currentDpi = displayInformation.LogicalDpi; } _targetGrid.PointerEntered -= TargetGrid_PointerEntered; _targetGrid.PointerEntered += TargetGrid_PointerEntered; _targetGrid.PointerExited -= TargetGrid_PointerExited; _targetGrid.PointerExited += TargetGrid_PointerExited; _targetGrid.PointerPressed -= TargetGrid_PointerPressed; _targetGrid.PointerPressed += TargetGrid_PointerPressed; _targetGrid.PointerMoved -= TargetGrid_PointerMoved; _targetGrid.PointerMoved += TargetGrid_PointerMoved; _targetGrid.PointerReleased -= TargetGrid_PointerReleased; _targetGrid.PointerReleased += TargetGrid_PointerReleased; } private async void XamlRoot_Changed(XamlRoot sender, XamlRootChangedEventArgs args) { if (_rootGrid.Width != sender.Size.Width || _rootGrid.Height != sender.Size.Height) { UpdateRootGridSize(sender.Size.Width, sender.Size.Height); } if (_currentDpi != sender.RasterizationScale) { _currentDpi = sender.RasterizationScale; await UpdateAppScreenshotAsync(); } } private void UnhookEvents() { Unloaded -= Eyedropper_Unloaded; if (ControlHelpers.IsXamlRootAvailable && XamlRoot != null) { XamlRoot.Changed -= XamlRoot_Changed; } else { Window.Current.SizeChanged -= Window_SizeChanged; DisplayInformation.GetForCurrentView().DpiChanged -= Eyedropper_DpiChanged; } if (_targetGrid != null) { _targetGrid.PointerEntered -= TargetGrid_PointerEntered; _targetGrid.PointerExited -= TargetGrid_PointerExited; _targetGrid.PointerPressed -= TargetGrid_PointerPressed; _targetGrid.PointerMoved -= TargetGrid_PointerMoved; _targetGrid.PointerReleased -= TargetGrid_PointerReleased; } } private void Eyedropper_Loaded(object sender, RoutedEventArgs e) { _lazyTask?.Invoke(); _lazyTask = null; } private void TargetGrid_PointerExited(object sender, PointerRoutedEventArgs e) { Window.Current.CoreWindow.PointerCursor = DefaultCursor; if (_pointerId != null) { _pointerId = null; Opacity = 0; } } private void TargetGrid_PointerEntered(object sender, PointerRoutedEventArgs e) { Window.Current.CoreWindow.PointerCursor = MoveCursor; } private async void Eyedropper_DpiChanged(DisplayInformation sender, object args) { _currentDpi = sender.LogicalDpi; await UpdateAppScreenshotAsync(); } private async void TargetGrid_PointerReleased(object sender, PointerRoutedEventArgs e) { var point = e.GetCurrentPoint(_rootGrid); await InternalPointerReleasedAsync(e.Pointer.PointerId, point.Position); } // Internal abstraction is used by the Unit Tests internal async Task InternalPointerReleasedAsync(uint pointerId, Point position) { if (pointerId == _pointerId) { if (_appScreenshot == null) { await UpdateAppScreenshotAsync(); } UpdateEyedropper(position); _pointerId = null; if (_taskSource != null && !_taskSource.Task.IsCanceled) { _taskSource.TrySetResult(Color); } PickCompleted?.Invoke(this, EventArgs.Empty); } } private void TargetGrid_PointerMoved(object sender, PointerRoutedEventArgs e) { var pointer = e.Pointer; var point = e.GetCurrentPoint(_rootGrid); InternalPointerMoved(pointer.PointerId, point.Position); } // Internal abstraction is used by the Unit Tests internal void InternalPointerMoved(uint pointerId, Point position) { if (pointerId == _pointerId) { UpdateEyedropper(position); } } private async void TargetGrid_PointerPressed(object sender, PointerRoutedEventArgs e) { var point = e.GetCurrentPoint(_rootGrid); await InternalPointerPressedAsync(e.Pointer.PointerId, point.Position, e.Pointer.PointerDeviceType); } // Internal abstraction is used by the Unit Tests internal async Task InternalPointerPressedAsync(uint pointerId, Point position, Windows.Devices.Input.PointerDeviceType pointerDeviceType) { _pointerId = pointerId; PickStarted?.Invoke(this, EventArgs.Empty); await UpdateAppScreenshotAsync(); UpdateEyedropper(position); if (pointerDeviceType == Windows.Devices.Input.PointerDeviceType.Touch) { VisualStateManager.GoToState(this, TouchState, false); } else { VisualStateManager.GoToState(this, MousePenState, false); } if (Opacity < 1) { Opacity = 1; } } private void Eyedropper_Unloaded(object sender, RoutedEventArgs e) { UnhookEvents(); if (_popup != null) { _popup.IsOpen = false; } _appScreenshot?.Dispose(); _appScreenshot = null; Window.Current.CoreWindow.PointerCursor = DefaultCursor; } private void Window_SizeChanged(object sender, WindowSizeChangedEventArgs e) { UpdateRootGridSize(Window.Current.Bounds.Width, Window.Current.Bounds.Height); } private void UpdateRootGridSize(double width, double height) { if (_rootGrid != null) { _rootGrid.Width = width; _rootGrid.Height = height; } } } }
Eyedropper
csharp
dotnet__orleans
src/api/Orleans.Streaming/Orleans.Streaming.cs
{ "start": 104763, "end": 106227 }
partial class ____ : global::Orleans.Runtime.TaskRequest { public global::Orleans.Providers.MemoryMessageData arg0; public override void Dispose() { } public override string GetActivityName() { throw null; } public override object GetArgument(int index) { throw null; } public override int GetArgumentCount() { throw null; } public override string GetInterfaceName() { throw null; } public override System.Type GetInterfaceType() { throw null; } public override System.Reflection.MethodInfo GetMethod() { throw null; } public override string GetMethodName() { throw null; } public override object GetTarget() { throw null; } protected override System.Threading.Tasks.Task InvokeInner() { throw null; } public override void SetArgument(int index, object value) { } public override void SetTarget(global::Orleans.Serialization.Invocation.ITargetHolder holder) { } } [System.CodeDom.Compiler.GeneratedCode("OrleansCodeGen", "9.0.0.0")] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] [global::Orleans.CompoundTypeAlias(new[] { "inv", typeof(global::Orleans.Runtime.GrainReference), typeof(global::Orleans.Providers.IMemoryStreamQueueGrain), "7A8F8C1A" })] public sealed
Invokable_IMemoryStreamQueueGrain_GrainReference_74D60341
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Perception.Spatial.Surfaces/SpatialSurfaceObserver.cs
{ "start": 310, "end": 5669 }
public partial class ____ { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public SpatialSurfaceObserver() { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Perception.Spatial.Surfaces.SpatialSurfaceObserver", "SpatialSurfaceObserver.SpatialSurfaceObserver()"); } #endif // Forced skipping of method Windows.Perception.Spatial.Surfaces.SpatialSurfaceObserver.SpatialSurfaceObserver() #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::System.Collections.Generic.IReadOnlyDictionary<global::System.Guid, global::Windows.Perception.Spatial.Surfaces.SpatialSurfaceInfo> GetObservedSurfaces() { throw new global::System.NotImplementedException("The member IReadOnlyDictionary<Guid, SpatialSurfaceInfo> SpatialSurfaceObserver.GetObservedSurfaces() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IReadOnlyDictionary%3CGuid%2C%20SpatialSurfaceInfo%3E%20SpatialSurfaceObserver.GetObservedSurfaces%28%29"); } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public void SetBoundingVolume(global::Windows.Perception.Spatial.SpatialBoundingVolume bounds) { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Perception.Spatial.Surfaces.SpatialSurfaceObserver", "void SpatialSurfaceObserver.SetBoundingVolume(SpatialBoundingVolume bounds)"); } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public void SetBoundingVolumes(global::System.Collections.Generic.IEnumerable<global::Windows.Perception.Spatial.SpatialBoundingVolume> bounds) { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Perception.Spatial.Surfaces.SpatialSurfaceObserver", "void SpatialSurfaceObserver.SetBoundingVolumes(IEnumerable<SpatialBoundingVolume> bounds)"); } #endif // Forced skipping of method Windows.Perception.Spatial.Surfaces.SpatialSurfaceObserver.ObservedSurfacesChanged.add // Forced skipping of method Windows.Perception.Spatial.Surfaces.SpatialSurfaceObserver.ObservedSurfacesChanged.remove #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static bool IsSupported() { throw new global::System.NotImplementedException("The member bool SpatialSurfaceObserver.IsSupported() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20SpatialSurfaceObserver.IsSupported%28%29"); } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static global::Windows.Foundation.IAsyncOperation<global::Windows.Perception.Spatial.SpatialPerceptionAccessStatus> RequestAccessAsync() { throw new global::System.NotImplementedException("The member IAsyncOperation<SpatialPerceptionAccessStatus> SpatialSurfaceObserver.RequestAccessAsync() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IAsyncOperation%3CSpatialPerceptionAccessStatus%3E%20SpatialSurfaceObserver.RequestAccessAsync%28%29"); } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public event global::Windows.Foundation.TypedEventHandler<global::Windows.Perception.Spatial.Surfaces.SpatialSurfaceObserver, object> ObservedSurfacesChanged { [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] add { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Perception.Spatial.Surfaces.SpatialSurfaceObserver", "event TypedEventHandler<SpatialSurfaceObserver, object> SpatialSurfaceObserver.ObservedSurfacesChanged"); } [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] remove { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Perception.Spatial.Surfaces.SpatialSurfaceObserver", "event TypedEventHandler<SpatialSurfaceObserver, object> SpatialSurfaceObserver.ObservedSurfacesChanged"); } } #endif } }
SpatialSurfaceObserver
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Driver.Tests/Core/Operations/AggregateToCollectionOperationTests.cs
{ "start": 1128, "end": 38984 }
public class ____ : OperationTestBase { private static readonly BsonDocument[] __pipeline = new[] { BsonDocument.Parse("{ $match : { _id : 1 } }"), BsonDocument.Parse("{ $out : \"awesome\" }") }; [Fact] public void Constructor_with_databaseNamespace_should_create_a_valid_instance() { var subject = new AggregateToCollectionOperation(_databaseNamespace, __pipeline, _messageEncoderSettings); subject.CollectionNamespace.Should().BeNull(); subject.DatabaseNamespace.Should().BeSameAs(_databaseNamespace); subject.Pipeline.Should().Equal(__pipeline); subject.MessageEncoderSettings.Should().BeSameAs(_messageEncoderSettings); subject.AllowDiskUse.Should().NotHaveValue(); subject.BypassDocumentValidation.Should().NotHaveValue(); subject.Collation.Should().BeNull(); subject.MaxTime.Should().NotHaveValue(); subject.WriteConcern.Should().BeNull(); } [Fact] public void Constructor_with_collectionNamespace_should_create_a_valid_instance() { var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings); subject.CollectionNamespace.Should().BeSameAs(_collectionNamespace); subject.DatabaseNamespace.Should().BeSameAs(_collectionNamespace.DatabaseNamespace); subject.Pipeline.Should().Equal(__pipeline); subject.MessageEncoderSettings.Should().BeSameAs(_messageEncoderSettings); subject.AllowDiskUse.Should().NotHaveValue(); subject.BypassDocumentValidation.Should().NotHaveValue(); subject.Collation.Should().BeNull(); subject.MaxTime.Should().NotHaveValue(); subject.ReadConcern.Should().BeNull(); subject.WriteConcern.Should().BeNull(); } [Theory] [InlineData("{ $out : 'collection' }", "{ $out : 'collection' }")] [InlineData("{ $out : { db : 'database', coll : 'collection' } }", "{ $out : 'collection' }")] [InlineData("{ $out : { db : 'differentdatabase', coll : 'collection' } }", "{ $out : { db : 'differentdatabase', coll : 'collection' } }")] [InlineData("{ $out : { s3 : { } } }", "{ $out : { s3 : { } } }")] public void Constructor_should_simplify_out_stage_when_possible(string outStageJson, string expectedOutStageJson) { var databaseNamespace = new DatabaseNamespace("database"); var pipeline = new[] { BsonDocument.Parse(outStageJson) }; var messageEncoderSettings = new MessageEncoderSettings(); var subject = new AggregateToCollectionOperation(databaseNamespace, pipeline, messageEncoderSettings); subject.Pipeline.Last().Should().Be(BsonDocument.Parse(expectedOutStageJson)); } [Fact] public void Constructor_should_throw_when_databaseNamespace_is_null() { var exception = Record.Exception(() => new AggregateToCollectionOperation((DatabaseNamespace)null, __pipeline, _messageEncoderSettings)); var argumentNullException = exception.Should().BeOfType<ArgumentNullException>().Subject; argumentNullException.ParamName.Should().Be("databaseNamespace"); } [Fact] public void Constructor_should_throw_when_collectionNamespace_is_null() { var exception = Record.Exception(() => new AggregateToCollectionOperation((CollectionNamespace)null, __pipeline, _messageEncoderSettings)); var argumentNullException = exception.Should().BeOfType<ArgumentNullException>().Subject; argumentNullException.ParamName.Should().Be("collectionNamespace"); } [Fact] public void Constructor_should_throw_when_pipeline_is_null() { var exception = Record.Exception(() => new AggregateToCollectionOperation(_collectionNamespace, null, _messageEncoderSettings)); var argumentNullException = exception.Should().BeOfType<ArgumentNullException>().Subject; argumentNullException.ParamName.Should().Be("pipeline"); } [Fact] public void Constructor_should_throw_when_pipeline_does_not_end_with_out() { var exception = Record.Exception(() => new AggregateToCollectionOperation(_collectionNamespace, Enumerable.Empty<BsonDocument>(), _messageEncoderSettings)); var argumentException = exception.Should().BeOfType<ArgumentException>().Subject; argumentException.ParamName.Should().Be("pipeline"); } [Fact] public void Constructor_should_throw_when_messageEncoderSettings_is_null() { var exception = Record.Exception(() => new AggregateToCollectionOperation(_collectionNamespace, __pipeline, null)); var argumentNullException = exception.Should().BeOfType<ArgumentNullException>().Subject; argumentNullException.ParamName.Should().Be("messageEncoderSettings"); } [Theory] [ParameterAttributeData] public void AllowDiskUse_get_and_set_should_work( [Values(null, false, true)] bool? value) { var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings); subject.AllowDiskUse = value; var result = subject.AllowDiskUse; result.Should().Be(value); } [Theory] [ParameterAttributeData] public void BypassDocumentValidation_get_and_set_should_work( [Values(null, false, true)] bool? value) { var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings); subject.BypassDocumentValidation = value; var result = subject.BypassDocumentValidation; result.Should().Be(value); } [Theory] [ParameterAttributeData] public void Collation_get_and_set_should_work( [Values(null, "en_US")] string locale) { var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings); var value = locale == null ? null : new Collation(locale); subject.Collation = value; var result = subject.Collation; result.Should().BeSameAs(value); } [Fact] public void Comment_get_and_set_should_work() { var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings); var value = (BsonValue)"test"; subject.Comment = value; var result = subject.Comment; result.Should().BeSameAs(value); } [Fact] public void Hint_get_and_set_should_work() { var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings); var value = new BsonDocument("x", 1); subject.Hint = value; var result = subject.Hint; result.Should().BeSameAs(value); } [Fact] public void Let_get_and_set_should_work() { var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings); var value = new BsonDocument("x", "y"); subject.Let = value; var result = subject.Let; result.Should().BeSameAs(value); } [Theory] [ParameterAttributeData] public void MaxTime_get_and_set_should_work( [Values(-10000, 0, 1, 10000, 99999)] long maxTimeTicks) { var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings); var value = TimeSpan.FromTicks(maxTimeTicks); subject.MaxTime = value; var result = subject.MaxTime; result.Should().Be(value); } [Theory] [ParameterAttributeData] public void MaxTime_set_should_throw_when_value_is_invalid( [Values(-10001, -9999, -1)] long maxTimeTicks) { var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings); var value = TimeSpan.FromTicks(maxTimeTicks); var exception = Record.Exception(() => subject.MaxTime = value); var e = exception.Should().BeOfType<ArgumentOutOfRangeException>().Subject; e.ParamName.Should().Be("value"); } [Theory] [ParameterAttributeData] public void ReadConcern_get_and_set_should_work([Values(ReadConcernLevel.Local, ReadConcernLevel.Majority)] ReadConcernLevel level) { var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings); var value = new ReadConcern(new Optional<ReadConcernLevel?>(level)); subject.ReadConcern = value; var result = subject.ReadConcern; result.Should().BeSameAs(value); } [Fact] public void ReadPreference_get_and_set_should_work() { var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings); var value = new ReadPreference(ReadPreferenceMode.Primary); subject.ReadPreference = value; var result = subject.ReadPreference; result.Should().BeSameAs(value); } [Theory] [ParameterAttributeData] public void WriteConcern_get_and_set_should_work( [Values(1, 2)] int w) { var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings); var value = new WriteConcern(w); subject.WriteConcern = value; var result = subject.WriteConcern; result.Should().BeSameAs(value); } [Theory] [InlineData(WireVersion.Server49, false)] [InlineData(WireVersion.Server50, true)] public void CanUseSecondary_should_return_expected_result(int maxWireVersion, bool expectedResult) { var subject = new AggregateToCollectionOperation.MayUseSecondary(ReadPreference.Secondary); var clusterId = new ClusterId(1); var endPoint = new DnsEndPoint("localhost", 27017); var serverId = new ServerId(clusterId, endPoint); var serverDescription = new ServerDescription(serverId, endPoint, wireVersionRange: new Range<int>(0, maxWireVersion)); var result = subject.CanUseSecondary(serverDescription); result.Should().Be(expectedResult); } [Fact] public void CreateCommand_should_return_expected_result() { var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings); var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); var expectedResult = new BsonDocument { { "aggregate", _collectionNamespace.CollectionName }, { "pipeline", new BsonArray(__pipeline) }, { "cursor", new BsonDocument() } }; result.Should().Be(expectedResult); } [Theory] [ParameterAttributeData] public void CreateCommand_should_return_expected_result_when_AllowDiskUse_is_set( [Values(null, false, true)] bool? allowDiskUse) { var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings) { AllowDiskUse = allowDiskUse }; var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); var expectedResult = new BsonDocument { { "aggregate", _collectionNamespace.CollectionName }, { "pipeline", new BsonArray(__pipeline) }, { "allowDiskUse", () => allowDiskUse.Value, allowDiskUse != null }, { "cursor", new BsonDocument() } }; result.Should().Be(expectedResult); } [Theory] [ParameterAttributeData] public void CreateCommand_should_return_expected_result_when_BypassDocumentValidation_is_set( [Values(null, false, true)] bool? bypassDocumentValidation) { var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings) { BypassDocumentValidation = bypassDocumentValidation }; var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); var expectedResult = new BsonDocument { { "aggregate", _collectionNamespace.CollectionName }, { "pipeline", new BsonArray(__pipeline) }, { "bypassDocumentValidation", () => bypassDocumentValidation.Value, bypassDocumentValidation != null }, { "cursor", new BsonDocument() } }; result.Should().Be(expectedResult); } [Theory] [ParameterAttributeData] public void CreateCommand_should_return_expected_result_when_Collation_is_set( [Values(null, "en_US")] string locale) { var collation = locale == null ? null : new Collation(locale); var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings) { Collation = collation }; var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); var expectedResult = new BsonDocument { { "aggregate", _collectionNamespace.CollectionName }, { "pipeline", new BsonArray(__pipeline) }, { "collation", () => collation.ToBsonDocument(), collation != null }, { "cursor", new BsonDocument() } }; result.Should().Be(expectedResult); } [Theory] [ParameterAttributeData] public void CreateCommand_should_return_expected_result_when_Comment_is_set( [Values(null, "test")] string comment) { var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings) { Comment = comment, }; var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); var expectedResult = new BsonDocument { { "aggregate", _collectionNamespace.CollectionName }, { "pipeline", new BsonArray(__pipeline) }, { "cursor", new BsonDocument() }, { "comment", () => comment, comment != null } }; result.Should().Be(expectedResult); } [Theory] [ParameterAttributeData] public void CreateCommand_should_return_the_expected_result_when_Hint_is_set( [Values(null, "{x: 1}")] string hintJson) { var hint = hintJson == null ? null : BsonDocument.Parse(hintJson); var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings) { Hint = hint }; var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); var expectedResult = new BsonDocument { { "aggregate", _collectionNamespace.CollectionName }, { "pipeline", new BsonArray(__pipeline) }, { "cursor", new BsonDocument() }, { "hint", () => hint, hint != null } }; result.Should().Be(expectedResult); } [Theory] [ParameterAttributeData] public void CreateCommand_should_return_the_expected_result_when_Let_is_set( [Values(null, "{ y : 'z' }")] string letJson) { var let = letJson == null ? null : BsonDocument.Parse(letJson); var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings) { Let = let }; var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); var expectedResult = new BsonDocument { { "aggregate", _collectionNamespace.CollectionName }, { "pipeline", new BsonArray(__pipeline) }, { "cursor", new BsonDocument() }, { "let", () => let, let != null } }; result.Should().Be(expectedResult); } [Theory] [InlineData(-10000, 0)] [InlineData(0, 0)] [InlineData(1, 1)] [InlineData(9999, 1)] [InlineData(10000, 1)] [InlineData(10001, 2)] public void CreateCommand_should_return_expected_result_when_MaxTime_is_set(long maxTimeTicks, int expectedMaxTimeMS) { var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings) { MaxTime = TimeSpan.FromTicks(maxTimeTicks) }; var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); var expectedResult = new BsonDocument { { "aggregate", _collectionNamespace.CollectionName }, { "pipeline", new BsonArray(__pipeline) }, { "maxTimeMS", expectedMaxTimeMS }, { "cursor", new BsonDocument() } }; result.Should().Be(expectedResult); result["maxTimeMS"].BsonType.Should().Be(BsonType.Int32); } [Theory] [InlineData(42)] [InlineData(-1)] public void CreateCommand_should_ignore_maxtime_if_timeout_specified(int timeoutMs) { var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings) { MaxTime = TimeSpan.FromTicks(10) }; var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); var operationContext = new OperationContext(TimeSpan.FromMilliseconds(timeoutMs), CancellationToken.None); var result = subject.CreateCommand(operationContext, session, connectionDescription); result.Should().NotContain("maxTimeMS"); } [Theory] [ParameterAttributeData] public void CreateCommand_should_return_expected_result_when_ReadConcern_is_set( [Values(ReadConcernLevel.Majority)] ReadConcernLevel readConcernLevel, [Values(false, true)] bool withReadConcern) { var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings); if (withReadConcern) { subject.ReadConcern = new ReadConcern(readConcernLevel); }; var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); var expectedResult = new BsonDocument { { "aggregate", _collectionNamespace.CollectionName }, { "pipeline", new BsonArray(__pipeline) }, { "readConcern", () => subject.ReadConcern.ToBsonDocument(), withReadConcern }, { "cursor", new BsonDocument() } }; result.Should().Be(expectedResult); } [Theory] [ParameterAttributeData] public void CreateCommand_should_return_expected_result_when_WriteConcern_is_set( [Values(null, 1, 2)] int? w) { var writeConcern = w.HasValue ? new WriteConcern(w.Value) : null; var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings) { WriteConcern = writeConcern }; var session = OperationTestHelper.CreateSession(); var connectionDescription = OperationTestHelper.CreateConnectionDescription(); var result = subject.CreateCommand(OperationContext.NoTimeout, session, connectionDescription); var expectedResult = new BsonDocument { { "aggregate", _collectionNamespace.CollectionName }, { "pipeline", new BsonArray(__pipeline) }, { "writeConcern", () => writeConcern.ToBsonDocument(), writeConcern != null }, { "cursor", new BsonDocument() } }; result.Should().Be(expectedResult); } [Theory] [ParameterAttributeData] public void Execute_should_return_expected_result( [Values("$out", "$merge")] string lastStageName, [Values(false, true)] bool usingDifferentOutputDatabase, [Values(false, true)] bool async) { RequireServer.Check(); var pipeline = new List<BsonDocument> { BsonDocument.Parse("{ $match : { _id : 1 } }") }; var inputDatabaseName = _databaseNamespace.DatabaseName; var inputCollectionName = _collectionNamespace.CollectionName; var outputDatabaseName = usingDifferentOutputDatabase ? $"{inputDatabaseName}-outputdatabase" : inputDatabaseName; var outputCollectionName = $"{inputCollectionName}-outputcollection"; switch (lastStageName) { case "$out": if (usingDifferentOutputDatabase) { RequireServer.Check().Supports(Feature.AggregateOutToDifferentDatabase); pipeline.Add(BsonDocument.Parse($"{{ $out : {{ db : '{outputDatabaseName}', coll : '{outputCollectionName}' }} }}")); } else { pipeline.Add(BsonDocument.Parse($"{{ $out : '{outputCollectionName}' }}")); } break; case "$merge": RequireServer.Check().Supports(Feature.AggregateMerge); if (usingDifferentOutputDatabase) { pipeline.Add(BsonDocument.Parse($"{{ $merge : {{ into : {{ db : '{outputDatabaseName}', coll : '{outputCollectionName}' }} }} }}")); } else { pipeline.Add(BsonDocument.Parse($"{{ $merge : {{ into : '{outputDatabaseName}' }} }}")); } break; default: throw new Exception($"Unexpected lastStageName: \"{lastStageName}\"."); } EnsureTestData(); if (usingDifferentOutputDatabase) { EnsureDatabaseExists(outputDatabaseName); } var subject = new AggregateToCollectionOperation(_collectionNamespace, pipeline, _messageEncoderSettings); ExecuteOperation(subject, async); var result = ReadAllFromCollection(new CollectionNamespace(new DatabaseNamespace(outputDatabaseName), outputCollectionName), async); result.Should().NotBeNull(); result.Should().HaveCount(1); } [Theory] [ParameterAttributeData] public void Execute_to_time_series_collection_should_work( [Values(false, true)] bool usingDifferentOutputDatabase, [Values(false, true)] bool async) { RequireServer.Check().Supports(Feature.AggregateOutTimeSeries); var pipeline = new List<BsonDocument> { BsonDocument.Parse("{ $match : { _id : 1 } }") }; var inputDatabaseName = _databaseNamespace.DatabaseName; var inputCollectionName = _collectionNamespace.CollectionName; var outputDatabaseName = usingDifferentOutputDatabase ? $"{inputDatabaseName}-outputdatabase-timeseries" : inputDatabaseName; var outputCollectionName = $"{inputCollectionName}-outputcollection-timeseries"; pipeline.Add(new BsonDocument { {"$set", new BsonDocument { {"time", DateTime.Now } } } } ); pipeline.Add(BsonDocument.Parse($"{{ $out : {{ db : '{outputDatabaseName}', coll : '{outputCollectionName}', timeseries: {{ timeField: 'time' }} }} }}")); EnsureTestData(); if (usingDifferentOutputDatabase) { EnsureDatabaseExists(outputDatabaseName); } var subject = new AggregateToCollectionOperation(_collectionNamespace, pipeline, _messageEncoderSettings); ExecuteOperation(subject, async); var databaseNamespace = new DatabaseNamespace(outputDatabaseName); var result = ReadAllFromCollection(new CollectionNamespace(databaseNamespace, outputCollectionName), async); result.Should().NotBeNull(); result.Should().HaveCount(1); var output = ListCollections(databaseNamespace); output["cursor"]["firstBatch"][0][0].ToString().Should().Be($"{outputCollectionName}"); // checking name of collection output["cursor"]["firstBatch"][0][1].ToString().Should().Be("timeseries"); // checking type of collection } [Theory] [ParameterAttributeData] public void Execute_should_return_expected_result_when_AllowDiskUse_is_set( [Values(null, false, true)] bool? allowDiskUse, [Values(false, true)] bool async) { RequireServer.Check(); EnsureTestData(); var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings) { AllowDiskUse = allowDiskUse }; ExecuteOperation(subject, async); var result = ReadAllFromCollection(new CollectionNamespace(_databaseNamespace, "awesome"), async); result.Should().NotBeNull(); result.Should().HaveCount(1); } [Theory] [ParameterAttributeData] public void Execute_should_return_expected_result_when_BypassDocumentValidation_is_set( [Values(null, false, true)] bool? bypassDocumentValidation, [Values(false, true)] bool async) { RequireServer.Check(); EnsureTestData(); var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings) { BypassDocumentValidation = bypassDocumentValidation }; ExecuteOperation(subject, async); var result = ReadAllFromCollection(new CollectionNamespace(_databaseNamespace, "awesome"), async); result.Should().NotBeNull(); result.Should().HaveCount(1); } [Theory] [ParameterAttributeData] public void Execute_should_return_expected_result_when_Collation_is_set( [Values(false, true)] bool caseSensitive, [Values(false, true)] bool async) { RequireServer.Check(); EnsureTestData(); var pipeline = new[] { BsonDocument.Parse("{ $match : { x : \"x\" } }"), BsonDocument.Parse("{ $out : \"awesome\" }") }; var collation = new Collation("en_US", caseLevel: caseSensitive, strength: CollationStrength.Primary); var subject = new AggregateToCollectionOperation(_collectionNamespace, pipeline, _messageEncoderSettings) { Collation = collation }; ExecuteOperation(subject, async); var result = ReadAllFromCollection(new CollectionNamespace(_databaseNamespace, "awesome"), async); result.Should().NotBeNull(); result.Should().HaveCount(caseSensitive ? 1 : 2); } [Theory] [ParameterAttributeData] public void Execute_should_throw_when_maxTime_is_exceeded( [Values(false, true)] bool async) { RequireServer.Check().ClusterTypes(ClusterType.Standalone, ClusterType.ReplicaSet); var pipeline = new[] { BsonDocument.Parse("{ $match : { x : \"x\" } }"), BsonDocument.Parse("{ $out : \"awesome\" }") }; var subject = new AggregateToCollectionOperation(_collectionNamespace, pipeline, _messageEncoderSettings) { MaxTime = TimeSpan.FromSeconds(9001) }; using (var failPoint = FailPoint.ConfigureAlwaysOn(_cluster, _session, FailPointName.MaxTimeAlwaysTimeout)) { var exception = Record.Exception(() => ExecuteOperation(subject, failPoint.Binding, async)); exception.Should().BeOfType<MongoExecutionTimeoutException>(); } } [Theory] [ParameterAttributeData] public void Execute_should_return_expected_result_when_Comment_is_set( [Values(false, true)] bool async) { RequireServer.Check().ClusterTypes(ClusterType.Standalone, ClusterType.ReplicaSet); EnsureTestData(); var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings) { Comment = "test" }; using (var profile = Profile(_collectionNamespace.DatabaseNamespace)) { ExecuteOperation(subject, async); var result = ReadAllFromCollection(new CollectionNamespace(_databaseNamespace, "awesome"), async); result.Should().NotBeNull(); var profileEntries = profile.Find(new BsonDocument("command.aggregate", new BsonDocument("$exists", true))); profileEntries.Should().HaveCount(1); profileEntries[0]["command"]["comment"].Should().Be(subject.Comment); } } [Theory] [ParameterAttributeData] public void Execute_should_return_expected_result_when_Hint_is_set( [Values(false, true)] bool async) { RequireServer.Check(); EnsureTestData(); var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings) { Hint = "_id_" }; ExecuteOperation(subject, async); var result = ReadAllFromCollection(new CollectionNamespace(_databaseNamespace, "awesome"), async); result.Should().NotBeNull(); } [Theory] [ParameterAttributeData] public void Execute_should_return_expected_result_when_Let_is_set_with_match_expression( [Values(false, true)] bool async) { RequireServer.Check().Supports(Feature.AggregateOptionsLet); EnsureTestData(); var pipeline = new[] { BsonDocument.Parse("{ $match : { $expr : { $eq : [ '$x', '$$y'] } } }"), BsonDocument.Parse("{ $out : \"awesome\" }") }; var subject = new AggregateToCollectionOperation(_collectionNamespace, pipeline, _messageEncoderSettings) { Let = new BsonDocument("y", "x") }; ExecuteOperation(subject, async); var result = ReadAllFromCollection(new CollectionNamespace(_databaseNamespace, "awesome"), async); result.Should().BeEquivalentTo(new[] { new BsonDocument { { "_id", 1 }, { "x", "x" } } }); } [Theory] [ParameterAttributeData] public void Execute_should_return_expected_result_when_Let_is_set_with_project( [Values(false, true)] bool async) { RequireServer.Check().Supports(Feature.AggregateOptionsLet); EnsureTestData(); var pipeline = new[] { BsonDocument.Parse("{ $project : { y : '$$z' } }"), BsonDocument.Parse("{ $out : \"awesome\" }") }; var subject = new AggregateToCollectionOperation(_collectionNamespace, pipeline, _messageEncoderSettings) { Let = new BsonDocument("z", "x") }; ExecuteOperation(subject, async); var result = ReadAllFromCollection(new CollectionNamespace(_databaseNamespace, "awesome"), async); result.Should().BeEquivalentTo(new[] { new BsonDocument { { "_id", 1 }, { "y", "x" } }, new BsonDocument { { "_id", 2 }, { "y", "x" } } }); } [Theory] [ParameterAttributeData] public void Execute_should_return_expected_result_when_MaxTime_is_set( [Values(null, 1000)] int? milliseconds, [Values(false, true)] bool async) { RequireServer.Check(); EnsureTestData(); var maxTime = milliseconds == null ? (TimeSpan?)null : TimeSpan.FromMilliseconds(milliseconds.Value); var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings) { MaxTime = maxTime }; ExecuteOperation(subject, async); var result = ReadAllFromCollection(new CollectionNamespace(_databaseNamespace, "awesome"), async); result.Should().NotBeNull(); result.Should().HaveCount(1); } [Theory] [ParameterAttributeData] public void Execute_should_throw_when_a_write_concern_error_occurs( [Values(false, true)] bool async) { RequireServer.Check().ClusterType(ClusterType.ReplicaSet); EnsureTestData(); var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings) { WriteConcern = new WriteConcern(9) }; var exception = Record.Exception(() => ExecuteOperation(subject, async)); exception.Should().BeOfType<MongoWriteConcernException>(); } [Theory] [ParameterAttributeData] public void Execute_should_send_session_id_when_supported( [Values(false, true)] bool async) { RequireServer.Check(); EnsureTestData(); var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings); VerifySessionIdWasSentWhenSupported(subject, "aggregate", async); } [Theory] [ParameterAttributeData] public async Task Execute_should_set_operation_name([Values(false, true)] bool async) { RequireServer.Check(); var subject = new AggregateToCollectionOperation(_collectionNamespace, __pipeline, _messageEncoderSettings); await VerifyOperationNameIsSet(subject, async, "aggregate"); } // private methods private void EnsureTestData() { RunOncePerFixture(() => { DropCollection(); Insert(new BsonDocument { { "_id", 1 }, { "x", "x" } }); Insert(new BsonDocument { { "_id", 2 }, { "x", "X" } }); }); } } }
AggregateToCollectionOperationTests
csharp
nunit__nunit
src/NUnitFramework/framework/Attributes/TestOfAttribute.cs
{ "start": 216, "end": 440 }
class ____ assembly, test fixture or test method is testing. /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false)]
the
csharp
PrismLibrary__Prism
src/Maui/Prism.Maui/Navigation/Xaml/NavigationExtensionBase.cs
{ "start": 189, "end": 306 }
class ____ navigation extensions in XAML, implementing <see cref="ICommand"/> for navigation actions. /// </summary>
for
csharp
dotnet__orleans
src/api/Azure/Orleans.Streaming.AzureStorage/Orleans.Streaming.AzureStorage.cs
{ "start": 9223, "end": 10168 }
partial class ____ { public static ISiloBuilder AddAzureQueueStreams(this ISiloBuilder builder, string name, System.Action<Microsoft.Extensions.Options.OptionsBuilder<Configuration.AzureQueueOptions>> configureOptions) { throw null; } public static ISiloBuilder AddAzureQueueStreams(this ISiloBuilder builder, string name, System.Action<SiloAzureQueueStreamConfigurator> configure) { throw null; } public static ISiloBuilder UseAzureBlobLeaseProvider(this ISiloBuilder builder, System.Action<Microsoft.Extensions.Options.OptionsBuilder<Configuration.AzureBlobLeaseProviderOptions>> configureOptions) { throw null; } public static void UseAzureBlobLeaseProvider(this ISiloPersistentStreamConfigurator configurator, System.Action<Microsoft.Extensions.Options.OptionsBuilder<Configuration.AzureBlobLeaseProviderOptions>> configureOptions) { } } } namespace Orleans.LeaseProviders {
SiloBuilderExtensions
csharp
open-telemetry__opentelemetry-dotnet
src/OpenTelemetry.Api/Internal/OpenTelemetryApiEventSource.cs
{ "start": 329, "end": 3484 }
internal sealed class ____ : EventSource { public static readonly OpenTelemetryApiEventSource Log = new(); [NonEvent] public void ActivityContextExtractException(string format, Exception ex) { if (this.IsEnabled(EventLevel.Warning, EventKeywords.All)) { this.FailedToExtractActivityContext(format, ex.ToInvariantString()); } } [NonEvent] public void BaggageExtractException(string format, Exception ex) { if (this.IsEnabled(EventLevel.Warning, EventKeywords.All)) { this.FailedToExtractBaggage(format, ex.ToInvariantString()); } } [NonEvent] public void TracestateExtractException(Exception ex) { if (this.IsEnabled(EventLevel.Warning, EventKeywords.All)) { this.TracestateExtractError(ex.ToInvariantString()); } } [NonEvent] public void TracestateKeyIsInvalid(ReadOnlySpan<char> key) { if (this.IsEnabled(EventLevel.Warning, EventKeywords.All)) { this.TracestateKeyIsInvalid(key.ToString()); } } [NonEvent] public void TracestateValueIsInvalid(ReadOnlySpan<char> value) { if (this.IsEnabled(EventLevel.Warning, EventKeywords.All)) { this.TracestateValueIsInvalid(value.ToString()); } } [Event(3, Message = "Failed to parse tracestate: too many items", Level = EventLevel.Warning)] public void TooManyItemsInTracestate() { this.WriteEvent(3); } [Event(4, Message = "Tracestate key is invalid, key = '{0}'", Level = EventLevel.Warning)] public void TracestateKeyIsInvalid(string key) { this.WriteEvent(4, key); } [Event(5, Message = "Tracestate value is invalid, value = '{0}'", Level = EventLevel.Warning)] public void TracestateValueIsInvalid(string value) { this.WriteEvent(5, value); } [Event(6, Message = "Tracestate parse error: '{0}'", Level = EventLevel.Warning)] public void TracestateExtractError(string error) { this.WriteEvent(6, error); } [Event(8, Message = "Failed to extract activity context in format: '{0}', context: '{1}'.", Level = EventLevel.Warning)] public void FailedToExtractActivityContext(string format, string exception) { this.WriteEvent(8, format, exception); } [Event(9, Message = "Failed to inject activity context in format: '{0}', context: '{1}'.", Level = EventLevel.Warning)] public void FailedToInjectActivityContext(string format, string error) { this.WriteEvent(9, format, error); } [Event(10, Message = "Failed to extract baggage in format: '{0}', baggage: '{1}'.", Level = EventLevel.Warning)] public void FailedToExtractBaggage(string format, string exception) { this.WriteEvent(10, format, exception); } [Event(11, Message = "Failed to inject baggage in format: '{0}', baggage: '{1}'.", Level = EventLevel.Warning)] public void FailedToInjectBaggage(string format, string error) { this.WriteEvent(11, format, error); } }
OpenTelemetryApiEventSource
csharp
dotnet__machinelearning
src/Microsoft.ML.Data/Transforms/NormalizeColumnDbl.cs
{ "start": 16315, "end": 19706 }
internal sealed class ____ { private readonly bool _useLog; private readonly Double[] _mean; private readonly Double[] _m2; private readonly long[] _cnan; private readonly long[] _cnz; private long _trainCount; public MeanVarDblAggregator(int size, bool useLog) { _useLog = useLog; _mean = new Double[size]; _m2 = new Double[size]; if (!_useLog) _cnan = new long[size]; _cnz = new long[size]; } public long[] Counts { get { return _cnz; } } public Double[] Mean { get { return _mean; } } public Double[] StdDevPopulation { get { return _m2.Select((m2, i) => Math.Sqrt(m2 / _cnz[i])).ToArray(); } } public Double[] StdDevSample { get { return _m2.Select((m2, i) => Math.Sqrt(m2 / Math.Max(0, _cnz[i] - 1))).ToArray(); } } public Double[] MeanSquareError { get { return _m2.Select((m2, i) => m2 / _cnz[i]).ToArray(); } } public Double[] SampleVariance { get { return _m2.Select((m2, i) => m2 / Math.Max(0, _cnz[i] - 1)).ToArray(); } } public Double[] M2 { get { return _m2; } } public void ProcessValue(in VBuffer<TFloat> value) { _trainCount++; var size = _mean.Length; var values = value.GetValues(); Contracts.Assert(0 <= values.Length && values.Length <= size); if (values.Length == 0) return; if (values.Length == size) { for (int j = 0; j < values.Length; j++) { var origVal = values[j]; Update(j, origVal); } } else { var indices = value.GetIndices(); for (int k = 0; k < values.Length; k++) { var origVal = values[k]; var j = indices[k]; Update(j, origVal); } } } public void Finish() { if (!_useLog) { for (int i = 0; i < _mean.Length; i++) { Contracts.Assert(_trainCount >= _cnan[i] + _cnz[i]); MeanVarUtils.AdjustForZeros(ref _mean[i], ref _m2[i], ref _cnz[i], _trainCount - _cnan[i] - _cnz[i]); } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void Update(int j, TFloat origVal) { if (origVal == 0) return; var val = _useLog ? (TFloat)Math.Log(origVal) : origVal; if (!FloatUtils.IsFinite(val)) { if (!_useLog) _cnan[j]++; return; } _cnz[j]++; var delta = val - _mean[j]; _mean[j] += delta / _cnz[j]; var dm2 = delta * (val - _mean[j]); Contracts.Assert(dm2 >= 0); _m2[j] += dm2; Contracts.Assert(_m2[j] >= 0); } } [BestFriend] internal static
MeanVarDblAggregator
csharp
App-vNext__Polly
test/Polly.Specs/Helpers/Custom/AddBehaviourIfHandle/AddBehaviourIfHandleSyntax.cs
{ "start": 61, "end": 705 }
internal static class ____ { internal static AddBehaviourIfHandlePolicy WithBehaviour(this PolicyBuilder policyBuilder, Action<Exception> behaviourIfHandle) { behaviourIfHandle.ShouldNotBeNull(); return new AddBehaviourIfHandlePolicy(behaviourIfHandle, policyBuilder); } internal static AddBehaviourIfHandlePolicy<TResult> WithBehaviour<TResult>(this PolicyBuilder<TResult> policyBuilder, Action<DelegateResult<TResult>> behaviourIfHandle) { behaviourIfHandle.ShouldNotBeNull(); return new AddBehaviourIfHandlePolicy<TResult>(behaviourIfHandle, policyBuilder); } }
AddBehaviourIfHandleSyntax
csharp
dotnet__maui
src/Controls/samples/Controls.Sample/Pages/Controls/GalleryBuilder.cs
{ "start": 170, "end": 800 }
public static class ____ { public static Button NavButton(string galleryName, Func<Page> gallery, INavigation nav) { var automationId = System.Text.RegularExpressions.Regex.Replace(galleryName, " |\\(|\\)", string.Empty); var button = new Button { Text = $"{galleryName}", AutomationId = automationId, FontSize = 10, HeightRequest = DeviceInfo.Platform == DevicePlatform.Android ? 40 : 30, HorizontalOptions = LayoutOptions.Fill, Margin = 5, Padding = 5 }; button.Clicked += async (sender, args) => { await nav.PushAsync(gallery()); }; return button; } } }
GalleryBuilder
csharp
dotnet__maui
src/Controls/src/Core/IViewContainer.cs
{ "start": 90, "end": 185 }
public interface ____<T> where T : VisualElement { IList<T> Children { get; } } }
IViewContainer
csharp
ServiceStack__ServiceStack
ServiceStack.Redis/tests/ServiceStack.Redis.Tests/RedisPubSubTests.Async.cs
{ "start": 236, "end": 12509 }
public class ____ : RedisClientTestsBaseAsync { public override void OnBeforeEachTest() { base.OnBeforeEachTest(); RedisRaw.NamespacePrefix = "RedisPubSubTests"; } [Test] public async Task Can_Subscribe_and_Publish_single_message() { var channelName = PrefixedKey("CHANNEL1"); const string message = "Hello, World!"; var key = PrefixedKey("Can_Subscribe_and_Publish_single_message"); await RedisAsync.IncrementValueAsync(key); await using (var subscription = await RedisAsync.CreateSubscriptionAsync()) { subscription.OnSubscribeAsync += channel => { Log("Subscribed to '{0}'", channel); Assert.That(channel, Is.EqualTo(channelName)); return default; }; subscription.OnUnSubscribeAsync += channel => { Log("UnSubscribed from '{0}'", channel); Assert.That(channel, Is.EqualTo(channelName)); return default; }; subscription.OnMessageAsync += async (channel, msg) => { Log("Received '{0}' from channel '{1}'", msg, channel); Assert.That(channel, Is.EqualTo(channelName)); Assert.That(msg, Is.EqualTo(message)); await subscription.UnSubscribeFromAllChannelsAsync(); }; ThreadPool.QueueUserWorkItem(async x => { await Task.Delay(100); // to be sure that we have subscribers await using var redisClient = CreateRedisClient().ForAsyncOnly(); Log("Publishing '{0}' to '{1}'", message, channelName); await redisClient.PublishMessageAsync(channelName, message); }); Log("Start Listening On " + channelName); await subscription.SubscribeToChannelsAsync(new[] { channelName }); //blocking } Log("Using as normal client again..."); await RedisAsync.IncrementValueAsync(key); Assert.That(await RedisAsync.GetAsync<int>(key), Is.EqualTo(2)); } [Test] public async Task Can_Subscribe_and_Publish_single_message_using_wildcard() { var channelWildcard = PrefixedKey("CHANNEL.*"); var channelName = PrefixedKey("CHANNEL.1"); const string message = "Hello, World!"; var key = PrefixedKey("Can_Subscribe_and_Publish_single_message"); await RedisAsync.IncrementValueAsync(key); await using (var subscription = await RedisAsync.CreateSubscriptionAsync()) { subscription.OnSubscribeAsync += channel => { Log("Subscribed to '{0}'", channelWildcard); Assert.That(channel, Is.EqualTo(channelWildcard)); return default; }; subscription.OnUnSubscribeAsync += channel => { Log("UnSubscribed from '{0}'", channelWildcard); Assert.That(channel, Is.EqualTo(channelWildcard)); return default; }; subscription.OnMessageAsync += async (channel, msg) => { Log("Received '{0}' from channel '{1}'", msg, channel); Assert.That(channel, Is.EqualTo(channelName)); Assert.That(msg, Is.EqualTo(message), "we should get the message, not the channel"); await subscription.UnSubscribeFromChannelsMatchingAsync(new string[0]); }; ThreadPool.QueueUserWorkItem(async x => { await Task.Delay(100); // to be sure that we have subscribers await using var redisClient = CreateRedisClient().ForAsyncOnly(); Log("Publishing '{0}' to '{1}'", message, channelName); await redisClient.PublishMessageAsync(channelName, message); }); Log("Start Listening On " + channelName); await subscription.SubscribeToChannelsMatchingAsync(new[] { channelWildcard }); //blocking } Log("Using as normal client again..."); await RedisAsync.IncrementValueAsync(key); Assert.That(await RedisAsync.GetAsync<int>(key), Is.EqualTo(2)); } [Test] public async Task Can_Subscribe_and_Publish_multiple_message() { var channelName = PrefixedKey("CHANNEL2"); const string messagePrefix = "MESSAGE "; string key = PrefixedKey("Can_Subscribe_and_Publish_multiple_message"); const int publishMessageCount = 5; var messagesReceived = 0; await RedisAsync.IncrementValueAsync(key); await using (var subscription = await RedisAsync.CreateSubscriptionAsync()) { subscription.OnSubscribeAsync += channel => { Log("Subscribed to '{0}'", channel); Assert.That(channel, Is.EqualTo(channelName)); return default; }; subscription.OnUnSubscribeAsync += channel => { Log("UnSubscribed from '{0}'", channel); Assert.That(channel, Is.EqualTo(channelName)); return default; }; subscription.OnMessageAsync += async (channel, msg) => { Log("Received '{0}' from channel '{1}'", msg, channel); Assert.That(channel, Is.EqualTo(channelName)); Assert.That(msg, Is.EqualTo(messagePrefix + messagesReceived++)); if (messagesReceived == publishMessageCount) { await subscription.UnSubscribeFromAllChannelsAsync(); } }; ThreadPool.QueueUserWorkItem(async x => { await Task.Delay(100); // to be sure that we have subscribers await using var redisClient = CreateRedisClient().ForAsyncOnly(); for (var i = 0; i < publishMessageCount; i++) { var message = messagePrefix + i; Log("Publishing '{0}' to '{1}'", message, channelName); await redisClient.PublishMessageAsync(channelName, message); } }); Log("Start Listening On"); await subscription.SubscribeToChannelsAsync(new[] { channelName }); //blocking } Log("Using as normal client again..."); await RedisAsync.IncrementValueAsync(key); Assert.That(await RedisAsync.GetAsync<int>(key), Is.EqualTo(2)); Assert.That(messagesReceived, Is.EqualTo(publishMessageCount)); } [Test] public async Task Can_Subscribe_and_Publish_message_to_multiple_channels() { var channelPrefix = PrefixedKey("CHANNEL3 "); const string message = "MESSAGE"; const int publishChannelCount = 5; var key = PrefixedKey("Can_Subscribe_and_Publish_message_to_multiple_channels"); var channels = new List<string>(); publishChannelCount.Times(i => channels.Add(channelPrefix + i)); var messagesReceived = 0; var channelsSubscribed = 0; var channelsUnSubscribed = 0; await RedisAsync.IncrementValueAsync(key); await using (var subscription = await RedisAsync.CreateSubscriptionAsync()) { subscription.OnSubscribeAsync += channel => { Log("Subscribed to '{0}'", channel); Assert.That(channel, Is.EqualTo(channelPrefix + channelsSubscribed++)); return default; }; subscription.OnUnSubscribeAsync += channel => { Log("UnSubscribed from '{0}'", channel); Assert.That(channel, Is.EqualTo(channelPrefix + channelsUnSubscribed++)); return default; }; subscription.OnMessageAsync += async (channel, msg) => { Log("Received '{0}' from channel '{1}'", msg, channel); Assert.That(channel, Is.EqualTo(channelPrefix + messagesReceived++)); Assert.That(msg, Is.EqualTo(message)); await subscription.UnSubscribeFromChannelsAsync(new[] { channel }); }; ThreadPool.QueueUserWorkItem(async x => { await Task.Delay(100); // to be sure that we have subscribers await using var redisClient = CreateRedisClient().ForAsyncOnly(); foreach (var channel in channels) { Log("Publishing '{0}' to '{1}'", message, channel); await redisClient.PublishMessageAsync(channel, message); } }); Log("Start Listening On"); await subscription.SubscribeToChannelsAsync(channels.ToArray()); //blocking } Log("Using as normal client again..."); await RedisAsync.IncrementValueAsync(key); Assert.That(await RedisAsync.GetAsync<int>(key), Is.EqualTo(2)); Assert.That(messagesReceived, Is.EqualTo(publishChannelCount)); Assert.That(channelsSubscribed, Is.EqualTo(publishChannelCount)); Assert.That(channelsUnSubscribed, Is.EqualTo(publishChannelCount)); } [Test] public async Task Can_Subscribe_to_channel_pattern() { int msgs = 0; await using var subscription = await RedisAsync.CreateSubscriptionAsync(); subscription.OnMessageAsync += async (channel, msg) => { Debug.WriteLine(String.Format("{0}: {1}", channel, msg + msgs++)); await subscription.UnSubscribeFromChannelsMatchingAsync(new[] { PrefixedKey("CHANNEL4:TITLE*") }); }; ThreadPool.QueueUserWorkItem(async x => { await Task.Delay(100); // to be sure that we have subscribers await using var redisClient = CreateRedisClient().ForAsyncOnly(); Log("Publishing msg..."); await redisClient.PublishMessageAsync(PrefixedKey("CHANNEL4:TITLE1"), "hello"); // .ToUtf8Bytes() }); Log("Start Listening On"); await subscription.SubscribeToChannelsMatchingAsync(new[] { PrefixedKey("CHANNEL4:TITLE*") }); } [Test] public async Task Can_Subscribe_to_multiplechannel_pattern() { var channels = new[] { PrefixedKey("CHANNEL5:TITLE*"), PrefixedKey("CHANNEL5:BODY*") }; int msgs = 0; await using var subscription = await RedisAsync.CreateSubscriptionAsync(); subscription.OnMessageAsync += async (channel, msg) => { Debug.WriteLine(String.Format("{0}: {1}", channel, msg + msgs++)); await subscription.UnSubscribeFromChannelsMatchingAsync(channels); }; ThreadPool.QueueUserWorkItem(async x => { await Task.Delay(100); // to be sure that we have subscribers await using var redisClient = CreateRedisClient().ForAsyncOnly(); Log("Publishing msg..."); await redisClient.PublishMessageAsync(PrefixedKey("CHANNEL5:BODY"), "hello"); // .ToUtf8Bytes() }); Log("Start Listening On"); await subscription.SubscribeToChannelsMatchingAsync(channels); } } }
RedisPubSubTestsAsync
csharp
dotnet__aspire
src/Shared/CommandLineArgsParser.cs
{ "start": 191, "end": 4986 }
internal static class ____ { /// <summary>Parses a command-line string into a command executable and the list of arguments</summary> public static (string exe, string[] args) ParseCommand(string arguments) { var result = new List<string>(); ParseArgumentsIntoList(arguments, result); var exe = result.First(); var args = result.Count > 1 ? result.Skip(1).ToArray() : Array.Empty<string>(); return (exe, args); } /// <summary>Parses a command-line argument string into a list of arguments.</summary> public static List<string> Parse(string arguments) { var result = new List<string>(); ParseArgumentsIntoList(arguments, result); return result; } /// <summary>Parses a command-line argument string into a list of arguments.</summary> /// <param name="arguments">The argument string.</param> /// <param name="results">The list into which the component arguments should be stored.</param> /// <remarks> /// This follows the rules outlined in "Parsing C++ Command-Line Arguments" at /// https://msdn.microsoft.com/library/17w5ykft.aspx. /// </remarks> // copied from https://github.com/dotnet/runtime/blob/404b286b23093cd93a985791934756f64a33483e/src/libraries/System.Diagnostics.Process/src/System/Diagnostics/Process.Unix.cs#L846-L945 private static void ParseArgumentsIntoList(string arguments, List<string> results) { // Iterate through all of the characters in the argument string. for (int i = 0; i < arguments.Length; i++) { while (i < arguments.Length && (arguments[i] == ' ' || arguments[i] == '\t')) { i++; } if (i == arguments.Length) { break; } results.Add(GetNextArgument(arguments, ref i)); } } private static string GetNextArgument(string arguments, ref int i) { var currentArgument = new StringBuilder(); bool inQuotes = false; while (i < arguments.Length) { // From the current position, iterate through contiguous backslashes. int backslashCount = 0; while (i < arguments.Length && arguments[i] == '\\') { i++; backslashCount++; } if (backslashCount > 0) { if (i >= arguments.Length || arguments[i] != '"') { // Backslashes not followed by a double quote: // they should all be treated as literal backslashes. currentArgument.Append('\\', backslashCount); } else { // Backslashes followed by a double quote: // - Output a literal slash for each complete pair of slashes // - If one remains, use it to make the subsequent quote a literal. currentArgument.Append('\\', backslashCount / 2); if (backslashCount % 2 != 0) { currentArgument.Append('"'); i++; } } continue; } char c = arguments[i]; // If this is a double quote, track whether we're inside of quotes or not. // Anything within quotes will be treated as a single argument, even if // it contains spaces. if (c == '"') { if (inQuotes && i < arguments.Length - 1 && arguments[i + 1] == '"') { // Two consecutive double quotes inside an inQuotes region should result in a literal double quote // (the parser is left in the inQuotes region). // This behavior is not part of the spec of code:ParseArgumentsIntoList, but is compatible with CRT // and .NET Framework. currentArgument.Append('"'); i++; } else { inQuotes = !inQuotes; } i++; continue; } // If this is a space/tab and we're not in quotes, we're done with the current // argument, it should be added to the results and then reset for the next one. if ((c == ' ' || c == '\t') && !inQuotes) { break; } // Nothing special; add the character to the current argument. currentArgument.Append(c); i++; } return currentArgument.ToString(); } }
CommandLineArgsParser
csharp
AvaloniaUI__Avalonia
src/Windows/Avalonia.Win32/TrayIconImpl.cs
{ "start": 9009, "end": 10899 }
private class ____ : Window { private readonly ManagedPopupPositioner _positioner; private readonly TrayIconManagedPopupPositionerPopupImplHelper _positionerHelper; public TrayPopupRoot() { _positionerHelper = new TrayIconManagedPopupPositionerPopupImplHelper(MoveResize); _positioner = new ManagedPopupPositioner(_positionerHelper); Topmost = true; Deactivated += TrayPopupRoot_Deactivated; ShowInTaskbar = false; ShowActivated = true; } private void TrayPopupRoot_Deactivated(object? sender, EventArgs e) { Close(); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _positionerHelper.Dispose(); } private void MoveResize(PixelPoint position, Size size, double scaling) { if (PlatformImpl is { } platformImpl) { platformImpl.Move(position); platformImpl.Resize(size, WindowResizeReason.Layout); } } protected override void ArrangeCore(Rect finalRect) { base.ArrangeCore(finalRect); _positioner.Update(new PopupPositionerParameters { Anchor = PopupAnchor.TopLeft, Gravity = PopupGravity.BottomRight, AnchorRectangle = new Rect(Position.ToPoint(Screens.Primary?.Scaling ?? 1.0), new Size(1, 1)), Size = finalRect.Size, ConstraintAdjustment = PopupPositionerConstraintAdjustment.FlipX | PopupPositionerConstraintAdjustment.FlipY, }); }
TrayPopupRoot
csharp
microsoft__FASTER
cs/samples/StoreCheckpointRecover/Types.cs
{ "start": 1556, "end": 1689 }
public class ____ { public MyValue value; public override string ToString() => value.ToString(); }
MyOutput
csharp
dotnet__aspnetcore
src/Http/Http.Extensions/gen/Microsoft.AspNetCore.Http.RequestDelegateGenerator/RequestDelegateGeneratorSources.cs
{ "start": 24795, "end": 26444 }
sealed class ____ : Attribute { public InterceptsLocationAttribute(int version, string data) { } } } namespace Microsoft.AspNetCore.Http.Generated { using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Text.Json; using System.Text.Json.Serialization.Metadata; using System.Threading.Tasks; using System.IO; using Microsoft.AspNetCore.Antiforgery; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing.Patterns; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Json; using Microsoft.AspNetCore.Http.Metadata; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Primitives; using Microsoft.Extensions.Options; using MetadataPopulator = System.Func<System.Reflection.MethodInfo, Microsoft.AspNetCore.Http.RequestDelegateFactoryOptions?, Microsoft.AspNetCore.Http.RequestDelegateMetadataResult>; using RequestDelegateFactoryFunc = System.Func<System.Delegate, Microsoft.AspNetCore.Http.RequestDelegateFactoryOptions, Microsoft.AspNetCore.Http.RequestDelegateMetadataResult?, Microsoft.AspNetCore.Http.RequestDelegateResult>; {{GeneratedCodeAttribute}} file
InterceptsLocationAttribute
csharp
dotnet__aspnetcore
src/Mvc/Mvc.Core/src/Infrastructure/ActionDescriptorCollectionProvider.cs
{ "start": 317, "end": 601 }
class ____ <see cref="IActionDescriptorCollectionProvider"/> which also provides an <see cref="IChangeToken"/> /// for reactive notifications of <see cref="ActionDescriptor"/> changes. /// </summary> /// <remarks> /// <see cref="ActionDescriptorCollectionProvider"/> is used as a base
for
csharp
dotnet__efcore
test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs
{ "start": 352237, "end": 352457 }
public class ____ { public int Id { get; set; } public RelatedEntity1615 ParentEntity { get; set; } public IEnumerable<RelatedEntity1617> ChildEntities { get; set; } }
RelatedEntity1616
csharp
SixLabors__ImageSharp
src/ImageSharp/Memory/Allocators/Internals/IRefCounted.cs
{ "start": 215, "end": 451 }
internal interface ____ { /// <summary> /// Increments the reference counter. /// </summary> void AddRef(); /// <summary> /// Decrements the reference counter. /// </summary> void ReleaseRef(); }
IRefCounted
csharp
dotnet__aspnetcore
src/Servers/Kestrel/Core/src/Internal/Infrastructure/KestrelTrace.BadRequests.cs
{ "start": 329, "end": 1664 }
partial class ____ : ILogger { public void ConnectionBadRequest(string connectionId, AspNetCore.Http.BadHttpRequestException ex) { BadRequestsLog.ConnectionBadRequest(_badRequestsLogger, connectionId, ex.Message, ex); } public void RequestProcessingError(string connectionId, Exception ex) { BadRequestsLog.RequestProcessingError(_badRequestsLogger, connectionId, ex); } public void RequestBodyMinimumDataRateNotSatisfied(string connectionId, string? traceIdentifier, double rate) { BadRequestsLog.RequestBodyMinimumDataRateNotSatisfied(_badRequestsLogger, connectionId, traceIdentifier, rate); } public void ResponseMinimumDataRateNotSatisfied(string connectionId, string? traceIdentifier) { BadRequestsLog.ResponseMinimumDataRateNotSatisfied(_badRequestsLogger, connectionId, traceIdentifier); } public void PossibleInvalidHttpVersionDetected(string connectionId, HttpVersion expectedHttpVersion, HttpVersion detectedHttpVersion) { if (_generalLogger.IsEnabled(LogLevel.Debug)) { BadRequestsLog.PossibleInvalidHttpVersionDetected(_badRequestsLogger, connectionId, HttpUtilities.VersionToString(expectedHttpVersion), HttpUtilities.VersionToString(detectedHttpVersion)); } } private static
KestrelTrace
csharp
FluentValidation__FluentValidation
src/FluentValidation/Validators/PrecisionScaleValidator.cs
{ "start": 3952, "end": 4765 }
private record ____ Info (int Scale, int Precision) { public int IntegerDigits => Precision - Scale; public static Info Get(decimal value, bool ignoreTrailingZeros) { var scale = value.Scale; var precision = 0; var tmp = GetMantissa(value); // Trim trailing zero's. if (ignoreTrailingZeros) { while (scale > 0 && tmp % 10 == 0) { tmp /= 10; scale--; } } // determine the precision. while (tmp >= 1) { precision++; tmp /= 10; } return new() { Scale = scale, Precision = precision, }; } /// <summary>Returns the positive value with the scale reset to zero.</summary> private static decimal GetMantissa(decimal Decimal) { var bits = decimal.GetBits(Decimal); return new decimal(bits[0], bits[1], bits[2], false, 0); } } }
struct
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Web.Http.Headers/HttpConnectionOptionHeaderValue.cs
{ "start": 299, "end": 3753 }
public partial class ____ : global::Windows.Foundation.IStringable { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public string Token { get { throw new global::System.NotImplementedException("The member string HttpConnectionOptionHeaderValue.Token is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20HttpConnectionOptionHeaderValue.Token"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public HttpConnectionOptionHeaderValue(string token) { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Web.Http.Headers.HttpConnectionOptionHeaderValue", "HttpConnectionOptionHeaderValue.HttpConnectionOptionHeaderValue(string token)"); } #endif // Forced skipping of method Windows.Web.Http.Headers.HttpConnectionOptionHeaderValue.HttpConnectionOptionHeaderValue(string) // Forced skipping of method Windows.Web.Http.Headers.HttpConnectionOptionHeaderValue.Token.get #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public override string ToString() { throw new global::System.NotImplementedException("The member string HttpConnectionOptionHeaderValue.ToString() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20HttpConnectionOptionHeaderValue.ToString%28%29"); } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static global::Windows.Web.Http.Headers.HttpConnectionOptionHeaderValue Parse(string input) { throw new global::System.NotImplementedException("The member HttpConnectionOptionHeaderValue HttpConnectionOptionHeaderValue.Parse(string input) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=HttpConnectionOptionHeaderValue%20HttpConnectionOptionHeaderValue.Parse%28string%20input%29"); } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static bool TryParse(string input, out global::Windows.Web.Http.Headers.HttpConnectionOptionHeaderValue connectionOptionHeaderValue) { throw new global::System.NotImplementedException("The member bool HttpConnectionOptionHeaderValue.TryParse(string input, out HttpConnectionOptionHeaderValue connectionOptionHeaderValue) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20HttpConnectionOptionHeaderValue.TryParse%28string%20input%2C%20out%20HttpConnectionOptionHeaderValue%20connectionOptionHeaderValue%29"); } #endif } }
HttpConnectionOptionHeaderValue
csharp
mysql-net__MySqlConnector
src/MySqlConnector.Authentication.Ed25519/Chaos.NaCl/Internal/Ed25519Ref10/ge_scalarmult_base.cs
{ "start": 75, "end": 3462 }
partial class ____ { private static byte equal(byte b, byte c) { byte ub = b; byte uc = c; byte x = (byte)(ub ^ uc); /* 0: yes; 1..255: no */ UInt32 y = x; /* 0: yes; 1..255: no */ unchecked { y -= 1; } /* 4294967295: yes; 0..254: no */ y >>= 31; /* 1: yes; 0: no */ return (byte)y; } private static byte negative(sbyte b) { ulong x = unchecked((ulong)(long)b); /* 18446744073709551361..18446744073709551615: yes; 0..255: no */ x >>= 63; /* 1: yes; 0: no */ return (byte)x; } private static void cmov(ref GroupElementPreComp t, ref GroupElementPreComp u, byte b) { FieldOperations.fe_cmov(ref t.yplusx, ref u.yplusx, b); FieldOperations.fe_cmov(ref t.yminusx, ref u.yminusx, b); FieldOperations.fe_cmov(ref t.xy2d, ref u.xy2d, b); } private static void select(out GroupElementPreComp t, int pos, sbyte b) { GroupElementPreComp minust; byte bnegative = negative(b); byte babs = (byte)(b - (((-bnegative) & b) << 1)); ge_precomp_0(out t); var table = LookupTables.Base[pos]; cmov(ref t, ref table[0], equal(babs, 1)); cmov(ref t, ref table[1], equal(babs, 2)); cmov(ref t, ref table[2], equal(babs, 3)); cmov(ref t, ref table[3], equal(babs, 4)); cmov(ref t, ref table[4], equal(babs, 5)); cmov(ref t, ref table[5], equal(babs, 6)); cmov(ref t, ref table[6], equal(babs, 7)); cmov(ref t, ref table[7], equal(babs, 8)); minust.yplusx = t.yminusx; minust.yminusx = t.yplusx; FieldOperations.fe_neg(out minust.xy2d, ref t.xy2d); cmov(ref t, ref minust, bnegative); } /* h = a * B where a = a[0]+256*a[1]+...+256^31 a[31] B is the Ed25519 base point (x,4/5) with x positive. Preconditions: a[31] <= 127 */ public static void ge_scalarmult_base(out GroupElementP3 h, byte[] a, int offset) { // todo: Perhaps remove this allocation sbyte[] e = new sbyte[64]; sbyte carry; GroupElementP1P1 r; GroupElementP2 s; GroupElementPreComp t; int i; for (i = 0; i < 32; ++i) { e[2 * i + 0] = (sbyte)((a[offset + i] >> 0) & 15); e[2 * i + 1] = (sbyte)((a[offset + i] >> 4) & 15); } /* each e[i] is between 0 and 15 */ /* e[63] is between 0 and 7 */ carry = 0; for (i = 0; i < 63; ++i) { e[i] += carry; carry = (sbyte)(e[i] + 8); carry >>= 4; e[i] -= (sbyte)(carry << 4); } e[63] += carry; /* each e[i] is between -8 and 8 */ ge_p3_0(out h); for (i = 1; i < 64; i += 2) { select(out t, i / 2, e[i]); ge_madd(out r, ref h, ref t); ge_p1p1_to_p3(out h, ref r); } ge_p3_dbl(out r, ref h); ge_p1p1_to_p2(out s, ref r); ge_p2_dbl(out r, ref s); ge_p1p1_to_p2(out s, ref r); ge_p2_dbl(out r, ref s); ge_p1p1_to_p2(out s, ref r); ge_p2_dbl(out r, ref s); ge_p1p1_to_p3(out h, ref r); for (i = 0; i < 64; i += 2) { select(out t, i / 2, e[i]); ge_madd(out r, ref h, ref t); ge_p1p1_to_p3(out h, ref r); } } }
GroupOperations
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/Collections/Pooled/ThrowHelper.cs
{ "start": 16342, "end": 21825 }
enum ____ is not defined, please check the ExceptionArgument Enum."); return argument.ToString(); } #endif private static string GetArgumentName(ExceptionArgument argument) { switch (argument) { case ExceptionArgument.obj: return "obj"; case ExceptionArgument.dictionary: return "dictionary"; case ExceptionArgument.array: return "array"; case ExceptionArgument.info: return "info"; case ExceptionArgument.key: return "key"; case ExceptionArgument.text: return "text"; case ExceptionArgument.values: return "values"; case ExceptionArgument.value: return "value"; case ExceptionArgument.startIndex: return "startIndex"; case ExceptionArgument.task: return "task"; case ExceptionArgument.ch: return "ch"; case ExceptionArgument.s: return "s"; case ExceptionArgument.input: return "input"; case ExceptionArgument.list: return "list"; case ExceptionArgument.index: return "index"; case ExceptionArgument.capacity: return "capacity"; case ExceptionArgument.collection: return "collection"; case ExceptionArgument.item: return "item"; case ExceptionArgument.converter: return "converter"; case ExceptionArgument.match: return "match"; case ExceptionArgument.count: return "count"; case ExceptionArgument.action: return "action"; case ExceptionArgument.comparison: return "comparison"; case ExceptionArgument.exceptions: return "exceptions"; case ExceptionArgument.exception: return "exception"; case ExceptionArgument.enumerable: return "enumerable"; case ExceptionArgument.start: return "start"; case ExceptionArgument.format: return "format"; case ExceptionArgument.culture: return "culture"; case ExceptionArgument.comparer: return "comparer"; case ExceptionArgument.comparable: return "comparable"; case ExceptionArgument.source: return "source"; case ExceptionArgument.state: return "state"; case ExceptionArgument.length: return "length"; case ExceptionArgument.comparisonType: return "comparisonType"; case ExceptionArgument.manager: return "manager"; case ExceptionArgument.sourceBytesToCopy: return "sourceBytesToCopy"; case ExceptionArgument.callBack: return "callBack"; case ExceptionArgument.creationOptions: return "creationOptions"; case ExceptionArgument.function: return "function"; case ExceptionArgument.delay: return "delay"; case ExceptionArgument.millisecondsDelay: return "millisecondsDelay"; case ExceptionArgument.millisecondsTimeout: return "millisecondsTimeout"; case ExceptionArgument.timeout: return "timeout"; case ExceptionArgument.type: return "type"; case ExceptionArgument.sourceIndex: return "sourceIndex"; case ExceptionArgument.sourceArray: return "sourceArray"; case ExceptionArgument.destinationIndex: return "destinationIndex"; case ExceptionArgument.destinationArray: return "destinationArray"; case ExceptionArgument.other: return "other"; case ExceptionArgument.newSize: return "newSize"; case ExceptionArgument.lowerBounds: return "lowerBounds"; case ExceptionArgument.lengths: return "lengths"; case ExceptionArgument.len: return "len"; case ExceptionArgument.keys: return "keys"; case ExceptionArgument.indices: return "indices"; case ExceptionArgument.endIndex: return "endIndex"; case ExceptionArgument.elementType: return "elementType"; case ExceptionArgument.arrayIndex: return "arrayIndex"; default: Debug.Fail("The
value
csharp
dotnet__reactive
AsyncRx.NET/System.Reactive.Async/Joins/AsyncPlan.Generated.cs
{ "start": 26358, "end": 30451 }
internal abstract class ____<TSource1, TSource2, TSource3, TSource4, TSource5, TSource6, TSource7, TResult> : AsyncPlan<TResult> { private readonly AsyncPattern<TSource1, TSource2, TSource3, TSource4, TSource5, TSource6, TSource7> _expression; internal AsyncPlanBase(AsyncPattern<TSource1, TSource2, TSource3, TSource4, TSource5, TSource6, TSource7> expression) { _expression = expression; } protected abstract ValueTask<TResult> EvalAsync(TSource1 arg1, TSource2 arg2, TSource3 arg3, TSource4 arg4, TSource5 arg5, TSource6 arg6, TSource7 arg7); internal override ActiveAsyncPlan Activate(Dictionary<object, IAsyncJoinObserver> externalSubscriptions, IAsyncObserver<TResult> observer, Func<ActiveAsyncPlan, ValueTask> deactivate) { var onError = new Func<Exception, ValueTask>(observer.OnErrorAsync); var joinObserver1 = AsyncPlan<TResult>.CreateObserver<TSource1>(externalSubscriptions, _expression.Source1, onError); var joinObserver2 = AsyncPlan<TResult>.CreateObserver<TSource2>(externalSubscriptions, _expression.Source2, onError); var joinObserver3 = AsyncPlan<TResult>.CreateObserver<TSource3>(externalSubscriptions, _expression.Source3, onError); var joinObserver4 = AsyncPlan<TResult>.CreateObserver<TSource4>(externalSubscriptions, _expression.Source4, onError); var joinObserver5 = AsyncPlan<TResult>.CreateObserver<TSource5>(externalSubscriptions, _expression.Source5, onError); var joinObserver6 = AsyncPlan<TResult>.CreateObserver<TSource6>(externalSubscriptions, _expression.Source6, onError); var joinObserver7 = AsyncPlan<TResult>.CreateObserver<TSource7>(externalSubscriptions, _expression.Source7, onError); var activePlan = default(ActiveAsyncPlan<TSource1, TSource2, TSource3, TSource4, TSource5, TSource6, TSource7>); activePlan = new ActiveAsyncPlan<TSource1, TSource2, TSource3, TSource4, TSource5, TSource6, TSource7>( joinObserver1, joinObserver2, joinObserver3, joinObserver4, joinObserver5, joinObserver6, joinObserver7, async (arg1, arg2, arg3, arg4, arg5, arg6, arg7) => { var res = default(TResult); try { res = await EvalAsync(arg1, arg2, arg3, arg4, arg5, arg6, arg7).ConfigureAwait(false); } catch (Exception ex) { await observer.OnErrorAsync(ex).ConfigureAwait(false); return; } await observer.OnNextAsync(res).ConfigureAwait(false); }, async () => { await joinObserver1.RemoveActivePlan(activePlan).ConfigureAwait(false); await joinObserver2.RemoveActivePlan(activePlan).ConfigureAwait(false); await joinObserver3.RemoveActivePlan(activePlan).ConfigureAwait(false); await joinObserver4.RemoveActivePlan(activePlan).ConfigureAwait(false); await joinObserver5.RemoveActivePlan(activePlan).ConfigureAwait(false); await joinObserver6.RemoveActivePlan(activePlan).ConfigureAwait(false); await joinObserver7.RemoveActivePlan(activePlan).ConfigureAwait(false); await deactivate(activePlan).ConfigureAwait(false); } ); joinObserver1.AddActivePlan(activePlan); joinObserver2.AddActivePlan(activePlan); joinObserver3.AddActivePlan(activePlan); joinObserver4.AddActivePlan(activePlan); joinObserver5.AddActivePlan(activePlan); joinObserver6.AddActivePlan(activePlan); joinObserver7.AddActivePlan(activePlan); return activePlan; } }
AsyncPlanBase
csharp
dotnet__aspire
src/Aspire.Hosting.Kubernetes/api/Aspire.Hosting.Kubernetes.cs
{ "start": 58208, "end": 58597 }
partial class ____ { [YamlDotNet.Serialization.YamlMember(Alias = "claimName")] public string ClaimName { get { throw null; } set { } } [YamlDotNet.Serialization.YamlMember(Alias = "readOnly")] public bool? ReadOnly { get { throw null; } set { } } } [YamlDotNet.Serialization.YamlSerializable] public sealed
PersistentVolumeClaimVolumeSourceV1
csharp
dotnetcore__CAP
samples/Sample.RabbitMQ.SqlServer/TypedConsumers/QueueHandlersExtensions.cs
{ "start": 164, "end": 993 }
internal static class ____ { private static readonly Type queueHandlerType = typeof(QueueHandler); public static IServiceCollection AddQueueHandlers(this IServiceCollection services, params Assembly[] assemblies) { assemblies ??= new[] { Assembly.GetEntryAssembly() }; foreach (var type in assemblies.Distinct().SelectMany(x => x.GetTypes().Where(FilterHandlers))) { services.AddTransient(queueHandlerType, type); } return services; } private static bool FilterHandlers(Type t) { var topic = t.GetCustomAttribute<QueueHandlerTopicAttribute>(); return queueHandlerType.IsAssignableFrom(t) && topic != null && t.IsClass && !t.IsAbstract; } } }
QueueHandlersExtensions
csharp
louthy__language-ext
LanguageExt.Core/Pretty/Doc_A.cs
{ "start": 7621, "end": 8156 }
public record ____<A>(Func<int, Doc<A>> React) : Doc<A> { public override Doc<B> ReAnnotate<B>(Func<A, B> f) => DocAnn.Column<B>(a => React(a).ReAnnotate(f)); public override FlattenResult<Doc<A>> ChangesUponFlattening() => new Flattened<Doc<A>>(DocAnn.Column<A>(x => React(x).Flatten())); public override Doc<A> Flatten() => DocAnn.Column<A>(x => React(x).Flatten()); } /// <summary> /// React on the document's page width /// </summary>
DocColumn
csharp
dotnet__efcore
test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs
{ "start": 37475, "end": 37692 }
public class ____ { public int Id { get; set; } public RelatedEntity173 ParentEntity { get; set; } public IEnumerable<RelatedEntity175> ChildEntities { get; set; } }
RelatedEntity174
csharp
npgsql__npgsql
src/Npgsql/NpgsqlBinaryImporter.cs
{ "start": 647, "end": 24599 }
public sealed class ____ : ICancelable { #region Fields and Properties NpgsqlConnector _connector; NpgsqlWriteBuffer _buf; ImporterState _state = ImporterState.Uninitialized; /// <summary> /// The number of columns in the current (not-yet-written) row. /// </summary> short _column; ulong _rowsImported; /// <summary> /// The number of columns, as returned from the backend in the CopyInResponse. /// </summary> int NumColumns => _params.Length; bool InMiddleOfRow => _column != -1 && _column != NumColumns; NpgsqlParameter?[] _params; readonly ILogger _copyLogger; PgWriter _pgWriter = null!; // Setup in Init Activity? _activity; /// <summary> /// Current timeout /// </summary> public TimeSpan Timeout { set { _buf.Timeout = value; _connector.ReadBuffer.Timeout = value; } } #endregion #region Construction / Initialization internal NpgsqlBinaryImporter(NpgsqlConnector connector) { _connector = connector; _buf = connector.WriteBuffer; _column = -1; _params = null!; _copyLogger = connector.LoggingConfiguration.CopyLogger; } internal async Task Init(string copyFromCommand, bool async, CancellationToken cancellationToken = default) { Debug.Assert(_activity is null); _activity = _connector.TraceCopyStart(copyFromCommand, "COPY FROM"); try { await _connector.WriteQuery(copyFromCommand, async, cancellationToken).ConfigureAwait(false); await _connector.Flush(async, cancellationToken).ConfigureAwait(false); using var registration = _connector.StartNestedCancellableOperation(cancellationToken, attemptPgCancellation: false); CopyInResponseMessage copyInResponse; var msg = await _connector.ReadMessage(async).ConfigureAwait(false); switch (msg.Code) { case BackendMessageCode.CopyInResponse: copyInResponse = (CopyInResponseMessage)msg; if (!copyInResponse.IsBinary) { throw _connector.Break( new ArgumentException("copyFromCommand triggered a text transfer, only binary is allowed", nameof(copyFromCommand))); } break; case BackendMessageCode.CommandComplete: throw new InvalidOperationException( "This API only supports import/export from the client, i.e. COPY commands containing TO/FROM STDIN. " + "To import/export with files on your PostgreSQL machine, simply execute the command with ExecuteNonQuery. " + "Note that your data has been successfully imported/exported."); default: throw _connector.UnexpectedMessageReceived(msg.Code); } _state = ImporterState.Ready; _params = new NpgsqlParameter[copyInResponse.NumColumns]; _rowsImported = 0; _buf.StartCopyMode(); WriteHeader(); // Only init after header. _pgWriter = _buf.GetWriter(_connector.DatabaseInfo); } catch (Exception e) { TraceSetException(e); throw; } } void WriteHeader() { _buf.WriteBytes(NpgsqlRawCopyStream.BinarySignature, 0, NpgsqlRawCopyStream.BinarySignature.Length); _buf.WriteInt32(0); // Flags field. OID inclusion not supported at the moment. _buf.WriteInt32(0); // Header extension area length } #endregion #region Write /// <summary> /// Starts writing a single row, must be invoked before writing any columns. /// </summary> public void StartRow() => StartRow(false).GetAwaiter().GetResult(); /// <summary> /// Starts writing a single row, must be invoked before writing any columns. /// </summary> public Task StartRowAsync(CancellationToken cancellationToken = default) => StartRow(async: true, cancellationToken); async Task StartRow(bool async, CancellationToken cancellationToken = default) { CheckReady(); cancellationToken.ThrowIfCancellationRequested(); if (_column is not -1 && _column != NumColumns) ThrowColumnMismatch(); if (_buf.WriteSpaceLeft < 2) await _buf.Flush(async, cancellationToken).ConfigureAwait(false); _buf.WriteInt16((short)NumColumns); _pgWriter.RefreshBuffer(); _column = 0; _rowsImported++; } /// <summary> /// Writes a single column in the current row. /// </summary> /// <param name="value">The value to be written</param> /// <typeparam name="T"> /// The type of the column to be written. This must correspond to the actual type or data /// corruption will occur. If in doubt, use <see cref="Write{T}(T, NpgsqlDbType)"/> to manually /// specify the type. /// </typeparam> public void Write<T>(T value) => Write(async: false, value, npgsqlDbType: null, dataTypeName: null).GetAwaiter().GetResult(); /// <summary> /// Writes a single column in the current row. /// </summary> /// <param name="value">The value to be written</param> /// <param name="cancellationToken"> /// An optional token to cancel the asynchronous operation. The default value is <see cref="CancellationToken.None"/>. /// </param> /// <typeparam name="T"> /// The type of the column to be written. This must correspond to the actual type or data /// corruption will occur. If in doubt, use <see cref="Write{T}(T, NpgsqlDbType)"/> to manually /// specify the type. /// </typeparam> public Task WriteAsync<T>(T value, CancellationToken cancellationToken = default) => Write(async: true, value, npgsqlDbType: null, dataTypeName: null, cancellationToken); /// <summary> /// Writes a single column in the current row as type <paramref name="npgsqlDbType"/>. /// </summary> /// <param name="value">The value to be written</param> /// <param name="npgsqlDbType"> /// In some cases <typeparamref name="T"/> isn't enough to infer the data type to be written to /// the database. This parameter can be used to unambiguously specify the type. An example is /// the JSONB type, for which <typeparamref name="T"/> will be a simple string but for which /// <paramref name="npgsqlDbType"/> must be specified as <see cref="NpgsqlDbType.Jsonb"/>. /// </param> /// <typeparam name="T">The .NET type of the column to be written.</typeparam> public void Write<T>(T value, NpgsqlDbType npgsqlDbType) => Write(async: false, value, npgsqlDbType, dataTypeName: null).GetAwaiter().GetResult(); /// <summary> /// Writes a single column in the current row as type <paramref name="npgsqlDbType"/>. /// </summary> /// <param name="value">The value to be written</param> /// <param name="npgsqlDbType"> /// In some cases <typeparamref name="T"/> isn't enough to infer the data type to be written to /// the database. This parameter can be used to unambiguously specify the type. An example is /// the JSONB type, for which <typeparamref name="T"/> will be a simple string but for which /// <paramref name="npgsqlDbType"/> must be specified as <see cref="NpgsqlDbType.Jsonb"/>. /// </param> /// <param name="cancellationToken"> /// An optional token to cancel the asynchronous operation. The default value is <see cref="CancellationToken.None"/>. /// </param> /// <typeparam name="T">The .NET type of the column to be written.</typeparam> public Task WriteAsync<T>(T value, NpgsqlDbType npgsqlDbType, CancellationToken cancellationToken = default) => Write(async: true, value, npgsqlDbType, dataTypeName: null, cancellationToken); /// <summary> /// Writes a single column in the current row as type <paramref name="dataTypeName"/>. /// </summary> /// <param name="value">The value to be written</param> /// <param name="dataTypeName"> /// In some cases <typeparamref name="T"/> isn't enough to infer the data type to be written to /// the database. This parameter and be used to unambiguously specify the type. /// </param> /// <typeparam name="T">The .NET type of the column to be written.</typeparam> public void Write<T>(T value, string dataTypeName) => Write(async: false, value, npgsqlDbType: null, dataTypeName).GetAwaiter().GetResult(); /// <summary> /// Writes a single column in the current row as type <paramref name="dataTypeName"/>. /// </summary> /// <param name="value">The value to be written</param> /// <param name="dataTypeName"> /// In some cases <typeparamref name="T"/> isn't enough to infer the data type to be written to /// the database. This parameter and be used to unambiguously specify the type. /// </param> /// <param name="cancellationToken"> /// An optional token to cancel the asynchronous operation. The default value is <see cref="CancellationToken.None"/>. /// </param> /// <typeparam name="T">The .NET type of the column to be written.</typeparam> public Task WriteAsync<T>(T value, string dataTypeName, CancellationToken cancellationToken = default) => Write(async: true, value, npgsqlDbType: null, dataTypeName, cancellationToken); Task Write<T>(bool async, T value, NpgsqlDbType? npgsqlDbType, string? dataTypeName, CancellationToken cancellationToken = default) { // Handle DBNull: // 1. when T = DBNull for backwards compatibility, DBNull as a type normally won't find a mapping. // 2. when T = object we resolve oid 0 if DBNull is the first value, later column value oids would needlessly be limited to oid 0. // Also handle null values for object typed parameters, these parameters require non null values to be seen as set. if (typeof(T) == typeof(DBNull) || (typeof(T) == typeof(object) && value is null or DBNull)) return WriteNull(async, cancellationToken); return Core(async, value, npgsqlDbType, dataTypeName, cancellationToken); async Task Core(bool async, T value, NpgsqlDbType? npgsqlDbType, string? dataTypeName, CancellationToken cancellationToken = default) { CheckReady(); cancellationToken.ThrowIfCancellationRequested(); CheckColumnIndex(); // Create the parameter objects for the first row or if the value type changes. var newParam = false; if (_params[_column] is not NpgsqlParameter<T> param) { newParam = true; param = new NpgsqlParameter<T>(); if (npgsqlDbType is not null) param._npgsqlDbType = npgsqlDbType; if (dataTypeName is not null) param._dataTypeName = dataTypeName; } // We only retrieve previous values if anything actually changed. // For object typed parameters we must do so whenever setting NpgsqlParameter.Value would reset the type info. PgTypeInfo? previousTypeInfo = null; PgConverter? previousConverter = null; PgTypeId previousTypeId = default; if (!newParam && ( (typeof(T) == typeof(object) && param.ShouldResetObjectTypeInfo(value)) || param._npgsqlDbType != npgsqlDbType || param._dataTypeName != dataTypeName)) { param.GetResolutionInfo(out previousTypeInfo, out previousConverter, out previousTypeId); if (!newParam) { param.ResetDbType(); if (npgsqlDbType is not null) param._npgsqlDbType = npgsqlDbType; if (dataTypeName is not null) param._dataTypeName = dataTypeName; } } // These actions can reset or change the type info, we'll check afterwards whether we're still consistent with the original values. param.TypedValue = value; param.ResolveTypeInfo(_connector.SerializerOptions, _connector.DbTypeResolver); if (previousTypeInfo is not null && previousConverter is not null && param.PgTypeId != previousTypeId) { var currentPgTypeId = param.PgTypeId; // We should only rollback values when the stored instance was used. We'll throw before writing the new instance back anyway. // Also always rolling back could set PgTypeInfos that were resolved for a type that doesn't match the T of the NpgsqlParameter. if (!newParam) param.SetResolutionInfo(previousTypeInfo, previousConverter, previousTypeId); throw new InvalidOperationException($"Write for column {_column} resolves to a different PostgreSQL type: {currentPgTypeId} than the first row resolved to ({previousTypeId}). " + $"Please make sure to use clr types that resolve to the same PostgreSQL type across rows. " + $"Alternatively pass the same NpgsqlDbType or DataTypeName to ensure the PostgreSQL type ends up to be identical." ); } if (newParam) _params[_column] = param; param.Bind(out _, out _, requiredFormat: DataFormat.Binary); try { await param.Write(async, _pgWriter.WithFlushMode(async ? FlushMode.NonBlocking : FlushMode.Blocking), cancellationToken) .ConfigureAwait(false); } catch (Exception ex) { TraceSetException(ex); _connector.Break(ex); throw; } _column++; } } /// <summary> /// Writes a single null column value. /// </summary> public void WriteNull() => WriteNull(false).GetAwaiter().GetResult(); /// <summary> /// Writes a single null column value. /// </summary> public Task WriteNullAsync(CancellationToken cancellationToken = default) => WriteNull(async: true, cancellationToken); async Task WriteNull(bool async, CancellationToken cancellationToken = default) { CheckReady(); if (cancellationToken.IsCancellationRequested) cancellationToken.ThrowIfCancellationRequested(); CheckColumnIndex(); if (_buf.WriteSpaceLeft < 4) await _buf.Flush(async, cancellationToken).ConfigureAwait(false); _buf.WriteInt32(-1); _pgWriter.RefreshBuffer(); _column++; } /// <summary> /// Writes an entire row of columns. /// Equivalent to calling <see cref="StartRow()"/>, followed by multiple <see cref="Write{T}(T)"/> /// on each value. /// </summary> /// <param name="values">An array of column values to be written as a single row</param> public void WriteRow(params object?[] values) => WriteRow(false, CancellationToken.None, values).GetAwaiter().GetResult(); /// <summary> /// Writes an entire row of columns. /// Equivalent to calling <see cref="StartRow()"/>, followed by multiple <see cref="Write{T}(T)"/> /// on each value. /// </summary> /// <param name="cancellationToken"> /// An optional token to cancel the asynchronous operation. The default value is <see cref="CancellationToken.None"/>. /// </param> /// <param name="values">An array of column values to be written as a single row</param> public Task WriteRowAsync(CancellationToken cancellationToken = default, params object?[] values) => WriteRow(async: true, cancellationToken, values); async Task WriteRow(bool async, CancellationToken cancellationToken = default, params object?[] values) { await StartRow(async, cancellationToken).ConfigureAwait(false); foreach (var value in values) await Write(async, value, npgsqlDbType: null, dataTypeName: null, cancellationToken).ConfigureAwait(false); } void CheckColumnIndex() { if (_column is -1 || _column >= NumColumns) Throw(); [MethodImpl(MethodImplOptions.NoInlining)] void Throw() { if (_column is -1) throw new InvalidOperationException("A row hasn't been started"); if (_column >= NumColumns) ThrowColumnMismatch(); } } #endregion #region Commit / Cancel / Close / Dispose /// <summary> /// Completes the import operation. The writer is unusable after this operation. /// </summary> public ulong Complete() => Complete(false).GetAwaiter().GetResult(); /// <summary> /// Completes the import operation. The writer is unusable after this operation. /// </summary> public ValueTask<ulong> CompleteAsync(CancellationToken cancellationToken = default) => Complete(async: true, cancellationToken); async ValueTask<ulong> Complete(bool async, CancellationToken cancellationToken = default) { CheckReady(); using var registration = _connector.StartNestedCancellableOperation(cancellationToken, attemptPgCancellation: false); if (InMiddleOfRow) { await Cancel(async, cancellationToken).ConfigureAwait(false); throw new InvalidOperationException("Binary importer closed in the middle of a row, cancelling import."); } try { // Write trailer if (_buf.WriteSpaceLeft < 2) await _buf.Flush(async, cancellationToken).ConfigureAwait(false); _buf.WriteInt16(-1); await _buf.Flush(async, cancellationToken).ConfigureAwait(false); _buf.EndCopyMode(); await _connector.WriteCopyDone(async, cancellationToken).ConfigureAwait(false); await _connector.Flush(async, cancellationToken).ConfigureAwait(false); var cmdComplete = Expect<CommandCompleteMessage>(await _connector.ReadMessage(async).ConfigureAwait(false), _connector); Expect<ReadyForQueryMessage>(await _connector.ReadMessage(async).ConfigureAwait(false), _connector); _state = ImporterState.Committed; return cmdComplete.Rows; } catch (Exception e) { TraceSetException(e); Cleanup(); throw; } } void ICancelable.Cancel() => Close(); async Task ICancelable.CancelAsync() => await CloseAsync().ConfigureAwait(false); /// <summary> /// <para> /// Terminates the ongoing binary import and puts the connection back into the idle state, where regular commands can be executed. /// </para> /// <para> /// Note that if <see cref="Complete()" /> hasn't been invoked before calling this, the import will be cancelled and all changes will /// be reverted. /// </para> /// </summary> public void Dispose() => Close(); /// <summary> /// <para> /// Async terminates the ongoing binary import and puts the connection back into the idle state, where regular commands can be executed. /// </para> /// <para> /// Note that if <see cref="CompleteAsync" /> hasn't been invoked before calling this, the import will be cancelled and all changes will /// be reverted. /// </para> /// </summary> public ValueTask DisposeAsync() => CloseAsync(true); async Task Cancel(bool async, CancellationToken cancellationToken = default) { _state = ImporterState.Cancelled; _buf.Clear(); _buf.EndCopyMode(); await _connector.WriteCopyFail(async, cancellationToken).ConfigureAwait(false); await _connector.Flush(async, cancellationToken).ConfigureAwait(false); try { using var registration = _connector.StartNestedCancellableOperation(cancellationToken, attemptPgCancellation: false); var msg = await _connector.ReadMessage(async).ConfigureAwait(false); // The CopyFail should immediately trigger an exception from the read above. throw _connector.Break( new NpgsqlException("Expected ErrorResponse when cancelling COPY but got: " + msg.Code)); } catch (PostgresException e) { if (e.SqlState != PostgresErrorCodes.QueryCanceled) throw; } } /// <summary> /// <para> /// Terminates the ongoing binary import and puts the connection back into the idle state, where regular commands can be executed. /// </para> /// <para> /// Note that if <see cref="Complete()" /> hasn't been invoked before calling this, the import will be cancelled and all changes will /// be reverted. /// </para> /// </summary> public void Close() => CloseAsync(async: false).GetAwaiter().GetResult(); /// <summary> /// <para> /// Async terminates the ongoing binary import and puts the connection back into the idle state, where regular commands can be executed. /// </para> /// <para> /// Note that if <see cref="CompleteAsync" /> hasn't been invoked before calling this, the import will be cancelled and all changes will /// be reverted. /// </para> /// </summary> public ValueTask CloseAsync(CancellationToken cancellationToken = default) => CloseAsync(async: true, cancellationToken); async ValueTask CloseAsync(bool async, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); switch (_state) { case ImporterState.Disposed: return; case ImporterState.Ready: await Cancel(async, cancellationToken).ConfigureAwait(false); break; case ImporterState.Uninitialized: case ImporterState.Cancelled: case ImporterState.Committed: break; default: throw new Exception("Invalid state: " + _state); } TraceImportStop(); Cleanup(); } #pragma warning disable CS8625 void Cleanup() { if (_state == ImporterState.Disposed) return; var connector = _connector; LogMessages.BinaryCopyOperationCompleted(_copyLogger, _rowsImported, connector?.Id ?? -1); if (connector != null) { connector.EndUserAction(); connector.CurrentCopyOperation = null; connector.Connection?.EndBindingScope(ConnectorBindingScope.Copy); _connector = null; } _buf = null; _state = ImporterState.Disposed; } #pragma warning restore CS8625 void CheckReady() { if (_state is not ImporterState.Ready and var state) Throw(state); [MethodImpl(MethodImplOptions.NoInlining)] static void Throw(ImporterState state) => throw (state switch { ImporterState.Uninitialized => throw new InvalidOperationException("The COPY operation has not been initialized."), ImporterState.Disposed => new ObjectDisposedException(typeof(NpgsqlBinaryImporter).FullName, "The COPY operation has already ended."), ImporterState.Cancelled => new InvalidOperationException("The COPY operation has already been cancelled."), ImporterState.Committed => new InvalidOperationException("The COPY operation has already been committed."), _ => new Exception("Invalid state: " + state) }); } #endregion #region Enums
NpgsqlBinaryImporter
csharp
dotnet__extensions
src/Libraries/Microsoft.Extensions.Telemetry/Enrichment/ApplicationEnricherServiceCollectionExtensions.cs
{ "start": 512, "end": 5730 }
public static class ____ { /// <summary> /// Adds an instance of the service enricher to the <see cref="IServiceCollection"/>. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> to add the service enricher to.</param> /// <returns>The value of <paramref name="services"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="services"/> is <see langword="null"/>.</exception> [Obsolete( DiagnosticIds.Obsoletions.ObsoleteTelemetryApiMessage, DiagnosticId = DiagnosticIds.Obsoletions.ObsoleteTelemetryApiDiagId, UrlFormat = DiagnosticIds.UrlFormat)] public static IServiceCollection AddServiceLogEnricher(this IServiceCollection services) => services.AddApplicationLogEnricher(_ => { }); /// <summary> /// Adds an instance of the service enricher to the <see cref="IServiceCollection"/>. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> to add the service enricher to.</param> /// <param name="configure">The <see cref="ApplicationLogEnricherOptions"/> configuration delegate.</param> /// <returns>The value of <paramref name="services"/>.</returns> /// <exception cref="ArgumentNullException">Any of the arguments is <see langword="null"/>.</exception> [Obsolete( DiagnosticIds.Obsoletions.ObsoleteTelemetryApiMessage, DiagnosticId = DiagnosticIds.Obsoletions.ObsoleteTelemetryApiDiagId, UrlFormat = DiagnosticIds.UrlFormat)] public static IServiceCollection AddServiceLogEnricher(this IServiceCollection services, Action<ApplicationLogEnricherOptions> configure) => services.AddApplicationLogEnricher(configure); /// <summary> /// Adds an instance of the service enricher to the <see cref="IServiceCollection"/>. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> to add the service enricher to.</param> /// <param name="section">The <see cref="IConfigurationSection"/> to use for configuring <see cref="ApplicationLogEnricherOptions"/> in the service enricher.</param> /// <returns>The value of <paramref name="services"/>.</returns> /// <exception cref="ArgumentNullException">Any of the arguments is <see langword="null"/>.</exception> [Obsolete( DiagnosticIds.Obsoletions.ObsoleteTelemetryApiMessage, DiagnosticId = DiagnosticIds.Obsoletions.ObsoleteTelemetryApiDiagId, UrlFormat = DiagnosticIds.UrlFormat)] public static IServiceCollection AddServiceLogEnricher(this IServiceCollection services, IConfigurationSection section) => services.AddApplicationLogEnricher(section); /// <summary> /// Adds an instance of the application enricher to the <see cref="IServiceCollection"/>. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> to add the application enricher to.</param> /// <returns>The value of <paramref name="services"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="services"/> is <see langword="null"/>.</exception> public static IServiceCollection AddApplicationLogEnricher(this IServiceCollection services) { _ = Throw.IfNull(services); return services .AddApplicationLogEnricher(_ => { }); } /// <summary> /// Adds an instance of the application enricher to the <see cref="IServiceCollection"/>. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> to add the application enricher to.</param> /// <param name="configure">The <see cref="ApplicationLogEnricherOptions"/> configuration delegate.</param> /// <returns>The value of <paramref name="services"/>.</returns> /// <exception cref="ArgumentNullException">Any of the arguments is <see langword="null"/>.</exception> public static IServiceCollection AddApplicationLogEnricher(this IServiceCollection services, Action<ApplicationLogEnricherOptions> configure) { _ = Throw.IfNull(services); _ = Throw.IfNull(configure); return services .AddStaticLogEnricher<ApplicationLogEnricher>() .Configure(configure); } /// <summary> /// Adds an instance of the application enricher to the <see cref="IServiceCollection"/>. /// </summary> /// <param name="services">The <see cref="IServiceCollection"/> to add the application enricher to.</param> /// <param name="section">The <see cref="IConfigurationSection"/> to use for configuring <see cref="ApplicationLogEnricherOptions"/> in the application enricher.</param> /// <returns>The value of <paramref name="services"/>.</returns> /// <exception cref="ArgumentNullException">Any of the arguments is <see langword="null"/>.</exception> public static IServiceCollection AddApplicationLogEnricher(this IServiceCollection services, IConfigurationSection section) { _ = Throw.IfNull(services); _ = Throw.IfNull(section); return services .AddStaticLogEnricher<ApplicationLogEnricher>() .Configure<ApplicationLogEnricherOptions>(section); } }
ApplicationEnricherServiceCollectionExtensions
csharp
dotnet__aspnetcore
src/Http/Http.Extensions/test/RequestDelegateGenerator/CompileTimeCreationTests.cs
{ "start": 601, "end": 9199 }
public partial class ____ : RequestDelegateCreationTests { protected override bool IsGeneratorEnabled { get; } = true; [Fact] public async Task MapGet_WithRequestDelegate_DoesNotGenerateSources() { var (generatorRunResult, compilation) = await RunGeneratorAsync(""" app.MapGet("/hello", (HttpContext context) => Task.CompletedTask); """); var results = Assert.IsType<GeneratorRunResult>(generatorRunResult); Assert.Empty(GetStaticEndpoints(results, GeneratorSteps.EndpointModelStep)); var endpoint = GetEndpointFromCompilation(compilation, false); var httpContext = CreateHttpContext(); await endpoint.RequestDelegate(httpContext); await VerifyResponseBodyAsync(httpContext, ""); } [Fact] public async Task MapAction_ExplicitRouteParamWithInvalidName_SimpleReturn() { var source = $$"""app.MapGet("/{routeValue}", ([FromRoute(Name = "invalidName" )] string parameterName) => parameterName);"""; var (_, compilation) = await RunGeneratorAsync(source); var endpoint = GetEndpointFromCompilation(compilation); var httpContext = CreateHttpContext(); var exception = await Assert.ThrowsAsync<InvalidOperationException>(() => endpoint.RequestDelegate(httpContext)); Assert.Equal("'invalidName' is not a route parameter.", exception.Message); } [Fact] public async Task SupportsSameInterceptorsFromDifferentFiles() { var project = CreateProject(); var source = GetMapActionString("""app.MapGet("/", (string name) => "Hello {name}!");app.MapGet("/bye", (string name) => "Bye {name}!");"""); var otherSource = GetMapActionString("""app.MapGet("/", (string name) => "Hello {name}!");""", "OtherTestMapActions"); project = project.AddDocument("TestMapActions.cs", SourceText.From(source, Encoding.UTF8)).Project; project = project.AddDocument("OtherTestMapActions.cs", SourceText.From(otherSource, Encoding.UTF8)).Project; var compilation = await project.GetCompilationAsync(); var generator = new RequestDelegateGenerator.RequestDelegateGenerator().AsSourceGenerator(); GeneratorDriver driver = CSharpGeneratorDriver.Create(generators: new[] { generator }, driverOptions: new GeneratorDriverOptions(IncrementalGeneratorOutputKind.None, trackIncrementalGeneratorSteps: true), parseOptions: ParseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var updatedCompilation, out var _); var diagnostics = updatedCompilation.GetDiagnostics(); Assert.Empty(diagnostics.Where(d => d.Severity >= DiagnosticSeverity.Warning)); await VerifyAgainstBaselineUsingFile(updatedCompilation); } [Fact] public async Task SupportsDifferentInterceptorsFromSameLocation() { var project = CreateProject(); var source = GetMapActionString("""app.MapGet("/", (string name) => "Hello {name}!");"""); var otherSource = GetMapActionString("""app.MapGet("/", (int age) => "Hello {age}!");""", "OtherTestMapActions"); project = project.AddDocument("TestMapActions.cs", SourceText.From(source, Encoding.UTF8)).Project; project = project.AddDocument("OtherTestMapActions.cs", SourceText.From(otherSource, Encoding.UTF8)).Project; var compilation = await project.GetCompilationAsync(); var generator = new RequestDelegateGenerator.RequestDelegateGenerator().AsSourceGenerator(); GeneratorDriver driver = CSharpGeneratorDriver.Create(generators: new[] { generator }, driverOptions: new GeneratorDriverOptions(IncrementalGeneratorOutputKind.None, trackIncrementalGeneratorSteps: true), parseOptions: ParseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var updatedCompilation, out var _); var diagnostics = updatedCompilation.GetDiagnostics(); Assert.Empty(diagnostics.Where(d => d.Severity >= DiagnosticSeverity.Warning)); await VerifyAgainstBaselineUsingFile(updatedCompilation); } [Fact] public async Task SupportsMapCallOnNewLine() { var source = """ app .MapGet("/hello1/{id}", (int id) => $"Hello {id}!"); EndpointRouteBuilderExtensions .MapGet(app, "/hello2/{id}", (int id) => $"Hello {id}!"); app. MapGet("/hello1/{id}", (int id) => $"Hello {id}!"); EndpointRouteBuilderExtensions. MapGet(app, "/hello2/{id}", (int id) => $"Hello {id}!"); app. MapGet("/hello1/{id}", (int id) => $"Hello {id}!"); EndpointRouteBuilderExtensions. MapGet(app, "/hello2/{id}", (int id) => $"Hello {id}!"); app. MapGet("/hello1/{id}", (int id) => $"Hello {id}!"); EndpointRouteBuilderExtensions. MapGet(app, "/hello2/{id}", (int id) => $"Hello {id}!"); app. MapGet ("/hello1/{id}", (int id) => $"Hello {id}!"); EndpointRouteBuilderExtensions. MapGet (app, "/hello2/{id}", (int id) => $"Hello {id}!"); app . MapGet ("/hello1/{id}", (int id) => $"Hello {id}!"); EndpointRouteBuilderExtensions . MapGet (app, "/hello2/{id}", (int id) => $"Hello {id}!"); """; var (_, compilation) = await RunGeneratorAsync(source); var endpoints = GetEndpointsFromCompilation(compilation); for (int i = 0; i < endpoints.Length; i++) { var httpContext = CreateHttpContext(); httpContext.Request.RouteValues["id"] = i.ToString(CultureInfo.InvariantCulture); await endpoints[i].RequestDelegate(httpContext); await VerifyResponseBodyAsync(httpContext, $"Hello {i}!"); } } [Fact] public async Task SourceMapsAllPathsInAttribute() { var currentDirectory = Directory.GetCurrentDirectory(); var mappedDirectory = Path.Combine(currentDirectory, "path", "mapped"); var project = CreateProject(modifyCompilationOptions: (options) => { return options.WithSourceReferenceResolver( new SourceFileResolver(ImmutableArray<string>.Empty, currentDirectory, ImmutableArray.Create(new KeyValuePair<string, string>(currentDirectory, mappedDirectory)))); }); var source = GetMapActionString("""app.MapGet("/", () => "Hello world!");"""); project = project.AddDocument("TestMapActions.cs", SourceText.From(source, Encoding.UTF8), filePath: Path.Combine(currentDirectory, "TestMapActions.cs")).Project; var compilation = await project.GetCompilationAsync(); var generator = new RequestDelegateGenerator.RequestDelegateGenerator().AsSourceGenerator(); GeneratorDriver driver = CSharpGeneratorDriver.Create(generators: new[] { generator }, driverOptions: new GeneratorDriverOptions(IncrementalGeneratorOutputKind.None, trackIncrementalGeneratorSteps: true), parseOptions: ParseOptions); driver = driver.RunGeneratorsAndUpdateCompilation(compilation, out var updatedCompilation, out var diags); var diagnostics = updatedCompilation.GetDiagnostics(); Assert.Empty(diagnostics.Where(d => d.Severity >= DiagnosticSeverity.Warning)); var endpoint = GetEndpointFromCompilation(updatedCompilation); var httpContext = CreateHttpContext(); await endpoint.RequestDelegate(httpContext); await VerifyResponseBodyAsync(httpContext, "Hello world!"); } [Theory] [InlineData(true)] [InlineData(false)] public async Task EmitsDiagnosticForUnsupportedAnonymousMethod(bool isAsync) { var source = isAsync ? @"app.MapGet(""/hello"", async (int value) => await Task.FromResult(new { Delay = value }));" : @"app.MapGet(""/hello"", (int value) => new { Delay = value });"; var (generatorRunResult, compilation) = await RunGeneratorAsync(source); // Emits diagnostic but generates no source var result = Assert.IsType<GeneratorRunResult>(generatorRunResult); var diagnostic = Assert.Single(result.Diagnostics); Assert.Equal(DiagnosticDescriptors.UnableToResolveAnonymousReturnType.Id, diagnostic.Id); Assert.Equal(DiagnosticSeverity.Warning, diagnostic.Severity); Assert.Empty(result.GeneratedSources); } [Fact] public async Task EmitsDiagnosticForGenericTypeParam() { var source = """ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Routing;
CompileTimeCreationTests
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.System.UserProfile/GlobalizationPreferencesForUser.cs
{ "start": 301, "end": 5552 }
public partial class ____ { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ internal GlobalizationPreferencesForUser() { } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::System.Collections.Generic.IReadOnlyList<string> Calendars { get { throw new global::System.NotImplementedException("The member IReadOnlyList<string> GlobalizationPreferencesForUser.Calendars is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IReadOnlyList%3Cstring%3E%20GlobalizationPreferencesForUser.Calendars"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::System.Collections.Generic.IReadOnlyList<string> Clocks { get { throw new global::System.NotImplementedException("The member IReadOnlyList<string> GlobalizationPreferencesForUser.Clocks is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IReadOnlyList%3Cstring%3E%20GlobalizationPreferencesForUser.Clocks"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::System.Collections.Generic.IReadOnlyList<string> Currencies { get { throw new global::System.NotImplementedException("The member IReadOnlyList<string> GlobalizationPreferencesForUser.Currencies is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IReadOnlyList%3Cstring%3E%20GlobalizationPreferencesForUser.Currencies"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public string HomeGeographicRegion { get { throw new global::System.NotImplementedException("The member string GlobalizationPreferencesForUser.HomeGeographicRegion is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20GlobalizationPreferencesForUser.HomeGeographicRegion"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::System.Collections.Generic.IReadOnlyList<string> Languages { get { throw new global::System.NotImplementedException("The member IReadOnlyList<string> GlobalizationPreferencesForUser.Languages is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IReadOnlyList%3Cstring%3E%20GlobalizationPreferencesForUser.Languages"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::Windows.System.User User { get { throw new global::System.NotImplementedException("The member User GlobalizationPreferencesForUser.User is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=User%20GlobalizationPreferencesForUser.User"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::Windows.Globalization.DayOfWeek WeekStartsOn { get { throw new global::System.NotImplementedException("The member DayOfWeek GlobalizationPreferencesForUser.WeekStartsOn is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=DayOfWeek%20GlobalizationPreferencesForUser.WeekStartsOn"); } } #endif // Forced skipping of method Windows.System.UserProfile.GlobalizationPreferencesForUser.User.get // Forced skipping of method Windows.System.UserProfile.GlobalizationPreferencesForUser.Calendars.get // Forced skipping of method Windows.System.UserProfile.GlobalizationPreferencesForUser.Clocks.get // Forced skipping of method Windows.System.UserProfile.GlobalizationPreferencesForUser.Currencies.get // Forced skipping of method Windows.System.UserProfile.GlobalizationPreferencesForUser.Languages.get // Forced skipping of method Windows.System.UserProfile.GlobalizationPreferencesForUser.HomeGeographicRegion.get // Forced skipping of method Windows.System.UserProfile.GlobalizationPreferencesForUser.WeekStartsOn.get } }
GlobalizationPreferencesForUser
csharp
unoplatform__uno
src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/GridView/GridViewEmptyGroups.xaml.cs
{ "start": 655, "end": 782 }
partial class ____ : UserControl { public GridViewEmptyGroups() { this.InitializeComponent(); } } }
GridViewEmptyGroups
csharp
unoplatform__uno
src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml_Markup/MarkupExtension_FullNameFirst.xaml.cs
{ "start": 141, "end": 274 }
partial class ____ : Page { public MarkupExtension_FullNameFirst() { this.InitializeComponent(); } }
MarkupExtension_FullNameFirst
csharp
dotnet__aspnetcore
src/DataProtection/DataProtection/src/Internal/IActivator.cs
{ "start": 269, "end": 431 }
interface ____ <see cref="Activator.CreateInstance{T}"/> that also supports /// limited dependency injection (of <see cref="IServiceProvider"/>). /// </summary>
into
csharp
unoplatform__uno
src/Uno.UI/UI/Xaml/Controls/Primitives/ButtonBase/ButtonBase.UIKit.cs
{ "start": 205, "end": 1927 }
public partial class ____ : ContentControl { private readonly SerialDisposable _clickSubscription = new SerialDisposable(); partial void OnLoadedPartial() { OnCanExecuteChanged(); } partial void OnUnloadedPartial() { _clickSubscription.Disposable = null; } partial void RegisterEvents() { _clickSubscription.Disposable = null; if (Window == null) { // Will be invoked again when this control will be attached loaded. return; } if (!(GetContentElement() is UIControl uiControl)) { // Button is using Windows template, no native events to register to return; } if (this.Log().IsEnabled(Uno.Foundation.Logging.LogLevel.Debug)) { this.Log().Debug("ControlTemplateRoot is a UIControl, hooking on to AllTouchEvents and TouchUpInside"); } void clickHandler(object e, EventArgs s) { if (this.Log().IsEnabled(Uno.Foundation.Logging.LogLevel.Debug)) { this.Log().Debug("TouchUpInside, executing command"); } OnClick(); RaiseEvent(TappedEvent, new TappedRoutedEventArgs { OriginalSource = this }); } // // Bind the enabled handler // void enabledHandler(object e, DependencyPropertyChangedEventArgs s) { uiControl.Enabled = IsEnabled; } uiControl.TouchUpInside += clickHandler; IsEnabledChanged += enabledHandler; void unregister() { uiControl.TouchUpInside -= clickHandler; IsEnabledChanged -= enabledHandler; } _clickSubscription.Disposable = Disposable.Create(unregister); } private UIView GetContentElement() { return TemplatedRoot ?.FindFirstChild<ContentPresenter>() ?.ContentTemplateRoot ?? TemplatedRoot as UIView; } } }
ButtonBase