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__extensions | test/Libraries/Microsoft.Extensions.Caching.Hybrid.Tests/SqlServerTests.cs | {
"start": 299,
"end": 1871
} | public class ____ : DistributedCacheTests
{
public SqlServerTests(ITestOutputHelper log)
: base(log)
{
}
protected override bool CustomClockSupported => true;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Caught and logged")]
protected override async ValueTask ConfigureAsync(IServiceCollection services)
{
// create a local DB named CacheBench, then
// dotnet tool install --global dotnet-sql-cache
// dotnet sql-cache create "Data Source=.;Initial Catalog=CacheBench;Integrated Security=True;Trust Server Certificate=True" dbo BenchmarkCache
const string ConnectionString = "Data Source=.;Initial Catalog=CacheBench;Integrated Security=True;Trust Server Certificate=True";
try
{
using var conn = new SqlConnection(ConnectionString);
using var cmd = conn.CreateCommand();
cmd.CommandText = "truncate table dbo.BenchmarkCache";
await conn.OpenAsync();
await cmd.ExecuteNonQueryAsync();
// if that worked: we should be fine
services.AddDistributedSqlServerCache(options =>
{
options.SchemaName = "dbo";
options.TableName = "BenchmarkCache";
options.ConnectionString = ConnectionString;
options.SystemClock = Clock;
});
}
catch (Exception ex)
{
Log.WriteLine(ex.Message);
}
}
}
| SqlServerTests |
csharp | jbogard__MediatR | src/MediatR/Pipeline/IRequestPostProcessor.cs | {
"start": 278,
"end": 798
} | public interface ____<in TRequest, in TResponse> where TRequest : notnull
{
/// <summary>
/// Process method executes after the Handle method on your handler
/// </summary>
/// <param name="request">Request instance</param>
/// <param name="response">Response instance</param>
/// <param name="cancellationToken">Cancellation token</param>
/// <returns>An awaitable task</returns>
Task Process(TRequest request, TResponse response, CancellationToken cancellationToken);
} | IRequestPostProcessor |
csharp | dotnet__aspnetcore | src/Http/Http.Features/src/ITlsConnectionFeature.cs | {
"start": 349,
"end": 742
} | public interface ____
{
/// <summary>
/// Synchronously retrieves the client certificate, if any.
/// </summary>
X509Certificate2? ClientCertificate { get; set; }
/// <summary>
/// Asynchronously retrieves the client certificate, if any.
/// </summary>
Task<X509Certificate2?> GetClientCertificateAsync(CancellationToken cancellationToken);
}
| ITlsConnectionFeature |
csharp | MapsterMapper__Mapster | src/Sample.CodeGen/Models/EnrollmentAdd.g.cs | {
"start": 38,
"end": 260
} | public partial record ____
{
public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }
public string Grade { get; set; }
}
} | EnrollmentAdd |
csharp | dotnet__aspnetcore | src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Transformers/Implementations/OpenApiSchemaReferenceTransformerTests.cs | {
"start": 48390,
"end": 48563
} | private class ____
{
public AddressResponse Address { get; init; } = new();
public BuilderResponse Builder { get; init; } = new();
}
| ProjectResponse |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.ApiExplorer/test/EndpointMetadataApiDescriptionProviderTest.cs | {
"start": 30039,
"end": 43984
} | public class ____ : IResult
{
public required string Content { get; set; }
public Task ExecuteAsync(HttpContext httpContext)
{
return httpContext.Response.WriteAsJsonAsync(this);
}
}
[Fact]
public void AddsFromRouteParameterAsPath()
{
static void AssertPathParameter(ApiDescription apiDescription)
{
var param = Assert.Single(apiDescription.ParameterDescriptions);
Assert.Equal(typeof(int), param.Type);
Assert.Equal(typeof(int), param.ModelMetadata.ModelType);
Assert.Equal(BindingSource.Path, param.Source);
}
AssertPathParameter(GetApiDescription((int foo) => { }, "/{foo}"));
AssertPathParameter(GetApiDescription(([FromRoute] int foo) => { }));
}
[Fact]
public void AddsFromRouteParameterAsPathWithCustomClassWithTryParse()
{
static void AssertPathParameter(ApiDescription apiDescription)
{
var param = Assert.Single(apiDescription.ParameterDescriptions);
Assert.Equal(typeof(TryParseStringRecord), param.Type);
Assert.Equal(typeof(string), param.ModelMetadata.ModelType);
Assert.Equal(BindingSource.Path, param.Source);
}
AssertPathParameter(GetApiDescription((TryParseStringRecord foo) => { }, "/{foo}"));
}
[Fact]
public void AddsFromRouteParameterAsPathWithPrimitiveType()
{
static void AssertPathParameter(ApiDescription apiDescription)
{
var param = Assert.Single(apiDescription.ParameterDescriptions);
Assert.Equal(typeof(int), param.Type);
Assert.Equal(typeof(int), param.ModelMetadata.ModelType);
Assert.Equal(BindingSource.Path, param.Source);
}
AssertPathParameter(GetApiDescription((int foo) => { }, "/{foo}"));
}
[Fact]
public void AddsFromRouteParameterAsPathWithSpecialPrimitiveType()
{
static void AssertPathParameter(ApiDescription apiDescription, Type expectedTYpe)
{
var param = Assert.Single(apiDescription.ParameterDescriptions);
Assert.Equal(expectedTYpe, param.Type);
Assert.Equal(expectedTYpe, param.ModelMetadata.ModelType);
Assert.Equal(BindingSource.Path, param.Source);
}
AssertPathParameter(GetApiDescription((DateTime foo) => { }, "/{foo}"), typeof(DateTime));
AssertPathParameter(GetApiDescription((DateTimeOffset foo) => { }, "/{foo}"), typeof(DateTimeOffset));
AssertPathParameter(GetApiDescription((DateOnly foo) => { }, "/{foo}"), typeof(DateOnly));
AssertPathParameter(GetApiDescription((TimeOnly foo) => { }, "/{foo}"), typeof(TimeOnly));
AssertPathParameter(GetApiDescription((TimeSpan foo) => { }, "/{foo}"), typeof(TimeSpan));
AssertPathParameter(GetApiDescription((decimal foo) => { }, "/{foo}"), typeof(decimal));
AssertPathParameter(GetApiDescription((Guid foo) => { }, "/{foo}"), typeof(Guid));
AssertPathParameter(GetApiDescription((Uri foo) => { }, "/{foo}"), typeof(Uri));
}
[Fact]
public void AddsFromRouteParameterAsPathWithNullableSpecialPrimitiveType()
{
static void AssertPathParameter(ApiDescription apiDescription, Type expectedTYpe)
{
var param = Assert.Single(apiDescription.ParameterDescriptions);
Assert.Equal(expectedTYpe, param.Type);
Assert.Equal(expectedTYpe, param.ModelMetadata.ModelType);
Assert.Equal(BindingSource.Path, param.Source);
}
AssertPathParameter(GetApiDescription((DateTime? foo) => { }, "/{foo}"), typeof(DateTime?));
AssertPathParameter(GetApiDescription((DateTimeOffset? foo) => { }, "/{foo}"), typeof(DateTimeOffset?));
AssertPathParameter(GetApiDescription((DateOnly? foo) => { }, "/{foo}"), typeof(DateOnly?));
AssertPathParameter(GetApiDescription((TimeOnly? foo) => { }, "/{foo}"), typeof(TimeOnly?));
AssertPathParameter(GetApiDescription((TimeSpan? foo) => { }, "/{foo}"), typeof(TimeSpan?));
AssertPathParameter(GetApiDescription((decimal? foo) => { }, "/{foo}"), typeof(decimal?));
AssertPathParameter(GetApiDescription((Guid? foo) => { }, "/{foo}"), typeof(Guid?));
AssertPathParameter(GetApiDescription((Uri? foo) => { }, "/{foo}"), typeof(Uri));
}
[Fact]
public void AddsFromRouteParameterAsPathWithNullablePrimitiveType()
{
static void AssertPathParameter(ApiDescription apiDescription)
{
var param = Assert.Single(apiDescription.ParameterDescriptions);
Assert.Equal(typeof(int?), param.Type);
Assert.Equal(typeof(int?), param.ModelMetadata.ModelType);
Assert.Equal(BindingSource.Path, param.Source);
}
AssertPathParameter(GetApiDescription((int? foo) => { }, "/{foo}"));
}
[Fact]
public void AddsFromRouteParameterAsPathWithStructTypeWithTryParse()
{
static void AssertPathParameter(ApiDescription apiDescription)
{
var param = Assert.Single(apiDescription.ParameterDescriptions);
Assert.Equal(typeof(TryParseStringRecordStruct), param.Type);
Assert.Equal(typeof(string), param.ModelMetadata.ModelType);
Assert.Equal(BindingSource.Path, param.Source);
}
AssertPathParameter(GetApiDescription((TryParseStringRecordStruct foo) => { }, "/{foo}"));
}
[Fact]
public void AddsFromQueryParameterAsQuery()
{
static void AssertQueryParameter<T>(ApiDescription apiDescription)
{
var param = Assert.Single(apiDescription.ParameterDescriptions);
Assert.Equal(typeof(T), param.Type);
Assert.Equal(typeof(T), param.ModelMetadata.ModelType);
Assert.Equal(BindingSource.Query, param.Source);
}
AssertQueryParameter<int>(GetApiDescription((int foo) => { }, "/"));
AssertQueryParameter<int>(GetApiDescription(([FromQuery] int foo) => { }));
AssertQueryParameter<TryParseStringRecordStruct>(GetApiDescription(([FromQuery] TryParseStringRecordStruct foo) => { }));
AssertQueryParameter<int[]>(GetApiDescription((int[] foo) => { }, "/"));
AssertQueryParameter<string[]>(GetApiDescription((string[] foo) => { }, "/"));
AssertQueryParameter<StringValues>(GetApiDescription((StringValues foo) => { }, "/"));
AssertQueryParameter<TryParseStringRecordStruct[]>(GetApiDescription((TryParseStringRecordStruct[] foo) => { }, "/"));
}
[Theory]
[InlineData("Put")]
[InlineData("Post")]
public void BodyIsInferredForArraysInsteadOfQuerySomeHttpMethods(string httpMethod)
{
static void AssertBody<T>(ApiDescription apiDescription)
{
var param = Assert.Single(apiDescription.ParameterDescriptions);
Assert.Equal(typeof(T), param.Type);
Assert.Equal(typeof(T), param.ModelMetadata.ModelType);
Assert.Equal(BindingSource.Body, param.Source);
}
AssertBody<int[]>(GetApiDescription((int[] foo) => { }, "/", httpMethods: new[] { httpMethod }));
AssertBody<string[]>(GetApiDescription((string[] foo) => { }, "/", httpMethods: new[] { httpMethod }));
AssertBody<TryParseStringRecordStruct[]>(GetApiDescription((TryParseStringRecordStruct[] foo) => { }, "/", httpMethods: new[] { httpMethod }));
}
[Fact]
public void AddsFromHeaderParameterAsHeader()
{
var apiDescription = GetApiDescription(([FromHeader] int foo) => { });
var param = Assert.Single(apiDescription.ParameterDescriptions);
Assert.Equal(typeof(int), param.Type);
Assert.Equal(typeof(int), param.ModelMetadata.ModelType);
Assert.Equal(BindingSource.Header, param.Source);
}
[Fact]
public void DoesNotAddFromServiceParameterAsService()
{
Assert.Empty(GetApiDescription((IInferredServiceInterface foo) => { }).ParameterDescriptions);
Assert.Empty(GetApiDescription(([FromServices] InferredServiceClass foo) => { }).ParameterDescriptions);
Assert.Empty(GetApiDescription(([CustomFromServices] InferredServiceClass foo) => { }).ParameterDescriptions);
Assert.Empty(GetApiDescription(([FromKeyedServices("foo")] InferredServiceClass foo) => { }).ParameterDescriptions);
Assert.Empty(GetApiDescription(([CustomFromKeyedServices("foo")] InferredServiceClass foo) => { }).ParameterDescriptions);
Assert.Empty(GetApiDescription((HttpContext context) => { }).ParameterDescriptions);
Assert.Empty(GetApiDescription((HttpRequest request) => { }).ParameterDescriptions);
Assert.Empty(GetApiDescription((HttpResponse response) => { }).ParameterDescriptions);
Assert.Empty(GetApiDescription((ClaimsPrincipal user) => { }).ParameterDescriptions);
Assert.Empty(GetApiDescription((CancellationToken token) => { }).ParameterDescriptions);
Assert.Empty(GetApiDescription((BindAsyncRecord context) => { }).ParameterDescriptions);
}
[Fact]
public void AddsBodyParameterInTheParameterDescription()
{
static void AssertBodyParameter(ApiDescription apiDescription, string expectedName, Type expectedType)
{
var param = Assert.Single(apiDescription.ParameterDescriptions);
Assert.Equal(expectedName, param.Name);
Assert.Equal(expectedType, param.Type);
Assert.Equal(expectedType, param.ModelMetadata.ModelType);
Assert.Equal(BindingSource.Body, param.Source);
}
AssertBodyParameter(GetApiDescription((InferredJsonClass foo) => { }, httpMethods: ["POST"]), "foo", typeof(InferredJsonClass));
AssertBodyParameter(GetApiDescription(([FromBody] int bar) => { }, httpMethods: ["POST"]), "bar", typeof(int));
}
[Fact]
public void AddsDefaultValueFromParameters()
{
var apiDescription = GetApiDescription(TestActionWithDefaultValue);
var param = Assert.Single(apiDescription.ParameterDescriptions);
Assert.Equal(42, param.DefaultValue);
}
[Fact]
public void AddsMultipleParameters()
{
var apiDescription = GetApiDescription(([FromRoute] int foo, int bar, InferredJsonClass fromBody) => { }, httpMethods: ["POST"]);
Assert.Equal(3, apiDescription.ParameterDescriptions.Count);
var fooParam = apiDescription.ParameterDescriptions[0];
Assert.Equal("foo", fooParam.Name);
Assert.Equal(typeof(int), fooParam.Type);
Assert.Equal(typeof(int), fooParam.ModelMetadata.ModelType);
Assert.Equal(BindingSource.Path, fooParam.Source);
Assert.True(fooParam.IsRequired);
var barParam = apiDescription.ParameterDescriptions[1];
Assert.Equal("bar", barParam.Name);
Assert.Equal(typeof(int), barParam.Type);
Assert.Equal(typeof(int), barParam.ModelMetadata.ModelType);
Assert.Equal(BindingSource.Query, barParam.Source);
Assert.True(barParam.IsRequired);
var fromBodyParam = apiDescription.ParameterDescriptions[2];
Assert.Equal("fromBody", fromBodyParam.Name);
Assert.Equal(typeof(InferredJsonClass), fromBodyParam.Type);
Assert.Equal(typeof(InferredJsonClass), fromBodyParam.ModelMetadata.ModelType);
Assert.Equal(BindingSource.Body, fromBodyParam.Source);
Assert.True(fromBodyParam.IsRequired);
}
#nullable disable
[Fact]
public void AddsMultipleParametersFromParametersAttribute()
{
static void AssertParameters(ApiDescription apiDescription, string capturedName = "Foo")
{
Assert.Collection(
apiDescription.ParameterDescriptions,
param =>
{
Assert.Equal(capturedName, param.Name);
Assert.Equal(typeof(int), param.ModelMetadata.ModelType);
Assert.Equal(BindingSource.Path, param.Source);
Assert.True(param.IsRequired);
},
param =>
{
Assert.Equal("Bar", param.Name);
Assert.Equal(typeof(int), param.ModelMetadata.ModelType);
Assert.Equal(BindingSource.Query, param.Source);
Assert.True(param.IsRequired);
},
param =>
{
Assert.Equal("FromBody", param.Name);
Assert.Equal(typeof(InferredJsonClass), param.Type);
Assert.Equal(typeof(InferredJsonClass), param.ModelMetadata.ModelType);
Assert.Equal(BindingSource.Body, param.Source);
Assert.False(param.IsRequired);
}
);
}
AssertParameters(GetApiDescription(([AsParameters] ArgumentListClass req) => { }, httpMethods: ["POST"]));
AssertParameters(GetApiDescription(([AsParameters] ArgumentListClassWithReadOnlyProperties req) => { }, httpMethods: ["POST"]));
AssertParameters(GetApiDescription(([AsParameters] ArgumentListStruct req) => { }, httpMethods: ["POST"]));
AssertParameters(GetApiDescription(([AsParameters] ArgumentListRecord req) => { }, httpMethods: ["POST"]));
AssertParameters(GetApiDescription(([AsParameters] ArgumentListRecordStruct req) => { }, httpMethods: ["POST"]));
AssertParameters(GetApiDescription(([AsParameters] ArgumentListRecordWithoutPositionalParameters req) => { }, httpMethods: ["POST"]));
AssertParameters(GetApiDescription(([AsParameters] ArgumentListRecordWithoutAttributes req) => { }, "/{foo}", httpMethods: ["POST"]), "foo");
AssertParameters(GetApiDescription(([AsParameters] ArgumentListRecordWithoutAttributes req) => { }, "/{Foo}", httpMethods: ["POST"]));
}
#nullable enable
| CustomIResultImplementor |
csharp | OrchardCMS__OrchardCore | src/OrchardCore/OrchardCore.ContentTypes.Abstractions/Editors/UpdateTypeEditorContext.cs | {
"start": 231,
"end": 702
} | public class ____ : UpdateContentDefinitionEditorContext<ContentTypeDefinitionBuilder>
{
public UpdateTypeEditorContext(
ContentTypeDefinitionBuilder builder,
IShape model,
string groupId,
bool isNew,
IShapeFactory shapeFactory,
IZoneHolding layout,
IUpdateModel updater)
: base(builder, model, groupId, isNew, shapeFactory, layout, updater)
{
}
}
| UpdateTypeEditorContext |
csharp | protobuf-net__protobuf-net | src/Examples/Issues/SO17245073.cs | {
"start": 1607,
"end": 1651
} | public enum ____ { X, Y, Z }
}
}
| H |
csharp | dotnet__aspnetcore | src/SignalR/common/Http.Connections/test/HttpConnectionDispatcherTests.cs | {
"start": 169471,
"end": 170424
} | public class ____ : ConnectionHandler
{
public override async Task OnConnectedAsync(ConnectionContext connection)
{
while (true)
{
var result = await connection.Transport.Input.ReadAsync();
try
{
if (result.IsCompleted)
{
break;
}
// Make sure we have an http context
var context = connection.GetHttpContext();
Assert.NotNull(context);
// Setting the response headers should have no effect
context.Response.ContentType = "application/xml";
// Echo the results
await connection.Transport.Output.WriteAsync(result.Buffer.ToArray());
}
finally
{
connection.Transport.Input.AdvanceTo(result.Buffer.End);
}
}
}
}
| HttpContextConnectionHandler |
csharp | cake-build__cake | src/Cake.Common/Tools/DotNet/Restore/DotNetRestorer.cs | {
"start": 468,
"end": 5496
} | public sealed class ____ : DotNetTool<DotNetRestoreSettings>
{
private readonly ICakeEnvironment _environment;
/// <summary>
/// Initializes a new instance of the <see cref="DotNetRestorer" /> 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>
/// <param name="log">The cake log.</param>
public DotNetRestorer(
IFileSystem fileSystem,
ICakeEnvironment environment,
IProcessRunner processRunner,
IToolLocator tools,
ICakeLog log) : base(fileSystem, environment, processRunner, tools)
{
_environment = environment;
}
/// <summary>
/// Restore the project using the specified path and settings.
/// </summary>
/// <param name="root">List of projects and project folders to restore. Each value can be: a path to a project.json or global.json file, or a folder to recursively search for project.json files.</param>
/// <param name="settings">The settings.</param>
public void Restore(string root, DotNetRestoreSettings settings)
{
ArgumentNullException.ThrowIfNull(settings);
RunCommand(settings, GetArguments(root, settings));
}
private ProcessArgumentBuilder GetArguments(string root, DotNetRestoreSettings settings)
{
var builder = CreateArgumentBuilder(settings);
builder.Append("restore");
// Specific root?
if (root != null)
{
builder.AppendQuoted(root);
}
// Runtime
if (!string.IsNullOrEmpty(settings.Runtime))
{
builder.Append("--runtime");
builder.Append(settings.Runtime);
}
// Output directory
if (settings.PackagesDirectory != null)
{
builder.Append("--packages");
builder.AppendQuoted(settings.PackagesDirectory.MakeAbsolute(_environment).FullPath);
}
// Sources
if (settings.Sources != null)
{
foreach (var source in settings.Sources)
{
builder.Append("--source");
builder.AppendQuoted(source);
}
}
// Config file
if (settings.ConfigFile != null)
{
builder.Append("--configfile");
builder.AppendQuoted(settings.ConfigFile.MakeAbsolute(_environment).FullPath);
}
// Ignore failed sources
if (settings.NoCache)
{
builder.Append("--no-cache");
}
// Disable parallel
if (settings.DisableParallel)
{
builder.Append("--disable-parallel");
}
// Ignore failed sources
if (settings.IgnoreFailedSources)
{
builder.Append("--ignore-failed-sources");
}
// Ignore project to project references
if (settings.NoDependencies)
{
builder.Append("--no-dependencies");
}
// Force restore
if (settings.Force)
{
builder.Append("--force");
}
// Interactive
if (settings.Interactive)
{
builder.Append("--interactive");
}
// Use lock file
if (settings.UseLockFile)
{
builder.Append("--use-lock-file");
}
// Locked mode
if (settings.LockedMode)
{
builder.Append("--locked-mode");
}
// Lock file path
if (settings.LockFilePath != null)
{
builder.AppendSwitchQuoted("--lock-file-path", " ", settings.LockFilePath.MakeAbsolute(_environment).FullPath);
}
// Force Evaluate
if (settings.ForceEvaluate)
{
builder.Append("--force-evaluate");
}
// Publish ReadyToRun
if (settings.PublishReadyToRun.HasValue)
{
if (settings.PublishReadyToRun.Value)
{
builder.Append("-p:PublishReadyToRun=true");
}
else
{
builder.Append("-p:PublishReadyToRun=false");
}
}
if (settings.MSBuildSettings != null)
{
builder.AppendMSBuildSettings(settings.MSBuildSettings, _environment);
}
return builder;
}
}
}
| DotNetRestorer |
csharp | dotnet__machinelearning | docs/samples/Microsoft.ML.Samples/Dynamic/Transforms/TimeSeries/DetectIidSpike.cs | {
"start": 3978,
"end": 4167
} | class ____
{
public float Value;
public TimeSeriesData(float value)
{
Value = value;
}
}
| TimeSeriesData |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Commands/ApiKeys/ListApiKeyCommand.cs | {
"start": 295,
"end": 3176
} | internal sealed class ____ : Command
{
public ListApiKeyCommand() : base("list")
{
Description = "Lists all api keys of a workspace";
AddOption(Opt<CursorOption>.Instance);
AddOption(Opt<WorkspaceIdOption>.Instance);
this.SetHandler(
ExecuteAsync,
Bind.FromServiceProvider<InvocationContext>(),
Bind.FromServiceProvider<IAnsiConsole>(),
Bind.FromServiceProvider<IApiClient>(),
Bind.FromServiceProvider<CancellationToken>());
}
private static async Task<int> ExecuteAsync(
InvocationContext context,
IAnsiConsole console,
IApiClient client,
CancellationToken ct)
{
var workspaceId = context.RequireWorkspaceId();
if (console.IsHumanReadable())
{
return await RenderInteractiveAsync(context, console, client, workspaceId, ct);
}
return await RenderNonInteractiveAsync(context, console, client, workspaceId, ct);
}
private static async Task<int> RenderInteractiveAsync(
InvocationContext context,
IAnsiConsole console,
IApiClient client,
string workspaceId,
CancellationToken ct)
{
var container = PaginationContainer
.Create((after, first, _) =>
client.ListApiKeyCommandQuery.ExecuteAsync(workspaceId, after, first, ct),
static p => p.WorkspaceById?.ApiKeys?.PageInfo,
static p => p.WorkspaceById?.ApiKeys?.Edges)
.PageSize(10);
var api = await PagedTable
.From(container)
.Title("ApiKeys")
.AddColumn("Id", x => x.Node.Id)
.AddColumn("Name", x => x.Node.Name)
.RenderAsync(console, ct);
if (api?.Node is IApiKeyDetailPrompt_ApiKey node)
{
context.SetResult(ApiKeyDetailPrompt.From(node).ToObject());
}
return ExitCodes.Success;
}
private static async Task<int> RenderNonInteractiveAsync(
InvocationContext context,
IAnsiConsole console,
IApiClient client,
string workspaceId,
CancellationToken ct)
{
var cursor = context.ParseResult.GetValueForOption(Opt<CursorOption>.Instance);
var result = await client
.ListApiKeyCommandQuery
.ExecuteAsync(workspaceId, cursor, 10, ct);
console.EnsureNoErrors(result);
var endCursor = result.Data?.WorkspaceById?.ApiKeys?.PageInfo.EndCursor;
var items = result.Data?.WorkspaceById?.ApiKeys?.Edges?.Select(x =>
ApiKeyDetailPrompt.From(x.Node).ToObject())
.ToArray() ?? [];
context.SetResult(new PaginatedListResult<ApiKeyDetailPrompt.ApiKeyDetailPromptResult>(items, endCursor));
return ExitCodes.Success;
}
}
| ListApiKeyCommand |
csharp | ServiceStack__ServiceStack | ServiceStack.OrmLite/src/ServiceStack.OrmLite.PostgreSQL/Converters/PostgreSqlDateTimeOffsetConverter.cs | {
"start": 142,
"end": 784
} | public class ____ : DateTimeOffsetConverter
{
public override string ColumnDefinition => "timestamp with time zone";
public override string ToQuotedString(Type fieldType, object value)
{
var dateValue = (DateTimeOffset) value;
const string iso8601Format = "yyyy-MM-dd HH:mm:ss.fff zzz";
return base.DialectProvider.GetQuotedValue(dateValue.ToString(iso8601Format, CultureInfo.InvariantCulture), typeof(string));
}
public override object ToDbValue(Type fieldType, object value)
{
return value;
}
}
}
| PostgreSqlDateTimeOffsetConverter |
csharp | dotnet__efcore | test/EFCore.SqlServer.FunctionalTests/ManyToManyTrackingGeneratedKeysSqlServerTest.cs | {
"start": 589,
"end": 2531
} | public class ____ : ManyToManyTrackingSqlServerFixtureBase
{
protected override string StoreName
=> "ManyToManyTrackingGeneratedKeys";
public override bool UseGeneratedKeys
=> true;
protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context)
{
base.OnModelCreating(modelBuilder, context);
modelBuilder.Entity<EntityOne>().Property(e => e.Id).ValueGeneratedOnAdd();
modelBuilder.Entity<EntityTwo>().Property(e => e.Id).ValueGeneratedOnAdd();
modelBuilder.Entity<EntityThree>().Property(e => e.Id).ValueGeneratedOnAdd();
modelBuilder.Entity<EntityCompositeKey>().Property(e => e.Key1).ValueGeneratedOnAdd();
modelBuilder.Entity<EntityRoot>().Property(e => e.Id).ValueGeneratedOnAdd();
modelBuilder.Entity<EntityTableSharing1>().Property(e => e.Id).ValueGeneratedOnAdd();
modelBuilder.Entity<EntityTableSharing2>().Property(e => e.Id).ValueGeneratedOnAdd();
modelBuilder.SharedTypeEntity<ProxyableSharedType>("PST").IndexerProperty<int>("Id").ValueGeneratedOnAdd();
modelBuilder.Entity<ImplicitManyToManyA>().Property(e => e.Id).ValueGeneratedOnAdd();
modelBuilder.Entity<ImplicitManyToManyB>().Property(e => e.Id).ValueGeneratedOnAdd();
modelBuilder.Entity<UnidirectionalEntityOne>().Property(e => e.Id).ValueGeneratedOnAdd();
modelBuilder.Entity<UnidirectionalEntityTwo>().Property(e => e.Id).ValueGeneratedOnAdd();
modelBuilder.Entity<UnidirectionalEntityThree>().Property(e => e.Id).ValueGeneratedOnAdd();
modelBuilder.Entity<UnidirectionalEntityCompositeKey>().Property(e => e.Key1).ValueGeneratedOnAdd();
modelBuilder.Entity<UnidirectionalEntityRoot>().Property(e => e.Id).ValueGeneratedOnAdd();
}
}
}
| ManyToManyTrackingGeneratedKeysSqlServerFixture |
csharp | grandnode__grandnode2 | src/Web/Grand.Web.Vendor/Validators/Vendor/VendorValidator.cs | {
"start": 288,
"end": 1066
} | public class ____ : BaseGrandValidator<VendorModel>
{
public VendorValidator(
IEnumerable<IValidatorConsumer<VendorModel>> validators,
IEnumerable<IValidatorConsumer<AddressModel>> addressValidators,
ITranslationService translationService)
: base(validators)
{
RuleFor(x => x.Name).NotEmpty().WithMessage(translationService.GetResource("Vendor.Fields.Name.Required"));
RuleFor(x => x.Email).NotEmpty().WithMessage(translationService.GetResource("Vendor.Fields.Email.Required"));
RuleFor(x => x.Email).EmailAddress().WithMessage(translationService.GetResource("Vendor.Common.WrongEmail"));
RuleFor(x => x.Address).SetValidator(new AddressValidator(addressValidators, translationService));
}
} | VendorValidator |
csharp | dotnet__aspire | src/Aspire.Hosting/Dcp/Model/Admin.cs | {
"start": 1545,
"end": 1786
} | internal static class ____
{
// Full resource cleanup (default).
// Projects will be stopped, non-persistent containers will be deleted etc.
public const string Full = "Full";
public const string None = "None";
}
| ResourceCleanup |
csharp | protobuf-net__protobuf-net | src/protobuf-net/Internal/Serializers/TimeOnlySerializer.cs | {
"start": 110,
"end": 1454
} | internal sealed class ____ : IRuntimeProtoSerializerNode
{
bool IRuntimeProtoSerializerNode.IsScalar => true;
private TimeOnlySerializer() { }
internal static readonly TimeOnlySerializer Instance = new TimeOnlySerializer();
static readonly Type expectedType = typeof(TimeOnly);
public Type ExpectedType => expectedType;
bool IRuntimeProtoSerializerNode.RequiresOldValue => false;
bool IRuntimeProtoSerializerNode.ReturnsValue => true;
public object Read(ref ProtoReader.State state, object value)
{
Debug.Assert(value is null); // since replaces
return BclHelpers.ReadTimeOnly(ref state);
}
public void Write(ref ProtoWriter.State state, object value)
{
BclHelpers.WriteTimeOnly(ref state, (TimeOnly)value);
}
void IRuntimeProtoSerializerNode.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom)
{
ctx.EmitStateBasedWrite(nameof(BclHelpers.WriteTimeOnly), valueFrom, typeof(BclHelpers));
}
void IRuntimeProtoSerializerNode.EmitRead(Compiler.CompilerContext ctx, Compiler.Local entity)
{
ctx.EmitStateBasedRead(typeof(BclHelpers), nameof(BclHelpers.ReadTimeOnly), ExpectedType);
}
}
}
#endif | TimeOnlySerializer |
csharp | CommunityToolkit__Maui | samples/CommunityToolkit.Maui.Sample/Pages/Converters/IsNullConverterPage.xaml.cs | {
"start": 118,
"end": 344
} | public partial class ____ : BasePage<IsNullConverterViewModel>
{
public IsNullConverterPage(IsNullConverterViewModel isNullConverterViewModel)
: base(isNullConverterViewModel)
{
InitializeComponent();
}
} | IsNullConverterPage |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 3773045,
"end": 3779470
} | public partial class ____ : global::ChilliCream.Nitro.CommandLine.Cloud.Client.ICreateWorkspaceCommandMutationMutation
{
private readonly global::StrawberryShake.IOperationExecutor<ICreateWorkspaceCommandMutationResult> _operationExecutor;
private readonly global::StrawberryShake.Serialization.IInputValueFormatter _createWorkspaceInputFormatter;
private readonly System.Collections.Immutable.ImmutableArray<global::System.Action<global::StrawberryShake.OperationRequest>> _configure = System.Collections.Immutable.ImmutableArray<global::System.Action<global::StrawberryShake.OperationRequest>>.Empty;
public CreateWorkspaceCommandMutationMutation(global::StrawberryShake.IOperationExecutor<ICreateWorkspaceCommandMutationResult> operationExecutor, global::StrawberryShake.Serialization.ISerializerResolver serializerResolver)
{
_operationExecutor = operationExecutor ?? throw new global::System.ArgumentNullException(nameof(operationExecutor));
_createWorkspaceInputFormatter = serializerResolver.GetInputValueFormatter("CreateWorkspaceInput");
}
private CreateWorkspaceCommandMutationMutation(global::StrawberryShake.IOperationExecutor<ICreateWorkspaceCommandMutationResult> operationExecutor, System.Collections.Immutable.ImmutableArray<global::System.Action<global::StrawberryShake.OperationRequest>> configure, global::StrawberryShake.Serialization.IInputValueFormatter createWorkspaceInputFormatter)
{
_operationExecutor = operationExecutor;
_configure = configure;
_createWorkspaceInputFormatter = createWorkspaceInputFormatter;
}
global::System.Type global::StrawberryShake.IOperationRequestFactory.ResultType => typeof(ICreateWorkspaceCommandMutationResult);
public global::ChilliCream.Nitro.CommandLine.Cloud.Client.ICreateWorkspaceCommandMutationMutation With(global::System.Action<global::StrawberryShake.OperationRequest> configure)
{
return new global::ChilliCream.Nitro.CommandLine.Cloud.Client.CreateWorkspaceCommandMutationMutation(_operationExecutor, _configure.Add(configure), _createWorkspaceInputFormatter);
}
public global::ChilliCream.Nitro.CommandLine.Cloud.Client.ICreateWorkspaceCommandMutationMutation WithRequestUri(global::System.Uri requestUri)
{
return With(r => r.ContextData["StrawberryShake.Transport.Http.HttpConnection.RequestUri"] = requestUri);
}
public global::ChilliCream.Nitro.CommandLine.Cloud.Client.ICreateWorkspaceCommandMutationMutation WithHttpClient(global::System.Net.Http.HttpClient httpClient)
{
return With(r => r.ContextData["StrawberryShake.Transport.Http.HttpConnection.HttpClient"] = httpClient);
}
public async global::System.Threading.Tasks.Task<global::StrawberryShake.IOperationResult<ICreateWorkspaceCommandMutationResult>> ExecuteAsync(global::ChilliCream.Nitro.CommandLine.Cloud.Client.CreateWorkspaceInput input, global::System.Threading.CancellationToken cancellationToken = default)
{
var request = CreateRequest(input);
foreach (var configure in _configure)
{
configure(request);
}
return await _operationExecutor.ExecuteAsync(request, cancellationToken).ConfigureAwait(false);
}
public global::System.IObservable<global::StrawberryShake.IOperationResult<ICreateWorkspaceCommandMutationResult>> Watch(global::ChilliCream.Nitro.CommandLine.Cloud.Client.CreateWorkspaceInput input, global::StrawberryShake.ExecutionStrategy? strategy = null)
{
var request = CreateRequest(input);
return _operationExecutor.Watch(request, strategy);
}
private global::StrawberryShake.OperationRequest CreateRequest(global::ChilliCream.Nitro.CommandLine.Cloud.Client.CreateWorkspaceInput input)
{
var variables = new global::System.Collections.Generic.Dictionary<global::System.String, global::System.Object?>();
variables.Add("input", FormatInput(input));
return CreateRequest(variables);
}
private global::StrawberryShake.OperationRequest CreateRequest(global::System.Collections.Generic.IReadOnlyDictionary<global::System.String, global::System.Object?>? variables)
{
return new global::StrawberryShake.OperationRequest(id: CreateWorkspaceCommandMutationMutationDocument.Instance.Hash.Value, name: "CreateWorkspaceCommandMutation", document: CreateWorkspaceCommandMutationMutationDocument.Instance, strategy: global::StrawberryShake.RequestStrategy.PersistedOperation, variables: variables);
}
private global::System.Object? FormatInput(global::ChilliCream.Nitro.CommandLine.Cloud.Client.CreateWorkspaceInput value)
{
if (value is null)
{
throw new global::System.ArgumentNullException(nameof(value));
}
return _createWorkspaceInputFormatter.Format(value);
}
global::StrawberryShake.OperationRequest global::StrawberryShake.IOperationRequestFactory.Create(global::System.Collections.Generic.IReadOnlyDictionary<global::System.String, global::System.Object?>? variables)
{
return CreateRequest(variables!);
}
}
/// <summary>
/// Represents the operation service of the CreateWorkspaceCommandMutation GraphQL operation
/// <code>
/// mutation CreateWorkspaceCommandMutation($input: CreateWorkspaceInput!) {
/// createWorkspace(input: $input) {
/// __typename
/// workspace {
/// __typename
/// id
/// name
/// ... WorkspaceDetailPrompt_Workspace
/// }
/// errors {
/// __typename
/// ... on UnauthorizedOperation {
/// message
/// }
/// ... on ValidationError {
/// message
/// }
/// ... on Error {
/// message
/// }
/// }
/// }
/// }
///
/// fragment WorkspaceDetailPrompt_Workspace on Workspace {
/// id
/// name
/// personal
/// }
/// </code>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| CreateWorkspaceCommandMutationMutation |
csharp | EventStore__EventStore | src/KurrentDB.Core/Transforms/Identity/IdentityChunkWriteTransform.cs | {
"start": 358,
"end": 1921
} | public sealed class ____ : IChunkWriteTransform {
private ChunkDataWriteStream _stream;
public ChunkDataWriteStream TransformData(ChunkDataWriteStream stream) {
_stream = stream;
return _stream;
}
public ValueTask CompleteData(int footerSize, int alignmentSize, CancellationToken token) {
var chunkHeaderAndDataSize = (int)_stream.Position;
var alignedSize = GetAlignedSize(chunkHeaderAndDataSize + footerSize, alignmentSize);
var paddingSize = alignedSize - chunkHeaderAndDataSize - footerSize;
return paddingSize > 0
? WritePaddingAsync(_stream, paddingSize, token)
: ValueTask.CompletedTask;
static async ValueTask WritePaddingAsync(ChunkDataWriteStream stream, int paddingSize, CancellationToken token) {
using var buffer = Memory.AllocateExactly<byte>(paddingSize);
buffer.Span.Clear(); // ensure that the padding is zeroed
await stream.WriteAsync(buffer.Memory, token);
}
}
public async ValueTask<int> WriteFooter(ReadOnlyMemory<byte> footer, CancellationToken token) {
await _stream.ChunkFileStream.WriteAsync(footer, token);
// The underlying stream can implement buffered I/O, this is why we need to flush it
// to get the correct length (because some bytes can be in the internal buffer)
await _stream.ChunkFileStream.FlushAsync(token);
return (int)_stream.Position;
}
private static int GetAlignedSize(int size, int alignmentSize) {
var quotient = Math.DivRem(size, alignmentSize, out var remainder);
return remainder is 0 ? size : (quotient + 1) * alignmentSize;
}
}
| IdentityChunkWriteTransform |
csharp | AvaloniaUI__Avalonia | src/Avalonia.Base/Media/Imaging/PixelFormatReaders.cs | {
"start": 74,
"end": 334
} | internal record ____ Rgba64Pixel
{
public Rgba64Pixel(ushort r, ushort g, ushort b, ushort a)
{
R = r;
G = g;
B = b;
A = a;
}
public ushort R;
public ushort G;
public ushort B;
public ushort A;
}
| struct |
csharp | App-vNext__Polly | test/Polly.Core.Tests/Retry/RetryDelayGeneratorArgumentsTests.cs | {
"start": 55,
"end": 517
} | public static class ____
{
[Fact]
public static void Ctor_Ok()
{
// Arrange
var context = ResilienceContextPool.Shared.Get(TestCancellation.Token);
// Act
var args = new RetryDelayGeneratorArguments<int>(context, Outcome.FromResult(1), 2);
// Assert
args.Context.ShouldBe(context);
args.Outcome.Result.ShouldBe(1);
args.AttemptNumber.ShouldBe(2);
}
}
| RetryDelayGeneratorArgumentsTests |
csharp | abpframework__abp | framework/src/Volo.Abp.Data/Volo/Abp/Data/DataSeedContext.cs | {
"start": 105,
"end": 1336
} | public class ____
{
public Guid? TenantId { get; set; }
/// <summary>
/// Gets/sets a key-value on the <see cref="Properties"/>.
/// </summary>
/// <param name="name">Name of the property</param>
/// <returns>
/// Returns the value in the <see cref="Properties"/> dictionary by given <paramref name="name"/>.
/// Returns null if given <paramref name="name"/> is not present in the <see cref="Properties"/> dictionary.
/// </returns>
public object? this[string name] {
get => Properties.GetOrDefault(name);
set => Properties[name] = value;
}
/// <summary>
/// Can be used to get/set custom properties.
/// </summary>
[NotNull]
public Dictionary<string, object?> Properties { get; }
public DataSeedContext(Guid? tenantId = null)
{
TenantId = tenantId;
Properties = new Dictionary<string, object?>();
}
/// <summary>
/// Sets a property in the <see cref="Properties"/> dictionary.
/// This is a shortcut for nested calls on this object.
/// </summary>
public virtual DataSeedContext WithProperty(string key, object? value)
{
Properties[key] = value;
return this;
}
}
| DataSeedContext |
csharp | unoplatform__uno | src/Uno.UI.Tests/Windows_UI_Xaml_Data/xBindTests/Controls/Binding_Static_Event_DataTemplate.xaml.cs | {
"start": 959,
"end": 1326
} | public static class ____
{
public static int CheckedRaised { get; private set; }
public static int UncheckedRaised { get; private set; }
internal static void OnCheckedRaised()
{
CheckedRaised++;
}
internal static void OnUncheckedRaised(object sender, RoutedEventArgs args)
{
UncheckedRaised++;
}
}
}
| Binding_Static_Event_DataTemplate_Model_Class |
csharp | microsoft__semantic-kernel | dotnet/samples/GettingStartedWithProcesses/Step03/Processes/FriedFishProcess.cs | {
"start": 379,
"end": 6510
} | public static class ____
{
public const string PrepareFriedFish = nameof(PrepareFriedFish);
// When multiple processes use the same final step, the should event marked as public
// so that the step event can be used as the output event of the process too.
// In these samples both fried fish and potato fries end with FryStep success
public const string FriedFishReady = FryFoodStep.OutputEvents.FriedFoodReady;
}
/// <summary>
/// For a visual reference of the FriedFishProcess check this
/// <see href="https://github.com/microsoft/semantic-kernel/blob/main/dotnet/samples/GettingStartedWithProcesses/README.md#fried-fish-preparation-process" >diagram</see>
/// </summary>
/// <param name="processName">name of the process</param>
/// <returns><see cref="ProcessBuilder"/></returns>
public static ProcessBuilder CreateProcess(string processName = "FriedFishProcess")
{
var processBuilder = new ProcessBuilder(processName);
var gatherIngredientsStep = processBuilder.AddStepFromType<GatherFriedFishIngredientsStep>();
var chopStep = processBuilder.AddStepFromType<CutFoodStep>();
var fryStep = processBuilder.AddStepFromType<FryFoodStep>();
processBuilder
.OnInputEvent(ProcessEvents.PrepareFriedFish)
.SendEventTo(new ProcessFunctionTargetBuilder(gatherIngredientsStep));
gatherIngredientsStep
.OnEvent(GatherFriedFishIngredientsStep.OutputEvents.IngredientsGathered)
.SendEventTo(new ProcessFunctionTargetBuilder(chopStep, functionName: CutFoodStep.ProcessStepFunctions.ChopFood));
chopStep
.OnEvent(CutFoodStep.OutputEvents.ChoppingReady)
.SendEventTo(new ProcessFunctionTargetBuilder(fryStep));
fryStep
.OnEvent(FryFoodStep.OutputEvents.FoodRuined)
.SendEventTo(new ProcessFunctionTargetBuilder(gatherIngredientsStep));
return processBuilder;
}
public static ProcessBuilder CreateProcessWithStatefulStepsV1(string processName = "FriedFishWithStatefulStepsProcess")
{
// It is recommended to specify process version in case this process is used as a step by another process
var processBuilder = new ProcessBuilder(processName) { Version = "FriedFishProcess.v1" }; ;
var gatherIngredientsStep = processBuilder.AddStepFromType<GatherFriedFishIngredientsWithStockStep>();
var chopStep = processBuilder.AddStepFromType<CutFoodStep>();
var fryStep = processBuilder.AddStepFromType<FryFoodStep>();
processBuilder
.OnInputEvent(ProcessEvents.PrepareFriedFish)
.SendEventTo(new ProcessFunctionTargetBuilder(gatherIngredientsStep));
gatherIngredientsStep
.OnEvent(GatherFriedFishIngredientsWithStockStep.OutputEvents.IngredientsGathered)
.SendEventTo(new ProcessFunctionTargetBuilder(chopStep, functionName: CutFoodWithSharpeningStep.ProcessStepFunctions.ChopFood));
chopStep
.OnEvent(CutFoodWithSharpeningStep.OutputEvents.ChoppingReady)
.SendEventTo(new ProcessFunctionTargetBuilder(fryStep));
fryStep
.OnEvent(FryFoodStep.OutputEvents.FoodRuined)
.SendEventTo(new ProcessFunctionTargetBuilder(gatherIngredientsStep));
return processBuilder;
}
/// <summary>
/// For a visual reference of the FriedFishProcess with stateful steps check this
/// <see href="https://github.com/microsoft/semantic-kernel/blob/main/dotnet/samples/GettingStartedWithProcesses/README.md#fried-fish-preparation-with-knife-sharpening-and-ingredient-stock-process" >diagram</see>
/// </summary>
/// <param name="processName">name of the process</param>
/// <returns><see cref="ProcessBuilder"/></returns>
public static ProcessBuilder CreateProcessWithStatefulStepsV2(string processName = "FriedFishWithStatefulStepsProcess")
{
// It is recommended to specify process version in case this process is used as a step by another process
var processBuilder = new ProcessBuilder(processName) { Version = "FriedFishProcess.v2" };
var gatherIngredientsStep = processBuilder.AddStepFromType<GatherFriedFishIngredientsWithStockStep>(id: "gatherFishIngredientStep", aliases: ["GatherFriedFishIngredientsWithStockStep"]);
var chopStep = processBuilder.AddStepFromType<CutFoodWithSharpeningStep>(id: "chopFishStep", aliases: ["CutFoodStep"]);
var fryStep = processBuilder.AddStepFromType<FryFoodStep>(id: "fryFishStep", aliases: ["FryFoodStep"]);
processBuilder
.OnInputEvent(ProcessEvents.PrepareFriedFish)
.SendEventTo(new ProcessFunctionTargetBuilder(gatherIngredientsStep));
gatherIngredientsStep
.OnEvent(GatherFriedFishIngredientsWithStockStep.OutputEvents.IngredientsGathered)
.SendEventTo(new ProcessFunctionTargetBuilder(chopStep, functionName: CutFoodWithSharpeningStep.ProcessStepFunctions.ChopFood));
gatherIngredientsStep
.OnEvent(GatherFriedFishIngredientsWithStockStep.OutputEvents.IngredientsOutOfStock)
.StopProcess();
chopStep
.OnEvent(CutFoodWithSharpeningStep.OutputEvents.ChoppingReady)
.SendEventTo(new ProcessFunctionTargetBuilder(fryStep));
chopStep
.OnEvent(CutFoodWithSharpeningStep.OutputEvents.KnifeNeedsSharpening)
.SendEventTo(new ProcessFunctionTargetBuilder(chopStep, functionName: CutFoodWithSharpeningStep.ProcessStepFunctions.SharpenKnife));
chopStep
.OnEvent(CutFoodWithSharpeningStep.OutputEvents.KnifeSharpened)
.SendEventTo(new ProcessFunctionTargetBuilder(chopStep, functionName: CutFoodWithSharpeningStep.ProcessStepFunctions.ChopFood));
fryStep
.OnEvent(FryFoodStep.OutputEvents.FoodRuined)
.SendEventTo(new ProcessFunctionTargetBuilder(gatherIngredientsStep));
return processBuilder;
}
[KernelProcessStepMetadata("GatherFishIngredient.V1")]
| ProcessEvents |
csharp | MassTransit__MassTransit | tests/MassTransit.Tests/Messages/PartialSerializationTestMessage.cs | {
"start": 152,
"end": 2672
} | public class ____ :
IEquatable<PartialSerializationTestMessage>
{
public Guid GuidValue { get; set; }
public bool BoolValue { get; set; }
public byte ByteValue { get; set; }
public string StringValue { get; set; }
public int IntValue { get; set; }
public long LongValue { get; set; }
public decimal DecimalValue { get; set; }
public double DoubleValue { get; set; }
public DateTime DateTimeValue { get; set; }
public decimal? MaybeMoney { get; set; }
public bool Equals(PartialSerializationTestMessage obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
return obj.GuidValue.Equals(GuidValue) &&
Equals(obj.StringValue, StringValue) &&
obj.IntValue == IntValue &&
obj.BoolValue == BoolValue &&
obj.ByteValue == ByteValue &&
obj.LongValue == LongValue &&
obj.DecimalValue == DecimalValue &&
obj.DoubleValue == DoubleValue &&
obj.MaybeMoney == MaybeMoney &&
obj.DateTimeValue.Equals(DateTimeValue);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
if (ReferenceEquals(this, obj))
return true;
if (obj.GetType() != typeof(PartialSerializationTestMessage))
return false;
return Equals((PartialSerializationTestMessage)obj);
}
public override int GetHashCode()
{
unchecked
{
var result = GuidValue.GetHashCode();
result = (result * 397) ^ (StringValue != null ? StringValue.GetHashCode() : 0);
result = (result * 397) ^ IntValue;
result = (result * 397) ^ LongValue.GetHashCode();
result = (result * 397) ^ BoolValue.GetHashCode();
result = (result * 397) ^ ByteValue.GetHashCode();
result = (result * 397) ^ DecimalValue.GetHashCode();
result = (result * 397) ^ DoubleValue.GetHashCode();
result = (result * 397) ^ DateTimeValue.GetHashCode();
result = (result * 397) ^ MaybeMoney.GetHashCode();
return result;
}
}
}
}
| PartialSerializationTestMessage |
csharp | nunit__nunit | src/NUnitFramework/framework/Internal/Results/TestResult.cs | {
"start": 22730,
"end": 30917
} | private struct ____
{
public ResultState ResultState { get; }
public string Message { get; }
public string? StackTrace { get; }
public ExceptionResult(Exception ex, FailureSite site)
{
if (ex is ResultStateException exception)
{
ResultState = exception.ResultState.WithSite(site);
Message = ex.GetMessageWithoutThrowing();
StackTrace = StackFilter.DefaultFilter.Filter(ex.GetStackTraceWithoutThrowing());
}
#if THREAD_ABORT
else if (ex is ThreadAbortException)
{
ResultState = ResultState.Cancelled.WithSite(site);
Message = "Test cancelled by user";
StackTrace = ex.GetStackTraceWithoutThrowing();
}
#endif
else if (ex is OperationCanceledException && TestExecutionContext.CurrentContext.CancellationToken.IsCancellationRequested)
{
ResultState = ResultState.Failure.WithSite(site);
Message = $"Test exceeded CancelAfter value of {TestExecutionContext.CurrentContext.TestCaseTimeout}ms";
StackTrace = ExceptionHelper.BuildStackTrace(ex);
}
else
{
ResultState = ResultState.Error.WithSite(site);
Message = ExceptionHelper.BuildMessage(ex);
StackTrace = ExceptionHelper.BuildStackTrace(ex);
}
}
}
/// <summary>
/// Update overall test result, including legacy Message, based
/// on AssertionResults that have been saved to this point.
/// </summary>
public void RecordTestCompletion()
{
switch (_assertionResults.Count)
{
case 0:
SetResult(ResultState.Success);
break;
case 1:
AssertionResult assertionResult = AssertionResults[0];
SetResult(
AssertionStatusToResultState(assertionResult.Status).WithSite(assertionResult.Site),
assertionResult.Message,
assertionResult.StackTrace);
break;
default:
SetResult(
AssertionStatusToResultState(WorstAssertionStatus),
CreateLegacyFailureMessage());
break;
}
}
/// <summary>
/// Record an assertion result
/// </summary>
public void RecordAssertion(AssertionResult assertion)
{
_assertionResults.Add(assertion);
}
/// <summary>
/// Record an assertion result
/// </summary>
public void RecordAssertion(AssertionStatus status, string message, string? stackTrace)
{
RecordAssertion(new AssertionResult(status, message, stackTrace));
}
/// <summary>
/// Record an assertion result
/// </summary>
public void RecordAssertion(AssertionStatus status, string message)
{
RecordAssertion(status, message, null);
}
/// <summary>
/// Creates a failure message incorporating failures
/// from a Multiple Assert block for use by runners
/// that don't know about AssertionResults.
/// </summary>
/// <returns>Message as a string</returns>
private string CreateLegacyFailureMessage()
{
var writer = new StringWriter();
if (_assertionResults.Count > 1)
writer.WriteLine(MULTIPLE_FAILURES_OR_WARNINGS_MESSAGE);
int counter = 0;
foreach (var assertion in _assertionResults)
{
writer.WriteLine($" {++counter}) {assertion.Message}");
if (assertion.StackTrace is not null)
writer.WriteLine($" {assertion.StackTrace}");
}
return writer.ToString();
}
#endregion
#region Helper Methods
/// <summary>
/// Adds a failure element to a node and returns it.
/// </summary>
/// <param name="targetNode">The target node.</param>
/// <returns>The new failure element.</returns>
private TNode AddFailureElement(TNode targetNode)
{
TNode failureNode = targetNode.AddElement("failure");
if (!string.IsNullOrWhiteSpace(Message))
failureNode.AddElementWithCDATA("message", Message);
if (!string.IsNullOrWhiteSpace(StackTrace))
failureNode.AddElementWithCDATA("stack-trace", StackTrace);
return failureNode;
}
private TNode AddOutputElement(TNode targetNode, string output)
{
return targetNode.AddElementWithCDATA("output", output);
}
private TNode AddAssertionsElement(TNode targetNode)
{
var assertionsNode = targetNode.AddElement("assertions");
foreach (var assertion in _assertionResults)
{
TNode assertionNode = assertionsNode.AddElement("assertion");
assertionNode.AddAttribute("result", assertion.Status.ToString());
if (assertion.Message is not null)
assertionNode.AddElementWithCDATA("message", assertion.Message);
if (assertion.StackTrace is not null)
assertionNode.AddElementWithCDATA("stack-trace", assertion.StackTrace);
}
return assertionsNode;
}
private ResultState AssertionStatusToResultState(AssertionStatus status)
{
switch (status)
{
case AssertionStatus.Inconclusive:
return ResultState.Inconclusive;
default:
case AssertionStatus.Passed:
return ResultState.Success;
case AssertionStatus.Warning:
return ResultState.Warning;
case AssertionStatus.Failed:
return ResultState.Failure;
case AssertionStatus.Error:
return ResultState.Error;
}
}
private AssertionStatus ResultStateToAssertionStatus(ResultState resultState)
{
switch (resultState.Status)
{
case TestStatus.Skipped:
case TestStatus.Inconclusive:
return AssertionStatus.Inconclusive;
default:
case TestStatus.Passed:
return AssertionStatus.Passed;
case TestStatus.Warning:
return AssertionStatus.Warning;
case TestStatus.Failed:
if (resultState.Label == ResultState.Error.Label)
return AssertionStatus.Error;
if (resultState.Label == ResultState.Failure.Label)
return AssertionStatus.Failed;
return AssertionStatus.Inconclusive;
}
}
/// <summary>
/// Adds an attachments element to a node and returns it.
/// </summary>
/// <param name="targetNode">The target node.</param>
/// <returns>The new attachments element.</returns>
private TNode AddAttachmentsElement(TNode targetNode)
{
TNode attachmentsNode = targetNode.AddElement("attachments");
foreach (var attachment in _testAttachments)
{
var attachmentNode = attachmentsNode.AddElement("attachment");
attachmentNode.AddElement("filePath", attachment.FilePath);
if (attachment.Description is not null)
attachmentNode.AddElementWithCDATA("description", attachment.Description);
}
return attachmentsNode;
}
#endregion
}
}
| ExceptionResult |
csharp | dotnet__efcore | test/EFCore.Proxies.Tests/ChangeDetectionProxyTests.cs | {
"start": 11434,
"end": 12194
} | private class ____<TEntity>(Action<EntityTypeBuilder<TEntity>> entityBuilderAction = null) : DbContext
where TEntity : class
{
private readonly Action<EntityTypeBuilder<TEntity>> _entityBuilderAction = entityBuilderAction;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseChangeTrackingProxies()
.UseInMemoryDatabase(GetType().ShortDisplayName());
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var builder = modelBuilder.SharedTypeEntity<TEntity>("STET");
builder.Property<int>("Id");
_entityBuilderAction?.Invoke(builder);
}
}
| SharedChangeContext |
csharp | ServiceStack__ServiceStack | ServiceStack.OrmLite/tests/ServiceStack.OrmLite.PostgreSQL.Tests/Issues/JsonDataTypeTests.cs | {
"start": 304,
"end": 1906
} | public class ____ : OrmLiteProvidersTestBase
{
public JsonDataTypeTests(DialectContext context) : base(context) {}
[Test]
public void Can_save_and_restore_JSON_property()
{
using (new TemporaryNamingStrategy(DialectProvider, new OrmLiteNamingStrategyBase()))
{
var item = new LicenseCheckTemp
{
Body = new CheckHistory
{
List = {
new ItemHistory { AddedOn = DateTime.MaxValue, Note = "Test" }
}
}
};
using (var db = OpenDbConnection())
{
db.DropAndCreateTable<LicenseCheckTemp>();
db.GetLastSql().Print();
db.Save(item);
}
using (var db = OpenDbConnection())
{
var items = db.Select<LicenseCheckTemp>();
items.PrintDump();
foreach (var licenseCheck in items.OrderBy(x => x.Id))
{
if (licenseCheck.Body != null && licenseCheck.Body.List.Any())
{
foreach (var itemHistory in licenseCheck.Body.List)
{
"{0} : Note {1}".Print(itemHistory.AddedOn, itemHistory.Note);
}
}
}
}
}
}
}
| JsonDataTypeTests |
csharp | moq__moq4 | src/Moq.Tests/MockFixture.cs | {
"start": 37338,
"end": 38169
} | public interface ____
{
int A { get; }
BadSerializable BadSerializable { get; }
string C { get; }
}
[Fact]
public void Accessing_property_of_bad_serializable_type_throws()
{
var mock = new Mock<IHaveBadSerializableProperty>() { DefaultValue = DefaultValue.Mock };
Assert.ThrowsAny<Exception>(() => mock.Object.BadSerializable);
}
[Fact]
public void Accessing_property_of_bad_serializable_type_after_SetupAllProperties_throws()
{
var mock = new Mock<IHaveBadSerializableProperty>() { DefaultValue = DefaultValue.Mock };
mock.SetupAllProperties();
Assert.ThrowsAny<Exception>(() => mock.Object.BadSerializable);
}
#endif
}
}
| IHaveBadSerializableProperty |
csharp | MassTransit__MassTransit | src/MassTransit/Consumers/Configuration/BatchConsumerMessageSpecification.cs | {
"start": 4505,
"end": 5144
} | class ____ :
IConsumerMessageConfigurator<Batch<TMessage>>
{
readonly IBuildPipeConfigurator<ConsumeContext<Batch<TMessage>>> _batchConfigurator;
public ConsumerMessageConfigurator(IBuildPipeConfigurator<ConsumeContext<Batch<TMessage>>> batchConfigurator)
{
_batchConfigurator = batchConfigurator;
}
public void AddPipeSpecification(IPipeSpecification<ConsumeContext<Batch<TMessage>>> specification)
{
_batchConfigurator.AddPipeSpecification(specification);
}
}
}
}
| ConsumerMessageConfigurator |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs | {
"start": 200008,
"end": 200225
} | public class ____
{
public int Id { get; set; }
public RelatedEntity922 ParentEntity { get; set; }
public IEnumerable<RelatedEntity924> ChildEntities { get; set; }
}
| RelatedEntity923 |
csharp | JoshClose__CsvHelper | src/CsvHelper/Configuration/ClassMapBuilder.cs | {
"start": 10549,
"end": 10603
} | private class ____<T> : ClassMap<T> { }
}
| BuilderClassMap |
csharp | dotnet__aspnetcore | src/Razor/Razor.Runtime/test/Runtime/TagHelpers/TestTagHelpers/TagHelperDescriptorFactoryTagHelpers.cs | {
"start": 2090,
"end": 2294
} | public class ____ : TagHelper
{
[EditorBrowsable(EditorBrowsableState.Never)]
public int Property { get; set; }
public virtual int Property2 { get; set; }
}
| MultiPropertyEditorBrowsableTagHelper |
csharp | abpframework__abp | framework/test/Volo.Abp.ObjectExtending.Tests/Volo/Abp/ObjectExtending/AbpObjectExtendingTestModule.cs | {
"start": 223,
"end": 1563
} | public class ____ : AbpModule
{
private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner();
public override void PreConfigureServices(ServiceConfigurationContext context)
{
OneTimeRunner.Run(() =>
{
ObjectExtensionManager.Instance
.AddOrUpdateProperty<ExtensibleTestPerson, string>("Name")
.AddOrUpdateProperty<ExtensibleTestPerson, int>("Age")
.AddOrUpdateProperty<ExtensibleTestPerson, string>("NoPairCheck", options => options.CheckPairDefinitionOnMapping = false)
.AddOrUpdateProperty<ExtensibleTestPerson, string>("CityName")
.AddOrUpdateProperty<ExtensibleTestPerson, ExtensibleTestEnumProperty>("EnumProperty")
.AddOrUpdateProperty<ExtensibleTestPersonDto, string>("Name")
.AddOrUpdateProperty<ExtensibleTestPersonDto, int>("ChildCount")
.AddOrUpdateProperty<ExtensibleTestPersonDto, string>("CityName")
.AddOrUpdateProperty<ExtensibleTestPersonDto, ExtensibleTestEnumProperty>("EnumProperty")
.AddOrUpdateProperty<ExtensibleTestPersonWithRegularPropertiesDto, string>("Name")
.AddOrUpdateProperty<ExtensibleTestPersonWithRegularPropertiesDto, int>("Age");
});
}
}
| AbpObjectExtendingTestModule |
csharp | dotnet__maui | src/Core/src/Platform/Windows/BorderExtensions.cs | {
"start": 315,
"end": 3610
} | public static class ____
{
public static void UpdateBorderShape(this Path borderPath, IShape? borderShape, double width, double height)
{
borderPath.UpdatePath(borderShape, width, height);
}
internal static void UpdatePath(this Path borderPath, IShape? borderShape, double width, double height)
{
if (borderShape is null || width <= 0 || height <= 0)
return;
var strokeThickness = borderPath?.StrokeThickness ?? 0;
var pathSize = new Graphics.Rect(0, 0, width - strokeThickness, height - strokeThickness);
var shapePath = borderShape.PathForBounds(pathSize);
var geometry = shapePath.AsPathGeometry();
if (borderPath is not null)
{
borderPath.Data = geometry;
borderPath.RenderTransform = new TranslateTransform() { X = strokeThickness / 2, Y = strokeThickness / 2 };
}
}
public static void UpdateBackground(this Path borderPath, Paint? background)
{
if (borderPath == null)
return;
borderPath.Fill = background?.ToPlatform();
}
public static void UpdateStroke(this Path borderPath, Paint? borderBrush)
{
if (borderPath == null)
return;
borderPath.Stroke = borderBrush?.ToPlatform();
}
public static void UpdateStrokeThickness(this Path borderPath, double borderWidth)
{
if (borderPath == null)
return;
borderPath.StrokeThickness = borderWidth;
}
public static void UpdateStrokeDashPattern(this Path borderPath, float[]? borderDashArray)
{
if (borderPath == null)
return;
borderPath.StrokeDashArray?.Clear();
if (borderDashArray != null && borderDashArray.Length > 0)
{
if (borderPath.StrokeDashArray == null)
borderPath.StrokeDashArray = new WDoubleCollection();
double[] array = new double[borderDashArray.Length];
borderDashArray.CopyTo(array, 0);
foreach (double value in array)
{
borderPath.StrokeDashArray.Add(value);
}
}
}
public static void UpdateBorderDashOffset(this Path borderPath, double borderDashOffset)
{
if (borderPath == null)
return;
borderPath.StrokeDashOffset = borderDashOffset;
}
public static void UpdateStrokeMiterLimit(this Path borderPath, double strokeMiterLimit)
{
if (borderPath == null)
return;
borderPath.StrokeMiterLimit = strokeMiterLimit;
}
public static void UpdateStrokeLineCap(this Path borderPath, LineCap strokeLineCap)
{
if (borderPath == null)
return;
WPenLineCap wLineCap = WPenLineCap.Flat;
switch (strokeLineCap)
{
case LineCap.Butt:
wLineCap = WPenLineCap.Flat;
break;
case LineCap.Square:
wLineCap = WPenLineCap.Square;
break;
case LineCap.Round:
wLineCap = WPenLineCap.Round;
break;
}
borderPath.StrokeStartLineCap = borderPath.StrokeEndLineCap = wLineCap;
}
public static void UpdateStrokeLineJoin(this Path borderPath, LineJoin strokeLineJoin)
{
if (borderPath == null)
return;
WPenLineJoin wLineJoin = WPenLineJoin.Miter;
switch (strokeLineJoin)
{
case LineJoin.Miter:
wLineJoin = WPenLineJoin.Miter;
break;
case LineJoin.Bevel:
wLineJoin = WPenLineJoin.Bevel;
break;
case LineJoin.Round:
wLineJoin = WPenLineJoin.Round;
break;
}
borderPath.StrokeLineJoin = wLineJoin;
}
}
} | BorderExtensions |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.Core/src/ActionConstraints/ActionConstraintCache.cs | {
"start": 5006,
"end": 5455
} | internal sealed class ____
{
private readonly ActionDescriptorCollection _actions;
public InnerCache(ActionDescriptorCollection actions)
{
_actions = actions;
}
public ConcurrentDictionary<ActionDescriptor, CacheEntry> Entries { get; } =
new ConcurrentDictionary<ActionDescriptor, CacheEntry>();
public int Version => _actions.Version;
}
internal readonly | InnerCache |
csharp | dotnet__efcore | test/EFCore.Tests/Query/EntityMaterializerSourceTest.cs | {
"start": 21695,
"end": 21846
} | private class ____(DbContext context)
{
public int Id { get; set; }
public DbContext Context { get; } = context;
}
| WithContext |
csharp | AvaloniaUI__Avalonia | src/Avalonia.Controls/Templates/FuncControlTemplate.cs | {
"start": 213,
"end": 840
} | public class ____ : FuncTemplate<TemplatedControl, Control>, IControlTemplate
{
/// <summary>
/// Initializes a new instance of the <see cref="FuncControlTemplate"/> class.
/// </summary>
/// <param name="build">The build function.</param>
public FuncControlTemplate(Func<TemplatedControl, INameScope, Control> build)
: base(build)
{
}
public new TemplateResult<Control> Build(TemplatedControl param)
{
var (control, scope) = BuildWithNameScope(param);
return new(control, scope);
}
}
}
| FuncControlTemplate |
csharp | smartstore__Smartstore | src/Smartstore/Imaging/ImageWrapper.cs | {
"start": 59,
"end": 2298
} | public class ____ : Disposable, IImage
{
private readonly IImageInfo _info;
private readonly bool _disposeStream;
public ImageWrapper(Stream stream, IImageInfo info, bool disposeStream = true)
{
Guard.NotNull(stream);
Guard.NotNull(info);
InStream = stream;
Format = info.Format;
SourceSize = new Size(info.Width, info.Height);
_info = info;
_disposeStream = disposeStream;
}
#region IImageInfo
/// <inheritdoc/>
public int Width => _info.Width;
/// <inheritdoc/>
public int Height => _info.Height;
/// <inheritdoc/>
public byte BitDepth => _info.BitDepth;
/// <inheritdoc/>
public IImageFormat Format { get; set; }
/// <inheritdoc/>
public IEnumerable<ImageMetadataEntry> GetMetadata()
=> _info.GetMetadata();
#endregion
public Stream InStream { get; }
/// <inheritdoc/>
public Size SourceSize { get; set; }
/// <inheritdoc/>
public IImage Save(Stream stream, IImageFormat format = null)
=> SaveInternal(stream, format, false).Await();
/// <inheritdoc/>
public Task<IImage> SaveAsync(Stream stream, IImageFormat format = null)
=> SaveInternal(stream, format, true);
private async Task<IImage> SaveInternal(Stream stream, IImageFormat format, bool async)
{
Guard.NotNull(stream);
if (stream.CanSeek)
{
stream.SetLength(0);
}
if (async)
{
await InStream.CopyToAsync(stream);
}
else
{
InStream.CopyTo(stream);
}
if (stream.CanSeek)
{
stream.Position = 0;
}
if (InStream.CanSeek)
{
InStream.Position = 0;
}
return this;
}
protected override void OnDispose(bool disposing)
{
if (disposing && _disposeStream)
InStream.Dispose();
}
}
}
| ImageWrapper |
csharp | FoundatioFx__Foundatio | src/Foundatio/Utility/IHaveLogger.cs | {
"start": 179,
"end": 262
} | public interface ____
{
ILoggerFactory LoggerFactory { get; }
}
| IHaveLoggerFactory |
csharp | ServiceStack__ServiceStack | ServiceStack.OrmLite/tests/ServiceStack.OrmLite.Tests/Issues/ComplexJoinWithAlias.cs | {
"start": 484,
"end": 1417
} | public class ____(DialectContext context) : OrmLiteProvidersTestBase(context)
{
private static long _classAColumnAId;
private static void Init(IDbConnection db)
{
db.DropAndCreateTable<ClassA>();
db.DropAndCreateTable<ClassB>();
_classAColumnAId = db.Insert(new ClassA { ColumnA = "1" }, true);
db.Insert(new ClassA { ColumnA = "2" });
db.Insert(new ClassA { ColumnA = "3" });
db.Insert(new ClassB { ColumnB = "1" });
db.Insert(new ClassB { ColumnB = "2" });
}
[Test]
public void ComplexJoin_With_Alias_Columns()
{
using var db = OpenDbConnection();
Init(db);
var q = db.From<ClassA>()
.Join<ClassB>((a, b) => a.ColumnA == b.ColumnB)
.Where<ClassA>(a => a.Id == _classAColumnAId);
var results = db.Single(q);
Assert.That(results.ColumnA, Is.EqualTo("1"));
}
} | ComplexJoinWithAlias |
csharp | MassTransit__MassTransit | src/Persistence/MassTransit.DapperIntegration/DapperIntegration/Saga/DapperSagaRepositoryContext.cs | {
"start": 240,
"end": 3050
} | public class ____<TSaga, TMessage> :
ConsumeContextScope<TMessage>,
SagaRepositoryContext<TSaga, TMessage>
where TSaga : class, ISaga
where TMessage : class
{
readonly ConsumeContext<TMessage> _consumeContext;
readonly DatabaseContext<TSaga> _context;
readonly ISagaConsumeContextFactory<DatabaseContext<TSaga>, TSaga> _factory;
public DapperSagaRepositoryContext(DatabaseContext<TSaga> context, ConsumeContext<TMessage> consumeContext,
ISagaConsumeContextFactory<DatabaseContext<TSaga>, TSaga> factory)
: base(consumeContext, context)
{
_context = context;
_consumeContext = consumeContext;
_factory = factory;
}
public Task<SagaConsumeContext<TSaga, T>> CreateSagaConsumeContext<T>(ConsumeContext<T> consumeContext, TSaga instance, SagaConsumeContextMode mode)
where T : class
{
return _factory.CreateSagaConsumeContext(_context, consumeContext, instance, mode);
}
public Task<SagaConsumeContext<TSaga, TMessage>> Add(TSaga instance)
{
return _factory.CreateSagaConsumeContext(_context, _consumeContext, instance, SagaConsumeContextMode.Add);
}
public async Task<SagaConsumeContext<TSaga, TMessage>> Insert(TSaga instance)
{
await _context.InsertAsync(instance, CancellationToken).ConfigureAwait(false);
return await _factory.CreateSagaConsumeContext(_context, _consumeContext, instance, SagaConsumeContextMode.Insert).ConfigureAwait(false);
}
public async Task<SagaConsumeContext<TSaga, TMessage>> Load(Guid correlationId)
{
var instance = await _context.LoadAsync(correlationId, CancellationToken).ConfigureAwait(false);
if (instance == default)
return default;
return await _factory.CreateSagaConsumeContext(_context, _consumeContext, instance, SagaConsumeContextMode.Load).ConfigureAwait(false);
}
public Task Save(SagaConsumeContext<TSaga> context)
{
return _context.InsertAsync(context.Saga, CancellationToken);
}
public Task Update(SagaConsumeContext<TSaga> context)
{
return _context.UpdateAsync(context.Saga, CancellationToken);
}
public Task Delete(SagaConsumeContext<TSaga> context)
{
return _context.DeleteAsync(context.Saga, CancellationToken);
}
public Task Discard(SagaConsumeContext<TSaga> context)
{
return Task.CompletedTask;
}
public Task Undo(SagaConsumeContext<TSaga> context)
{
return Task.CompletedTask;
}
}
| DapperSagaRepositoryContext |
csharp | nunit__nunit | src/NUnitFramework/tests/Internal/CallContextTests.cs | {
"start": 3987,
"end": 4126
} | public class ____ : GenericIdentity
{
public TestIdentity(string name) : base(name)
{
}
}
}
#endif
| TestIdentity |
csharp | protobuf-net__protobuf-net | assorted/demo-rpc-client-silverlight/Page.xaml.cs | {
"start": 438,
"end": 1097
} | public partial class ____ : UserControl
{
public Page()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var client = new NorthwindClient();
client.GetCustomersCompleted += new EventHandler<GetCustomersCompletedEventArgs>(client_GetCustomersCompleted);
client.GetCustomersAsync();
}
void client_GetCustomersCompleted(object sender, GetCustomersCompletedEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
list.ItemsSource = e.Result;
});
}
}
}
| Page |
csharp | dotnet__aspnetcore | src/Security/Authentication/Core/src/ISystemClock.cs | {
"start": 309,
"end": 465
} | public interface ____
{
/// <summary>
/// Retrieves the current system time in UTC.
/// </summary>
DateTimeOffset UtcNow { get; }
}
| ISystemClock |
csharp | aspnetboilerplate__aspnetboilerplate | src/Abp.Zero.Common/Application/Features/IAbpZeroFeatureValueStore.cs | {
"start": 72,
"end": 624
} | public interface ____ : IFeatureValueStore
{
Task<string> GetValueOrNullAsync(int tenantId, string featureName);
string GetValueOrNull(int tenantId, string featureName);
Task<string> GetEditionValueOrNullAsync(int editionId, string featureName);
string GetEditionValueOrNull(int editionId, string featureName);
Task SetEditionFeatureValueAsync(int editionId, string featureName, string value);
void SetEditionFeatureValue(int editionId, string featureName, string value);
}
} | IAbpZeroFeatureValueStore |
csharp | files-community__Files | src/Files.App/Helpers/Layout/LayoutPreferencesDatabaseManager.cs | {
"start": 195,
"end": 902
} | public class ____
{
// Fields
private static readonly Lazy<LayoutPreferencesDatabase> dbInstance = new(() => new());
// Methods
public LayoutPreferencesItem? GetPreferences(string filePath, ulong? frn = null)
{
return dbInstance.Value.GetPreferences(filePath, frn);
}
public void SetPreferences(string filePath, ulong? frn, LayoutPreferencesItem? preferencesItem)
{
dbInstance.Value.SetPreferences(filePath, frn, preferencesItem);
}
public void ResetAll()
{
dbInstance.Value.ResetAll();
}
public void Import(string json)
{
dbInstance.Value.Import(json);
}
public string Export()
{
return dbInstance.Value.Export();
}
}
}
| LayoutPreferencesDatabaseManager |
csharp | dotnet__aspnetcore | src/Shared/TrimmingAttributes.cs | {
"start": 1998,
"end": 3373
} | internal sealed class ____ : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="RequiresUnreferencedCodeAttribute"/> class
/// with the specified message.
/// </summary>
/// <param name="message">
/// A message that contains information about the usage of unreferenced code.
/// </param>
public RequiresUnreferencedCodeAttribute(string message)
{
Message = message;
}
/// <summary>
/// Gets a message that contains information about the usage of unreferenced code.
/// </summary>
public string Message { get; }
/// <summary>
/// Gets or sets an optional URL that contains more information about the method,
/// why it requires unreferenced code, and what options a consumer has to deal with it.
/// </summary>
public string? Url { get; set; }
}
/// <summary>
/// Suppresses reporting of a specific rule violation, allowing multiple suppressions on a
/// single code artifact.
/// </summary>
/// <remarks>
/// <see cref="UnconditionalSuppressMessageAttribute"/> is different than
/// <see cref="SuppressMessageAttribute"/> in that it doesn't have a
/// <see cref="ConditionalAttribute"/>. So it is always preserved in the compiled assembly.
/// </remarks>
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
| RequiresUnreferencedCodeAttribute |
csharp | dotnet__maui | src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue18251.cs | {
"start": 116,
"end": 580
} | public class ____ : _IssuesUITest
{
public Issue18251(TestDevice device) : base(device) { }
public override string Issue => "IllegalArgumentException when changing number of tabbar pages";
[Test]
[Category(UITestCategories.Shell)]
public void NoExceptionShouldBeThrownAddingShellTabs()
{
App.WaitForElement("button");
for (int i = 0; i < 2; i++)
{
App.Click("button");
}
// The test passes if no crash is observed
}
}
} | Issue18251 |
csharp | OrchardCMS__OrchardCore | src/OrchardCore.Modules/OrchardCore.Search.Lucene/Startup.cs | {
"start": 3513,
"end": 3780
} | public sealed class ____ : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddSearchService<LuceneSearchService>(LuceneConstants.ProviderName);
}
}
[RequireFeatures("OrchardCore.Deployment")]
| SearchStartup |
csharp | SixLabors__ImageSharp | src/ImageSharp/Processing/Processors/Normalization/AdaptiveHistogramEqualizationSlidingWindowProcessor.cs | {
"start": 270,
"end": 2063
} | public class ____ : HistogramEqualizationProcessor
{
/// <summary>
/// Initializes a new instance of the <see cref="AdaptiveHistogramEqualizationSlidingWindowProcessor"/> class.
/// </summary>
/// <param name="luminanceLevels">The number of different luminance levels. Typical values are 256 for 8-bit grayscale images
/// or 65536 for 16-bit grayscale images.</param>
/// <param name="clipHistogram">Indicating whether to clip the histogram bins at a specific value.</param>
/// <param name="clipLimit">The histogram clip limit. Histogram bins which exceed this limit, will be capped at this value.</param>
/// <param name="numberOfTiles">The number of tiles the image is split into (horizontal and vertically). Minimum value is 2. Maximum value is 100.</param>
public AdaptiveHistogramEqualizationSlidingWindowProcessor(
int luminanceLevels,
bool clipHistogram,
int clipLimit,
int numberOfTiles)
: base(luminanceLevels, clipHistogram, clipLimit)
{
this.NumberOfTiles = numberOfTiles;
}
/// <summary>
/// Gets the number of tiles the image is split into (horizontal and vertically) for the adaptive histogram equalization.
/// </summary>
public int NumberOfTiles { get; }
/// <inheritdoc />
public override IImageProcessor<TPixel> CreatePixelSpecificProcessor<TPixel>(Configuration configuration, Image<TPixel> source, Rectangle sourceRectangle)
=> new AdaptiveHistogramEqualizationSlidingWindowProcessor<TPixel>(
configuration,
this.LuminanceLevels,
this.ClipHistogram,
this.ClipLimit,
this.NumberOfTiles,
source,
sourceRectangle);
}
| AdaptiveHistogramEqualizationSlidingWindowProcessor |
csharp | dotnet__BenchmarkDotNet | tests/BenchmarkDotNet.Tests/Columns/MetricColumnTests.cs | {
"start": 2573,
"end": 3357
} | private sealed class ____ : IMetricDescriptor
{
public static readonly IMetricDescriptor TimeInstance = new LocalMetricDescriptor(UnitType.Time);
private LocalMetricDescriptor(UnitType unitType)
{
UnitType = unitType;
}
public string Id { get; } = nameof(LocalMetricDescriptor);
public string DisplayName => Id;
public string Legend { get; }
public string NumberFormat { get; }
public UnitType UnitType { get; }
public string Unit { get; }
public bool TheGreaterTheBetter { get; }
public int PriorityInCategory => 0;
public bool GetIsAvailable(Metric metric) => true;
}
}
} | LocalMetricDescriptor |
csharp | dotnetcore__CAP | src/DotNetCore.CAP.Kafka/IConnectionPool.cs | {
"start": 214,
"end": 386
} | public interface ____
{
string ServersAddress { get; }
IProducer<string, byte[]> RentProducer();
bool Return(IProducer<string, byte[]> producer);
} | IConnectionPool |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.ViewFeatures/src/IgnoreAntiforgeryTokenAttribute.cs | {
"start": 452,
"end": 1342
} | public class ____ : Attribute, IAntiforgeryPolicy, IOrderedFilter
{
/// <summary>
/// Gets the order value for determining the order of execution of filters. Filters execute in
/// ascending numeric value of the <see cref="Order"/> property.
/// </summary>
/// <remarks>
/// <para>
/// Filters are executed in an ordering determined by an ascending sort of the <see cref="Order"/> property.
/// </para>
/// <para>
/// The default Order for this attribute is 1000 because it must run after any filter which does authentication
/// or login in order to allow them to behave as expected (ie Unauthenticated or Redirect instead of 400).
/// </para>
/// <para>
/// Look at <see cref="IOrderedFilter.Order"/> for more detailed info.
/// </para>
/// </remarks>
public int Order { get; set; } = 1000;
}
| IgnoreAntiforgeryTokenAttribute |
csharp | nuke-build__nuke | source/Nuke.Common.Tests/CI/ITestConfigurationGenerator.cs | {
"start": 242,
"end": 350
} | public interface ____ : IConfigurationGenerator
{
StreamWriter Stream { set; }
}
| ITestConfigurationGenerator |
csharp | abpframework__abp | framework/test/Volo.Abp.Ddd.Tests/Volo/Abp/Domain/Entities/EntityHelper_Tests.cs | {
"start": 1860,
"end": 2017
} | public class ____ : Entity<Guid>
{
public new Guid Id {
get => base.Id;
set => base.Id = value;
}
}
}
| NewIdEntity |
csharp | AutoMapper__AutoMapper | src/UnitTests/Indexers.cs | {
"start": 334,
"end": 1027
} | public class ____
{
public string Value { get; set; }
public string this[string key] { get { return null; }}
}
protected override MapperConfiguration CreateConfiguration() => new(cfg =>
{
cfg.CreateMap<Source, Destination>();
});
protected override void Because_of()
{
_result = Mapper.Map<Source, Destination>(new Source {Value = "Bob"});
}
[Fact]
public void Should_ignore_indexers_and_map_successfully()
{
_result.Value.ShouldBe("Bob");
}
}
}
} | Destination |
csharp | abpframework__abp | modules/setting-management/src/Volo.Abp.SettingManagement.Domain/Volo/Abp/SettingManagement/SettingManagementProvider.cs | {
"start": 96,
"end": 1242
} | public abstract class ____ : ISettingManagementProvider
{
public abstract string Name { get; }
//TODO: Rename to Store
protected ISettingManagementStore SettingManagementStore { get; }
protected SettingManagementProvider(ISettingManagementStore settingManagementStore)
{
SettingManagementStore = settingManagementStore;
}
public virtual async Task<string> GetOrNullAsync(SettingDefinition setting, string providerKey)
{
return await SettingManagementStore.GetOrNullAsync(setting.Name, Name, NormalizeProviderKey(providerKey));
}
public virtual async Task SetAsync(SettingDefinition setting, string value, string providerKey)
{
await SettingManagementStore.SetAsync(setting.Name, value, Name, NormalizeProviderKey(providerKey));
}
public virtual async Task ClearAsync(SettingDefinition setting, string providerKey)
{
await SettingManagementStore.DeleteAsync(setting.Name, Name, NormalizeProviderKey(providerKey));
}
protected virtual string NormalizeProviderKey(string providerKey)
{
return providerKey;
}
}
| SettingManagementProvider |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/CheckWeb/Test.dtos.cs | {
"start": 6101,
"end": 6229
} | public partial class ____
: IReturn<NoRepeatResponse>
{
public virtual Guid Id { get; set; }
}
| NoRepeat |
csharp | dotnet__aspnetcore | src/SignalR/clients/csharp/Client/test/UnitTests/TestHttpMessageHandler.cs | {
"start": 546,
"end": 9985
} | public class ____ : HttpMessageHandler
{
private readonly List<HttpRequestMessage> _receivedRequests = new List<HttpRequestMessage>();
private RequestDelegate _app;
private readonly ILogger _logger;
private readonly List<Func<RequestDelegate, RequestDelegate>> _middleware = new List<Func<RequestDelegate, RequestDelegate>>();
public bool Disposed { get; private set; }
public IReadOnlyList<HttpRequestMessage> ReceivedRequests
{
get
{
lock (_receivedRequests)
{
return _receivedRequests.ToArray();
}
}
}
public TestHttpMessageHandler(ILoggerFactory loggerFactory, bool autoNegotiate = true, bool handleFirstPoll = true)
{
_logger = loggerFactory?.CreateLogger<TestHttpMessageHandler>() ?? NullLoggerFactory.Instance.CreateLogger<TestHttpMessageHandler>();
if (autoNegotiate)
{
OnNegotiate((_, cancellationToken) => ResponseUtils.CreateResponse(HttpStatusCode.OK, ResponseUtils.CreateNegotiationContent()));
}
if (handleFirstPoll)
{
var firstPoll = true;
OnRequest(async (request, next, cancellationToken) =>
{
cancellationToken.ThrowIfCancellationRequested();
if (ResponseUtils.IsLongPollRequest(request) && firstPoll)
{
firstPoll = false;
return ResponseUtils.CreateResponse(HttpStatusCode.OK);
}
else
{
return await next();
}
});
}
}
public TestHttpMessageHandler(bool autoNegotiate = true, bool handleFirstPoll = true)
: this(NullLoggerFactory.Instance, autoNegotiate, handleFirstPoll)
{
}
protected override void Dispose(bool disposing)
{
Disposed = true;
base.Dispose(disposing);
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
_logger.LogDebug("Calling handlers for a '{Method}' going to '{Url}'.", request.Method, request.RequestUri);
await Task.Yield();
lock (_receivedRequests)
{
_receivedRequests.Add(request);
if (_app == null)
{
_middleware.Reverse();
RequestDelegate handler = BaseHandler;
foreach (var middleware in _middleware)
{
handler = middleware(handler);
}
_app = handler;
}
}
return await _app(request, cancellationToken);
}
public static TestHttpMessageHandler CreateDefault()
{
var testHttpMessageHandler = new TestHttpMessageHandler();
var deleteCts = new CancellationTokenSource();
testHttpMessageHandler.OnSocketSend((_, __) => ResponseUtils.CreateResponse(HttpStatusCode.Accepted));
testHttpMessageHandler.OnLongPoll(async cancellationToken =>
{
var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, deleteCts.Token);
// Just block until canceled
var tcs = new TaskCompletionSource();
using (cts.Token.Register(() => tcs.TrySetResult()))
{
await tcs.Task;
}
return ResponseUtils.CreateResponse(HttpStatusCode.NoContent);
});
testHttpMessageHandler.OnRequest((request, next, cancellationToken) =>
{
if (request.Method.Equals(HttpMethod.Delete) && request.RequestUri.PathAndQuery.Contains("id="))
{
deleteCts.Cancel();
return Task.FromResult(ResponseUtils.CreateResponse(HttpStatusCode.Accepted));
}
return next();
});
return testHttpMessageHandler;
}
public void OnRequest(Func<HttpRequestMessage, Func<Task<HttpResponseMessage>>, CancellationToken, Task<HttpResponseMessage>> handler)
{
void OnRequestCore(Func<RequestDelegate, RequestDelegate> middleware)
{
_middleware.Add(middleware);
}
OnRequestCore(next =>
{
return (request, cancellationToken) =>
{
return handler(request, () => next(request, cancellationToken), cancellationToken);
};
});
}
public void OnGet(string pathAndQuery, Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handler) => OnRequest(HttpMethod.Get, pathAndQuery, handler);
public void OnPost(string pathAndQuery, Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handler) => OnRequest(HttpMethod.Post, pathAndQuery, handler);
public void OnPut(string pathAndQuery, Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handler) => OnRequest(HttpMethod.Put, pathAndQuery, handler);
public void OnDelete(string pathAndQuery, Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handler) => OnRequest(HttpMethod.Delete, pathAndQuery, handler);
public void OnHead(string pathAndQuery, Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handler) => OnRequest(HttpMethod.Head, pathAndQuery, handler);
public void OnOptions(string pathAndQuery, Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handler) => OnRequest(HttpMethod.Options, pathAndQuery, handler);
public void OnTrace(string pathAndQuery, Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handler) => OnRequest(HttpMethod.Trace, pathAndQuery, handler);
public void OnRequest(HttpMethod method, string pathAndQuery, Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handler)
{
OnRequest((request, next, cancellationToken) =>
{
cancellationToken.ThrowIfCancellationRequested();
if (request.Method.Equals(method) && string.Equals(request.RequestUri.PathAndQuery, pathAndQuery))
{
return handler(request, cancellationToken);
}
else
{
return next();
}
});
}
public void OnNegotiate(Func<HttpRequestMessage, CancellationToken, HttpResponseMessage> handler) => OnNegotiate((req, cancellationToken) => Task.FromResult(handler(req, cancellationToken)));
public void OnNegotiate(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handler)
{
OnRequest((request, next, cancellationToken) =>
{
if (ResponseUtils.IsNegotiateRequest(request))
{
return handler(request, cancellationToken);
}
else
{
return next();
}
});
}
public void OnLongPollDelete(Func<CancellationToken, HttpResponseMessage> handler) => OnLongPollDelete((cancellationToken) => Task.FromResult(handler(cancellationToken)));
public void OnLongPollDelete(Func<CancellationToken, Task<HttpResponseMessage>> handler)
{
OnRequest((request, next, cancellationToken) =>
{
if (ResponseUtils.IsLongPollDeleteRequest(request))
{
return handler(cancellationToken);
}
else
{
return next();
}
});
}
public void OnLongPoll(Func<CancellationToken, HttpResponseMessage> handler) => OnLongPoll(cancellationToken => Task.FromResult(handler(cancellationToken)));
public void OnLongPoll(Func<CancellationToken, Task<HttpResponseMessage>> handler)
{
OnLongPoll((request, token) => handler(token));
}
public void OnLongPoll(Func<HttpRequestMessage, CancellationToken, HttpResponseMessage> handler)
{
OnLongPoll((request, token) => Task.FromResult(handler(request, token)));
}
public void OnLongPoll(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handler)
{
OnRequest((request, next, cancellationToken) =>
{
if (ResponseUtils.IsLongPollRequest(request))
{
return handler(request, cancellationToken);
}
else
{
return next();
}
});
}
public void OnSocketSend(Func<byte[], CancellationToken, HttpResponseMessage> handler) => OnSocketSend((data, cancellationToken) => Task.FromResult(handler(data, cancellationToken)));
public void OnSocketSend(Func<byte[], CancellationToken, Task<HttpResponseMessage>> handler)
{
OnRequest(async (request, next, cancellationToken) =>
{
if (ResponseUtils.IsSocketSendRequest(request))
{
var data = await request.Content.ReadAsByteArrayAsync();
return await handler(data, cancellationToken);
}
else
{
return await next();
}
});
}
private Task<HttpResponseMessage> BaseHandler(HttpRequestMessage request, CancellationToken cancellationToken)
{
return Task.FromException<HttpResponseMessage>(new InvalidOperationException($"Http endpoint not implemented: {request.Method} {request.RequestUri}"));
}
}
| TestHttpMessageHandler |
csharp | unoplatform__uno | src/Uno.Foundation.Runtime.WebAssembly/Helpers/IndentedStringBuilder.cs | {
"start": 954,
"end": 3171
} | internal class ____
{
private readonly StringBuilder _stringBuilder;
public int CurrentLevel { get; private set; }
public IndentedStringBuilder()
: this(new StringBuilder())
{
}
public IndentedStringBuilder(StringBuilder stringBuilder)
{
_stringBuilder = stringBuilder;
}
public virtual IDisposable Indent(int count = 1)
{
CurrentLevel += count;
return new DisposableAction(() => CurrentLevel -= count);
}
public virtual IDisposable Block(int count = 1)
{
var current = CurrentLevel;
CurrentLevel += count;
Append("{".Indent(current));
AppendLine();
return new DisposableAction(() =>
{
CurrentLevel -= count;
Append("}".Indent(current));
AppendLine();
});
}
public virtual IDisposable Block(IFormatProvider formatProvider, string pattern, params object[] parameters)
{
AppendFormat(formatProvider, pattern, parameters);
AppendLine();
return Block();
}
public virtual void Append(string text)
{
_stringBuilder.Append(text);
}
public virtual void AppendFormat(IFormatProvider formatProvider, string pattern, params object[] replacements)
{
_stringBuilder.AppendFormat(formatProvider, pattern.Indent(CurrentLevel), replacements);
}
/// <summary>
/// Appends a newline.
/// </summary>
/// <remarks>
/// This method presents correct behavior, as opposed to its <see cref="AppendLine(String)"/>
/// overload. Therefore, this method should be used whenever a newline is desired.
/// </remarks>
public virtual void AppendLine()
{
_stringBuilder.AppendLine();
}
/// <summary>
/// Appends the given string, *without* appending a newline at the end.
/// </summary>
/// <param name="text">The string to append.</param>
/// <remarks>
/// Even though this method seems like it appends a newline, it doesn't. To append a
/// newline, call <see cref="AppendLine()"/> after this method, as the parameterless
/// overload has the correct behavior.
/// </remarks>
public virtual void AppendLine(string text)
{
_stringBuilder.Append(text.Indent(CurrentLevel));
}
public override string ToString()
{
return _stringBuilder.ToString();
}
}
}
| IndentedStringBuilder |
csharp | MassTransit__MassTransit | src/MassTransit/Middleware/PipeContextSourceBindFilter.cs | {
"start": 311,
"end": 1543
} | public class ____<TLeft, TRight> :
IFilter<TLeft>
where TLeft : class, PipeContext
where TRight : class, PipeContext
{
readonly IPipe<BindContext<TLeft, TRight>> _output;
readonly IPipeContextSource<TRight, TLeft> _source;
public PipeContextSourceBindFilter(IPipe<BindContext<TLeft, TRight>> output, IPipeContextSource<TRight, TLeft> source)
{
_output = output;
_source = source;
}
public Task Send(TLeft context, IPipe<TLeft> next)
{
var bindPipe = new BindPipe(context, _output);
var sourceTask = _source.Send(context, bindPipe);
if (sourceTask.Status == TaskStatus.RanToCompletion)
return next.Send(context);
async Task SendAsync()
{
await sourceTask.ConfigureAwait(false);
await next.Send(context).ConfigureAwait(false);
}
return SendAsync();
}
public void Probe(ProbeContext context)
{
var scope = context.CreateFilterScope("bind");
_output.Probe(scope);
_source.Probe(scope);
}
| PipeContextSourceBindFilter |
csharp | dotnet__aspire | tests/Aspire.Azure.Storage.Queues.Tests/StorageQueuesPublicApiTests.cs | {
"start": 234,
"end": 4630
} | public class ____
{
[Fact]
public void AddAzureQueueServiceClientShouldThrowWhenBuilderIsNull()
{
IHostApplicationBuilder builder = null!;
const string connectionName = "queue";
var action = () => builder.AddAzureQueueServiceClient(connectionName);
var exception = Assert.Throws<ArgumentNullException>(action);
Assert.Equal(nameof(builder), exception.ParamName);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void AddAzureQueueServiceClientShouldThrowWhenConnectionNameIsNullOrEmpty(bool isNull)
{
var builder = Host.CreateEmptyApplicationBuilder(null);
var connectionName = isNull ? null! : string.Empty;
var action = () => builder.AddAzureQueueServiceClient(connectionName);
var exception = isNull
? Assert.Throws<ArgumentNullException>(action)
: Assert.Throws<ArgumentException>(action);
Assert.Equal(nameof(connectionName), exception.ParamName);
}
[Fact]
public void AddKeyedAzureQueueServiceClientShouldThrowWhenBuilderIsNull()
{
IHostApplicationBuilder builder = null!;
const string name = "queue";
var action = () => builder.AddKeyedAzureQueueServiceClient(name);
var exception = Assert.Throws<ArgumentNullException>(action);
Assert.Equal(nameof(builder), exception.ParamName);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void AddKeyedAzureQueueServiceClientShouldThrowWhenNameIsNullOrEmpty(bool isNull)
{
var builder = Host.CreateEmptyApplicationBuilder(null);
var name = isNull ? null! : string.Empty;
var action = () => builder.AddKeyedAzureQueueServiceClient(name);
var exception = isNull
? Assert.Throws<ArgumentNullException>(action)
: Assert.Throws<ArgumentException>(action);
Assert.Equal(nameof(name), exception.ParamName);
}
[Fact]
public void AddAzureQueueClientShouldThrowWhenBuilderIsNull()
{
IHostApplicationBuilder builder = null!;
const string connectionName = "queue";
#pragma warning disable CS0618 // Type or member is obsolete
var action = () => builder.AddAzureQueueServiceClient(connectionName);
#pragma warning restore CS0618 // Type or member is obsolete
var exception = Assert.Throws<ArgumentNullException>(action);
Assert.Equal(nameof(builder), exception.ParamName);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void AddAzureQueueClientShouldThrowWhenConnectionNameIsNullOrEmpty(bool isNull)
{
var builder = Host.CreateEmptyApplicationBuilder(null);
var connectionName = isNull ? null! : string.Empty;
#pragma warning disable CS0618 // Type or member is obsolete
var action = () => builder.AddAzureQueueServiceClient(connectionName);
#pragma warning restore CS0618 // Type or member is obsolete
var exception = isNull
? Assert.Throws<ArgumentNullException>(action)
: Assert.Throws<ArgumentException>(action);
Assert.Equal(nameof(connectionName), exception.ParamName);
}
[Fact]
public void AddKeyedAzureQueueClientShouldThrowWhenBuilderIsNull()
{
IHostApplicationBuilder builder = null!;
const string name = "queue";
#pragma warning disable CS0618 // Type or member is obsolete
var action = () => builder.AddKeyedAzureQueueServiceClient(name);
#pragma warning restore CS0618 // Type or member is obsolete
var exception = Assert.Throws<ArgumentNullException>(action);
Assert.Equal(nameof(builder), exception.ParamName);
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void AddKeyedAzureQueueClientShouldThrowWhenNameIsNullOrEmpty(bool isNull)
{
var builder = Host.CreateEmptyApplicationBuilder(null);
var name = isNull ? null! : string.Empty;
#pragma warning disable CS0618 // Type or member is obsolete
var action = () => builder.AddKeyedAzureQueueServiceClient(name);
#pragma warning restore CS0618 // Type or member is obsolete
var exception = isNull
? Assert.Throws<ArgumentNullException>(action)
: Assert.Throws<ArgumentException>(action);
Assert.Equal(nameof(name), exception.ParamName);
}
}
| StorageQueuesPublicApiTests |
csharp | microsoft__semantic-kernel | dotnet/samples/Concepts/Functions/MethodFunctions.cs | {
"start": 119,
"end": 531
} | public class ____(ITestOutputHelper output) : BaseTest(output)
{
[Fact]
public Task RunAsync()
{
Console.WriteLine("======== Functions ========");
// Load native plugin
var text = new TextPlugin();
// Use function without kernel
var result = text.Uppercase("ciao!");
Console.WriteLine(result);
return Task.CompletedTask;
}
}
| MethodFunctions |
csharp | dotnet__tye | src/Microsoft.Tye.Core/ExternalServiceBuilder.cs | {
"start": 235,
"end": 435
} | public sealed class ____ : ServiceBuilder
{
public ExternalServiceBuilder(string name, ServiceSource source)
: base(name, source)
{
}
}
}
| ExternalServiceBuilder |
csharp | DuendeSoftware__IdentityServer | identity-server/test/IdentityServer.UnitTests/Licensing/v2/DiagnosticHostedServiceTests.cs | {
"start": 411,
"end": 1717
} | public class ____
{
[Fact]
public async Task ExecuteAsync_ShouldNotThrowOperationCancelledException()
{
var diagnosticSummaryLogger = new NullLogger<DiagnosticSummary>();
var firstDiagnosticEntry = new TestDiagnosticEntry();
var secondDiagnosticEntry = new TestDiagnosticEntry();
var thirdDiagnosticEntry = new TestDiagnosticEntry();
var entries = new List<IDiagnosticEntry>
{
firstDiagnosticEntry,
secondDiagnosticEntry,
thirdDiagnosticEntry
};
var diagnosticService = new DiagnosticDataService(DateTime.UtcNow, entries);
var diagnosticSummary = new DiagnosticSummary(diagnosticService, new IdentityServerOptions(), new StubLoggerFactory(diagnosticSummaryLogger));
var options = Options.Create(new IdentityServerOptions());
var logger = new NullLogger<DiagnosticHostedService>();
var service = new DiagnosticHostedService(diagnosticSummary, options, logger);
using var cts = new CancellationTokenSource();
cts.CancelAfter(100);
var exception = await Record.ExceptionAsync(async () =>
{
await service.ExecuteForTestOnly(cts.Token);
});
exception.ShouldBeNull();
}
| DiagnosticHostedServiceTests |
csharp | dotnet__maui | src/Controls/src/Core/Internals/PreserveAttribute.cs | {
"start": 260,
"end": 951
} | public sealed class ____ : Attribute
{
/// <summary>For internal use by platform renderers.</summary>
public bool AllMembers;
/// <summary>For internal use by platform renderers.</summary>
public bool Conditional;
/// <include file="../../../docs/Microsoft.Maui.Controls.Internals/PreserveAttribute.xml" path="//Member[@MemberName='.ctor'][2]/Docs/*" />
public PreserveAttribute(bool allMembers, bool conditional)
{
AllMembers = allMembers;
Conditional = conditional;
}
/// <include file="../../../docs/Microsoft.Maui.Controls.Internals/PreserveAttribute.xml" path="//Member[@MemberName='.ctor'][1]/Docs/*" />
public PreserveAttribute()
{
}
}
} | PreserveAttribute |
csharp | abpframework__abp | modules/cms-kit/src/Volo.CmsKit.Domain/Volo/CmsKit/Comments/Comment.cs | {
"start": 180,
"end": 2135
} | public class ____ : AggregateRoot<Guid>, IHasCreationTime, IMustHaveCreator, IMultiTenant
{
public virtual Guid? TenantId { get; protected set; }
public virtual string EntityType { get; protected set; }
public virtual string EntityId { get; protected set; }
public virtual string Text { get; protected set; }
public virtual Guid? RepliedCommentId { get; protected set; }
public virtual Guid CreatorId { get; set; }
public virtual DateTime CreationTime { get; set; }
public virtual string Url { get; set; }
public virtual string IdempotencyToken { get; set; }
public virtual bool? IsApproved { get; private set; }
protected Comment()
{
}
internal Comment(
Guid id,
[NotNull] string entityType,
[NotNull] string entityId,
[NotNull] string text,
Guid? repliedCommentId,
Guid creatorId,
[CanBeNull] string url = null,
Guid? tenantId = null)
: base(id)
{
EntityType = Check.NotNullOrWhiteSpace(entityType, nameof(entityType), CommentConsts.MaxEntityTypeLength);
EntityId = Check.NotNullOrWhiteSpace(entityId, nameof(entityId), CommentConsts.MaxEntityIdLength);
RepliedCommentId = repliedCommentId;
CreatorId = creatorId;
Url = url;
TenantId = tenantId;
SetTextInternal(text);
}
public virtual void SetText(string text)
{
SetTextInternal(text);
}
protected virtual void SetTextInternal(string text)
{
Text = Check.NotNullOrWhiteSpace(text, nameof(text), CommentConsts.MaxTextLength);
}
public virtual Comment Approve()
{
IsApproved = true;
return this;
}
public virtual Comment Reject()
{
IsApproved = false;
return this;
}
public virtual Comment WaitForApproval()
{
IsApproved = null;
return this;
}
}
| Comment |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Data/src/Data/Sorting/Context/ISortingInfo.cs | {
"start": 129,
"end": 299
} | public interface ____
{
/// <summary>
/// Returns all sorting fields of this value
/// </summary>
IReadOnlyList<ISortingFieldInfo> GetFields();
}
| ISortingInfo |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL/Validation/Errors/VariablesInAllowedPositionError.cs | {
"start": 179,
"end": 1434
} | public class ____ : ValidationError
{
internal const string NUMBER = "5.8.5";
/// <summary>
/// Initializes a new instance with the specified properties.
/// </summary>
public VariablesInAllowedPositionError(ValidationContext context, GraphQLVariableDefinition varDef, IGraphType varType, VariableUsage usage)
: base(context.Document.Source, NUMBER, BadVarPosMessage(usage, varType.ToString()!))
{
var varDefLoc = Location.FromLinearPosition(context.Document.Source, varDef.Location.Start);
var usageLoc = Location.FromLinearPosition(context.Document.Source, usage.Node.Location.Start);
AddLocation(varDefLoc);
AddLocation(usageLoc);
}
internal static string BadVarPosMessage(VariableUsage usage, string varType)
{
string usageType = usage.Type.ToString()!;
if (usage.IsRequired && !usageType.EndsWith("!"))
usageType += "!";
return BadVarPosMessage(usage.Node.Name.StringValue, varType, usageType);
}
internal static string BadVarPosMessage(string varName, string varType, string expectedType)
=> $"Variable '${varName}' of type '{varType}' used in position expecting type '{expectedType}'.";
}
| VariablesInAllowedPositionError |
csharp | dotnet__aspire | src/Aspire.Hosting/Dcp/Model/ContainerNetwork.cs | {
"start": 1903,
"end": 2575
} | internal static class ____
{
// The network is being created, this is the initial state
public const string ContainerNetworkStatePending = "Pending";
// The network was successfully created
public const string ContainerNetworkStateRunning = "Running";
// An attempt was made to create the network, but it failed
public const string ContainerNetworkStateFailedToStart = "FailedToStart";
// Network was running at some point, but has been removed
public const string ContainerNetworkStateRemoved = "Removed";
// An existing network was not found
public const string ContainerNetworkStateNotFound = "NotFound";
}
| ContainerNetworkState |
csharp | jellyfin__jellyfin | Jellyfin.Data/Queries/ActivityLogQuery.cs | {
"start": 76,
"end": 149
} | class ____ a query to the activity logs.
/// </summary>
| representing |
csharp | dotnet__aspnetcore | src/Components/Endpoints/src/Rendering/EndpointComponentState.cs | {
"start": 553,
"end": 2674
} | internal sealed class ____ : ComponentState
{
private static readonly ConcurrentDictionary<Type, StreamRenderingAttribute?> _streamRenderingAttributeByComponentType = new();
static EndpointComponentState()
{
if (HotReloadManager.Default.MetadataUpdateSupported)
{
HotReloadManager.Default.OnDeltaApplied += _streamRenderingAttributeByComponentType.Clear;
}
}
private readonly EndpointHtmlRenderer _renderer;
public EndpointComponentState(Renderer renderer, int componentId, IComponent component, ComponentState? parentComponentState)
: base(renderer, componentId, component, parentComponentState)
{
_renderer = (EndpointHtmlRenderer)renderer;
var streamRenderingAttribute = _streamRenderingAttributeByComponentType.GetOrAdd(component.GetType(),
type => type.GetCustomAttribute<StreamRenderingAttribute>());
if (streamRenderingAttribute is not null)
{
StreamRendering = streamRenderingAttribute.Enabled;
}
else
{
var parentEndpointComponentState = (EndpointComponentState?)LogicalParentComponentState;
StreamRendering = parentEndpointComponentState?.StreamRendering ?? false;
}
}
public bool StreamRendering { get; }
protected override object? GetComponentKey()
{
if (ParentComponentState != null && ParentComponentState.Component is SSRRenderModeBoundary boundary)
{
var (sequence, key) = _renderer.GetSequenceAndKey(ParentComponentState);
var marker = boundary.GetComponentMarkerKey(sequence, key);
if (!marker.Equals(default))
{
return marker.Serialized();
}
}
// Fall back to the default implementation
return base.GetComponentKey();
}
/// <summary>
/// MetadataUpdateHandler event. This is invoked by the hot reload host via reflection.
/// </summary>
public static void UpdateApplication(Type[]? _) => _streamRenderingAttributeByComponentType.Clear();
}
| EndpointComponentState |
csharp | unoplatform__uno | src/SourceGenerators/Uno.UI.SourceGenerators.Tests/XamlCodeGeneratorTests/Out/Given_Binding/TeTeInXLoEl/XamlCodeGenerator_MainPage_d6cd66944958ced0c513e0a04797b51d.cs | {
"start": 871,
"end": 12575
} | partial class ____ : global::Microsoft.UI.Xaml.Controls.Page
{
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
private const string __baseUri_prefix_MainPage_d6cd66944958ced0c513e0a04797b51d = "ms-appx:///TestProject/";
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
private const string __baseUri_MainPage_d6cd66944958ced0c513e0a04797b51d = "ms-appx:///TestProject/";
private global::Microsoft.UI.Xaml.NameScope __nameScope = new global::Microsoft.UI.Xaml.NameScope();
[global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Generated code")]
[global::System.Diagnostics.CodeAnalysis.UnconditionalSuppressMessage("Trimming", "IL2111", Justification = "Generated code")]
private void InitializeComponent()
{
NameScope.SetNameScope(this, __nameScope);
var __that = this;
base.IsParsing = true;
// Source 0\MainPage.xaml (Line 1:2)
base.Content =
new global::Microsoft.UI.Xaml.Controls.StackPanel
{
IsParsing = true,
// Source 0\MainPage.xaml (Line 10:3)
Children =
{
new Microsoft.UI.Xaml.ElementStub( () =>
new global::Microsoft.UI.Xaml.Controls.Grid
{
IsParsing = true,
Name = "outerGrid",
// Source 0\MainPage.xaml (Line 11:4)
Children =
{
new global::Microsoft.UI.Xaml.Controls.StackPanel
{
IsParsing = true,
Name = "inner1",
// Source 0\MainPage.xaml (Line 12:5)
Children =
{
new global::Microsoft.UI.Xaml.Controls.Button
{
IsParsing = true,
Name = "inner1Button",
// Source 0\MainPage.xaml (Line 13:6)
}
.MainPage_d6cd66944958ced0c513e0a04797b51d_XamlApply((MainPage_d6cd66944958ced0c513e0a04797b51dXamlApplyExtensions.XamlApplyHandler0)(__p1 =>
{
__nameScope.RegisterName("inner1Button", __p1);
__that.inner1Button = __p1;
global::Uno.UI.FrameworkElementHelper.SetBaseUri(__p1, __baseUri_MainPage_d6cd66944958ced0c513e0a04797b51d);
__p1.CreationComplete();
}
))
,
}
}
.MainPage_d6cd66944958ced0c513e0a04797b51d_XamlApply((MainPage_d6cd66944958ced0c513e0a04797b51dXamlApplyExtensions.XamlApplyHandler1)(__p1 =>
{
__nameScope.RegisterName("inner1", __p1);
__that.inner1 = __p1;
global::Uno.UI.FrameworkElementHelper.SetBaseUri(__p1, __baseUri_MainPage_d6cd66944958ced0c513e0a04797b51d);
__p1.CreationComplete();
}
))
,
new global::Microsoft.UI.Xaml.Controls.Button
{
IsParsing = true,
Name = "inner2",
Template = new global::Microsoft.UI.Xaml.Controls.ControlTemplate(this, Build_PagΞ0_StaPanΞ0_GriΞ1_But_TemΞ0_ConTem)
,
// Source 0\MainPage.xaml (Line 15:5)
}
.MainPage_d6cd66944958ced0c513e0a04797b51d_XamlApply((MainPage_d6cd66944958ced0c513e0a04797b51dXamlApplyExtensions.XamlApplyHandler0)(__p1 =>
{
__nameScope.RegisterName("inner2", __p1);
__that.inner2 = __p1;
global::Uno.UI.FrameworkElementHelper.SetBaseUri(__p1, __baseUri_MainPage_d6cd66944958ced0c513e0a04797b51d);
__p1.CreationComplete();
}
))
,
new global::Microsoft.UI.Xaml.Controls.StackPanel
{
IsParsing = true,
Name = "inner3",
// Source 0\MainPage.xaml (Line 24:5)
Children =
{
new global::Microsoft.UI.Xaml.Controls.Button
{
IsParsing = true,
Name = "inner3Button",
// Source 0\MainPage.xaml (Line 25:6)
}
.MainPage_d6cd66944958ced0c513e0a04797b51d_XamlApply((MainPage_d6cd66944958ced0c513e0a04797b51dXamlApplyExtensions.XamlApplyHandler0)(__p1 =>
{
__nameScope.RegisterName("inner3Button", __p1);
__that.inner3Button = __p1;
global::Uno.UI.FrameworkElementHelper.SetBaseUri(__p1, __baseUri_MainPage_d6cd66944958ced0c513e0a04797b51d);
__p1.CreationComplete();
}
))
,
}
}
.MainPage_d6cd66944958ced0c513e0a04797b51d_XamlApply((MainPage_d6cd66944958ced0c513e0a04797b51dXamlApplyExtensions.XamlApplyHandler1)(__p1 =>
{
__nameScope.RegisterName("inner3", __p1);
__that.inner3 = __p1;
global::Uno.UI.FrameworkElementHelper.SetBaseUri(__p1, __baseUri_MainPage_d6cd66944958ced0c513e0a04797b51d);
__p1.CreationComplete();
}
))
,
}
}
.MainPage_d6cd66944958ced0c513e0a04797b51d_XamlApply((MainPage_d6cd66944958ced0c513e0a04797b51dXamlApplyExtensions.XamlApplyHandler2)(__p1 =>
{
/* _isTopLevelDictionary:False */
__that._component_0 = __p1;
__nameScope.RegisterName("outerGrid", __p1);
__that.outerGrid = __p1;
/* Skipping x:Load attribute already applied to ElementStub */
global::Uno.UI.FrameworkElementHelper.SetBaseUri(__p1, __baseUri_MainPage_d6cd66944958ced0c513e0a04797b51d);
__p1.CreationComplete();
}
))
) .MainPage_d6cd66944958ced0c513e0a04797b51d_XamlApply((MainPage_d6cd66944958ced0c513e0a04797b51dXamlApplyExtensions.XamlApplyHandler3)(__p1 =>
{
__p1.Name = "outerGrid";
_outerGridSubject.ElementInstance = __p1;
__p1.SetBinding(
global::Microsoft.UI.Xaml.ElementStub.LoadProperty,
new Microsoft.UI.Xaml.Data.Binding()
{
Mode = BindingMode.OneTime,
}
.BindingApply(__that, (___b, ___t) => /*defaultBindModeOneTime IsLoaded*/ global::Uno.UI.Xaml.BindingHelper.SetBindingXBindProvider(___b, ___t, ___ctx => ___ctx is global::TestRepro.MainPage ___tctx ? (TryGetInstance_xBind_1(___tctx, out var bindResult1) ? (true, bindResult1) : (false, default)) : (false, default), null ))
);
__that._component_1 = __p1;
var _component_1_update_That = (this as global::Uno.UI.DataBinding.IWeakReferenceProvider).WeakReference;
void _component_1_update(global::Microsoft.UI.Xaml.ElementStub sender)
{
if (_component_1_update_That.Target is global::TestRepro.MainPage that)
{
if (sender.IsMaterialized)
{
that.Bindings.UpdateResources();
that.Bindings.NotifyXLoad("outerGrid");
}
else
{
that._outerGridSubject.ElementInstance = null;
that._inner1Subject.ElementInstance = null;
that._inner1Subject.ElementInstance = null;
that._inner1ButtonSubject.ElementInstance = null;
that._inner1ButtonSubject.ElementInstance = null;
that._inner2Subject.ElementInstance = null;
that._inner2Subject.ElementInstance = null;
that._inner3Subject.ElementInstance = null;
that._inner3Subject.ElementInstance = null;
that._inner3ButtonSubject.ElementInstance = null;
that._inner3ButtonSubject.ElementInstance = null;
}
}
}
__p1.MaterializationChanged += _component_1_update;
var owner = this;
void _component_1_materializing(object sender)
{
if (_component_1_update_That.Target is global::TestRepro.MainPage that)
{
that._component_0.ApplyXBind();
that._component_0.UpdateResourceBindings();
}
}
__p1.Materializing += _component_1_materializing;
}
))
,
}
}
.MainPage_d6cd66944958ced0c513e0a04797b51d_XamlApply((MainPage_d6cd66944958ced0c513e0a04797b51dXamlApplyExtensions.XamlApplyHandler1)(__p1 =>
{
global::Uno.UI.FrameworkElementHelper.SetBaseUri(__p1, __baseUri_MainPage_d6cd66944958ced0c513e0a04797b51d);
__p1.CreationComplete();
}
))
;
this
.MainPage_d6cd66944958ced0c513e0a04797b51d_XamlApply((MainPage_d6cd66944958ced0c513e0a04797b51dXamlApplyExtensions.XamlApplyHandler4)(__p1 =>
{
// Source 0\MainPage.xaml (Line 1:2)
// [WARNING] C:/Project/0/MainPage.xaml(1,2): Property 'base' does not exist on 'Page', this error was however considered irrelevant by the XamlFileGenerator.
}
))
.MainPage_d6cd66944958ced0c513e0a04797b51d_XamlApply((MainPage_d6cd66944958ced0c513e0a04797b51dXamlApplyExtensions.XamlApplyHandler4)(__p1 =>
{
// Class TestRepro.MainPage
global::Uno.UI.FrameworkElementHelper.SetBaseUri(__p1, __baseUri_MainPage_d6cd66944958ced0c513e0a04797b51d);
__p1.CreationComplete();
}
))
;
OnInitializeCompleted();
Bindings = new MainPage_Bindings(this);
((global::Microsoft.UI.Xaml.FrameworkElement)this).Loading += __UpdateBindingsAndResources;
((global::Microsoft.UI.Xaml.FrameworkElement)this).Unloaded += __StopTracking;
}
partial void OnInitializeCompleted();
private static _View Build_PagΞ0_StaPanΞ0_GriΞ1_But_TemΞ0_ConTem(object __owner, global::Microsoft.UI.Xaml.TemplateMaterializationSettings __settings)
{
return new __MainPage_d6cd66944958ced0c513e0a04797b51d.__PagΞ0_StaPanΞ0_GriΞ1_But_TemΞ0_ConTem().Build(__owner, __settings);
}
private void __UpdateBindingsAndResources(global::Microsoft.UI.Xaml.FrameworkElement s, object e)
{
this.Bindings.Update();
this.Bindings.UpdateResources();
}
private void __StopTracking(object s, global::Microsoft.UI.Xaml.RoutedEventArgs e)
{
this.Bindings.StopTracking();
}
private readonly global::Microsoft.UI.Xaml.Data.ElementNameSubject _inner1Subject = new global::Microsoft.UI.Xaml.Data.ElementNameSubject();
private global::Microsoft.UI.Xaml.Controls.StackPanel inner1
{
get => (global::Microsoft.UI.Xaml.Controls.StackPanel)_inner1Subject.ElementInstance;
set => _inner1Subject.ElementInstance = value;
}
private readonly global::Microsoft.UI.Xaml.Data.ElementNameSubject _inner1ButtonSubject = new global::Microsoft.UI.Xaml.Data.ElementNameSubject();
private global::Microsoft.UI.Xaml.Controls.Button inner1Button
{
get => (global::Microsoft.UI.Xaml.Controls.Button)_inner1ButtonSubject.ElementInstance;
set => _inner1ButtonSubject.ElementInstance = value;
}
private readonly global::Microsoft.UI.Xaml.Data.ElementNameSubject _inner2Subject = new global::Microsoft.UI.Xaml.Data.ElementNameSubject();
private global::Microsoft.UI.Xaml.Controls.Button inner2
{
get => (global::Microsoft.UI.Xaml.Controls.Button)_inner2Subject.ElementInstance;
set => _inner2Subject.ElementInstance = value;
}
private readonly global::Microsoft.UI.Xaml.Data.ElementNameSubject _inner3Subject = new global::Microsoft.UI.Xaml.Data.ElementNameSubject();
private global::Microsoft.UI.Xaml.Controls.StackPanel inner3
{
get => (global::Microsoft.UI.Xaml.Controls.StackPanel)_inner3Subject.ElementInstance;
set => _inner3Subject.ElementInstance = value;
}
private readonly global::Microsoft.UI.Xaml.Data.ElementNameSubject _inner3ButtonSubject = new global::Microsoft.UI.Xaml.Data.ElementNameSubject();
private global::Microsoft.UI.Xaml.Controls.Button inner3Button
{
get => (global::Microsoft.UI.Xaml.Controls.Button)_inner3ButtonSubject.ElementInstance;
set => _inner3ButtonSubject.ElementInstance = value;
}
private readonly global::Microsoft.UI.Xaml.Data.ElementNameSubject _outerGridSubject = new global::Microsoft.UI.Xaml.Data.ElementNameSubject();
private global::Microsoft.UI.Xaml.Controls.Grid outerGrid
{
get => (global::Microsoft.UI.Xaml.Controls.Grid)_outerGridSubject.ElementInstance;
set => _outerGridSubject.ElementInstance = value;
}
[global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)]
[global::System.Runtime.CompilerServices.CreateNewOnMetadataUpdate]
| MainPage |
csharp | ServiceStack__ServiceStack.OrmLite | src/ServiceStack.OrmLite/Expressions/IUntypedSqlExpression.cs | {
"start": 20996,
"end": 23764
} | public static class ____
{
public static IUntypedSqlExpression GetUntypedSqlExpression(this ISqlExpression sqlExpression)
{
var hasUntyped = sqlExpression as IHasUntypedSqlExpression;
return hasUntyped?.GetUntyped();
}
public static IOrmLiteDialectProvider ToDialectProvider(this ISqlExpression sqlExpression) =>
(sqlExpression as IHasDialectProvider)?.DialectProvider ?? OrmLiteConfig.DialectProvider;
public static string Table<T>(this ISqlExpression sqlExpression) => sqlExpression.ToDialectProvider().GetQuotedTableName(typeof(T).GetModelDefinition());
public static string Table<T>(this IOrmLiteDialectProvider dialect) => dialect.GetQuotedTableName(typeof(T).GetModelDefinition());
public static string Column<Table>(this ISqlExpression sqlExpression, Expression<Func<Table, object>> propertyExpression, bool prefixTable = false) =>
sqlExpression.ToDialectProvider().Column(propertyExpression, prefixTable);
public static string Column<Table>(this IOrmLiteDialectProvider dialect, Expression<Func<Table, object>> propertyExpression, bool prefixTable = false)
{
string propertyName = null;
Expression expr = propertyExpression;
if (expr is LambdaExpression lambda)
expr = lambda.Body;
if (expr.NodeType == ExpressionType.Convert && expr is UnaryExpression unary)
expr = unary.Operand;
if (expr is MemberExpression member)
propertyName = member.Member.Name;
if (propertyName == null)
propertyName = expr.ToPropertyInfo()?.Name;
if (propertyName != null)
return dialect.Column<Table>(propertyName, prefixTable);
throw new ArgumentException("Expected Lambda MemberExpression but received: " + propertyExpression.Name);
}
public static string Column<Table>(this ISqlExpression sqlExpression, string propertyName, bool prefixTable = false) =>
sqlExpression.ToDialectProvider().Column<Table>(propertyName, prefixTable);
public static string Column<Table>(this IOrmLiteDialectProvider dialect, string propertyName, bool prefixTable = false)
{
var tableDef = typeof(Table).GetModelDefinition();
var fieldDef = tableDef.FieldDefinitions.FirstOrDefault(x => x.Name == propertyName);
var fieldName = fieldDef != null
? fieldDef.FieldName
: propertyName;
return prefixTable
? dialect.GetQuotedColumnName(tableDef, fieldName)
: dialect.GetQuotedColumnName(fieldName);
}
}
} | SqlExpressionExtensions |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/src/Execution/Processing/OperationContext.Operation.cs | {
"start": 129,
"end": 2722
} | partial class ____
{
/// <summary>
/// Gets the schema on which the query is being executed.
/// </summary>
public Schema Schema
{
get
{
AssertInitialized();
return _schema;
}
}
/// <summary>
/// Gets the operation that is being executed.
/// </summary>
public IOperation Operation
{
get
{
AssertInitialized();
return _operation;
}
}
/// <summary>
/// Gets the coerced variable values for the current operation.
/// </summary>
public IVariableValueCollection Variables
{
get
{
AssertInitialized();
return _variables;
}
}
/// <summary>
/// Gets the include flags for the current request.
/// </summary>
public long IncludeFlags { get; private set; }
/// <summary>
/// Gets the value representing the instance of the
/// <see cref="IOperation.RootType" />
/// </summary>
public object? RootValue
{
get
{
AssertInitialized();
return _rootValue;
}
}
/// <summary>
/// Get the fields for the specified selection set according to the execution plan.
/// The selection set will show all possibilities and needs to be pre-processed.
/// </summary>
/// <param name="selection">
/// The selection for which we want to get the compiled selection set.
/// </param>
/// <param name="typeContext">
/// The type context.
/// </param>
/// <returns></returns>
public ISelectionSet CollectFields(ISelection selection, ObjectType typeContext)
{
AssertInitialized();
return Operation.GetSelectionSet(selection, typeContext);
}
/// <summary>
/// Get the query root instance.
/// </summary>
/// <typeparam name="T">
/// The type of the query root.
/// </typeparam>
/// <returns>
/// Returns the query root instance.
/// </returns>
public T GetQueryRoot<T>()
{
AssertInitialized();
var query = _resolveQueryRootValue();
if (query is null
&& typeof(T) == typeof(object)
&& new object() is T dummy)
{
return dummy;
}
if (query is T casted)
{
return casted;
}
throw new InvalidCastException(
string.Format(
Resources.OperationContext_GetQueryRoot_InvalidCast,
typeof(T).FullName ?? typeof(T).Name));
}
}
| OperationContext |
csharp | Cysharp__UniTask | src/UniTask/Assets/Plugins/UniTask/Runtime/UnityAsyncExtensions.uGUI.cs | {
"start": 14421,
"end": 14545
} | public interface ____<T> : IDisposable
{
UniTask<T> OnValueChangedAsync();
}
| IAsyncValueChangedEventHandler |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Controls/ProgressRing/Legacy/ProgressRing.UIKit.cs | {
"start": 595,
"end": 1191
} | public partial class ____
{
private void ApplyForeground()
{
if (_native != null && Foreground is { } foreground)
{
_native.Color = Brush.GetColorWithOpacity(foreground);
}
}
partial void OnLoadedPartial() => TrySetNativeAnimating();
partial void OnUnloadedPartial() => TrySetNativeAnimating();
partial void OnIsActiveChangedPartial(bool isActive) => TrySetNativeAnimating();
partial void TrySetNativeAnimating()
{
if (_native != null)
{
if (IsActive && IsLoaded)
{
_native.StartAnimating();
}
else
{
_native.StopAnimating();
}
}
}
}
| ProgressRing |
csharp | jellyfin__jellyfin | MediaBrowser.Model/Entities/ExtraType.cs | {
"start": 76,
"end": 380
} | public enum ____
{
Unknown = 0,
Clip = 1,
Trailer = 2,
BehindTheScenes = 3,
DeletedScene = 4,
Interview = 5,
Scene = 6,
Sample = 7,
ThemeSong = 8,
ThemeVideo = 9,
Featurette = 10,
Short = 11
}
}
| ExtraType |
csharp | AutoMapper__AutoMapper | src/IntegrationTests/Inheritance/ProxyTests.cs | {
"start": 2334,
"end": 2550
} | public class ____
{
public int CourseId { get; set; }
public string CourseName { get; set; }
public virtual ICollection<TrainingContentDto> Content { get; set; }
}
| TrainingCourseDto |
csharp | OrchardCMS__OrchardCore | src/OrchardCore/OrchardCore.Abstractions/Extensions/Features/IFeatureHash.cs | {
"start": 99,
"end": 349
} | interface ____ efficient access to the state
/// of the enabled feature in order to provide hashes used for caching.
/// Because its state should be cached, the instance should not have any state
/// thus is declared as transient.
/// </summary>
| provide |
csharp | OrchardCMS__OrchardCore | src/OrchardCore.Modules/OrchardCore.Indexing/Drivers/IndexProfileDisplayDriver.cs | {
"start": 375,
"end": 4742
} | internal sealed class ____ : DisplayDriver<IndexProfile>
{
private readonly IIndexProfileStore _indexProfileStore;
private readonly IServiceProvider _serviceProvider;
internal readonly IStringLocalizer S;
public IndexProfileDisplayDriver(
IIndexProfileStore indexProfileStore,
IServiceProvider serviceProvider,
IStringLocalizer<IndexProfileDisplayDriver> stringLocalizer)
{
_indexProfileStore = indexProfileStore;
_serviceProvider = serviceProvider;
S = stringLocalizer;
}
public override Task<IDisplayResult> DisplayAsync(IndexProfile indexProfile, BuildDisplayContext context)
{
return CombineAsync(
View("IndexProfile_Fields_SummaryAdmin", indexProfile)
.Location(OrchardCoreConstants.DisplayType.SummaryAdmin, "Content:1"),
View("IndexProfile_Buttons_SummaryAdmin", indexProfile)
.Location(OrchardCoreConstants.DisplayType.SummaryAdmin, "Actions:5"),
View("IndexProfile_DefaultTags_SummaryAdmin", indexProfile)
.Location(OrchardCoreConstants.DisplayType.SummaryAdmin, "Tags:5"),
View("IndexProfile_DefaultMeta_SummaryAdmin", indexProfile)
.Location(OrchardCoreConstants.DisplayType.SummaryAdmin, "Meta:5"),
View("IndexProfile_ActionsMenuItems_SummaryAdmin", indexProfile)
.Location(OrchardCoreConstants.DisplayType.SummaryAdmin, "ActionsMenu:5")
);
}
public override IDisplayResult Edit(IndexProfile indexProfile, BuildEditorContext context)
{
return Initialize<EditIndexProfileViewModel>("IndexProfileFields_Edit", model =>
{
model.Name = indexProfile.Name;
model.IndexName = indexProfile.IndexName;
model.IsNew = context.IsNew;
}).Location("Content:1");
}
public override async Task<IDisplayResult> UpdateAsync(IndexProfile indexProfile, UpdateEditorContext context)
{
var model = new EditIndexProfileViewModel();
await context.Updater.TryUpdateModelAsync(model, Prefix);
if (context.IsNew)
{
var hasIndexName = !string.IsNullOrEmpty(model.IndexName);
if (!hasIndexName)
{
context.Updater.ModelState.AddModelError(Prefix, nameof(model.IndexName), S["The index name is a required field."]);
}
else if (await _indexProfileStore.FindByIndexNameAndProviderAsync(model.IndexName, indexProfile.ProviderName) is not null)
{
context.Updater.ModelState.AddModelError(Prefix, nameof(model.IndexName), S["There is already another index with the same name."]);
}
if (hasIndexName && model.IndexName.Length > 255)
{
context.Updater.ModelState.AddModelError(Prefix, nameof(model.IndexName), S["The index name must be less than 255 characters."]);
}
if (hasIndexName && !string.IsNullOrEmpty(indexProfile.ProviderName))
{
var nameProvider = _serviceProvider.GetKeyedService<IIndexNameProvider>(indexProfile.ProviderName);
if (nameProvider is not null)
{
indexProfile.IndexFullName = nameProvider.GetFullIndexName(model.IndexName);
}
}
indexProfile.IndexName = model.IndexName;
}
if (string.IsNullOrEmpty(model.Name))
{
context.Updater.ModelState.AddModelError(Prefix, nameof(model.Name), S["The name is required field."]);
}
else
{
if (model.Name.Length > 255)
{
context.Updater.ModelState.AddModelError(Prefix, nameof(model.Name), S["The name must be less than 255 characters."]);
}
else
{
var existing = await _indexProfileStore.FindByNameAsync(model.Name);
if (existing is not null && existing.Id != indexProfile.Id)
{
context.Updater.ModelState.AddModelError(Prefix, nameof(model.Name), S["There is already another index with the same name."]);
}
}
}
indexProfile.Name = model.Name;
return Edit(indexProfile, context);
}
}
| IndexProfileDisplayDriver |
csharp | microsoft__garnet | libs/storage/Tsavorite/cs/src/core/Index/Tsavorite/Implementation/ReadCache.cs | {
"start": 10274,
"end": 10951
} | record ____ the same time.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool EnsureNoNewMainLogRecordWasSpliced(ref TKey key, RecordSource<TKey, TValue, TStoreFunctions, TAllocator> recSrc, long highestSearchedAddress, ref OperationStatus failStatus)
{
bool success = true;
ref RecordInfo lowest_rcri = ref readcache.GetInfo(recSrc.LowestReadCachePhysicalAddress);
Debug.Assert(!IsReadCache(lowest_rcri.PreviousAddress), "lowest-rcri.PreviousAddress should be a main-log address");
if (lowest_rcri.PreviousAddress > highestSearchedAddress)
{
// Someone added a new | at |
csharp | unoplatform__uno | src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/ListView/ListViewResizableText.xaml.cs | {
"start": 897,
"end": 1028
} | partial class ____ : UserControl
{
public ListViewResizableText()
{
this.InitializeComponent();
}
}
}
| ListViewResizableText |
csharp | open-telemetry__opentelemetry-dotnet | test/OpenTelemetry.Exporter.OpenTelemetryProtocol.Tests/UseOtlpExporterExtensionTests.cs | {
"start": 15330,
"end": 15415
} | private sealed class ____ : BaseProcessor<LogRecord>
{
}
}
| TestLogRecordProcessor |
csharp | CommunityToolkit__WindowsCommunityToolkit | Microsoft.Toolkit.Uwp.UI.Controls.DataGrid/CollectionViews/ListCollectionView.cs | {
"start": 57075,
"end": 87317
} | class ____ raise an event to our listeners
if (!IsGrouping)
{
// we've already returned if (action == NotifyCollectionChangedAction.Reset) above
// To avoid notification reentrancy we need to mark this collection view as processing a change
// so any changes to the current item will only be raised once, and from this method
// _currentChangedMonitor is used to guard whether the CurrentChanged and CurrentChanging event can be fired
// so by entering it we're preventing the base calls from firing those events.
DiagnosticsDebug.Assert(!CurrentChangedMonitor.Busy, "Expected _currentChangedMonitor.Busy is false.");
CurrentChangedMonitor.Enter();
using (CurrentChangedMonitor)
{
OnCollectionChanged(args);
if (args2 != null)
{
OnCollectionChanged(args2);
}
}
// Any scalar properties that changed don't need a further notification,
// but do need a new snapshot
if (IsCurrentAfterLast != oldIsCurrentAfterLast)
{
afterLastHasChanged = false;
oldIsCurrentAfterLast = IsCurrentAfterLast;
}
if (IsCurrentBeforeFirst != oldIsCurrentBeforeFirst)
{
beforeFirstHasChanged = false;
oldIsCurrentBeforeFirst = IsCurrentBeforeFirst;
}
if (CurrentPosition != oldCurrentPosition)
{
currentPositionHasChanged = false;
oldCurrentPosition = CurrentPosition;
}
if (CurrentItem != oldCurrentItem)
{
currentItemHasChanged = false;
oldCurrentItem = CurrentItem;
}
}
// currency has to change after firing the deletion event,
// so event handlers have the right picture
if (_currentElementWasRemoved)
{
int oldCurPos = originalCurrentPosition;
#if FEATURE_ICOLLECTIONVIEW_GROUP
if (_newGroupedItem != null)
{
oldCurPos = IndexOf(_newGroupedItem);
}
#endif
MoveCurrencyOffDeletedElement(oldCurPos);
// changes to the scalar properties need notification
afterLastHasChanged = afterLastHasChanged || (IsCurrentAfterLast != oldIsCurrentAfterLast);
beforeFirstHasChanged = beforeFirstHasChanged || (IsCurrentBeforeFirst != oldIsCurrentBeforeFirst);
currentPositionHasChanged = currentPositionHasChanged || (CurrentPosition != oldCurrentPosition);
currentItemHasChanged = currentItemHasChanged || (CurrentItem != oldCurrentItem);
}
// notify that the properties have changed. We may end up doing
// double notification for properties that change during the collection
// change event, but that's not harmful. Detecting the double change
// is more trouble than it's worth.
RaiseCurrencyChanges(
false /*raiseCurrentChanged*/,
currentItemHasChanged,
currentPositionHasChanged,
beforeFirstHasChanged,
afterLastHasChanged);
}
/// <summary>
/// Return index of item in the internal list.
/// </summary>
/// <returns>Index of item in the internal list.</returns>
protected int InternalIndexOf(object item)
{
#if FEATURE_ICOLLECTIONVIEW_GROUP
if (IsGrouping)
{
return _group.LeafIndexOf(item);
}
#endif
#if FEATURE_ICOLLECTIONVIEW_SORT_OR_FILTER
#if FEATURE_IEDITABLECOLLECTIONVIEW
if (IsAddingNew && object.Equals(item, _newItem) && UsesLocalArray)
{
return InternalCount - 1;
}
#endif
#endif
return InternalList.IndexOf(item);
}
/// <summary>
/// Return item at the given index in the internal list.
/// </summary>
/// <returns>Item at the given index in the internal list.</returns>
protected object InternalItemAt(int index)
{
#if FEATURE_ICOLLECTIONVIEW_GROUP
if (IsGrouping)
{
return _group.LeafAt(index);
}
#endif
#if FEATURE_IEDITABLECOLLECTIONVIEW
#if FEATURE_ICOLLECTIONVIEW_SORT_OR_FILTER
if (IsAddingNew && UsesLocalArray && index == InternalCount - 1)
{
return _newItem;
}
#endif
#endif
return InternalList[index];
}
/// <summary>
/// Return true if internal list contains the item.
/// </summary>
/// <returns>True if internal list contains the item.</returns>
protected bool InternalContains(object item)
{
#if FEATURE_ICOLLECTIONVIEW_GROUP
if (!IsGrouping)
{
#endif
return InternalList.Contains(item);
#if FEATURE_ICOLLECTIONVIEW_GROUP
}
else
{
return _group.LeafIndexOf(item) >= 0;
}
#endif
}
/// <summary>
/// Return an enumerator for the internal list.
/// </summary>
/// <returns>An enumerator for the internal list.</returns>
protected IEnumerator InternalGetEnumerator()
{
#if FEATURE_ICOLLECTIONVIEW_GROUP
if (!IsGrouping)
{
#endif
#if FEATURE_IEDITABLECOLLECTIONVIEW
return new PlaceholderAwareEnumerator(this, InternalList.GetEnumerator(), _newItem);
#else
return new PlaceholderAwareEnumerator(this, InternalList.GetEnumerator(), NoNewItem);
#endif
#if FEATURE_ICOLLECTIONVIEW_GROUP
}
else
{
return _group.GetLeafEnumerator();
}
#endif
}
#if FEATURE_ICOLLECTIONVIEW_SORT_OR_FILTER
/// <summary>
/// Gets a value indicating whether a private copy of the data is needed for sorting and filtering
/// </summary>
protected bool UsesLocalArray
{
get
{
return ActiveComparer != null || ActiveFilter != null;
}
}
#endif
/// <summary>
/// Gets a protected accessor to private _internalList field.
/// </summary>
protected IList InternalList
{
get
{
return _internalList;
}
}
#if FEATURE_ICOLLECTIONVIEW_SORT
/// <summary>
/// Gets or sets a protected accessor to private _activeComparer field.
/// </summary>
protected IComparer<object> ActiveComparer
{
get
{
return _activeComparer;
}
set
{
_activeComparer = value;
}
}
#endif
#if FEATURE_ICOLLECTIONVIEW_FILTER
/// <summary>
/// Gets or sets a protected accessor to private _activeFilter field.
/// </summary>
protected Predicate<object> ActiveFilter
{
get
{
return _activeFilter;
}
set
{
_activeFilter = value;
}
}
#endif
/// <summary>
/// Gets a value indicating whether grouping is supported.
/// </summary>
protected bool IsGrouping
{
get
{
#if FEATURE_ICOLLECTIONVIEW_GROUP
return _isGrouping;
#else
return false;
#endif
}
}
/// <summary>
/// Gets a protected accessor to private count.
/// </summary>
protected int InternalCount
{
get
{
#if FEATURE_ICOLLECTIONVIEW_GROUP
if (IsGrouping)
{
return _group.ItemCount;
}
#endif
#if FEATURE_ICOLLECTIONVIEW_SORT_OR_FILTER
bool usesLocalArray = UsesLocalArray;
#else
bool usesLocalArray = false;
#endif
#if FEATURE_IEDITABLECOLLECTIONVIEW
bool isAddingNew = IsAddingNew;
#else
bool isAddingNew = false;
#endif
int delta = (usesLocalArray && isAddingNew) ? 1 : 0;
return delta + InternalList.Count;
}
}
#if FEATURE_ICOLLECTIONVIEW_SORT
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
// returns true if this ListCollectionView has sort descriptions,
// without tripping off lazy creation of SortDescriptions collection.
internal bool HasSortDescriptions
{
get
{
return _sort != null && _sort.Count > 0;
}
}
#endif
//------------------------------------------------------
//
// Private Properties
//
//------------------------------------------------------
// true if CurrentPosition points to item within view
private bool IsCurrentInView
{
get
{
return CurrentPosition >= 0 && CurrentPosition < InternalCount;
}
}
#if FEATURE_ICOLLECTIONVIEW_GROUP
// can the group name(s) for an item change after we've grouped the item?
private bool CanGroupNamesChange
{
// There's no way we can deduce this - the app has to tell us.
// If this is true, removing a grouped item is quite difficult.
// We cannot rely on its group names to tell us which group we inserted
// it into (they may have been different at insertion time), so we
// have to do a linear search.
get
{
return true;
}
}
#endif
private IList SourceList
{
get
{
return SourceCollection as IList;
}
}
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
/// <summary>
/// Validates provided NotifyCollectionChangedEventArgs
/// </summary>
/// <param name="e">NotifyCollectionChangedEventArgs to validate.</param>
[Conditional("DEBUG")]
private void Debug_ValidateCollectionChangedEventArgs(NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
DiagnosticsDebug.Assert(e.NewItems.Count == 1, "Unexpected NotifyCollectionChangedEventArgs.NewItems.Count for Add action");
break;
case NotifyCollectionChangedAction.Remove:
DiagnosticsDebug.Assert(e.OldItems.Count == 1, "Unexpected NotifyCollectionChangedEventArgs.OldItems.Count for Remove action");
break;
case NotifyCollectionChangedAction.Replace:
DiagnosticsDebug.Assert(e.OldItems.Count == 1, "Unexpected NotifyCollectionChangedEventArgs.OldItems.Count for Replace action");
DiagnosticsDebug.Assert(e.NewItems.Count == 1, "Unexpected NotifyCollectionChangedEventArgs.NewItems.Count for Replace action");
break;
case NotifyCollectionChangedAction.Reset:
break;
default:
DiagnosticsDebug.Assert(false, "Unexpected NotifyCollectionChangedEventArgs action");
break;
}
}
#if FEATURE_ICOLLECTIONVIEW_SORT_OR_FILTER
/// <summary>
/// Create, filter and sort the local index array.
/// called from Refresh(), override in derived classes as needed.
/// </summary>
/// <param name="list">new ILIst to associate this view with</param>
/// <returns>new local array to use for this view</returns>
private IList PrepareLocalArray(IList list)
{
if (list == null)
{
throw new ArgumentNullException("list");
}
// filter the collection's array into the local array
List<object> al;
if (ActiveFilter == null)
{
al = new List<object>();
foreach (var o in list)
{
al.Add(o);
}
}
else
{
al = new List<object>(list.Count);
for (int k = 0; k < list.Count; ++k)
{
if (ActiveFilter(list[k]))
{
al.Add(list[k]);
}
}
}
// sort the local array
if (ActiveComparer != null)
{
al.Sort(ActiveComparer);
}
return al;
}
#endif
private void MoveCurrencyOffDeletedElement(int oldCurrentPosition)
{
int lastPosition = InternalCount - 1; // OK if last is -1
// if position falls beyond last position, move back to last position
int newPosition = (oldCurrentPosition < lastPosition) ? oldCurrentPosition : lastPosition;
// reset this to false before raising events to avoid problems in re-entrancy
_currentElementWasRemoved = false;
OnCurrentChanging();
if (newPosition < 0)
{
SetCurrent(null, newPosition);
}
else
{
SetCurrent(InternalItemAt(newPosition), newPosition);
}
OnCurrentChanged();
}
// Convert the collection's index to an index into the view.
// Return -1 if the index is unknown or moot (Reset events).
// Return -2 if the event doesn't apply to this view.
private int AdjustBefore(NotifyCollectionChangedAction action, object item, int index)
{
// index is not relevant to Reset events
if (action == NotifyCollectionChangedAction.Reset)
{
return -1;
}
IList ilFull = SourceCollection as IList;
// validate input
if (index < -1 || index > ilFull.Count)
{
throw CollectionViewsError.ListCollectionView.CollectionChangedOutOfRange();
}
if (action == NotifyCollectionChangedAction.Add)
{
if (index >= 0)
{
if (!object.Equals(item, ilFull[index]))
{
throw CollectionViewsError.CollectionView.ItemNotAtIndex("added");
}
}
else
{
// event didn't specify index - determine it the hard way
index = ilFull.IndexOf(item);
if (index < 0)
{
throw CollectionViewsError.ListCollectionView.AddedItemNotInCollection();
}
}
}
#if FEATURE_ICOLLECTIONVIEW_SORT_OR_FILTER
// If there's no sort or filter, use the index into the full array
if (!UsesLocalArray)
#endif
{
#if FEATURE_IEDITABLECOLLECTIONVIEW
if (IsAddingNew)
{
if (index > _newItemIndex)
{
index--; // the new item has been artificially moved elsewhere
}
}
#endif
return index;
}
#if FEATURE_ICOLLECTIONVIEW_SORT_OR_FILTER
if (action == NotifyCollectionChangedAction.Add)
{
#if FEATURE_ICOLLECTIONVIEW_FILTER
// if the item isn't in the filter, return -2
if (!PassesFilter(item))
{
return -2;
}
#endif
// search the local array
List<object> al = InternalList as List<object>;
if (al == null)
{
index = -1;
}
#if FEATURE_ICOLLECTIONVIEW_SORT
else if (ActiveComparer != null)
{
// if there's a sort order, use binary search
index = al.BinarySearch(item, ActiveComparer);
if (index < 0)
{
index = ~index;
}
}
#endif
else
{
// otherwise, do a linear search of the full array, advancing
// localIndex past elements that appear in the local array,
// until either (a) reaching the position of the item in the
// full array, or (b) falling off the end of the local array.
// localIndex is now the desired index.
// One small wrinkle: we have to ignore the target item in
// the local array (this arises in a Move event).
int fullIndex = 0, localIndex = 0;
while (fullIndex < index && localIndex < al.Count)
{
if (object.Equals(ilFull[fullIndex], al[localIndex]))
{
// match - current item passes filter. Skip it.
++fullIndex;
++localIndex;
}
else if (object.Equals(item, al[localIndex]))
{
// skip over an unmatched copy of the target item
// (this arises in a Move event)
++localIndex;
}
else
{
// no match - current item fails filter. Ignore it.
++fullIndex;
}
}
index = localIndex;
}
}
else if (action == NotifyCollectionChangedAction.Remove)
{
#if FEATURE_IEDITABLECOLLECTIONVIEW
if (!IsAddingNew || item != _newItem)
{
#endif
// a deleted item should already be in the local array
index = InternalList.IndexOf(item);
// but may not be, if it was already filtered out (can't use
// PassesFilter here, because the item could have changed
// while it was out of our sight)
if (index < 0)
{
return -2;
}
#if FEATURE_IEDITABLECOLLECTIONVIEW
}
else
{
// the new item is in a special position
return InternalCount - 1;
}
#endif
}
else
{
index = -1;
}
return (index < 0) ? index : index;
#endif
}
// fix up CurrentPosition and CurrentItem after a collection change
private void AdjustCurrencyForAdd(int index)
{
if (InternalCount == 1)
{
if (CurrentItem != null || CurrentPosition != -1)
{
// fire current changing notification
OnCurrentChanging();
}
// added first item; set current at BeforeFirst
SetCurrent(null, -1);
}
else if (index <= CurrentPosition)
{
// adjust current index if insertion is earlier
int newPosition = CurrentPosition + 1;
if (newPosition < InternalCount)
{
// CurrentItem might be out of sync if underlying list is not INCC
// or if this Add is the result of a Replace (Rem + Add)
SetCurrent(GetItemAt(newPosition), newPosition);
}
else
{
SetCurrent(null, InternalCount);
}
}
else if (!IsCurrentInSync)
{
// Make sure current item and position are in sync.
SetCurrent(CurrentItem, InternalIndexOf(CurrentItem));
}
}
// fix up CurrentPosition and CurrentItem after a collection change
private void AdjustCurrencyForRemove(int index)
{
// adjust current index if deletion is earlier
if (index < CurrentPosition)
{
SetCurrent(CurrentItem, CurrentPosition - 1);
}
// remember to move currency off the deleted element
else if (index == CurrentPosition)
{
_currentElementWasRemoved = true;
}
}
// fix up CurrentPosition and CurrentItem after a collection change
private void AdjustCurrencyForMove(int oldIndex, int newIndex)
{
if (oldIndex == CurrentPosition)
{
// moving the current item - currency moves with the item (bug 1942184)
SetCurrent(GetItemAt(newIndex), newIndex);
}
else if (oldIndex < CurrentPosition && CurrentPosition <= newIndex)
{
// moving an item from before current position to after -
// current item shifts back one position
SetCurrent(CurrentItem, CurrentPosition - 1);
}
else if (newIndex <= CurrentPosition && CurrentPosition < oldIndex)
{
// moving an item from after current position to before -
// current item shifts ahead one position
SetCurrent(CurrentItem, CurrentPosition + 1);
}
// else no change necessary
}
// fix up CurrentPosition and CurrentItem after a collection change
private void AdjustCurrencyForReplace(int index)
{
// remember to move currency off the deleted element
if (index == CurrentPosition)
{
_currentElementWasRemoved = true;
}
}
private void RaiseCurrencyChanges(
bool raiseCurrentChanged,
bool raiseCurrentItem,
bool raiseCurrentPosition,
bool raiseIsCurrentBeforeFirst,
bool raiseIsCurrentAfterLast)
{
if (raiseCurrentChanged)
{
OnCurrentChanged();
}
if (raiseIsCurrentAfterLast)
{
OnPropertyChanged(IsCurrentAfterLastPropertyName);
}
if (raiseIsCurrentBeforeFirst)
{
OnPropertyChanged(IsCurrentBeforeFirstPropertyName);
}
if (raiseCurrentPosition)
{
OnPropertyChanged(CurrentPositionPropertyName);
}
if (raiseCurrentItem)
{
OnPropertyChanged(CurrentItemPropertyName);
}
}
// build the sort and filter information from the relevant properties
private void PrepareSortAndFilter()
{
#if FEATURE_ICOLLECTIONVIEW_SORT
// sort: prepare the comparer
if (_sort != null && _sort.Count > 0)
{
ActiveComparer = new SortFieldComparer(_sort, Culture);
}
else
{
ActiveComparer = null;
}
#endif
#if FEATURE_ICOLLECTIONVIEW_FILTER
// filter: prepare the Predicate<object> filter
ActiveFilter = Filter;
#endif
}
#if FEATURE_ICOLLECTIONVIEW_SORT
// set new SortDescription collection; rehook collection change notification handler
private void SetSortDescriptions(SortDescriptionCollection descriptions)
{
if (_sort != null)
{
((INotifyCollectionChanged)_sort).CollectionChanged -= new NotifyCollectionChangedEventHandler(SortDescriptionsChanged);
}
_sort = descriptions;
if (_sort != null)
{
DiagnosticsDebug.Assert(_sort.Count == 0, "must be empty SortDescription collection");
((INotifyCollectionChanged)_sort).CollectionChanged += new NotifyCollectionChangedEventHandler(SortDescriptionsChanged);
}
}
// SortDescription was added/removed, refresh CollectionView
private void SortDescriptionsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
#if FEATURE_IEDITABLECOLLECTIONVIEW
if (IsAddingNew || IsEditingItem)
{
throw CollectionViewsError.CollectionView.MemberNotAllowedDuringAddOrEdit("Sorting");
}
#endif
RefreshOrDefer();
}
#endif
#if FEATURE_ICOLLECTIONVIEW_GROUP
// divide the data items into groups
private void PrepareGroups()
{
// discard old groups
_group.Clear();
// initialize the synthetic top level group
_group.Initialize();
// if there's no grouping, there's nothing to do
_isGrouping = _group.GroupBy != null;
if (!_isGrouping)
{
return;
}
// reset the grouping comparer
IComparer<object> comparer = ActiveComparer;
if (comparer != null)
{
_group.ActiveComparer = comparer;
}
else
{
CollectionViewGroupInternal.IListComparer ilc = _group.ActiveComparer as CollectionViewGroupInternal.IListComparer;
if (ilc != null)
{
ilc.ResetList(InternalList);
}
else
{
_group.ActiveComparer = new CollectionViewGroupInternal.IListComparer(InternalList);
}
}
// loop through the sorted/filtered list of items, dividing them
// into groups (with special cases for new item)
for (int k = 0, n = InternalList.Count; k < n; ++k)
{
object item = InternalList[k];
if (!IsAddingNew || !object.Equals(_newItem, item))
{
_group.AddToSubgroups(item, true /*loading*/);
}
}
if (IsAddingNew)
{
_group.InsertSpecialItem(_group.Items.Count, _newItem, true /*loading*/);
}
}
// For the Group to report collection changed
private void OnGroupChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
AdjustCurrencyForAdd(e.NewStartingIndex);
}
else if (e.Action == NotifyCollectionChangedAction.Remove)
{
AdjustCurrencyForRemove(e.OldStartingIndex);
}
OnCollectionChanged(e);
}
// The GroupDescriptions collection changed
private void OnGroupByChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (IsAddingNew || IsEditingItem)
{
throw CollectionViewsError.CollectionView.MemberNotAllowedDuringAddOrEdit("Grouping");
}
// This is a huge change. Just refresh the view.
RefreshOrDefer();
}
// A group description for one of the subgroups changed
private void OnGroupDescriptionChanged(object sender, EventArgs e)
{
if (IsAddingNew || IsEditingItem)
{
throw CollectionViewsError.CollectionView.MemberNotAllowedDuringAddOrEdit("Grouping");
}
// This is a huge change. Just refresh the view.
RefreshOrDefer();
}
// An item was inserted into the collection. Update the groups.
private void AddItemToGroups(object item)
{
if (IsAddingNew && item == _newItem)
{
_group.InsertSpecialItem(_group.Items.Count, item, false /*loading*/);
}
else
{
_group.AddToSubgroups(item, false /*loading*/);
}
}
// An item was removed from the collection. Update the groups.
private void RemoveItemFromGroups(object item)
{
if (CanGroupNamesChange || _group.RemoveFromSubgroups(item))
{
// the item didn't appear where we expected it to.
_group.RemoveItemFromSubgroupsByExhaustiveSearch(item);
}
}
#endif
/// <summary>
/// Helper to raise a PropertyChanged event />).
/// </summary>
private void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
//------------------------------------------------------
//
// Private Types
//
//------------------------------------------------------
/// <summary>
/// Private EffectiveNotifyCollectionChangedAction enum
/// </summary>
| will |
csharp | unoplatform__uno | src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Text/ParagraphStyle.cs | {
"start": 255,
"end": 1818
} | public enum ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Undefined = 0,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
None = 1,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Normal = 2,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Heading1 = 3,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Heading2 = 4,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Heading3 = 5,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Heading4 = 6,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Heading5 = 7,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Heading6 = 8,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Heading7 = 9,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Heading8 = 10,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Heading9 = 11,
#endif
}
#endif
}
| ParagraphStyle |
csharp | smartstore__Smartstore | src/Smartstore.Core/Platform/DataExchange/Domain/ExportFilter.cs | {
"start": 202,
"end": 5547
} | public class ____
{
/// <summary>
/// Store identifier. 0 to load all records.
/// </summary>
public int StoreId { get; set; }
/// <summary>
/// Entity created from.
/// </summary>
public DateTime? CreatedFrom { get; set; }
/// <summary>
/// Entity created to.
/// </summary>
public DateTime? CreatedTo { get; set; }
/// <summary>
/// A value indicating whether to load only published or non published entities.
/// </summary>
public bool? IsPublished { get; set; }
#region Product
/// <summary>
/// Minimum product identifier.
/// </summary>
public int? IdMinimum { get; set; }
/// <summary>
/// Maximum product identifier.
/// </summary>
public int? IdMaximum { get; set; }
/// <summary>
/// Minimum price.
/// </summary>
public decimal? PriceMinimum { get; set; }
/// <summary>
/// Maximum price.
/// </summary>
public decimal? PriceMaximum { get; set; }
/// <summary>
/// Minimum product availability.
/// </summary>
public int? AvailabilityMinimum { get; set; }
/// <summary>
/// Maximum product availability.
/// </summary>
public int? AvailabilityMaximum { get; set; }
/// <summary>
/// A value indicating whether to load products without any category mapping.
/// </summary>
public bool? WithoutCategories { get; set; }
/// <summary>
/// Category identifiers.
/// </summary>
public int[] CategoryIds { get; set; }
public int? CategoryId { get; set; }
/// <summary>
/// A value indicating whether products from subcategories should also be filtered.
/// </summary>
public bool IncludeSubCategories { get; set; }
/// <summary>
/// A value indicating whether to load products without any manufacturer mapping.
/// </summary>
public bool? WithoutManufacturers { get; set; }
/// <summary>
/// Manufacturer identifier.
/// </summary>
public int? ManufacturerId { get; set; }
/// <summary>
/// Identifiers of product tag.
/// </summary>
public int? ProductTagId { get; set; }
/// <summary>
/// A value indicating whether to load products that are marked as featured (relates only to categories and manufacturers).
/// </summary>
public bool? FeaturedProducts { get; set; }
/// <summary>
/// Filter by product type.
/// </summary>
public ProductType? ProductType { get; set; }
/// <summary>
/// Filter by visibility.
/// </summary>
public ProductVisibility? Visibility { get; set; } = ProductVisibility.Full;
#endregion
#region Order
/// <summary>
/// Filter by order status.
/// </summary>
public int[] OrderStatusIds { get; set; }
/// <summary>
/// Filter by payment status.
/// </summary>
public int[] PaymentStatusIds { get; set; }
/// <summary>
/// Filter by shipping status.
/// </summary>
public int[] ShippingStatusIds { get; set; }
#endregion
#region Customer
/// <summary>
/// Filter by active or inactive customers.
/// </summary>
public bool? IsActiveCustomer { get; set; }
/// <summary>
/// Filter by tax exempt customers.
/// </summary>
public bool? IsTaxExempt { get; set; }
/// <summary>
/// Identifiers of customer roles.
/// </summary>
public int[] CustomerRoleIds { get; set; }
/// <summary>
/// Filter by billing country identifiers.
/// </summary>
public int[] BillingCountryIds { get; set; }
/// <summary>
/// Filter by shipping country identifiers.
/// </summary>
public int[] ShippingCountryIds { get; set; }
/// <summary>
/// Filter by last activity date from.
/// </summary>
public DateTime? LastActivityFrom { get; set; }
/// <summary>
/// Filter by last activity date to.
/// </summary>
public DateTime? LastActivityTo { get; set; }
/// <summary>
/// Filter by at least spent amount.
/// </summary>
public decimal? HasSpentAtLeastAmount { get; set; }
/// <summary>
/// Filter by at least placed orders.
/// </summary>
public int? HasPlacedAtLeastOrders { get; set; }
#endregion
#region Newsletter Subscription
/// <summary>
/// Filter by active or inactive subscriber.
/// </summary>
public bool? IsActiveSubscriber { get; set; }
/// <summary>
/// Filter by language.
/// </summary>
public int? WorkingLanguageId { get; set; }
#endregion
#region Shopping Cart
/// <summary>
/// Filter by shopping cart type identifier.
/// </summary>
public int? ShoppingCartTypeId { get; set; }
#endregion
}
}
| ExportFilter |
csharp | aspnetboilerplate__aspnetboilerplate | src/Abp/Json/SystemTextJson/AbpDateTimeConverterModifier.cs | {
"start": 233,
"end": 1742
} | public class ____
{
private readonly List<string> _inputDateTimeFormats;
private readonly string _outputDateTimeFormat;
public AbpDateTimeConverterModifier(List<string> inputDateTimeFormats, string outputDateTimeFormat)
{
_inputDateTimeFormats = inputDateTimeFormats;
_outputDateTimeFormat = outputDateTimeFormat;
}
public Action<JsonTypeInfo> CreateModifyAction()
{
return Modify;
}
private void Modify(JsonTypeInfo jsonTypeInfo)
{
if (ReflectionHelper.GetSingleAttributeOfMemberOrDeclaringTypeOrDefault<DisableDateTimeNormalizationAttribute>(jsonTypeInfo.Type) != null)
{
return;
}
foreach (var property in jsonTypeInfo.Properties.Where(x => x.PropertyType == typeof(DateTime) || x.PropertyType == typeof(DateTime?)))
{
if (property.AttributeProvider == null ||
!property.AttributeProvider.GetCustomAttributes(typeof(DisableDateTimeNormalizationAttribute), false).Any())
{
property.CustomConverter = property.PropertyType == typeof(DateTime)
? (JsonConverter) new AbpDateTimeConverter(_inputDateTimeFormats, _outputDateTimeFormat)
: new AbpNullableDateTimeConverter(_inputDateTimeFormats, _outputDateTimeFormat);
}
}
}
}
}
| AbpDateTimeConverterModifier |
csharp | CommunityToolkit__Maui | src/CommunityToolkit.Maui.UnitTests/Extensions/NavigatedToEventArgsExtensionsTests.cs | {
"start": 2742,
"end": 3032
} | sealed class ____ : ContentPage
{
public event EventHandler<NavigatedToEventArgs>? NavigatedToEventArgsReceived;
protected override void OnNavigatedTo(NavigatedToEventArgs args)
{
base.OnNavigatedTo(args);
NavigatedToEventArgsReceived?.Invoke(this, args);
}
}
} | ShellContentPage |
csharp | OrchardCMS__OrchardCore | src/OrchardCore/OrchardCore.AdminMenu.Abstractions/Services/IAdminNodeProviderFactory.cs | {
"start": 80,
"end": 177
} | public interface ____
{
string Name { get; }
AdminNode Create();
}
| IAdminNodeProviderFactory |
csharp | dotnet__orleans | test/Transactions/Orleans.Transactions.Tests/Memory/TocFaultTransactionMemoryTests.cs | {
"start": 183,
"end": 496
} | public class ____ : TocFaultTransactionTestRunnerxUnit, IClassFixture<MemoryTransactionsFixture>
{
public TocFaultTransactionMemoryTests(MemoryTransactionsFixture fixture, ITestOutputHelper output)
: base(fixture.GrainFactory, output)
{
}
}
}
| TocFaultTransactionMemoryTests |
csharp | dotnet__reactive | Rx.NET/Samples/HOL/CS/Excercise2/Step06/Program.cs | {
"start": 90,
"end": 643
} | class ____
{
static void Main(string[] args)
{
IObservable<int> source = Observable.Range(5, 3);
IDisposable subscription = source.Subscribe(
x => Console.WriteLine("OnNext: {0}", x),
ex => Console.WriteLine("OnError: {0}", ex.Message),
() => Console.WriteLine("OnCompleted")
);
Console.WriteLine("Press ENTER to unsubscribe...");
Console.ReadLine();
subscription.Dispose();
}
}
}
| Program |
csharp | MapsterMapper__Mapster | src/Mapster.Tests/Classes/TypeTestClass.cs | {
"start": 1981,
"end": 2138
} | public class ____
{
public string Name { get; set; }
public DefaultMaxDepthTestDest Source { get; set; }
}
| DefaultMaxDepthTestSource |
csharp | ChilliCream__graphql-platform | src/StrawberryShake/CodeGeneration/test/CodeGeneration.CSharp.Tests/Integration/UploadScalarTest.Client.cs | {
"start": 35728,
"end": 56705
} | public partial class ____ : global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.ITestUploadQuery
{
private readonly global::StrawberryShake.IOperationExecutor<ITestUploadResult> _operationExecutor;
private readonly global::StrawberryShake.Serialization.IInputValueFormatter _stringFormatter;
private readonly global::StrawberryShake.Serialization.IInputValueFormatter _uploadFormatter;
private readonly global::StrawberryShake.Serialization.IInputValueFormatter _testInputFormatter;
private readonly global::System.Collections.Immutable.ImmutableArray<global::System.Action<global::StrawberryShake.OperationRequest>> _configure = global::System.Collections.Immutable.ImmutableArray<global::System.Action<global::StrawberryShake.OperationRequest>>.Empty;
public TestUploadQuery(global::StrawberryShake.IOperationExecutor<ITestUploadResult> operationExecutor, global::StrawberryShake.Serialization.ISerializerResolver serializerResolver)
{
_operationExecutor = operationExecutor ?? throw new global::System.ArgumentNullException(nameof(operationExecutor));
_stringFormatter = serializerResolver.GetInputValueFormatter("String");
_uploadFormatter = serializerResolver.GetInputValueFormatter("Upload");
_testInputFormatter = serializerResolver.GetInputValueFormatter("TestInput");
}
private TestUploadQuery(global::StrawberryShake.IOperationExecutor<ITestUploadResult> operationExecutor, global::System.Collections.Immutable.ImmutableArray<global::System.Action<global::StrawberryShake.OperationRequest>> configure, global::StrawberryShake.Serialization.IInputValueFormatter @stringFormatter, global::StrawberryShake.Serialization.IInputValueFormatter testInputFormatter, global::StrawberryShake.Serialization.IInputValueFormatter uploadFormatter)
{
_operationExecutor = operationExecutor;
_configure = configure;
_stringFormatter = @stringFormatter;
_testInputFormatter = testInputFormatter;
_uploadFormatter = uploadFormatter;
}
global::System.Type global::StrawberryShake.IOperationRequestFactory.ResultType => typeof(ITestUploadResult);
public global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.ITestUploadQuery With(global::System.Action<global::StrawberryShake.OperationRequest> configure)
{
return new global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.TestUploadQuery(_operationExecutor, _configure.Add(configure), _stringFormatter, _testInputFormatter, _uploadFormatter);
}
public global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.ITestUploadQuery WithRequestUri(global::System.Uri requestUri)
{
return With(r => r.ContextData["StrawberryShake.Transport.Http.HttpConnection.RequestUri"] = requestUri);
}
public global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.ITestUploadQuery WithHttpClient(global::System.Net.Http.HttpClient httpClient)
{
return With(r => r.ContextData["StrawberryShake.Transport.Http.HttpConnection.HttpClient"] = httpClient);
}
public async global::System.Threading.Tasks.Task<global::StrawberryShake.IOperationResult<ITestUploadResult>> ExecuteAsync(global::System.String? nonUpload, global::StrawberryShake.Upload? single, global::System.Collections.Generic.IReadOnlyList<global::StrawberryShake.Upload?>? list, global::System.Collections.Generic.IReadOnlyList<global::System.Collections.Generic.IReadOnlyList<global::StrawberryShake.Upload?>?>? nested, global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.TestInput? @object, global::System.Collections.Generic.IReadOnlyList<global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.TestInput?>? objectList, global::System.Collections.Generic.IReadOnlyList<global::System.Collections.Generic.IReadOnlyList<global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.TestInput?>?>? objectNested, global::System.Threading.CancellationToken cancellationToken = default)
{
var request = CreateRequest(nonUpload, single, list, nested, @object, objectList, objectNested);
foreach (var configure in _configure)
{
configure(request);
}
return await _operationExecutor.ExecuteAsync(request, cancellationToken).ConfigureAwait(false);
}
private void MapFilesFromArgumentSingle(global::System.String path, global::StrawberryShake.Upload? value, global::System.Collections.Generic.Dictionary<global::System.String, global::StrawberryShake.Upload?> files)
{
files.Add(path, value is global::StrawberryShake.Upload u ? u : null);
}
private void MapFilesFromArgumentList(global::System.String path, global::System.Collections.Generic.IReadOnlyList<global::StrawberryShake.Upload?>? value, global::System.Collections.Generic.Dictionary<global::System.String, global::StrawberryShake.Upload?> files)
{
if (value is { } value_i)
{
var path_counter = 0;
foreach (var value_lt in value_i)
{
var path_lt = path + "." + (path_counter++);
files.Add(path_lt, value_lt is global::StrawberryShake.Upload u ? u : null);
}
}
}
private void MapFilesFromArgumentNested(global::System.String path, global::System.Collections.Generic.IReadOnlyList<global::System.Collections.Generic.IReadOnlyList<global::StrawberryShake.Upload?>?>? value, global::System.Collections.Generic.Dictionary<global::System.String, global::StrawberryShake.Upload?> files)
{
if (value is { } value_i)
{
var path_counter = 0;
foreach (var value_lt in value_i)
{
var path_lt = path + "." + (path_counter++);
if (value_lt is { } value_lt_i)
{
var path_lt_counter = 0;
foreach (var value_lt_lt in value_lt_i)
{
var path_lt_lt = path_lt + "." + (path_lt_counter++);
files.Add(path_lt_lt, value_lt_lt is global::StrawberryShake.Upload u ? u : null);
}
}
}
}
}
private void MapFilesFromTypeTestInput(global::System.String path, global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.TestInput value, global::System.Collections.Generic.Dictionary<global::System.String, global::StrawberryShake.Upload?> files)
{
var pathBar = path + ".bar";
var valueBar = value.Bar;
if (valueBar is { } valueBar_i)
{
MapFilesFromTypeBarInput(pathBar, valueBar_i, files);
}
}
private void MapFilesFromTypeBarInput(global::System.String path, global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.BarInput value, global::System.Collections.Generic.Dictionary<global::System.String, global::StrawberryShake.Upload?> files)
{
var pathBaz = path + ".baz";
var valueBaz = value.Baz;
if (valueBaz is { } valueBaz_i)
{
MapFilesFromTypeBazInput(pathBaz, valueBaz_i, files);
}
}
private void MapFilesFromTypeBazInput(global::System.String path, global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.BazInput value, global::System.Collections.Generic.Dictionary<global::System.String, global::StrawberryShake.Upload?> files)
{
var pathFile = path + ".file";
var valueFile = value.File;
files.Add(pathFile, valueFile is global::StrawberryShake.Upload u ? u : null);
}
private void MapFilesFromArgumentObject(global::System.String path, global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.TestInput? value, global::System.Collections.Generic.Dictionary<global::System.String, global::StrawberryShake.Upload?> files)
{
if (value is { } value_i)
{
MapFilesFromTypeTestInput(path, value_i, files);
}
}
private void MapFilesFromArgumentObjectList(global::System.String path, global::System.Collections.Generic.IReadOnlyList<global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.TestInput?>? value, global::System.Collections.Generic.Dictionary<global::System.String, global::StrawberryShake.Upload?> files)
{
if (value is { } value_i)
{
var path_counter = 0;
foreach (var value_lt in value_i)
{
var path_lt = path + "." + (path_counter++);
if (value_lt is { } value_lt_i)
{
MapFilesFromTypeTestInput(path_lt, value_lt_i, files);
}
}
}
}
private void MapFilesFromArgumentObjectNested(global::System.String path, global::System.Collections.Generic.IReadOnlyList<global::System.Collections.Generic.IReadOnlyList<global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.TestInput?>?>? value, global::System.Collections.Generic.Dictionary<global::System.String, global::StrawberryShake.Upload?> files)
{
if (value is { } value_i)
{
var path_counter = 0;
foreach (var value_lt in value_i)
{
var path_lt = path + "." + (path_counter++);
if (value_lt is { } value_lt_i)
{
var path_lt_counter = 0;
foreach (var value_lt_lt in value_lt_i)
{
var path_lt_lt = path_lt + "." + (path_lt_counter++);
if (value_lt_lt is { } value_lt_lt_i)
{
MapFilesFromTypeTestInput(path_lt_lt, value_lt_lt_i, files);
}
}
}
}
}
}
public global::System.IObservable<global::StrawberryShake.IOperationResult<ITestUploadResult>> Watch(global::System.String? nonUpload, global::StrawberryShake.Upload? single, global::System.Collections.Generic.IReadOnlyList<global::StrawberryShake.Upload?>? list, global::System.Collections.Generic.IReadOnlyList<global::System.Collections.Generic.IReadOnlyList<global::StrawberryShake.Upload?>?>? nested, global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.TestInput? @object, global::System.Collections.Generic.IReadOnlyList<global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.TestInput?>? objectList, global::System.Collections.Generic.IReadOnlyList<global::System.Collections.Generic.IReadOnlyList<global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.TestInput?>?>? objectNested, global::StrawberryShake.ExecutionStrategy? strategy = null)
{
var request = CreateRequest(nonUpload, single, list, nested, @object, objectList, objectNested);
return _operationExecutor.Watch(request, strategy);
}
private global::StrawberryShake.OperationRequest CreateRequest(global::System.String? nonUpload, global::StrawberryShake.Upload? single, global::System.Collections.Generic.IReadOnlyList<global::StrawberryShake.Upload?>? list, global::System.Collections.Generic.IReadOnlyList<global::System.Collections.Generic.IReadOnlyList<global::StrawberryShake.Upload?>?>? nested, global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.TestInput? @object, global::System.Collections.Generic.IReadOnlyList<global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.TestInput?>? objectList, global::System.Collections.Generic.IReadOnlyList<global::System.Collections.Generic.IReadOnlyList<global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.TestInput?>?>? objectNested)
{
var variables = new global::System.Collections.Generic.Dictionary<global::System.String, global::System.Object?>();
variables.Add("nonUpload", FormatNonUpload(nonUpload));
variables.Add("single", FormatSingle(single));
variables.Add("list", FormatList(list));
variables.Add("nested", FormatNested(nested));
variables.Add("object", FormatObject(@object));
variables.Add("objectList", FormatObjectList(objectList));
variables.Add("objectNested", FormatObjectNested(objectNested));
var files = new global::System.Collections.Generic.Dictionary<global::System.String, global::StrawberryShake.Upload?>();
MapFilesFromArgumentSingle("variables.single", single, files);
MapFilesFromArgumentList("variables.list", list, files);
MapFilesFromArgumentNested("variables.nested", nested, files);
MapFilesFromArgumentObject("variables.object", @object, files);
MapFilesFromArgumentObjectList("variables.objectList", objectList, files);
MapFilesFromArgumentObjectNested("variables.objectNested", objectNested, files);
return CreateRequest(variables, files);
}
private global::StrawberryShake.OperationRequest CreateRequest(global::System.Collections.Generic.IReadOnlyDictionary<global::System.String, global::System.Object?>? variables, global::System.Collections.Generic.Dictionary<global::System.String, global::StrawberryShake.Upload?> files)
{
return new global::StrawberryShake.OperationRequest(id: TestUploadQueryDocument.Instance.Hash.Value, name: "TestUpload", document: TestUploadQueryDocument.Instance, strategy: global::StrawberryShake.RequestStrategy.Default, files: files, variables: variables);
}
private global::System.Object? FormatNonUpload(global::System.String? value)
{
if (value is null)
{
return value;
}
else
{
return _stringFormatter.Format(value);
}
}
private global::System.Object? FormatSingle(global::StrawberryShake.Upload? value)
{
if (value is null)
{
return value;
}
else
{
return _uploadFormatter.Format(value);
}
}
private global::System.Object? FormatList(global::System.Collections.Generic.IReadOnlyList<global::StrawberryShake.Upload?>? value)
{
if (value is null)
{
return value;
}
else
{
var value_list = new global::System.Collections.Generic.List<global::System.Object?>();
foreach (var value_elm in value)
{
if (value_elm is null)
{
value_list.Add(value_elm);
}
else
{
value_list.Add(_uploadFormatter.Format(value_elm));
}
}
return value_list;
}
}
private global::System.Object? FormatNested(global::System.Collections.Generic.IReadOnlyList<global::System.Collections.Generic.IReadOnlyList<global::StrawberryShake.Upload?>?>? value)
{
if (value is null)
{
return value;
}
else
{
var value_list = new global::System.Collections.Generic.List<global::System.Object?>();
foreach (var value_elm in value)
{
if (value_elm is null)
{
value_list.Add(value_elm);
}
else
{
var value_elm_list = new global::System.Collections.Generic.List<global::System.Object?>();
foreach (var value_elm_elm in value_elm)
{
if (value_elm_elm is null)
{
value_elm_list.Add(value_elm_elm);
}
else
{
value_elm_list.Add(_uploadFormatter.Format(value_elm_elm));
}
}
value_list.Add(value_elm_list);
}
}
return value_list;
}
}
private global::System.Object? FormatObject(global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.TestInput? value)
{
if (value is null)
{
return value;
}
else
{
return _testInputFormatter.Format(value);
}
}
private global::System.Object? FormatObjectList(global::System.Collections.Generic.IReadOnlyList<global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.TestInput?>? value)
{
if (value is null)
{
return value;
}
else
{
var value_list = new global::System.Collections.Generic.List<global::System.Object?>();
foreach (var value_elm in value)
{
if (value_elm is null)
{
value_list.Add(value_elm);
}
else
{
value_list.Add(_testInputFormatter.Format(value_elm));
}
}
return value_list;
}
}
private global::System.Object? FormatObjectNested(global::System.Collections.Generic.IReadOnlyList<global::System.Collections.Generic.IReadOnlyList<global::StrawberryShake.CodeGeneration.CSharp.Integration.UploadScalar.TestInput?>?>? value)
{
if (value is null)
{
return value;
}
else
{
var value_list = new global::System.Collections.Generic.List<global::System.Object?>();
foreach (var value_elm in value)
{
if (value_elm is null)
{
value_list.Add(value_elm);
}
else
{
var value_elm_list = new global::System.Collections.Generic.List<global::System.Object?>();
foreach (var value_elm_elm in value_elm)
{
if (value_elm_elm is null)
{
value_elm_list.Add(value_elm_elm);
}
else
{
value_elm_list.Add(_testInputFormatter.Format(value_elm_elm));
}
}
value_list.Add(value_elm_list);
}
}
return value_list;
}
}
global::StrawberryShake.OperationRequest global::StrawberryShake.IOperationRequestFactory.Create(global::System.Collections.Generic.IReadOnlyDictionary<global::System.String, global::System.Object?>? variables)
{
return CreateRequest(variables!, new global::System.Collections.Generic.Dictionary<global::System.String, global::StrawberryShake.Upload?>());
}
}
// StrawberryShake.CodeGeneration.CSharp.Generators.OperationServiceInterfaceGenerator
/// <summary>
/// Represents the operation service of the TestUpload GraphQL operation
/// <code>
/// query TestUpload(
/// $nonUpload: String
/// $single: Upload
/// $list: [Upload]
/// $nested: [[Upload]]
/// $object: TestInput
/// $objectList: [TestInput]
/// $objectNested: [[TestInput]]
/// ) {
/// upload(nonUpload: $nonUpload, single: $single, list: $list, nested: $nested, object: $object, objectList: $objectList, objectNested: $objectNested)
/// }
/// </code>
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")]
| TestUploadQuery |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Media.Core/TimedTextSourceResolveResultEventArgs.cs | {
"start": 293,
"end": 2063
} | public partial class ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal TimedTextSourceResolveResultEventArgs()
{
}
#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.Media.Core.TimedMetadataTrackError Error
{
get
{
throw new global::System.NotImplementedException("The member TimedMetadataTrackError TimedTextSourceResolveResultEventArgs.Error is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=TimedMetadataTrackError%20TimedTextSourceResolveResultEventArgs.Error");
}
}
#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<global::Windows.Media.Core.TimedMetadataTrack> Tracks
{
get
{
throw new global::System.NotImplementedException("The member IReadOnlyList<TimedMetadataTrack> TimedTextSourceResolveResultEventArgs.Tracks is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IReadOnlyList%3CTimedMetadataTrack%3E%20TimedTextSourceResolveResultEventArgs.Tracks");
}
}
#endif
// Forced skipping of method Windows.Media.Core.TimedTextSourceResolveResultEventArgs.Error.get
// Forced skipping of method Windows.Media.Core.TimedTextSourceResolveResultEventArgs.Tracks.get
}
}
| TimedTextSourceResolveResultEventArgs |
csharp | ardalis__CleanArchitecture | MinimalClean/src/MinimalClean.Architecture.Web/Infrastructure/Data/AppDbContext.cs | {
"start": 365,
"end": 1065
} | public class ____(DbContextOptions<AppDbContext> options) :
DbContext(options)
{
public DbSet<Product> Products => Set<Product>();
public DbSet<Cart> Carts => Set<Cart>();
public DbSet<CartItem> CartItems => Set<CartItem>();
public DbSet<GuestUser> GuestUsers => Set<GuestUser>();
public DbSet<Order> Orders => Set<Order>();
public DbSet<OrderItem> OrderItems => Set<OrderItem>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());
}
public override int SaveChanges() =>
SaveChangesAsync().GetAwaiter().GetResult();
}
| AppDbContext |
csharp | CommunityToolkit__WindowsCommunityToolkit | Microsoft.Toolkit.Uwp.UI.Media/Helpers/Cache/CompositionObjectCache{T}.cs | {
"start": 574,
"end": 2102
} | internal sealed class ____<T>
where T : CompositionObject
{
/// <summary>
/// The cache of weak references of type <typeparamref name="T"/>, to avoid memory leaks
/// </summary>
private readonly ConditionalWeakTable<Compositor, WeakReference<T>> cache = new ConditionalWeakTable<Compositor, WeakReference<T>>();
/// <summary>
/// Tries to retrieve a valid <typeparamref name="T"/> instance from the cache, and uses the provided factory if an existing item is not found
/// </summary>
/// <param name="compositor">The current <see cref="Compositor"/> instance to get the value for</param>
/// <param name="producer">A <see cref="Func{TResult}"/> instance used to produce a <typeparamref name="T"/> instance</param>
/// <returns>A <typeparamref name="T"/> instance that is linked to <paramref name="compositor"/></returns>
public T GetValue(Compositor compositor, Func<Compositor, T> producer)
{
lock (cache)
{
if (this.cache.TryGetValue(compositor, out var reference) &&
reference.TryGetTarget(out var instance))
{
return instance;
}
// Create a new instance when needed
var fallback = producer(compositor);
this.cache.AddOrUpdate(compositor, new WeakReference<T>(fallback));
return fallback;
}
}
}
} | CompositionObjectCache |
csharp | ChilliCream__graphql-platform | src/StrawberryShake/Client/test/Core.Tests/Serialization/BooleanSerializerTests.cs | {
"start": 42,
"end": 1574
} | public class ____
{
[Fact]
public void Parse()
{
// arrange
var serializer = new BooleanSerializer();
// act
bool? result = serializer.Parse(true);
// assert
Assert.True(Assert.IsType<bool>(result));
}
[Fact]
public void Format_Null()
{
// arrange
var serializer = new BooleanSerializer();
// act
var result = serializer.Format(null);
// assert
Assert.Null(result);
}
[Fact]
public void Format_True()
{
// arrange
var serializer = new BooleanSerializer();
// act
var result = serializer.Format(true);
// assert
Assert.True(Assert.IsType<bool>(result));
}
[Fact]
public void Format_False()
{
// arrange
var serializer = new BooleanSerializer();
// act
var result = serializer.Format(false);
// assert
Assert.False(Assert.IsType<bool>(result));
}
[Fact]
public void TypeName_Default()
{
// arrange
var serializer = new BooleanSerializer();
// act
var typeName = serializer.TypeName;
// assert
Assert.Equal("Boolean", typeName);
}
[Fact]
public void TypeName_Custom()
{
// arrange
var serializer = new BooleanSerializer("Abc");
// act
var typeName = serializer.TypeName;
// assert
Assert.Equal("Abc", typeName);
}
}
| BooleanSerializerTests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.