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__efcore
test/EFCore.Tests/Metadata/Internal/InternalNavigationBuilderTest.cs
{ "start": 13323, "end": 14030 }
protected class ____ { public static readonly FieldInfo DetailsField = typeof(Order) .GetField(nameof(_details), BindingFlags.Instance | BindingFlags.NonPublic); public static readonly FieldInfo OtherDetailsField = typeof(Order) .GetField(nameof(_otherDetails), BindingFlags.Instance | BindingFlags.NonPublic); public int OrderId { get; set; } private ICollection<OrderDetails> _details; private readonly ICollection<OrderDetails> _otherDetails = new List<OrderDetails>(); public OrderDetails SingleDetails { get; set; } public ICollection<OrderDetails> Details { get => _details; set => _details = value; } }
Order
csharp
dotnet__aspnetcore
src/Mvc/test/Mvc.IntegrationTests/ModelPrefixSelectionIntegrationTest.cs
{ "start": 4564, "end": 6169 }
private class ____ { [FromForm] public string Name { get; set; } } [Fact] public async Task ComplexModel_EmptyPrefixSelected_NoMatchingValueProviderValue_WithFilteredValueProviders() { // Arrange var parameterBinder = ModelBindingTestHelper.GetParameterBinder(); var parameter = new ParameterDescriptor() { Name = "parameter", ParameterType = typeof(Person4), BindingInfo = new BindingInfo() { BindingSource = BindingSource.Query, }, }; var testContext = ModelBindingTestHelper.GetTestContext(request => { // This will only match empty prefix, but can't be used because of [FromForm] on the property. request.QueryString = new QueryString("?Name="); // This value won't be used to select a prefix, because we're only looking at the query string. request.Form = new FormCollection(new Dictionary<string, StringValues>() { { "parameter", string.Empty }, }); }); var modelState = testContext.ModelState; // Act var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext); // Assert Assert.True(modelBindingResult.IsModelSet); var model = Assert.IsType<Person4>(modelBindingResult.Model); Assert.Null(model.Name); Assert.Empty(modelState); Assert.Equal(0, modelState.ErrorCount); Assert.True(modelState.IsValid); }
Person4
csharp
dotnet__efcore
test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs
{ "start": 257637, "end": 257857 }
public class ____ { public int Id { get; set; } public RelatedEntity1185 ParentEntity { get; set; } public IEnumerable<RelatedEntity1187> ChildEntities { get; set; } }
RelatedEntity1186
csharp
dotnet__BenchmarkDotNet
src/BenchmarkDotNet/Columns/BaselineAllocationRatioColumn.cs
{ "start": 240, "end": 4250 }
public class ____ : BaselineCustomColumn { public override string Id => nameof(BaselineAllocationRatioColumn); public override string ColumnName => Column.AllocRatio; public static readonly IColumn RatioMean = new BaselineAllocationRatioColumn(); private BaselineAllocationRatioColumn() { } public override string GetValue(Summary summary, BenchmarkCase benchmarkCase, Statistics baseline, IReadOnlyDictionary<string, Metric> baselineMetrics, Statistics current, IReadOnlyDictionary<string, Metric> currentMetrics, bool isBaseline) { double? ratio = GetAllocationRatio(currentMetrics, baselineMetrics); double? invertedRatio = GetAllocationRatio(baselineMetrics, currentMetrics); if (ratio == null) return "NA"; var cultureInfo = summary.GetCultureInfo(); var ratioStyle = summary?.Style?.RatioStyle ?? RatioStyle.Value; bool advancedPrecision = IsNonBaselinesPrecise(summary, baselineMetrics, benchmarkCase); switch (ratioStyle) { case RatioStyle.Value: return ratio.Value.ToString(advancedPrecision ? "N3" : "N2", cultureInfo); case RatioStyle.Percentage: return isBaseline ? "" : ratio.Value >= 1.0 ? "+" + ((ratio.Value - 1.0) * 100).ToString(advancedPrecision ? "N1" : "N0", cultureInfo) + "%" : "-" + ((1.0 - ratio.Value) * 100).ToString(advancedPrecision ? "N1" : "N0", cultureInfo) + "%"; case RatioStyle.Trend: return isBaseline ? "" : ratio.Value >= 1.0 ? ratio.Value.ToString(advancedPrecision ? "N3" : "N2", cultureInfo) + "x more" : invertedRatio == null ? "NA" : invertedRatio.Value.ToString(advancedPrecision ? "N3" : "N2", cultureInfo) + "x less"; default: throw new ArgumentOutOfRangeException(nameof(summary), ratioStyle, "RatioStyle is not supported"); } } private static bool IsNonBaselinesPrecise(Summary summary, IReadOnlyDictionary<string, Metric> baselineMetric, BenchmarkCase benchmarkCase) { string logicalGroupKey = summary.GetLogicalGroupKey(benchmarkCase); var nonBaselines = summary.GetNonBaselines(logicalGroupKey); return nonBaselines.Any(c => GetAllocationRatio(summary[c].Metrics, baselineMetric) is > 0 and < 0.01); } private static double? GetAllocationRatio( IReadOnlyDictionary<string, Metric>? current, IReadOnlyDictionary<string, Metric>? baseline) { double? currentBytes = GetAllocatedBytes(current); double? baselineBytes = GetAllocatedBytes(baseline); if (currentBytes == null || baselineBytes == null) return null; if (baselineBytes == 0) return null; return currentBytes / baselineBytes; } private static double? GetAllocatedBytes(IReadOnlyDictionary<string, Metric>? metrics) { var metric = metrics?.Values.FirstOrDefault(m => m.Descriptor is AllocatedMemoryMetricDescriptor); return metric?.Value; } public override ColumnCategory Category => ColumnCategory.Metric; //it should be displayed after Allocated column public override int PriorityInCategory => AllocatedMemoryMetricDescriptor.Instance.PriorityInCategory + 1; public override bool IsNumeric => true; public override UnitType UnitType => UnitType.Dimensionless; public override string Legend => "Allocated memory ratio distribution ([Current]/[Baseline])"; } }
BaselineAllocationRatioColumn
csharp
ServiceStack__ServiceStack.OrmLite
src/ServiceStack.OrmLite/NamingStrategy.cs
{ "start": 1127, "end": 1473 }
public class ____ : OrmLiteNamingStrategyBase { public override string GetTableName(string name) { return name.ToLowercaseUnderscore(); } public override string GetColumnName(string name) { return name.ToLowercaseUnderscore(); } }
LowercaseUnderscoreNamingStrategy
csharp
npgsql__npgsql
test/Npgsql.Tests/Types/CompositeTests.cs
{ "start": 2690, "end": 27723 }
class ____ : INpgsqlNameTranslator { public string TranslateTypeName(string clrName) => throw new NotImplementedException(); public string TranslateMemberName(string clrName) => clrName[0].ToString().ToLowerInvariant(); } #pragma warning disable CS0618 // GlobalTypeMapper is obsolete [Test, NonParallelizable] public async Task Global_mapping() { await using var adminConnection = await OpenConnectionAsync(); var type = await GetTempTypeName(adminConnection); await adminConnection.ExecuteNonQueryAsync($"CREATE TYPE {type} AS (x int, some_text text)"); NpgsqlConnection.GlobalTypeMapper.MapComposite<SomeComposite>(type); try { var dataSourceBuilder = CreateDataSourceBuilder(); dataSourceBuilder.MapComposite<SomeComposite>(type); await using var dataSource = dataSourceBuilder.Build(); await using var connection = await dataSource.OpenConnectionAsync(); await connection.ReloadTypesAsync(); await AssertType( connection, new SomeComposite { SomeText = "foo", X = 8 }, "(8,foo)", type, npgsqlDbType: null); } finally { NpgsqlConnection.GlobalTypeMapper.Reset(); } } #pragma warning restore CS0618 // GlobalTypeMapper is obsolete [Test] public async Task Nested() { await using var adminConnection = await OpenConnectionAsync(); var containerType = await GetTempTypeName(adminConnection); var containeeType = await GetTempTypeName(adminConnection); await adminConnection.ExecuteNonQueryAsync($@" CREATE TYPE {containeeType} AS (x int, some_text text); CREATE TYPE {containerType} AS (a int, containee {containeeType});"); var dataSourceBuilder = CreateDataSourceBuilder(); // Registration in inverse dependency order should work dataSourceBuilder .MapComposite<SomeCompositeContainer>(containerType) .MapComposite<SomeComposite>(containeeType); await using var dataSource = dataSourceBuilder.Build(); await using var connection = await dataSource.OpenConnectionAsync(); await AssertType( connection, new SomeCompositeContainer { A = 8, Containee = new() { SomeText = "foo", X = 9 } }, @"(8,""(9,foo)"")", containerType, npgsqlDbType: null); } [Test, IssueLink("https://github.com/npgsql/npgsql/issues/1168")] public async Task With_schema() { await using var adminConnection = await OpenConnectionAsync(); var schema = await CreateTempSchema(adminConnection); await adminConnection.ExecuteNonQueryAsync($"CREATE TYPE {schema}.some_composite AS (x int, some_text text)"); var dataSourceBuilder = CreateDataSourceBuilder(); dataSourceBuilder.MapComposite<SomeComposite>($"{schema}.some_composite"); await using var dataSource = dataSourceBuilder.Build(); await using var connection = await dataSource.OpenConnectionAsync(); await AssertType( connection, new SomeComposite { SomeText = "foo", X = 8 }, "(8,foo)", $"{schema}.some_composite", npgsqlDbType: null); } [Test, IssueLink("https://github.com/npgsql/npgsql/issues/4365")] public async Task In_different_schemas_same_type_with_nested() { await using var adminConnection = await OpenConnectionAsync(); var firstSchemaName = await CreateTempSchema(adminConnection); var secondSchemaName = await CreateTempSchema(adminConnection); await adminConnection.ExecuteNonQueryAsync($@" CREATE TYPE {firstSchemaName}.containee AS (x int, some_text text); CREATE TYPE {firstSchemaName}.container AS (a int, containee {firstSchemaName}.containee); CREATE TYPE {secondSchemaName}.containee AS (x int, some_text text); CREATE TYPE {secondSchemaName}.container AS (a int, containee {secondSchemaName}.containee);"); var dataSourceBuilder = CreateDataSourceBuilder(); dataSourceBuilder .MapComposite<SomeComposite>($"{firstSchemaName}.containee") .MapComposite<SomeCompositeContainer>($"{firstSchemaName}.container") .MapComposite<SomeComposite>($"{secondSchemaName}.containee") .MapComposite<SomeCompositeContainer>($"{secondSchemaName}.container"); await using var dataSource = dataSourceBuilder.Build(); await using var connection = await dataSource.OpenConnectionAsync(); await AssertType( connection, new SomeCompositeContainer { A = 8, Containee = new() { SomeText = "foo", X = 9 } }, @"(8,""(9,foo)"")", $"{secondSchemaName}.container", npgsqlDbType: null, isDefaultForWriting: false); await AssertType( connection, new SomeCompositeContainer { A = 8, Containee = new() { SomeText = "foo", X = 9 } }, @"(8,""(9,foo)"")", $"{firstSchemaName}.container", npgsqlDbType: null, isDefaultForWriting: true); } [Test, IssueLink("https://github.com/npgsql/npgsql/issues/5972")] public async Task With_schema_and_dots_in_type_name() { await using var adminConnection = await OpenConnectionAsync(); var schema = await CreateTempSchema(adminConnection); var typename = "Some.Composite.with.dots"; await adminConnection.ExecuteNonQueryAsync($"CREATE TYPE {schema}.\"{typename}\" AS (x int, some_text text)"); var dataSourceBuilder = CreateDataSourceBuilder(); dataSourceBuilder.MapComposite<SomeComposite>($"{schema}.{typename}"); await using var dataSource = dataSourceBuilder.Build(); await using var connection = await dataSource.OpenConnectionAsync(); await AssertType( connection, new SomeComposite { SomeText = "foobar", X = 10 }, "(10,foobar)", $"{schema}.\"{typename}\"", npgsqlDbType: null); } [Test] public async Task Struct() { await using var adminConnection = await OpenConnectionAsync(); var type = await GetTempTypeName(adminConnection); await adminConnection.ExecuteNonQueryAsync($"CREATE TYPE {type} AS (x int, some_text text)"); var dataSourceBuilder = CreateDataSourceBuilder(); dataSourceBuilder.MapComposite<SomeCompositeStruct>(type); await using var dataSource = dataSourceBuilder.Build(); await using var connection = await dataSource.OpenConnectionAsync(); await AssertType( connection, new SomeCompositeStruct { SomeText = "foo", X = 8 }, "(8,foo)", type, npgsqlDbType: null); } [Test] public async Task Array() { await using var adminConnection = await OpenConnectionAsync(); var type = await GetTempTypeName(adminConnection); await adminConnection.ExecuteNonQueryAsync($"CREATE TYPE {type} AS (x int, some_text text)"); var dataSourceBuilder = CreateDataSourceBuilder(); dataSourceBuilder.MapComposite<SomeComposite>(type); await using var dataSource = dataSourceBuilder.Build(); await using var connection = await dataSource.OpenConnectionAsync(); await AssertType( connection, new SomeComposite[] { new() { SomeText = "foo", X = 8 }, new() { SomeText = "bar", X = 9 }}, @"{""(8,foo)"",""(9,bar)""}", type + "[]", npgsqlDbType: null); } [Test, IssueLink("https://github.com/npgsql/npgsql/issues/859")] public async Task Name_translation() { await using var adminConnection = await OpenConnectionAsync(); var type = await GetTempTypeName(adminConnection); await adminConnection.ExecuteNonQueryAsync(@$" CREATE TYPE {type} AS (simple int, two_words int, some_database_name int)"); var dataSourceBuilder = CreateDataSourceBuilder(); dataSourceBuilder.MapComposite<NameTranslationComposite>(type); await using var dataSource = dataSourceBuilder.Build(); await using var connection = await dataSource.OpenConnectionAsync(); await AssertType( connection, new NameTranslationComposite { Simple = 2, TwoWords = 3, SomeClrName = 4 }, "(2,3,4)", type, npgsqlDbType: null); } [Test, IssueLink("https://github.com/npgsql/npgsql/issues/856")] public async Task Composite_containing_domain_type() { await using var adminConnection = await OpenConnectionAsync(); var domainType = await GetTempTypeName(adminConnection); var compositeType = await GetTempTypeName(adminConnection); await adminConnection.ExecuteNonQueryAsync($@" CREATE DOMAIN {domainType} AS TEXT; CREATE TYPE {compositeType} AS (street TEXT, postal_code {domainType})"); var dataSourceBuilder = CreateDataSourceBuilder(); dataSourceBuilder.MapComposite<Address>(compositeType); await using var dataSource = dataSourceBuilder.Build(); await using var connection = await dataSource.OpenConnectionAsync(); await AssertType( connection, new Address { PostalCode = "12345", Street = "Main St." }, @"(""Main St."",12345)", compositeType, npgsqlDbType: null); } [Test] public async Task Composite_containing_array_type() { await using var adminConnection = await OpenConnectionAsync(); var compositeType = await GetTempTypeName(adminConnection); await adminConnection.ExecuteNonQueryAsync($@" CREATE TYPE {compositeType} AS (ints int4[])"); var dataSourceBuilder = CreateDataSourceBuilder(); dataSourceBuilder.MapComposite<SomeCompositeWithArray>(compositeType); await using var dataSource = dataSourceBuilder.Build(); await using var connection = await dataSource.OpenConnectionAsync(); await AssertType( connection, new SomeCompositeWithArray { Ints = [1, 2, 3, 4] }, @"(""{1,2,3,4}"")", compositeType, npgsqlDbType: null, comparer: (actual, expected) => actual.Ints!.SequenceEqual(expected.Ints!)); } [Test] public async Task Composite_containing_enum_type() { await using var adminConnection = await OpenConnectionAsync(); var enumType = await GetTempTypeName(adminConnection); var compositeType = await GetTempTypeName(adminConnection); await adminConnection.ExecuteNonQueryAsync($@" CREATE TYPE {enumType} AS enum ('value1', 'value2', 'value3'); CREATE TYPE {compositeType} AS (enum_value {enumType});"); var dataSourceBuilder = CreateDataSourceBuilder(); dataSourceBuilder.MapComposite<SomeCompositeWithEnum>(compositeType); dataSourceBuilder.MapEnum<SomeCompositeWithEnum.TestEnum>(enumType); await using var dataSource = dataSourceBuilder.Build(); await using var connection = await dataSource.OpenConnectionAsync(); await AssertType( connection, new SomeCompositeWithEnum { EnumValue = SomeCompositeWithEnum.TestEnum.Value2 }, @"(value2)", compositeType, npgsqlDbType: null, comparer: (actual, expected) => actual.EnumValue == expected.EnumValue); } [Test] public async Task Composite_containing_IPAddress() { await using var adminConnection = await OpenConnectionAsync(); var compositeType = await GetTempTypeName(adminConnection); await adminConnection.ExecuteNonQueryAsync($@" CREATE TYPE {compositeType} AS (address inet)"); var dataSourceBuilder = CreateDataSourceBuilder(); dataSourceBuilder.MapComposite<SomeCompositeWithIPAddress>(compositeType); await using var dataSource = dataSourceBuilder.Build(); await using var connection = await dataSource.OpenConnectionAsync(); await AssertType( connection, new SomeCompositeWithIPAddress { Address = IPAddress.Loopback }, @"(127.0.0.1)", compositeType, npgsqlDbType: null, comparer: (actual, expected) => actual.Address!.Equals(expected.Address)); } [Test] public async Task Composite_containing_converter_resolver_type() { await using var adminConnection = await OpenConnectionAsync(); var compositeType = await GetTempTypeName(adminConnection); await adminConnection.ExecuteNonQueryAsync($@" CREATE TYPE {compositeType} AS (date_times timestamp[])"); var dataSourceBuilder = CreateDataSourceBuilder(); dataSourceBuilder.ConnectionStringBuilder.Timezone = "Europe/Berlin"; dataSourceBuilder.MapComposite<SomeCompositeWithConverterResolverType>(compositeType); await using var dataSource = dataSourceBuilder.Build(); await using var connection = await dataSource.OpenConnectionAsync(); await AssertType( connection, new SomeCompositeWithConverterResolverType { DateTimes = [new DateTime(DateTime.UnixEpoch.Ticks, DateTimeKind.Unspecified), new DateTime(DateTime.UnixEpoch.Ticks, DateTimeKind.Unspecified).AddDays(1) ] }, """("{""1970-01-01 00:00:00"",""1970-01-02 00:00:00""}")""", compositeType, npgsqlDbType: null, comparer: (actual, expected) => actual.DateTimes!.SequenceEqual(expected.DateTimes!)); } [Test] public async Task Composite_containing_converter_resolver_type_throws() { await using var adminConnection = await OpenConnectionAsync(); var compositeType = await GetTempTypeName(adminConnection); await adminConnection.ExecuteNonQueryAsync($@" CREATE TYPE {compositeType} AS (date_times timestamp[])"); var dataSourceBuilder = CreateDataSourceBuilder(); dataSourceBuilder.ConnectionStringBuilder.Timezone = "Europe/Berlin"; dataSourceBuilder.MapComposite<SomeCompositeWithConverterResolverType>(compositeType); await using var dataSource = dataSourceBuilder.Build(); await using var connection = await dataSource.OpenConnectionAsync(); Assert.ThrowsAsync<ArgumentException>(() => AssertType( connection, new SomeCompositeWithConverterResolverType { DateTimes = [DateTime.UnixEpoch] }, // UTC DateTime """("{""1970-01-01 01:00:00"",""1970-01-02 01:00:00""}")""", compositeType, npgsqlDbType: null, comparer: (actual, expected) => actual.DateTimes!.SequenceEqual(expected.DateTimes!))); } [Test, IssueLink("https://github.com/npgsql/npgsql/issues/990")] public async Task Table_as_composite([Values] bool enabled) { await using var adminConnection = await OpenConnectionAsync(); var table = await CreateTempTable(adminConnection, "x int, some_text text"); var dataSourceBuilder = CreateDataSourceBuilder(); dataSourceBuilder.MapComposite<SomeComposite>(table); dataSourceBuilder.ConfigureTypeLoading(b => b.EnableTableCompositesLoading(enabled)); await using var dataSource = dataSourceBuilder.Build(); await using var connection = await dataSource.OpenConnectionAsync(); if (enabled) await DoAssertion(); else { Assert.ThrowsAsync<NotSupportedException>(DoAssertion); // Start a transaction specifically for multiplexing (to bind a connector to the connection) await using var tx = await connection.BeginTransactionAsync(); Assert.That(connection.Connector!.DatabaseInfo.CompositeTypes.SingleOrDefault(c => c.Name.Contains(table)), Is.Null); Assert.That(connection.Connector!.DatabaseInfo.ArrayTypes.SingleOrDefault(c => c.Name.Contains(table)), Is.Null); } Task DoAssertion() => AssertType( connection, new SomeComposite { SomeText = "foo", X = 8 }, "(8,foo)", table, npgsqlDbType: null); } [Test, IssueLink("https://github.com/npgsql/npgsql/issues/1267")] public async Task Table_as_composite_with_deleted_columns() { await using var adminConnection = await OpenConnectionAsync(); var table = await CreateTempTable(adminConnection, "x int, some_text text, bar int"); await adminConnection.ExecuteNonQueryAsync($"ALTER TABLE {table} DROP COLUMN bar;"); var dataSourceBuilder = CreateDataSourceBuilder(); dataSourceBuilder.ConfigureTypeLoading(b => b.EnableTableCompositesLoading()); dataSourceBuilder.MapComposite<SomeComposite>(table); await using var dataSource = dataSourceBuilder.Build(); await using var connection = await dataSource.OpenConnectionAsync(); await AssertType( connection, new SomeComposite { SomeText = "foo", X = 8 }, "(8,foo)", table, npgsqlDbType: null); } [Test, IssueLink("https://github.com/npgsql/npgsql/issues/1125")] public async Task Nullable_property_in_class_composite() { await using var adminConnection = await OpenConnectionAsync(); var type = await GetTempTypeName(adminConnection); await adminConnection.ExecuteNonQueryAsync($"CREATE TYPE {type} AS (foo INT)"); var dataSourceBuilder = CreateDataSourceBuilder(); dataSourceBuilder.MapComposite<ClassWithNullableProperty>(type); await using var dataSource = dataSourceBuilder.Build(); await using var connection = await dataSource.OpenConnectionAsync(); await AssertType( connection, new ClassWithNullableProperty { Foo = 8 }, "(8)", type, npgsqlDbType: null); await AssertType( connection, new ClassWithNullableProperty { Foo = null }, "()", type, npgsqlDbType: null); } [Test, IssueLink("https://github.com/npgsql/npgsql/issues/1125")] public async Task Nullable_property_in_struct_composite() { await using var adminConnection = await OpenConnectionAsync(); var type = await GetTempTypeName(adminConnection); await adminConnection.ExecuteNonQueryAsync($"CREATE TYPE {type} AS (foo INT)"); var dataSourceBuilder = CreateDataSourceBuilder(); dataSourceBuilder.MapComposite<StructWithNullableProperty>(type); await using var dataSource = dataSourceBuilder.Build(); await using var connection = await dataSource.OpenConnectionAsync(); await AssertType( connection, new StructWithNullableProperty { Foo = 8 }, "(8)", type, npgsqlDbType: null); await AssertType( connection, new StructWithNullableProperty { Foo = null }, "()", type, npgsqlDbType: null); } [Test] public async Task PostgresType() { // With multiplexing we can't guarantee that after ReloadTypesAsync we'll execute the query on a connection which has the new types // Set max pool size to 1 enforce this await using var dataSource = CreateDataSource(connectionStringBuilderAction: csb => csb.MaxPoolSize = 1); await using var connection = await dataSource.OpenConnectionAsync(); var type1 = await GetTempTypeName(connection); var type2 = await GetTempTypeName(connection); await connection.ExecuteNonQueryAsync(@$" CREATE TYPE {type1} AS (x int, some_text text); CREATE TYPE {type2} AS (comp {type1}, comps {type1}[]);"); await connection.ReloadTypesAsync(); await using var cmd = new NpgsqlCommand( $"SELECT ROW(ROW(8, 'foo')::{type1}, ARRAY[ROW(9, 'bar')::{type1}, ROW(10, 'baz')::{type1}])::{type2}", connection); await using var reader = await cmd.ExecuteReaderAsync(); await reader.ReadAsync(); var comp2Type = (PostgresCompositeType)reader.GetPostgresType(0); Assert.That(comp2Type.Name, Is.EqualTo(type2)); Assert.That(comp2Type.FullName, Is.EqualTo($"public.{type2}")); Assert.That(comp2Type.Fields, Has.Count.EqualTo(2)); var field1 = comp2Type.Fields[0]; var field2 = comp2Type.Fields[1]; Assert.That(field1.Name, Is.EqualTo("comp")); Assert.That(field2.Name, Is.EqualTo("comps")); var comp1Type = (PostgresCompositeType)field1.Type; Assert.That(comp1Type.Name, Is.EqualTo(type1)); var arrType = (PostgresArrayType)field2.Type; Assert.That(arrType.Name, Is.EqualTo(type1 + "[]")); var elemType = arrType.Element; Assert.That(elemType, Is.SameAs(comp1Type)); } [Test] public async Task DuplicateConstructorParameters() { await using var adminConnection = await OpenConnectionAsync(); var type = await GetTempTypeName(adminConnection); await adminConnection.ExecuteNonQueryAsync($"CREATE TYPE {type} AS (long int8, boolean bool)"); var dataSourceBuilder = CreateDataSourceBuilder(); dataSourceBuilder.MapComposite<DuplicateOneLongOneBool>(type); await using var dataSource = dataSourceBuilder.Build(); await using var connection = await dataSource.OpenConnectionAsync(); var ex = Assert.ThrowsAsync<InvalidCastException>(async () => await AssertType( connection, new DuplicateOneLongOneBool(true, 1), "(1,t)", type, npgsqlDbType: null)); Assert.That(ex!.InnerException, Is.TypeOf<AmbiguousMatchException>()); } [Test] public async Task PartialConstructorMissingSetter() { await using var adminConnection = await OpenConnectionAsync(); var type = await GetTempTypeName(adminConnection); await adminConnection.ExecuteNonQueryAsync($"CREATE TYPE {type} AS (long int8, boolean bool)"); var dataSourceBuilder = CreateDataSourceBuilder(); dataSourceBuilder.MapComposite<MissingSetterOneLongOneBool>(type); await using var dataSource = dataSourceBuilder.Build(); await using var connection = await dataSource.OpenConnectionAsync(); var ex = Assert.ThrowsAsync<InvalidOperationException>(async () => await AssertTypeRead( connection, "(1,t)", type, new MissingSetterOneLongOneBool(true, 1))); Assert.That(ex, Is.TypeOf<InvalidOperationException>().With.Message.Contains("No (public) setter for")); } [Test] public async Task PartialConstructorWorks() { await using var adminConnection = await OpenConnectionAsync(); var type = await GetTempTypeName(adminConnection); await adminConnection.ExecuteNonQueryAsync($"CREATE TYPE {type} AS (long int8, boolean bool)"); var dataSourceBuilder = CreateDataSourceBuilder(); dataSourceBuilder.MapComposite<OneLongOneBool>(type); await using var dataSource = dataSourceBuilder.Build(); await using var connection = await dataSource.OpenConnectionAsync(); await AssertType( connection, new OneLongOneBool(1) { BooleanValue = true }, "(1,t)", type, npgsqlDbType: null); } [Test] public async Task CompositeOverRange() { await using var adminConnection = await OpenConnectionAsync(); var type = await GetTempTypeName(adminConnection); var rangeType = await GetTempTypeName(adminConnection); await adminConnection.ExecuteNonQueryAsync($"CREATE TYPE {type} AS (x int, some_text text); CREATE TYPE {rangeType} AS RANGE(subtype={type})"); var dataSourceBuilder = CreateDataSourceBuilder(); dataSourceBuilder.MapComposite<SomeComposite>(type); dataSourceBuilder.EnableUnmappedTypes(); await using var dataSource = dataSourceBuilder.Build(); await using var connection = await dataSource.OpenConnectionAsync(); var composite1 = new SomeComposite { SomeText = "foo", X = 8 }; var composite2 = new SomeComposite { SomeText = "bar", X = 42 }; await AssertType( connection, new NpgsqlRange<SomeComposite>(composite1, composite2), "[\"(8,foo)\",\"(42,bar)\"]", rangeType, npgsqlDbType: null, isDefaultForWriting: false); } #region Test Types #pragma warning disable CS9113 readonly
CustomTranslator
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.Extensions.Tests/BackgroundJobsTests.cs
{ "start": 4620, "end": 5170 }
public class ____ : SyncCommandWithResult<DependentJob,DependentJobResult> { public static long Count; public static IRequest? LastRequest { get; set; } public static DependentJob? LastCommandRequest { get; set; } protected override DependentJobResult Run(DependentJob request) { Interlocked.Increment(ref Count); LastRequest = Request; LastCommandRequest = request; var job = Request.GetBackgroundJob(); return new() { Id = request.Id, ParentJob = job.ParentJob }; } }
DependentJobCommand
csharp
dotnet__aspnetcore
src/Components/Analyzers/test/PersistentStateAnalyzerTest.cs
{ "start": 851, "end": 955 }
public abstract class ____ : System.Attribute {{ }}
CascadingParameterAttributeBase
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Driver.Tests/Core/MongoWriteConcernExceptionTests.cs
{ "start": 970, "end": 4665 }
public class ____ { private readonly ConnectionId _connectionId = new ConnectionId(new ServerId(new ClusterId(1), new DnsEndPoint("localhost", 27017)), 2).WithServerValue(3); private readonly string _message = "message"; private readonly WriteConcernResult _writeConcernResult = new WriteConcernResult(new BsonDocument("result", 1)); [Fact] public void constructor_should_initialize_subject() { var subject = new MongoWriteConcernException(_connectionId, _message, _writeConcernResult); subject.Command.Should().BeNull(); subject.ConnectionId.Should().BeSameAs(_connectionId); subject.InnerException.Should().BeNull(); subject.Message.Should().BeSameAs(_message); subject.Result.Should().Be(_writeConcernResult.Response); subject.WriteConcernResult.Should().Be(_writeConcernResult); } [Theory] [InlineData(ServerErrorCode.LegacyNotPrimary, typeof(MongoNotPrimaryException))] [InlineData(ServerErrorCode.NotWritablePrimary, typeof(MongoNotPrimaryException))] [InlineData(ServerErrorCode.NotPrimaryNoSecondaryOk, typeof(MongoNotPrimaryException))] [InlineData(OppressiveLanguageConstants.LegacyNotPrimaryErrorMessage, typeof(MongoNotPrimaryException))] [InlineData(ServerErrorCode.InterruptedAtShutdown, typeof(MongoNodeIsRecoveringException))] // IsShutdownError [InlineData(ServerErrorCode.ShutdownInProgress, typeof(MongoNodeIsRecoveringException))] // IsShutdownError [InlineData(ServerErrorCode.InterruptedDueToReplStateChange, typeof(MongoNodeIsRecoveringException))] [InlineData(ServerErrorCode.NotPrimaryOrSecondary, typeof(MongoNodeIsRecoveringException))] [InlineData(ServerErrorCode.PrimarySteppedDown, typeof(MongoNodeIsRecoveringException))] [InlineData(OppressiveLanguageConstants.LegacyNotPrimaryOrSecondaryErrorMessage, typeof(MongoNodeIsRecoveringException))] [InlineData("node is recovering", typeof(MongoNodeIsRecoveringException))] [InlineData(ServerErrorCode.MaxTimeMSExpired, typeof(MongoExecutionTimeoutException))] [InlineData(13475, typeof(MongoExecutionTimeoutException))] [InlineData(16986, typeof(MongoExecutionTimeoutException))] [InlineData(16712, typeof(MongoExecutionTimeoutException))] [InlineData("exceeded time limit", typeof(MongoExecutionTimeoutException))] [InlineData("execution terminated", typeof(MongoExecutionTimeoutException))] [InlineData(-1, null)] [InlineData("test", null)] public void constructor_should_should_map_writeConcernResult(object exceptionInfo, Type expectedExceptionType) { var response = new BsonDocument { { "writeConcernError", Enum.TryParse<ServerErrorCode>(exceptionInfo.ToString(), out var errorCode) ? new BsonDocument("code", (int)errorCode) : new BsonDocument("errmsg", exceptionInfo.ToString()) } }; var writeConcernResult = new WriteConcernResult(response); var writeConcernException = new MongoWriteConcernException(_connectionId, "dummy", writeConcernResult); var result = writeConcernException.MappedWriteConcernResultException; if (expectedExceptionType != null) { result.GetType().Should().Be(expectedExceptionType); } else { result.Should().BeNull(); } } } }
MongoWriteConcernExceptionTests
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/Collections/Pooled/PooledStack.cs
{ "start": 1007, "end": 21981 }
internal class ____<T> : IEnumerable<T>, ICollection, IReadOnlyCollection<T>, IDisposable, IDeserializationCallback { [NonSerialized] private ArrayPool<T> _pool; [NonSerialized] private object? _syncRoot; private T[] _array; // Storage for stack elements. Do not rename (binary serialization) private int _size; // Number of items in the stack. Do not rename (binary serialization) private int _version; // Used to keep enumerator in sync w/ collection. Do not rename (binary serialization) private readonly bool _clearOnFree; private const int DefaultCapacity = 4; #region Constructors /// <summary> /// Create a stack with the default initial capacity. /// </summary> public PooledStack() : this(ClearMode.Auto, ArrayPool<T>.Shared) { } /// <summary> /// Create a stack with the default initial capacity. /// </summary> public PooledStack(ClearMode clearMode) : this(clearMode, ArrayPool<T>.Shared) { } /// <summary> /// Create a stack with the default initial capacity. /// </summary> public PooledStack(ArrayPool<T> customPool) : this(ClearMode.Auto, customPool) { } /// <summary> /// Create a stack with the default initial capacity and a custom ArrayPool. /// </summary> public PooledStack(ClearMode clearMode, ArrayPool<T> customPool) { _pool = customPool ?? ArrayPool<T>.Shared; _array = Array.Empty<T>(); _clearOnFree = ShouldClear(clearMode); } /// <summary> /// Create a stack with a specific initial capacity. The initial capacity /// must be a non-negative number. /// </summary> public PooledStack(int capacity) : this(capacity, ClearMode.Auto, ArrayPool<T>.Shared) { } /// <summary> /// Create a stack with a specific initial capacity. The initial capacity /// must be a non-negative number. /// </summary> public PooledStack(int capacity, ClearMode clearMode) : this(capacity, clearMode, ArrayPool<T>.Shared) { } /// <summary> /// Create a stack with a specific initial capacity. The initial capacity /// must be a non-negative number. /// </summary> public PooledStack(int capacity, ArrayPool<T> customPool) : this(capacity, ClearMode.Auto, customPool) { } /// <summary> /// Create a stack with a specific initial capacity. The initial capacity /// must be a non-negative number. /// </summary> public PooledStack(int capacity, ClearMode clearMode, ArrayPool<T> customPool) { if (capacity < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } _pool = customPool ?? ArrayPool<T>.Shared; _array = _pool.Rent(capacity); _clearOnFree = ShouldClear(clearMode); } /// <summary> /// Fills a Stack with the contents of a particular collection. The items are /// pushed onto the stack in the same order they are read by the enumerator. /// </summary> public PooledStack(IEnumerable<T> enumerable) : this(enumerable, ClearMode.Auto, ArrayPool<T>.Shared) { } /// <summary> /// Fills a Stack with the contents of a particular collection. The items are /// pushed onto the stack in the same order they are read by the enumerator. /// </summary> public PooledStack(IEnumerable<T> enumerable, ClearMode clearMode) : this(enumerable, clearMode, ArrayPool<T>.Shared) { } /// <summary> /// Fills a Stack with the contents of a particular collection. The items are /// pushed onto the stack in the same order they are read by the enumerator. /// </summary> public PooledStack(IEnumerable<T> enumerable, ArrayPool<T> customPool) : this(enumerable, ClearMode.Auto, customPool) { } /// <summary> /// Fills a Stack with the contents of a particular collection. The items are /// pushed onto the stack in the same order they are read by the enumerator. /// </summary> public PooledStack(IEnumerable<T> enumerable, ClearMode clearMode, ArrayPool<T> customPool) { _pool = customPool ?? ArrayPool<T>.Shared; _clearOnFree = ShouldClear(clearMode); switch (enumerable) { case null: ThrowHelper.ThrowArgumentNullException(ExceptionArgument.enumerable); break; case ICollection<T> collection: if (collection.Count == 0) { _array = Array.Empty<T>(); } else { _array = _pool.Rent(collection.Count); collection.CopyTo(_array, 0); _size = collection.Count; } break; default: using (var list = new PooledList<T>(enumerable)) { _array = _pool.Rent(list.Count); list.Span.CopyTo(_array); _size = list.Count; } break; } } /// <summary> /// Fills a Stack with the contents of a particular collection. The items are /// pushed onto the stack in the same order they are read by the enumerator. /// </summary> public PooledStack(T[] array) : this(array.AsSpan(), ClearMode.Auto, ArrayPool<T>.Shared) { } /// <summary> /// Fills a Stack with the contents of a particular collection. The items are /// pushed onto the stack in the same order they are read by the enumerator. /// </summary> public PooledStack(T[] array, ClearMode clearMode) : this(array.AsSpan(), clearMode, ArrayPool<T>.Shared) { } /// <summary> /// Fills a Stack with the contents of a particular collection. The items are /// pushed onto the stack in the same order they are read by the enumerator. /// </summary> public PooledStack(T[] array, ArrayPool<T> customPool) : this(array.AsSpan(), ClearMode.Auto, customPool) { } /// <summary> /// Fills a Stack with the contents of a particular collection. The items are /// pushed onto the stack in the same order they are read by the enumerator. /// </summary> public PooledStack(T[] array, ClearMode clearMode, ArrayPool<T> customPool) : this(array.AsSpan(), clearMode, customPool) { } /// <summary> /// Fills a Stack with the contents of a particular collection. The items are /// pushed onto the stack in the same order they are read by the enumerator. /// </summary> public PooledStack(ReadOnlySpan<T> span) : this(span, ClearMode.Auto, ArrayPool<T>.Shared) { } /// <summary> /// Fills a Stack with the contents of a particular collection. The items are /// pushed onto the stack in the same order they are read by the enumerator. /// </summary> public PooledStack(ReadOnlySpan<T> span, ClearMode clearMode) : this(span, clearMode, ArrayPool<T>.Shared) { } /// <summary> /// Fills a Stack with the contents of a particular collection. The items are /// pushed onto the stack in the same order they are read by the enumerator. /// </summary> public PooledStack(ReadOnlySpan<T> span, ArrayPool<T> customPool) : this(span, ClearMode.Auto, customPool) { } /// <summary> /// Fills a Stack with the contents of a particular collection. The items are /// pushed onto the stack in the same order they are read by the enumerator. /// </summary> public PooledStack(ReadOnlySpan<T> span, ClearMode clearMode, ArrayPool<T> customPool) { _pool = customPool ?? ArrayPool<T>.Shared; _clearOnFree = ShouldClear(clearMode); _array = _pool.Rent(span.Length); span.CopyTo(_array); _size = span.Length; } #endregion /// <summary> /// The number of items in the stack. /// </summary> public int Count => _size; /// <summary> /// Returns the ClearMode behavior for the collection, denoting whether values are /// cleared from internal arrays before returning them to the pool. /// </summary> public ClearMode ClearMode => _clearOnFree ? ClearMode.Always : ClearMode.Never; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot { get { if (_syncRoot == null) { Interlocked.CompareExchange<object?>(ref _syncRoot, new object(), null); } return _syncRoot; } } /// <summary> /// Removes all Objects from the Stack. /// </summary> public void Clear() { if (_clearOnFree) { Array.Clear(_array, 0, _size); // clear the elements so that the gc can reclaim the references. } _size = 0; _version++; } /// <summary> /// Compares items using the default equality comparer /// </summary> public bool Contains(T item) { // PERF: Internally Array.LastIndexOf calls // EqualityComparer<T>.Default.LastIndexOf, which // is specialized for different types. This // boosts performance since instead of making a // virtual method call each iteration of the loop, // via EqualityComparer<T>.Default.Equals, we // only make one virtual call to EqualityComparer.LastIndexOf. return _size != 0 && Array.LastIndexOf(_array, item, _size - 1) != -1; } /// <summary> /// This method removes all items which match the predicate. /// The complexity is O(n). /// </summary> public int RemoveWhere(Func<T, bool> match) { if (match == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); int freeIndex = 0; // the first free slot in items array // Find the first item which needs to be removed. while (freeIndex < _size && !match(_array[freeIndex])) freeIndex++; if (freeIndex >= _size) return 0; int current = freeIndex + 1; while (current < _size) { // Find the first item which needs to be kept. while (current < _size && match(_array[current])) current++; if (current < _size) { // copy item to the free slot. _array[freeIndex++] = _array[current++]; } } if (_clearOnFree) { // Clear the removed elements so that the gc can reclaim the references. Array.Clear(_array, freeIndex, _size - freeIndex); } int result = _size - freeIndex; _size = freeIndex; _version++; return result; } // Copies the stack into an array. public void CopyTo(T[] array, int arrayIndex) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (arrayIndex < 0 || arrayIndex > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.arrayIndex); } if (array.Length - arrayIndex < _size) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } Debug.Assert(array != _array); int srcIndex = 0; int dstIndex = arrayIndex + _size; while (srcIndex < _size) { array[--dstIndex] = _array[srcIndex++]; } } public void CopyTo(Span<T> span) { if (span.Length < _size) { ThrowHelper.ThrowArgumentException_DestinationTooShort(); } int srcIndex = 0; int dstIndex = _size; while (srcIndex < _size) { span[--dstIndex] = _array[srcIndex++]; } } void ICollection.CopyTo(Array array, int arrayIndex) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound, ExceptionArgument.array); } if (arrayIndex < 0 || arrayIndex > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.arrayIndex); } if (array.Length - arrayIndex < _size) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); } try { Array.Copy(_array, 0, array, arrayIndex, _size); Array.Reverse(array, arrayIndex, _size); } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException_Argument_InvalidArrayType(); } } /// <summary> /// Returns an IEnumerator for this PooledStack. /// </summary> /// <returns></returns> public Enumerator GetEnumerator() => new Enumerator(this); /// <internalonly/> IEnumerator<T> IEnumerable<T>.GetEnumerator() => new Enumerator(this); IEnumerator IEnumerable.GetEnumerator() => new Enumerator(this); public void TrimExcess() { if (_size == 0) { ReturnArray(replaceWith: Array.Empty<T>()); _version++; return; } int threshold = (int)(_array.Length * 0.9); if (_size < threshold) { var newArray = _pool.Rent(_size); if (newArray.Length < _array.Length) { Array.Copy(_array, newArray, _size); ReturnArray(replaceWith: newArray); _version++; } else { // The array from the pool wasn't any smaller than the one we already had, // (we can only control minimum size) so return it and do nothing. // If we create an exact-sized array not from the pool, we'll // get an exception when returning it to the pool. _pool.Return(newArray); } } } /// <summary> /// Returns the top object on the stack without removing it. If the stack /// is empty, Peek throws an InvalidOperationException. /// </summary> public T Peek() { int size = _size - 1; T[] array = _array; if ((uint)size >= (uint)array.Length) { ThrowForEmptyStack(); } return array[size]; } public bool TryPeek([MaybeNullWhen(false)] out T result) { int size = _size - 1; T[] array = _array; if ((uint)size >= (uint)array.Length) { result = default; return false; } result = array[size]; return true; } /// <summary> /// Pops an item from the top of the stack. If the stack is empty, Pop /// throws an InvalidOperationException. /// </summary> public T Pop() { int size = _size - 1; T[] array = _array; // if (_size == 0) is equivalent to if (size == -1), and this case // is covered with (uint)size, thus allowing bounds check elimination // https://github.com/dotnet/coreclr/pull/9773 if ((uint)size >= (uint)array.Length) { ThrowForEmptyStack(); } _version++; _size = size; T item = array[size]; if (_clearOnFree) { array[size] = default!; // Free memory quicker. } return item; } public bool TryPop([MaybeNullWhen(false)] out T result) { int size = _size - 1; T[] array = _array; if ((uint)size >= (uint)array.Length) { result = default; return false; } _version++; _size = size; result = array[size]; if (_clearOnFree) { array[size] = default!; // Free memory quicker. } return true; } /// <summary> /// Pushes an item to the top of the stack. /// </summary> public void Push(T item) { int size = _size; T[] array = _array; if ((uint)size < (uint)array.Length) { array[size] = item; _version++; _size = size + 1; } else { PushWithResize(item); } } // Non-inline from Stack.Push to improve its code quality as uncommon path [MethodImpl(MethodImplOptions.NoInlining)] private void PushWithResize(T item) { var newArray = _pool.Rent((_array.Length == 0) ? DefaultCapacity : 2 * _array.Length); Array.Copy(_array, newArray, _size); ReturnArray(replaceWith: newArray); _array[_size] = item; _version++; _size++; } /// <summary> /// Copies the Stack to an array, in the same order Pop would return the items. /// </summary> public T[] ToArray() { if (_size == 0) return Array.Empty<T>(); T[] objArray = new T[_size]; int i = 0; while (i < _size) { objArray[i] = _array[_size - i - 1]; i++; } return objArray; } private void ThrowForEmptyStack() { Debug.Assert(_size == 0); throw new InvalidOperationException("Stack was empty."); } private void ReturnArray(T[]? replaceWith = null) { if (_array?.Length > 0) { try { _pool.Return(_array, clearArray: _clearOnFree); } catch (ArgumentException) { // oh well, the array pool didn't like our array } } if (!(replaceWith is null)) { _array = replaceWith; } } private static bool ShouldClear(ClearMode mode) { #if NETCOREAPP2_1_OR_GREATER return mode == ClearMode.Always || (mode == ClearMode.Auto && RuntimeHelpers.IsReferenceOrContainsReferences<T>()); #else return mode != ClearMode.Never; #endif } public void Dispose() { ReturnArray(replaceWith: Array.Empty<T>()); _size = 0; _version++; } void IDeserializationCallback.OnDeserialization(object? sender) { // We can't serialize array pools, so deserialized PooledStacks will // have to use the shared pool, even if they were using a custom pool // before serialization. _pool = ArrayPool<T>.Shared; } [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")]
PooledStack
csharp
ChilliCream__graphql-platform
src/StrawberryShake/CodeGeneration/test/CodeGeneration.CSharp.Tests/Integration/StarWarsGetHeroWithFragmentIncludeAndSkipDirectiveTest.Client.cs
{ "start": 91938, "end": 92691 }
public partial class ____ : global::StrawberryShake.StoreAccessor { public StarWarsGetHeroWithFragmentIncludeAndSkipDirectiveClientStoreAccessor(global::StrawberryShake.IOperationStore operationStore, global::StrawberryShake.IEntityStore entityStore, global::StrawberryShake.IEntityIdSerializer entityIdSerializer, global::System.Collections.Generic.IEnumerable<global::StrawberryShake.IOperationRequestFactory> requestFactories, global::System.Collections.Generic.IEnumerable<global::StrawberryShake.IOperationResultDataFactory> resultDataFactories) : base(operationStore, entityStore, entityIdSerializer, requestFactories, resultDataFactories) { } } }
StarWarsGetHeroWithFragmentIncludeAndSkipDirectiveClientStoreAccessor
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/src/Validation/MaxValidationErrorsException.cs
{ "start": 140, "end": 438 }
public class ____ : Exception { public MaxValidationErrorsException() { } public MaxValidationErrorsException(string message) : base(message) { } public MaxValidationErrorsException(string message, Exception inner) : base(message, inner) { } }
MaxValidationErrorsException
csharp
ServiceStack__ServiceStack
ServiceStack.OrmLite/src/ServiceStack.OrmLite/Expressions/IUntypedSqlExpression.cs
{ "start": 258, "end": 6490 }
public interface ____ : ISqlExpression { string TableAlias { get; set; } bool PrefixFieldWithTableName { get; set; } bool WhereStatementWithoutWhereString { get; set; } IOrmLiteDialectProvider DialectProvider { get; set; } string SelectExpression { get; set; } string FromExpression { get; set; } string BodyExpression { get; } string WhereExpression { get; set; } string GroupByExpression { get; set; } string HavingExpression { get; set; } string OrderByExpression { get; set; } int? Rows { get; set; } int? Offset { get; set; } List<string> UpdateFields { get; set; } List<string> InsertFields { get; set; } ModelDefinition ModelDef { get; } IUntypedSqlExpression Clone(); IUntypedSqlExpression Select(); IUntypedSqlExpression Select(string selectExpression); IUntypedSqlExpression UnsafeSelect(string rawSelect); IUntypedSqlExpression Select<Table1, Table2>(Expression<Func<Table1, Table2, object>> fields); IUntypedSqlExpression Select<Table1, Table2, Table3>(Expression<Func<Table1, Table2, Table3, object>> fields); IUntypedSqlExpression SelectDistinct<Table1, Table2>(Expression<Func<Table1, Table2, object>> fields); IUntypedSqlExpression SelectDistinct<Table1, Table2, Table3>(Expression<Func<Table1, Table2, Table3, object>> fields); IUntypedSqlExpression SelectDistinct(); IUntypedSqlExpression From(string tables); IUntypedSqlExpression UnsafeFrom(string rawFrom); IUntypedSqlExpression Where(); IUntypedSqlExpression UnsafeWhere(string rawSql, params object[] filterParams); IUntypedSqlExpression Ensure(string sqlFilter, params object[] filterParams); IUntypedSqlExpression Where(string sqlFilter, params object[] filterParams); IUntypedSqlExpression UnsafeAnd(string rawSql, params object[] filterParams); IUntypedSqlExpression And(string sqlFilter, params object[] filterParams); IUntypedSqlExpression UnsafeOr(string rawSql, params object[] filterParams); IUntypedSqlExpression Or(string sqlFilter, params object[] filterParams); IUntypedSqlExpression AddCondition(string condition, string sqlFilter, params object[] filterParams); IUntypedSqlExpression GroupBy(); IUntypedSqlExpression GroupBy(string groupBy); IUntypedSqlExpression Having(); IUntypedSqlExpression Having(string sqlFilter, params object[] filterParams); IUntypedSqlExpression OrderBy(); IUntypedSqlExpression OrderBy(string orderBy); ModelDefinition GetModelDefinition(FieldDefinition fieldDef); IUntypedSqlExpression OrderByFields(params FieldDefinition[] fields); IUntypedSqlExpression OrderByFieldsDescending(params FieldDefinition[] fields); IUntypedSqlExpression OrderByFields(params string[] fieldNames); IUntypedSqlExpression OrderByFieldsDescending(params string[] fieldNames); IUntypedSqlExpression OrderBy<Table>(Expression<Func<Table, object>> keySelector); IUntypedSqlExpression ThenBy(string orderBy); IUntypedSqlExpression ThenBy<Table>(Expression<Func<Table, object>> keySelector); IUntypedSqlExpression OrderByDescending<Table>(Expression<Func<Table, object>> keySelector); IUntypedSqlExpression OrderByDescending(string orderBy); IUntypedSqlExpression ThenByDescending(string orderBy); IUntypedSqlExpression ThenByDescending<Table>(Expression<Func<Table, object>> keySelector); IUntypedSqlExpression Skip(int? skip = null); IUntypedSqlExpression Take(int? take = null); IUntypedSqlExpression Limit(int skip, int rows); IUntypedSqlExpression Limit(int? skip, int? rows); IUntypedSqlExpression Limit(int rows); IUntypedSqlExpression Limit(); IUntypedSqlExpression ClearLimits(); IUntypedSqlExpression Update(List<string> updateFields); IUntypedSqlExpression Update(); IUntypedSqlExpression Insert(List<string> insertFields); IUntypedSqlExpression Insert(); IDbDataParameter CreateParam(string name, object value = null, ParameterDirection direction = ParameterDirection.Input, DbType? dbType = null); IUntypedSqlExpression Join<Source, Target>(Expression<Func<Source, Target, bool>> joinExpr = null); IUntypedSqlExpression Join(Type sourceType, Type targetType, Expression joinExpr = null); IUntypedSqlExpression LeftJoin<Source, Target>(Expression<Func<Source, Target, bool>> joinExpr = null); IUntypedSqlExpression LeftJoin(Type sourceType, Type targetType, Expression joinExpr = null); IUntypedSqlExpression RightJoin<Source, Target>(Expression<Func<Source, Target, bool>> joinExpr = null); IUntypedSqlExpression FullJoin<Source, Target>(Expression<Func<Source, Target, bool>> joinExpr = null); IUntypedSqlExpression CrossJoin<Source, Target>(Expression<Func<Source, Target, bool>> joinExpr = null); IUntypedSqlExpression CustomJoin(string joinString); IUntypedSqlExpression Ensure<Target>(Expression<Func<Target, bool>> predicate); IUntypedSqlExpression Ensure<Source, Target>(Expression<Func<Source, Target, bool>> predicate); IUntypedSqlExpression Where<Target>(Expression<Func<Target, bool>> predicate); IUntypedSqlExpression Where<Source, Target>(Expression<Func<Source, Target, bool>> predicate); IUntypedSqlExpression And<Target>(Expression<Func<Target, bool>> predicate); IUntypedSqlExpression And<Source, Target>(Expression<Func<Source, Target, bool>> predicate); IUntypedSqlExpression Or<Target>(Expression<Func<Target, bool>> predicate); IUntypedSqlExpression Or<Source, Target>(Expression<Func<Source, Target, bool>> predicate); string SqlTable(ModelDefinition modelDef); string SqlColumn(string columnName); string ToDeleteRowStatement(); string ToCountStatement(); IList<string> GetAllFields(); Tuple<ModelDefinition, FieldDefinition> FirstMatchingField(string fieldName); }
IUntypedSqlExpression
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp/Domain/Entities/Auditing/FullAuditedAggregateRoot.cs
{ "start": 1268, "end": 1500 }
class ____ full-audited aggregate roots. /// </summary> /// <typeparam name="TPrimaryKey">Type of the primary key of the entity</typeparam> /// <typeparam name="TUser">Type of the user</typeparam> [Serializable]
for
csharp
dotnet__machinelearning
test/Microsoft.ML.TestFramework/TestInitialization.cs
{ "start": 2870, "end": 3059 }
partial class ____ : BaseTestBaseline { protected TestDataViewBase(ITestOutputHelper helper) : base(helper) { } } public sealed
TestDataViewBase
csharp
Antaris__RazorEngine
src/source/RazorEngine.Core/Legacy/Templating/ITemplateResolver.cs
{ "start": 228, "end": 608 }
public interface ____ { #region Methods /// <summary> /// Resolves the template content with the specified name. /// </summary> /// <param name="name">The name of the template to resolve.</param> /// <returns>The template content.</returns> string Resolve(string name); #endregion } }
ITemplateResolver
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp/Application/Services/Dto/NameValueDto.cs
{ "start": 1060, "end": 1799 }
public class ____<T> : NameValue<T> { /// <summary> /// Creates a new <see cref="NameValueDto"/>. /// </summary> public NameValueDto() { } /// <summary> /// Creates a new <see cref="NameValueDto"/>. /// </summary> public NameValueDto(string name, T value) : base(name, value) { } /// <summary> /// Creates a new <see cref="NameValueDto"/>. /// </summary> /// <param name="nameValue">A <see cref="NameValue"/> object to get it's name and value</param> public NameValueDto(NameValue<T> nameValue) : this(nameValue.Name, nameValue.Value) { } } }
NameValueDto
csharp
ChilliCream__graphql-platform
src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs
{ "start": 696179, "end": 696544 }
public partial interface ____ : IOnClientVersionPublishUpdated_OnClientVersionPublishingUpdate_Deployment_Errors_Changes_Changes_6, IDescriptionChanged { } [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
IOnClientVersionPublishUpdated_OnClientVersionPublishingUpdate_Deployment_Errors_Changes_Changes_DescriptionChanged_6
csharp
npgsql__efcore.pg
test/EFCore.PG.FunctionalTests/TestUtilities/TestNpgsqlRetryingExecutionStrategy.cs
{ "start": 103, "end": 2024 }
public class ____ : NpgsqlRetryingExecutionStrategy { private const bool ErrorNumberDebugMode = false; private static readonly string[] AdditionalSqlStates = ["XX000"]; public TestNpgsqlRetryingExecutionStrategy() : base( new DbContext( new DbContextOptionsBuilder() .EnableServiceProviderCaching(false) .UseNpgsql(TestEnvironment.DefaultConnection).Options), DefaultMaxRetryCount, DefaultMaxDelay, AdditionalSqlStates) { } public TestNpgsqlRetryingExecutionStrategy(DbContext context) : base(context, DefaultMaxRetryCount, DefaultMaxDelay, AdditionalSqlStates) { } public TestNpgsqlRetryingExecutionStrategy(DbContext context, TimeSpan maxDelay) : base(context, DefaultMaxRetryCount, maxDelay, AdditionalSqlStates) { } // ReSharper disable once UnusedMember.Global public TestNpgsqlRetryingExecutionStrategy(ExecutionStrategyDependencies dependencies) : base(dependencies, DefaultMaxRetryCount, DefaultMaxDelay, AdditionalSqlStates) { } protected override bool ShouldRetryOn(Exception? exception) { if (base.ShouldRetryOn(exception)) { return true; } #pragma warning disable 162 if (ErrorNumberDebugMode && exception is PostgresException postgresException) { var message = $"Didn't retry on {postgresException.SqlState}"; throw new InvalidOperationException(message, exception); } #pragma warning restore 162 return exception is InvalidOperationException { Message: "Internal .Net Framework Data Provider error 6." }; } public new virtual TimeSpan? GetNextDelay(Exception lastException) { ExceptionsEncountered.Add(lastException); return base.GetNextDelay(lastException); } }
TestNpgsqlRetryingExecutionStrategy
csharp
dotnet__extensions
src/Generators/Microsoft.Gen.ComplianceReports/Model/ClassifiedType.cs
{ "start": 305, "end": 481 }
internal sealed class ____ { public string TypeName = string.Empty; public List<ClassifiedItem>? Members; public List<ClassifiedLogMethod>? LogMethods; }
ClassifiedType
csharp
bitwarden__server
src/Core/Billing/Extensions/InvoiceExtensions.cs
{ "start": 94, "end": 2918 }
public static class ____ { /// <summary> /// Formats invoice line items specifically for provider invoices, standardizing product descriptions /// and ensuring consistent tax representation. /// </summary> /// <param name="invoice">The Stripe invoice containing line items</param> /// <param name="subscription">The associated subscription (for future extensibility)</param> /// <returns>A list of formatted invoice item descriptions</returns> public static List<string> FormatForProvider(this Invoice invoice, Subscription subscription) { var items = new List<string>(); // Return empty list if no line items if (invoice.Lines == null) { return items; } foreach (var line in invoice.Lines.Data ?? new List<InvoiceLineItem>()) { // Skip null lines or lines without description if (line?.Description == null) { continue; } var description = line.Description; // Handle Provider Portal and Business Unit Portal service lines if (description.Contains("Provider Portal") || description.Contains("Business Unit")) { var priceMatch = Regex.Match(description, @"\(at \$[\d,]+\.?\d* / month\)"); var priceInfo = priceMatch.Success ? priceMatch.Value : ""; var standardizedDescription = $"{line.Quantity} × Manage service provider {priceInfo}"; items.Add(standardizedDescription); } // Handle tax lines else if (description.ToLower().Contains("tax")) { var priceMatch = Regex.Match(description, @"\(at \$[\d,]+\.?\d* / month\)"); var priceInfo = priceMatch.Success ? priceMatch.Value : ""; // If no price info found in description, calculate from amount if (string.IsNullOrEmpty(priceInfo) && line.Quantity > 0) { var pricePerItem = (line.Amount / 100m) / line.Quantity; priceInfo = $"(at ${pricePerItem:F2} / month)"; } var taxDescription = $"{line.Quantity} × Tax {priceInfo}"; items.Add(taxDescription); } // Handle other line items as-is else { items.Add(description); } } var tax = invoice.TotalTaxes?.Sum(invoiceTotalTax => invoiceTotalTax.Amount) ?? 0; // Add fallback tax from invoice-level tax if present and not already included if (tax > 0) { var taxAmount = tax / 100m; items.Add($"1 × Tax (at ${taxAmount:F2} / month)"); } return items; } }
InvoiceExtensions
csharp
dotnet__aspnetcore
src/Shared/Roslyn/CodeAnalysisExtensions.cs
{ "start": 332, "end": 3580 }
internal static class ____ { public static bool HasAttribute(this ITypeSymbol typeSymbol, ITypeSymbol attribute, bool inherit) => GetAttributes(typeSymbol, attribute, inherit).Any(); public static bool HasAttribute(this IMethodSymbol methodSymbol, ITypeSymbol attribute, bool inherit) => GetAttributes(methodSymbol, attribute, inherit).Any(); public static IEnumerable<AttributeData> GetAttributes(this ISymbol symbol, ITypeSymbol attribute) { foreach (var declaredAttribute in symbol.GetAttributes()) { if (declaredAttribute.AttributeClass is not null && attribute.IsAssignableFrom(declaredAttribute.AttributeClass)) { yield return declaredAttribute; } } } public static IEnumerable<AttributeData> GetAttributes(this IMethodSymbol methodSymbol, ITypeSymbol attribute, bool inherit) { Debug.Assert(methodSymbol != null); attribute = attribute ?? throw new ArgumentNullException(nameof(attribute)); IMethodSymbol? current = methodSymbol; while (current != null) { foreach (var attributeData in GetAttributes(current, attribute)) { yield return attributeData; } if (!inherit) { break; } current = current.IsOverride ? current.OverriddenMethod : null; } } public static IEnumerable<AttributeData> GetAttributes(this ITypeSymbol typeSymbol, ITypeSymbol attribute, bool inherit) { typeSymbol = typeSymbol ?? throw new ArgumentNullException(nameof(typeSymbol)); attribute = attribute ?? throw new ArgumentNullException(nameof(attribute)); foreach (var type in GetTypeHierarchy(typeSymbol)) { foreach (var attributeData in GetAttributes(type, attribute)) { yield return attributeData; } if (!inherit) { break; } } } public static bool HasAttribute(this IPropertySymbol propertySymbol, ITypeSymbol attribute, bool inherit) { propertySymbol = propertySymbol ?? throw new ArgumentNullException(nameof(propertySymbol)); attribute = attribute ?? throw new ArgumentNullException(nameof(attribute)); if (!inherit) { return HasAttribute(propertySymbol, attribute); } IPropertySymbol? current = propertySymbol; while (current != null) { if (current.HasAttribute(attribute)) { return true; } current = current.IsOverride ? current.OverriddenProperty : null; } return false; } public static bool IsAssignableFrom(this ITypeSymbol source, ITypeSymbol target) { source = source ?? throw new ArgumentNullException(nameof(source)); target = target ?? throw new ArgumentNullException(nameof(target)); if (SymbolEqualityComparer.Default.Equals(source, target)) { return true; } if (source.TypeKind == TypeKind.Interface) { foreach (var @
CodeAnalysisExtensions
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/Rendering/Composition/Transport/BatchStream.cs
{ "start": 4119, "end": 7422 }
internal class ____ : IDisposable { private readonly BatchStreamData _input; private readonly BatchStreamMemoryPool _memoryPool; private readonly BatchStreamObjectPool<object?> _objectPool; private BatchStreamSegment<object?[]?> _currentObjectSegment; private BatchStreamSegment<IntPtr> _currentDataSegment; private int _memoryOffset, _objectOffset; public BatchStreamReader(BatchStreamData input, BatchStreamMemoryPool memoryPool, BatchStreamObjectPool<object?> objectPool) { _input = input; _memoryPool = memoryPool; _objectPool = objectPool; } public unsafe T Read<T>() where T : unmanaged { var size = Unsafe.SizeOf<T>(); if (_currentDataSegment.Data == IntPtr.Zero) { if (_input.Structs.Count == 0) throw new EndOfStreamException(); _currentDataSegment = _input.Structs.Dequeue(); _memoryOffset = 0; } if (_memoryOffset + size > _currentDataSegment.ElementCount) throw new InvalidOperationException("Attempted to read more memory then left in the current segment"); var ptr = (byte*)_currentDataSegment.Data + _memoryOffset; T rv; // Unsafe.ReadUnaligned/Unsafe.WriteUnaligned are broken on arm32, // see https://github.com/dotnet/runtime/issues/80068 if (RuntimeInformation.ProcessArchitecture == Architecture.Arm) rv = UnalignedMemoryHelper.ReadUnaligned<T>(ptr); else rv = Unsafe.ReadUnaligned<T>(ptr); _memoryOffset += size; if (_memoryOffset == _currentDataSegment.ElementCount) { _memoryPool.Return(_currentDataSegment.Data); _currentDataSegment = new(); } return rv; } public T ReadObject<T>() where T : class? => (T)ReadObject()!; public object? ReadObject() { if (_currentObjectSegment.Data == null) { if (_input.Objects.Count == 0) throw new EndOfStreamException(); _currentObjectSegment = _input.Objects.Dequeue()!; _objectOffset = 0; } var rv = _currentObjectSegment.Data![_objectOffset]; _objectOffset++; if (_objectOffset == _currentObjectSegment.ElementCount) { _objectPool.Return(_currentObjectSegment.Data); _currentObjectSegment = new(); } return rv; } public bool IsObjectEof => _currentObjectSegment.Data == null && _input.Objects.Count == 0; public bool IsStructEof => _currentDataSegment.Data == IntPtr.Zero && _input.Structs.Count == 0; public void Dispose() { if (_currentDataSegment.Data != IntPtr.Zero) { _memoryPool.Return(_currentDataSegment.Data); _currentDataSegment = new(); } while (_input.Structs.Count > 0) _memoryPool.Return(_input.Structs.Dequeue().Data); if (_currentObjectSegment.Data != null) { _objectPool.Return(_currentObjectSegment.Data); _currentObjectSegment = new(); } while (_input.Objects.Count > 0) _objectPool.Return(_input.Objects.Dequeue().Data); } }
BatchStreamReader
csharp
SixLabors__ImageSharp
tests/ImageSharp.Tests/TestImages.cs
{ "start": 460, "end": 9499 }
public static class ____ { public const string Transparency = "Png/transparency.png"; public const string P1 = "Png/pl.png"; public const string Pd = "Png/pd.png"; public const string Blur = "Png/blur.png"; public const string Indexed = "Png/indexed.png"; public const string Splash = "Png/splash.png"; public const string Cross = "Png/cross.png"; public const string Powerpoint = "Png/pp.png"; public const string SplashInterlaced = "Png/splash-interlaced.png"; public const string Interlaced = "Png/interlaced.png"; public const string Palette8Bpp = "Png/palette-8bpp.png"; public const string Bpp1 = "Png/bpp1.png"; public const string Gray4Bpp = "Png/gray_4bpp.png"; public const string L16Bit = "Png/gray-16.png"; public const string GrayA8Bit = "Png/gray-alpha-8.png"; public const string GrayA8BitInterlaced = "Png/rollsroyce.png"; public const string GrayAlpha1BitInterlaced = "Png/iftbbn0g01.png"; public const string GrayAlpha2BitInterlaced = "Png/iftbbn0g02.png"; public const string Gray4BitInterlaced = "Png/iftbbn0g04.png"; public const string GrayAlpha16Bit = "Png/gray-alpha-16.png"; public const string GrayTrns16BitInterlaced = "Png/gray-16-tRNS-interlaced.png"; public const string Rgb24BppTrans = "Png/rgb-8-tRNS.png"; public const string Rgb48Bpp = "Png/rgb-48bpp.png"; public const string Rgb48BppInterlaced = "Png/rgb-48bpp-interlaced.png"; public const string Rgb48BppTrans = "Png/rgb-16-tRNS.png"; public const string Rgba64Bpp = "Png/rgb-16-alpha.png"; public const string ColorsSaturationLightness = "Png/colors-saturation-lightness.png"; public const string CalliphoraPartial = "Png/CalliphoraPartial.png"; public const string CalliphoraPartialGrayscale = "Png/CalliphoraPartialGrayscale.png"; public const string Bike = "Png/Bike.png"; public const string BikeSmall = "Png/bike-small.png"; public const string BikeGrayscale = "Png/BikeGrayscale.png"; public const string SnakeGame = "Png/SnakeGame.png"; public const string Icon = "Png/icon.png"; public const string Kaboom = "Png/kaboom.png"; public const string PDSrc = "Png/pd-source.png"; public const string PDDest = "Png/pd-dest.png"; public const string Gray1BitTrans = "Png/gray-1-trns.png"; public const string Gray2BitTrans = "Png/gray-2-tRNS.png"; public const string Gray4BitTrans = "Png/gray-4-tRNS.png"; public const string L8BitTrans = "Png/gray-8-tRNS.png"; public const string LowColorVariance = "Png/low-variance.png"; public const string PngWithMetadata = "Png/PngWithMetaData.png"; public const string InvalidTextData = "Png/InvalidTextData.png"; public const string David = "Png/david.png"; public const string TestPattern31x31 = "Png/testpattern31x31.png"; public const string TestPattern31x31HalfTransparent = "Png/testpattern31x31-halftransparent.png"; public const string XmpColorPalette = "Png/xmp-colorpalette.png"; public const string AdamHeadsHlg = "Png/adamHeadsHLG.png"; // Animated // https://philip.html5.org/tests/apng/tests.html public const string APng = "Png/animated/apng.png"; public const string SplitIDatZeroLength = "Png/animated/4-split-idat-zero-length.png"; public const string DisposeNone = "Png/animated/7-dispose-none.png"; public const string DisposeBackground = "Png/animated/8-dispose-background.png"; public const string DisposeBackgroundBeforeRegion = "Png/animated/14-dispose-background-before-region.png"; public const string DisposeBackgroundRegion = "Png/animated/15-dispose-background-region.png"; public const string DisposePreviousFirst = "Png/animated/12-dispose-prev-first.png"; public const string BlendOverMultiple = "Png/animated/21-blend-over-multiple.png"; public const string FrameOffset = "Png/animated/frame-offset.png"; public const string DefaultNotAnimated = "Png/animated/default-not-animated.png"; public const string Issue2666 = "Png/issues/Issue_2666.png"; public const string Issue2882 = "Png/issues/Issue_2882.png"; // Filtered test images from http://www.schaik.com/pngsuite/pngsuite_fil_png.html public const string Filter0 = "Png/filter0.png"; public const string SubFilter3BytesPerPixel = "Png/filter1.png"; public const string SubFilter4BytesPerPixel = "Png/SubFilter4Bpp.png"; public const string UpFilter = "Png/filter2.png"; public const string AverageFilter3BytesPerPixel = "Png/filter3.png"; public const string AverageFilter4BytesPerPixel = "Png/AverageFilter4Bpp.png"; public const string PaethFilter3BytesPerPixel = "Png/filter4.png"; public const string PaethFilter4BytesPerPixel = "Png/PaethFilter4Bpp.png"; // Paletted images also from http://www.schaik.com/pngsuite/pngsuite_fil_png.html public const string PalettedTwoColor = "Png/basn3p01.png"; public const string PalettedFourColor = "Png/basn3p02.png"; public const string PalettedSixteenColor = "Png/basn3p04.png"; public const string Paletted256Colors = "Png/basn3p08.png"; // Filter changing per scanline public const string FilterVar = "Png/filterVar.png"; public const string VimImage1 = "Png/vim16x16_1.png"; public const string VimImage2 = "Png/vim16x16_2.png"; public const string VersioningImage1 = "Png/versioning-1_1.png"; public const string VersioningImage2 = "Png/versioning-1_2.png"; public const string Banner7Adam7InterlaceMode = "Png/banner7-adam.png"; public const string Banner8Index = "Png/banner8-index.png"; public const string Ratio1x4 = "Png/ratio-1x4.png"; public const string Ratio4x1 = "Png/ratio-4x1.png"; public const string Ducky = "Png/ducky.png"; public const string Rainbow = "Png/rainbow.png"; public const string Bradley01 = "Png/Bradley01.png"; public const string Bradley02 = "Png/Bradley02.png"; // Issue 1014: https://github.com/SixLabors/ImageSharp/issues/1014 public const string Issue1014_1 = "Png/issues/Issue_1014_1.png"; public const string Issue1014_2 = "Png/issues/Issue_1014_2.png"; public const string Issue1014_3 = "Png/issues/Issue_1014_3.png"; public const string Issue1014_4 = "Png/issues/Issue_1014_4.png"; public const string Issue1014_5 = "Png/issues/Issue_1014_5.png"; public const string Issue1014_6 = "Png/issues/Issue_1014_6.png"; // Issue 1127: https://github.com/SixLabors/ImageSharp/issues/1127 public const string Issue1127 = "Png/issues/Issue_1127.png"; // Issue 1177: https://github.com/SixLabors/ImageSharp/issues/1177 public const string Issue1177_1 = "Png/issues/Issue_1177_1.png"; public const string Issue1177_2 = "Png/issues/Issue_1177_2.png"; // Issue 935: https://github.com/SixLabors/ImageSharp/issues/935 public const string Issue935 = "Png/issues/Issue_935.png"; // Issue 1765: https://github.com/SixLabors/ImageSharp/issues/1765 public const string Issue1765_Net6DeflateStreamRead = "Png/issues/Issue_1765_Net6DeflateStreamRead.png"; // Discussion 1875: https://github.com/SixLabors/ImageSharp/discussions/1875 public const string Issue1875 = "Png/raw-profile-type-exif.png"; // Issue 2217: https://github.com/SixLabors/ImageSharp/issues/2217 public const string Issue2217 = "Png/issues/Issue_2217_AdaptiveThresholdProcessor.png"; // Issue 2209: https://github.com/SixLabors/ImageSharp/issues/2209 public const string Issue2209IndexedWithTransparency = "Png/issues/Issue_2209.png"; // Issue 2259: https://github.com/SixLabors/ImageSharp/issues/2469 public const string Issue2259 = "Png/issues/Issue_2259.png"; // Issue 2259: https://github.com/SixLabors/ImageSharp/issues/2469 public const string Issue2469 = "Png/issues/issue_2469.png"; // Issue 2447: https://github.com/SixLabors/ImageSharp/issues/2447 public const string Issue2447 = "Png/issues/issue_2447.png"; // Issue 2668: https://github.com/SixLabors/ImageSharp/issues/2668 public const string Issue2668 = "Png/issues/Issue_2668.png"; // Issue 2752: https://github.com/SixLabors/ImageSharp/issues/2752 public const string Issue2752 = "Png/issues/Issue_2752.png"; // Issue 2924: https://github.com/SixLabors/ImageSharp/issues/2924 public const string Issue2924 = "Png/issues/Issue_2924.png"; // Issue 3000: https://github.com/SixLabors/ImageSharp/issues/3000 public const string Issue3000 = "Png/issues/issue_3000.png";
Png
csharp
unoplatform__uno
src/Uno.UI/Controls/BindableCheckBox.Android.cs
{ "start": 236, "end": 1126 }
public partial class ____ : AndroidX.AppCompat.Widget.AppCompatCheckBox, INotifyPropertyChanged, DependencyObject { public event PropertyChangedEventHandler PropertyChanged; public BindableCheckBox() : base(ContextHelper.Current) { InitializeBinder(); } public override bool Enabled { get { return base.Enabled; } set { if (base.Enabled != value) { base.Enabled = value; RaisePropertyChanged(); } } } public override bool Checked { get { return base.Checked; } set { if (base.Checked != value) { base.Checked = value; RaisePropertyChanged(); } } } protected void RaisePropertyChanged([CallerMemberName] string propertyName = null) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
BindableCheckBox
csharp
dotnet__orleans
src/api/Orleans.Core/Orleans.Core.cs
{ "start": 43148, "end": 43273 }
public partial interface ____ : Internal.IBackoffProvider { } [GenerateSerializer]
IFailedSessionBackoffProvider
csharp
dotnet__BenchmarkDotNet
src/BenchmarkDotNet/Characteristics/IResolver.cs
{ "start": 213, "end": 830 }
public interface ____ { bool CanResolve(Characteristic characteristic); object Resolve(CharacteristicObject obj, Characteristic characteristic); T Resolve<[DynamicallyAccessedMembers(CharacteristicObject.CharacteristicMemberTypes)] T>(CharacteristicObject obj, Characteristic<T> characteristic); object Resolve(CharacteristicObject obj, Characteristic characteristic, object defaultValue); T Resolve<[DynamicallyAccessedMembers(CharacteristicObject.CharacteristicMemberTypes)] T>(CharacteristicObject obj, Characteristic<T> characteristic, T defaultValue); } }
IResolver
csharp
atata-framework__atata
src/Atata/Logging/Sections/AtataSessionDeInitLogSection.cs
{ "start": 19, "end": 236 }
public sealed class ____ : LogSection { public AtataSessionDeInitLogSection(AtataSession session) { Message = $"Deinitialize {session}"; Level = LogLevel.Trace; } }
AtataSessionDeInitLogSection
csharp
dotnet__efcore
test/EFCore.Specification.Tests/SeedingTestBase.cs
{ "start": 2595, "end": 3010 }
public class ____(DbContextOptions options) : DbContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity<KeylessSeed>() .HasNoKey() .HasData( new KeylessSeed { Species = "Apple" }, new KeylessSeed { Species = "Orange" } ); }
KeylessSeedingContext
csharp
unoplatform__uno
src/SourceGenerators/XamlGenerationTests/TestSetup_SingleXBind.xaml.cs
{ "start": 480, "end": 649 }
partial class ____ : Page { public TestSetup_SingleXBind() { this.InitializeComponent(); } public TestSetup_SingleXBind_Data VM { get; set; }
TestSetup_SingleXBind
csharp
dotnet__orleans
test/Grains/TestGrainInterfaces/IValueTypeTestGrain.cs
{ "start": 440, "end": 574 }
public enum ____ : byte { First, Second, Third } [Serializable] [GenerateSerializer]
TestEnum
csharp
spectreconsole__spectre.console
src/Generator/Commands/AsciiCast/Samples/CalendarSamples.cs
{ "start": 63, "end": 209 }
internal abstract class ____ : BaseSample { public override (int Cols, int Rows) ConsoleSize => (base.ConsoleSize.Cols, 12); }
BaseCalendarSample
csharp
JoshClose__CsvHelper
tests/CsvHelper.Tests/Mocks/ParserMock.cs
{ "start": 504, "end": 1950 }
public class ____ : IParser, IEnumerable<string[]> { private readonly Queue<string[]?> records = new Queue<string[]?>(); private string[]? record; private int row; public CsvContext Context { get; private set; } public IParserConfiguration Configuration { get; private set; } public int Count => record?.Length ?? 0; public string[]? Record => record; public string RawRecord => string.Empty; public int Row => row; public int RawRow => row; public long ByteCount => 0; public long CharCount => 0; public string Delimiter => Configuration.Delimiter; public string this[int index] => record != null ? record[index] : string.Empty; public ParserMock() : this(new CsvConfiguration(CultureInfo.InvariantCulture)) { } public ParserMock(CsvConfiguration configuration) { Configuration = configuration; Context = new CsvContext(this); } public bool Read() { if (records.Count == 0) { return false; } row++; record = records.Dequeue(); return true; } public Task<bool> ReadAsync() { row++; record = records.Dequeue(); return Task.FromResult(records.Count > 0); } public void Dispose() { } #region Mock Methods public void Add(params string[]? record) { records.Enqueue(record); } public IEnumerator<string[]> GetEnumerator() { return records.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion Mock Methods }
ParserMock
csharp
dotnet__machinelearning
src/Microsoft.ML.Core/Utilities/BigArray.cs
{ "start": 4117, "end": 18261 }
class ____ a specified size. /// </summary> public BigArray(long size = 0) { // Verifies the preconditional invariant that BlockSize is a power of two. Contracts.Assert(BlockSize > 1 && (BlockSize & (BlockSize - 1)) == 0, "Block size is not a power of two."); Contracts.CheckParam(size >= 0, nameof(size), "Must be non-negative."); if (size == 0) { _entries = new T[0][]; return; } Contracts.CheckParam(size <= MaxSize, nameof(size), "Size of BigArray is too large."); var longBlockCount = ((size - 1) >> BlockSizeBits) + 1; Contracts.Assert(longBlockCount <= Utils.ArrayMaxSize); int blockCount = (int)longBlockCount; int lastBlockSize = (int)(((size - 1) & BlockSizeMinusOne) + 1); Contracts.Assert(blockCount > 0); Contracts.Assert(0 < lastBlockSize && lastBlockSize <= BlockSize); _length = size; _entries = new T[blockCount][]; for (int i = 0; i < blockCount - 1; i++) _entries[i] = new T[BlockSize]; _entries[blockCount - 1] = new T[lastBlockSize]; } public delegate void Visitor(long index, ref T item); /// <summary> /// Applies a <see cref="Visitor"/> method at a given <paramref name="index"/>. /// </summary> public void ApplyAt(long index, Visitor manip) { Contracts.CheckValue(manip, nameof(manip)); Contracts.CheckParam(0 <= index && index < _length, nameof(index), "Index out of range."); int bI = (int)(index >> BlockSizeBits); int idx = (int)(index & BlockSizeMinusOne); manip(index, ref _entries[bI][idx]); } /// <summary> /// Implements a more efficient way to loop over index range in [min, lim) and apply /// the specified method delegate. /// </summary> public void ApplyRange(long min, long lim, Visitor manip) { Contracts.CheckValue(manip, nameof(manip)); Contracts.CheckParam(min >= 0, nameof(min), "Specified minimum index must be non-negative."); Contracts.CheckParam(lim <= _length, nameof(lim), "Specified limit index must be no more than length of the array."); if (min >= lim) return; long max = lim - 1; int minBlockIndex = (int)(min >> BlockSizeBits); int minIndexInBlock = (int)(min & BlockSizeMinusOne); int maxBlockIndex = (int)(max >> BlockSizeBits); int maxIndexInBlock = (int)(max & BlockSizeMinusOne); long index = min; for (int bI = minBlockIndex; bI <= maxBlockIndex; bI++) { int idxMin = bI == minBlockIndex ? minIndexInBlock : 0; int idxMax = bI == maxBlockIndex ? maxIndexInBlock : BlockSizeMinusOne; var block = _entries[bI]; for (int idx = idxMin; idx <= idxMax; idx++) manip(index++, ref block[idx]); } Contracts.Assert(index == lim); } /// <summary> /// Fills the entries with index in [min, lim) with the given value. /// </summary> public void FillRange(long min, long lim, T value) { Contracts.CheckParam(min >= 0, nameof(min), "Specified minimum index must be non-negative."); Contracts.CheckParam(lim <= _length, nameof(lim), "Specified limit index must be no more than length of the array."); if (min >= lim) return; long max = lim - 1; int minBlockIndex = (int)(min >> BlockSizeBits); int minIndexInBlock = (int)(min & BlockSizeMinusOne); int maxBlockIndex = (int)(max >> BlockSizeBits); int maxIndexInBlock = (int)(max & BlockSizeMinusOne); #if DEBUG long index = min; #endif for (int bI = minBlockIndex; bI <= maxBlockIndex; bI++) { int idxMin = bI == minBlockIndex ? minIndexInBlock : 0; int idxMax = bI == maxBlockIndex ? maxIndexInBlock : BlockSizeMinusOne; var block = _entries[bI]; for (int idx = idxMin; idx <= idxMax; idx++) { block[idx] = value; #if DEBUG index++; #endif } } #if DEBUG Contracts.Assert(index == lim); #endif } /// <summary> /// Resizes the array so that its logical length equals <paramref name="newLength"/>. This method /// is more efficient than initialize another array and copy the entries because it preserves /// existing blocks. The actual capacity of the array may become larger than <paramref name="newLength"/>. /// If <paramref name="newLength"/> equals <see cref="Length"/>, then no operation is done. /// If <paramref name="newLength"/> is less than <see cref="Length"/>, the array shrinks in size /// so that both its length and its capacity equal <paramref name="newLength"/>. /// If <paramref name="newLength"/> is larger than <see cref="Length"/>, the array capacity grows /// to the smallest integral multiple of <see cref="BlockSize"/> that is larger than <paramref name="newLength"/>, /// unless <paramref name="newLength"/> is less than <see cref="BlockSize"/>, in which case the capacity /// grows to double its current capacity or <paramref name="newLength"/>, which ever is larger, /// but up to <see cref="BlockSize"/>. /// </summary> public void Resize(long newLength) { Contracts.CheckParam(newLength >= 0, nameof(newLength), "Specified new size must be non-negative."); Contracts.CheckParam(newLength <= MaxSize, nameof(newLength), "Specified new size is too large."); if (newLength == _length) return; if (newLength == 0) { // Shrink to empty. _entries = new T[0][]; _length = newLength; return; } var longBlockCount = ((newLength - 1) >> BlockSizeBits) + 1; Contracts.Assert(0 < longBlockCount && longBlockCount <= Utils.ArrayMaxSize); int newBlockCount = (int)longBlockCount; int newLastBlockLength = (int)(((newLength - 1) & BlockSizeMinusOne) + 1); Contracts.Assert(0 < newLastBlockLength && newLastBlockLength <= BlockSize); if (_length == 0) { _entries = new T[newBlockCount][]; for (int i = 0; i < newBlockCount - 1; i++) _entries[i] = new T[BlockSize]; _entries[newBlockCount - 1] = new T[newLastBlockLength]; _length = newLength; return; } int curBlockCount = _entries.GetLength(0); Contracts.Assert(curBlockCount > 0); int curLastBlockSize = Utils.Size(_entries[curBlockCount - 1]); int curLastBlockLength = (int)(((_length - 1) & BlockSizeMinusOne) + 1); Contracts.Assert(0 < curLastBlockLength && curLastBlockLength <= curLastBlockSize && curLastBlockSize <= BlockSize); if (newLength < _length) { // Shrink to a smaller array Contracts.Assert(newBlockCount < curBlockCount || (newBlockCount == curBlockCount && newLastBlockLength < curLastBlockLength)); Array.Resize(ref _entries, newBlockCount); Array.Resize(ref _entries[newBlockCount - 1], newLastBlockLength); } else if (newLength <= ((long)curBlockCount) << BlockSizeBits) { // Grow to a larger array, but with the same number of blocks. // So only need to grow the size of the last block if necessary. Contracts.Assert(curBlockCount == newBlockCount); if (newLastBlockLength > curLastBlockSize) { if (newBlockCount == 1) { Contracts.Assert(_length == curLastBlockLength); Contracts.Assert(newLength == newLastBlockLength); Contracts.Assert(_entries.Length == 1); Array.Resize(ref _entries[0], Math.Min(BlockSize, Math.Max(2 * curLastBlockSize, newLastBlockLength))); } else { // Grow the last block to full size if there are more than one blocks. Array.Resize(ref _entries[newBlockCount - 1], BlockSize); } } } else { // Need more blocks. Contracts.Assert(newBlockCount > curBlockCount); Array.Resize(ref _entries, newBlockCount); Array.Resize(ref _entries[curBlockCount - 1], BlockSize); for (int bI = curBlockCount; bI < newBlockCount; bI++) _entries[bI] = new T[BlockSize]; } _length = newLength; } /// <summary> /// Trims the capacity to logical length. /// </summary> public void TrimCapacity() { if (_length == 0) { Contracts.Assert(Utils.Size(_entries) == 0); return; } int maMax; int miLim; LongLimToMajorMaxMinorLim(_length, out maMax, out miLim); Contracts.Assert(maMax >= 0); Contracts.Assert(0 < miLim && miLim <= Utils.Size(_entries[maMax])); if (Utils.Size(_entries[maMax]) != miLim) Array.Resize(ref _entries[maMax], miLim); Array.Resize(ref _entries, maMax + 1); } /// <summary> /// Appends the elements of <paramref name="src"/> to the end. /// This method is thread safe related to calls to <see cref="M:CopyTo"/> (assuming those copy operations /// are happening over ranges already added), but concurrent calls to /// <see cref="M:AddRange"/> should not be attempted. Intended usage is that /// one thread will call this method, while multiple threads may access /// previously added ranges from <see cref="M:CopyTo"/>, concurrently with /// this method or themselves. /// </summary> public void AddRange(ReadOnlySpan<T> src) { if (src.IsEmpty) return; int maMin; int miMin; int maMax; int miLim; LongMinToMajorMinorMin(_length, out maMin, out miMin); LongLimToMajorMaxMinorLim(_length + src.Length, out maMax, out miLim); Contracts.Assert(maMin <= maMax); // Could be violated if length == 0, but we already took care of this. Utils.EnsureSize(ref _entries, maMax + 1, BlockSize); switch (maMax - maMin) { case 0: // Spans only one subarray, most common case and simplest implementation. Contracts.Assert(miLim - miMin == src.Length); Utils.EnsureSize(ref _entries[maMax], maMax >= FullAllocationBeyond ? BlockSize : miLim, BlockSize); src.CopyTo(_entries[maMax].AsSpan(miMin)); break; case 1: // Spans two subarrays. Contracts.Assert((BlockSize - miMin) + miLim == src.Length); Utils.EnsureSize(ref _entries[maMin], BlockSize, BlockSize); int firstSubArrayCapacity = BlockSize - miMin; src.Slice(0, firstSubArrayCapacity).CopyTo(_entries[maMin].AsSpan(miMin)); Contracts.Assert(_entries[maMax] == null); Utils.EnsureSize(ref _entries[maMax], maMax >= FullAllocationBeyond ? BlockSize : miLim, BlockSize); src.Slice(firstSubArrayCapacity, miLim).CopyTo(_entries[maMax]); break; default: // Spans three or more subarrays. Very rare. int miSubMin = miMin; // Copy the first segment. Utils.EnsureSize(ref _entries[maMin], BlockSize, BlockSize); int srcSoFar = BlockSize - miMin; src.Slice(0, srcSoFar).CopyTo(_entries[maMin].AsSpan(miMin)); // Copy the internal segments. for (int major = maMin + 1; major < maMax; ++major) { Contracts.Assert(_entries[major] == null); _entries[major] = new T[BlockSize]; src.Slice(srcSoFar, BlockSize).CopyTo(_entries[major]); srcSoFar += BlockSize; Contracts.Assert(srcSoFar < src.Length); } // Copy the last segment. Contracts.Assert(src.Length - srcSoFar == miLim); Contracts.Assert(_entries[maMax] == null); Utils.EnsureSize(ref _entries[maMax], maMax >= FullAllocationBeyond ? BlockSize : miLim, BlockSize); src.Slice(srcSoFar, miLim).CopyTo(_entries[maMax]); break; } _length += src.Length; } /// <summary> /// Copies the subarray starting from index <paramref name="idx"/> of length /// <paramref name="length"/> to the destination array <paramref name="dst"/>. /// Concurrent calls to this method is valid even with one single concurrent call /// to <see cref="M:AddRange"/>. /// </summary> public void CopyTo(long idx, Span<T> dst, int length) { // Accesses on the internal arrays of this
with
csharp
Cysharp__MemoryPack
tests/MemoryPack.Tests/MemoryLayoutTest.cs
{ "start": 5242, "end": 5498 }
public struct ____ { public DateTimeOffset DateTime; // short offset(2+padding) + dateTime/ulong(8) = 16 public long Timestamp; // 8 public bool IsItInSeconds; // 1(+padding7) = 8 } [StructLayout(LayoutKind.Explicit, Size = 25)]
DateTimeParamAuto
csharp
dotnet__efcore
test/EFCore.Tests/ChangeTracking/Internal/KeyPropagatorTest.cs
{ "start": 12718, "end": 12995 }
private class ____ : BaseType { public int CategoryId { get; set; } public Category Category { get; set; } public ProductDetail Detail { get; set; } public ICollection<OrderLine> OrderLines { get; } = new List<OrderLine>(); }
Product
csharp
microsoft__PowerToys
src/settings-ui/Settings.UI.Library/ColorPickerProperties.cs
{ "start": 458, "end": 5028 }
public class ____ { [CmdConfigureIgnore] public HotkeySettings DefaultActivationShortcut => new HotkeySettings(true, false, false, true, 0x43); public ColorPickerProperties() { ActivationShortcut = DefaultActivationShortcut; ChangeCursor = false; ColorHistoryLimit = 20; VisibleColorFormats = new Dictionary<string, KeyValuePair<bool, string>>(); VisibleColorFormats.Add("HEX", new KeyValuePair<bool, string>(true, ColorFormatHelper.GetDefaultFormat("HEX"))); VisibleColorFormats.Add("RGB", new KeyValuePair<bool, string>(true, ColorFormatHelper.GetDefaultFormat("RGB"))); VisibleColorFormats.Add("HSL", new KeyValuePair<bool, string>(true, ColorFormatHelper.GetDefaultFormat("HSL"))); VisibleColorFormats.Add("HSV", new KeyValuePair<bool, string>(false, ColorFormatHelper.GetDefaultFormat("HSV"))); VisibleColorFormats.Add("CMYK", new KeyValuePair<bool, string>(false, ColorFormatHelper.GetDefaultFormat("CMYK"))); VisibleColorFormats.Add("HSB", new KeyValuePair<bool, string>(false, ColorFormatHelper.GetDefaultFormat("HSB"))); VisibleColorFormats.Add("HSI", new KeyValuePair<bool, string>(false, ColorFormatHelper.GetDefaultFormat("HSI"))); VisibleColorFormats.Add("HWB", new KeyValuePair<bool, string>(false, ColorFormatHelper.GetDefaultFormat("HWB"))); VisibleColorFormats.Add("NCol", new KeyValuePair<bool, string>(false, ColorFormatHelper.GetDefaultFormat("NCol"))); VisibleColorFormats.Add("CIEXYZ", new KeyValuePair<bool, string>(false, ColorFormatHelper.GetDefaultFormat("CIEXYZ"))); VisibleColorFormats.Add("CIELAB", new KeyValuePair<bool, string>(false, ColorFormatHelper.GetDefaultFormat("CIELAB"))); VisibleColorFormats.Add("Oklab", new KeyValuePair<bool, string>(false, ColorFormatHelper.GetDefaultFormat("Oklab"))); VisibleColorFormats.Add("Oklch", new KeyValuePair<bool, string>(false, ColorFormatHelper.GetDefaultFormat("Oklch"))); VisibleColorFormats.Add("VEC4", new KeyValuePair<bool, string>(false, ColorFormatHelper.GetDefaultFormat("VEC4"))); VisibleColorFormats.Add("Decimal", new KeyValuePair<bool, string>(false, ColorFormatHelper.GetDefaultFormat("Decimal"))); VisibleColorFormats.Add("HEX Int", new KeyValuePair<bool, string>(false, ColorFormatHelper.GetDefaultFormat("HEX Int"))); ShowColorName = false; ActivationAction = ColorPickerActivationAction.OpenColorPicker; PrimaryClickAction = ColorPickerClickAction.PickColorThenEditor; MiddleClickAction = ColorPickerClickAction.PickColorAndClose; SecondaryClickAction = ColorPickerClickAction.Close; CopiedColorRepresentation = "HEX"; } public HotkeySettings ActivationShortcut { get; set; } [JsonPropertyName("changecursor")] [JsonConverter(typeof(BoolPropertyJsonConverter))] [CmdConfigureIgnoreAttribute] public bool ChangeCursor { get; set; } [JsonPropertyName("copiedcolorrepresentation")] public string CopiedColorRepresentation { get; set; } [JsonPropertyName("activationaction")] public ColorPickerActivationAction ActivationAction { get; set; } [JsonPropertyName("primaryclickaction")] public ColorPickerClickAction PrimaryClickAction { get; set; } [JsonPropertyName("middleclickaction")] public ColorPickerClickAction MiddleClickAction { get; set; } [JsonPropertyName("secondaryclickaction")] public ColorPickerClickAction SecondaryClickAction { get; set; } // Property ColorHistory is not used, the color history is saved separately in the colorHistory.json file [JsonPropertyName("colorhistory")] [CmdConfigureIgnoreAttribute] public List<string> ColorHistory { get; set; } [JsonPropertyName("colorhistorylimit")] [CmdConfigureIgnoreAttribute] public int ColorHistoryLimit { get; set; } [JsonPropertyName("visiblecolorformats")] [CmdConfigureIgnoreAttribute] public Dictionary<string, KeyValuePair<bool, string>> VisibleColorFormats { get; set; } [JsonPropertyName("showcolorname")] [JsonConverter(typeof(BoolPropertyJsonConverter))] public bool ShowColorName { get; set; } public override string ToString() => JsonSerializer.Serialize(this); } }
ColorPickerProperties
csharp
EventStore__EventStore
src/KurrentDB.Core.Tests/Services/GossipService/ClusterMultipleVersionsLoggerTests.cs
{ "start": 6410, "end": 8456 }
public class ____ : NodeGossipServiceTestFixture { protected override Message[] Given() => GivenSystemInitializedWithKnownGossipSeedSources(); protected override Message When() => // nodeTwo is sending gossip; this is an old node hence, no version info (<null> value) for any node new GossipMessage.GossipReceived(new NoopEnvelope(), new ClusterInfo(MemberInfoForVNode(_nodeTwo, _timeProvider.UtcNow, epochNumber: 1, esVersion: null), MemberInfoForVNode(_nodeThree, _timeProvider.UtcNow, epochNumber: 1, esVersion: null, isAlive: true)), _nodeTwo.HttpEndPoint); private ClusterInfo GetExpectedClusterInfo() { return new ClusterInfo( MemberInfoForVNode(_currentNode, _timeProvider.UtcNow, esVersion: VersionInfo.DefaultVersion), MemberInfoForVNode(_nodeTwo, _timeProvider.UtcNow, epochNumber: 1, esVersion: VersionInfo.OldVersion), // since currentNode has no previous information about nodeThree, its version info is Unknown as long as currentNode is concerned MemberInfoForVNode(_nodeThree, _timeProvider.UtcNow, epochNumber: 1, esVersion: VersionInfo.UnknownVersion)); } private Dictionary<EndPoint, string> GetExpectedEndPointVsVersion() { Dictionary<EndPoint, string> endpointVsVersion = new Dictionary<EndPoint, string> { { _nodeThree.HttpEndPoint, VersionInfo.UnknownVersion }, { _nodeTwo.HttpEndPoint, VersionInfo.OldVersion }, { _currentNode.HttpEndPoint, VersionInfo.DefaultVersion } }; return endpointVsVersion; } [Test] public void version_should_be_unknown() { // version of nodeThree is Unknown ExpectMessages(new GossipMessage.GossipUpdated(GetExpectedClusterInfo())); Dictionary<EndPoint, string> ipAddressVsVersion = ClusterMultipleVersionsLogger.GetIPAddressVsVersion(GetExpectedClusterInfo(), out int numDistinctKnownVersions); ipAddressVsVersion.Should().BeEquivalentTo(GetExpectedEndPointVsVersion()); Assert.AreEqual(2, numDistinctKnownVersions); } }
if_gossip_received_from_old_node_with_NO_previous_version_info
csharp
dotnet__efcore
src/EFCore.Sqlite.Core/Storage/Internal/SqliteDecimalTypeMapping.cs
{ "start": 739, "end": 3795 }
public class ____ : DecimalTypeMapping { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static new SqliteDecimalTypeMapping Default { get; } = new(SqliteTypeMappingSource.TextTypeName); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public SqliteDecimalTypeMapping(string storeType, DbType? dbType = System.Data.DbType.Decimal) : this( new RelationalTypeMappingParameters( new CoreTypeMappingParameters( typeof(decimal), jsonValueReaderWriter: SqliteJsonDecimalReaderWriter.Instance), storeType, dbType: dbType)) { } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> protected SqliteDecimalTypeMapping(RelationalTypeMappingParameters parameters) : base(parameters) { } /// <summary> /// Creates a copy of this mapping. /// </summary> /// <param name="parameters">The parameters for this mapping.</param> /// <returns>The newly created mapping.</returns> protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters) => new SqliteDecimalTypeMapping(parameters); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> protected override string SqlLiteralFormatString => "'" + base.SqlLiteralFormatString + "'"; }
SqliteDecimalTypeMapping
csharp
EventStore__EventStore
src/KurrentDB.Projections.Core.Tests/Services/Jint/when_defining_a_js_projection.cs
{ "start": 11546, "end": 12295 }
public class ____ : TestFixtureWithInterpretedProjection { protected override void Given() { _projection = @" options({ biState: true, }); fromAll().when({ $any:function(state, sharedState, event) { return state; }}); "; _state = @"{""count"": 0}"; } [Test, Category(_projectionType)] public void source_definition_is_correct() { var expected = SourceDefinitionBuilder.From(b => { b.AllEvents(); b.FromAll(); b.SetDefinesFold(); b.SetIsBiState(true); }); AssertEx.AreEqual(expected, _source); } } [TestFixture]
with_bi_state_option
csharp
dotnet__orleans
test/Orleans.CodeGenerator.Tests/snapshots/OrleansSourceGeneratorTests.TestBasicClassWithDifferentAccessModifiers.verified.cs
{ "start": 13843, "end": 14721 }
internal sealed class ____ : global::Orleans.Serialization.Configuration.TypeManifestProviderBase { protected override void ConfigureInner(global::Orleans.Serialization.Configuration.TypeManifestOptions config) { config.Serializers.Add(typeof(OrleansCodeGen.TestProject.Codec_PublicDemoData)); config.Serializers.Add(typeof(OrleansCodeGen.TestProject.Codec_InternalDemoData)); config.Copiers.Add(typeof(OrleansCodeGen.TestProject.Copier_PublicDemoData)); config.Copiers.Add(typeof(OrleansCodeGen.TestProject.Copier_InternalDemoData)); config.Activators.Add(typeof(OrleansCodeGen.TestProject.Activator_PublicDemoData)); config.Activators.Add(typeof(OrleansCodeGen.TestProject.Activator_InternalDemoData)); } } } #pragma warning restore CS1591, RS0016, RS0041
Metadata_TestProject
csharp
microsoft__PowerToys
src/modules/EnvironmentVariables/EnvironmentVariablesUILib/Converters/VariableTypeToGlyphConverter.cs
{ "start": 320, "end": 1041 }
public partial class ____ : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { var type = (VariablesSetType)value; return type switch { VariablesSetType.User => "\uE77B", VariablesSetType.System => "\uE977", VariablesSetType.Profile => "\uEDE3", VariablesSetType.Path => "\uE8AC", VariablesSetType.Duplicate => "\uE8C8", _ => throw new NotImplementedException(), }; } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } }
VariableTypeToGlyphConverter
csharp
ServiceStack__ServiceStack
ServiceStack/tests/Check.ServiceInterface/JwtServices.cs
{ "start": 382, "end": 560 }
public class ____ { public string Token { get; set; } public ResponseStatus ResponseStatus { get; set; } } [Route("/jwt-refresh")]
CreateJwtResponse
csharp
dotnet__machinelearning
src/Microsoft.ML.FastTree/SumupPerformanceCommand.cs
{ "start": 1075, "end": 14457 }
public sealed class ____ { // REVIEW: Convert to using subcomponents. [Argument(ArgumentType.AtMostOnce, HelpText = "The type of IntArray to construct", ShortName = "type", SortOrder = 0)] public IntArrayType Type = IntArrayType.Dense; [Argument(ArgumentType.AtMostOnce, HelpText = "The length of each int arrays", ShortName = "len", SortOrder = 1)] public int Length; [Argument(ArgumentType.AtMostOnce, HelpText = "The number of int arrays to create", ShortName = "c", SortOrder = 2)] public int Count; [Argument(ArgumentType.AtMostOnce, HelpText = "The number of bins to have in the int array", ShortName = "b", SortOrder = 3)] public int Bins; [Argument(ArgumentType.AtMostOnce, HelpText = "The random parameter, which will differ depending on the type of the feature", ShortName = "p", SortOrder = 4)] public double Parameter; [Argument(ArgumentType.AtMostOnce, HelpText = "The number of seconds to run sumups in each trial", ShortName = "s", SortOrder = 5)] public double Seconds = 5; [Argument(ArgumentType.AtMostOnce, HelpText = "Random seed", ShortName = "seed", SortOrder = 101)] public int? RandomSeed; [Argument(ArgumentType.AtMostOnce, HelpText = "Verbose?", ShortName = "v", Hide = true)] public bool? Verbose; // This is actually an advisory value. The implementations themselves are responsible for // determining what they consider appropriate, and the actual heuristics is a bit more // complex than just this. [Argument(ArgumentType.LastOccurrenceWins, HelpText = "Desired degree of parallelism in the data pipeline", ShortName = "n", SortOrder = 6)] public int? Parallel; } private readonly IHost _host; private readonly IntArrayType _type; private readonly int _len; private readonly int _count; private readonly int _bins; private readonly int _parallel; private readonly double _param; private readonly double _seconds; public SumupPerformanceCommand(IHostEnvironment env, Arguments args) { Contracts.CheckValue(env, nameof(env)); // Capture the environment options from args. env.CheckUserArg(!args.Parallel.HasValue || args.Parallel > 0, nameof(args.Parallel), "If defined must be positive"); _host = env.Register("FastTreeSumupPerformance", args.RandomSeed, args.Verbose); _host.CheckValue(args, nameof(args)); _host.CheckUserArg(Enum.IsDefined(typeof(IntArrayType), args.Type) && args.Type != IntArrayType.Current, nameof(args.Type), "Value not defined"); _host.CheckUserArg(args.Length >= 0, nameof(args.Length), "Must be non-negative"); _host.CheckUserArg(args.Count >= 0, nameof(args.Count), "Must be non-negative"); _host.CheckUserArg(args.Bins > 0, nameof(args.Bins), "Must be positive"); _host.CheckUserArg(args.Seconds > 0, nameof(args.Seconds), "Must be positive"); _type = args.Type; _len = args.Length; _count = args.Count; _bins = args.Bins; _parallel = args.Parallel ?? Environment.ProcessorCount; _param = args.Parameter; _seconds = args.Seconds; } private IEnumerable<int> CreateDense(IChannel ch, Random rgen) { for (int i = 0; i < _len; ++i) yield return rgen.Next(_bins); } private IEnumerable<int> CreateSparse(IChannel ch, Random rgen) { ch.CheckUserArg(0 <= _param && _param < 1, nameof(Arguments.Parameter), "For sparse arrays"); // The parameter is the level of sparsity. Use the geometric distribution to determine the number of // Geometric distribution (with 0 support) would be Math. double denom = Math.Log(1 - _param); if (double.IsNegativeInfinity(denom)) { // The parameter is so high, it's effectively dense. foreach (int v in CreateDense(ch, rgen)) yield return 0; yield break; } if (denom == 0) { // The parameter must have been so small that we effectively will never have an "on" entry. for (int i = 0; i < _len; ++i) yield return 0; yield break; } ch.Assert(FloatUtils.IsFinite(denom) && denom < 0); int remaining = _len; while (remaining > 0) { // A value being sparse or not we view as a Bernoulli trial, so, we can more efficiently // model the number of sparse values as being a geometric distribution. This reduces the // number of calls to the random number generator considerable vs. the naive sampling. double r = 1 - rgen.NextDouble(); // Has support in [0,1). We subtract 1-r to make support in (0,1]. int numZeros = (int)Math.Min(Math.Floor(Math.Log(r) / denom), remaining); for (int i = 0; i < numZeros; ++i) yield return 0; if ((remaining -= numZeros) > 0) { --remaining; yield return rgen.Next(_bins); } } ch.Assert(remaining == 0); } private IntArray[] CreateRandomIntArrays(IChannel ch) { IntArray[] arrays = new IntArray[_count]; using (var pch = _host.StartProgressChannel("Create IntArrays")) { int created = 0; pch.SetHeader(new ProgressHeader("arrays"), e => e.SetProgress(0, created, arrays.Length)); IntArrayBits bits = IntArray.NumBitsNeeded(_bins); ch.Info("Bits per item is {0}", bits); int salt = _host.Rand.Next(); Func<IChannel, Random, IEnumerable<int>> createIntArray; switch (_type) { case IntArrayType.Dense: createIntArray = CreateDense; break; case IntArrayType.Sparse: createIntArray = CreateSparse; if (_param == 1) createIntArray = CreateDense; break; default: throw _host.ExceptNotImpl("Haven't yet wrote a random generator appropriate for {0}", _type); } ParallelEnumerable.Range(0, arrays.Length).ForAll(i => { Random r = new Random(salt + i); arrays[i] = IntArray.New(_len, _type, bits, createIntArray(ch, r)); created++; }); return arrays; } } private IEnumerator<double> Geometric(double p, Random rgen) { double denom = Math.Log(1 - p); if (double.IsNegativeInfinity(denom)) { // The parameter is so high, it's effectively dense. while (true) yield return 0; } else if (denom == 0) { // The parameter must have been so small that we effectively will never have an "on" entry. while (true) yield return double.PositiveInfinity; } else { while (true) { double r = 1 - rgen.NextDouble(); // Has support in [0,1). We subtract 1-r to make support in (0,1]. yield return Math.Floor(Math.Log(r) / denom); } } } private IEnumerable<int> CreateDocIndicesCore(double sparsity, Random rgen) { _host.Assert(0 < sparsity && sparsity < 1); int remaining = _len; IEnumerator<double> g = Geometric(sparsity, rgen); int currDoc = -1; while (remaining > 0) { g.MoveNext(); double skippedDocs = g.Current + 1; // Number docs till the next good one. if (skippedDocs >= remaining) yield break; int sd = (int)skippedDocs; remaining -= sd; yield return (currDoc += sd); } } private IEnumerable<int> CreateDocIndices(double sparsity, Random rgen) { _host.Assert(0 <= sparsity && sparsity <= 1); if (sparsity == 1) return Enumerable.Range(0, _len); if (sparsity == 0) return Enumerable.Empty<int>(); return CreateDocIndicesCore(sparsity, rgen); } private void InitSumupInputData(SumupInputData data, double sparsity, Random rgen) { int count = 0; foreach (int d in CreateDocIndices(sparsity, rgen)) data.DocIndices[count++] = d; _host.Assert(Utils.IsIncreasing(0, data.DocIndices, count, _len)); data.TotalCount = count; FloatType osum = 0; if (data.Weights == null) { for (int i = 0; i < count; ++i) osum += (data.Outputs[i] = (FloatType)(2 * rgen.NextDouble() - 1)); data.SumWeights = count; } else { FloatType wsum = 0; for (int i = 0; i < count; ++i) { osum += (data.Outputs[i] = (FloatType)(2 * rgen.NextDouble() - 1)); wsum += (data.Weights[i] = (FloatType)(2 * rgen.NextDouble() - 1)); } data.SumWeights = wsum; } data.SumTargets = osum; } public void Run() { using (var ch = _host.Start("Run")) { IntArray[] arrays = CreateRandomIntArrays(ch); FeatureHistogram[] histograms = arrays.Select(bins => new FeatureHistogram(bins, _bins, false)).ToArray(arrays.Length); long bytes = arrays.Sum(i => (long)i.SizeInBytes()); ch.Info("Created {0} int arrays taking {1} bytes", arrays.Length, bytes); // Objects for the pool. ch.Info("Parallelism = {0}", _parallel); AutoResetEvent[] events = Utils.BuildArray(_parallel, i => new AutoResetEvent(false)); AutoResetEvent[] mainEvents = Utils.BuildArray(_parallel, i => new AutoResetEvent(false)); SumupInputData data = new SumupInputData(_len, 0, 0, new FloatType[_len], null, new int[_len]); Thread[] threadPool = new Thread[_parallel]; Stopwatch sw = new Stopwatch(); long ticksPerCycle = (long)(Stopwatch.Frequency * _seconds); double[] partitionProportion = { 1, 1, 0.5, 1e-1, 1e-2, 1e-3, 1e-4 }; long completed = 0; for (int t = 0; t < threadPool.Length; ++t) { Thread thread = threadPool[t] = Utils.RunOnForegroundThread((object io) => { int w = (int)io; AutoResetEvent ev = events[w]; AutoResetEvent mev = mainEvents[w]; for (int s = 0; s < partitionProportion.Length; s++) { ev.WaitOne(); long localCompleted = 0; for (int f = w; ; f = f + threadPool.Length < arrays.Length ? f + threadPool.Length : w) { // This should repeat till done. arrays[f].Sumup(data, histograms[f]); if (sw.ElapsedTicks > ticksPerCycle) break; Interlocked.Increment(ref completed); ++localCompleted; } mev.Set(); } }); thread.Start(t); } foreach (double partition in partitionProportion) { InitSumupInputData(data, partition, _host.Rand); completed = 0; sw.Restart(); foreach (var e in events) e.Set(); foreach (var e in mainEvents) e.WaitOne(); double ticksPerDoc = (double)ticksPerCycle / (completed * data.TotalCount); double nsPerDoc = ticksPerDoc * 1e9 / Stopwatch.Frequency; ch.Info("Partition {0} ({1} of {2}), completed {3} ({4:0.000} ns per doc)", partition, data.TotalCount, _len, completed, nsPerDoc); } } } } }
Arguments
csharp
dotnet__maui
src/Core/src/Handlers/HybridWebView/HybridWebViewHandler.Windows.cs
{ "start": 371, "end": 9291 }
public partial class ____ : ViewHandler<IHybridWebView, WebView2> { private readonly HybridWebView2Proxy _proxy = new(); protected override WebView2 CreatePlatformView() { return new MauiHybridWebView(this); } protected override void ConnectHandler(WebView2 platformView) { _proxy.Connect(this, platformView); base.ConnectHandler(platformView); if (platformView.IsLoaded) { OnLoaded(); } else { platformView.Loaded += OnWebViewLoaded; } PlatformView.DispatcherQueue.TryEnqueue(async () => { var isWebViewInitialized = await (PlatformView as MauiHybridWebView)!.WebViewReadyTask!; if (isWebViewInitialized) { PlatformView.Source = new Uri(new Uri(AppOriginUri, "/").ToString()); } }); } void OnWebViewLoaded(object sender, RoutedEventArgs e) { OnLoaded(); } void OnLoaded() { var window = MauiContext!.GetPlatformWindow(); _proxy.Connect(window); } void Disconnect(WebView2 platformView) { platformView.Loaded -= OnWebViewLoaded; _proxy.Disconnect(platformView); if (platformView.CoreWebView2 is not null) { platformView.Close(); } } protected override void DisconnectHandler(WebView2 platformView) { Disconnect(platformView); base.DisconnectHandler(platformView); } internal static void EvaluateJavaScript(IHybridWebViewHandler handler, IHybridWebView hybridWebView, EvaluateJavaScriptAsyncRequest request) { if (handler.PlatformView is not MauiHybridWebView hybridPlatformWebView) { return; } hybridPlatformWebView.RunAfterInitialize(() => hybridPlatformWebView.EvaluateJavaScript(request)); } public static void MapSendRawMessage(IHybridWebViewHandler handler, IHybridWebView hybridWebView, object? arg) { if (arg is not HybridWebViewRawMessage hybridWebViewRawMessage || handler.PlatformView is not MauiHybridWebView hybridPlatformWebView) { return; } hybridPlatformWebView.RunAfterInitialize(() => hybridPlatformWebView.SendRawMessage(hybridWebViewRawMessage.Message ?? "")); } private void OnWebMessageReceived(WebView2 sender, CoreWebView2WebMessageReceivedEventArgs args) { MessageReceived(args.TryGetWebMessageAsString()); } internal static void MapFlowDirection(IHybridWebViewHandler handler, IHybridWebView hybridWebView) { // Explicitly do nothing here to override the base ViewHandler.MapFlowDirection behavior // This prevents the WebView2.FlowDirection from being set, avoiding content mirroring } private async void OnWebResourceRequested(CoreWebView2 sender, CoreWebView2WebResourceRequestedEventArgs eventArgs) { var url = eventArgs.Request.Uri; var logger = MauiContext?.CreateLogger<HybridWebViewHandler>(); logger?.LogDebug("Intercepting request for {Url}.", url); // 1. First check if the app wants to modify or override the request. if (WebRequestInterceptingWebView.TryInterceptResponseStream(this, sender, eventArgs, url, logger)) { return; } // 2. If this is an app request, then assume the request is for a local resource. if (new Uri(url) is Uri uri && AppOriginUri.IsBaseOf(uri)) { logger?.LogDebug("Request for {Url} will be handled by .NET MAUI.", url); // 2.a. Get a deferral object so that WebView2 knows there's some async stuff going on. We call Complete() at the end of this method. using var deferral = eventArgs.GetDeferral(); // 2.b. Check if the request is for a local resource var (stream, contentType, statusCode, reason) = await GetResponseStreamAsync(url, eventArgs.Request, logger); // 2.c. Create the response header var headers = ""; if (stream?.Size is { } contentLength && contentLength > 0) { headers += $"Content-Length: {contentLength}{Environment.NewLine}"; } if (contentType is not null) { headers += $"Content-Type: {contentType}{Environment.NewLine}"; } // 2.d. If something was found, return the content eventArgs.Response = sender.Environment!.CreateWebResourceResponse( Content: stream, StatusCode: statusCode, ReasonPhrase: reason, Headers: headers); // 2.e. Notify WebView2 that the deferred (async) operation is complete and we set a response. deferral.Complete(); return; } // 3. If the request is not handled by the app nor is it a local source, then we let the WebView2 // handle the request as it would normally do. This means that it will try to load the resource // from the internet or from the local cache. logger?.LogDebug("Request for {Url} was not handled.", url); } private async Task<(IRandomAccessStream? Stream, string? ContentType, int StatusCode, string Reason)> GetResponseStreamAsync(string url, CoreWebView2WebResourceRequest request, ILogger? logger) { var requestUri = WebUtils.RemovePossibleQueryString(url); if (new Uri(requestUri) is Uri uri && AppOriginUri.IsBaseOf(uri)) { var relativePath = AppOriginUri.MakeRelativeUri(uri).ToString(); // 1.a. Try the special "_framework/hybridwebview.js" path if (relativePath == HybridWebViewDotJsPath) { logger?.LogDebug("Request for {Url} will return the hybrid web view script.", url); var jsStream = GetEmbeddedStream(HybridWebViewDotJsPath); if (jsStream is not null) { var ras = await CopyContentToRandomAccessStreamAsync(jsStream); return (Stream: ras, ContentType: "application/javascript", StatusCode: 200, Reason: "OK"); } } // 1.b. Try special InvokeDotNet path if (relativePath == InvokeDotNetPath) { logger?.LogDebug("Request for {Url} will be handled by the .NET method invoker.", url); // Only accept requests that have the expected headers if (!HasExpectedHeaders(request.Headers)) { logger?.LogError("InvokeDotNet endpoint missing or invalid request header"); return (Stream: null, ContentType: null, StatusCode: 400, Reason: "Bad Request"); } // Only accept POST requests if (!string.Equals(request.Method, "POST", StringComparison.OrdinalIgnoreCase)) { logger?.LogError("InvokeDotNet endpoint only accepts POST requests. Received: {Method}", request.Method); return (Stream: null, ContentType: null, StatusCode: 405, Reason: "Method Not Allowed"); } // Read the request body Stream requestBody; if (request.Content is { } bodyStream && bodyStream.Size > 0) { requestBody = bodyStream.AsStreamForRead(); } else { logger?.LogError("InvokeDotNet request body is empty"); return (Stream: null, ContentType: null, StatusCode: 400, Reason: "Bad Request"); } // Invoke the method var contentBytes = await InvokeDotNetAsync(streamBody: requestBody); if (contentBytes is not null) { var ras = await CopyContentToRandomAccessStreamAsync(contentBytes.AsBuffer()); return (Stream: ras, ContentType: "application/json", StatusCode: 200, Reason: "OK"); } } string contentType; // 2. If nothing found yet, try to get static content from the asset path if (string.IsNullOrEmpty(relativePath)) { relativePath = VirtualView.DefaultFile; contentType = "text/html"; } else { if (!ContentTypeProvider.TryGetContentType(relativePath, out contentType!)) { contentType = "text/plain"; logger?.LogWarning("Could not determine content type for '{relativePath}'", relativePath); } } var assetPath = Path.Combine(VirtualView.HybridRoot!, relativePath!); using var contentStream = await GetAssetStreamAsync(assetPath); if (contentStream is not null) { // 3.a. If something was found, return the content logger?.LogDebug("Request for {Url} will return an app package file.", url); var ras = await CopyContentToRandomAccessStreamAsync(contentStream); return (Stream: ras, ContentType: contentType, StatusCode: 200, Reason: "OK"); } } // 3.b. Otherwise, return a 404 logger?.LogDebug("Request for {Url} could not be fulfilled.", url); return (Stream: null, ContentType: null, StatusCode: 404, Reason: "Not Found"); } static async Task<IRandomAccessStream> CopyContentToRandomAccessStreamAsync(Stream content) { var ras = new InMemoryRandomAccessStream(); var stream = ras.AsStreamForWrite(); // do not dispose as this stream IS the IMRAS await content.CopyToAsync(stream); await stream.FlushAsync(); ras.Seek(0); return ras; } static async Task<IRandomAccessStream> CopyContentToRandomAccessStreamAsync(IBuffer content) { var ras = new InMemoryRandomAccessStream(); await ras.WriteAsync(content); await ras.FlushAsync(); ras.Seek(0); return ras; } [RequiresUnreferencedCode(DynamicFeatures)] #if !NETSTANDARD [RequiresDynamicCode(DynamicFeatures)] #endif
HybridWebViewHandler
csharp
dotnet__aspnetcore
src/Identity/Core/src/Passkeys/PublicKeyCredentialDescriptor.cs
{ "start": 385, "end": 933 }
internal sealed class ____ { /// <summary> /// Gets or sets the type of the public key credential. /// </summary> public required string Type { get; init; } /// <summary> /// Gets or sets the identifier of the public key credential. /// </summary> public required BufferSource Id { get; init; } /// <summary> /// Gets or sets hints as to how the client might communicate with the authenticator. /// </summary> public IReadOnlyList<string> Transports { get; init; } = []; }
PublicKeyCredentialDescriptor
csharp
StackExchange__StackExchange.Redis
src/StackExchange.Redis/RedisDatabase.cs
{ "start": 257075, "end": 277523 }
private sealed class ____ : Message.CommandKeyBase // XREAD with a single stream. Example: XREAD COUNT 2 STREAMS mystream 0-0 { private readonly RedisValue afterId; private readonly int? count; private readonly int argCount; public SingleStreamReadCommandMessage(int db, CommandFlags flags, RedisKey key, RedisValue afterId, int? count) : base(db, flags, RedisCommand.XREAD, key) { if (count.HasValue && count <= 0) { throw new ArgumentOutOfRangeException(nameof(count), "count must be greater than 0."); } afterId.AssertNotNull(); this.afterId = afterId; this.count = count; argCount = count.HasValue ? 5 : 3; } protected override void WriteImpl(PhysicalConnection physical) { physical.WriteHeader(Command, argCount); if (count.HasValue) { physical.WriteBulkString("COUNT"u8); physical.WriteBulkString(count.Value); } physical.WriteBulkString("STREAMS"u8); physical.Write(Key); physical.WriteBulkString(afterId); } public override int ArgCount => argCount; } private Message GetStreamTrimMessage(bool maxLen, RedisKey key, RedisValue threshold, bool useApproximateMaxLength, long? limit, StreamTrimMode mode, CommandFlags flags) { if (limit.HasValue && limit.GetValueOrDefault() <= 0) { throw new ArgumentOutOfRangeException(nameof(limit), "limit must be greater than 0 when specified."); } if (limit is null && !useApproximateMaxLength && mode == StreamTrimMode.KeepReferences) { // avoid array alloc in simple case return Message.Create(Database, flags, RedisCommand.XTRIM, key, maxLen ? StreamConstants.MaxLen : StreamConstants.MinId, threshold); } var values = new RedisValue[2 + (useApproximateMaxLength ? 1 : 0) + (limit.HasValue ? 2 : 0) + (mode == StreamTrimMode.KeepReferences ? 0 : 1)]; var offset = 0; values[offset++] = maxLen ? StreamConstants.MaxLen : StreamConstants.MinId; if (useApproximateMaxLength) { values[offset++] = StreamConstants.ApproximateMaxLen; } values[offset++] = threshold; if (limit.HasValue) { values[offset++] = RedisLiterals.LIMIT; values[offset++] = limit.GetValueOrDefault(); } if (mode != StreamTrimMode.KeepReferences) // omit when not needed, for back-compat { values[offset++] = StreamConstants.GetMode(mode); } Debug.Assert(offset == values.Length); return Message.Create( Database, flags, RedisCommand.XTRIM, key, values); } private Message? GetStringBitOperationMessage(Bitwise operation, RedisKey destination, RedisKey[] keys, CommandFlags flags) { if (keys == null) throw new ArgumentNullException(nameof(keys)); if (keys.Length == 0) return null; // these ones are too bespoke to warrant custom Message implementations var serverSelectionStrategy = multiplexer.ServerSelectionStrategy; int slot = serverSelectionStrategy.HashSlot(destination); var values = new RedisValue[keys.Length + 2]; values[0] = RedisLiterals.Get(operation); values[1] = destination.AsRedisValue(); for (int i = 0; i < keys.Length; i++) { values[i + 2] = keys[i].AsRedisValue(); slot = serverSelectionStrategy.CombineSlot(slot, keys[i]); } return Message.CreateInSlot(Database, slot, flags, RedisCommand.BITOP, values); } private Message GetStringBitOperationMessage(Bitwise operation, RedisKey destination, RedisKey first, RedisKey second, CommandFlags flags) { // these ones are too bespoke to warrant custom Message implementations var op = RedisLiterals.Get(operation); var serverSelectionStrategy = multiplexer.ServerSelectionStrategy; int slot = serverSelectionStrategy.HashSlot(destination); slot = serverSelectionStrategy.CombineSlot(slot, first); if (second.IsNull || operation == Bitwise.Not) { // unary return Message.CreateInSlot(Database, slot, flags, RedisCommand.BITOP, new[] { op, destination.AsRedisValue(), first.AsRedisValue() }); } // binary slot = serverSelectionStrategy.CombineSlot(slot, second); return Message.CreateInSlot(Database, slot, flags, RedisCommand.BITOP, new[] { op, destination.AsRedisValue(), first.AsRedisValue(), second.AsRedisValue() }); } private Message GetStringGetExMessage(in RedisKey key, Expiration expiry, CommandFlags flags = CommandFlags.None) { return expiry.TokenCount switch { 0 => Message.Create(Database, flags, RedisCommand.GETEX, key), 1 => Message.Create(Database, flags, RedisCommand.GETEX, key, expiry.Operand), _ => Message.Create(Database, flags, RedisCommand.GETEX, key, expiry.Operand, expiry.Value), }; } private Message GetStringGetWithExpiryMessage(RedisKey key, CommandFlags flags, out ResultProcessor<RedisValueWithExpiry> processor, out ServerEndPoint? server) { if (this is IBatch) { throw new NotSupportedException("This operation is not possible inside a transaction or batch; please issue separate GetString and KeyTimeToLive requests"); } var features = GetFeatures(key, flags, RedisCommand.PTTL, out server); processor = StringGetWithExpiryProcessor.Default; if (server != null && features.MillisecondExpiry && multiplexer.CommandMap.IsAvailable(RedisCommand.PTTL)) { return new StringGetWithExpiryMessage(Database, flags, RedisCommand.PTTL, key); } // if we use TTL, it doesn't matter which server server = null; return new StringGetWithExpiryMessage(Database, flags, RedisCommand.TTL, key); } private Message? GetStringSetMessage(KeyValuePair<RedisKey, RedisValue>[] values, When when, Expiration expiry, CommandFlags flags) { if (values == null) throw new ArgumentNullException(nameof(values)); switch (values.Length) { case 0: return null; case 1: return GetStringSetMessage(values[0].Key, values[0].Value, expiry, when, flags); default: // assume MSETEX in the general case, but look for scenarios where we can use the simpler // MSET/MSETNX commands (which have wider applicability in terms of server versions) // (note that when/expiry is ignored when not MSETEX; no need to explicitly wipe) WhenAlwaysOrExistsOrNotExists(when); var cmd = when switch { When.Always when expiry.IsNone => RedisCommand.MSET, When.NotExists when expiry.IsNoneOrKeepTtl => RedisCommand.MSETNX, // "keepttl" with "not exists" is the same as "no expiry" _ => RedisCommand.MSETEX, }; return Message.Create(Database, flags, cmd, values, expiry, when); } } private Message GetStringSetMessage( RedisKey key, RedisValue value, Expiration expiry, When when = When.Always, CommandFlags flags = CommandFlags.None) { WhenAlwaysOrExistsOrNotExists(when); static Message ThrowWhen() => throw new ArgumentOutOfRangeException(nameof(when)); if (value.IsNull) return Message.Create(Database, flags, RedisCommand.DEL, key); if (expiry.IsPersist) throw new NotSupportedException("SET+PERSIST is not supported"); // we don't expect to get here ever if (expiry.IsNone) { return when switch { When.Always => Message.Create(Database, flags, RedisCommand.SET, key, value), When.NotExists => Message.Create(Database, flags, RedisCommand.SETNX, key, value), When.Exists => Message.Create(Database, flags, RedisCommand.SET, key, value, RedisLiterals.XX), _ => ThrowWhen(), }; } if (expiry.IsKeepTtl) { return when switch { When.Always => Message.Create(Database, flags, RedisCommand.SET, key, value, RedisLiterals.KEEPTTL), When.NotExists => Message.Create(Database, flags, RedisCommand.SETNX, key, value), // (there would be no existing TTL to keep) When.Exists => Message.Create(Database, flags, RedisCommand.SET, key, value, RedisLiterals.XX, RedisLiterals.KEEPTTL), _ => ThrowWhen(), }; } if (when is When.Always & expiry.IsRelative) { // special case to SETEX/PSETEX return expiry.IsSeconds ? Message.Create(Database, flags, RedisCommand.SETEX, key, expiry.Value, value) : Message.Create(Database, flags, RedisCommand.PSETEX, key, expiry.Value, value); } // use SET with EX/PX/EXAT/PXAT and possibly XX/NX var expiryOperand = expiry.GetOperand(out var expiryValue); return when switch { When.Always => Message.Create(Database, flags, RedisCommand.SET, key, value, expiryOperand, expiryValue), When.Exists => Message.Create(Database, flags, RedisCommand.SET, key, value, expiryOperand, expiryValue, RedisLiterals.XX), When.NotExists => Message.Create(Database, flags, RedisCommand.SET, key, value, expiryOperand, expiryValue, RedisLiterals.NX), _ => throw new ArgumentOutOfRangeException(nameof(when)), }; } private Message GetStringSetAndGetMessage( RedisKey key, RedisValue value, TimeSpan? expiry = null, bool keepTtl = false, When when = When.Always, CommandFlags flags = CommandFlags.None) { WhenAlwaysOrExistsOrNotExists(when); if (value.IsNull) return Message.Create(Database, flags, RedisCommand.GETDEL, key); if (expiry == null || expiry.Value == TimeSpan.MaxValue) { // no expiry return when switch { When.Always when !keepTtl => Message.Create(Database, flags, RedisCommand.SET, key, value, RedisLiterals.GET), When.Always when keepTtl => Message.Create(Database, flags, RedisCommand.SET, key, value, RedisLiterals.GET, RedisLiterals.KEEPTTL), When.Exists when !keepTtl => Message.Create(Database, flags, RedisCommand.SET, key, value, RedisLiterals.XX, RedisLiterals.GET), When.Exists when keepTtl => Message.Create(Database, flags, RedisCommand.SET, key, value, RedisLiterals.XX, RedisLiterals.GET, RedisLiterals.KEEPTTL), When.NotExists when !keepTtl => Message.Create(Database, flags, RedisCommand.SET, key, value, RedisLiterals.NX, RedisLiterals.GET), When.NotExists when keepTtl => Message.Create(Database, flags, RedisCommand.SET, key, value, RedisLiterals.NX, RedisLiterals.GET, RedisLiterals.KEEPTTL), _ => throw new ArgumentOutOfRangeException(nameof(when)), }; } long milliseconds = expiry.Value.Ticks / TimeSpan.TicksPerMillisecond; if ((milliseconds % 1000) == 0) { // a nice round number of seconds long seconds = milliseconds / 1000; return when switch { When.Always => Message.Create(Database, flags, RedisCommand.SET, key, value, RedisLiterals.EX, seconds, RedisLiterals.GET), When.Exists => Message.Create(Database, flags, RedisCommand.SET, key, value, RedisLiterals.EX, seconds, RedisLiterals.XX, RedisLiterals.GET), When.NotExists => Message.Create(Database, flags, RedisCommand.SET, key, value, RedisLiterals.EX, seconds, RedisLiterals.NX, RedisLiterals.GET), _ => throw new ArgumentOutOfRangeException(nameof(when)), }; } return when switch { When.Always => Message.Create(Database, flags, RedisCommand.SET, key, value, RedisLiterals.PX, milliseconds, RedisLiterals.GET), When.Exists => Message.Create(Database, flags, RedisCommand.SET, key, value, RedisLiterals.PX, milliseconds, RedisLiterals.XX, RedisLiterals.GET), When.NotExists => Message.Create(Database, flags, RedisCommand.SET, key, value, RedisLiterals.PX, milliseconds, RedisLiterals.NX, RedisLiterals.GET), _ => throw new ArgumentOutOfRangeException(nameof(when)), }; } private Message? IncrMessage(RedisKey key, long value, CommandFlags flags) => value switch { 0 => ((flags & CommandFlags.FireAndForget) != 0) ? null : Message.Create(Database, flags, RedisCommand.INCRBY, key, value), 1 => Message.Create(Database, flags, RedisCommand.INCR, key), -1 => Message.Create(Database, flags, RedisCommand.DECR, key), > 0 => Message.Create(Database, flags, RedisCommand.INCRBY, key, value), _ => Message.Create(Database, flags, RedisCommand.DECRBY, key, -value), }; private static RedisCommand SetOperationCommand(SetOperation operation, bool store) => operation switch { SetOperation.Difference => store ? RedisCommand.SDIFFSTORE : RedisCommand.SDIFF, SetOperation.Intersect => store ? RedisCommand.SINTERSTORE : RedisCommand.SINTER, SetOperation.Union => store ? RedisCommand.SUNIONSTORE : RedisCommand.SUNION, _ => throw new ArgumentOutOfRangeException(nameof(operation)), }; private CursorEnumerable<T>? TryScan<T>(RedisKey key, RedisValue pattern, int pageSize, long cursor, int pageOffset, CommandFlags flags, RedisCommand command, ResultProcessor<ScanEnumerable<T>.ScanResult> processor, out ServerEndPoint? server, bool noValues = false) { server = null; if (pageSize <= 0) throw new ArgumentOutOfRangeException(nameof(pageSize)); if (!multiplexer.CommandMap.IsAvailable(command)) return null; var features = GetFeatures(key, flags, RedisCommand.SCAN, out server); if (!features.Scan) return null; if (CursorUtils.IsNil(pattern)) pattern = (byte[]?)null; return new ScanEnumerable<T>(this, server, key, pattern, pageSize, cursor, pageOffset, flags, command, processor, noValues); } private Message GetLexMessage(RedisCommand command, RedisKey key, RedisValue min, RedisValue max, Exclude exclude, long skip, long take, CommandFlags flags, Order order) { RedisValue start = GetLexRange(min, exclude, true, order), stop = GetLexRange(max, exclude, false, order); if (skip == 0 && take == -1) return Message.Create(Database, flags, command, key, start, stop); return Message.Create(Database, flags, command, key, new[] { start, stop, RedisLiterals.LIMIT, skip, take }); } public long SortedSetLengthByValue(RedisKey key, RedisValue min, RedisValue max, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) { var msg = GetLexMessage(RedisCommand.ZLEXCOUNT, key, min, max, exclude, 0, -1, flags, Order.Ascending); return ExecuteSync(msg, ResultProcessor.Int64); } public RedisValue[] SortedSetRangeByValue(RedisKey key, RedisValue min, RedisValue max, Exclude exclude, long skip, long take, CommandFlags flags) => SortedSetRangeByValue(key, min, max, exclude, Order.Ascending, skip, take, flags); private static void ReverseLimits(Order order, ref Exclude exclude, ref RedisValue start, ref RedisValue stop) { bool reverseLimits = (order == Order.Ascending) == (stop != default && start.CompareTo(stop) > 0); if (reverseLimits) { var tmp = start; start = stop; stop = tmp; switch (exclude) { case Exclude.Start: exclude = Exclude.Stop; break; case Exclude.Stop: exclude = Exclude.Start; break; } } } public RedisValue[] SortedSetRangeByValue( RedisKey key, RedisValue min = default, RedisValue max = default, Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None) { ReverseLimits(order, ref exclude, ref min, ref max); var msg = GetLexMessage(order == Order.Ascending ? RedisCommand.ZRANGEBYLEX : RedisCommand.ZREVRANGEBYLEX, key, min, max, exclude, skip, take, flags, order); return ExecuteSync(msg, ResultProcessor.RedisValueArray, defaultValue: Array.Empty<RedisValue>()); } public long SortedSetRemoveRangeByValue(RedisKey key, RedisValue min, RedisValue max, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) { var msg = GetLexMessage(RedisCommand.ZREMRANGEBYLEX, key, min, max, exclude, 0, -1, flags, Order.Ascending); return ExecuteSync(msg, ResultProcessor.Int64); } public Task<long> SortedSetLengthByValueAsync(RedisKey key, RedisValue min, RedisValue max, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) { var msg = GetLexMessage(RedisCommand.ZLEXCOUNT, key, min, max, exclude, 0, -1, flags, Order.Ascending); return ExecuteAsync(msg, ResultProcessor.Int64); } public Task<RedisValue[]> SortedSetRangeByValueAsync(RedisKey key, RedisValue min, RedisValue max, Exclude exclude, long skip, long take, CommandFlags flags) => SortedSetRangeByValueAsync(key, min, max, exclude, Order.Ascending, skip, take, flags); public Task<RedisValue[]> SortedSetRangeByValueAsync( RedisKey key, RedisValue min = default, RedisValue max = default, Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0, long take = -1, CommandFlags flags = CommandFlags.None) { ReverseLimits(order, ref exclude, ref min, ref max); var msg = GetLexMessage(order == Order.Ascending ? RedisCommand.ZRANGEBYLEX : RedisCommand.ZREVRANGEBYLEX, key, min, max, exclude, skip, take, flags, order); return ExecuteAsync(msg, ResultProcessor.RedisValueArray, defaultValue: Array.Empty<RedisValue>()); } public Task<long> SortedSetRemoveRangeByValueAsync(RedisKey key, RedisValue min, RedisValue max, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) { var msg = GetLexMessage(RedisCommand.ZREMRANGEBYLEX, key, min, max, exclude, 0, -1, flags, Order.Ascending); return ExecuteAsync(msg, ResultProcessor.Int64); }
SingleStreamReadCommandMessage
csharp
atata-framework__atata
src/Atata/Attributes/Triggers/PressKeysAttribute.cs
{ "start": 139, "end": 566 }
public class ____ : TriggerAttribute { public PressKeysAttribute(string keys, TriggerEvents on = TriggerEvents.AfterSet, TriggerPriority priority = TriggerPriority.Medium) : base(on, priority) => Keys = keys; public string Keys { get; protected set; } protected internal override void Execute<TOwner>(TriggerContext<TOwner> context) => context.Component.Owner.Press(Keys); }
PressKeysAttribute
csharp
grpc__grpc-dotnet
src/Grpc.AspNetCore.Server.ClientFactory/ContextPropagationInterceptor.cs
{ "start": 12663, "end": 13388 }
class ____ TResponse : class { internal static readonly Func<object, Task<Metadata>> GetResponseHeadersAsync = state => ((ContextState<AsyncDuplexStreamingCall<TRequest, TResponse>>)state).Call.ResponseHeadersAsync; internal static readonly Func<object, Status> GetStatus = state => ((ContextState<AsyncDuplexStreamingCall<TRequest, TResponse>>)state).Call.GetStatus(); internal static readonly Func<object, Metadata> GetTrailers = state => ((ContextState<AsyncDuplexStreamingCall<TRequest, TResponse>>)state).Call.GetTrailers(); internal static readonly Action<object> Dispose = state => ((ContextState<AsyncDuplexStreamingCall<TRequest, TResponse>>)state).Dispose(); }
where
csharp
npgsql__npgsql
src/Npgsql/Internal/ResolverFactories/RecordTypeInfoResolverFactory.cs
{ "start": 1724, "end": 2319 }
sealed class ____ : Resolver, IPgTypeInfoResolver { TypeInfoMappingCollection? _mappings; new TypeInfoMappingCollection Mappings => _mappings ??= AddMappings(new(base.Mappings)); public new PgTypeInfo? GetTypeInfo(Type? type, DataTypeName? dataTypeName, PgSerializerOptions options) => Mappings.Find(type, dataTypeName, options); static TypeInfoMappingCollection AddMappings(TypeInfoMappingCollection mappings) { mappings.AddArrayType<object[]>(DataTypeNames.Record); return mappings; } } }
ArrayResolver
csharp
dotnet__aspnetcore
src/Components/Server/src/Circuits/RemoteScrollToLocationHash.cs
{ "start": 358, "end": 1927 }
internal sealed class ____ : IScrollToLocationHash { private IJSRuntime _jsRuntime; public void AttachJSRuntime(IJSRuntime jsRuntime) { if (HasAttachedJSRuntime) { throw new InvalidOperationException("JSRuntime has already been initialized."); } _jsRuntime = jsRuntime; } public bool HasAttachedJSRuntime => _jsRuntime != null; public async Task RefreshScrollPositionForHash(string locationAbsolute) { if (!HasAttachedJSRuntime) { // We should generally never get here in the ordinary case. Router will only call this API once pre-rendering is complete. // This would guard any unusual usage of this API. throw new InvalidOperationException("Navigation commands can not be issued at this time. This is because the component is being " + "prerendered and the page has not yet loaded in the browser or because the circuit is currently disconnected. " + "Components must wrap any navigation calls in conditional logic to ensure those navigation calls are not " + "attempted during prerendering or while the client is disconnected."); } var hashIndex = locationAbsolute.IndexOf("#", StringComparison.Ordinal); if (hashIndex > -1 && locationAbsolute.Length > hashIndex + 1) { var elementId = locationAbsolute[(hashIndex + 1)..]; await _jsRuntime.InvokeVoidAsync(Interop.ScrollToElement, elementId); } } }
RemoteScrollToLocationHash
csharp
DapperLib__Dapper
Dapper/SqlMapper.GridReader.cs
{ "start": 21285, "end": 25648 }
record ____.</typeparam> /// <param name="types">The types to read from the result set.</param> /// <param name="map">The mapping function from the read types to the return type.</param> /// <param name="splitOn">The field(s) we should split and read the second object from (defaults to "id")</param> /// <param name="buffered">Whether to buffer results in memory.</param> public IEnumerable<TReturn> Read<TReturn>(Type[] types, Func<object[], TReturn> map, string splitOn = "id", bool buffered = true) { var result = MultiReadInternal(types, map, splitOn); return buffered ? result.ToList() : result; } private IEnumerable<T> ReadDeferred<T>(int index, Func<DbDataReader, object> deserializer, Type effectiveType) { try { while (index == ResultIndex && reader?.Read() == true) { yield return ConvertTo<T>(deserializer(reader)); } } finally // finally so that First etc progresses things even when multiple rows { OnAfterGrid(index); } } const int CONSUMED_FLAG = 1 << 31; private int _resultIndexAndConsumedFlag; //, readCount; /// <summary> /// Indicates the current result index /// </summary> protected int ResultIndex => _resultIndexAndConsumedFlag & ~CONSUMED_FLAG; /// <summary> /// Has the underlying reader been consumed? /// </summary> /// <remarks>This also reports <c>true</c> if the current grid is actively being consumed</remarks> public bool IsConsumed => (_resultIndexAndConsumedFlag & CONSUMED_FLAG) != 0; /// <summary> /// The command associated with the reader /// </summary> public IDbCommand Command { get; set; } /// <summary> /// The underlying reader /// </summary> protected DbDataReader Reader => reader; /// <summary> /// The cancellation token associated with this reader /// </summary> protected CancellationToken CancellationToken => cancel; /// <summary> /// Marks the current grid as consumed, and moves to the next result /// </summary> protected void OnAfterGrid(int index) { if (index != ResultIndex) { // not our data! } else if (reader is null) { // nothing to do } else if (reader.NextResult()) { // readCount++; _resultIndexAndConsumedFlag = index + 1; } else { // happy path; close the reader cleanly - no // need for "Cancel" etc reader.Dispose(); reader = null!; onCompleted?.Invoke(state); Dispose(); } } /// <summary> /// Dispose the grid, closing and disposing both the underlying reader and command. /// </summary> public void Dispose() { if (reader is not null) { if (!reader.IsClosed) Command?.Cancel(); reader.Dispose(); reader = null!; } if (Command is not null) { Command.Dispose(); Command = null!; } GC.SuppressFinalize(this); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static T ConvertTo<T>(object? value) => value switch { T typed => typed, null or DBNull => default!, _ => (T)Convert.ChangeType(value, Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T), CultureInfo.InvariantCulture), }; } } }
set
csharp
Xabaril__AspNetCore.Diagnostics.HealthChecks
src/HealthChecks.UI.Core/UIHealthReport.cs
{ "start": 2489, "end": 2830 }
public class ____ { public IReadOnlyDictionary<string, object> Data { get; set; } = null!; public string? Description { get; set; } public TimeSpan Duration { get; set; } public string? Exception { get; set; } public UIHealthStatus Status { get; set; } public IEnumerable<string>? Tags { get; set; } }
UIHealthReportEntry
csharp
dotnet__orleans
src/Orleans.Serialization/Buffers/ArcBufferWriter.cs
{ "start": 46479, "end": 48450 }
public struct ____(ArcBuffer slice) : IEnumerable<ArraySegment<byte>>, IEnumerator<ArraySegment<byte>> { private PageSegmentEnumerator _enumerator = slice.PageSegments; /// <summary> /// Gets this instance as an enumerator. /// </summary> /// <returns>This instance.</returns> public readonly ArraySegmentEnumerator GetEnumerator() => this; /// <summary> /// Gets the element in the collection at the current position of the enumerator. /// </summary> public ArraySegment<byte> Current { get; private set; } /// <inheritdoc/> readonly object? IEnumerator.Current => Current; /// <summary> /// Gets a value indicating whether enumeration has completed. /// </summary> public readonly bool IsCompleted => _enumerator.IsCompleted; /// <summary> /// Advances the enumerator to the next element of the collection. /// </summary> /// <returns><see langword="true"/> if the enumerator was successfully advanced to the next element; <see langword="false"/> if the enumerator has passed the end of the collection.</returns> public bool MoveNext() { if (_enumerator.MoveNext()) { Current = _enumerator.Current.ArraySegment; return true; } Current = default; return false; } /// <inheritdoc/> readonly IEnumerator<ArraySegment<byte>> IEnumerable<ArraySegment<byte>>.GetEnumerator() => GetEnumerator(); /// <inheritdoc/> readonly IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /// <inheritdoc/> void IEnumerator.Reset() { _enumerator = _enumerator.Slice.PageSegments; Current = default; } /// <inheritdoc/> readonly void IDisposable.Dispose() { } }
ArraySegmentEnumerator
csharp
AutoMapper__AutoMapper
src/UnitTests/Bug/CollectionMapperMapsISetIncorrectly.cs
{ "start": 201, "end": 324 }
public class ____ { public IEnumerable<TypeWithStringProperty> Stuff { get; set; } }
SourceWithIEnumerable
csharp
dotnet__orleans
src/api/Orleans.Serialization/Orleans.Serialization.cs
{ "start": 120319, "end": 121263 }
partial class ____ : IFieldCodec<sbyte>, IFieldCodec { sbyte IFieldCodec<sbyte>.ReadValue<TInput>(ref Buffers.Reader<TInput> reader, WireProtocol.Field field) { throw null; } void IFieldCodec<sbyte>.WriteField<TBufferWriter>(ref Buffers.Writer<TBufferWriter> writer, uint fieldIdDelta, System.Type expectedType, sbyte value) { } public static sbyte ReadValue<TInput>(ref Buffers.Reader<TInput> reader, WireProtocol.Field field) { throw null; } public static void WriteField<TBufferWriter>(ref Buffers.Writer<TBufferWriter> writer, uint fieldIdDelta, sbyte value) where TBufferWriter : System.Buffers.IBufferWriter<byte> { } public static void WriteField<TBufferWriter>(ref Buffers.Writer<TBufferWriter> writer, uint fieldIdDelta, System.Type expectedType, sbyte value, System.Type actualType) where TBufferWriter : System.Buffers.IBufferWriter<byte> { } }
SByteCodec
csharp
dotnetcore__FreeSql
Providers/FreeSql.Provider.Firebird/FirebirdProvider.cs
{ "start": 168, "end": 2395 }
public class ____<TMark> : BaseDbProvider, IFreeSql<TMark> { public override ISelect<T1> CreateSelectProvider<T1>(object dywhere) => new FirebirdSelect<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); public override IInsert<T1> CreateInsertProvider<T1>() => new FirebirdInsert<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression); public override IUpdate<T1> CreateUpdateProvider<T1>(object dywhere) => new FirebirdUpdate<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); public override IDelete<T1> CreateDeleteProvider<T1>(object dywhere) => new FirebirdDelete<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression, dywhere); public override IInsertOrUpdate<T1> CreateInsertOrUpdateProvider<T1>() => new FirebirdInsertOrUpdate<T1>(this, this.InternalCommonUtils, this.InternalCommonExpression); public FirebirdProvider(string masterConnectionString, string[] slaveConnectionString, Func<DbConnection> connectionFactory = null) { this.InternalCommonUtils = new FirebirdUtils(this); this.InternalCommonExpression = new FirebirdExpression(this.InternalCommonUtils); this.Ado = new FirebirdAdo(this.InternalCommonUtils, masterConnectionString, slaveConnectionString, connectionFactory); this.Aop = new AopProvider(); this.DbFirst = new FirebirdDbFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); this.CodeFirst = new FirebirdCodeFirst(this, this.InternalCommonUtils, this.InternalCommonExpression); if ((this.Ado as FirebirdAdo).IsFirebird2_5) this.Aop.ConfigEntityProperty += (_, e) => { if (e.Property.PropertyType.NullableTypeOrThis() == typeof(bool)) e.ModifyResult.MapType = typeof(short); }; } ~FirebirdProvider() => this.Dispose(); int _disposeCounter; public override void Dispose() { if (Interlocked.Increment(ref _disposeCounter) != 1) return; (this.Ado as AdoProvider)?.Dispose(); } } }
FirebirdProvider
csharp
dotnet__aspire
src/Aspire.Hosting/api/Aspire.Hosting.cs
{ "start": 89110, "end": 89450 }
partial class ____ { public bool Canceled { get { throw null; } init { } } public string? ErrorMessage { get { throw null; } init { } } public required bool Success { get { throw null; } init { } } } [System.Diagnostics.DebuggerDisplay("Type = {GetType().Name,nq}")] public sealed
ExecuteCommandResult
csharp
dotnet__aspnetcore
src/Mvc/Mvc.Core/test/CreatedResultTests.cs
{ "start": 524, "end": 4542 }
public class ____ { [Fact] public void CreatedResult_SetsStatusCode() { // Act var result = new CreatedResult(); // Assert Assert.Equal(StatusCodes.Status201Created, result.StatusCode); } [Fact] public void CreatedResult_SetsLocation() { // Arrange var location = "http://test/location"; // Act var result = new CreatedResult(location, "testInput"); // Assert Assert.Same(location, result.Location); } [Fact] public void CreatedResult_WithNoArgs_SetsLocationNull() { // Act var result = new CreatedResult(); // Assert Assert.Null(result.Location); } [Fact] public void CreatedResult_SetsLocationNull() { // Act var result = new CreatedResult((string)null, "testInput"); // Assert Assert.Null(result.Location); } [Fact] public async Task CreatedResult_ReturnsStatusCode_SetsLocationHeader() { // Arrange var location = "/test/"; var httpContext = GetHttpContext(); var actionContext = GetActionContext(httpContext); var result = new CreatedResult(location, "testInput"); // Act await result.ExecuteResultAsync(actionContext); // Assert Assert.Equal(StatusCodes.Status201Created, httpContext.Response.StatusCode); Assert.Equal(location, httpContext.Response.Headers["Location"]); } [Fact] public async Task CreatedResult_ReturnsStatusCode_NotSetLocationHeader() { // Arrange var httpContext = GetHttpContext(); var actionContext = GetActionContext(httpContext); var result = new CreatedResult((string)null, "testInput"); // Act await result.ExecuteResultAsync(actionContext); // Assert Assert.Equal(StatusCodes.Status201Created, httpContext.Response.StatusCode); Assert.Equal(0, httpContext.Response.Headers["Location"].Count); } [Fact] public async Task CreatedResult_OverwritesLocationHeader() { // Arrange var location = "/test/"; var httpContext = GetHttpContext(); var actionContext = GetActionContext(httpContext); httpContext.Response.Headers["Location"] = "/different/location/"; var result = new CreatedResult(location, "testInput"); // Act await result.ExecuteResultAsync(actionContext); // Assert Assert.Equal(StatusCodes.Status201Created, httpContext.Response.StatusCode); Assert.Equal(location, httpContext.Response.Headers["Location"]); } private static ActionContext GetActionContext(HttpContext httpContext) { var routeData = new RouteData(); routeData.Routers.Add(Mock.Of<IRouter>()); return new ActionContext(httpContext, routeData, new ActionDescriptor()); } private static HttpContext GetHttpContext() { var httpContext = new DefaultHttpContext(); httpContext.Request.PathBase = new PathString(""); httpContext.Response.Body = new MemoryStream(); httpContext.RequestServices = CreateServices(); return httpContext; } private static IServiceProvider CreateServices() { var options = Options.Create(new MvcOptions()); options.Value.OutputFormatters.Add(new StringOutputFormatter()); options.Value.OutputFormatters.Add(SystemTextJsonOutputFormatter.CreateFormatter(new JsonOptions())); var services = new ServiceCollection(); services.AddSingleton<IActionResultExecutor<ObjectResult>>(new ObjectResultExecutor( new DefaultOutputFormatterSelector(options, NullLoggerFactory.Instance), new TestHttpResponseStreamWriterFactory(), NullLoggerFactory.Instance, options)); return services.BuildServiceProvider(); } }
CreatedResultTests
csharp
graphql-dotnet__graphql-dotnet
src/GraphQL.Analyzers.Tests/ValidateArgumentsAttributeAnalyzerTests.cs
{ "start": 2047, "end": 2219 }
public class ____ { public const string ValidatorName = "PrivateValidator"; } }
Constants
csharp
AvaloniaUI__Avalonia
src/tools/Avalonia.Generators/Common/Domain/IViewResolver.cs
{ "start": 434, "end": 573 }
internal record ____(string ClassName, string Namespace, XamlDocument Xaml) : ResolvedViewInfo(ClassName, Namespace);
ResolvedViewDocument
csharp
bitwarden__server
test/Core.Test/AdminConsole/OrganizationFeatures/Organizations/GetOrganizationSubscriptionsToUpdateQueryTests.cs
{ "start": 446, "end": 2026 }
public class ____ { [Theory] [BitAutoData] public async Task GetOrganizationSubscriptionsToUpdateAsync_WhenNoOrganizationsNeedToBeSynced_ThenAnEmptyListIsReturned( SutProvider<GetOrganizationSubscriptionsToUpdateQuery> sutProvider) { sutProvider.GetDependency<IOrganizationRepository>() .GetOrganizationsForSubscriptionSyncAsync() .Returns([]); var result = await sutProvider.Sut.GetOrganizationSubscriptionsToUpdateAsync(); Assert.Empty(result); } [Theory] [BitAutoData] public async Task GetOrganizationSubscriptionsToUpdateAsync_WhenOrganizationsNeedToBeSynced_ThenUpdateIsReturnedWithCorrectPlanAndOrg( Organization organization, SutProvider<GetOrganizationSubscriptionsToUpdateQuery> sutProvider) { organization.PlanType = PlanType.EnterpriseAnnually2023; sutProvider.GetDependency<IOrganizationRepository>() .GetOrganizationsForSubscriptionSyncAsync() .Returns([organization]); sutProvider.GetDependency<IPricingClient>() .ListPlans() .Returns([new Enterprise2023Plan(true)]); var result = await sutProvider.Sut.GetOrganizationSubscriptionsToUpdateAsync(); var matchingUpdate = result.FirstOrDefault(x => x.Organization.Id == organization.Id); Assert.NotNull(matchingUpdate); Assert.Equal(organization.PlanType, matchingUpdate.Plan!.Type); Assert.Equal(organization, matchingUpdate.Organization); } }
GetOrganizationSubscriptionsToUpdateQueryTests
csharp
NLog__NLog
examples/targets/Configuration API/File/Simple/Example.cs
{ "start": 52, "end": 632 }
class ____ { static void Main(string[] args) { FileTarget target = new FileTarget(); target.Layout = "${longdate} ${logger} ${message}"; target.FileName = "${basedir}/logs/logfile.txt"; target.KeepFileOpen = false; target.Encoding = System.Text.Encoding.UTF8; LoggingConfiguration nlogConfig = new LoggingConfiguration(); nlogConfig.AddRuleForAllLevels(target); LogManager.Configuration = nlogConfig; Logger logger = LogManager.GetLogger("Example"); logger.Debug("log message"); } }
Example
csharp
atata-framework__atata
src/Atata/Attributes/Triggers/PressEnterAttribute.cs
{ "start": 160, "end": 522 }
public class ____ : TriggerAttribute { public PressEnterAttribute(TriggerEvents on = TriggerEvents.AfterSet, TriggerPriority priority = TriggerPriority.Medium) : base(on, priority) { } protected internal override void Execute<TOwner>(TriggerContext<TOwner> context) => context.Component.Owner.Press(Keys.Enter); }
PressEnterAttribute
csharp
pythonnet__pythonnet
src/runtime/Types/ClassDerived.cs
{ "start": 6705, "end": 8743 }
class ____ implement. if (baseType.IsInterface) { interfaces.Add(baseType); baseClass = typeof(object); } TypeBuilder typeBuilder = moduleBuilder.DefineType(name, TypeAttributes.Public | TypeAttributes.Class, baseClass, interfaces.ToArray()); // add a field for storing the python object pointer // FIXME: fb not used FieldBuilder fb = typeBuilder.DefineField(PyObjName, #pragma warning disable CS0618 // Type or member is obsolete. OK for internal use. typeof(UnsafeReferenceWithRun), #pragma warning restore CS0618 // Type or member is obsolete FieldAttributes.Private); // override any constructors ConstructorInfo[] constructors = baseClass.GetConstructors(); foreach (ConstructorInfo ctor in constructors) { AddConstructor(ctor, baseType, typeBuilder); } // Override any properties explicitly overridden in python var pyProperties = new HashSet<string>(); if (py_dict != null && Runtime.PyDict_Check(py_dict)) { using var dict = new PyDict(py_dict); using var keys = dict.Keys(); foreach (PyObject pyKey in keys) { using var value = dict[pyKey]; if (value.HasAttr("_clr_property_type_")) { string propertyName = pyKey.ToString()!; pyProperties.Add(propertyName); // Add the property to the type AddPythonProperty(propertyName, value, typeBuilder); } pyKey.Dispose(); } } // override any virtual not already overridden by the properties above // also override any
will
csharp
unoplatform__uno
src/AddIns/Uno.UI.WebView.Skia.X11/X11NativeWebView.cs
{ "start": 1266, "end": 14068 }
public class ____ : INativeWebView { [ThreadStatic] private static bool _isGtkThread; private static readonly Exception? _initException; private static readonly bool _usingWebKit2Gtk41; private readonly CoreWebView2 _coreWebView; private readonly ContentPresenter _presenter; private readonly Window _window; private readonly WebKit.WebView _webview; private readonly string _title = $"Uno WebView {Random.Shared.Next()}"; private bool _dontRaiseNextNavigationCompleted; [DllImport("libwebkit2gtk-4.1.so", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr webkit_uri_request_get_http_headers(IntPtr request); [DllImport("libsoup-3.0.so", CallingConvention = CallingConvention.Cdecl)] private static extern void soup_message_headers_append(IntPtr hdrs, string name, string value); [DllImport("libgdk-3.so", CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr gdk_x11_window_get_xid(IntPtr window); static X11NativeWebView() { try { // webkit2gtk-4.1 adds support for exposing libsoup objects, most importantly in webkit_uri_request_get_http_headers. // Gtk# by default loads libwebkit2gtk-4.0 (+ libsoup-2.0), but we want libwebkit2gtk-4.1 (+ libsoup-3.0), so what // we do is that before WebKitGtk# makes its dlopen calls, we load libwebkit2gtk-4.1 and put it where the handle to // libwebkit2gtk-4.0 will be expected to be, so that when WebKitGtk# attempts to dlopen(libwebkit2gtk-4.0), it will // find the handle already there and will just use it instead. if (!NativeLibrary.TryLoad("libwebkit2gtk-4.1.so", typeof(X11NativeWebView).Assembly, DllImportSearchPath.UserDirectories, out var webkitgtk41handle)) { if (typeof(X11NativeWebView).Log().IsEnabled(LogLevel.Error)) { typeof(X11NativeWebView).Log().Error($"libwebkit2gtk-4.1 was not found. Attempting to call {nameof(ProcessNavigation)} with an {nameof(HttpRequestMessage)} instance will crash the process."); } } else { Assembly assembly = Assembly.Load("WebKitGtkSharp"); Type glibraryType = assembly.GetType("GLibrary") ?? throw new NullReferenceException("Couldn't find GLibrary in WebKitGtkSharp"); Type libraryType = assembly.GetType("Library") ?? throw new NullReferenceException("Couldn't find Library in WebKitGtkSharp"); object webkitLibraryEnum = Enum.ToObject(libraryType, 11); FieldInfo field = glibraryType.GetField("_libraries", BindingFlags.NonPublic | BindingFlags.Static) ?? throw new NullReferenceException("Couldn't find a field named _libraries in GLibrary"); object libraries = field.GetValue(null) ?? throw new NullReferenceException("Couldn't read the static field named _libraries in GLibrary"); var setItemMethod = libraries.GetType().GetMethod("set_Item") ?? throw new NullReferenceException("Couldn't find a method named set_Item in _libraries"); setItemMethod.Invoke(libraries, [webkitLibraryEnum, webkitgtk41handle]); _usingWebKit2Gtk41 = true; } if (!WebKit.Global.IsSupported) { _initException = new PlatformNotSupportedException("libwebkit2gtk-4.0 is not found. Make sure that WebKit2GTK 4.0 and GTK 3 are installed. See https://aka.platform.uno/webview2 for more information"); return; } GLib.ExceptionManager.UnhandledException += args => { if (typeof(X11NativeWebView).Log().IsEnabled(LogLevel.Error)) { typeof(X11NativeWebView).Log().Error("GLib exception", args.ExceptionObject as Exception); } }; new Thread(() => { _isGtkThread = true; Application.Init(); Application.Run(); }) { IsBackground = true, Name = "X11 WebKitGTK thread" }.Start(); } catch (TypeInitializationException e) { _initException = e; if (typeof(X11NativeWebView).Log().IsEnabled(LogLevel.Error)) { typeof(X11NativeWebView).Log().Error("Unable to initialize Gtk, visit https://aka.platform.uno/gtk-install for more information.", e); } } } public X11NativeWebView(CoreWebView2 coreWebView2, ContentPresenter presenter) { if (_initException is { }) { throw _initException; } _coreWebView = coreWebView2; _presenter = presenter; (_window, _webview) = RunOnGtkThread(() => { var window = new Window(Gtk.WindowType.Toplevel); window.Title = _title; var webview = new WebKit.WebView(); webview.Settings.EnableSmoothScrolling = true; webview.Settings.EnableJavascript = true; webview.Settings.AllowFileAccessFromFileUrls = true; #if DEBUG webview.Settings.EnableDeveloperExtras = true; #endif return (window, webview); }); var xid = RunOnGtkThread(() => { _webview.LoadChanged += WebViewOnLoadChanged; _webview.LoadFailed += WebViewOnLoadFailed; _webview.UserContentManager.RegisterScriptMessageHandler("unoWebView"); _webview.UserContentManager.ScriptMessageReceived += UserContentManagerOnScriptMessageReceived; _webview.AddNotification(WebViewNotificationHandler); _window.Add(_webview); _webview.ShowAll(); _window.Realize(); // creates the Gdk window (and the X11 window) without showing it return gdk_x11_window_get_xid(_window.Window.Handle); }); presenter.Content = new X11NativeWindow(xid); if (presenter.IsInLiveTree) { RunOnGtkThread(() => _window.ShowAll()); } presenter.Loaded += (_, _) => RunOnGtkThread(() => _window.ShowAll()); presenter.Unloaded += (_, _) => RunOnGtkThread(() => _window.Hide()); } ~X11NativeWebView() { RunOnGtkThread(() => _window.Close()); } public string DocumentTitle => RunOnGtkThread(() => _webview.Title); private static T RunOnGtkThread<T>(Func<T> func) { if (_isGtkThread) { return func(); } else { var tcs = new TaskCompletionSource<T>(); GLib.Idle.Add(() => { tcs.SetResult(func()); return false; }); return tcs.Task.Result; } } private static void RunOnGtkThread(Action func) { if (_isGtkThread) { func(); } else { var tcs = new TaskCompletionSource(); GLib.Idle.Add(() => { func(); tcs.SetResult(); return false; }); tcs.Task.Wait(); } } public void GoBack() => RunOnGtkThread(() => _webview.GoBack()); public void GoForward() => RunOnGtkThread(() => _webview.GoForward()); public void Stop() => RunOnGtkThread(() => _webview.StopLoading()); public void Reload() => RunOnGtkThread(() => _webview.Reload()); public void ProcessNavigation(Uri uri) { if (_coreWebView.HostToFolderMap.TryGetValue(uri.Host.ToLowerInvariant(), out var folderName)) { var relativePath = uri.PathAndQuery; var baseUrl = Package.Current.InstalledPath; RunOnGtkThread(() => _webview.LoadUri($"file://{Path.Join(baseUrl, folderName, relativePath)}")); } else { ProcessNavigation(new HttpRequestMessage(HttpMethod.Get, uri)); } } public void ProcessNavigation(string html) => RunOnGtkThread(() => { _webview.LoadHtml(html); }); public void ProcessNavigation(HttpRequestMessage httpRequestMessage) => RunOnGtkThread(() => { var url = httpRequestMessage.RequestUri?.ToString(); if (url is null) { if (this.Log().IsEnabled(LogLevel.Error)) { this.Log().Error($"{nameof(ProcessNavigation)} received an {nameof(HttpRequestMessage)} with a null uri."); } return; } var request = new URIRequest(url); if (_usingWebKit2Gtk41) { var headers = webkit_uri_request_get_http_headers(request.Handle); foreach (var header in httpRequestMessage.Headers) { // a header name can have multiple values foreach (var val in header.Value) { soup_message_headers_append(headers, header.Key, val); } } } _webview.LoadRequest(request); }); public Task<string?> ExecuteScriptAsync(string script, CancellationToken token) { var tcs = new TaskCompletionSource<string?>(); _webview.RunJavascript(script, null, (wv, res) => { // INCREDIBLY IMPORTANT NOTES // Read JSValue only once. Each time result.JsValue is read, it increments the ref count // of the native object and you'll get "Unexpected number of toggle-refs. // g_object_add_toggle_ref() must be paired with g_object_remove_toggle_ref()". This also // means that if you're investing something related to the native ref-counting like a // double free, make sure that you don't read JsValue in the Debugger, or even hover over // it, because if you do, the ref count will be incremented and the double free will go away. // Instead, log JavaScript.Value.RefCount using reflection. // Console.WriteLine($"Ref count: {typeof(Value).GetProperty("RefCount", BindingFlags.NonPublic | BindingFlags.Instance)!.GetValue(jsval)}"); try { var result = ((WebKit.WebView)wv).RunJavascriptFinish(res); var jsval = result.JsValue; tcs.SetResult(JsValueToString(jsval)); result.Dispose(); // There is a WebKitGtkSharp bug that causes a double free if you let both result and result.JSValue finalize // It seems like JSValue gets freed as a part of the owning result, so if you let both of their finalizers run, // you'll get a double free. GC.SuppressFinalize(jsval); } catch (GException e) { if (this.Log().IsEnabled(LogLevel.Error)) { this.Log().Error($"{nameof(ExecuteScriptAsync)} threw an exception", e); } tcs.SetException(e); } }); return tcs.Task; } public Task<string?> InvokeScriptAsync(string script, string[]? arguments, CancellationToken token) { // JsonSerializer.Serialize safely escapes quotes and concatenates the arguments (with a comma) to be passed to eval // the [1..^1] part is to remove [ and ]. var argumentString = arguments is not null ? JsonSerializer.Serialize(arguments)[1..^1] : ""; return ExecuteScriptAsync($"{script}({argumentString})", token); } public void SetScrollingEnabled(bool isScrollingEnabled) { if (this.Log().IsEnabled(LogLevel.Error)) { this.Log().Error($"{nameof(SetScrollingEnabled)} is not supported on the X11 target."); } } private void WebViewOnLoadChanged(object o, LoadChangedArgs args) { switch (args.LoadEvent) { case LoadEvent.Started: { if (Uri.TryCreate(_webview.Uri, UriKind.Absolute, out var uri)) { _presenter.DispatcherQueue.TryEnqueue(() => { _coreWebView.RaiseNavigationStarting(uri, out var cancel); if (cancel) { GLib.Idle.Add(() => { _webview.StopLoading(); return false; }); } }); } } break; case LoadEvent.Redirected: break; case LoadEvent.Committed: break; case LoadEvent.Finished: { var (canGoBack, canGoForward, uriString) = (_webview.CanGoBack(), _webview.CanGoForward(), _webview.Uri); if (_dontRaiseNextNavigationCompleted) { _dontRaiseNextNavigationCompleted = false; } else { _presenter.DispatcherQueue.TryEnqueue(() => { _coreWebView.SetHistoryProperties(canGoBack, canGoForward); _coreWebView.RaiseHistoryChanged(); Uri.TryCreate(uriString, UriKind.Absolute, out var uri); _presenter.DispatcherQueue.TryEnqueue(() => { _coreWebView.RaiseNavigationCompleted(uri, isSuccess: true, httpStatusCode: 200, errorStatus: CoreWebView2WebErrorStatus.Unknown, shouldSetSource: true); }); }); } } break; } } private void WebViewOnLoadFailed(object o, LoadFailedArgs args) { _dontRaiseNextNavigationCompleted = true; Uri.TryCreate(args.FailingUri, UriKind.Absolute, out var uri); _presenter.DispatcherQueue.TryEnqueue(() => { _coreWebView.RaiseNavigationCompleted(uri, isSuccess: false, httpStatusCode: 0, errorStatus: CoreWebView2WebErrorStatus.Unknown, shouldSetSource: true); }); } private void WebViewNotificationHandler(object o, NotifyArgs args) { if (args.Property == "title") { _coreWebView.OnDocumentTitleChanged(); } } private void UserContentManagerOnScriptMessageReceived(object o, ScriptMessageReceivedArgs args) { var result = args.JsResult; var value = result.JsValue; var str = JsValueToString(value); result.Dispose(); GC.SuppressFinalize(value); // see comments in ExecuteScriptAsync _presenter.DispatcherQueue.TryEnqueue(() => { _coreWebView.RaiseWebMessageReceived(str); }); } private string JsValueToString(Value value) { if (value.IsNull) { return "null"; } else if (value.IsUndefined) { return "undefined"; } else if (value.IsString) { // We do this to get string quoting to be closer to other platforms // Regex.Unescape negates the double escaping due to Encode + ToJson return Regex.Unescape(System.Text.Json.JsonEncodedText.Encode(value.ToJson(0), JavaScriptEncoder.UnsafeRelaxedJsonEscaping).ToString()); } return value.ToJson(0); } }
X11NativeWebView
csharp
bitwarden__server
test/Common/MockedHttpClient/HttpRequestMatcher.cs
{ "start": 83, "end": 3621 }
public class ____ : IHttpRequestMatcher { private readonly Func<HttpRequestMessage, bool> _matcher; private HttpRequestMatcher? _childMatcher; private MockedHttpResponse _mockedResponse = new(HttpStatusCode.OK); private bool _responseSpecified = false; public int NumberOfMatches { get; private set; } /// <summary> /// Returns whether or not the provided request can be handled by this matcher chain. /// </summary> /// <param name="request"></param> /// <returns></returns> public bool Matches(HttpRequestMessage request) => _matcher(request) && (_childMatcher == null || _childMatcher.Matches(request)); public HttpRequestMatcher(HttpMethod method) { _matcher = request => request.Method == method; } public HttpRequestMatcher(string uri) { _matcher = request => request.RequestUri == new Uri(uri); } public HttpRequestMatcher(Uri uri) { _matcher = request => request.RequestUri == uri; } public HttpRequestMatcher(HttpMethod method, string uri) { _matcher = request => request.Method == method && request.RequestUri == new Uri(uri); } public HttpRequestMatcher(Func<HttpRequestMessage, bool> matcher) { _matcher = matcher; } public HttpRequestMatcher WithHeader(string name, string value) { return AddChild(request => request.Headers.TryGetValues(name, out var values) && values.Contains(value)); } public HttpRequestMatcher WithQueryParameters(Dictionary<string, string> requiredQueryParameters) => WithQueryParameters(requiredQueryParameters.Select(x => $"{x.Key}={x.Value}").ToArray()); public HttpRequestMatcher WithQueryParameters(string name, string value) => WithQueryParameters($"{name}={value}"); public HttpRequestMatcher WithQueryParameters(params string[] queryKeyValues) { bool matcher(HttpRequestMessage request) { var query = request.RequestUri?.Query; if (query == null) { return false; } return queryKeyValues.All(queryKeyValue => query.Contains(queryKeyValue)); } return AddChild(matcher); } /// <summary> /// Configure how this matcher should respond to matching HttpRequestMessages. /// Note, after specifying a response, you can no longer further specify match criteria. /// </summary> /// <param name="statusCode"></param> /// <returns></returns> public MockedHttpResponse RespondWith(HttpStatusCode statusCode) { _responseSpecified = true; _mockedResponse = new MockedHttpResponse(statusCode); return _mockedResponse; } /// <summary> /// Called to produce an HttpResponseMessage for the given request. This is probably something you want to leave alone /// </summary> /// <param name="request"></param> public async Task<HttpResponseMessage> RespondToAsync(HttpRequestMessage request) { NumberOfMatches++; return await (_childMatcher == null ? _mockedResponse.RespondToAsync(request) : _childMatcher.RespondToAsync(request)); } private HttpRequestMatcher AddChild(Func<HttpRequestMessage, bool> matcher) { if (_responseSpecified) { throw new Exception("Cannot continue to configure a matcher after a response has been specified"); } _childMatcher = new HttpRequestMatcher(matcher); return _childMatcher; } }
HttpRequestMatcher
csharp
IdentityModel__IdentityModel
src/Client/Extensions/HttpClientJsonWebKeySetExtensions.cs
{ "start": 425, "end": 2622 }
public static class ____ { /// <summary> /// Sends a JSON web key set document request /// </summary> /// <param name="client">The client.</param> /// <param name="address"></param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> public static async Task<JsonWebKeySetResponse> GetJsonWebKeySetAsync(this HttpMessageInvoker client, string? address = null, CancellationToken cancellationToken = default) { return await client.GetJsonWebKeySetAsync(new JsonWebKeySetRequest { Address = address }, cancellationToken).ConfigureAwait(); } /// <summary> /// Sends a JSON web key set document request /// </summary> /// <param name="client">The client.</param> /// <param name="request">The request</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> public static async Task<JsonWebKeySetResponse> GetJsonWebKeySetAsync(this HttpMessageInvoker client, JsonWebKeySetRequest request, CancellationToken cancellationToken = default) { var clone = request.Clone(); clone.Method = HttpMethod.Get; clone.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/jwk-set+json")); clone.Prepare(); HttpResponseMessage response; try { response = await client.SendAsync(clone, cancellationToken).ConfigureAwait(); if (!response.IsSuccessStatusCode) { return await ProtocolResponse.FromHttpResponseAsync<JsonWebKeySetResponse>(response, $"Error connecting to {clone.RequestUri!.AbsoluteUri}: {response.ReasonPhrase}").ConfigureAwait(); } } catch (OperationCanceledException) { throw; } catch (Exception ex) { return ProtocolResponse.FromException<JsonWebKeySetResponse>(ex, $"Error connecting to {clone.RequestUri!.AbsoluteUri}. {ex.Message}."); } return await ProtocolResponse.FromHttpResponseAsync<JsonWebKeySetResponse>(response).ConfigureAwait(); } }
HttpClientJsonWebKeySetExtensions
csharp
abpframework__abp
modules/openiddict/test/Volo.Abp.OpenIddict.TestBase/Volo/Abp/OpenIddict/AbpOpenIddictTestData.cs
{ "start": 84, "end": 1010 }
public class ____ : ISingletonDependency { public Guid App1Id { get; set; } = Guid.NewGuid(); public string App1ClientId { get; set; } = "Client1"; public Guid App2Id { get; set; } = Guid.NewGuid(); public string App2ClientId { get; set; } = "Client2"; public Guid Scope1Id { get; set; } = Guid.NewGuid(); public string Scope1Name { get; set; } = "Scope1"; public Guid Scope2Id { get; set; } = Guid.NewGuid(); public string Subject1 { get; set; } = "Subject1"; public string Subject2 { get; set; } = "Subject2"; public string Subject3 { get; set; } = "Subject3"; public string Scope2Name { get; set; } = "Scope2"; public Guid Token1Id { get; set; } = Guid.NewGuid(); public Guid Token2Id { get; set; } = Guid.NewGuid(); public Guid Authorization1Id { get; set; } = Guid.NewGuid(); public Guid Authorization2Id { get; set; } = Guid.NewGuid(); }
AbpOpenIddictTestData
csharp
dotnet__machinelearning
docs/samples/Microsoft.ML.GenAI.Samples/Mistral/Mistral_7B_Instruct.cs
{ "start": 306, "end": 3118 }
public partial class ____ { private static Mistral_7B_Instruct instance = new Mistral_7B_Instruct(); /// <summary> /// get weather from city /// </summary> /// <param name="city"></param> [Function] public Task<string> GetWeather(string city) { return Task.FromResult($"The weather in {city} is sunny."); } public static async Task RunAsync() { var device = "cuda"; if (device == "cuda") { torch.InitializeDeviceType(DeviceType.CUDA); } var defaultType = ScalarType.BFloat16; torch.manual_seed(1); torch.set_default_dtype(defaultType); var weightFolder = @"C:\Users\xiaoyuz\source\repos\Mistral-7B-Instruct-v0.3"; var configName = "config.json"; var originalWeightFolder = Path.Combine(weightFolder); Console.WriteLine("Loading Mistral from huggingface model weight folder"); var tokenizer = MistralTokenizerHelper.FromPretrained(originalWeightFolder); var model = MistralForCausalLM.FromPretrained(weightFolder, configName, layersOnTargetDevice: -1); var pipeline = new CausalLMPipeline<LlamaTokenizer, MistralForCausalLM>(tokenizer, model, device); var agent = new MistralCausalLMAgent(pipeline, "assistant") .RegisterPrintMessage(); var task = """ How are you. """; await agent.SendAsync(task); } public static void Embedding() { var device = "cuda"; if (device == "cuda") { torch.InitializeDeviceType(DeviceType.CUDA); } var defaultType = ScalarType.Float32; torch.manual_seed(1); torch.set_default_dtype(defaultType); var weightFolder = @"C:\Users\xiaoyuz\source\repos\bge-en-icl"; var configName = "config.json"; var originalWeightFolder = Path.Combine(weightFolder); Console.WriteLine("Loading Mistral from huggingface model weight folder"); var tokenizer = MistralTokenizerHelper.FromPretrained(originalWeightFolder, modelName: "tokenizer.model"); var mistralConfig = JsonSerializer.Deserialize<MistralConfig>(File.ReadAllText(Path.Combine(weightFolder, configName))) ?? throw new ArgumentNullException(nameof(configName)); var model = new MistralModel(mistralConfig); model.load_checkpoint(weightFolder, "model.safetensors.index.json", strict: true, useTqdm: false); model.to(device); var pipeline = new CausalLMPipeline<LlamaTokenizer, MistralModel>(tokenizer, model, device); var query = """ <instruct>Given a web search query, retrieve relevant passages that answer the query. <query>what is a virtual interface <response>A virtual
Mistral_7B_Instruct
csharp
ServiceStack__ServiceStack
ServiceStack.Text/tests/ServiceStack.Text.Tests/UseCases/StripeGateway.cs
{ "start": 5817, "end": 6067 }
public class ____ : IPost, IReturn<StripeCard> { [IgnoreDataMember] public string CustomerId { get; set; } public StripeCard Card { get; set; } } [Route("/customers/{CustomerId}/cards/{CardId}")]
CreateStripeCard
csharp
icsharpcode__SharpZipLib
src/ICSharpCode.SharpZipLib/GZip/GzipOutputStream.cs
{ "start": 1127, "end": 9809 }
private enum ____ { Header, Footer, Finished, Closed, }; #region Instance Fields /// <summary> /// CRC-32 value for uncompressed data /// </summary> protected Crc32 crc = new Crc32(); private OutputState state_ = OutputState.Header; private string fileName; private GZipFlags flags = 0; #endregion Instance Fields #region Constructors /// <summary> /// Creates a GzipOutputStream with the default buffer size /// </summary> /// <param name="baseOutputStream"> /// The stream to read data (to be compressed) from /// </param> public GZipOutputStream(Stream baseOutputStream) : this(baseOutputStream, 4096) { } /// <summary> /// Creates a GZipOutputStream with the specified buffer size /// </summary> /// <param name="baseOutputStream"> /// The stream to read data (to be compressed) from /// </param> /// <param name="size"> /// Size of the buffer to use /// </param> public GZipOutputStream(Stream baseOutputStream, int size) : base(baseOutputStream, new Deflater(Deflater.DEFAULT_COMPRESSION, true), size) { } #endregion Constructors #region Public API /// <summary> /// Sets the active compression level (0-9). The new level will be activated /// immediately. /// </summary> /// <param name="level">The compression level to set.</param> /// <exception cref="ArgumentOutOfRangeException"> /// Level specified is not supported. /// </exception> /// <see cref="Deflater"/> public void SetLevel(int level) { if (level < Deflater.NO_COMPRESSION || level > Deflater.BEST_COMPRESSION) throw new ArgumentOutOfRangeException(nameof(level), "Compression level must be 0-9"); deflater_.SetLevel(level); } /// <summary> /// Get the current compression level. /// </summary> /// <returns>The current compression level.</returns> public int GetLevel() { return deflater_.GetLevel(); } /// <summary> /// Original filename /// </summary> public string FileName { get => fileName; set { fileName = CleanFilename(value); if (string.IsNullOrEmpty(fileName)) { flags &= ~GZipFlags.FNAME; } else { flags |= GZipFlags.FNAME; } } } /// <summary> /// If defined, will use this time instead of the current for the output header /// </summary> public DateTime? ModifiedTime { get; set; } #endregion Public API #region Stream overrides /// <summary> /// Write given buffer to output updating crc /// </summary> /// <param name="buffer">Buffer to write</param> /// <param name="offset">Offset of first byte in buf to write</param> /// <param name="count">Number of bytes to write</param> public override void Write(byte[] buffer, int offset, int count) => WriteSyncOrAsync(buffer, offset, count, null).GetAwaiter().GetResult(); private async Task WriteSyncOrAsync(byte[] buffer, int offset, int count, CancellationToken? ct) { if (state_ == OutputState.Header) { if (ct.HasValue) { await WriteHeaderAsync(ct.Value).ConfigureAwait(false); } else { WriteHeader(); } } if (state_ != OutputState.Footer) throw new InvalidOperationException("Write not permitted in current state"); crc.Update(new ArraySegment<byte>(buffer, offset, count)); if (ct.HasValue) { await base.WriteAsync(buffer, offset, count, ct.Value).ConfigureAwait(false); } else { base.Write(buffer, offset, count); } } /// <summary> /// Asynchronously write given buffer to output updating crc /// </summary> /// <param name="buffer">Buffer to write</param> /// <param name="offset">Offset of first byte in buf to write</param> /// <param name="count">Number of bytes to write</param> /// <param name="ct">The token to monitor for cancellation requests</param> public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken ct) => await WriteSyncOrAsync(buffer, offset, count, ct).ConfigureAwait(false); /// <summary> /// Writes remaining compressed output data to the output stream /// and closes it. /// </summary> protected override void Dispose(bool disposing) { try { Finish(); } finally { if (state_ != OutputState.Closed) { state_ = OutputState.Closed; if (IsStreamOwner) { baseOutputStream_.Dispose(); } } } } #if NETSTANDARD2_1_OR_GREATER || NETCOREAPP3_1_OR_GREATER /// <inheritdoc cref="DeflaterOutputStream.Dispose"/> public override async ValueTask DisposeAsync() { try { await FinishAsync(CancellationToken.None).ConfigureAwait(false); } finally { if (state_ != OutputState.Closed) { state_ = OutputState.Closed; if (IsStreamOwner) { await baseOutputStream_.DisposeAsync().ConfigureAwait(false); } } await base.DisposeAsync().ConfigureAwait(false); } } #endif /// <summary> /// Flushes the stream by ensuring the header is written, and then calling <see cref="DeflaterOutputStream.Flush">Flush</see> /// on the deflater. /// </summary> public override void Flush() { if (state_ == OutputState.Header) { WriteHeader(); } base.Flush(); } /// <inheritdoc cref="Flush"/> public override async Task FlushAsync(CancellationToken ct) { if (state_ == OutputState.Header) { await WriteHeaderAsync(ct).ConfigureAwait(false); } await base.FlushAsync(ct).ConfigureAwait(false); } #endregion Stream overrides #region DeflaterOutputStream overrides /// <summary> /// Finish compression and write any footer information required to stream /// </summary> public override void Finish() { // If no data has been written a header should be added. if (state_ == OutputState.Header) { WriteHeader(); } if (state_ == OutputState.Footer) { state_ = OutputState.Finished; base.Finish(); var gzipFooter = GetFooter(); baseOutputStream_.Write(gzipFooter, 0, gzipFooter.Length); } } /// <inheritdoc cref="Finish"/> public override async Task FinishAsync(CancellationToken ct) { // If no data has been written a header should be added. if (state_ == OutputState.Header) { await WriteHeaderAsync(ct).ConfigureAwait(false); } if (state_ == OutputState.Footer) { state_ = OutputState.Finished; await base.FinishAsync(ct).ConfigureAwait(false); var gzipFooter = GetFooter(); await baseOutputStream_.WriteAsync(gzipFooter, 0, gzipFooter.Length, ct).ConfigureAwait(false); } } #endregion DeflaterOutputStream overrides #region Support Routines private byte[] GetFooter() { var totalin = (uint)(deflater_.TotalIn & 0xffffffff); var crcval = (uint)(crc.Value & 0xffffffff); byte[] gzipFooter; unchecked { gzipFooter = new [] { (byte) crcval, (byte) (crcval >> 8), (byte) (crcval >> 16), (byte) (crcval >> 24), (byte) totalin, (byte) (totalin >> 8), (byte) (totalin >> 16), (byte) (totalin >> 24), }; } return gzipFooter; } private byte[] GetHeader() { var modifiedUtc = ModifiedTime?.ToUniversalTime() ?? DateTime.UtcNow; var modTime = (int)((modifiedUtc - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks / 10000000L); // Ticks give back 100ns intervals byte[] gzipHeader = { // The two magic bytes GZipConstants.ID1, GZipConstants.ID2, // The compression type GZipConstants.CompressionMethodDeflate, // The flags (not set) (byte)flags, // The modification time (byte) modTime, (byte) (modTime >> 8), (byte) (modTime >> 16), (byte) (modTime >> 24), // The extra flags 0, // The OS type (unknown) 255 }; if (!flags.HasFlag(GZipFlags.FNAME)) { return gzipHeader; } return gzipHeader .Concat(GZipConstants.Encoding.GetBytes(fileName)) .Concat(new byte []{0}) // End filename string with a \0 .ToArray(); } private static string CleanFilename(string path) => path.Substring(path.LastIndexOf('/') + 1); private void WriteHeader() { if (state_ != OutputState.Header) return; state_ = OutputState.Footer; var gzipHeader = GetHeader(); baseOutputStream_.Write(gzipHeader, 0, gzipHeader.Length); } private async Task WriteHeaderAsync(CancellationToken ct) { if (state_ != OutputState.Header) return; state_ = OutputState.Footer; var gzipHeader = GetHeader(); await baseOutputStream_.WriteAsync(gzipHeader, 0, gzipHeader.Length, ct).ConfigureAwait(false); } #endregion Support Routines } }
OutputState
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.Razor/Html/RouteValueDictionary.cs
{ "start": 1492, "end": 1561 }
public class ____ : IDictionary<string, object> {
RouteValueDictionary
csharp
MonoGame__MonoGame
Tools/MonoGame.Tools.Tests/Program.cs
{ "start": 286, "end": 429 }
static class ____ { static int Main(string [] args) { return new AutoRun().Execute(args); } } }
Program
csharp
bitwarden__server
util/PostgresMigrations/Migrations/20240703205916_UpdateNullConstraintsAdminConsole.Designer.cs
{ "start": 523, "end": 104059 }
partial class ____ { /// <inheritdoc /> protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Npgsql:CollationDefinition:postgresIndetermanisticCollation", "en-u-ks-primary,en-u-ks-primary,icu,False") .HasAnnotation("ProductVersion", "8.0.6") .HasAnnotation("Relational:MaxIdentifierLength", 63); NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<bool>("AllowAdminAccessToAllCollectionItems") .HasColumnType("boolean") .HasDefaultValue(true); b.Property<string>("BillingEmail") .IsRequired() .HasMaxLength(256) .HasColumnType("character varying(256)"); b.Property<string>("BusinessAddress1") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("BusinessAddress2") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("BusinessAddress3") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("BusinessCountry") .HasMaxLength(2) .HasColumnType("character varying(2)"); b.Property<string>("BusinessName") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("BusinessTaxNumber") .HasMaxLength(30) .HasColumnType("character varying(30)"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<bool>("Enabled") .HasColumnType("boolean"); b.Property<DateTime?>("ExpirationDate") .HasColumnType("timestamp with time zone"); b.Property<bool>("FlexibleCollections") .HasColumnType("boolean"); b.Property<byte?>("Gateway") .HasColumnType("smallint"); b.Property<string>("GatewayCustomerId") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("GatewaySubscriptionId") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("Identifier") .HasMaxLength(50) .HasColumnType("character varying(50)") .UseCollation("postgresIndetermanisticCollation"); b.Property<string>("LicenseKey") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property<bool>("LimitCollectionCreationDeletion") .HasColumnType("boolean") .HasDefaultValue(true); b.Property<int?>("MaxAutoscaleSeats") .HasColumnType("integer"); b.Property<int?>("MaxAutoscaleSmSeats") .HasColumnType("integer"); b.Property<int?>("MaxAutoscaleSmServiceAccounts") .HasColumnType("integer"); b.Property<short?>("MaxCollections") .HasColumnType("smallint"); b.Property<short?>("MaxStorageGb") .HasColumnType("smallint"); b.Property<string>("Name") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<DateTime?>("OwnersNotifiedOfAutoscaling") .HasColumnType("timestamp with time zone"); b.Property<string>("Plan") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<byte>("PlanType") .HasColumnType("smallint"); b.Property<string>("PrivateKey") .HasColumnType("text"); b.Property<string>("PublicKey") .HasColumnType("text"); b.Property<string>("ReferenceData") .HasColumnType("text"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<int?>("Seats") .HasColumnType("integer"); b.Property<bool>("SelfHost") .HasColumnType("boolean"); b.Property<int?>("SmSeats") .HasColumnType("integer"); b.Property<int?>("SmServiceAccounts") .HasColumnType("integer"); b.Property<byte>("Status") .HasColumnType("smallint"); b.Property<long?>("Storage") .HasColumnType("bigint"); b.Property<string>("TwoFactorProviders") .HasColumnType("text"); b.Property<bool>("Use2fa") .HasColumnType("boolean"); b.Property<bool>("UseApi") .HasColumnType("boolean"); b.Property<bool>("UseCustomPermissions") .HasColumnType("boolean"); b.Property<bool>("UseDirectory") .HasColumnType("boolean"); b.Property<bool>("UseEvents") .HasColumnType("boolean"); b.Property<bool>("UseGroups") .HasColumnType("boolean"); b.Property<bool>("UseKeyConnector") .HasColumnType("boolean"); b.Property<bool>("UsePasswordManager") .HasColumnType("boolean"); b.Property<bool>("UsePolicies") .HasColumnType("boolean"); b.Property<bool>("UseResetPassword") .HasColumnType("boolean"); b.Property<bool>("UseScim") .HasColumnType("boolean"); b.Property<bool>("UseSecretsManager") .HasColumnType("boolean"); b.Property<bool>("UseSso") .HasColumnType("boolean"); b.Property<bool>("UseTotp") .HasColumnType("boolean"); b.Property<bool>("UsersGetPremium") .HasColumnType("boolean"); b.HasKey("Id"); b.HasIndex("Id", "Enabled"); NpgsqlIndexBuilderExtensions.IncludeProperties(b.HasIndex("Id", "Enabled"), new[] { "UseTotp" }); b.ToTable("Organization", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Policy", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Data") .HasColumnType("text"); b.Property<bool>("Enabled") .HasColumnType("boolean"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<byte>("Type") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("OrganizationId") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("OrganizationId", "Type") .IsUnique() .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Policy", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<string>("BillingEmail") .HasColumnType("text"); b.Property<string>("BillingPhone") .HasColumnType("text"); b.Property<string>("BusinessAddress1") .HasColumnType("text"); b.Property<string>("BusinessAddress2") .HasColumnType("text"); b.Property<string>("BusinessAddress3") .HasColumnType("text"); b.Property<string>("BusinessCountry") .HasColumnType("text"); b.Property<string>("BusinessName") .HasColumnType("text"); b.Property<string>("BusinessTaxNumber") .HasColumnType("text"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<bool>("Enabled") .HasColumnType("boolean"); b.Property<byte?>("Gateway") .HasColumnType("smallint"); b.Property<string>("GatewayCustomerId") .HasColumnType("text"); b.Property<string>("GatewaySubscriptionId") .HasColumnType("text"); b.Property<string>("Name") .HasColumnType("text"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<byte>("Status") .HasColumnType("smallint"); b.Property<byte>("Type") .HasColumnType("smallint"); b.Property<bool>("UseEvents") .HasColumnType("boolean"); b.HasKey("Id"); b.ToTable("Provider", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.ProviderOrganization", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Key") .HasColumnType("text"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<Guid>("ProviderId") .HasColumnType("uuid"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Settings") .HasColumnType("text"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.HasIndex("ProviderId"); b.ToTable("ProviderOrganization", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.ProviderUser", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Email") .HasColumnType("text"); b.Property<string>("Key") .HasColumnType("text"); b.Property<string>("Permissions") .HasColumnType("text"); b.Property<Guid>("ProviderId") .HasColumnType("uuid"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<byte>("Status") .HasColumnType("smallint"); b.Property<byte>("Type") .HasColumnType("smallint"); b.Property<Guid?>("UserId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("ProviderId"); b.HasIndex("UserId"); b.ToTable("ProviderUser", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.AuthRequest", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<string>("AccessCode") .HasMaxLength(25) .HasColumnType("character varying(25)"); b.Property<bool?>("Approved") .HasColumnType("boolean"); b.Property<DateTime?>("AuthenticationDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Key") .HasColumnType("text"); b.Property<string>("MasterPasswordHash") .HasColumnType("text"); b.Property<Guid?>("OrganizationId") .HasColumnType("uuid"); b.Property<string>("PublicKey") .HasColumnType("text"); b.Property<string>("RequestDeviceIdentifier") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<byte>("RequestDeviceType") .HasColumnType("smallint"); b.Property<string>("RequestIpAddress") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<DateTime?>("ResponseDate") .HasColumnType("timestamp with time zone"); b.Property<Guid?>("ResponseDeviceId") .HasColumnType("uuid"); b.Property<byte>("Type") .HasColumnType("smallint"); b.Property<Guid>("UserId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.HasIndex("ResponseDeviceId"); b.HasIndex("UserId"); b.ToTable("AuthRequest", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.EmergencyAccess", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Email") .HasMaxLength(256) .HasColumnType("character varying(256)"); b.Property<Guid?>("GranteeId") .HasColumnType("uuid"); b.Property<Guid>("GrantorId") .HasColumnType("uuid"); b.Property<string>("KeyEncrypted") .HasColumnType("text"); b.Property<DateTime?>("LastNotificationDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime?>("RecoveryInitiatedDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<byte>("Status") .HasColumnType("smallint"); b.Property<byte>("Type") .HasColumnType("smallint"); b.Property<int>("WaitTimeDays") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("GranteeId"); b.HasIndex("GrantorId"); b.ToTable("EmergencyAccess", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.Grant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("integer"); NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<int>("Id")); b.Property<string>("ClientId") .IsRequired() .HasMaxLength(200) .HasColumnType("character varying(200)"); b.Property<DateTime?>("ConsumedDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Data") .IsRequired() .HasColumnType("text"); b.Property<string>("Description") .HasMaxLength(200) .HasColumnType("character varying(200)"); b.Property<DateTime?>("ExpirationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Key") .IsRequired() .HasMaxLength(200) .HasColumnType("character varying(200)"); b.Property<string>("SessionId") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property<string>("SubjectId") .HasMaxLength(200) .HasColumnType("character varying(200)"); b.Property<string>("Type") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.HasKey("Id") .HasName("PK_Grant") .HasAnnotation("SqlServer:Clustered", true); b.HasIndex("ExpirationDate") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("Key") .IsUnique(); b.ToTable("Grant", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.SsoConfig", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id")); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Data") .HasColumnType("text"); b.Property<bool>("Enabled") .HasColumnType("boolean"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.ToTable("SsoConfig", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.SsoUser", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint"); NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property<long>("Id")); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("ExternalId") .HasMaxLength(50) .HasColumnType("character varying(50)") .UseCollation("postgresIndetermanisticCollation"); b.Property<Guid?>("OrganizationId") .HasColumnType("uuid"); b.Property<Guid>("UserId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("OrganizationId") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("UserId"); b.HasIndex("OrganizationId", "ExternalId") .IsUnique() .HasAnnotation("SqlServer:Clustered", false); NpgsqlIndexBuilderExtensions.IncludeProperties(b.HasIndex("OrganizationId", "ExternalId"), new[] { "UserId" }); b.HasIndex("OrganizationId", "UserId") .IsUnique() .HasAnnotation("SqlServer:Clustered", false); b.ToTable("SsoUser", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.WebAuthnCredential", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<Guid>("AaGuid") .HasColumnType("uuid"); b.Property<int>("Counter") .HasColumnType("integer"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("CredentialId") .HasMaxLength(256) .HasColumnType("character varying(256)"); b.Property<string>("EncryptedPrivateKey") .HasMaxLength(2000) .HasColumnType("character varying(2000)"); b.Property<string>("EncryptedPublicKey") .HasMaxLength(2000) .HasColumnType("character varying(2000)"); b.Property<string>("EncryptedUserKey") .HasMaxLength(2000) .HasColumnType("character varying(2000)"); b.Property<string>("Name") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("PublicKey") .HasMaxLength(256) .HasColumnType("character varying(256)"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<bool>("SupportsPrf") .HasColumnType("boolean"); b.Property<string>("Type") .HasMaxLength(20) .HasColumnType("character varying(20)"); b.Property<Guid>("UserId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("WebAuthnCredential", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Billing.Models.ProviderInvoiceItem", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<int>("AssignedSeats") .HasColumnType("integer"); b.Property<string>("ClientName") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<DateTime>("Created") .HasColumnType("timestamp with time zone"); b.Property<string>("InvoiceId") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("InvoiceNumber") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("PlanName") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<Guid>("ProviderId") .HasColumnType("uuid"); b.Property<decimal>("Total") .HasColumnType("numeric"); b.Property<int>("UsedSeats") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("ProviderId"); b.ToTable("ProviderInvoiceItem", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Billing.Models.ProviderPlan", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<int?>("AllocatedSeats") .HasColumnType("integer"); b.Property<byte>("PlanType") .HasColumnType("smallint"); b.Property<Guid>("ProviderId") .HasColumnType("uuid"); b.Property<int?>("PurchasedSeats") .HasColumnType("integer"); b.Property<int?>("SeatMinimum") .HasColumnType("integer"); b.HasKey("Id"); b.HasIndex("ProviderId"); b.HasIndex("Id", "PlanType") .IsUnique(); b.ToTable("ProviderPlan", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Cache", b => { b.Property<string>("Id") .HasMaxLength(449) .HasColumnType("character varying(449)"); b.Property<DateTime?>("AbsoluteExpiration") .HasColumnType("timestamp with time zone"); b.Property<DateTime>("ExpiresAtTime") .HasColumnType("timestamp with time zone"); b.Property<long?>("SlidingExpirationInSeconds") .HasColumnType("bigint"); b.Property<byte[]>("Value") .HasColumnType("bytea"); b.HasKey("Id") .HasAnnotation("SqlServer:Clustered", true); b.HasIndex("ExpiresAtTime") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Cache", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Collection", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("ExternalId") .HasMaxLength(300) .HasColumnType("character varying(300)"); b.Property<string>("Name") .IsRequired() .HasColumnType("text"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.ToTable("Collection", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionCipher", b => { b.Property<Guid>("CollectionId") .HasColumnType("uuid"); b.Property<Guid>("CipherId") .HasColumnType("uuid"); b.HasKey("CollectionId", "CipherId"); b.HasIndex("CipherId"); b.ToTable("CollectionCipher", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionGroup", b => { b.Property<Guid>("CollectionId") .HasColumnType("uuid"); b.Property<Guid>("GroupId") .HasColumnType("uuid"); b.Property<bool>("HidePasswords") .HasColumnType("boolean"); b.Property<bool>("Manage") .HasColumnType("boolean"); b.Property<bool>("ReadOnly") .HasColumnType("boolean"); b.HasKey("CollectionId", "GroupId"); b.HasIndex("GroupId"); b.ToTable("CollectionGroups"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionUser", b => { b.Property<Guid>("CollectionId") .HasColumnType("uuid"); b.Property<Guid>("OrganizationUserId") .HasColumnType("uuid"); b.Property<bool>("HidePasswords") .HasColumnType("boolean"); b.Property<bool>("Manage") .HasColumnType("boolean"); b.Property<bool>("ReadOnly") .HasColumnType("boolean"); b.HasKey("CollectionId", "OrganizationUserId"); b.HasIndex("OrganizationUserId"); b.ToTable("CollectionUsers"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Device", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("EncryptedPrivateKey") .HasColumnType("text"); b.Property<string>("EncryptedPublicKey") .HasColumnType("text"); b.Property<string>("EncryptedUserKey") .HasColumnType("text"); b.Property<string>("Identifier") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("Name") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("PushToken") .HasMaxLength(255) .HasColumnType("character varying(255)"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<byte>("Type") .HasColumnType("smallint"); b.Property<Guid>("UserId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("Identifier") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("UserId") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("UserId", "Identifier") .IsUnique() .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Device", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Event", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<Guid?>("ActingUserId") .HasColumnType("uuid"); b.Property<Guid?>("CipherId") .HasColumnType("uuid"); b.Property<Guid?>("CollectionId") .HasColumnType("uuid"); b.Property<DateTime>("Date") .HasColumnType("timestamp with time zone"); b.Property<byte?>("DeviceType") .HasColumnType("smallint"); b.Property<string>("DomainName") .HasColumnType("text"); b.Property<Guid?>("GroupId") .HasColumnType("uuid"); b.Property<Guid?>("InstallationId") .HasColumnType("uuid"); b.Property<string>("IpAddress") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<Guid?>("OrganizationId") .HasColumnType("uuid"); b.Property<Guid?>("OrganizationUserId") .HasColumnType("uuid"); b.Property<Guid?>("PolicyId") .HasColumnType("uuid"); b.Property<Guid?>("ProviderId") .HasColumnType("uuid"); b.Property<Guid?>("ProviderOrganizationId") .HasColumnType("uuid"); b.Property<Guid?>("ProviderUserId") .HasColumnType("uuid"); b.Property<Guid?>("SecretId") .HasColumnType("uuid"); b.Property<Guid?>("ServiceAccountId") .HasColumnType("uuid"); b.Property<byte?>("SystemUser") .HasColumnType("smallint"); b.Property<int>("Type") .HasColumnType("integer"); b.Property<Guid?>("UserId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("Date", "OrganizationId", "ActingUserId", "CipherId") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Event", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Group", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<bool>("AccessAll") .HasColumnType("boolean"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("ExternalId") .HasMaxLength(300) .HasColumnType("character varying(300)"); b.Property<string>("Name") .IsRequired() .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.ToTable("Group", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.GroupUser", b => { b.Property<Guid>("GroupId") .HasColumnType("uuid"); b.Property<Guid>("OrganizationUserId") .HasColumnType("uuid"); b.HasKey("GroupId", "OrganizationUserId"); b.HasIndex("OrganizationUserId"); b.ToTable("GroupUser", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Installation", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Email") .IsRequired() .HasMaxLength(256) .HasColumnType("character varying(256)"); b.Property<bool>("Enabled") .HasColumnType("boolean"); b.Property<string>("Key") .IsRequired() .HasMaxLength(150) .HasColumnType("character varying(150)"); b.HasKey("Id"); b.ToTable("Installation", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationApiKey", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<string>("ApiKey") .IsRequired() .HasMaxLength(30) .HasColumnType("character varying(30)"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<byte>("Type") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.ToTable("OrganizationApiKey", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationConnection", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<string>("Config") .HasColumnType("text"); b.Property<bool>("Enabled") .HasColumnType("boolean"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<byte>("Type") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.ToTable("OrganizationConnection", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationDomain", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("DomainName") .IsRequired() .HasMaxLength(255) .HasColumnType("character varying(255)"); b.Property<int>("JobRunCount") .HasColumnType("integer"); b.Property<DateTime?>("LastCheckedDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime>("NextRunDate") .HasColumnType("timestamp with time zone"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<string>("Txt") .IsRequired() .HasColumnType("text"); b.Property<DateTime?>("VerifiedDate") .HasColumnType("timestamp with time zone"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.ToTable("OrganizationDomain", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationSponsorship", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<string>("FriendlyName") .HasMaxLength(256) .HasColumnType("character varying(256)"); b.Property<DateTime?>("LastSyncDate") .HasColumnType("timestamp with time zone"); b.Property<string>("OfferedToEmail") .HasMaxLength(256) .HasColumnType("character varying(256)"); b.Property<byte?>("PlanSponsorshipType") .HasColumnType("smallint"); b.Property<Guid?>("SponsoredOrganizationId") .HasColumnType("uuid"); b.Property<Guid?>("SponsoringOrganizationId") .HasColumnType("uuid"); b.Property<Guid>("SponsoringOrganizationUserId") .HasColumnType("uuid"); b.Property<bool>("ToDelete") .HasColumnType("boolean"); b.Property<DateTime?>("ValidUntil") .HasColumnType("timestamp with time zone"); b.HasKey("Id"); b.HasIndex("SponsoredOrganizationId"); b.HasIndex("SponsoringOrganizationId"); b.HasIndex("SponsoringOrganizationUserId") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("OrganizationSponsorship", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<bool>("AccessAll") .HasColumnType("boolean"); b.Property<bool>("AccessSecretsManager") .HasColumnType("boolean"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Email") .HasMaxLength(256) .HasColumnType("character varying(256)"); b.Property<string>("ExternalId") .HasMaxLength(300) .HasColumnType("character varying(300)"); b.Property<string>("Key") .HasColumnType("text"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<string>("Permissions") .HasColumnType("text"); b.Property<string>("ResetPasswordKey") .HasColumnType("text"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<short>("Status") .HasColumnType("smallint"); b.Property<byte>("Type") .HasColumnType("smallint"); b.Property<Guid?>("UserId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("OrganizationId") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("UserId") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("UserId", "OrganizationId", "Status") .HasAnnotation("SqlServer:Clustered", false); NpgsqlIndexBuilderExtensions.IncludeProperties(b.HasIndex("UserId", "OrganizationId", "Status"), new[] { "AccessAll" }); b.ToTable("OrganizationUser", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Send", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<int>("AccessCount") .HasColumnType("integer"); b.Property<Guid?>("CipherId") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Data") .HasColumnType("text"); b.Property<DateTime>("DeletionDate") .HasColumnType("timestamp with time zone"); b.Property<bool>("Disabled") .HasColumnType("boolean"); b.Property<DateTime?>("ExpirationDate") .HasColumnType("timestamp with time zone"); b.Property<bool?>("HideEmail") .HasColumnType("boolean"); b.Property<string>("Key") .HasColumnType("text"); b.Property<int?>("MaxAccessCount") .HasColumnType("integer"); b.Property<Guid?>("OrganizationId") .HasColumnType("uuid"); b.Property<string>("Password") .HasMaxLength(300) .HasColumnType("character varying(300)"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<byte>("Type") .HasColumnType("smallint"); b.Property<Guid?>("UserId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("DeletionDate") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("OrganizationId"); b.HasIndex("UserId") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("UserId", "OrganizationId") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Send", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.TaxRate", b => { b.Property<string>("Id") .HasMaxLength(40) .HasColumnType("character varying(40)"); b.Property<bool>("Active") .HasColumnType("boolean"); b.Property<string>("Country") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("PostalCode") .IsRequired() .HasMaxLength(10) .HasColumnType("character varying(10)"); b.Property<decimal>("Rate") .HasColumnType("numeric"); b.Property<string>("State") .HasMaxLength(2) .HasColumnType("character varying(2)"); b.HasKey("Id"); b.ToTable("TaxRate", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Transaction", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<decimal>("Amount") .HasColumnType("numeric"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Details") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property<byte?>("Gateway") .HasColumnType("smallint"); b.Property<string>("GatewayId") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<Guid?>("OrganizationId") .HasColumnType("uuid"); b.Property<byte?>("PaymentMethodType") .HasColumnType("smallint"); b.Property<Guid?>("ProviderId") .HasColumnType("uuid"); b.Property<bool?>("Refunded") .HasColumnType("boolean"); b.Property<decimal?>("RefundedAmount") .HasColumnType("numeric"); b.Property<byte>("Type") .HasColumnType("smallint"); b.Property<Guid?>("UserId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.HasIndex("ProviderId"); b.HasIndex("UserId") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("UserId", "OrganizationId", "CreationDate") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Transaction", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.User", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("AccountRevisionDate") .HasColumnType("timestamp with time zone"); b.Property<string>("ApiKey") .IsRequired() .HasMaxLength(30) .HasColumnType("character varying(30)"); b.Property<string>("AvatarColor") .HasMaxLength(7) .HasColumnType("character varying(7)"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Culture") .IsRequired() .HasMaxLength(10) .HasColumnType("character varying(10)"); b.Property<string>("Email") .IsRequired() .HasMaxLength(256) .HasColumnType("character varying(256)") .UseCollation("postgresIndetermanisticCollation"); b.Property<bool>("EmailVerified") .HasColumnType("boolean"); b.Property<string>("EquivalentDomains") .HasColumnType("text"); b.Property<string>("ExcludedGlobalEquivalentDomains") .HasColumnType("text"); b.Property<int>("FailedLoginCount") .HasColumnType("integer"); b.Property<bool>("ForcePasswordReset") .HasColumnType("boolean"); b.Property<byte?>("Gateway") .HasColumnType("smallint"); b.Property<string>("GatewayCustomerId") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<string>("GatewaySubscriptionId") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<byte>("Kdf") .HasColumnType("smallint"); b.Property<int>("KdfIterations") .HasColumnType("integer"); b.Property<int?>("KdfMemory") .HasColumnType("integer"); b.Property<int?>("KdfParallelism") .HasColumnType("integer"); b.Property<string>("Key") .HasColumnType("text"); b.Property<DateTime?>("LastEmailChangeDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime?>("LastFailedLoginDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime?>("LastKdfChangeDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime?>("LastKeyRotationDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime?>("LastPasswordChangeDate") .HasColumnType("timestamp with time zone"); b.Property<string>("LicenseKey") .HasMaxLength(100) .HasColumnType("character varying(100)"); b.Property<string>("MasterPassword") .HasMaxLength(300) .HasColumnType("character varying(300)"); b.Property<string>("MasterPasswordHint") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<short?>("MaxStorageGb") .HasColumnType("smallint"); b.Property<string>("Name") .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<bool>("Premium") .HasColumnType("boolean"); b.Property<DateTime?>("PremiumExpirationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("PrivateKey") .HasColumnType("text"); b.Property<string>("PublicKey") .HasColumnType("text"); b.Property<string>("ReferenceData") .HasColumnType("text"); b.Property<DateTime?>("RenewalReminderDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<string>("SecurityStamp") .IsRequired() .HasMaxLength(50) .HasColumnType("character varying(50)"); b.Property<long?>("Storage") .HasColumnType("bigint"); b.Property<string>("TwoFactorProviders") .HasColumnType("text"); b.Property<string>("TwoFactorRecoveryCode") .HasMaxLength(32) .HasColumnType("character varying(32)"); b.Property<bool>("UsesKeyConnector") .HasColumnType("boolean"); b.HasKey("Id"); b.HasIndex("Email") .IsUnique() .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("Premium", "PremiumExpirationDate", "RenewalReminderDate") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("User", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Discriminator") .IsRequired() .HasMaxLength(34) .HasColumnType("character varying(34)"); b.Property<bool>("Read") .HasColumnType("boolean"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<bool>("Write") .HasColumnType("boolean"); b.HasKey("Id") .HasAnnotation("SqlServer:Clustered", true); b.ToTable("AccessPolicy", (string)null); b.HasDiscriminator<string>("Discriminator").HasValue("AccessPolicy"); b.UseTphMappingStrategy(); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ApiKey", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<string>("ClientSecretHash") .HasMaxLength(128) .HasColumnType("character varying(128)"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("EncryptedPayload") .IsRequired() .HasMaxLength(4000) .HasColumnType("character varying(4000)"); b.Property<DateTime?>("ExpireAt") .HasColumnType("timestamp with time zone"); b.Property<string>("Key") .IsRequired() .HasColumnType("text"); b.Property<string>("Name") .IsRequired() .HasMaxLength(200) .HasColumnType("character varying(200)"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Scope") .IsRequired() .HasMaxLength(4000) .HasColumnType("character varying(4000)"); b.Property<Guid?>("ServiceAccountId") .HasColumnType("uuid"); b.HasKey("Id") .HasAnnotation("SqlServer:Clustered", true); b.HasIndex("ServiceAccountId") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("ApiKey", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime?>("DeletedDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Name") .HasColumnType("text"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.HasKey("Id") .HasAnnotation("SqlServer:Clustered", true); b.HasIndex("DeletedDate") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("OrganizationId") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Project", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<DateTime?>("DeletedDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Key") .HasColumnType("text"); b.Property<string>("Note") .HasColumnType("text"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Value") .HasColumnType("text"); b.HasKey("Id") .HasAnnotation("SqlServer:Clustered", true); b.HasIndex("DeletedDate") .HasAnnotation("SqlServer:Clustered", false); b.HasIndex("OrganizationId") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("Secret", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Name") .HasColumnType("text"); b.Property<Guid>("OrganizationId") .HasColumnType("uuid"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.HasKey("Id") .HasAnnotation("SqlServer:Clustered", true); b.HasIndex("OrganizationId") .HasAnnotation("SqlServer:Clustered", false); b.ToTable("ServiceAccount", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Cipher", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<string>("Attachments") .HasColumnType("text"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Data") .HasColumnType("text"); b.Property<DateTime?>("DeletedDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Favorites") .HasColumnType("text"); b.Property<string>("Folders") .HasColumnType("text"); b.Property<string>("Key") .HasColumnType("text"); b.Property<Guid?>("OrganizationId") .HasColumnType("uuid"); b.Property<byte?>("Reprompt") .HasColumnType("smallint"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<byte>("Type") .HasColumnType("smallint"); b.Property<Guid?>("UserId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("OrganizationId"); b.HasIndex("UserId"); b.ToTable("Cipher", (string)null); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Folder", b => { b.Property<Guid>("Id") .HasColumnType("uuid"); b.Property<DateTime>("CreationDate") .HasColumnType("timestamp with time zone"); b.Property<string>("Name") .HasColumnType("text"); b.Property<DateTime>("RevisionDate") .HasColumnType("timestamp with time zone"); b.Property<Guid>("UserId") .HasColumnType("uuid"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("Folder", (string)null); }); modelBuilder.Entity("ProjectSecret", b => { b.Property<Guid>("ProjectsId") .HasColumnType("uuid"); b.Property<Guid>("SecretsId") .HasColumnType("uuid"); b.HasKey("ProjectsId", "SecretsId"); b.HasIndex("SecretsId"); b.ToTable("ProjectSecret"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupProjectAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedProjectId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("GrantedProjectId"); b.Property<Guid?>("GroupId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("GroupId"); b.HasIndex("GrantedProjectId"); b.HasIndex("GroupId"); b.HasDiscriminator().HasValue("group_project"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupSecretAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedSecretId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("GrantedSecretId"); b.Property<Guid?>("GroupId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("GroupId"); b.HasIndex("GrantedSecretId"); b.HasIndex("GroupId"); b.HasDiscriminator().HasValue("group_secret"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupServiceAccountAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedServiceAccountId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("GrantedServiceAccountId"); b.Property<Guid?>("GroupId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("GroupId"); b.HasIndex("GrantedServiceAccountId"); b.HasIndex("GroupId"); b.HasDiscriminator().HasValue("group_service_account"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccountProjectAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedProjectId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("GrantedProjectId"); b.Property<Guid?>("ServiceAccountId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("ServiceAccountId"); b.HasIndex("GrantedProjectId"); b.HasIndex("ServiceAccountId"); b.HasDiscriminator().HasValue("service_account_project"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccountSecretAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedSecretId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("GrantedSecretId"); b.Property<Guid?>("ServiceAccountId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("ServiceAccountId"); b.HasIndex("GrantedSecretId"); b.HasIndex("ServiceAccountId"); b.HasDiscriminator().HasValue("service_account_secret"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserProjectAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedProjectId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("GrantedProjectId"); b.Property<Guid?>("OrganizationUserId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("OrganizationUserId"); b.HasIndex("GrantedProjectId"); b.HasIndex("OrganizationUserId"); b.HasDiscriminator().HasValue("user_project"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserSecretAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedSecretId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("GrantedSecretId"); b.Property<Guid?>("OrganizationUserId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("OrganizationUserId"); b.HasIndex("GrantedSecretId"); b.HasIndex("OrganizationUserId"); b.HasDiscriminator().HasValue("user_secret"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserServiceAccountAccessPolicy", b => { b.HasBaseType("Bit.Infrastructure.EntityFramework.SecretsManager.Models.AccessPolicy"); b.Property<Guid?>("GrantedServiceAccountId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("GrantedServiceAccountId"); b.Property<Guid?>("OrganizationUserId") .ValueGeneratedOnUpdateSometimes() .HasColumnType("uuid") .HasColumnName("OrganizationUserId"); b.HasIndex("GrantedServiceAccountId"); b.HasIndex("OrganizationUserId"); b.HasDiscriminator().HasValue("user_service_account"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Policy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("Policies") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.ProviderOrganization", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany() .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", "Provider") .WithMany() .HasForeignKey("ProviderId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); b.Navigation("Provider"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.ProviderUser", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", "Provider") .WithMany() .HasForeignKey("ProviderId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany() .HasForeignKey("UserId"); b.Navigation("Provider"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.AuthRequest", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany() .HasForeignKey("OrganizationId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.Device", "ResponseDevice") .WithMany() .HasForeignKey("ResponseDeviceId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); b.Navigation("ResponseDevice"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.EmergencyAccess", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "Grantee") .WithMany() .HasForeignKey("GranteeId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "Grantor") .WithMany() .HasForeignKey("GrantorId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Grantee"); b.Navigation("Grantor"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.SsoConfig", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("SsoConfigs") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.SsoUser", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("SsoUsers") .HasForeignKey("OrganizationId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany("SsoUsers") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Auth.Models.WebAuthnCredential", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Billing.Models.ProviderInvoiceItem", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", "Provider") .WithMany() .HasForeignKey("ProviderId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Provider"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Billing.Models.ProviderPlan", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", "Provider") .WithMany() .HasForeignKey("ProviderId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Provider"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Collection", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("Collections") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionCipher", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Vault.Models.Cipher", "Cipher") .WithMany("CollectionCiphers") .HasForeignKey("CipherId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.Models.Collection", "Collection") .WithMany("CollectionCiphers") .HasForeignKey("CollectionId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Cipher"); b.Navigation("Collection"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionGroup", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Models.Collection", "Collection") .WithMany("CollectionGroups") .HasForeignKey("CollectionId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group") .WithMany() .HasForeignKey("GroupId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Collection"); b.Navigation("Group"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.CollectionUser", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Models.Collection", "Collection") .WithMany("CollectionUsers") .HasForeignKey("CollectionId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser") .WithMany("CollectionUsers") .HasForeignKey("OrganizationUserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Collection"); b.Navigation("OrganizationUser"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Device", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Group", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("Groups") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.GroupUser", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group") .WithMany("GroupUsers") .HasForeignKey("GroupId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser") .WithMany("GroupUsers") .HasForeignKey("OrganizationUserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Group"); b.Navigation("OrganizationUser"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationApiKey", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("ApiKeys") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationConnection", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("Connections") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationDomain", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("Domains") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationSponsorship", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "SponsoredOrganization") .WithMany() .HasForeignKey("SponsoredOrganizationId"); b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "SponsoringOrganization") .WithMany() .HasForeignKey("SponsoringOrganizationId"); b.Navigation("SponsoredOrganization"); b.Navigation("SponsoringOrganization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("OrganizationUsers") .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany("OrganizationUsers") .HasForeignKey("UserId"); b.Navigation("Organization"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Send", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany() .HasForeignKey("OrganizationId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany() .HasForeignKey("UserId"); b.Navigation("Organization"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Transaction", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("Transactions") .HasForeignKey("OrganizationId"); b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Provider.Provider", "Provider") .WithMany() .HasForeignKey("ProviderId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany("Transactions") .HasForeignKey("UserId"); b.Navigation("Organization"); b.Navigation("Provider"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ApiKey", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "ServiceAccount") .WithMany() .HasForeignKey("ServiceAccountId"); b.Navigation("ServiceAccount"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany() .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany() .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany() .HasForeignKey("OrganizationId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("Organization"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Cipher", b => { b.HasOne("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", "Organization") .WithMany("Ciphers") .HasForeignKey("OrganizationId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany("Ciphers") .HasForeignKey("UserId"); b.Navigation("Organization"); b.Navigation("User"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Folder", b => { b.HasOne("Bit.Infrastructure.EntityFramework.Models.User", "User") .WithMany("Folders") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.Navigation("User"); }); modelBuilder.Entity("ProjectSecret", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", null) .WithMany() .HasForeignKey("ProjectsId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", null) .WithMany() .HasForeignKey("SecretsId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupProjectAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", "GrantedProject") .WithMany("GroupAccessPolicies") .HasForeignKey("GrantedProjectId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group") .WithMany() .HasForeignKey("GroupId") .OnDelete(DeleteBehavior.Cascade); b.Navigation("GrantedProject"); b.Navigation("Group"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupSecretAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", "GrantedSecret") .WithMany("GroupAccessPolicies") .HasForeignKey("GrantedSecretId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group") .WithMany() .HasForeignKey("GroupId") .OnDelete(DeleteBehavior.Cascade); b.Navigation("GrantedSecret"); b.Navigation("Group"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.GroupServiceAccountAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "GrantedServiceAccount") .WithMany("GroupAccessPolicies") .HasForeignKey("GrantedServiceAccountId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.Group", "Group") .WithMany() .HasForeignKey("GroupId") .OnDelete(DeleteBehavior.Cascade); b.Navigation("GrantedServiceAccount"); b.Navigation("Group"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccountProjectAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", "GrantedProject") .WithMany("ServiceAccountAccessPolicies") .HasForeignKey("GrantedProjectId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "ServiceAccount") .WithMany() .HasForeignKey("ServiceAccountId"); b.Navigation("GrantedProject"); b.Navigation("ServiceAccount"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccountSecretAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", "GrantedSecret") .WithMany("ServiceAccountAccessPolicies") .HasForeignKey("GrantedSecretId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "ServiceAccount") .WithMany() .HasForeignKey("ServiceAccountId"); b.Navigation("GrantedSecret"); b.Navigation("ServiceAccount"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserProjectAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", "GrantedProject") .WithMany("UserAccessPolicies") .HasForeignKey("GrantedProjectId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser") .WithMany() .HasForeignKey("OrganizationUserId"); b.Navigation("GrantedProject"); b.Navigation("OrganizationUser"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserSecretAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", "GrantedSecret") .WithMany("UserAccessPolicies") .HasForeignKey("GrantedSecretId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser") .WithMany() .HasForeignKey("OrganizationUserId"); b.Navigation("GrantedSecret"); b.Navigation("OrganizationUser"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.UserServiceAccountAccessPolicy", b => { b.HasOne("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", "GrantedServiceAccount") .WithMany("UserAccessPolicies") .HasForeignKey("GrantedServiceAccountId"); b.HasOne("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", "OrganizationUser") .WithMany() .HasForeignKey("OrganizationUserId"); b.Navigation("GrantedServiceAccount"); b.Navigation("OrganizationUser"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.AdminConsole.Models.Organization", b => { b.Navigation("ApiKeys"); b.Navigation("Ciphers"); b.Navigation("Collections"); b.Navigation("Connections"); b.Navigation("Domains"); b.Navigation("Groups"); b.Navigation("OrganizationUsers"); b.Navigation("Policies"); b.Navigation("SsoConfigs"); b.Navigation("SsoUsers"); b.Navigation("Transactions"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Collection", b => { b.Navigation("CollectionCiphers"); b.Navigation("CollectionGroups"); b.Navigation("CollectionUsers"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.Group", b => { b.Navigation("GroupUsers"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.OrganizationUser", b => { b.Navigation("CollectionUsers"); b.Navigation("GroupUsers"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Models.User", b => { b.Navigation("Ciphers"); b.Navigation("Folders"); b.Navigation("OrganizationUsers"); b.Navigation("SsoUsers"); b.Navigation("Transactions"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Project", b => { b.Navigation("GroupAccessPolicies"); b.Navigation("ServiceAccountAccessPolicies"); b.Navigation("UserAccessPolicies"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.Secret", b => { b.Navigation("GroupAccessPolicies"); b.Navigation("ServiceAccountAccessPolicies"); b.Navigation("UserAccessPolicies"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.SecretsManager.Models.ServiceAccount", b => { b.Navigation("GroupAccessPolicies"); b.Navigation("UserAccessPolicies"); }); modelBuilder.Entity("Bit.Infrastructure.EntityFramework.Vault.Models.Cipher", b => { b.Navigation("CollectionCiphers"); }); #pragma warning restore 612, 618 } } }
UpdateNullConstraintsAdminConsole
csharp
ShareX__ShareX
ShareX/Forms/MainForm.cs
{ "start": 13338, "end": 91415 }
enum ____ doesn't. EndSessionReasons reason = (EndSessionReasons)m.LParam.ToInt64(); if (reason.HasFlag(EndSessionReasons.ENDSESSION_CLOSEAPP)) { // Register for restart. This allows our application to automatically restart when it is installing an update from the Store. // Also allows it to restart if it gets terminated for other reasons (see description of ENDSESSION_CLOSEAPP). // Add the silent switch to avoid ShareX popping up in front of the user when the application restarts. NativeMethods.RegisterApplicationRestart("-silent", 0); } m.Result = new IntPtr(1); // "Applications should respect the user's intentions and return TRUE." } else if (m.Msg == (int)WindowsMessages.ENDSESSION) { if (m.WParam != IntPtr.Zero) { // If wParam is not equal to false (0), the application can be terminated at any moment after processing this message // thus should save its data while processing the message. Program.CloseSequence(); } m.Result = IntPtr.Zero; // "If an application processes this message, it should return zero." } else { base.WndProc(ref m); } } private void AfterShownJobs() { if (!Program.Settings.ShowMostRecentTaskFirst && lvUploads.Items.Count > 0) { lvUploads.Items[lvUploads.Items.Count - 1].EnsureVisible(); } if (Program.SteamFirstTimeConfig) { using (FirstTimeConfigForm firstTimeConfigForm = new FirstTimeConfigForm()) { firstTimeConfigForm.ShowDialog(); } } else { this.ForceActivate(); } } private async Task InitHotkeys() { await Task.Run(() => SettingManager.WaitHotkeysConfig()); if (Program.HotkeyManager == null) { Program.HotkeyManager = new HotkeyManager(this); Program.HotkeyManager.HotkeyTrigger += HandleHotkeys; } Program.HotkeyManager.UpdateHotkeys(Program.HotkeysConfig.Hotkeys, !Program.IgnoreHotkeyWarning); DebugHelper.WriteLine("HotkeyManager started."); if (Program.WatchFolderManager == null) { Program.WatchFolderManager = new WatchFolderManager(); } Program.WatchFolderManager.UpdateWatchFolders(); DebugHelper.WriteLine("WatchFolderManager started."); UpdateWorkflowsMenu(); if (pHotkeys.Visible) { pHotkeys.Focus(); } } private async void HandleHotkeys(HotkeySettings hotkeySetting) { DebugHelper.WriteLine("Hotkey triggered. " + hotkeySetting); await TaskHelpers.ExecuteJob(hotkeySetting.TaskSettings); } private void UpdateWorkflowsMenu() { tsddbWorkflows.DropDownItems.Clear(); tsmiTrayWorkflows.DropDownItems.Clear(); foreach (HotkeySettings hotkeySetting in Program.HotkeysConfig.Hotkeys) { if (hotkeySetting.TaskSettings.Job != HotkeyType.None && (!Program.Settings.WorkflowsOnlyShowEdited || !hotkeySetting.TaskSettings.IsUsingDefaultSettings)) { tsddbWorkflows.DropDownItems.Add(WorkflowMenuItem(hotkeySetting)); tsmiTrayWorkflows.DropDownItems.Add(WorkflowMenuItem(hotkeySetting)); } } if (tsddbWorkflows.DropDownItems.Count > 0) { ToolStripSeparator tss = new ToolStripSeparator(); tsddbWorkflows.DropDownItems.Add(tss); } ToolStripMenuItem tsmi = new ToolStripMenuItem(Resources.MainForm_UpdateWorkflowsMenu_You_can_add_workflows_from_hotkey_settings___); tsmi.Click += tsbHotkeySettings_Click; tsddbWorkflows.DropDownItems.Add(tsmi); tsmiTrayWorkflows.Visible = tsmiTrayWorkflows.DropDownItems.Count > 0; UpdateMainFormTip(); } private void UpdateMainFormTip() { TaskManager.UpdateMainFormTip(); dgvHotkeys.Rows.Clear(); foreach (HotkeySettings hotkey in Program.HotkeysConfig.Hotkeys.Where(x => x.HotkeyInfo.IsValidHotkey)) { int index = dgvHotkeys.Rows.Add(); DataGridViewRow row = dgvHotkeys.Rows[index]; row.Cells[0].Style.BackColor = row.Cells[0].Style.SelectionBackColor = hotkey.HotkeyInfo.Status == HotkeyStatus.Registered ? Color.FromArgb(80, 160, 80) : Color.FromArgb(200, 80, 80); row.Cells[1].Value = hotkey.HotkeyInfo.ToString(); row.Cells[2].Value = hotkey.TaskSettings.ToString(); } } private ToolStripMenuItem WorkflowMenuItem(HotkeySettings hotkeySetting) { ToolStripMenuItem tsmi = new ToolStripMenuItem(); tsmi.Text = hotkeySetting.TaskSettings.ToString().Replace("&", "&&"); if (!hotkeySetting.TaskSettings.IsUsingDefaultSettings) { tsmi.Text += "*"; } if (hotkeySetting.HotkeyInfo.IsValidHotkey) { tsmi.ShortcutKeyDisplayString = " " + hotkeySetting.HotkeyInfo; } tsmi.Image = TaskHelpers.FindMenuIcon(hotkeySetting.TaskSettings.Job); tsmi.Click += async (sender, e) => await TaskHelpers.ExecuteJob(hotkeySetting.TaskSettings); return tsmi; } private void UpdateDestinationStates() { if (Program.UploadersConfig != null) { EnableDisableToolStripMenuItems<ImageDestination>(tsmiImageUploaders, tsmiTrayImageUploaders); EnableDisableToolStripMenuItems<FileDestination>(tsmiImageFileUploaders, tsmiTrayImageFileUploaders); EnableDisableToolStripMenuItems<TextDestination>(tsmiTextUploaders, tsmiTrayTextUploaders); EnableDisableToolStripMenuItems<FileDestination>(tsmiTextFileUploaders, tsmiTrayTextFileUploaders); EnableDisableToolStripMenuItems<FileDestination>(tsmiFileUploaders, tsmiTrayFileUploaders); EnableDisableToolStripMenuItems<UrlShortenerType>(tsmiURLShorteners, tsmiTrayURLShorteners); EnableDisableToolStripMenuItems<URLSharingServices>(tsmiURLSharingServices, tsmiTrayURLSharingServices); } } private void AddEnumItems<T>(Action<T> selectedEnum, params ToolStripDropDownItem[] parents) where T : Enum { T[] enums = Helpers.GetEnums<T>(); foreach (ToolStripDropDownItem parent in parents) { for (int i = 0; i < enums.Length; i++) { T currentEnum = enums[i]; ToolStripMenuItem tsmi = new ToolStripMenuItem(currentEnum.GetLocalizedDescription()); int index = i; tsmi.Click += (sender, e) => { foreach (ToolStripDropDownItem parent2 in parents) { for (int i2 = 0; i2 < enums.Length; i2++) { ToolStripMenuItem tsmi2 = (ToolStripMenuItem)parent2.DropDownItems[i2]; tsmi2.Checked = index == i2; } } selectedEnum(currentEnum); UpdateUploaderMenuNames(); }; parent.DropDownItems.Add(tsmi); } } } public static void Uncheck(params ToolStripDropDownItem[] lists) { foreach (ToolStripDropDownItem parent in lists) { foreach (ToolStripItem dropDownItem in parent.DropDownItems) { ((ToolStripMenuItem)dropDownItem).Checked = false; } } } private static void SetEnumChecked(Enum value, params ToolStripDropDownItem[] parents) { if (value == null) { return; } int index = value.GetIndex(); foreach (ToolStripDropDownItem parent in parents) { ((ToolStripMenuItem)parent.DropDownItems[index]).RadioCheck(); } } private void AddMultiEnumItems<T>(Action<T> selectedEnum, ToolStripDropDownItem[] parents, T[] ignoreEnums = null) where T : Enum { if (ignoreEnums == null) { ignoreEnums = new T[0]; } T[] enums = Helpers.GetEnums<T>().Skip(1).Except(ignoreEnums).ToArray(); foreach (ToolStripDropDownItem parent in parents) { for (int i = 0; i < enums.Length; i++) { T currentEnum = enums[i]; ToolStripMenuItem tsmi = new ToolStripMenuItem(currentEnum.GetLocalizedDescription()); tsmi.Tag = currentEnum; tsmi.Image = TaskHelpers.FindMenuIcon(currentEnum); int index = i; tsmi.Click += (sender, e) => { foreach (ToolStripDropDownItem parent2 in parents) { ToolStripMenuItem tsmi2 = (ToolStripMenuItem)parent2.DropDownItems[index]; tsmi2.Checked = !tsmi2.Checked; } selectedEnum(currentEnum); }; parent.DropDownItems.Add(tsmi); } } } private void UpdateImageEffectsMenu(ToolStripDropDownItem parent) { int indexAddImageEffects = AfterCaptureTasks.AddImageEffects.GetIndex() - 1; ToolStripMenuItem tsmiAddImageEffects = (ToolStripMenuItem)parent.DropDownItems[indexAddImageEffects]; tsmiAddImageEffects.DisableMenuCloseOnClick(); tsmiAddImageEffects.DropDownItems.Clear(); if (Program.DefaultTaskSettings.ImageSettings.ImageEffectPresets == null) { Program.DefaultTaskSettings.ImageSettings.ImageEffectPresets = new List<ImageEffectPreset>(); } int count = Program.DefaultTaskSettings.ImageSettings.ImageEffectPresets.Count; if (count > 0) { List<ToolStripItem> items = new List<ToolStripItem>(); for (int i = 0; i < count; i++) { ImageEffectPreset effectPreset = Program.DefaultTaskSettings.ImageSettings.ImageEffectPresets[i]; if (effectPreset != null) { ToolStripMenuItem tsmi = new ToolStripMenuItem(effectPreset.ToString()); tsmi.Checked = i == Program.DefaultTaskSettings.ImageSettings.SelectedImageEffectPreset; int indexSelected = i; tsmi.Click += (sender, e) => { Program.DefaultTaskSettings.ImageSettings.SelectedImageEffectPreset = indexSelected; ((ToolStripMenuItem)sender).RadioCheck(); }; items.Add(tsmi); } } if (items.Count > 0) { tsmiAddImageEffects.DropDownItems.AddRange(items.ToArray()); } } } private void SetMultiEnumChecked(Enum value, params ToolStripDropDownItem[] parents) { for (int i = 0; i < parents[0].DropDownItems.Count; i++) { foreach (ToolStripDropDownItem parent in parents) { ToolStripMenuItem tsmi = (ToolStripMenuItem)parent.DropDownItems[i]; tsmi.Checked = value.HasFlag(1 << i); } } } private void EnableDisableToolStripMenuItems<T>(params ToolStripDropDownItem[] parents) { foreach (ToolStripDropDownItem parent in parents) { for (int i = 0; i < parent.DropDownItems.Count; i++) { parent.DropDownItems[i].ForeColor = UploadersConfigValidator.Validate<T>(i, Program.UploadersConfig) ? SystemColors.ControlText : Color.FromArgb(200, 0, 0); } } } private void UpdateInfoManager() { cmsTaskInfo.SuspendLayout(); tsmiStopUpload.Visible = tsmiOpen.Visible = tsmiCopy.Visible = tsmiShowErrors.Visible = tsmiShowResponse.Visible = tsmiAnalyzeImage.Visible = tsmiGoogleLens.Visible = tsmiBingVisualSearch.Visible = tsmiShowQRCode.Visible = tsmiOCRImage.Visible = tsmiCombineImages.Visible = tsmiUploadSelectedFile.Visible = tsmiDownloadSelectedURL.Visible = tsmiEditSelectedFile.Visible = tsmiBeautifyImage.Visible = tsmiAddImageEffects.Visible = tsmiPinSelectedFile.Visible = tsmiRunAction.Visible = tsmiDeleteSelectedItem.Visible = tsmiDeleteSelectedFile.Visible = tsmiShortenSelectedURL.Visible = tsmiShareSelectedURL.Visible = false; if (Program.Settings.TaskViewMode == TaskViewMode.ListView) { pbPreview.Reset(); uim.UpdateSelectedItems(lvUploads.SelectedItems.Cast<ListViewItem>().Select(x => x.Tag as WorkerTask)); switch (Program.Settings.ImagePreview) { case ImagePreviewVisibility.Show: scMain.Panel2Collapsed = false; break; case ImagePreviewVisibility.Hide: scMain.Panel2Collapsed = true; break; case ImagePreviewVisibility.Automatic: scMain.Panel2Collapsed = !uim.IsItemSelected || (!uim.SelectedItem.IsImageFile && !uim.SelectedItem.IsImageURL); break; } switch (Program.Settings.ImagePreviewLocation) { case ImagePreviewLocation.Side: scMain.Orientation = Orientation.Vertical; break; case ImagePreviewLocation.Bottom: scMain.Orientation = Orientation.Horizontal; break; } } else if (Program.Settings.TaskViewMode == TaskViewMode.ThumbnailView) { uim.UpdateSelectedItems(ucTaskThumbnailView.SelectedPanels.Select(x => x.Task)); } if (uim.IsItemSelected) { // Open tsmiOpen.Visible = true; tsmiOpenURL.Enabled = uim.SelectedItem.IsURLExist; tsmiOpenShortenedURL.Enabled = uim.SelectedItem.IsShortenedURLExist; tsmiOpenThumbnailURL.Enabled = uim.SelectedItem.IsThumbnailURLExist; tsmiOpenDeletionURL.Enabled = uim.SelectedItem.IsDeletionURLExist; tsmiOpenFile.Enabled = uim.SelectedItem.IsFileExist; tsmiOpenFolder.Enabled = uim.SelectedItem.IsFileExist; tsmiOpenThumbnailFile.Enabled = uim.SelectedItem.IsThumbnailFileExist; if (uim.SelectedItems != null && uim.SelectedItems.Any(x => x.Task.IsWorking)) { tsmiStopUpload.Visible = true; } else { tsmiShowErrors.Visible = uim.SelectedItem.Info.Result.IsError; // Copy tsmiCopy.Visible = true; tsmiCopyURL.Enabled = uim.SelectedItems.Any(x => x.IsURLExist); tsmiCopyShortenedURL.Enabled = uim.SelectedItems.Any(x => x.IsShortenedURLExist); tsmiCopyThumbnailURL.Enabled = uim.SelectedItems.Any(x => x.IsThumbnailURLExist); tsmiCopyDeletionURL.Enabled = uim.SelectedItems.Any(x => x.IsDeletionURLExist); tsmiCopyFile.Enabled = uim.SelectedItem.IsFileExist; tsmiCopyImage.Enabled = uim.SelectedItem.IsImageFile; tsmiCopyImageDimensions.Enabled = uim.SelectedItem.IsImageFile; tsmiCopyText.Enabled = uim.SelectedItem.IsTextFile; tsmiCopyThumbnailFile.Enabled = uim.SelectedItem.IsThumbnailFileExist; tsmiCopyThumbnailImage.Enabled = uim.SelectedItem.IsThumbnailFileExist; tsmiCopyHTMLLink.Enabled = uim.SelectedItems.Any(x => x.IsURLExist); tsmiCopyHTMLImage.Enabled = uim.SelectedItems.Any(x => x.IsImageURL); tsmiCopyHTMLLinkedImage.Enabled = uim.SelectedItems.Any(x => x.IsImageURL && x.IsThumbnailURLExist); tsmiCopyForumLink.Enabled = uim.SelectedItems.Any(x => x.IsURLExist); tsmiCopyForumImage.Enabled = uim.SelectedItems.Any(x => x.IsImageURL && x.IsURLExist); tsmiCopyForumLinkedImage.Enabled = uim.SelectedItems.Any(x => x.IsImageURL && x.IsThumbnailURLExist); tsmiCopyMarkdownLink.Enabled = uim.SelectedItems.Any(x => x.IsURLExist); tsmiCopyMarkdownImage.Enabled = uim.SelectedItems.Any(x => x.IsImageURL); tsmiCopyMarkdownLinkedImage.Enabled = uim.SelectedItems.Any(x => x.IsImageURL && x.IsThumbnailURLExist); tsmiCopyFilePath.Enabled = uim.SelectedItems.Any(x => x.IsFilePathValid); tsmiCopyFileName.Enabled = uim.SelectedItems.Any(x => x.IsFilePathValid); tsmiCopyFileNameWithExtension.Enabled = uim.SelectedItems.Any(x => x.IsFilePathValid); tsmiCopyFolder.Enabled = uim.SelectedItems.Any(x => x.IsFilePathValid); CleanCustomClipboardFormats(); if (Program.Settings.ClipboardContentFormats != null && Program.Settings.ClipboardContentFormats.Count > 0) { tssCopy6.Visible = true; foreach (ClipboardFormat cf in Program.Settings.ClipboardContentFormats) { ToolStripMenuItem tsmiClipboardFormat = new ToolStripMenuItem(cf.Description); tsmiClipboardFormat.Tag = cf; tsmiClipboardFormat.Click += tsmiClipboardFormat_Click; tsmiCopy.DropDownItems.Add(tsmiClipboardFormat); } } tsmiUploadSelectedFile.Visible = !SystemOptions.DisableUpload && uim.SelectedItem.IsFileExist; tsmiDownloadSelectedURL.Visible = uim.SelectedItem.IsFileURL; tsmiEditSelectedFile.Visible = uim.SelectedItem.IsImageFile; tsmiBeautifyImage.Visible = uim.SelectedItem.IsImageFile; tsmiAddImageEffects.Visible = uim.SelectedItem.IsImageFile; tsmiPinSelectedFile.Visible = uim.SelectedItem.IsImageFile; UpdateActionsMenu(uim.SelectedItem.Info.FilePath); tsmiDeleteSelectedItem.Visible = true; tsmiDeleteSelectedFile.Visible = uim.SelectedItem.IsFileExist; tsmiShortenSelectedURL.Visible = !SystemOptions.DisableUpload && uim.SelectedItem.IsURLExist; tsmiShareSelectedURL.Visible = !SystemOptions.DisableUpload && uim.SelectedItem.IsURLExist; tsmiAnalyzeImage.Visible = uim.SelectedItem.IsImageFile; tsmiGoogleLens.Visible = uim.SelectedItem.IsURLExist; tsmiBingVisualSearch.Visible = uim.SelectedItem.IsURLExist; tsmiShowQRCode.Visible = uim.SelectedItem.IsURLExist; tsmiOCRImage.Visible = uim.SelectedItem.IsImageFile; tsmiCombineImages.Visible = uim.SelectedItems.Count(x => x.IsImageFile) > 1; tsmiShowResponse.Visible = !string.IsNullOrEmpty(uim.SelectedItem.Info.Result.Response); } if (Program.Settings.TaskViewMode == TaskViewMode.ListView) { if (!scMain.Panel2Collapsed) { if (uim.SelectedItem.IsImageFile) { pbPreview.LoadImageFromFileAsync(uim.SelectedItem.Info.FilePath); } else if (uim.SelectedItem.IsImageURL) { pbPreview.LoadImageFromURLAsync(uim.SelectedItem.Info.Result.URL); } } } } tsmiClearList.Visible = tssUploadInfo1.Visible = lvUploads.Items.Count > 0; cmsTaskInfo.ResumeLayout(); Refresh(); } private void UpdateTaskViewMode() { if (Program.Settings.TaskViewMode == TaskViewMode.ListView) { tsmiSwitchTaskViewMode.Text = Resources.SwitchToThumbnailView; tsmiSwitchTaskViewMode.Image = Resources.application_icon_large; scMain.Visible = true; ucTaskThumbnailView.Visible = false; scMain.Focus(); } else { tsmiSwitchTaskViewMode.Text = Resources.SwitchToListView; tsmiSwitchTaskViewMode.Image = Resources.application_list; ucTaskThumbnailView.Visible = true; scMain.Visible = false; ucTaskThumbnailView.Focus(); } } public void UpdateTheme() { if (Program.Settings.Themes == null || Program.Settings.Themes.Count == 0) { Program.Settings.Themes = ShareXTheme.GetDefaultThemes(); Program.Settings.SelectedTheme = 0; } if (!Program.Settings.Themes.IsValidIndex(Program.Settings.SelectedTheme)) { Program.Settings.SelectedTheme = 0; } ShareXResources.Theme = Program.Settings.Themes[Program.Settings.SelectedTheme]; if (IsHandleCreated) { NativeMethods.UseImmersiveDarkMode(Handle, ShareXResources.IsDarkTheme); } #pragma warning disable WFO5001 if (ShareXResources.IsDarkTheme) { Application.SetColorMode(SystemColorMode.Dark); } else { Application.SetColorMode(SystemColorMode.Classic); } #pragma warning restore WFO5001 BackColor = ShareXResources.Theme.BackgroundColor; tsMain.Font = ShareXResources.Theme.MenuFont; tsMain.Renderer = new ToolStripDarkRenderer(); tsMain.DrawCustomBorder = false; ShareXResources.ApplyCustomThemeToContextMenuStrip(cmsTray); ShareXResources.ApplyCustomThemeToContextMenuStrip(cmsTaskInfo); ttMain.BackColor = ShareXResources.Theme.BackgroundColor; ttMain.ForeColor = ShareXResources.Theme.TextColor; lvUploads.BackColor = ShareXResources.Theme.BackgroundColor; lvUploads.ForeColor = ShareXResources.Theme.TextColor; scMain.SplitterColor = ShareXResources.Theme.BackgroundColor; scMain.SplitterLineColor = ShareXResources.Theme.BorderColor; ShareXResources.ApplyCustomThemeToControl(dgvHotkeys); dgvHotkeys.BackgroundColor = ShareXResources.Theme.BackgroundColor; tsbX.Image = ShareXResources.IsDarkTheme ? Resources.X_white : Resources.X_black; tsbDiscord.Image = ShareXResources.IsDarkTheme ? Resources.Discord_white : Resources.Discord_black; tsmiQRCode.Image = TaskHelpers.FindMenuIcon(HotkeyType.QRCode); tsmiTrayQRCode.Image = TaskHelpers.FindMenuIcon(HotkeyType.QRCode); tsmiShowQRCode.Image = TaskHelpers.FindMenuIcon(HotkeyType.QRCode); tsmiOCR.Image = TaskHelpers.FindMenuIcon(HotkeyType.OCR); tsmiTrayOCR.Image = TaskHelpers.FindMenuIcon(HotkeyType.OCR); tsmiOCRImage.Image = TaskHelpers.FindMenuIcon(HotkeyType.OCR); tsmiShortenURL.Image = TaskHelpers.FindMenuIcon(HotkeyType.ShortenURL); tsmiTrayShortenURL.Image = TaskHelpers.FindMenuIcon(HotkeyType.ShortenURL); tsmiURLShorteners.Image = TaskHelpers.FindMenuIcon(HotkeyType.ShortenURL); tsmiTrayURLShorteners.Image = TaskHelpers.FindMenuIcon(HotkeyType.ShortenURL); tsmiTestURLShortener.Image = TaskHelpers.FindMenuIcon(HotkeyType.ShortenURL); tsmiShortenSelectedURL.Image = TaskHelpers.FindMenuIcon(HotkeyType.ShortenURL); pbPreview.UpdateTheme(); pbPreview.UpdateCheckers(true); ucTaskThumbnailView.UpdateTheme(); } private void CleanCustomClipboardFormats() { tssCopy6.Visible = false; int tssCopy6Index = tsmiCopy.DropDownItems.IndexOf(tssCopy6); while (tssCopy6Index < tsmiCopy.DropDownItems.Count - 1) { using (ToolStripItem tsi = tsmiCopy.DropDownItems[tsmiCopy.DropDownItems.Count - 1]) { tsmiCopy.DropDownItems.Remove(tsi); } } } private void UpdateActionsMenu(string filePath) { tsmiRunAction.DropDownItems.Clear(); if (!string.IsNullOrEmpty(filePath) && File.Exists(filePath)) { IEnumerable<ExternalProgram> actions = Program.DefaultTaskSettings.ExternalPrograms. Where(x => !string.IsNullOrEmpty(x.Name) && x.CheckExtension(filePath)); if (actions.Count() > 0) { tsmiRunAction.Visible = true; foreach (ExternalProgram action in actions) { string name = action.Name.Truncate(50, "..."); ToolStripMenuItem tsmi = new ToolStripMenuItem(name); try { string actionFilePath = action.GetFullPath(); tsmi.Image = actionsMenuIconCache.GetFileIconAsImage(actionFilePath); } catch { } tsmi.Click += async (sender, e) => await action.RunAsync(filePath); tsmiRunAction.DropDownItems.Add(tsmi); } } } } private void AfterApplicationSettingsJobs() { HotkeyRepeatLimit = Program.Settings.HotkeyRepeatLimit; HelpersOptions.CurrentProxy = Program.Settings.ProxySettings; HelpersOptions.URLEncodeIgnoreEmoji = Program.Settings.URLEncodeIgnoreEmoji; HelpersOptions.DefaultCopyImageFillBackground = Program.Settings.DefaultClipboardCopyImageFillBackground; HelpersOptions.UseAlternativeClipboardCopyImage = Program.Settings.UseAlternativeClipboardCopyImage; HelpersOptions.UseAlternativeClipboardGetImage = Program.Settings.UseAlternativeClipboardGetImage; HelpersOptions.RotateImageByExifOrientationData = Program.Settings.RotateImageByExifOrientationData; HelpersOptions.BrowserPath = Program.Settings.BrowserPath; HelpersOptions.RecentColors = Program.Settings.RecentColors; HelpersOptions.DevMode = Program.Settings.DevMode; Program.UpdateHelpersSpecialFolders(); TaskManager.RecentManager.MaxCount = Program.Settings.RecentTasksMaxCount; UpdateTheme(); Refresh(); if (ShareXResources.UseWhiteIcon != Program.Settings.UseWhiteShareXIcon) { ShareXResources.UseWhiteIcon = Program.Settings.UseWhiteShareXIcon; Icon = ShareXResources.Icon; niTray.Icon = ShareXResources.Icon; } Text = Program.Title; niTray.Text = Program.TitleShort; tsmiRestartAsAdmin.Visible = HelpersOptions.DevMode && !Helpers.IsAdministrator(); #if RELEASE ConfigureAutoUpdate(); #else if (UpdateChecker.ForceUpdate) { ConfigureAutoUpdate(); } #endif UpdateTaskViewMode(); UpdateMainWindowLayout(); UpdateInfoManager(); } private void ConfigureAutoUpdate() { Program.UpdateManager.AllowAutoUpdate = !SystemOptions.DisableUpdateCheck && Program.Settings.AutoCheckUpdate; Program.UpdateManager.UpdateChannel = Program.Settings.UpdateChannel; Program.UpdateManager.ConfigureAutoUpdate(); } private void AfterTaskSettingsJobs() { tsmiShowCursor.Checked = tsmiTrayShowCursor.Checked = Program.DefaultTaskSettings.CaptureSettings.ShowCursor; SetScreenshotDelay(Program.DefaultTaskSettings.CaptureSettings.ScreenshotDelay); } public void UpdateCheckStates() { SetMultiEnumChecked(Program.DefaultTaskSettings.AfterCaptureJob, tsddbAfterCaptureTasks, tsmiTrayAfterCaptureTasks); SetMultiEnumChecked(Program.DefaultTaskSettings.AfterUploadJob, tsddbAfterUploadTasks, tsmiTrayAfterUploadTasks); SetEnumChecked(Program.DefaultTaskSettings.ImageDestination, tsmiImageUploaders, tsmiTrayImageUploaders); SetImageFileDestinationChecked(Program.DefaultTaskSettings.ImageDestination, Program.DefaultTaskSettings.ImageFileDestination, tsmiImageFileUploaders, tsmiTrayImageFileUploaders); SetEnumChecked(Program.DefaultTaskSettings.TextDestination, tsmiTextUploaders, tsmiTrayTextUploaders); SetTextFileDestinationChecked(Program.DefaultTaskSettings.TextDestination, Program.DefaultTaskSettings.TextFileDestination, tsmiTextFileUploaders, tsmiTrayTextFileUploaders); SetEnumChecked(Program.DefaultTaskSettings.FileDestination, tsmiFileUploaders, tsmiTrayFileUploaders); SetEnumChecked(Program.DefaultTaskSettings.URLShortenerDestination, tsmiURLShorteners, tsmiTrayURLShorteners); SetEnumChecked(Program.DefaultTaskSettings.URLSharingServiceDestination, tsmiURLSharingServices, tsmiTrayURLSharingServices); } public static void SetTextFileDestinationChecked(TextDestination textDestination, FileDestination textFileDestination, params ToolStripDropDownItem[] lists) { if (textDestination == TextDestination.FileUploader) { SetEnumChecked(textFileDestination, lists); } else { Uncheck(lists); } } public static void SetImageFileDestinationChecked(ImageDestination imageDestination, FileDestination imageFileDestination, params ToolStripDropDownItem[] lists) { if (imageDestination == ImageDestination.FileUploader) { SetEnumChecked(imageFileDestination, lists); } else { Uncheck(lists); } } public void UpdateUploaderMenuNames() { string imageUploader = Program.DefaultTaskSettings.ImageDestination == ImageDestination.FileUploader ? Program.DefaultTaskSettings.ImageFileDestination.GetLocalizedDescription() : Program.DefaultTaskSettings.ImageDestination.GetLocalizedDescription(); tsmiImageUploaders.Text = tsmiTrayImageUploaders.Text = string.Format(Resources.TaskSettingsForm_UpdateUploaderMenuNames_Image_uploader___0_, imageUploader); string textUploader = Program.DefaultTaskSettings.TextDestination == TextDestination.FileUploader ? Program.DefaultTaskSettings.TextFileDestination.GetLocalizedDescription() : Program.DefaultTaskSettings.TextDestination.GetLocalizedDescription(); tsmiTextUploaders.Text = tsmiTrayTextUploaders.Text = string.Format(Resources.TaskSettingsForm_UpdateUploaderMenuNames_Text_uploader___0_, textUploader); tsmiFileUploaders.Text = tsmiTrayFileUploaders.Text = string.Format(Resources.TaskSettingsForm_UpdateUploaderMenuNames_File_uploader___0_, Program.DefaultTaskSettings.FileDestination.GetLocalizedDescription()); tsmiURLShorteners.Text = tsmiTrayURLShorteners.Text = string.Format(Resources.TaskSettingsForm_UpdateUploaderMenuNames_URL_shortener___0_, Program.DefaultTaskSettings.URLShortenerDestination.GetLocalizedDescription()); tsmiURLSharingServices.Text = tsmiTrayURLSharingServices.Text = string.Format(Resources.TaskSettingsForm_UpdateUploaderMenuNames_URL_sharing_service___0_, Program.DefaultTaskSettings.URLSharingServiceDestination.GetLocalizedDescription()); } private WorkerTask[] GetSelectedTasks() { if (lvUploads.SelectedItems.Count > 0) { return lvUploads.SelectedItems.Cast<ListViewItem>().Select(x => x.Tag as WorkerTask).Where(x => x != null).ToArray(); } return null; } private void RemoveTasks(WorkerTask[] tasks) { if (tasks != null) { foreach (WorkerTask task in tasks.Where(x => x != null && !x.IsWorking)) { TaskManager.Remove(task); } UpdateInfoManager(); } } private void RemoveSelectedItems() { IEnumerable<WorkerTask> tasks = null; if (Program.Settings.TaskViewMode == TaskViewMode.ListView) { tasks = lvUploads.SelectedItems.Cast<ListViewItem>().Select(x => x.Tag as WorkerTask); } else if (Program.Settings.TaskViewMode == TaskViewMode.ThumbnailView) { tasks = ucTaskThumbnailView.SelectedPanels.Select(x => x.Task); } RemoveTasks(tasks.ToArray()); } private void RemoveAllItems() { RemoveTasks(lvUploads.Items.Cast<ListViewItem>().Select(x => x.Tag as WorkerTask).ToArray()); } private void UpdateMainWindowLayout() { tsMain.Visible = Program.Settings.ShowMenu; ucTaskThumbnailView.TitleVisible = Program.Settings.ShowThumbnailTitle; ucTaskThumbnailView.TitleLocation = Program.Settings.ThumbnailTitleLocation; ucTaskThumbnailView.ThumbnailSize = Program.Settings.ThumbnailSize; ucTaskThumbnailView.ClickAction = Program.Settings.ThumbnailClickAction; lvUploads.HeaderStyle = Program.Settings.ShowColumns ? ColumnHeaderStyle.Nonclickable : ColumnHeaderStyle.None; Refresh(); } public void UpdateToggleHotkeyButton() { if (Program.Settings.DisableHotkeys) { tsmiTrayToggleHotkeys.Text = Resources.MainForm_UpdateToggleHotkeyButton_Enable_hotkeys; tsmiTrayToggleHotkeys.Image = Resources.keyboard__plus; } else { tsmiTrayToggleHotkeys.Text = Resources.MainForm_UpdateToggleHotkeyButton_Disable_hotkeys; tsmiTrayToggleHotkeys.Image = Resources.keyboard__minus; } } private void RunPuushTasks() { if (Program.PuushMode && Program.Settings.IsFirstTimeRun) { using (PuushLoginForm puushLoginForm = new PuushLoginForm()) { if (puushLoginForm.ShowDialog() == DialogResult.OK) { Program.DefaultTaskSettings.ImageDestination = ImageDestination.FileUploader; Program.DefaultTaskSettings.ImageFileDestination = FileDestination.Puush; Program.DefaultTaskSettings.TextDestination = TextDestination.FileUploader; Program.DefaultTaskSettings.TextFileDestination = FileDestination.Puush; Program.DefaultTaskSettings.FileDestination = FileDestination.Puush; SettingManager.WaitUploadersConfig(); if (Program.UploadersConfig != null) { Program.UploadersConfig.PuushAPIKey = puushLoginForm.APIKey; } } } } } private void SetScreenshotDelay(decimal delay) { Program.DefaultTaskSettings.CaptureSettings.ScreenshotDelay = delay; switch (delay) { default: tsmiScreenshotDelay.UpdateCheckedAll(false); tsmiTrayScreenshotDelay.UpdateCheckedAll(false); break; case 0: tsmiScreenshotDelay0.RadioCheck(); tsmiTrayScreenshotDelay0.RadioCheck(); break; case 1: tsmiScreenshotDelay1.RadioCheck(); tsmiTrayScreenshotDelay1.RadioCheck(); break; case 2: tsmiScreenshotDelay2.RadioCheck(); tsmiTrayScreenshotDelay2.RadioCheck(); break; case 3: tsmiScreenshotDelay3.RadioCheck(); tsmiTrayScreenshotDelay3.RadioCheck(); break; case 4: tsmiScreenshotDelay4.RadioCheck(); tsmiTrayScreenshotDelay4.RadioCheck(); break; case 5: tsmiScreenshotDelay5.RadioCheck(); tsmiTrayScreenshotDelay5.RadioCheck(); break; } tsmiScreenshotDelay.Text = tsmiTrayScreenshotDelay.Text = string.Format(Resources.ScreenshotDelay0S, delay.ToString("0.#")); tsmiScreenshotDelay.Checked = tsmiTrayScreenshotDelay.Checked = delay > 0; } private async Task PrepareCaptureMenuAsync(ToolStripMenuItem tsmiWindow, EventHandler handlerWindow, ToolStripMenuItem tsmiMonitor, EventHandler handlerMonitor) { tsmiWindow.DropDownItems.Clear(); WindowsList windowsList = new WindowsList(); List<WindowInfo> windows = await Task.Run(() => windowsList.GetVisibleWindowsList()); if (windows != null && windows.Count > 0) { List<ToolStripItem> items = new List<ToolStripItem>(); foreach (WindowInfo window in windows) { try { string title = window.Text.Truncate(50, "..."); ToolStripMenuItem tsmi = new ToolStripMenuItem(title); tsmi.Tag = window; tsmi.Click += handlerWindow; items.Add(tsmi); using (Icon icon = await Task.Run(() => window.Icon)) { if (icon != null && icon.Width > 0 && icon.Height > 0) { tsmi.Image = icon.ToBitmap(); } } } catch (Exception e) { DebugHelper.WriteException(e); } } tsmiWindow.DropDownItems.AddRange(items.ToArray()); } tsmiWindow.Invalidate(); tsmiMonitor.DropDownItems.Clear(); Screen[] screens = Screen.AllScreens; if (screens != null && screens.Length > 0) { ToolStripItem[] items = new ToolStripItem[screens.Length]; for (int i = 0; i < items.Length; i++) { Screen screen = screens[i]; string text = string.Format("{0}. {1}x{2}", i + 1, screen.Bounds.Width, screen.Bounds.Height); ToolStripMenuItem tsmi = new ToolStripMenuItem(text); tsmi.Tag = screen.Bounds; tsmi.Click += handlerMonitor; items[i] = tsmi; } tsmiMonitor.DropDownItems.AddRange(items); } tsmiMonitor.Invalidate(); } public void ForceClose() { if (ScreenRecordManager.IsRecording) { if (MessageBox.Show(Resources.ShareXCannotBeClosedWhileScreenRecordingIsActive, "ShareX", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { ScreenRecordManager.AbortRecording(); } } else { forceClose = true; Close(); } } #region Form events protected override void SetVisibleCore(bool value) { if (value && !IsHandleCreated && (Program.SilentRun || Program.Settings.SilentRun) && Program.Settings.ShowTray) { CreateHandle(); value = false; } base.SetVisibleCore(value); } private void MainForm_Shown(object sender, EventArgs e) { AfterShownJobs(); } private void MainForm_Resize(object sender, EventArgs e) { Refresh(); } private void MainForm_VisibleChanged(object sender, EventArgs e) { if (Visible && !CaptureHelpers.GetScreenBounds().IntersectsWith(Bounds)) { Rectangle activeScreen = CaptureHelpers.GetActiveScreenBounds(); Location = new Point((activeScreen.Width - Size.Width) / 2, (activeScreen.Height - Size.Height) / 2); } } private void MainForm_LocationChanged(object sender, EventArgs e) { if (IsReady && WindowState == FormWindowState.Normal) { Program.Settings.MainFormPosition = Location; } } private void MainForm_SizeChanged(object sender, EventArgs e) { if (IsReady && WindowState == FormWindowState.Normal) { Program.Settings.MainFormSize = Size; } } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { if (e.CloseReason == CloseReason.UserClosing && Program.Settings.ShowTray && !forceClose) { e.Cancel = true; Hide(); SettingManager.SaveAllSettingsAsync(); if (Program.Settings.FirstTimeMinimizeToTray) { TaskHelpers.ShowNotificationTip(Resources.ShareXIsMinimizedToTheSystemTray, "ShareX", 8000); Program.Settings.FirstTimeMinimizeToTray = false; } } } private void MainForm_FormClosed(object sender, FormClosedEventArgs e) { TaskManager.StopAllTasks(); } private void MainForm_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop, false) || e.Data.GetDataPresent(DataFormats.Bitmap, false) || e.Data.GetDataPresent(DataFormats.Text, false)) { e.Effect = DragDropEffects.Copy; } else { e.Effect = DragDropEffects.None; } } private void MainForm_DragDrop(object sender, DragEventArgs e) { UploadManager.DragDropUpload(e.Data); } private void TtMain_Draw(object sender, DrawToolTipEventArgs e) { e.DrawBackground(); e.DrawBorder(); e.DrawText(); } private void dgvHotkeys_MouseUp(object sender, MouseEventArgs e) { if (Program.Settings.TaskViewMode == TaskViewMode.ListView) { if (e.Button == MouseButtons.Left) { lvUploads.Focus(); } else if (e.Button == MouseButtons.Right) { UpdateInfoManager(); cmsTaskInfo.Show((Control)sender, e.X + 1, e.Y + 1); } } else if (Program.Settings.TaskViewMode == TaskViewMode.ThumbnailView) { if (e.Button == MouseButtons.Right) { UcTaskView_ContextMenuRequested(sender, e); } } } private void dgvHotkeys_MouseDoubleClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { tsbHotkeySettings_Click(sender, e); } } private async void lvUploads_SelectedIndexChanged(object sender, EventArgs e) { lvUploads.SelectedIndexChanged -= lvUploads_SelectedIndexChanged; await Task.Delay(1); lvUploads.SelectedIndexChanged += lvUploads_SelectedIndexChanged; UpdateInfoManager(); } private void lvUploads_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) { UpdateInfoManager(); cmsTaskInfo.Show(lvUploads, e.X + 1, e.Y + 1); } } private void lvUploads_MouseDoubleClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { uim.TryOpen(); } } private void scMain_SplitterMoved(object sender, SplitterEventArgs e) { Program.Settings.PreviewSplitterDistance = scMain.SplitterDistance; } private void lvUploads_KeyDown(object sender, KeyEventArgs e) { switch (e.KeyData) { default: return; case Keys.Enter: uim.TryOpen(); break; case Keys.Control | Keys.Enter: uim.OpenFile(); break; case Keys.Shift | Keys.Enter: uim.OpenFolder(); break; case Keys.Control | Keys.C: uim.TryCopy(); break; case Keys.Shift | Keys.C: uim.CopyFile(); break; case Keys.Alt | Keys.C: uim.CopyImage(); break; case Keys.Control | Keys.Shift | Keys.C: uim.CopyFilePath(); break; case Keys.Control | Keys.X: uim.TryCopy(); RemoveSelectedItems(); break; case Keys.Control | Keys.V: UploadManager.ClipboardUploadMainWindow(); break; case Keys.Control | Keys.U: uim.Upload(); break; case Keys.Control | Keys.D: uim.Download(); break; case Keys.Control | Keys.E: uim.EditImage(); break; case Keys.Control | Keys.P: uim.PinToScreen(); break; case Keys.Delete: RemoveSelectedItems(); break; case Keys.Shift | Keys.Delete: uim.DeleteFiles(); RemoveSelectedItems(); break; case Keys.Apps: if (lvUploads.SelectedItems.Count > 0) { UpdateInfoManager(); Rectangle rect = lvUploads.GetItemRect(lvUploads.SelectedIndex); cmsTaskInfo.Show(lvUploads, new Point(rect.X, rect.Bottom)); } break; } e.SuppressKeyPress = true; } private void pbPreview_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left && lvUploads.SelectedIndices.Count > 0) { string[] files = lvUploads.Items.Cast<ListViewItem>().Select(x => ((WorkerTask)x.Tag).Info?.FilePath).ToArray(); int index = lvUploads.SelectedIndices[0]; ImageViewer.ShowImage(files, index); } } private void ucTaskThumbnailView_SelectedPanelChanged(object sender, EventArgs e) { UpdateInfoManager(); } private void UcTaskView_ContextMenuRequested(object sender, MouseEventArgs e) { cmsTaskInfo.Show(sender as Control, e.X + 1, e.Y + 1); } private void cmsTaskInfo_Closing(object sender, ToolStripDropDownClosingEventArgs e) { if (e.CloseReason == ToolStripDropDownCloseReason.Keyboard) { e.Cancel = !(NativeMethods.GetKeyState((int)Keys.Apps) < 0 || NativeMethods.GetKeyState((int)Keys.F10) < 0 || NativeMethods.GetKeyState((int)Keys.Escape) < 0); } } private void cmsTaskInfo_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { if (e.KeyData == Keys.Apps) { cmsTaskInfo.Close(); } } private void lvUploads_ColumnWidthChanged(object sender, ColumnWidthChangedEventArgs e) { if (IsReady) { Program.Settings.TaskListViewColumnWidths = new List<int>(); for (int i = 0; i < lvUploads.Columns.Count; i++) { Program.Settings.TaskListViewColumnWidths.Add(lvUploads.Columns[i].Width); } } } private void lvUploads_ItemDrag(object sender, ItemDragEventArgs e) { TaskInfo[] taskInfos = GetSelectedTasks().Select(x => x.Info).Where(x => x != null).ToArray(); if (taskInfos.Length > 0) { IDataObject dataObject = null; if (ModifierKeys.HasFlag(Keys.Control)) { string[] urls = taskInfos.Select(x => x.ToString()).Where(x => !string.IsNullOrEmpty(x)).ToArray(); if (urls.Length > 0) { dataObject = new DataObject(DataFormats.Text, string.Join(Environment.NewLine, urls)); } } else { string[] files = taskInfos.Select(x => x.FilePath).Where(x => !string.IsNullOrEmpty(x) && File.Exists(x)).ToArray(); if (files.Length > 0) { dataObject = new DataObject(DataFormats.FileDrop, files); } } if (dataObject != null) { AllowDrop = false; lvUploads.DoDragDrop(dataObject, DragDropEffects.Copy | DragDropEffects.Move); AllowDrop = true; } } } #region Menu events private void tsmiFullscreen_Click(object sender, EventArgs e) { new CaptureFullscreen().Capture(true); } private async void tsddbCapture_DropDownOpening(object sender, EventArgs e) { await PrepareCaptureMenuAsync(tsmiWindow, tsmiWindowItems_Click, tsmiMonitor, tsmiMonitorItems_Click); } private void tsmiWindowItems_Click(object sender, EventArgs e) { ToolStripItem tsi = (ToolStripItem)sender; if (tsi.Tag is WindowInfo wi) { new CaptureWindow(wi.Handle).Capture(true); } } private void tsmiMonitorItems_Click(object sender, EventArgs e) { ToolStripItem tsi = (ToolStripItem)sender; Rectangle rect = (Rectangle)tsi.Tag; if (!rect.IsEmpty) { new CaptureMonitor(rect).Capture(true); } } private void tsmiRectangle_Click(object sender, EventArgs e) { new CaptureRegion().Capture(true); } private void tsmiRectangleLight_Click(object sender, EventArgs e) { new CaptureRegion(RegionCaptureType.Light).Capture(true); } private void tsmiRectangleTransparent_Click(object sender, EventArgs e) { new CaptureRegion(RegionCaptureType.Transparent).Capture(true); } private void tsmiLastRegion_Click(object sender, EventArgs e) { new CaptureLastRegion().Capture(true); } private void tsmiScreenRecordingFFmpeg_Click(object sender, EventArgs e) { TaskHelpers.StartScreenRecording(ScreenRecordOutput.FFmpeg, ScreenRecordStartMethod.Region); } private void tsmiScreenRecordingGIF_Click(object sender, EventArgs e) { TaskHelpers.StartScreenRecording(ScreenRecordOutput.GIF, ScreenRecordStartMethod.Region); } private async void tsmiScrollingCapture_Click(object sender, EventArgs e) { await TaskHelpers.OpenScrollingCapture(); } private void tsmiAutoCapture_Click(object sender, EventArgs e) { TaskHelpers.OpenAutoCapture(); } private void tsmiShowCursor_Click(object sender, EventArgs e) { Program.DefaultTaskSettings.CaptureSettings.ShowCursor = ((ToolStripMenuItem)sender).Checked; tsmiShowCursor.Checked = tsmiTrayShowCursor.Checked = Program.DefaultTaskSettings.CaptureSettings.ShowCursor; } private void tsmiScreenshotDelay0_Click(object sender, EventArgs e) { SetScreenshotDelay(0); } private void tsmiScreenshotDelay1_Click(object sender, EventArgs e) { SetScreenshotDelay(1); } private void tsmiScreenshotDelay2_Click(object sender, EventArgs e) { SetScreenshotDelay(2); } private void tsmiScreenshotDelay3_Click(object sender, EventArgs e) { SetScreenshotDelay(3); } private void tsmiScreenshotDelay4_Click(object sender, EventArgs e) { SetScreenshotDelay(4); } private void tsmiScreenshotDelay5_Click(object sender, EventArgs e) { SetScreenshotDelay(5); } private void tsbFileUpload_Click(object sender, EventArgs e) { UploadManager.UploadFile(); } private void tsmiUploadFolder_Click(object sender, EventArgs e) { UploadManager.UploadFolder(); } private void tsbClipboardUpload_Click(object sender, EventArgs e) { UploadManager.ClipboardUploadMainWindow(); } private void tsmiUploadText_Click(object sender, EventArgs e) { UploadManager.ShowTextUploadDialog(); } private void tsmiUploadURL_Click(object sender, EventArgs e) { UploadManager.UploadURL(); } private void tsbDragDropUpload_Click(object sender, EventArgs e) { TaskHelpers.OpenDropWindow(); } private void tsmiShortenURL_Click(object sender, EventArgs e) { UploadManager.ShowShortenURLDialog(); } private void tsmiColorPicker_Click(object sender, EventArgs e) { TaskHelpers.ShowScreenColorPickerDialog(); } private void tsmiScreenColorPicker_Click(object sender, EventArgs e) { TaskHelpers.OpenScreenColorPicker(); } private void tsmiRuler_Click(object sender, EventArgs e) { TaskHelpers.OpenRuler(); } private void tsmiPinToScreen_Click(object sender, EventArgs e) { TaskHelpers.PinToScreen(); } private void tsmiImageEditor_Click(object sender, EventArgs e) { TaskHelpers.OpenImageEditor(); } private void tsmiImageBeautifier_Click(object sender, EventArgs e) { TaskHelpers.OpenImageBeautifier(); } private void tsmiImageEffects_Click(object sender, EventArgs e) { TaskHelpers.OpenImageEffects(); } private void tsmiImageViewer_Click(object sender, EventArgs e) { TaskHelpers.OpenImageViewer(); } private void tsmiImageCombiner_Click(object sender, EventArgs e) { TaskHelpers.OpenImageCombiner(); } private void tsmiImageSplitter_Click(object sender, EventArgs e) { TaskHelpers.OpenImageSplitter(); } private void tsmiImageThumbnailer_Click(object sender, EventArgs e) { TaskHelpers.OpenImageThumbnailer(); } private void tsmiVideoConverter_Click(object sender, EventArgs e) { TaskHelpers.OpenVideoConverter(); } private void tsmiVideoThumbnailer_Click(object sender, EventArgs e) { TaskHelpers.OpenVideoThumbnailer(); } private void tsmiAI_Click(object sender, EventArgs e) { TaskHelpers.AnalyzeImage(); } private async void tsmiOCR_Click(object sender, EventArgs e) { Hide(); await Task.Delay(250); try { await TaskHelpers.OCRImage(); } catch (Exception ex) { DebugHelper.WriteException(ex); } finally { this.ForceActivate(); } } private void tsmiQRCode_Click(object sender, EventArgs e) { TaskHelpers.OpenQRCode(); } private void tsmiHashChecker_Click(object sender, EventArgs e) { TaskHelpers.OpenHashCheck(); } private void tsmiMetadata_Click(object sender, EventArgs e) { TaskHelpers.OpenMetadataWindow(); } private void tsmiIndexFolder_Click(object sender, EventArgs e) { TaskHelpers.OpenDirectoryIndexer(); } private void tsmiClipboardViewer_Click(object sender, EventArgs e) { TaskHelpers.OpenClipboardViewer(); } private void tsmiBorderlessWindow_Click(object sender, EventArgs e) { TaskHelpers.OpenBorderlessWindow(); } private void tsmiInspectWindow_Click(object sender, EventArgs e) { TaskHelpers.OpenInspectWindow(); } private void tsmiMonitorTest_Click(object sender, EventArgs e) { TaskHelpers.OpenMonitorTest(); } private void TsddbAfterCaptureTasks_DropDownOpening(object sender, EventArgs e) { UpdateImageEffectsMenu(tsddbAfterCaptureTasks); } private void TsmiTrayAfterCaptureTasks_DropDownOpening(object sender, EventArgs e) { UpdateImageEffectsMenu(tsmiTrayAfterCaptureTasks); } private void tsddbDestinations_DropDownOpened(object sender, EventArgs e) { UpdateDestinationStates(); } private void tsbApplicationSettings_Click(object sender, EventArgs e) { using (ApplicationSettingsForm settingsForm = new ApplicationSettingsForm()) { settingsForm.ShowDialog(); } if (!IsDisposed) { AfterApplicationSettingsJobs(); UpdateWorkflowsMenu(); SettingManager.SaveApplicationConfigAsync(); } } private void tsbTaskSettings_Click(object sender, EventArgs e) { using (TaskSettingsForm taskSettingsForm = new TaskSettingsForm(Program.DefaultTaskSettings, true)) { taskSettingsForm.ShowDialog(); } if (!IsDisposed) { AfterTaskSettingsJobs(); SettingManager.SaveApplicationConfigAsync(); } } private void tsbHotkeySettings_Click(object sender, EventArgs e) { if (Program.HotkeyManager != null) { using (HotkeySettingsForm hotkeySettingsForm = new HotkeySettingsForm(Program.HotkeyManager)) { hotkeySettingsForm.ShowDialog(); } if (!IsDisposed) { UpdateWorkflowsMenu(); SettingManager.SaveHotkeysConfigAsync(); } } } private void tsbDestinationSettings_Click(object sender, EventArgs e) { TaskHelpers.OpenUploadersConfigWindow(); } private void tsbCustomUploaderSettings_Click(object sender, EventArgs e) { TaskHelpers.OpenCustomUploaderSettingsWindow(); } private void tsbScreenshotsFolder_Click(object sender, EventArgs e) { TaskHelpers.OpenScreenshotsFolder(); } private void tsbHistory_Click(object sender, EventArgs e) { TaskHelpers.OpenHistory(); } private void tsbImageHistory_Click(object sender, EventArgs e) { TaskHelpers.OpenImageHistory(); } private void tsmiShowDebugLog_Click(object sender, EventArgs e) { TaskHelpers.OpenDebugLog(); } private void tsmiTestImageUpload_Click(object sender, EventArgs e) { UploadManager.UploadImage(ShareXResources.Logo); } private void tsmiTestTextUpload_Click(object sender, EventArgs e) { UploadManager.UploadText(Resources.MainForm_tsmiTestTextUpload_Click_Text_upload_test); } private void tsmiTestFileUpload_Click(object sender, EventArgs e) { UploadManager.UploadImage(ShareXResources.Logo, ImageDestination.FileUploader, Program.DefaultTaskSettings.FileDestination); } private void tsmiTestURLShortener_Click(object sender, EventArgs e) { UploadManager.ShortenURL(Links.Website); } private void tsmiTestURLSharing_Click(object sender, EventArgs e) { UploadManager.ShareURL(Links.Website); } private void tsbDonate_Click(object sender, EventArgs e) { #if STEAM URLHelpers.OpenURL(Links.Website); #else URLHelpers.OpenURL(Links.Donate); #endif } private void tsbX_Click(object sender, EventArgs e) { URLHelpers.OpenURL(Links.XFollow); } private void tsbDiscord_Click(object sender, EventArgs e) { URLHelpers.OpenURL(Links.Discord); } private void tsbAbout_Click(object sender, EventArgs e) { using (AboutForm aboutForm = new AboutForm()) { aboutForm.ShowDialog(); } } #endregion Menu events #region Tray events private async void niTray_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { if (Program.Settings.TrayLeftDoubleClickAction == HotkeyType.None) { await TaskHelpers.ExecuteJob(Program.Settings.TrayLeftClickAction); } else { trayClickCount++; if (trayClickCount == 1) { timerTraySingleClick.Interval = SystemInformation.DoubleClickTime; timerTraySingleClick.Start(); } else { trayClickCount = 0; timerTraySingleClick.Stop(); await TaskHelpers.ExecuteJob(Program.Settings.TrayLeftDoubleClickAction); } } } else if (e.Button == MouseButtons.Middle) { await TaskHelpers.ExecuteJob(Program.Settings.TrayMiddleClickAction); } } private async void timerTraySingleClick_Tick(object sender, EventArgs e) { if (trayClickCount == 1) { trayClickCount = 0; timerTraySingleClick.Stop(); await TaskHelpers.ExecuteJob(Program.Settings.TrayLeftClickAction); } } private void niTray_BalloonTipClicked(object sender, EventArgs e) { if (niTray.Tag is BalloonTipAction action) { switch (action.ClickAction) { case BalloonTipClickAction.OpenURL: URLHelpers.OpenURL(action.Text); break; case BalloonTipClickAction.OpenDebugLog: TaskHelpers.OpenDebugLog(); break; } } } private void cmsTray_Opened(object sender, EventArgs e) { if (Program.Settings.TrayAutoExpandCaptureMenu) { tsmiTrayCapture.Select(); tsmiTrayCapture.ShowDropDown(); } } private void tsmiTrayFullscreen_Click(object sender, EventArgs e) { new CaptureFullscreen().Capture(); } private async void tsmiCapture_DropDownOpening(object sender, EventArgs e) { await PrepareCaptureMenuAsync(tsmiTrayWindow, tsmiTrayWindowItems_Click, tsmiTrayMonitor, tsmiTrayMonitorItems_Click); } private void tsmiTrayWindowItems_Click(object sender, EventArgs e) { ToolStripItem tsi = (ToolStripItem)sender; if (tsi.Tag is WindowInfo wi) { new CaptureWindow(wi.Handle).Capture(); } } private void tsmiTrayMonitorItems_Click(object sender, EventArgs e) { ToolStripItem tsi = (ToolStripItem)sender; Rectangle rect = (Rectangle)tsi.Tag; if (!rect.IsEmpty) { new CaptureMonitor(rect).Capture(); } } private void tsmiTrayRectangle_Click(object sender, EventArgs e) { new CaptureRegion().Capture(); } private void tsmiTrayRectangleLight_Click(object sender, EventArgs e) { new CaptureRegion(RegionCaptureType.Light).Capture(); } private void tsmiTrayRectangleTransparent_Click(object sender, EventArgs e) { new CaptureRegion(RegionCaptureType.Transparent).Capture(); } private void tsmiTrayLastRegion_Click(object sender, EventArgs e) { new CaptureLastRegion().Capture(); } private async void tsmiTrayOCR_Click(object sender, EventArgs e) { try { await TaskHelpers.OCRImage(); } catch (Exception ex) { DebugHelper.WriteException(ex); } } private void tsmiTrayToggleHotkeys_Click(object sender, EventArgs e) { TaskHelpers.ToggleHotkeys(); } private void tsmiRestartAsAdmin_Click(object sender, EventArgs e) { Program.Restart(true); } private void tsmiOpenActionsToolbar_Click(object sender, EventArgs e) { TaskHelpers.ToggleActionsToolbar(); } private void tsmiTrayShow_Click(object sender, EventArgs e) { this.ForceActivate(); } private void tsmiTrayExit_MouseDown(object sender, MouseEventArgs e) { trayMenuSaveSettings = false; } private void cmsTray_Closed(object sender, ToolStripDropDownClosedEventArgs e) { if (trayMenuSaveSettings) { SettingManager.SaveAllSettingsAsync(); } trayMenuSaveSettings = true; } private void tsmiTrayExit_Click(object sender, EventArgs e) { ForceClose(); } #endregion Tray events #region UploadInfoMenu events private void tsmiShowErrors_Click(object sender, EventArgs e) { uim.ShowErrors(); } private void tsmiStopUpload_Click(object sender, EventArgs e) { uim.StopUpload(); } private void tsmiOpenURL_Click(object sender, EventArgs e) { uim.OpenURL(); } private void tsmiOpenShortenedURL_Click(object sender, EventArgs e) { uim.OpenShortenedURL(); } private void tsmiOpenThumbnailURL_Click(object sender, EventArgs e) { uim.OpenThumbnailURL(); } private void tsmiOpenDeletionURL_Click(object sender, EventArgs e) { uim.OpenDeletionURL(); } private void tsmiOpenFile_Click(object sender, EventArgs e) { uim.OpenFile(); } private void tsmiOpenThumbnailFile_Click(object sender, EventArgs e) { uim.OpenThumbnailFile(); } private void tsmiOpenFolder_Click(object sender, EventArgs e) { uim.OpenFolder(); } private void tsmiCopyURL_Click(object sender, EventArgs e) { uim.CopyURL(); } private void tsmiCopyShortenedURL_Click(object sender, EventArgs e) { uim.CopyShortenedURL(); } private void tsmiCopyThumbnailURL_Click(object sender, EventArgs e) { uim.CopyThumbnailURL(); } private void tsmiCopyDeletionURL_Click(object sender, EventArgs e) { uim.CopyDeletionURL(); } private void tsmiCopyFile_Click(object sender, EventArgs e) { uim.CopyFile(); } private void tsmiCopyImage_Click(object sender, EventArgs e) { uim.CopyImage(); } private void tsmiCopyImageDimensions_Click(object sender, EventArgs e) { uim.CopyImageDimensions(); } private void tsmiCopyText_Click(object sender, EventArgs e) { uim.CopyText(); } private void tsmiCopyThumbnailFile_Click(object sender, EventArgs e) { uim.CopyThumbnailFile(); } private void tsmiCopyThumbnailImage_Click(object sender, EventArgs e) { uim.CopyThumbnailImage(); } private void tsmiCopyHTMLLink_Click(object sender, EventArgs e) { uim.CopyHTMLLink(); } private void tsmiCopyHTMLImage_Click(object sender, EventArgs e) { uim.CopyHTMLImage(); } private void tsmiCopyHTMLLinkedImage_Click(object sender, EventArgs e) { uim.CopyHTMLLinkedImage(); } private void tsmiCopyForumLink_Click(object sender, EventArgs e) { uim.CopyForumLink(); } private void tsmiCopyForumImage_Click(object sender, EventArgs e) { uim.CopyForumImage(); } private void tsmiCopyForumLinkedImage_Click(object sender, EventArgs e) { uim.CopyForumLinkedImage(); } private void tsmiCopyMarkdownLink_Click(object sender, EventArgs e) { uim.CopyMarkdownLink(); } private void tsmiCopyMarkdownImage_Click(object sender, EventArgs e) { uim.CopyMarkdownImage(); } private void tsmiCopyMarkdownLinkedImage_Click(object sender, EventArgs e) { uim.CopyMarkdownLinkedImage(); } private void tsmiCopyFilePath_Click(object sender, EventArgs e) { uim.CopyFilePath(); } private void tsmiCopyFileName_Click(object sender, EventArgs e) { uim.CopyFileName(); } private void tsmiCopyFileNameWithExtension_Click(object sender, EventArgs e) { uim.CopyFileNameWithExtension(); } private void tsmiCopyFolder_Click(object sender, EventArgs e) { uim.CopyFolder(); } private void tsmiClipboardFormat_Click(object sender, EventArgs e) { ToolStripMenuItem tsmiClipboardFormat = sender as ToolStripMenuItem; ClipboardFormat cf = tsmiClipboardFormat.Tag as ClipboardFormat; uim.CopyCustomFormat(cf.Format); } private void tsmiUploadSelectedFile_Click(object sender, EventArgs e) { uim.Upload(); } private void tsmiDownloadSelectedURL_Click(object sender, EventArgs e) { uim.Download(); } private void tsmiDeleteSelectedItem_Click(object sender, EventArgs e) { RemoveSelectedItems(); } private void tsmiDeleteSelectedFile_Click(object sender, EventArgs e) { if (MessageBox.Show(Resources.MainForm_tsmiDeleteSelectedFile_Click_Do_you_really_want_to_delete_this_file_, "ShareX - " + Resources.MainForm_tsmiDeleteSelectedFile_Click_File_delete_confirmation, MessageBoxButtons.YesNo) == DialogResult.Yes) { uim.DeleteFiles(); RemoveSelectedItems(); } } private void tsmiEditSelectedFile_Click(object sender, EventArgs e) { uim.EditImage(); } private void tsmiBeautifyImage_Click(object sender, EventArgs e) { uim.BeautifyImage(); } private void tsmiAddImageEffects_Click(object sender, EventArgs e) { uim.AddImageEffects(); } private void tsmiPinSelectedFile_Click(object sender, EventArgs e) { uim.PinToScreen(); } private void tsmiGoogleLens_Click(object sender, EventArgs e) { uim.SearchImageUsingGoogleLens(); } private void tsmiBingVisualSearch_Click(object sender, EventArgs e) { uim.SearchImageUsingBing(); } private void tsmiAnalyzeImage_Click(object sender, EventArgs e) { uim.AnalyzeImage(); } private void tsmiShowQRCode_Click(object sender, EventArgs e) { uim.ShowQRCode(); } private async void tsmiOCRImage_Click(object sender, EventArgs e) { await uim.OCRImage(); } private void tsmiCombineImages_Click(object sender, EventArgs e) { uim.CombineImages(); } private void tsmiCombineImagesHorizontally_Click(object sender, EventArgs e) { uim.CombineImages(Orientation.Horizontal); } private void tsmiCombineImagesVertically_Click(object sender, EventArgs e) { uim.CombineImages(Orientation.Vertical); } private void tsmiShowResponse_Click(object sender, EventArgs e) { uim.ShowResponse(); } private void tsmiClearList_Click(object sender, EventArgs e) { RemoveAllItems(); TaskManager.RecentManager.Clear(); } private void TsmiSwitchTaskViewMode_Click(object sender, EventArgs e) { tsMain.SendToBack(); if (Program.Settings.TaskViewMode == TaskViewMode.ListView) { Program.Settings.TaskViewMode = TaskViewMode.ThumbnailView; ucTaskThumbnailView.UpdateAllThumbnails(); } else { Program.Settings.TaskViewMode = TaskViewMode.ListView; } UpdateTaskViewMode(); UpdateMainWindowLayout(); UpdateInfoManager(); } #endregion UploadInfoMenu events #endregion Form events } }
conversion
csharp
dotnet__machinelearning
test/Microsoft.ML.Tests/Transformers/CustomMappingTests.cs
{ "start": 5025, "end": 5121 }
public class ____ { public HashSet<float> SeenValues; }
MyState
csharp
unoplatform__uno
src/Uno.UI/UI/Xaml/Controls/Materials/Backdrop/BackdropMaterial.cs
{ "start": 2882, "end": 7101 }
private partial class ____ : DependencyObject, IDisposable { private readonly DispatcherHelper _dispatcherHelper; private readonly WeakReference<Control> _target; private readonly IDisposable _themeChangedRevoker; private readonly IDisposable _colorValuesChangedRevoker; private readonly UISettings _uiSettings = new UISettings(); private readonly IDisposable _highContrastChangedRevoker; private bool _isHighContrast; private bool _isDisposed; public BackdropMaterialState(Control target) { _dispatcherHelper = new DispatcherHelper(this); _target = new WeakReference<Control>(target); // Track whether we're connected and update the number of connected BackdropMaterial on this thread. _connectedBrushCount.Value++; CreateOrDestroyMicaController(); // Normally QI would be fine, but .NET is lying about implementing this interface (e.g. C# TestFrame derives from Frame and this QI // returns success even on RS2, but it's not implemented by XAML until RS3). if (SharedHelpers.IsRS3OrHigher()) { if (target is FrameworkElement targetThemeChanged) { void OnActualThemeChanged(FrameworkElement sender, object args) { UpdateFallbackBrush(); } targetThemeChanged.ActualThemeChanged += OnActualThemeChanged; _themeChangedRevoker = Disposable.Create(() => targetThemeChanged.ActualThemeChanged -= OnActualThemeChanged); } } void OnColorValuesChanged(UISettings uiSettings, object args) { _dispatcherHelper.RunAsync(() => UpdateFallbackBrush()); } _uiSettings.ColorValuesChanged += OnColorValuesChanged; _colorValuesChangedRevoker = Disposable.Create(() => _uiSettings.ColorValuesChanged -= OnColorValuesChanged); // Listen for High Contrast changes var accessibilitySettings = new AccessibilitySettings(); _isHighContrast = accessibilitySettings.HighContrast; void OnHighContrastChanged(AccessibilitySettings sender, object args) { _dispatcherHelper.RunAsync(() => { _isHighContrast = accessibilitySettings.HighContrast; UpdateFallbackBrush(); }); } accessibilitySettings.HighContrastChanged += OnHighContrastChanged; _highContrastChangedRevoker = Disposable.Create(() => accessibilitySettings.HighContrastChanged -= OnHighContrastChanged); UpdateFallbackBrush(); } public BackdropMaterialState() => Dispose(); public void Dispose() { if (!_isDisposed) { _isDisposed = true; _connectedBrushCount.Value--; CreateOrDestroyMicaController(); _highContrastChangedRevoker.Dispose(); _themeChangedRevoker.Dispose(); _colorValuesChangedRevoker.Dispose(); } } private void UpdateFallbackBrush() { if (_target.TryGetTarget(out var target)) { if (_micaController.Value == null) { // When not using mica, use the theme and high contrast states to determine the fallback color. ElementTheme GetTheme() { // See other IsRS3OrHigher usage for comment explaining why the version check and QI. if (SharedHelpers.IsRS3OrHigher()) { if (target is FrameworkElement targetTheme) { return targetTheme.ActualTheme; } } var value = _uiSettings.GetColorValue(UIColorType.Background); if (value.B == 0) { return ElementTheme.Dark; } return ElementTheme.Light; } var theme = GetTheme(); Color GetColor() { if (_isHighContrast) { return _uiSettings.GetColorValue(UIColorType.Background); } if (theme == ElementTheme.Dark) { return MicaController.DarkThemeColor; } else { return MicaController.LightThemeColor; } } var color = GetColor(); target.Background = new SolidColorBrush(color); } else { // When Mica is involved, use transparent for the background (this is so that the hit testing // behavior is consistent with/without the material). target.Background = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)); } } } } } }
BackdropMaterialState
csharp
smartstore__Smartstore
src/Smartstore.Core/Content/Menus/Consumers/CatalogMenuInvalidator.cs
{ "start": 318, "end": 3230 }
internal class ____ : IConsumer { private readonly IMenuService _menuService; private readonly CatalogSettings _catalogSettings; private readonly ICacheManager _cache; private readonly SmartDbContext _db; private List<string> _invalidated = new(); private List<string> _countsResetted = new(); public CatalogMenuInvalidator( IMenuService menuService, CatalogSettings catalogSettings, ICacheManager cache, SmartDbContext db) { _menuService = menuService; _catalogSettings = catalogSettings; _cache = cache; _db = db; } public async Task HandleAsync(CategoryTreeChangedEvent eventMessage) { var affectedMenuNames = await _db.MenuItems .AsNoTracking() .Where(x => x.ProviderName == "catalog") .Select(x => x.Menu.SystemName) .Distinct() .ToListAsync(); foreach (var menuName in affectedMenuNames) { var reason = eventMessage.Reason; if (reason == CategoryTreeChangeReason.ElementCounts) { await ResetElementCounts(menuName); } else { await Invalidate(menuName); } } } private async Task Invalidate(string menuName) { if (!_invalidated.Contains(menuName)) { await (await _menuService.GetMenuAsync(menuName))?.ClearCacheAsync(); _invalidated.Add(menuName); } } private async Task ResetElementCounts(string menuName) { if (!_countsResetted.Contains(menuName) && _catalogSettings.ShowCategoryProductNumber) { var allCachedMenus = (await _menuService.GetMenuAsync(menuName))?.GetAllCachedMenus(); if (allCachedMenus != null) { foreach (var kvp in allCachedMenus) { bool dirty = false; kvp.Value.Traverse(x => { if (x.Value.ElementsCount.HasValue) { dirty = true; x.Value.ElementsCount = null; x.Value.ElementsCountResolved = false; } }, true); if (dirty) { await _cache.PutAsync(kvp.Key, kvp.Value); } } } _countsResetted.Add(menuName); } } } }
CatalogMenuInvalidator
csharp
dotnet__extensions
test/Libraries/Microsoft.Extensions.AI.Tests/ChatCompletion/FunctionInvokingChatClientTests.cs
{ "start": 680, "end": 62668 }
public class ____ { [Fact] public void InvalidArgs_Throws() { Assert.Throws<ArgumentNullException>("innerClient", () => new FunctionInvokingChatClient(null!)); Assert.Throws<ArgumentNullException>("builder", () => ((ChatClientBuilder)null!).UseFunctionInvocation()); } [Fact] public void Ctor_HasExpectedDefaults() { using TestChatClient innerClient = new(); using FunctionInvokingChatClient client = new(innerClient); Assert.False(client.AllowConcurrentInvocation); Assert.False(client.IncludeDetailedErrors); Assert.Equal(40, client.MaximumIterationsPerRequest); Assert.Equal(3, client.MaximumConsecutiveErrorsPerRequest); Assert.Null(client.FunctionInvoker); Assert.Null(client.AdditionalTools); } [Fact] public void Properties_Roundtrip() { using TestChatClient innerClient = new(); using FunctionInvokingChatClient client = new(innerClient); Assert.False(client.AllowConcurrentInvocation); client.AllowConcurrentInvocation = true; Assert.True(client.AllowConcurrentInvocation); Assert.False(client.IncludeDetailedErrors); client.IncludeDetailedErrors = true; Assert.True(client.IncludeDetailedErrors); Assert.Equal(40, client.MaximumIterationsPerRequest); client.MaximumIterationsPerRequest = 5; Assert.Equal(5, client.MaximumIterationsPerRequest); Assert.Equal(3, client.MaximumConsecutiveErrorsPerRequest); client.MaximumConsecutiveErrorsPerRequest = 1; Assert.Equal(1, client.MaximumConsecutiveErrorsPerRequest); Assert.Null(client.FunctionInvoker); Func<FunctionInvocationContext, CancellationToken, ValueTask<object?>> invoker = (ctx, ct) => new ValueTask<object?>("test"); client.FunctionInvoker = invoker; Assert.Same(invoker, client.FunctionInvoker); Assert.Null(client.AdditionalTools); IList<AITool> additionalTools = [AIFunctionFactory.Create(() => "Additional Tool")]; client.AdditionalTools = additionalTools; Assert.Same(additionalTools, client.AdditionalTools); } [Fact] public async Task SupportsSingleFunctionCallPerRequestAsync() { var options = new ChatOptions { Tools = [ AIFunctionFactory.Create(() => "Result 1", "Func1"), AIFunctionFactory.Create((int i) => $"Result 2: {i}", "Func2"), AIFunctionFactory.Create((int i) => { }, "VoidReturn"), ] }; List<ChatMessage> plan = [ new ChatMessage(ChatRole.User, "hello"), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId1", "Func1")]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId1", result: "Result 1")]), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId2", "Func2", arguments: new Dictionary<string, object?> { { "i", 42 } })]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId2", result: "Result 2: 42")]), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId3", "VoidReturn", arguments: new Dictionary<string, object?> { { "i", 43 } })]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId3", result: "Success: Function completed.")]), new ChatMessage(ChatRole.Assistant, "world"), ]; await InvokeAndAssertAsync(options, plan); await InvokeAndAssertStreamingAsync(options, plan); } [Theory] [InlineData(false)] [InlineData(true)] public async Task SupportsToolsProvidedByAdditionalTools(bool provideOptions) { ChatOptions? options = provideOptions ? new() { Tools = [AIFunctionFactory.Create(() => "Shouldn't be invoked", "ChatOptionsFunc")] } : null; Func<ChatClientBuilder, ChatClientBuilder> configure = builder => builder.UseFunctionInvocation(configure: c => c.AdditionalTools = [ AIFunctionFactory.Create(() => "Result 1", "Func1"), AIFunctionFactory.Create((int i) => $"Result 2: {i}", "Func2"), AIFunctionFactory.Create((int i) => { }, "VoidReturn"), ]); List<ChatMessage> plan = [ new ChatMessage(ChatRole.User, "hello"), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId1", "Func1")]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId1", result: "Result 1")]), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId2", "Func2", arguments: new Dictionary<string, object?> { { "i", 42 } })]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId2", result: "Result 2: 42")]), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId3", "VoidReturn", arguments: new Dictionary<string, object?> { { "i", 43 } })]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId3", result: "Success: Function completed.")]), new ChatMessage(ChatRole.Assistant, "world"), ]; await InvokeAndAssertAsync(options, plan, configurePipeline: configure); await InvokeAndAssertStreamingAsync(options, plan, configurePipeline: configure); } [Fact] public async Task PrefersToolsProvidedByChatOptions() { ChatOptions options = new() { Tools = [AIFunctionFactory.Create(() => "Result 1", "Func1")] }; Func<ChatClientBuilder, ChatClientBuilder> configure = builder => builder.UseFunctionInvocation(configure: c => c.AdditionalTools = [ AIFunctionFactory.Create(() => "Should never be invoked", "Func1"), AIFunctionFactory.Create((int i) => $"Result 2: {i}", "Func2"), AIFunctionFactory.Create((int i) => { }, "VoidReturn"), ]); List<ChatMessage> plan = [ new ChatMessage(ChatRole.User, "hello"), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId1", "Func1")]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId1", result: "Result 1")]), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId2", "Func2", arguments: new Dictionary<string, object?> { { "i", 42 } })]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId2", result: "Result 2: 42")]), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId3", "VoidReturn", arguments: new Dictionary<string, object?> { { "i", 43 } })]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId3", result: "Success: Function completed.")]), new ChatMessage(ChatRole.Assistant, "world"), ]; await InvokeAndAssertAsync(options, plan, configurePipeline: configure); await InvokeAndAssertStreamingAsync(options, plan, configurePipeline: configure); } [Theory] [InlineData(false)] [InlineData(true)] public async Task SupportsMultipleFunctionCallsPerRequestAsync(bool concurrentInvocation) { var options = new ChatOptions { Tools = [ AIFunctionFactory.Create((int? i = 42) => "Result 1", "Func1"), AIFunctionFactory.Create((int i) => $"Result 2: {i}", "Func2"), ] }; List<ChatMessage> plan = [ new ChatMessage(ChatRole.User, "hello"), new ChatMessage(ChatRole.Assistant, [ new FunctionCallContent("callId1", "Func1"), new FunctionCallContent("callId2", "Func2", arguments: new Dictionary<string, object?> { { "i", 34 } }), new FunctionCallContent("callId3", "Func2", arguments: new Dictionary<string, object?> { { "i", 56 } }), ]), new ChatMessage(ChatRole.Tool, [ new FunctionResultContent("callId1", result: "Result 1"), new FunctionResultContent("callId2", result: "Result 2: 34"), new FunctionResultContent("callId3", result: "Result 2: 56"), ]), new ChatMessage(ChatRole.Assistant, [ new FunctionCallContent("callId4", "Func2", arguments: new Dictionary<string, object?> { { "i", 78 } }), new FunctionCallContent("callId5", "Func1") ]), new ChatMessage(ChatRole.Tool, [ new FunctionResultContent("callId4", result: "Result 2: 78"), new FunctionResultContent("callId5", result: "Result 1") ]), new ChatMessage(ChatRole.Assistant, "world"), ]; Func<ChatClientBuilder, ChatClientBuilder> configure = b => b.Use( s => new FunctionInvokingChatClient(s) { AllowConcurrentInvocation = concurrentInvocation }); await InvokeAndAssertAsync(options, plan, configurePipeline: configure); await InvokeAndAssertStreamingAsync(options, plan, configurePipeline: configure); } [Fact] public async Task ParallelFunctionCallsMayBeInvokedConcurrentlyAsync() { int remaining = 2; var tcs = new TaskCompletionSource<bool>(); var options = new ChatOptions { Tools = [ AIFunctionFactory.Create(async (string arg) => { if (Interlocked.Decrement(ref remaining) == 0) { tcs.SetResult(true); } await tcs.Task; return arg + arg; }, "Func"), ] }; List<ChatMessage> plan = [ new ChatMessage(ChatRole.User, "hello"), new ChatMessage(ChatRole.Assistant, [ new FunctionCallContent("callId1", "Func", arguments: new Dictionary<string, object?> { { "arg", "hello" } }), new FunctionCallContent("callId2", "Func", arguments: new Dictionary<string, object?> { { "arg", "world" } }), ]), new ChatMessage(ChatRole.Tool, [ new FunctionResultContent("callId1", result: "hellohello"), new FunctionResultContent("callId2", result: "worldworld"), ]), new ChatMessage(ChatRole.Assistant, "done"), ]; Func<ChatClientBuilder, ChatClientBuilder> configure = b => b.Use( s => new FunctionInvokingChatClient(s) { AllowConcurrentInvocation = true }); await InvokeAndAssertAsync(options, plan, configurePipeline: configure); await InvokeAndAssertStreamingAsync(options, plan, configurePipeline: configure); } [Fact] public async Task ConcurrentInvocationOfParallelCallsDisabledByDefaultAsync() { int activeCount = 0; var options = new ChatOptions { Tools = [ AIFunctionFactory.Create(async (string arg) => { Interlocked.Increment(ref activeCount); await Task.Delay(100); Assert.Equal(1, activeCount); Interlocked.Decrement(ref activeCount); return arg + arg; }, "Func"), ] }; List<ChatMessage> plan = [ new ChatMessage(ChatRole.User, "hello"), new ChatMessage(ChatRole.Assistant, [ new FunctionCallContent("callId1", "Func", arguments: new Dictionary<string, object?> { { "arg", "hello" } }), new FunctionCallContent("callId2", "Func", arguments: new Dictionary<string, object?> { { "arg", "world" } }), ]), new ChatMessage(ChatRole.Tool, [ new FunctionResultContent("callId1", result: "hellohello"), new FunctionResultContent("callId2", result: "worldworld"), ]), new ChatMessage(ChatRole.Assistant, "done"), ]; await InvokeAndAssertAsync(options, plan); await InvokeAndAssertStreamingAsync(options, plan); } [Fact] public async Task FunctionInvokerDelegateOverridesHandlingAsync() { var options = new ChatOptions { Tools = [ AIFunctionFactory.Create(() => "Result 1", "Func1"), AIFunctionFactory.Create((int i) => $"Result 2: {i}", "Func2"), AIFunctionFactory.Create((int i) => { }, "VoidReturn"), ] }; List<ChatMessage> plan = [ new ChatMessage(ChatRole.User, "hello"), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId1", "Func1")]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId1", result: "Result 1 from delegate")]), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId2", "Func2", arguments: new Dictionary<string, object?> { { "i", 42 } })]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId2", result: "Result 2: 42 from delegate")]), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId3", "VoidReturn", arguments: new Dictionary<string, object?> { { "i", 43 } })]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId3", result: "Success: Function completed.")]), new ChatMessage(ChatRole.Assistant, "world"), ]; Func<ChatClientBuilder, ChatClientBuilder> configure = b => b.Use( s => new FunctionInvokingChatClient(s) { FunctionInvoker = async (ctx, cancellationToken) => { Assert.NotNull(ctx); var result = await ctx.Function.InvokeAsync(ctx.Arguments, cancellationToken); return result is JsonElement e ? JsonSerializer.SerializeToElement($"{e.GetString()} from delegate", AIJsonUtilities.DefaultOptions) : result; } }); await InvokeAndAssertAsync(options, plan, configurePipeline: configure); await InvokeAndAssertStreamingAsync(options, plan, configurePipeline: configure); } [Fact] public async Task ContinuesWithSuccessfulCallsUntilMaximumIterations() { var maxIterations = 7; Func<ChatClientBuilder, ChatClientBuilder> configurePipeline = pipeline => pipeline .UseFunctionInvocation(configure: functionInvokingChatClient => { functionInvokingChatClient.MaximumIterationsPerRequest = maxIterations; }); var actualCallCount = 0; var options = new ChatOptions { Tools = [ AIFunctionFactory.Create(() => { actualCallCount++; }, "VoidReturn"), ] }; List<ChatMessage> plan = [ new ChatMessage(ChatRole.User, "hello"), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent($"callId0", "VoidReturn")]), ]; // Note that this plan ends with a function call. Normally we would expect the system to try to resolve // the call, but it won't because of the maximum iterations limit. for (var i = 0; i < maxIterations; i++) { plan.Add(new ChatMessage(ChatRole.Tool, [new FunctionResultContent($"callId{i}", result: "Success: Function completed.")])); plan.Add(new ChatMessage(ChatRole.Assistant, [new FunctionCallContent($"callId{(i + 1)}", "VoidReturn")])); } await InvokeAndAssertAsync(options, plan, configurePipeline: configurePipeline); Assert.Equal(maxIterations, actualCallCount); actualCallCount = 0; await InvokeAndAssertStreamingAsync(options, plan, configurePipeline: configurePipeline); Assert.Equal(maxIterations, actualCallCount); } [Theory] [InlineData(false)] [InlineData(true)] public async Task ContinuesWithFailingCallsUntilMaximumConsecutiveErrors(bool allowConcurrentInvocation) { Func<ChatClientBuilder, ChatClientBuilder> configurePipeline = pipeline => pipeline .UseFunctionInvocation(configure: functionInvokingChatClient => { functionInvokingChatClient.MaximumConsecutiveErrorsPerRequest = 2; functionInvokingChatClient.AllowConcurrentInvocation = allowConcurrentInvocation; }); var options = new ChatOptions { Tools = [ AIFunctionFactory.Create((bool shouldThrow, int callIndex) => { if (shouldThrow) { throw new InvalidTimeZoneException($"Exception from call {callIndex}"); } }, "Func"), ] }; var callIndex = 0; List<ChatMessage> plan = [ new ChatMessage(ChatRole.User, "hello"), // A single failure isn't enough to stop the cycle ..CreateFunctionCallIterationPlan(ref callIndex, true, false), // Now NumConsecutiveErrors = 1 // We can reset the number of consecutive errors by having a successful iteration ..CreateFunctionCallIterationPlan(ref callIndex, false, false, false), // Now NumConsecutiveErrors = 0 // Any failure within an iteration causes the whole iteration to be treated as failed ..CreateFunctionCallIterationPlan(ref callIndex, false, true, false), // Now NumConsecutiveErrors = 1 // Even if several calls in the same iteration fail, that only counts as a single iteration having failed, so won't exceed the limit yet ..CreateFunctionCallIterationPlan(ref callIndex, true, true, true), // Now NumConsecutiveErrors = 2 // Any more failures will now exceed the limit ..CreateFunctionCallIterationPlan(ref callIndex, true, true), ]; if (allowConcurrentInvocation) { // With concurrent invocation, we always make all the calls in the iteration // and combine their exceptions into an AggregateException var ex = await Assert.ThrowsAsync<AggregateException>(() => InvokeAndAssertAsync(options, plan, configurePipeline: configurePipeline)); Assert.Equal(2, ex.InnerExceptions.Count); Assert.Equal("Exception from call 11", ex.InnerExceptions[0].Message); Assert.Equal("Exception from call 12", ex.InnerExceptions[1].Message); ex = await Assert.ThrowsAsync<AggregateException>(() => InvokeAndAssertStreamingAsync(options, plan, configurePipeline: configurePipeline)); Assert.Equal(2, ex.InnerExceptions.Count); Assert.Equal("Exception from call 11", ex.InnerExceptions[0].Message); Assert.Equal("Exception from call 12", ex.InnerExceptions[1].Message); } else { // With serial invocation, we allow the threshold-crossing exception to propagate // directly and terminate the iteration var ex = await Assert.ThrowsAsync<InvalidTimeZoneException>(() => InvokeAndAssertAsync(options, plan, configurePipeline: configurePipeline)); Assert.Equal("Exception from call 11", ex.Message); ex = await Assert.ThrowsAsync<InvalidTimeZoneException>(() => InvokeAndAssertStreamingAsync(options, plan, configurePipeline: configurePipeline)); Assert.Equal("Exception from call 11", ex.Message); } } [Theory] [InlineData(false)] [InlineData(true)] public async Task CanFailOnFirstException(bool allowConcurrentInvocation) { Func<ChatClientBuilder, ChatClientBuilder> configurePipeline = pipeline => pipeline .UseFunctionInvocation(configure: functionInvokingChatClient => { functionInvokingChatClient.MaximumConsecutiveErrorsPerRequest = 0; functionInvokingChatClient.AllowConcurrentInvocation = allowConcurrentInvocation; }); var options = new ChatOptions { Tools = [ AIFunctionFactory.Create(() => { throw new InvalidTimeZoneException($"It failed"); }, "Func"), ] }; var callIndex = 0; List<ChatMessage> plan = [ new ChatMessage(ChatRole.User, "hello"), ..CreateFunctionCallIterationPlan(ref callIndex, true), ]; // Regardless of AllowConcurrentInvocation, if there's only a single exception, // we don't wrap it in an AggregateException var ex = await Assert.ThrowsAsync<InvalidTimeZoneException>(() => InvokeAndAssertAsync(options, plan, configurePipeline: configurePipeline)); Assert.Equal("It failed", ex.Message); ex = await Assert.ThrowsAsync<InvalidTimeZoneException>(() => InvokeAndAssertStreamingAsync(options, plan, configurePipeline: configurePipeline)); Assert.Equal("It failed", ex.Message); } private static IEnumerable<ChatMessage> CreateFunctionCallIterationPlan(ref int callIndex, params bool[] shouldThrow) { var assistantMessage = new ChatMessage(ChatRole.Assistant, []); var toolMessage = new ChatMessage(ChatRole.Tool, []); foreach (var callShouldThrow in shouldThrow) { var thisCallIndex = callIndex++; var callId = $"callId{thisCallIndex}"; assistantMessage.Contents.Add(new FunctionCallContent(callId, "Func", arguments: new Dictionary<string, object?> { { "shouldThrow", callShouldThrow }, { "callIndex", thisCallIndex } })); toolMessage.Contents.Add(new FunctionResultContent(callId, result: callShouldThrow ? "Error: Function failed." : "Success")); } return [assistantMessage, toolMessage]; } [Fact] public async Task KeepsFunctionCallingContent() { var options = new ChatOptions { Tools = [ AIFunctionFactory.Create(() => "Result 1", "Func1"), AIFunctionFactory.Create((int i) => $"Result 2: {i}", "Func2"), AIFunctionFactory.Create((int i) => { }, "VoidReturn"), ] }; List<ChatMessage> plan = [ new ChatMessage(ChatRole.User, "hello"), new ChatMessage(ChatRole.Assistant, [new TextContent("extra"), new FunctionCallContent("callId1", "Func1"), new TextContent("stuff")]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId2", result: "Result 1")]), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId2", "Func2", arguments: new Dictionary<string, object?> { { "i", 42 } })]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId2", result: "Result 2: 42")]), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId3", "VoidReturn", arguments: new Dictionary<string, object?> { { "i", 43 } }), new TextContent("more")]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId3", result: "Success: Function completed.")]), new ChatMessage(ChatRole.Assistant, "world"), ]; #pragma warning disable SA1005, S125 Validate(await InvokeAndAssertAsync(options, plan)); Validate(await InvokeAndAssertStreamingAsync(options, plan)); static void Validate(List<ChatMessage> finalChat) { IEnumerable<AIContent> content = finalChat.SelectMany(m => m.Contents); Assert.Contains(content, c => c is FunctionCallContent or FunctionResultContent); } } [Theory] [InlineData(false)] [InlineData(true)] public async Task ExceptionDetailsOnlyReportedWhenRequestedAsync(bool detailedErrors) { var options = new ChatOptions { Tools = [ AIFunctionFactory.Create(string () => throw new InvalidOperationException("Oh no!"), "Func1"), ] }; List<ChatMessage> plan = [ new ChatMessage(ChatRole.User, "hello"), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId1", "Func1")]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId1", result: detailedErrors ? "Error: Function failed. Exception: Oh no!" : "Error: Function failed.")]), new ChatMessage(ChatRole.Assistant, "world"), ]; Func<ChatClientBuilder, ChatClientBuilder> configure = b => b.Use( s => new FunctionInvokingChatClient(s) { IncludeDetailedErrors = detailedErrors }); await InvokeAndAssertAsync(options, plan, configurePipeline: configure); await InvokeAndAssertStreamingAsync(options, plan, configurePipeline: configure); } [Theory] [InlineData(LogLevel.Trace)] [InlineData(LogLevel.Debug)] [InlineData(LogLevel.Information)] public async Task FunctionInvocationsLogged(LogLevel level) { List<ChatMessage> plan = [ new ChatMessage(ChatRole.User, "hello"), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId1", "Func1", new Dictionary<string, object?> { ["arg1"] = "value1" })]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId1", result: "Result 1")]), new ChatMessage(ChatRole.Assistant, "world"), ]; var options = new ChatOptions { Tools = [AIFunctionFactory.Create(() => "Result 1", "Func1")] }; Func<ChatClientBuilder, ChatClientBuilder> configure = b => b.Use((c, services) => new FunctionInvokingChatClient(c, services.GetRequiredService<ILoggerFactory>())); await InvokeAsync(services => InvokeAndAssertAsync(options, plan, configurePipeline: configure, services: services)); await InvokeAsync(services => InvokeAndAssertStreamingAsync(options, plan, configurePipeline: configure, services: services)); async Task InvokeAsync(Func<IServiceProvider, Task> work) { var collector = new FakeLogCollector(); ServiceCollection c = new(); c.AddLogging(b => b.AddProvider(new FakeLoggerProvider(collector)).SetMinimumLevel(level)); await work(c.BuildServiceProvider()); var logs = collector.GetSnapshot(); if (level is LogLevel.Trace) { Assert.Collection(logs, entry => Assert.True(entry.Message.Contains("Invoking Func1({") && entry.Message.Contains("\"arg1\": \"value1\"")), entry => Assert.True(entry.Message.Contains("Func1 invocation completed. Duration:") && entry.Message.Contains("Result: \"Result 1\""))); } else if (level is LogLevel.Debug) { Assert.Collection(logs, entry => Assert.True(entry.Message.Contains("Invoking Func1") && !entry.Message.Contains("arg1")), entry => Assert.True(entry.Message.Contains("Func1 invocation completed. Duration:") && !entry.Message.Contains("Result"))); } else { Assert.Empty(logs); } } } [Theory] [InlineData(false, false)] [InlineData(true, false)] [InlineData(true, true)] public async Task FunctionInvocationTrackedWithActivity(bool enableTelemetry, bool enableSensitiveData) { string sourceName = Guid.NewGuid().ToString(); List<ChatMessage> plan = [ new ChatMessage(ChatRole.User, "hello"), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId1", "Func1", new Dictionary<string, object?> { ["arg1"] = "value1" })]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId1", result: "Result 1")]), new ChatMessage(ChatRole.Assistant, "world"), ]; ChatOptions options = new() { Tools = [AIFunctionFactory.Create(() => "Result 1", "Func1")] }; Func<ChatClientBuilder, ChatClientBuilder> configure = b => b.Use(c => new FunctionInvokingChatClient(new OpenTelemetryChatClient(c, sourceName: sourceName) { EnableSensitiveData = enableSensitiveData })); await InvokeAsync(() => InvokeAndAssertAsync(options, plan, configurePipeline: configure)); await InvokeAsync(() => InvokeAndAssertStreamingAsync(options, plan, configurePipeline: configure)); async Task InvokeAsync(Func<Task> work) { var activities = new List<Activity>(); using TracerProvider? tracerProvider = enableTelemetry ? OpenTelemetry.Sdk.CreateTracerProviderBuilder() .AddSource(sourceName) .AddInMemoryExporter(activities) .Build() : null; await work(); if (enableTelemetry) { Assert.Collection(activities, activity => Assert.Equal("chat", activity.DisplayName), activity => Assert.Equal("execute_tool Func1", activity.DisplayName), activity => Assert.Equal("chat", activity.DisplayName), activity => Assert.Equal("orchestrate_tools", activity.DisplayName)); var executeTool = activities[1]; if (enableSensitiveData) { var args = Assert.Single(executeTool.Tags, t => t.Key == "gen_ai.tool.call.arguments"); Assert.Equal( JsonSerializer.Serialize(new Dictionary<string, object?> { ["arg1"] = "value1" }, AIJsonUtilities.DefaultOptions), args.Value); var result = Assert.Single(executeTool.Tags, t => t.Key == "gen_ai.tool.call.result"); Assert.Equal("Result 1", JsonSerializer.Deserialize<string>(result.Value!, AIJsonUtilities.DefaultOptions)); } else { Assert.DoesNotContain(executeTool.Tags, t => t.Key == "gen_ai.tool.call.arguments"); Assert.DoesNotContain(executeTool.Tags, t => t.Key == "gen_ai.tool.call.result"); } for (int i = 0; i < activities.Count - 1; i++) { // Activities are exported in the order of completion, so all except the last are children of the last (i.e., outer) Assert.Same(activities[activities.Count - 1], activities[i].Parent); } } else { Assert.Empty(activities); } } } [Fact] public async Task SupportsConsecutiveStreamingUpdatesWithFunctionCalls() { var options = new ChatOptions { Tools = [AIFunctionFactory.Create((string text) => $"Result for {text}", "Func1")] }; var messages = new List<ChatMessage> { new(ChatRole.User, "Hello"), }; using var innerClient = new TestChatClient { GetStreamingResponseAsyncCallback = (chatContents, chatOptions, cancellationToken) => { // If the conversation is just starting, issue two consecutive updates with function calls // Otherwise just end the conversation. List<ChatResponseUpdate> updates; string messageId = Guid.NewGuid().ToString("N"); if (chatContents.Last().Text == "Hello") { updates = [ new() { Contents = [new FunctionCallContent("callId1", "Func1", new Dictionary<string, object?> { ["text"] = "Input 1" })] }, new() { Contents = [new FunctionCallContent("callId2", "Func1", new Dictionary<string, object?> { ["text"] = "Input 2" })] } ]; } else { updates = [new() { Contents = [new TextContent("OK bye")] }]; } foreach (var update in updates) { update.MessageId = messageId; } return YieldAsync(updates); } }; using var client = new FunctionInvokingChatClient(innerClient); var response = await client.GetStreamingResponseAsync(messages, options, CancellationToken.None).ToChatResponseAsync(); // The returned message should include the FCCs and FRCs. Assert.Collection(response.Messages, m => Assert.Collection(m.Contents, c => Assert.Equal("Input 1", Assert.IsType<FunctionCallContent>(c).Arguments!["text"]), c => Assert.Equal("Input 2", Assert.IsType<FunctionCallContent>(c).Arguments!["text"])), m => Assert.Collection(m.Contents, c => Assert.Equal("Result for Input 1", Assert.IsType<FunctionResultContent>(c).Result?.ToString()), c => Assert.Equal("Result for Input 2", Assert.IsType<FunctionResultContent>(c).Result?.ToString())), m => Assert.Equal("OK bye", Assert.IsType<TextContent>(Assert.Single(m.Contents)).Text)); } [Fact] public async Task AllResponseMessagesReturned() { var options = new ChatOptions { Tools = [AIFunctionFactory.Create(() => "doesn't matter", "Func1")] }; var messages = new List<ChatMessage> { new(ChatRole.User, "Hello"), }; using var innerClient = new TestChatClient { GetResponseAsyncCallback = async (chatContents, chatOptions, cancellationToken) => { await Task.Yield(); ChatMessage message = chatContents.Count() is 1 or 3 ? new(ChatRole.Assistant, [new FunctionCallContent($"callId{chatContents.Count()}", "Func1")]) : new(ChatRole.Assistant, "The answer is 42."); return new(message); } }; using var client = new FunctionInvokingChatClient(innerClient); ChatResponse response = await client.GetResponseAsync(messages, options); Assert.Equal(5, response.Messages.Count); Assert.Equal("The answer is 42.", response.Text); Assert.IsType<FunctionCallContent>(Assert.Single(response.Messages[0].Contents)); Assert.IsType<FunctionResultContent>(Assert.Single(response.Messages[1].Contents)); Assert.IsType<FunctionCallContent>(Assert.Single(response.Messages[2].Contents)); Assert.IsType<FunctionResultContent>(Assert.Single(response.Messages[3].Contents)); Assert.IsType<TextContent>(Assert.Single(response.Messages[4].Contents)); } [Fact] public async Task CanAccesssFunctionInvocationContextFromFunctionCall() { var invocationContexts = new List<FunctionInvocationContext>(); var function = AIFunctionFactory.Create(async (int i) => { // The context should propogate across async calls await Task.Yield(); var context = FunctionInvokingChatClient.CurrentContext!; invocationContexts.Add(context); if (i == 42) { context.Terminate = true; } return $"Result {i}"; }, "Func1"); var options = new ChatOptions { Tools = [function], }; // The invocation loop should terminate after the second function call List<ChatMessage> planBeforeTermination = [ new ChatMessage(ChatRole.User, "hello"), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId1", "Func1", new Dictionary<string, object?> { ["i"] = 41 })]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId1", result: "Result 41")]), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId2", "Func1", new Dictionary<string, object?> { ["i"] = 42 })]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId2", result: "Result 42")]), ]; // The full plan should never be fulfilled List<ChatMessage> plan = [ .. planBeforeTermination, new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId3", "Func1", new Dictionary<string, object?> { ["i"] = 43 })]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId3", result: "Result 43")]), new ChatMessage(ChatRole.Assistant, "world"), ]; await InvokeAsync(() => InvokeAndAssertAsync(options, plan, planBeforeTermination)); await InvokeAsync(() => InvokeAndAssertStreamingAsync(options, plan, planBeforeTermination)); // The current context should be null outside the async call stack for the function invocation Assert.Null(FunctionInvokingChatClient.CurrentContext); async Task InvokeAsync(Func<Task<List<ChatMessage>>> work) { invocationContexts.Clear(); var messages = await work(); Assert.Collection(invocationContexts, c => AssertInvocationContext(c, iteration: 0, terminate: false), c => AssertInvocationContext(c, iteration: 1, terminate: true)); void AssertInvocationContext(FunctionInvocationContext context, int iteration, bool terminate) { Assert.NotNull(context); Assert.Equal(messages.Count, context.Messages.Count); Assert.Equal(string.Concat(messages), string.Concat(context.Messages)); Assert.Same(function, context.Function); Assert.Equal("Func1", context.CallContent.Name); Assert.Equal(0, context.FunctionCallIndex); Assert.Equal(1, context.FunctionCount); Assert.Equal(iteration, context.Iteration); Assert.Equal(terminate, context.Terminate); } } } [Fact] public async Task HaltFunctionCallingAfterTermination() { var function = AIFunctionFactory.Create((string? result = null) => { if (!string.IsNullOrEmpty(result)) { return result; } FunctionInvokingChatClient.CurrentContext!.Terminate = true; return (object?)null; }, "Search"); using var innerChatClient = new TestChatClient { GetResponseAsyncCallback = (chatContents, chatOptions, cancellationToken) => { // We can have a mixture of calls that are not terminated and terminated var existingSearchResult = chatContents.SingleOrDefault(m => m.Role == ChatRole.Tool); AIContent[] resultContents = existingSearchResult is not null && existingSearchResult.Contents.OfType<FunctionResultContent>().ToList() is { } frcs ? [new TextContent($"The search results were '{string.Join(", ", frcs.Select(frc => frc.Result))}'")] : [ new FunctionCallContent("callId1", "Search"), new FunctionCallContent("callId2", "Search", new Dictionary<string, object?> { { "result", "birds" } }), new FunctionCallContent("callId3", "Search"), ]; var message = new ChatMessage(ChatRole.Assistant, resultContents); return Task.FromResult(new ChatResponse(message)); } }; using var chatClient = new FunctionInvokingChatClient(innerChatClient); // The function should terminate the invocation loop without calling the inner client for a final answer // But it still makes all the function calls within the same iteration List<ChatMessage> messages = [new(ChatRole.User, "hello")]; var chatOptions = new ChatOptions { Tools = [function] }; var result = await chatClient.GetResponseAsync(messages, chatOptions); messages.AddMessages(result); // Application code can then set the results var lastMessage = messages.Last(); Assert.Equal(ChatRole.Tool, lastMessage.Role); var frcs = lastMessage.Contents.OfType<FunctionResultContent>().ToList(); Assert.Single(frcs); frcs[0].Result = "dogs"; // We can re-enter the function calling mechanism to get a final answer result = await chatClient.GetResponseAsync(messages, chatOptions); Assert.Equal("The search results were 'dogs'", result.Text); } [Fact] public async Task PropagatesResponseConversationIdToOptions() { var options = new ChatOptions { Tools = [AIFunctionFactory.Create(() => "Result 1", "Func1")], }; int iteration = 0; Func<IEnumerable<ChatMessage>, ChatOptions?, CancellationToken, ChatResponse> callback = (chatContents, chatOptions, cancellationToken) => { iteration++; if (iteration == 1) { Assert.Null(chatOptions?.ConversationId); return new ChatResponse(new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId-abc", "Func1")])) { ConversationId = "12345", }; } else if (iteration == 2) { Assert.Equal("12345", chatOptions?.ConversationId); return new ChatResponse(new ChatMessage(ChatRole.Assistant, "done!")); } else { throw new InvalidOperationException("Unexpected iteration"); } }; using var innerClient = new TestChatClient { GetResponseAsyncCallback = (chatContents, chatOptions, cancellationToken) => Task.FromResult(callback(chatContents, chatOptions, cancellationToken)), GetStreamingResponseAsyncCallback = (chatContents, chatOptions, cancellationToken) => YieldAsync(callback(chatContents, chatOptions, cancellationToken).ToChatResponseUpdates()), }; using IChatClient service = innerClient.AsBuilder().UseFunctionInvocation().Build(); iteration = 0; Assert.Equal("done!", (await service.GetResponseAsync("hey", options)).ToString()); iteration = 0; Assert.Equal("done!", (await service.GetStreamingResponseAsync("hey", options).ToChatResponseAsync()).ToString()); } [Fact] public async Task FunctionInvocations_PassesServices() { List<ChatMessage> plan = [ new ChatMessage(ChatRole.User, "hello"), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId1", "Func1", new Dictionary<string, object?> { ["arg1"] = "value1" })]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId1", result: "Result 1")]), new ChatMessage(ChatRole.Assistant, "world"), ]; ServiceCollection c = new(); IServiceProvider expected = c.BuildServiceProvider(); var options = new ChatOptions { Tools = [AIFunctionFactory.Create((IServiceProvider actual) => { Assert.Same(expected, actual); return "Result 1"; }, "Func1")] }; await InvokeAndAssertAsync(options, plan, services: expected); } [Fact] public async Task FunctionInvocations_InvokedOnOriginalSynchronizationContext() { SynchronizationContext ctx = new CustomSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(ctx); List<ChatMessage> plan = [ new ChatMessage(ChatRole.User, "hello"), new ChatMessage(ChatRole.Assistant, [ new FunctionCallContent("callId1", "Func1", new Dictionary<string, object?> { ["arg"] = "value1" }), new FunctionCallContent("callId2", "Func1", new Dictionary<string, object?> { ["arg"] = "value2" }), ]), new ChatMessage(ChatRole.Tool, [ new FunctionResultContent("callId2", result: "value1"), new FunctionResultContent("callId2", result: "value2") ]), new ChatMessage(ChatRole.Assistant, "world"), ]; var options = new ChatOptions { Tools = [AIFunctionFactory.Create(async (string arg, CancellationToken cancellationToken) => { await Task.Delay(1, cancellationToken); Assert.Same(ctx, SynchronizationContext.Current); return arg; }, "Func1")] }; Func<ChatClientBuilder, ChatClientBuilder> configurePipeline = builder => builder .Use(async (messages, options, next, cancellationToken) => { await Task.Delay(1, cancellationToken); await next(messages, options, cancellationToken); }) .UseOpenTelemetry() .UseFunctionInvocation(configure: c => { c.AllowConcurrentInvocation = true; c.IncludeDetailedErrors = true; }); await InvokeAndAssertAsync(options, plan, configurePipeline: configurePipeline); await InvokeAndAssertStreamingAsync(options, plan, configurePipeline: configurePipeline); } [Theory] [InlineData(false)] [InlineData(true)] public async Task TerminateOnUnknownCalls_ControlsBehaviorForUnknownFunctions(bool terminateOnUnknown) { ChatOptions options = new() { Tools = [AIFunctionFactory.Create((int i) => $"Known: {i}", "KnownFunc")] }; Func<ChatClientBuilder, ChatClientBuilder> configure = b => b.Use( s => new FunctionInvokingChatClient(s) { TerminateOnUnknownCalls = terminateOnUnknown }); if (!terminateOnUnknown) { List<ChatMessage> planForContinue = [ new(ChatRole.User, "hello"), new(ChatRole.Assistant, [ new FunctionCallContent("callId1", "UnknownFunc", new Dictionary<string, object?> { ["i"] = 1 }), new FunctionCallContent("callId2", "KnownFunc", new Dictionary<string, object?> { ["i"] = 2 }) ]), new(ChatRole.Tool, [ new FunctionResultContent("callId1", result: "Error: Requested function \"UnknownFunc\" not found."), new FunctionResultContent("callId2", result: "Known: 2") ]), new(ChatRole.Assistant, "done"), ]; await InvokeAndAssertAsync(options, planForContinue, configurePipeline: configure); await InvokeAndAssertStreamingAsync(options, planForContinue, configurePipeline: configure); } else { List<ChatMessage> fullPlanWithUnknown = [ new(ChatRole.User, "hello"), new(ChatRole.Assistant, [ new FunctionCallContent("callId1", "UnknownFunc", new Dictionary<string, object?> { ["i"] = 1 }), new FunctionCallContent("callId2", "KnownFunc", new Dictionary<string, object?> { ["i"] = 2 }) ]), new(ChatRole.Tool, [ new FunctionResultContent("callId1", result: "Error: Requested function \"UnknownFunc\" not found."), new FunctionResultContent("callId2", result: "Known: 2") ]), new(ChatRole.Assistant, "done"), ]; var expected = fullPlanWithUnknown.Take(2).ToList(); await InvokeAndAssertAsync(options, fullPlanWithUnknown, expected, configure); await InvokeAndAssertStreamingAsync(options, fullPlanWithUnknown, expected, configure); } } [Theory] [InlineData(false)] [InlineData(true)] public async Task RequestsWithOnlyFunctionDeclarations_TerminatesRegardlessOfTerminateOnUnknownCalls(bool terminateOnUnknown) { var declarationOnly = AIFunctionFactory.Create(() => "unused", "DefOnly").AsDeclarationOnly(); ChatOptions options = new() { Tools = [declarationOnly] }; List<ChatMessage> fullPlan = [ new(ChatRole.User, "hello"), new(ChatRole.Assistant, [new FunctionCallContent("callId1", "DefOnly")]), new(ChatRole.Tool, [new FunctionResultContent("callId1", result: "Should not be produced")]), new(ChatRole.Assistant, "world"), ]; List<ChatMessage> expected = fullPlan.Take(2).ToList(); Func<ChatClientBuilder, ChatClientBuilder> configure = b => b.Use( s => new FunctionInvokingChatClient(s) { TerminateOnUnknownCalls = terminateOnUnknown }); await InvokeAndAssertAsync(options, fullPlan, expected, configure); await InvokeAndAssertStreamingAsync(options, fullPlan, expected, configure); } [Fact] public async Task MixedKnownFunctionAndDeclaration_TerminatesWithoutInvokingKnown() { int invoked = 0; var known = AIFunctionFactory.Create(() => { invoked++; return "OK"; }, "Known"); var defOnly = AIFunctionFactory.Create(() => "unused", "DefOnly").AsDeclarationOnly(); var options = new ChatOptions { Tools = [known, defOnly] }; List<ChatMessage> fullPlan = [ new(ChatRole.User, "hi"), new(ChatRole.Assistant, [ new FunctionCallContent("callId1", "Known"), new FunctionCallContent("callId2", "DefOnly") ]), new(ChatRole.Tool, [new FunctionResultContent("callId1", result: "OK"), new FunctionResultContent("callId2", result: "nope")]), new(ChatRole.Assistant, "done"), ]; List<ChatMessage> expected = fullPlan.Take(2).ToList(); Func<ChatClientBuilder, ChatClientBuilder> configure = b => b.Use(s => new FunctionInvokingChatClient(s) { TerminateOnUnknownCalls = false }); await InvokeAndAssertAsync(options, fullPlan, expected, configure); Assert.Equal(0, invoked); invoked = 0; configure = b => b.Use(s => new FunctionInvokingChatClient(s) { TerminateOnUnknownCalls = true }); await InvokeAndAssertStreamingAsync(options, fullPlan, expected, configure); Assert.Equal(0, invoked); } [Fact] public async Task ClonesChatOptionsAndResetContinuationTokenForBackgroundResponsesAsync() { ChatOptions? actualChatOptions = null; using var innerChatClient = new TestChatClient { GetResponseAsyncCallback = (chatContents, chatOptions, cancellationToken) => { actualChatOptions = chatOptions; List<ChatMessage> messages = []; // Simulate the model returning a function call for the first call only if (!chatContents.Any(m => m.Contents.OfType<FunctionCallContent>().Any())) { messages.Add(new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId1", "Func1")])); } return Task.FromResult(new ChatResponse { Messages = messages }); } }; using var chatClient = new FunctionInvokingChatClient(innerChatClient); var originalChatOptions = new ChatOptions { Tools = [AIFunctionFactory.Create(() => { }, "Func1")], ContinuationToken = ResponseContinuationToken.FromBytes(new byte[] { 1, 2, 3, 4 }), }; await chatClient.GetResponseAsync("hi", originalChatOptions); // The original options should be cloned and have a null ContinuationToken Assert.NotSame(originalChatOptions, actualChatOptions); Assert.Null(actualChatOptions!.ContinuationToken); } [Fact] public async Task DoesNotCreateOrchestrateToolsSpanWhenInvokeAgentIsParent() { string agentSourceName = Guid.NewGuid().ToString(); string clientSourceName = Guid.NewGuid().ToString(); List<ChatMessage> plan = [ new ChatMessage(ChatRole.User, "hello"), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId1", "Func1")]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId1", result: "Result 1")]), new ChatMessage(ChatRole.Assistant, "world"), ]; ChatOptions options = new() { Tools = [AIFunctionFactory.Create(() => "Result 1", "Func1")] }; Func<ChatClientBuilder, ChatClientBuilder> configure = b => b.Use(c => new FunctionInvokingChatClient(new OpenTelemetryChatClient(c, sourceName: clientSourceName))); var activities = new List<Activity>(); using TracerProvider tracerProvider = OpenTelemetry.Sdk.CreateTracerProviderBuilder() .AddSource(agentSourceName) .AddSource(clientSourceName) .AddInMemoryExporter(activities) .Build(); using (var agentSource = new ActivitySource(agentSourceName)) using (var invokeAgentActivity = agentSource.StartActivity("invoke_agent")) { Assert.NotNull(invokeAgentActivity); await InvokeAndAssertAsync(options, plan, configurePipeline: configure); } Assert.DoesNotContain(activities, a => a.DisplayName == "orchestrate_tools"); Assert.Contains(activities, a => a.DisplayName == "chat"); Assert.Contains(activities, a => a.DisplayName == "execute_tool Func1"); var invokeAgent = Assert.Single(activities, a => a.DisplayName == "invoke_agent"); var childActivities = activities.Where(a => a != invokeAgent).ToList(); Assert.All(childActivities, activity => Assert.Same(invokeAgent, activity.Parent)); } [Fact] public async Task UsesAgentActivitySourceWhenInvokeAgentIsParent() { string agentSourceName = Guid.NewGuid().ToString(); string clientSourceName = Guid.NewGuid().ToString(); List<ChatMessage> plan = [ new ChatMessage(ChatRole.User, "hello"), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId1", "Func1")]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId1", result: "Result 1")]), new ChatMessage(ChatRole.Assistant, "world"), ]; ChatOptions options = new() { Tools = [AIFunctionFactory.Create(() => "Result 1", "Func1")] }; Func<ChatClientBuilder, ChatClientBuilder> configure = b => b.Use(c => new FunctionInvokingChatClient(new OpenTelemetryChatClient(c, sourceName: clientSourceName))); var activities = new List<Activity>(); using TracerProvider tracerProvider = OpenTelemetry.Sdk.CreateTracerProviderBuilder() .AddSource(agentSourceName) .AddSource(clientSourceName) .AddInMemoryExporter(activities) .Build(); using (var agentSource = new ActivitySource(agentSourceName)) using (var invokeAgentActivity = agentSource.StartActivity("invoke_agent")) { Assert.NotNull(invokeAgentActivity); await InvokeAndAssertAsync(options, plan, configurePipeline: configure); } var executeToolActivities = activities.Where(a => a.DisplayName == "execute_tool Func1").ToList(); Assert.NotEmpty(executeToolActivities); Assert.All(executeToolActivities, executeTool => Assert.Equal(agentSourceName, executeTool.Source.Name)); } public static IEnumerable<object[]> SensitiveDataPropagatesFromAgentActivityWhenInvokeAgentIsParent_MemberData() => from invokeAgentSensitiveData in new bool?[] { null, false, true } from innerOpenTelemetryChatClient in new bool?[] { null, false, true } select new object?[] { invokeAgentSensitiveData, innerOpenTelemetryChatClient }; [Theory] [MemberData(nameof(SensitiveDataPropagatesFromAgentActivityWhenInvokeAgentIsParent_MemberData))] public async Task SensitiveDataPropagatesFromAgentActivityWhenInvokeAgentIsParent( bool? invokeAgentSensitiveData, bool? innerOpenTelemetryChatClient) { string agentSourceName = Guid.NewGuid().ToString(); string clientSourceName = Guid.NewGuid().ToString(); List<ChatMessage> plan = [ new ChatMessage(ChatRole.User, "hello"), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId1", "Func1", new Dictionary<string, object?> { ["arg1"] = "secret" })]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId1", result: "Result 1")]), new ChatMessage(ChatRole.Assistant, "world"), ]; ChatOptions options = new() { Tools = [AIFunctionFactory.Create(() => "Result 1", "Func1")] }; var activities = new List<Activity>(); using TracerProvider tracerProvider = OpenTelemetry.Sdk.CreateTracerProviderBuilder() .AddSource(agentSourceName) .AddSource(clientSourceName) .AddInMemoryExporter(activities) .Build(); using (var agentSource = new ActivitySource(agentSourceName)) using (var invokeAgentActivity = agentSource.StartActivity("invoke_agent")) { if (invokeAgentSensitiveData is not null) { invokeAgentActivity?.SetCustomProperty("__EnableSensitiveData__", invokeAgentSensitiveData is true ? "true" : "false"); } await InvokeAndAssertAsync(options, plan, configurePipeline: b => { b.UseFunctionInvocation(); if (innerOpenTelemetryChatClient is not null) { b.UseOpenTelemetry(sourceName: clientSourceName, configure: c => { c.EnableSensitiveData = innerOpenTelemetryChatClient.Value; }); } return b; }); } var executeToolActivity = Assert.Single(activities, a => a.DisplayName == "execute_tool Func1"); var hasArguments = executeToolActivity.Tags.Any(t => t.Key == "gen_ai.tool.call.arguments"); var hasResult = executeToolActivity.Tags.Any(t => t.Key == "gen_ai.tool.call.result"); if (invokeAgentSensitiveData is true) { Assert.True(hasArguments, "Expected arguments to be logged when agent EnableSensitiveData is true"); Assert.True(hasResult, "Expected result to be logged when agent EnableSensitiveData is true"); var argsTag = Assert.Single(executeToolActivity.Tags, t => t.Key == "gen_ai.tool.call.arguments"); Assert.Contains("arg1", argsTag.Value); } else { Assert.False(hasArguments, "Expected arguments NOT to be logged when agent EnableSensitiveData is false"); Assert.False(hasResult, "Expected result NOT to be logged when agent EnableSensitiveData is false"); } } [Theory] [InlineData(false)] [InlineData(true)] public async Task CreatesOrchestrateToolsSpanWhenNoInvokeAgentParent(bool streaming) { string clientSourceName = Guid.NewGuid().ToString(); List<ChatMessage> plan = [ new ChatMessage(ChatRole.User, "hello"), new ChatMessage(ChatRole.Assistant, [new FunctionCallContent("callId1", "Func1")]), new ChatMessage(ChatRole.Tool, [new FunctionResultContent("callId1", result: "Result 1")]), new ChatMessage(ChatRole.Assistant, "world"), ]; ChatOptions options = new() { Tools = [AIFunctionFactory.Create(() => "Result 1", "Func1")] }; Func<ChatClientBuilder, ChatClientBuilder> configure = b => b.Use(c => new FunctionInvokingChatClient(new OpenTelemetryChatClient(c, sourceName: clientSourceName))); var activities = new List<Activity>(); using TracerProvider tracerProvider = OpenTelemetry.Sdk.CreateTracerProviderBuilder() .AddSource(clientSourceName) .AddInMemoryExporter(activities) .Build(); if (streaming) { await InvokeAndAssertStreamingAsync(options, plan, configurePipeline: configure); } else { await InvokeAndAssertAsync(options, plan, configurePipeline: configure); } var orchestrateTools = Assert.Single(activities, a => a.DisplayName == "orchestrate_tools"); var executeTools = activities.Where(a => a.DisplayName.StartsWith("execute_tool")).ToList(); Assert.NotEmpty(executeTools); foreach (var executeTool in executeTools) { Assert.Same(orchestrateTools, executeTool.Parent); } }
FunctionInvokingChatClientTests
csharp
AvaloniaUI__Avalonia
tests/Avalonia.Base.UnitTests/Data/DefaultValueConverterTests.cs
{ "start": 6005, "end": 6396 }
private class ____ { public ExplicitDouble(double value) { Value = value; } public double Value { get; } public static explicit operator double (ExplicitDouble v) { return v.Value; } } [TypeConverter(typeof(CustomTypeConverter))]
ExplicitDouble
csharp
AutoFixture__AutoFixture
Src/AutoFixtureUnitTest/Kernel/MultipleToEnumerableRelayTests.cs
{ "start": 166, "end": 5213 }
public class ____ { [Fact] public void SutIsSpecimenBuilder() { var sut = new MultipleToEnumerableRelay(); Assert.IsAssignableFrom<ISpecimenBuilder>(sut); } [Theory] [InlineData(null)] [InlineData(typeof(object))] [InlineData(typeof(Type))] [InlineData(1)] [InlineData(9992)] [InlineData("")] public void CreateFromNonMultipleRequestReturnsCorrectResult( object request) { // Arrange var sut = new MultipleToEnumerableRelay(); // Act var dummyContext = new DelegatingSpecimenContext(); var actual = sut.Create(request, dummyContext); // Assert var expected = new NoSpecimen(); Assert.Equal(expected, actual); } [Theory] [InlineData(typeof(object), 1)] [InlineData(typeof(string), 42)] [InlineData(typeof(int), 1337)] public void CreateFromMultipleRequestReturnsCorrectResult( Type itemType, int arrayLength) { // Arrange var sut = new MultipleToEnumerableRelay(); var context = new DelegatingSpecimenContext { OnResolve = r => { Assert.Equal( typeof(IEnumerable<>).MakeGenericType(itemType), r); return Array.CreateInstance((Type)itemType, arrayLength); } }; // Act var request = new MultipleRequest(itemType); var actual = sut.Create(request, context); // Assert Assert.IsAssignableFrom( typeof(IEnumerable<>).MakeGenericType(itemType), actual); var enumerable = Assert.IsAssignableFrom<System.Collections.IEnumerable>(actual); Assert.Equal(arrayLength, enumerable.Cast<object>().Count()); } [Theory] [InlineData("foo")] [InlineData("1")] [InlineData(false)] public void CreateFromMultipleRequestWithNonTypeRequestReturnsCorrectResult( object innerRequest) { // Arrange var sut = new MultipleToEnumerableRelay(); var request = new MultipleRequest(innerRequest); // Act var dummyContext = new DelegatingSpecimenContext(); var actual = sut.Create(request, dummyContext); // Assert var expected = new NoSpecimen(); Assert.Equal(expected, actual); } [Theory] [InlineData(typeof(bool), true, 53)] [InlineData(typeof(string), "ploeh", 9)] [InlineData(typeof(int), 7, 902)] public void CreateFromMultipleSeededRequestReturnsCorrectResult( Type itemType, object seed, int arrayLength) { // Arrange var sut = new MultipleToEnumerableRelay(); var context = new DelegatingSpecimenContext { OnResolve = r => { Assert.Equal( typeof(IEnumerable<>).MakeGenericType(itemType), r); return Array.CreateInstance((Type)itemType, arrayLength); } }; // Act var request = new MultipleRequest(new SeededRequest(itemType, seed)); var actual = sut.Create(request, context); // Assert Assert.IsAssignableFrom( typeof(IEnumerable<>).MakeGenericType(itemType), actual); var enumerable = Assert.IsAssignableFrom<System.Collections.IEnumerable>(actual); Assert.Equal(arrayLength, enumerable.Cast<object>().Count()); } [Theory] [InlineData("bar")] [InlineData("9")] [InlineData(true)] public void CreateFromMultipleSeededRequestWithNonTypeRequestReturnsCorrectResult( object innerRequest) { // Arrange var sut = new MultipleToEnumerableRelay(); var request = new MultipleRequest( new SeededRequest( innerRequest, new object())); // Act var dummyContext = new DelegatingSpecimenContext(); var actual = sut.Create(request, dummyContext); // Assert var expected = new NoSpecimen(); Assert.Equal(expected, actual); } [Fact] public void CreateWithNullContextThrows() { // Arrange var sut = new MultipleToEnumerableRelay(); // Act & assert var dummyRequest = new object(); Assert.Throws<ArgumentNullException>( () => sut.Create(dummyRequest, null)); } } }
MultipleToEnumerableRelayTests
csharp
dotnet__orleans
test/Tester/StorageFacet/Feature.Implementations/TableExampleStorage.cs
{ "start": 1897, "end": 2323 }
public static class ____ { public static void UseTableExampleStorage(this ISiloBuilder builder, string name) { builder.ConfigureServices(services => { services.AddKeyedTransient<IExampleStorageFactory, TableExampleStorageFactory>(name); services.AddTransient(typeof(TableExampleStorage<>)); }); } } }
TableExampleStorageExtensions
csharp
ServiceStack__ServiceStack
ServiceStack.OrmLite/src/ServiceStack.OrmLite/Legacy/OrmLiteWriteCommandExtensionsLegacy.cs
{ "start": 114, "end": 1196 }
public static class ____ { /// <summary> /// Delete rows using a SqlFormat filter. E.g: /// <para>db.Delete&lt;Person&gt;("Age > {0}", 42)</para> /// </summary> /// <returns>number of rows deleted</returns> [Obsolete(Messages.LegacyApi)] public static int DeleteFmt<T>(this IDbConnection dbConn, string sqlFilter, params object[] filterParams) { return dbConn.Exec(dbCmd => dbCmd.DeleteFmt<T>(sqlFilter, filterParams)); } /// <summary> /// Delete rows from the runtime table type using a SqlFormat filter. E.g: /// </summary> /// <para>db.DeleteFmt(typeof(Person), "Age = {0}", 27)</para> /// <returns>number of rows deleted</returns> [Obsolete(Messages.LegacyApi)] public static int DeleteFmt(this IDbConnection dbConn, Type tableType, string sqlFilter, params object[] filterParams) { return dbConn.Exec(dbCmd => dbCmd.DeleteFmt(tableType, sqlFilter, filterParams)); } } }
OrmLiteWriteCommandExtensionsLegacy
csharp
dotnet__extensions
src/Libraries/Microsoft.Extensions.DataIngestion.Abstractions/IngestionDocument.cs
{ "start": 399, "end": 2260 }
public sealed class ____ { /// <summary> /// Initializes a new instance of the <see cref="IngestionDocument"/> class. /// </summary> /// <param name="identifier">The unique identifier for the document.</param> /// <exception cref="ArgumentNullException"><paramref name="identifier"/> is <see langword="null"/>.</exception> public IngestionDocument(string identifier) { Identifier = Throw.IfNullOrEmpty(identifier); } /// <summary> /// Gets the unique identifier for the document. /// </summary> public string Identifier { get; } /// <summary> /// Gets the sections of the document. /// </summary> public IList<IngestionDocumentSection> Sections { get; } = []; /// <summary> /// Iterate over all elements in the document, including those in nested sections. /// </summary> /// <returns>An enumerable collection of elements.</returns> /// <remarks> /// Sections themselves are not included. /// </remarks> public IEnumerable<IngestionDocumentElement> EnumerateContent() { Stack<IngestionDocumentElement> elementsToProcess = new(); for (int sectionIndex = Sections.Count - 1; sectionIndex >= 0; sectionIndex--) { elementsToProcess.Push(Sections[sectionIndex]); } while (elementsToProcess.Count > 0) { IngestionDocumentElement currentElement = elementsToProcess.Pop(); if (currentElement is not IngestionDocumentSection nestedSection) { yield return currentElement; } else { for (int i = nestedSection.Elements.Count - 1; i >= 0; i--) { elementsToProcess.Push(nestedSection.Elements[i]); } } } } }
IngestionDocument
csharp
ChilliCream__graphql-platform
src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs
{ "start": 6355394, "end": 6356253 }
public partial record ____ { public CancelFusionConfigurationCompositionPayloadData(global::System.String __typename, global::System.Collections.Generic.IReadOnlyList<global::ChilliCream.Nitro.CommandLine.Cloud.Client.State.ICancelFusionConfigurationCompositionErrorData>? errors = default !) { this.__typename = __typename ?? throw new global::System.ArgumentNullException(nameof(__typename)); Errors = errors; } public global::System.String __typename { get; init; } public global::System.Collections.Generic.IReadOnlyList<global::ChilliCream.Nitro.CommandLine.Cloud.Client.State.ICancelFusionConfigurationCompositionErrorData>? Errors { get; init; } } [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
CancelFusionConfigurationCompositionPayloadData
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/src/Types.Analyzers/Errors.cs
{ "start": 10401, "end": 10947 }
record ____ must use the 'property:' target specifier", category: "TypeSystem", DiagnosticSeverity.Error, isEnabledByDefault: true); public static readonly DiagnosticDescriptor WrongAuthorizeAttribute = new( id: "HC0106", title: "Microsoft Authorization Attribute Not Allowed", messageFormat: "Use HotChocolate.Authorization.{0} instead", category: "TypeSystem", DiagnosticSeverity.Error, isEnabledByDefault: true); }
parameters
csharp
dotnet__extensions
test/Analyzers/Microsoft.Analyzers.Extra.Tests/CallAnalysis/LegacyLoggingTests.Extra.cs
{ "start": 28124, "end": 28970 }
partial class ____ { [Microsoft.Extensions.Logging.LoggerMessage(0, Microsoft.Extensions.Logging.LogLevel.Trace, ""Hello"")] internal static partial void Hello(this Microsoft.Extensions.Logging.ILogger? logger); } "; var l = await RoslynTestUtils.RunAnalyzerAndFixer( new CallAnalyzer(), new LegacyLoggingFixer(), new[] { Assembly.GetAssembly(typeof(ILogger))!, Assembly.GetAssembly(typeof(LoggerMessageAttribute))! }, new[] { OrriginalSource, OrriginalTarget }); var actualSource = l[0]; var actualTarget = l[1]; Assert.Equal(ExpectedSource.Replace("\r\n", "\n", StringComparison.Ordinal), actualSource); Assert.Equal(ExpectedTarget.Replace("\r\n", "\n", StringComparison.Ordinal), actualTarget); } }
Log
csharp
ServiceStack__ServiceStack.OrmLite
tests/ServiceStack.OrmLite.PostgreSQL.Tests/PgSqlTests.cs
{ "start": 97, "end": 1397 }
public class ____ { [Test] public void Can_create_NpgsqlParameter() { Assert.That(PgSql.Param("p", 1).NpgsqlDbType, Is.EqualTo(NpgsqlDbType.Integer)); Assert.That(PgSql.Param("p", "s").NpgsqlDbType, Is.EqualTo(NpgsqlDbType.Text)); Assert.That(PgSql.Param("p", 'c').NpgsqlDbType, Is.EqualTo(NpgsqlDbType.Char)); Assert.That(PgSql.Param("p", new [] { 1 }).NpgsqlDbType, Is.EqualTo(NpgsqlDbType.Integer | NpgsqlDbType.Array)); } [Test] public void Does_PgSqlArray() { Assert.That(PgSql.Array((string[])null), Is.EqualTo("ARRAY[]")); Assert.That(PgSql.Array(new string[0]), Is.EqualTo("ARRAY[]")); Assert.That(PgSql.Array(new int[0]), Is.EqualTo("ARRAY[]")); Assert.That(PgSql.Array(1,2,3), Is.EqualTo("ARRAY[1,2,3]")); Assert.That(PgSql.Array("A","B","C"), Is.EqualTo("ARRAY['A','B','C']")); Assert.That(PgSql.Array("A'B","C\"D"), Is.EqualTo("ARRAY['A''B','C\"D']")); Assert.That(PgSql.Array(new string[0], nullIfEmpty:true), Is.EqualTo("null")); Assert.That(PgSql.Array(new[]{"A","B","C"}, nullIfEmpty:true), Is.EqualTo("ARRAY['A','B','C']")); } } }
PgSqlTests
csharp
abpframework__abp
framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/Localization/AbpMvcDataAnnotationsLocalizationOptions.cs
{ "start": 153, "end": 771 }
public class ____ { public IDictionary<Assembly, Type> AssemblyResources { get; } public AbpMvcDataAnnotationsLocalizationOptions() { AssemblyResources = new Dictionary<Assembly, Type>(); } public void AddAssemblyResource( [NotNull] Type resourceType, params Assembly[] assemblies) { if (assemblies.IsNullOrEmpty()) { assemblies = new[] { resourceType.Assembly }; } foreach (var assembly in assemblies) { AssemblyResources[assembly] = resourceType; } } }
AbpMvcDataAnnotationsLocalizationOptions
csharp
grandnode__grandnode2
src/Web/Grand.Web.Admin/Controllers/ShippingController.cs
{ "start": 990, "end": 31152 }
public class ____ : BaseAdminController { #region Constructors public ShippingController( IShippingService shippingService, IShippingMethodService shippingMethodService, IPickupPointService pickupPointService, IDeliveryDateService deliveryDateService, IWarehouseService warehouseService, ISettingService settingService, ICountryService countryService, ITranslationService translationService, ILanguageService languageService, IStoreService storeService, IGroupService groupService) { _shippingService = shippingService; _shippingMethodService = shippingMethodService; _pickupPointService = pickupPointService; _deliveryDateService = deliveryDateService; _warehouseService = warehouseService; _settingService = settingService; _countryService = countryService; _translationService = translationService; _languageService = languageService; _storeService = storeService; _groupService = groupService; } #endregion #region Fields private readonly IShippingService _shippingService; private readonly IShippingMethodService _shippingMethodService; private readonly IPickupPointService _pickupPointService; private readonly IDeliveryDateService _deliveryDateService; private readonly IWarehouseService _warehouseService; private readonly ISettingService _settingService; private readonly ICountryService _countryService; private readonly ITranslationService _translationService; private readonly ILanguageService _languageService; private readonly IStoreService _storeService; private readonly IGroupService _groupService; #endregion #region Utilities protected virtual async Task PrepareAddressWarehouseModel(WarehouseModel model) { model.Address.AvailableCountries.Add(new SelectListItem { Text = _translationService.GetResource("Admin.Address.SelectCountry"), Value = "" }); foreach (var c in await _countryService.GetAllCountries(showHidden: true)) model.Address.AvailableCountries.Add(new SelectListItem { Text = c.Name, Value = c.Id, Selected = c.Id == model.Address.CountryId }); //states var states = !string.IsNullOrEmpty(model.Address.CountryId) ? (await _countryService.GetCountryById(model.Address.CountryId))?.StateProvinces : new List<StateProvince>(); if (states?.Count > 0) foreach (var s in states) model.Address.AvailableStates.Add(new SelectListItem { Text = s.Name, Value = s.Id, Selected = s.Id == model.Address.StateProvinceId }); model.Address.CountryEnabled = true; model.Address.StateProvinceEnabled = true; model.Address.CityEnabled = true; model.Address.StreetAddressEnabled = true; model.Address.ZipPostalCodeEnabled = true; model.Address.ZipPostalCodeRequired = true; model.Address.PhoneEnabled = true; model.Address.FaxEnabled = true; model.Address.CompanyEnabled = true; } protected virtual async Task PreparePickupPointModel(PickupPointModel model) { model.Address.AvailableCountries.Add(new SelectListItem { Text = _translationService.GetResource("Admin.Address.SelectCountry"), Value = "" }); foreach (var c in await _countryService.GetAllCountries(showHidden: true)) model.Address.AvailableCountries.Add(new SelectListItem { Text = c.Name, Value = c.Id, Selected = c.Id == model.Address.CountryId }); //states var states = !string.IsNullOrEmpty(model.Address.CountryId) ? (await _countryService.GetCountryById(model.Address.CountryId))?.StateProvinces : new List<StateProvince>(); if (states?.Count > 0) foreach (var s in states) model.Address.AvailableStates.Add(new SelectListItem { Text = s.Name, Value = s.Id, Selected = s.Id == model.Address.StateProvinceId }); model.Address.CountryEnabled = true; model.Address.StateProvinceEnabled = true; model.Address.CityEnabled = true; model.Address.StreetAddressEnabled = true; model.Address.ZipPostalCodeEnabled = true; model.Address.ZipPostalCodeRequired = true; model.Address.PhoneEnabled = true; model.Address.FaxEnabled = true; model.Address.CompanyEnabled = true; model.AvailableStores.Add(new SelectListItem { Text = _translationService.GetResource("Admin.Configuration.Shipping.PickupPoint.SelectStore"), Value = "" }); foreach (var c in await _storeService.GetAllStores()) model.AvailableStores.Add(new SelectListItem { Text = c.Shortcut, Value = c.Id }); model.AvailableWarehouses.Add(new SelectListItem { Text = _translationService.GetResource("Admin.Configuration.Shipping.PickupPoint.SelectWarehouse"), Value = "" }); foreach (var c in await _warehouseService.GetAllWarehouses()) model.AvailableWarehouses.Add(new SelectListItem { Text = c.Name, Value = c.Id }); } #endregion #region Shipping rate methods public IActionResult Providers() { return View(); } [HttpPost] public async Task<IActionResult> Providers(DataSourceRequest command) { var storeScope = await GetActiveStore(); var _shippingProviderSettings = await _settingService.LoadSetting<ShippingProviderSettings>(storeScope); var shippingProvidersModel = new List<ShippingRateComputationMethodModel>(); var shippingProviders = _shippingService.LoadAllShippingRateCalculationProviders(); foreach (var shippingProvider in shippingProviders) { var tmp1 = shippingProvider.ToModel(); tmp1.IsActive = shippingProvider.IsShippingRateMethodActive(_shippingProviderSettings); shippingProvidersModel.Add(tmp1); } shippingProvidersModel = shippingProvidersModel.ToList(); var gridModel = new DataSourceResult { Data = shippingProvidersModel, Total = shippingProvidersModel.Count }; return Json(gridModel); } [HttpPost] public async Task<IActionResult> ProviderUpdate(ShippingRateComputationMethodModel model) { var storeScope = await GetActiveStore(); var _shippingProviderSettings = await _settingService.LoadSetting<ShippingProviderSettings>(storeScope); var srcm = _shippingService.LoadShippingRateCalculationProviderBySystemName(model.SystemName); if (srcm.IsShippingRateMethodActive(_shippingProviderSettings)) { if (!model.IsActive) { //mark as disabled _shippingProviderSettings.ActiveSystemNames.Remove(srcm.SystemName); await _settingService.SaveSetting(_shippingProviderSettings, storeScope); } } else { if (model.IsActive) { //mark as active _shippingProviderSettings.ActiveSystemNames.Add(srcm.SystemName); await _settingService.SaveSetting(_shippingProviderSettings, storeScope); } } return new JsonResult(""); } #endregion #region Shipping methods public IActionResult Methods() { return View(); } [HttpPost] public async Task<IActionResult> Methods(DataSourceRequest command) { var shippingMethodsModel = (await _shippingMethodService.GetAllShippingMethods()) .Select(x => x.ToModel()) .ToList(); var gridModel = new DataSourceResult { Data = shippingMethodsModel, Total = shippingMethodsModel.Count }; return Json(gridModel); } public async Task<IActionResult> CreateMethod() { var model = new ShippingMethodModel(); //locales await AddLocales(_languageService, model.Locales); return View(model); } [HttpPost] [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")] public async Task<IActionResult> CreateMethod(ShippingMethodModel model, bool continueEditing) { if (ModelState.IsValid) { var sm = model.ToEntity(); await _shippingMethodService.InsertShippingMethod(sm); Success(_translationService.GetResource("Admin.Configuration.Shipping.Methods.Added")); return continueEditing ? RedirectToAction("EditMethod", new { id = sm.Id }) : RedirectToAction("Methods"); } //If we got this far, something failed, redisplay form return View(model); } public async Task<IActionResult> EditMethod(string id) { var sm = await _shippingMethodService.GetShippingMethodById(id); if (sm == null) //No shipping method found with the specified id return RedirectToAction("Methods"); var model = sm.ToModel(); //locales await AddLocales(_languageService, model.Locales, (locale, languageId) => { locale.Name = sm.GetTranslation(x => x.Name, languageId, false); locale.Description = sm.GetTranslation(x => x.Description, languageId, false); }); return View(model); } [HttpPost] [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")] public async Task<IActionResult> EditMethod(ShippingMethodModel model, bool continueEditing) { var sm = await _shippingMethodService.GetShippingMethodById(model.Id); if (sm == null) //No shipping method found with the specified id return RedirectToAction("Methods"); if (ModelState.IsValid) { sm = model.ToEntity(sm); await _shippingMethodService.UpdateShippingMethod(sm); Success(_translationService.GetResource("Admin.Configuration.Shipping.Methods.Updated")); return continueEditing ? RedirectToAction("EditMethod", new { id = sm.Id }) : RedirectToAction("Methods"); } //If we got this far, something failed, redisplay form return View(model); } [HttpPost] public async Task<IActionResult> DeleteMethod(string id) { var sm = await _shippingMethodService.GetShippingMethodById(id); if (sm == null) //No shipping method found with the specified id return RedirectToAction("Methods"); await _shippingMethodService.DeleteShippingMethod(sm); Success(_translationService.GetResource("Admin.Configuration.Shipping.Methods.Deleted")); return RedirectToAction("Methods"); } #endregion #region Shipping Settings public async Task<IActionResult> Settings() { //load settings for a chosen store scope var storeScope = await GetActiveStore(); var shippingSettings = await _settingService.LoadSetting<ShippingSettings>(storeScope); var model = shippingSettings.ToModel(); model.ActiveStore = storeScope; //shipping origin var originAddress = shippingSettings.ShippingOriginAddress; if (originAddress != null) model.ShippingOriginAddress = await originAddress.ToModel(_countryService); else model.ShippingOriginAddress = new AddressModel(); model.ShippingOriginAddress.AvailableCountries.Add(new SelectListItem { Text = _translationService.GetResource("Admin.Address.SelectCountry"), Value = "" }); foreach (var c in await _countryService.GetAllCountries(showHidden: true)) model.ShippingOriginAddress.AvailableCountries.Add(new SelectListItem { Text = c.Name, Value = c.Id, Selected = originAddress != null && c.Id == originAddress.CountryId }); var states = originAddress != null && !string.IsNullOrEmpty(originAddress.CountryId) ? (await _countryService.GetCountryById(originAddress.CountryId))?.StateProvinces : new List<StateProvince>(); if (states?.Count > 0) foreach (var s in states) model.ShippingOriginAddress.AvailableStates.Add(new SelectListItem { Text = s.Name, Value = s.Id, Selected = s.Id == originAddress.StateProvinceId }); model.ShippingOriginAddress.CountryEnabled = true; model.ShippingOriginAddress.StateProvinceEnabled = true; model.ShippingOriginAddress.CityEnabled = true; model.ShippingOriginAddress.StreetAddressEnabled = true; model.ShippingOriginAddress.ZipPostalCodeEnabled = true; model.ShippingOriginAddress.ZipPostalCodeRequired = true; model.ShippingOriginAddress.AddressTypeEnabled = false; return View(model); } [HttpPost] public async Task<IActionResult> Settings(ShippingSettingsModel model) { //load settings for a chosen store scope var storeScope = await GetActiveStore(); var shippingSettings = await _settingService.LoadSetting<ShippingSettings>(storeScope); shippingSettings = model.ToEntity(shippingSettings); await _settingService.SaveSetting(shippingSettings, storeScope); Success(_translationService.GetResource("Admin.Configuration.Updated")); return RedirectToAction("Settings"); } #endregion #region Delivery dates public IActionResult DeliveryDates() { return View(); } [HttpPost] public async Task<IActionResult> DeliveryDates(DataSourceRequest command) { var deliveryDatesModel = (await _deliveryDateService.GetAllDeliveryDates()) .Select(x => x.ToModel()) .ToList(); var gridModel = new DataSourceResult { Data = deliveryDatesModel, Total = deliveryDatesModel.Count }; return Json(gridModel); } public async Task<IActionResult> CreateDeliveryDate() { var model = new DeliveryDateModel { ColorSquaresRgb = "#000000" }; //locales await AddLocales(_languageService, model.Locales); return View(model); } [HttpPost] [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")] public async Task<IActionResult> CreateDeliveryDate(DeliveryDateModel model, bool continueEditing) { if (ModelState.IsValid) { var deliveryDate = model.ToEntity(); await _deliveryDateService.InsertDeliveryDate(deliveryDate); Success(_translationService.GetResource("Admin.Configuration.Shipping.DeliveryDates.Added")); return continueEditing ? RedirectToAction("EditDeliveryDate", new { id = deliveryDate.Id }) : RedirectToAction("DeliveryDates"); } //If we got this far, something failed, redisplay form return View(model); } public async Task<IActionResult> EditDeliveryDate(string id) { var deliveryDate = await _deliveryDateService.GetDeliveryDateById(id); if (deliveryDate == null) //No delivery date found with the specified id return RedirectToAction("DeliveryDates"); var model = deliveryDate.ToModel(); if (string.IsNullOrEmpty(model.ColorSquaresRgb)) model.ColorSquaresRgb = "#000000"; //locales await AddLocales(_languageService, model.Locales, (locale, languageId) => { locale.Name = deliveryDate.GetTranslation(x => x.Name, languageId, false); }); return View(model); } [HttpPost] [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")] public async Task<IActionResult> EditDeliveryDate(DeliveryDateModel model, bool continueEditing) { var deliveryDate = await _deliveryDateService.GetDeliveryDateById(model.Id); if (deliveryDate == null) //No delivery date found with the specified id return RedirectToAction("DeliveryDates"); if (ModelState.IsValid) { deliveryDate = model.ToEntity(deliveryDate); await _deliveryDateService.UpdateDeliveryDate(deliveryDate); //locales Success(_translationService.GetResource("Admin.Configuration.Shipping.DeliveryDates.Updated")); return continueEditing ? RedirectToAction("EditDeliveryDate", new { id = deliveryDate.Id }) : RedirectToAction("DeliveryDates"); } //If we got this far, something failed, redisplay form return View(model); } [HttpPost] public async Task<IActionResult> DeleteDeliveryDate(string id) { var deliveryDate = await _deliveryDateService.GetDeliveryDateById(id); if (deliveryDate == null) //No delivery date found with the specified id return RedirectToAction("DeliveryDates"); if (ModelState.IsValid) { await _deliveryDateService.DeleteDeliveryDate(deliveryDate); Success(_translationService.GetResource("Admin.Configuration.Shipping.DeliveryDates.Deleted")); return RedirectToAction("DeliveryDates"); } Error(ModelState); return RedirectToAction("EditDeliveryDate", new { id }); } #endregion #region Warehouses public IActionResult Warehouses() { return View(); } [HttpPost] public async Task<IActionResult> Warehouses(DataSourceRequest command) { var warehousesModel = (await _warehouseService.GetAllWarehouses()) .Select(x => x.ToModel()) .ToList(); var gridModel = new DataSourceResult { Data = warehousesModel, Total = warehousesModel.Count }; return Json(gridModel); } public async Task<IActionResult> CreateWarehouse() { var model = new WarehouseModel(); await PrepareAddressWarehouseModel(model); return View(model); } [HttpPost] [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")] public async Task<IActionResult> CreateWarehouse(WarehouseModel model, bool continueEditing) { if (ModelState.IsValid) { var warehouse = model.ToEntity(); var address = model.Address.ToEntity(); warehouse.Address = address; await _warehouseService.InsertWarehouse(warehouse); Success(_translationService.GetResource("Admin.Configuration.Shipping.Warehouses.Added")); return continueEditing ? RedirectToAction("EditWarehouse", new { id = warehouse.Id }) : RedirectToAction("Warehouses"); } //If we got this far, something failed, redisplay form await PrepareAddressWarehouseModel(model); return View(model); } public async Task<IActionResult> EditWarehouse(string id) { var warehouse = await _warehouseService.GetWarehouseById(id); if (warehouse == null) //No warehouse found with the specified id return RedirectToAction("Warehouses"); var model = warehouse.ToModel(); await PrepareAddressWarehouseModel(model); return View(model); } [HttpPost] [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")] public async Task<IActionResult> EditWarehouse(WarehouseModel model, bool continueEditing) { var warehouse = await _warehouseService.GetWarehouseById(model.Id); if (warehouse == null) //No warehouse found with the specified id return RedirectToAction("Warehouses"); if (ModelState.IsValid) { warehouse = model.ToEntity(warehouse); await _warehouseService.UpdateWarehouse(warehouse); Success(_translationService.GetResource("Admin.Configuration.Shipping.Warehouses.Updated")); return continueEditing ? RedirectToAction("EditWarehouse", new { id = warehouse.Id }) : RedirectToAction("Warehouses"); } //If we got this far, something failed, redisplay form await PrepareAddressWarehouseModel(model); return View(model); } [HttpPost] public async Task<IActionResult> DeleteWarehouse(string id) { var warehouse = await _warehouseService.GetWarehouseById(id); if (warehouse == null) //No warehouse found with the specified id return RedirectToAction("Warehouses"); await _warehouseService.DeleteWarehouse(warehouse); Success(_translationService.GetResource("Admin.Configuration.Shipping.warehouses.Deleted")); return RedirectToAction("Warehouses"); } #endregion #region PickupPoints public IActionResult PickupPoints() { return View(); } [HttpPost] public async Task<IActionResult> PickupPoints(DataSourceRequest command) { var pickupPointsModel = (await _pickupPointService.GetAllPickupPoints()) .Select(x => x.ToModel()) .ToList(); var gridModel = new DataSourceResult { Data = pickupPointsModel, Total = pickupPointsModel.Count }; return Json(gridModel); } public async Task<IActionResult> CreatePickupPoint() { var model = new PickupPointModel(); await PreparePickupPointModel(model); return View(model); } [HttpPost] [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")] public async Task<IActionResult> CreatePickupPoint(PickupPointModel model, bool continueEditing) { if (ModelState.IsValid) { var pickuppoint = model.ToEntity(); await _pickupPointService.InsertPickupPoint(pickuppoint); Success(_translationService.GetResource("Admin.Configuration.Shipping.PickupPoints.Added")); return continueEditing ? RedirectToAction("EditPickupPoint", new { id = pickuppoint.Id }) : RedirectToAction("PickupPoints"); } //If we got this far, something failed, redisplay form await PreparePickupPointModel(model); return View(model); } public async Task<IActionResult> EditPickupPoint(string id) { var pickuppoint = await _pickupPointService.GetPickupPointById(id); if (pickuppoint == null) //No pickup pint found with the specified id return RedirectToAction("PickupPoints"); var model = pickuppoint.ToModel(); await PreparePickupPointModel(model); return View(model); } [HttpPost] [ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")] public async Task<IActionResult> EditPickupPoint(PickupPointModel model, bool continueEditing) { var pickupPoint = await _pickupPointService.GetPickupPointById(model.Id); if (pickupPoint == null) //No pickup point found with the specified id return RedirectToAction("PickupPoints"); if (ModelState.IsValid) { pickupPoint = model.ToEntity(pickupPoint); await _pickupPointService.UpdatePickupPoint(pickupPoint); Success(_translationService.GetResource("Admin.Configuration.Shipping.PickupPoints.Updated")); return continueEditing ? RedirectToAction("EditPickupPoint", new { id = pickupPoint.Id }) : RedirectToAction("PickupPoints"); } //If we got this far, something failed, redisplay form await PreparePickupPointModel(model); return View(model); } [HttpPost] public async Task<IActionResult> DeletePickupPoint(string id) { var pickupPoint = await _pickupPointService.GetPickupPointById(id); if (pickupPoint == null) //No pickup point found with the specified id return RedirectToAction("PickupPoints"); await _pickupPointService.DeletePickupPoint(pickupPoint); Success(_translationService.GetResource("Admin.Configuration.Shipping.PickupPoints.Deleted")); return RedirectToAction("PickupPoints"); } #endregion #region Restrictions public async Task<IActionResult> Restrictions() { var model = new ShippingMethodRestrictionModel(); var countries = await _countryService.GetAllCountries(showHidden: true); var shippingMethods = await _shippingMethodService.GetAllShippingMethods(); var customerGroups = await _groupService.GetAllCustomerGroups(); foreach (var country in countries) model.AvailableCountries.Add(new CountryModel { Id = country.Id, Name = country.Name }); foreach (var sm in shippingMethods) model.AvailableShippingMethods.Add(new ShippingMethodModel { Id = sm.Id, Name = sm.Name }); foreach (var r in customerGroups) model.AvailableCustomerGroups.Add(new CustomerGroupModel { Id = r.Id, Name = r.Name }); foreach (var country in countries) foreach (var shippingMethod in shippingMethods) { var restricted = shippingMethod.CountryRestrictionExists(country.Id); if (!model.Restricted.ContainsKey(country.Id)) model.Restricted[country.Id] = new Dictionary<string, bool>(); model.Restricted[country.Id][shippingMethod.Id] = restricted; } foreach (var role in customerGroups) foreach (var shippingMethod in shippingMethods) { var restricted = shippingMethod.CustomerGroupRestrictionExists(role.Id); if (!model.RestictedGroup.ContainsKey(role.Id)) model.RestictedGroup[role.Id] = new Dictionary<string, bool>(); model.RestictedGroup[role.Id][shippingMethod.Id] = restricted; } return View(model); } [HttpPost] [ActionName("Restrictions")] [RequestFormLimits(ValueCountLimit = 2048)] public async Task<IActionResult> RestrictionSave(IDictionary<string, string[]> model) { var countries = await _countryService.GetAllCountries(showHidden: true); var shippingMethods = await _shippingMethodService.GetAllShippingMethods(); var customerGroups = await _groupService.GetAllCustomerGroups(); foreach (var shippingMethod in shippingMethods) { await SaveRestrictedCountries(model, shippingMethod, countries); await SaveRestrictedGroup(model, shippingMethod, customerGroups); } Success(_translationService.GetResource("Admin.Configuration.Shipping.Restrictions.Updated")); //selected tab await SaveSelectedTabIndex(); return RedirectToAction("Restrictions"); } private async Task SaveRestrictedGroup(IDictionary<string, string[]> model, ShippingMethod shippingMethod, IPagedList<CustomerGroup> customerGroups) { if (model.TryGetValue($"restrictgroup_{shippingMethod.Id}", out var roleIds)) { var roleIdsToRestrict = roleIds.ToList(); foreach (var role in customerGroups) { var restrict = roleIdsToRestrict.Contains(role.Id); if (restrict) { if (shippingMethod.RestrictedGroups.FirstOrDefault(c => c == role.Id) == null) { shippingMethod.RestrictedGroups.Add(role.Id); await _shippingMethodService.UpdateShippingMethod(shippingMethod); } } else { if (shippingMethod.RestrictedGroups.FirstOrDefault(c => c == role.Id) != null) { shippingMethod.RestrictedGroups.Remove(role.Id); await _shippingMethodService.UpdateShippingMethod(shippingMethod); } } } } else { shippingMethod.RestrictedGroups.Clear(); await _shippingMethodService.UpdateShippingMethod(shippingMethod); } } private async Task SaveRestrictedCountries(IDictionary<string, string[]> model, ShippingMethod shippingMethod, IList<Country> countries) { if (model.TryGetValue($"restrict_{shippingMethod.Id}", out var countryIds)) { var countryIdsToRestrict = countryIds.ToList(); foreach (var country in countries) { var restrict = countryIdsToRestrict.Contains(country.Id); if (restrict) { if (shippingMethod.RestrictedCountries.FirstOrDefault(c => c.Id == country.Id) == null) { shippingMethod.RestrictedCountries.Add(country); await _shippingMethodService.UpdateShippingMethod(shippingMethod); } } else { if (shippingMethod.RestrictedCountries.FirstOrDefault(c => c.Id == country.Id) != null) { shippingMethod.RestrictedCountries.Remove( shippingMethod.RestrictedCountries.FirstOrDefault(x => x.Id == country.Id)); await _shippingMethodService.UpdateShippingMethod(shippingMethod); } } } } else { shippingMethod.RestrictedCountries.Clear(); await _shippingMethodService.UpdateShippingMethod(shippingMethod); } } #endregion }
ShippingController
csharp
DuendeSoftware__IdentityServer
bff/src/Bff/Otel/LogMessages.cs
{ "start": 11116, "end": 12037 }
record ____ store for sub {{{OTelParameters.Sub}}} sid {{{OTelParameters.Sid}}}")] // public static partial void GettingUserSession(this ILogger logger, LogLevel logLevel, string sub, string? sid); // // [LoggerMessage( // message: // $"Getting {{{OTelParameters.Count}}} user session(s) from store for sub {{{OTelParameters.Sub}}} sid {{{OTelParameters.Sid}}}")] // public static partial void GettingUserSessions(this ILogger logger, LogLevel logLevel, int count, string? sub, string? sid); // // [LoggerMessage( // message: // $"Deleting {{{OTelParameters.Count}}} user session(s) from store for sub {{{OTelParameters.Sub}}} sid {{{OTelParameters.Sid}}}")] // public static partial void DeletingUserSessions(this ILogger logger, LogLevel logLevel, int count, string? sub, string? sid); // // [LoggerMessage( // message: // $"Updating user session
from
csharp
unoplatform__uno
src/Uno.UI.Tests/Global.cs
{ "start": 206, "end": 995 }
public static class ____ { [AssemblyInitialize] public static void GlobalTestInitialize(TestContext _) { // Ensure all tests are run under the same culture context Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; var factory = LoggerFactory.Create(builder => { #if false // DEBUG // debug logging is generally very verbose and slows down testing. Enable when needed. var logLevel = LogLevel.Debug; #else var logLevel = LogLevel.None; #endif builder.SetMinimumLevel(logLevel); builder.AddConsole(); }); Uno.UI.Adapter.Microsoft.Extensions.Logging.LoggingAdapter.Initialize(); Uno.Extensions.LogExtensionPoint.AmbientLoggerFactory = factory; } } }
Global
csharp
MassTransit__MassTransit
src/MassTransit.Abstractions/Middleware/ConnectPipeOptions.cs
{ "start": 60, "end": 183 }
public enum ____ { ConfigureConsumeTopology = 1, All = ConfigureConsumeTopology } }
ConnectPipeOptions
csharp
ChilliCream__graphql-platform
src/Nullable.cs
{ "start": 4665, "end": 4977 }
sealed class ____ : Attribute; /// <summary>Specifies that the method will not return if the associated Boolean parameter is passed the specified value.</summary> [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] #if INTERNAL_NULLABLE_ATTRIBUTES internal #else public #endif
DoesNotReturnAttribute
csharp
grpc__grpc-dotnet
test/Grpc.Net.Client.Tests/Infrastructure/WinHttpHandler.cs
{ "start": 753, "end": 897 }
public class ____ : DelegatingHandler { public WinHttpHandler(HttpMessageHandler innerHandler) : base(innerHandler) { } }
WinHttpHandler
csharp
smartstore__Smartstore
src/Smartstore.Core/Data/Migrations/IMigrationTable.cs
{ "start": 2347, "end": 2456 }
public interface ____<TContext> : IMigrationTable where TContext : HookingDbContext { } }
IMigrationTable
csharp
RicoSuter__NSwag
src/NSwag.CodeGeneration.TypeScript/InjectionTokenType.cs
{ "start": 506, "end": 757 }
public enum ____ { /// <summary>Use the legacy/obsolete OpaqueToken (pre Angular 4).</summary> OpaqueToken, /// <summary>Use the new InjectionToken class (Angular 4+).</summary> InjectionToken } }
InjectionTokenType
csharp
dotnet__BenchmarkDotNet
src/BenchmarkDotNet/Disassemblers/Exporters/HtmlDisassemblyExporter.cs
{ "start": 315, "end": 5086 }
internal class ____ : ExporterBase { private static readonly Lazy<string> HighlightingLabelsScript = new Lazy<string>(() => ResourceHelper.LoadTemplate("highlightingLabelsScript.js")); private readonly IReadOnlyDictionary<BenchmarkCase, DisassemblyResult> results; private readonly DisassemblyDiagnoserConfig config; internal HtmlDisassemblyExporter(IReadOnlyDictionary<BenchmarkCase, DisassemblyResult> results, DisassemblyDiagnoserConfig config) { this.results = results; this.config = config; } protected override string FileExtension => "html"; protected override string FileCaption => "asm"; public override void ExportToLog(Summary summary, ILogger logger) { logger.WriteLine("<!DOCTYPE html><html lang='en'><head><meta charset='utf-8' /><head>"); logger.WriteLine($"<title>Pretty Output of DisassemblyDiagnoser for {summary.Title}</title>"); logger.WriteLine(InstructionPointerExporter.CssStyle); logger.WriteLine(@" <style type='text/css'> td.label:hover { cursor: pointer; background-color: yellow !important; } td.highlighted { background-color: yellow !important; } </style></head><body>"); logger.WriteLine("<script src=\"https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js\"></script>"); logger.WriteLine($"<script>{HighlightingLabelsScript.Value}</script>"); int referenceIndex = 0; foreach (var benchmarkCase in summary.BenchmarksCases.Where(results.ContainsKey)) { Export(logger, summary, results[benchmarkCase], benchmarkCase, ref referenceIndex); } logger.WriteLine("</body></html>"); } private void Export(ILogger logger, Summary summary, DisassemblyResult disassemblyResult, BenchmarkCase benchmarkCase, ref int referenceIndex) { logger.WriteLine($"<h2>{summary[benchmarkCase].GetRuntimeInfo()}</h2>"); logger.WriteLine($"<h3>Job: {benchmarkCase.Job.DisplayInfo}</h3>"); logger.WriteLine("<table><tbody>"); int methodIndex = 0; foreach (var method in disassemblyResult.Methods.Where(method => string.IsNullOrEmpty(method.Problem))) { referenceIndex++; logger.WriteLine($"<tr><th colspan=\"2\" style=\"text-align: left;\">{method.Name}</th><th></th></tr>"); var pretty = DisassemblyPrettifier.Prettify(method, disassemblyResult, config, $"M{methodIndex++:00}"); bool even = false, diffTheLabels = pretty.Count > 1; foreach (var element in pretty) { if (element is DisassemblyPrettifier.Label label) { even = !even; logger.WriteLine($"<tr class=\"{(even && diffTheLabels ? "evenMap" : string.Empty)}\">"); logger.WriteLine($"<td id=\"{referenceIndex}_{label.Id}\" class=\"label\" data-label=\"{referenceIndex}_{label.TextRepresentation}\"><pre><code>{label.TextRepresentation}</pre></code></td>"); logger.WriteLine("<td>&nbsp;</td></tr>"); continue; } logger.WriteLine($"<tr class=\"{(even && diffTheLabels ? "evenMap" : string.Empty)}\">"); logger.Write("<td></td>"); if (element is DisassemblyPrettifier.Reference reference) logger.WriteLine($"<td id=\"{referenceIndex}\" class=\"reference\" data-reference=\"{referenceIndex}_{reference.Id}\"><a href=\"#{referenceIndex}_{reference.Id}\"><pre><code>{reference.TextRepresentation}</pre></code></a></td>"); else logger.WriteLine($"<td><pre><code>{element.TextRepresentation}</pre></code></td>"); logger.Write("</tr>"); } logger.WriteLine("<tr><td colspan=\"{2}\">&nbsp;</td></tr>"); } foreach (var withProblems in disassemblyResult.Methods .Where(method => !string.IsNullOrEmpty(method.Problem)) .GroupBy(method => method.Problem)) { logger.WriteLine($"<tr><td colspan=\"{2}\"><b>{withProblems.Key}</b></td></tr>"); foreach (var withProblem in withProblems) { logger.WriteLine($"<tr><td colspan=\"{2}\">{withProblem.Name}</td></tr>"); } logger.WriteLine("<tr><td colspan=\"{2}\"></td></tr>"); } logger.WriteLine("</tbody></table>"); } } }
HtmlDisassemblyExporter
csharp
HangfireIO__Hangfire
src/Hangfire.Core/Common/Job.cs
{ "start": 18571, "end": 22835 }
class ____ on the /// given expression tree of an instance method call with explicit /// type specification. /// </summary> /// <typeparam name="TType">Explicit type that should be used on method call.</typeparam> /// <param name="methodCall">Expression tree of a method call on <typeparamref name="TType"/>.</param> /// /// <exception cref="ArgumentNullException"><paramref name="methodCall"/> is null.</exception> /// <exception cref="ArgumentException"> /// <paramref name="methodCall"/> expression body is not of type /// <see cref="MethodCallExpression"/>.</exception> /// <exception cref="NotSupportedException"><paramref name="methodCall"/> /// expression contains a method that is not supported.</exception> /// /// <remarks> /// <para>All the arguments are evaluated using the expression compiler /// that uses caching where possible to decrease the performance /// penalty.</para> /// </remarks> public static Job FromExpression<TType>([NotNull, InstantHandle] Expression<Func<TType, Task>> methodCall) { return FromExpression(methodCall, null); } public static Job FromExpression<TType>([NotNull, InstantHandle] Expression<Func<TType, Task>> methodCall, [CanBeNull] string queue) { return FromExpression(methodCall, typeof(TType), queue); } private static Job FromExpression([NotNull] LambdaExpression methodCall, [CanBeNull] Type explicitType, [CanBeNull] string queue) { if (methodCall == null) throw new ArgumentNullException(nameof(methodCall)); var callExpression = methodCall.Body as MethodCallExpression; if (callExpression == null) { throw new ArgumentException("Expression body should be of type `MethodCallExpression`", nameof(methodCall)); } var type = explicitType ?? callExpression.Method.DeclaringType; var method = callExpression.Method; if (explicitType == null && callExpression.Object != null) { // Creating a job that is based on a scope variable. We should infer its // type and method based on its value, and not from the expression tree. // TODO: BREAKING: Consider removing this special case entirely. // People consider that the whole object is serialized, this is not true. var objectValue = GetExpressionValue(callExpression.Object); if (objectValue == null) { throw new InvalidOperationException("Expression object should be not null."); } // TODO: BREAKING: Consider using `callExpression.Object.Type` expression instead. type = objectValue.GetType(); // If an expression tree is based on interface, we should use its own // MethodInfo instance, based on the same method name and parameter types. method = type.GetNonOpenMatchingMethod( callExpression.Method.Name, callExpression.Method.GetParameters().Select(static x => x.ParameterType).ToArray()); } return new Job( // ReSharper disable once AssignNullToNotNullAttribute type, method, GetExpressionValues(callExpression.Arguments), queue); } private static void Validate( Type type, [InvokerParameterName] string typeParameterName, MethodInfo method, // ReSharper disable once UnusedParameter.Local [InvokerParameterName] string methodParameterName, // ReSharper disable once UnusedParameter.Local int argumentCount, [InvokerParameterName] string argumentParameterName) { if (!method.IsPublic) { throw new NotSupportedException("Only public methods can be invoked in the background. Ensure your method has the `public` access modifier, and you aren't using explicit
based