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
microsoft__PowerToys
src/dsc/v3/PowerToys.DSC.UnitTests/SettingsResourceTests/SettingsResourceModuleTest`1.cs
{ "start": 611, "end": 9518 }
public abstract class ____<TSettingsConfig> : BaseDscTest where TSettingsConfig : ISettingsConfig, new() { private readonly SettingsUtils _settingsUtils = new(); private TSettingsConfig _originalSettings; protected TSettingsConfig DefaultSettings => new(); protected string Module { get; } protected List<string> DiffSettings { get; } = [SettingsResourceObject<AwakeSettings>.SettingsJsonPropertyName]; protected List<string> DiffEmpty { get; } = []; public SettingsResourceModuleTest(string module) { Module = module; } [TestInitialize] public void TestInitialize() { _originalSettings = GetSettings(); ResetSettingsToDefaultValues(); } [TestCleanup] public void TestCleanup() { SaveSettings(_originalSettings); } [TestMethod] public void Get_Success() { // Arrange var settingsBeforeExecute = GetSettings(); // Act var result = ExecuteDscCommand<GetCommand>("--resource", SettingsResource.ResourceName, "--module", Module); var state = result.OutputState<SettingsResourceObject<TSettingsConfig>>(); // Assert Assert.IsTrue(result.Success); AssertSettingsAreEqual(settingsBeforeExecute, GetSettings()); AssertStateAndSettingsAreEqual(settingsBeforeExecute, state); } [TestMethod] public void Export_Success() { // Arrange var settingsBeforeExecute = GetSettings(); // Act var result = ExecuteDscCommand<ExportCommand>("--resource", SettingsResource.ResourceName, "--module", Module); var state = result.OutputState<SettingsResourceObject<TSettingsConfig>>(); // Assert Assert.IsTrue(result.Success); AssertSettingsAreEqual(settingsBeforeExecute, GetSettings()); AssertStateAndSettingsAreEqual(settingsBeforeExecute, state); } [TestMethod] public void SetWithDiff_Success() { // Arrange var settingsModifier = GetSettingsModifier(); var input = CreateInputResourceObject(settingsModifier); // Act var result = ExecuteDscCommand<SetCommand>("--resource", SettingsResource.ResourceName, "--module", Module, "--input", input); var (state, diff) = result.OutputStateAndDiff<SettingsResourceObject<TSettingsConfig>>(); // Assert Assert.IsTrue(result.Success); AssertSettingsHasChanged(settingsModifier); AssertStateAndSettingsAreEqual(GetSettings(), state); CollectionAssert.AreEqual(DiffSettings, diff); } [TestMethod] public void SetWithoutDiff_Success() { // Arrange var settingsModifier = GetSettingsModifier(); UpdateSettings(settingsModifier); var settingsBeforeExecute = GetSettings(); var input = CreateInputResourceObject(settingsModifier); // Act var result = ExecuteDscCommand<SetCommand>("--resource", SettingsResource.ResourceName, "--module", Module, "--input", input); var (state, diff) = result.OutputStateAndDiff<SettingsResourceObject<TSettingsConfig>>(); // Assert Assert.IsTrue(result.Success); AssertSettingsAreEqual(settingsBeforeExecute, GetSettings()); AssertStateAndSettingsAreEqual(settingsBeforeExecute, state); CollectionAssert.AreEqual(DiffEmpty, diff); } [TestMethod] public void TestWithDiff_Success() { // Arrange var settingsModifier = GetSettingsModifier(); var settingsBeforeExecute = GetSettings(); var input = CreateInputResourceObject(settingsModifier); // Act var result = ExecuteDscCommand<TestCommand>("--resource", SettingsResource.ResourceName, "--module", Module, "--input", input); var (state, diff) = result.OutputStateAndDiff<SettingsResourceObject<TSettingsConfig>>(); // Assert Assert.IsTrue(result.Success); AssertSettingsAreEqual(settingsBeforeExecute, GetSettings()); AssertStateAndSettingsAreEqual(settingsBeforeExecute, state); CollectionAssert.AreEqual(DiffSettings, diff); Assert.IsFalse(state.InDesiredState); } [TestMethod] public void TestWithoutDiff_Success() { // Arrange var settingsModifier = GetSettingsModifier(); UpdateSettings(settingsModifier); var settingsBeforeExecute = GetSettings(); var input = CreateInputResourceObject(settingsModifier); // Act var result = ExecuteDscCommand<TestCommand>("--resource", SettingsResource.ResourceName, "--module", Module, "--input", input); var (state, diff) = result.OutputStateAndDiff<SettingsResourceObject<TSettingsConfig>>(); // Assert Assert.IsTrue(result.Success); AssertSettingsAreEqual(settingsBeforeExecute, GetSettings()); AssertStateAndSettingsAreEqual(settingsBeforeExecute, state); CollectionAssert.AreEqual(DiffEmpty, diff); Assert.IsTrue(state.InDesiredState); } /// <summary> /// Gets the settings modifier action for the specific settings configuration. /// </summary> /// <returns>An action that modifies the settings configuration.</returns> protected abstract Action<TSettingsConfig> GetSettingsModifier(); /// <summary> /// Resets the settings to default values. /// </summary> private void ResetSettingsToDefaultValues() { SaveSettings(DefaultSettings); } /// <summary> /// Get the settings for the specified module. /// </summary> /// <returns>An instance of the settings type with the current configuration.</returns> private TSettingsConfig GetSettings() { return _settingsUtils.GetSettingsOrDefault<TSettingsConfig>(DefaultSettings.GetModuleName()); } /// <summary> /// Saves the settings for the specified module. /// </summary> /// <param name="settings">Settings to save.</param> private void SaveSettings(TSettingsConfig settings) { _settingsUtils.SaveSettings(JsonSerializer.Serialize(settings), DefaultSettings.GetModuleName()); } /// <summary> /// Create the resource object for the operation. /// </summary> /// <param name="settings">Settings to include in the resource object.</param> /// <returns>A JSON string representing the resource object.</returns> private string CreateResourceObject(TSettingsConfig settings) { var resourceObject = new SettingsResourceObject<TSettingsConfig> { Settings = settings, }; return JsonSerializer.Serialize(resourceObject); } private string CreateInputResourceObject(Action<TSettingsConfig> settingsModifier) { var settings = DefaultSettings; settingsModifier(settings); return CreateResourceObject(settings); } /// <summary> /// Create the response for the Get operation. /// </summary> /// <returns>A JSON string representing the response.</returns> private string CreateGetResponse() { return CreateResourceObject(GetSettings()); } /// <summary> /// Asserts that the state and settings are equal. /// </summary> /// <param name="settings">Settings manifest to compare against.</param> /// <param name="state">Output state to compare.</param> private void AssertStateAndSettingsAreEqual(TSettingsConfig settings, SettingsResourceObject<TSettingsConfig> state) { AssertSettingsAreEqual(settings, state.Settings); } /// <summary> /// Asserts that two settings manifests are equal. /// </summary> /// <param name="expected">Expected settings.</param> /// <param name="actual">Actual settings.</param> private void AssertSettingsAreEqual(TSettingsConfig expected, TSettingsConfig actual) { var expectedJson = JsonSerializer.SerializeToNode(expected) as JsonObject; var actualJson = JsonSerializer.SerializeToNode(actual) as JsonObject; Assert.IsTrue(JsonNode.DeepEquals(expectedJson, actualJson)); } /// <summary> /// Asserts that the current settings have changed. /// </summary> /// <param name="action">Action to prepare the default settings.</param> private void AssertSettingsHasChanged(Action<TSettingsConfig> action) { var currentSettings = GetSettings(); var defaultSettings = DefaultSettings; action(defaultSettings); AssertSettingsAreEqual(defaultSettings, currentSettings); } /// <summary> /// Updates the settings. /// </summary> /// <param name="action">Action to modify the settings.</param> private void UpdateSettings(Action<TSettingsConfig> action) { var settings = GetSettings(); action(settings); SaveSettings(settings); } }
SettingsResourceModuleTest
csharp
neuecc__MessagePack-CSharp
sandbox/SharedData/Class1.cs
{ "start": 8486, "end": 9054 }
public class ____ : IMessagePackSerializationCallbackReceiver { [Key(0)] public int X { get; set; } [IgnoreMember] public bool CalledBefore { get; private set; } [IgnoreMember] public bool CalledAfter { get; private set; } public Callback1(int x) { } public void OnBeforeSerialize() { this.CalledBefore = true; } public void OnAfterDeserialize() { this.CalledAfter = true; } } [MessagePackObject]
Callback1
csharp
aspnetboilerplate__aspnetboilerplate
test/Abp.EntityFrameworkCore.Tests/Tests/ExplicitLoading_Tests.cs
{ "start": 219, "end": 1862 }
public class ____ : EntityFrameworkCoreModuleTestBase { private readonly IRepository<Blog> _blogRepository; private readonly IRepository<Post, Guid> _postRepository; public ExplicitLoading_Tests() { _blogRepository = Resolve<IRepository<Blog>>(); _postRepository = Resolve<IRepository<Post, Guid>>(); } [Fact] public async Task Should_Explicitly_Load_Collections() { var uowManager = Resolve<IUnitOfWorkManager>(); using (var uow = uowManager.Begin()) { var blog = await _blogRepository.FirstOrDefaultAsync(b => b.Name == "test-blog-1"); blog.ShouldNotBeNull(); blog.Posts.ShouldBeNull(); //Because EF core does not have lazy loading yet! await _blogRepository.EnsureCollectionLoadedAsync(blog, b => b.Posts); blog.Posts.ShouldNotBeNull(); //Now loaded it! blog.Posts.Count.ShouldBeGreaterThan(0); await uow.CompleteAsync(); } } [Fact] public async Task Should_Explicitly_Load_Properties() { using (var uow = Resolve<IUnitOfWorkManager>().Begin()) { var post = await _postRepository.FirstOrDefaultAsync(b => b.Title == "test-post-1-title"); post.ShouldNotBeNull(); post.Blog.ShouldBeNull(); //Because EF core does not have lazy loading yet! await _postRepository.EnsurePropertyLoadedAsync(post, p => p.Blog); post.Blog.ShouldNotBeNull(); //Now loaded it! post.Blog.Name.ShouldBe("test-blog-1"); await uow.CompleteAsync(); } } }
ExplicitLoading_Tests
csharp
unoplatform__uno
src/Uno.UI.RuntimeTests/Tests/NativeCtorGeneratorTests/GameBoardCanvas.cs
{ "start": 104, "end": 340 }
public partial class ____ : Android.Views.View { public MyCustomView(Context context) : base(context) { } public MyCustomView(Context context, Android.Util.IAttributeSet attributeSet) : base(context, attributeSet) { } }
MyCustomView
csharp
louthy__language-ext
LanguageExt.Core/Effects/IO/DSL/IOLocal.cs
{ "start": 99, "end": 278 }
abstract record ____<A>(Func<EnvIO, EnvIO> MapEnvIO) : IO<A> { public abstract IO<A> MakeOperation(); public override string ToString() => "IO local"; }
IOLocal
csharp
EventStore__EventStore
src/KurrentDB.SecondaryIndexing/Indexes/EventType/EventTypeSql.cs
{ "start": 597, "end": 1385 }
public struct ____ : IQuery<ReadEventTypeIndexQueryArgs, IndexQueryRecord> { public static BindingContext Bind(in ReadEventTypeIndexQueryArgs args, PreparedStatement statement) => new(statement) { args.EventType, args.StartPosition, args.EndPosition, args.Count }; public static ReadOnlySpan<byte> CommandText => "select log_position, commit_position, event_number from idx_all where event_type=$1 and log_position>$2 and log_position<$3 order by rowid limit $4"u8; public static IndexQueryRecord Parse(ref DataChunk.Row row) => new(row.ReadInt64(), row.TryReadInt64(), row.ReadInt64()); } /// <summary> /// Get index records for a given event type where the log position is greater or equal the start position /// </summary>
ReadEventTypeIndexQueryExcl
csharp
dotnetcore__Util
test/Util.Ui.NgZorro.Tests/TreeTables/TreeTableColumnTagHelperTest.cs
{ "start": 360, "end": 8815 }
public class ____ { #region 测试初始化 /// <summary> /// 输出工具 /// </summary> private readonly ITestOutputHelper _output; /// <summary> /// TagHelper包装器 /// </summary> private readonly TagHelperWrapper<Customer> _wrapper; /// <summary> /// 测试初始化 /// </summary> public TreeTableColumnTagHelperTest( ITestOutputHelper output ) { Id.SetId( "id" ); _output = output; _wrapper = new TableColumnTagHelper().ToWrapper<Customer>(); } #endregion #region 辅助操作 /// <summary> /// 获取结果 /// </summary> private string GetResult() { var result = _wrapper.GetResult(); _output.WriteLine( result ); return result; } /// <summary> /// 添加启用扩展的表格起始标签 /// </summary> /// <param name="result">结果</param> private void AppendExtendTable( StringBuilder result ) { result.Append( "<nz-table #x_id=\"xTableExtend\" " ); result.Append( "(nzPageIndexChange)=\"x_id.pageIndexChange($event)\" (nzPageSizeChange)=\"x_id.pageSizeChange($event)\" " ); result.Append( "x-table-extend=\"\" " ); result.Append( "[(nzPageIndex)]=\"x_id.queryParam.page\" [(nzPageSize)]=\"x_id.queryParam.pageSize\" " ); result.Append( "[nzData]=\"x_id.dataSource\" " ); result.Append( "[nzFrontPagination]=\"false\" [nzLoading]=\"x_id.loading\" [nzShowQuickJumper]=\"true\" " ); result.Append( "[nzShowSizeChanger]=\"true\" [nzShowTotal]=\"total_id\" [nzTotal]=\"x_id.total\">" ); } /// <summary> /// 添加表格总行数模板标签 /// </summary> /// <param name="result">结果</param> private void AppendTotalTemplate( StringBuilder result ) { result.Append( "<ng-template #total_id=\"\" let-range=\"range\" let-total=\"\">" ); result.Append( "{{ 'util.tableTotalTemplate'|i18n:{start:range[0],end:range[1],total:total} }}" ); result.Append( "</ng-template>" ); } #endregion #region Checkbox /// <summary> /// 测试设置复选框 /// </summary> [Fact] public void TestCheckbox() { _wrapper.SetItem( new TableShareConfig( "id" ) { IsEnableExtend = true,IsShowCheckbox = true,IsTreeTable = true } ); _wrapper.SetContextAttribute( UiConst.Column, "a" ); var result = new StringBuilder(); result.Append( "<td " ); result.Append( "(nzExpandChange)=\"x_id.collapse(row,$event)\" " ); result.Append( "[nzExpand]=\"x_id.isExpand(row)\" " ); result.Append( "[nzIndentSize]=\"row.level*x_id.config.table.indentUnitWidth\" " ); result.Append( "[nzShowExpand]=\"!x_id.isLeaf(row)\"" ); result.Append( ">" ); result.Append( "<label " ); result.Append( "(nzCheckedChange)=\"x_id.toggle(row)\" " ); result.Append( "nz-checkbox=\"\" " ); result.Append( "[nzChecked]=\"x_id.isChecked(row)\" " ); result.Append( "[nzIndeterminate]=\"x_id.isIndeterminate(row)\">" ); result.Append( "{{row.a}}" ); result.Append( "</label>" ); result.Append( "</td>" ); Assert.Equal( result.ToString(), GetResult() ); } #endregion #region Radio /// <summary> /// 测试设置单选框 /// </summary> [Fact] public void TestRadio_1() { _wrapper.SetItem( new TableShareConfig( "id" ) { IsEnableExtend = true, IsShowRadio = true, IsTreeTable = true } ); _wrapper.SetContextAttribute( UiConst.Column, "a" ); var result = new StringBuilder(); result.Append( "<td " ); result.Append( "(nzExpandChange)=\"x_id.collapse(row,$event)\" " ); result.Append( "[nzExpand]=\"x_id.isExpand(row)\" " ); result.Append( "[nzIndentSize]=\"row.level*x_id.config.table.indentUnitWidth\" " ); result.Append( "[nzShowExpand]=\"!x_id.isLeaf(row)\"" ); result.Append( ">" ); result.Append( "<label (click)=\"$event.stopPropagation()\" (ngModelChange)=\"x_id.checkRowOnly(row)\" name=\"r_x_id\" nz-radio=\"\" [ngModel]=\"x_id.isChecked(row)\">" ); result.Append( "{{row.a}}" ); result.Append( "</label>" ); result.Append( "</td>" ); Assert.Equal( result.ToString(), GetResult() ); } /// <summary> /// 测试设置单选框 - 如果已设置复选框,则单选框不生效 /// </summary> [Fact] public void TestRadio_2() { _wrapper.SetItem( new TableShareConfig( "id" ) { IsEnableExtend = true, IsShowCheckbox = true, IsShowRadio = true, IsTreeTable = true } ); _wrapper.SetContextAttribute( UiConst.Column, "a" ); var result = new StringBuilder(); result.Append( "<td " ); result.Append( "(nzExpandChange)=\"x_id.collapse(row,$event)\" " ); result.Append( "[nzExpand]=\"x_id.isExpand(row)\" " ); result.Append( "[nzIndentSize]=\"row.level*x_id.config.table.indentUnitWidth\" " ); result.Append( "[nzShowExpand]=\"!x_id.isLeaf(row)\"" ); result.Append( ">" ); result.Append( "<label " ); result.Append( "(nzCheckedChange)=\"x_id.toggle(row)\" " ); result.Append( "nz-checkbox=\"\" " ); result.Append( "[nzChecked]=\"x_id.isChecked(row)\" " ); result.Append( "[nzIndeterminate]=\"x_id.isIndeterminate(row)\">" ); result.Append( "{{row.a}}" ); result.Append( "</label>" ); result.Append( "</td>" ); Assert.Equal( result.ToString(), GetResult() ); } #endregion #region CheckboxLeft /// <summary> /// 测试固定复选框 /// </summary> [Fact] public void TestCheckboxLeft() { _wrapper.SetItem( new TableShareConfig( "id" ) { IsEnableExtend = true, IsShowCheckbox = true, IsCheckboxLeft = "a", IsTreeTable = true } ); _wrapper.SetContextAttribute( UiConst.Column, "a" ); var result = new StringBuilder(); result.Append( "<td " ); result.Append( "(nzExpandChange)=\"x_id.collapse(row,$event)\" nzLeft=\"a\" " ); result.Append( "[nzExpand]=\"x_id.isExpand(row)\" " ); result.Append( "[nzIndentSize]=\"row.level*x_id.config.table.indentUnitWidth\" " ); result.Append( "[nzShowExpand]=\"!x_id.isLeaf(row)\"" ); result.Append( ">" ); result.Append( "<label " ); result.Append( "(nzCheckedChange)=\"x_id.toggle(row)\" " ); result.Append( "nz-checkbox=\"\" " ); result.Append( "[nzChecked]=\"x_id.isChecked(row)\" " ); result.Append( "[nzIndeterminate]=\"x_id.isIndeterminate(row)\">" ); result.Append( "{{row.a}}" ); result.Append( "</label>" ); result.Append( "</td>" ); Assert.Equal( result.ToString(), GetResult() ); } #endregion #region RadioLeft /// <summary> /// 测试固定单选框 /// </summary> [Fact] public void TestRadioLeft() { _wrapper.SetItem( new TableShareConfig( "id" ) { IsEnableExtend = true, IsShowRadio = true,IsRadioLeft = "a",IsTreeTable = true } ); _wrapper.SetContextAttribute( UiConst.Column, "a" ); var result = new StringBuilder(); result.Append( "<td " ); result.Append( "(nzExpandChange)=\"x_id.collapse(row,$event)\" nzLeft=\"a\" " ); result.Append( "[nzExpand]=\"x_id.isExpand(row)\" " ); result.Append( "[nzIndentSize]=\"row.level*x_id.config.table.indentUnitWidth\" " ); result.Append( "[nzShowExpand]=\"!x_id.isLeaf(row)\"" ); result.Append( ">" ); result.Append( "<label (click)=\"$event.stopPropagation()\" (ngModelChange)=\"x_id.checkRowOnly(row)\" name=\"r_x_id\" nz-radio=\"\" [ngModel]=\"x_id.isChecked(row)\">" ); result.Append( "{{row.a}}" ); result.Append( "</label>" ); result.Append( "</td>" ); Assert.Equal( result.ToString(), GetResult() ); } #endregion } }
TreeTableColumnTagHelperTest
csharp
dotnet__aspnetcore
src/HealthChecks/Abstractions/src/HealthReportEntry.cs
{ "start": 416, "end": 3927 }
public struct ____ { private static readonly IReadOnlyDictionary<string, object> _emptyReadOnlyDictionary = new Dictionary<string, object>(); /// <summary> /// Creates a new <see cref="HealthReportEntry"/> with the specified values for <paramref name="status"/>, <paramref name="exception"/>, /// <paramref name="description"/>, and <paramref name="data"/>. /// </summary> /// <param name="status">A value indicating the health status of the component that was checked.</param> /// <param name="description">A human-readable description of the status of the component that was checked.</param> /// <param name="duration">A value indicating the health execution duration.</param> /// <param name="exception">An <see cref="Exception"/> representing the exception that was thrown when checking for status (if any).</param> /// <param name="data">Additional key-value pairs describing the health of the component.</param> public HealthReportEntry(HealthStatus status, string? description, TimeSpan duration, Exception? exception, IReadOnlyDictionary<string, object>? data) : this(status, description, duration, exception, data, null) { } /// <summary> /// Creates a new <see cref="HealthReportEntry"/> with the specified values for <paramref name="status"/>, <paramref name="exception"/>, /// <paramref name="description"/>, and <paramref name="data"/>. /// </summary> /// <param name="status">A value indicating the health status of the component that was checked.</param> /// <param name="description">A human-readable description of the status of the component that was checked.</param> /// <param name="duration">A value indicating the health execution duration.</param> /// <param name="exception">An <see cref="Exception"/> representing the exception that was thrown when checking for status (if any).</param> /// <param name="data">Additional key-value pairs describing the health of the component.</param> /// <param name="tags">Tags associated with the health check that generated the report entry.</param> public HealthReportEntry(HealthStatus status, string? description, TimeSpan duration, Exception? exception, IReadOnlyDictionary<string, object>? data, IEnumerable<string>? tags = null) { Status = status; Description = description; Duration = duration; Exception = exception; Data = data ?? _emptyReadOnlyDictionary; Tags = tags ?? Enumerable.Empty<string>(); } /// <summary> /// Gets additional key-value pairs describing the health of the component. /// </summary> public IReadOnlyDictionary<string, object> Data { get; } /// <summary> /// Gets a human-readable description of the status of the component that was checked. /// </summary> public string? Description { get; } /// <summary> /// Gets the health check execution duration. /// </summary> public TimeSpan Duration { get; } /// <summary> /// Gets an <see cref="System.Exception"/> representing the exception that was thrown when checking for status (if any). /// </summary> public Exception? Exception { get; } /// <summary> /// Gets the health status of the component that was checked. /// </summary> public HealthStatus Status { get; } /// <summary> /// Gets the tags associated with the health check. /// </summary> public IEnumerable<string> Tags { get; } }
HealthReportEntry
csharp
StackExchange__StackExchange.Redis
src/StackExchange.Redis/Enums/StreamTrimResult.cs
{ "start": 104, "end": 679 }
public enum ____ { /// <summary> /// No such id exists in the provided stream key. /// </summary> NotFound = -1, /// <summary> /// Entry was deleted from the stream. /// </summary> Deleted = 1, /// <summary> /// Entry was not deleted because it has either not been delivered to any consumer, or /// still has references in the consumer groups' Pending Entries List (PEL). /// </summary> /// <remarks>This response relates to the <see cref="StreamTrimMode.Acknowledged"/> mode.</remarks> NotDeleted = 2, }
StreamTrimResult
csharp
atata-framework__atata
test/Atata.IntegrationTests/Components/GoTo2Page.cs
{ "start": 76, "end": 612 }
public class ____ : Page<_> { public const string DefaultUrl = "/goto2"; public LinkDelegate<GoTo1Page, _> GoTo1 { get; private set; } [GoTemporarily] public LinkDelegate<GoTo1Page, _> GoTo1Temporarily { get; private set; } public LinkDelegate<_> GoTo1Blank { get; private set; } public LinkDelegate<GoTo3Page, _> GoTo3 { get; private set; } [GoTemporarily] public LinkDelegate<GoTo3Page, _> GoTo3Temporarily { get; private set; } public LinkDelegate<_> GoTo3Blank { get; private set; } }
GoTo2Page
csharp
dotnet__orleans
test/Orleans.Serialization.UnitTests/BuiltInCodecTests.cs
{ "start": 38232, "end": 38997 }
public class ____(ITestOutputHelper output) : FieldCodecTester<ValueTuple<string, string, string>, ValueTupleCodec<string, string, string>>(output) { protected override ValueTuple<string, string, string> CreateValue() => ValueTuple.Create( Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); protected override ValueTuple<string, string, string>[] TestValues => [ default, ValueTuple.Create(default(string), default(string), default(string)), ValueTuple.Create(string.Empty, string.Empty, "foo"), ValueTuple.Create("foo", "bar", "baz"), ValueTuple.Create("foo", "foo", "foo") ]; }
ValueTuple3Tests
csharp
JoshClose__CsvHelper
tests/CsvHelper.Tests/Configuration/CsvClassMapCollectionTests.cs
{ "start": 1366, "end": 1423 }
private sealed class ____ : ClassMap<Parent> { }
ParentMap
csharp
dotnet__maui
src/Controls/tests/TestCases.HostApp/Issues/Issue8295.xaml.cs
{ "start": 160, "end": 305 }
public class ____ : NavigationPage { public Issue8295_NavigationPage() : base(new Issue8295_ContentPage()) { } }
Issue8295_NavigationPage
csharp
dotnet__orleans
test/Orleans.CodeGenerator.Tests/OrleansSourceGeneratorTests.cs
{ "start": 15849, "end": 16003 }
public enum ____ { None, One, Two, Three } [GenerateSerializer(GenerateFieldIds = GenerateFieldIds.PublicProperties), Immutable]
MyCustomEnum
csharp
cake-build__cake
src/Cake.Common/Tools/DotNet/NuGet/Push/DotNetNuGetPusher.cs
{ "start": 446, "end": 4275 }
public sealed class ____ : DotNetTool<DotNetNuGetPushSettings> { /// <summary> /// Initializes a new instance of the <see cref="DotNetNuGetPusher" /> class. /// </summary> /// <param name="fileSystem">The file system.</param> /// <param name="environment">The environment.</param> /// <param name="processRunner">The process runner.</param> /// <param name="tools">The tool locator.</param> public DotNetNuGetPusher( IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IToolLocator tools) : base(fileSystem, environment, processRunner, tools) { } /// <summary> /// Push one or more NuGet package using the specified name, version and settings. /// </summary> /// <param name="packageName">The name of the target package.</param> /// <param name="settings">The settings.</param> public void Push(string packageName, DotNetNuGetPushSettings settings) { ArgumentNullException.ThrowIfNull(settings); RunCommand(settings, GetArguments(packageName, settings)); } private ProcessArgumentBuilder GetArguments(string packageName, DotNetNuGetPushSettings settings) { if (string.IsNullOrWhiteSpace(packageName)) { throw new ArgumentNullException(nameof(packageName)); } var builder = CreateArgumentBuilder(settings); builder.Append("nuget push"); // Specific package builder.AppendQuoted(packageName); // Where to push package to if (!string.IsNullOrWhiteSpace(settings.Source)) { builder.Append("--source"); builder.Append(settings.Source); } // api key for source if (!string.IsNullOrWhiteSpace(settings.ApiKey)) { builder.Append("--api-key"); builder.AppendQuotedSecret(settings.ApiKey); } // Where to push symbol package to if (!string.IsNullOrWhiteSpace(settings.SymbolSource)) { builder.Append("--symbol-source"); builder.Append(settings.SymbolSource); } // api key for symbol source if (!string.IsNullOrWhiteSpace(settings.SymbolApiKey)) { builder.Append("--symbol-api-key"); builder.AppendQuotedSecret(settings.SymbolApiKey); } // No service endpoint if (settings.NoServiceEndpoint) { builder.Append("--no-service-endpoint"); } // Interactive if (settings.Interactive) { builder.Append("--interactive"); } // Timeout if (settings.Timeout.HasValue) { builder.Append("--timeout"); builder.Append(settings.Timeout.Value.ToString()); } // Disable buffering if (settings.DisableBuffering) { builder.Append("--disable-buffering"); } // push symbol package? if (settings.IgnoreSymbols) { builder.Append("--no-symbols"); } // skip duplicate if (settings.SkipDuplicate) { builder.Append("--skip-duplicate"); } // Force English Output if (settings.ForceEnglishOutput) { builder.Append("--force-english-output"); } return builder; } } }
DotNetNuGetPusher
csharp
MassTransit__MassTransit
tests/MassTransit.HangfireIntegration.Tests/ScheduleMessage_Specs.cs
{ "start": 1523, "end": 2960 }
public class ____ : HangfireInMemoryTestFixture { [Test] public async Task Should_get_both_messages() { await Scheduler.ScheduleSend(InputQueueAddress, DateTime.Now, new FirstMessage()); await _first; await _second; if (_secondActivityId != null && _firstActivityId != null) Assert.That(_secondActivityId, Does.StartWith(_firstActivityId)); } Task<ConsumeContext<SecondMessage>> _second; Task<ConsumeContext<FirstMessage>> _first; string _firstActivityId; string _secondActivityId; protected override void ConfigureInMemoryBus(IInMemoryBusFactoryConfigurator configurator) { configurator.UseRawJsonSerializer(); base.ConfigureInMemoryBus(configurator); } protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator) { _first = Handler<FirstMessage>(configurator, async context => { _firstActivityId = Activity.Current?.Id; await context.ScheduleSend(TimeSpan.FromSeconds(5), new SecondMessage()); }); _second = Handler<SecondMessage>(configurator, async context => { _secondActivityId = Activity.Current?.Id; }); }
ScheduleMessageUsingJson_Specs
csharp
GtkSharp__GtkSharp
Source/Libs/PangoSharp/GlyphString.cs
{ "start": 43, "end": 820 }
class ____ // // Copyright (c) 2005 Novell, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of version 2 of the Lesser GNU General // Public License as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. namespace Pango { using System;
customizations
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/RouteTests.cs
{ "start": 14912, "end": 15006 }
public class ____ : IReturn<ModifiedRoute> { public string Data { get; set; } }
ModifiedRoute
csharp
CommunityToolkit__WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.Notifications/Toasts/Compat/ToastNotificationManagerCompat.cs
{ "start": 13648, "end": 14768 }
private class ____ : IClassFactory { private Type _activatorType; public NotificationActivatorClassFactory(Type activatorType) { _activatorType = activatorType; } public int CreateInstance(IntPtr pUnkOuter, ref Guid riid, out IntPtr ppvObject) { ppvObject = IntPtr.Zero; if (pUnkOuter != IntPtr.Zero) { Marshal.ThrowExceptionForHR(CLASS_E_NOAGGREGATION); } if (riid == _activatorType.GUID || riid == IUnknownGuid) { // Create the instance of the .NET object ppvObject = Marshal.GetComInterfaceForObject( Activator.CreateInstance(_activatorType), typeof(Internal.InternalNotificationActivator.INotificationActivationCallback)); } else { // The object that ppvObject points to does not support the //
NotificationActivatorClassFactory
csharp
bitwarden__server
bitwarden_license/test/Commercial.Core.Test/AdminConsole/AutoFixture/ProviderUserFixtures.cs
{ "start": 705, "end": 1235 }
public class ____ : CustomizeAttribute { private readonly ProviderUserStatusType _status; private readonly ProviderUserType _type; public ProviderUserAttribute( ProviderUserStatusType status = ProviderUserStatusType.Confirmed, ProviderUserType type = ProviderUserType.ProviderAdmin) { _status = status; _type = type; } public override ICustomization GetCustomization(ParameterInfo parameter) { return new ProviderUser(_status, _type); } }
ProviderUserAttribute
csharp
unoplatform__uno
src/Uno.UI.RuntimeTests/MUX/Microsoft_UI_Xaml_Controls/LayoutPanel/LayoutPanelTests.cs
{ "start": 1100, "end": 6904 }
public partial class ____ : MUXApiTestBase { [ClassInitialize] [TestProperty("Classification", "Integration")] public static void ClassInitialize(TestContext context) { } [TestMethod] public void VerifyPaddingAndBorderThicknessLayoutOffset() { RunOnUIThread.Execute(() => { double width = 400; double height = 400; Thickness borderThickness = new Thickness(5, 10, 15, 20); Thickness padding = new Thickness(2, 4, 6, 8); LayoutPanel panel = new LayoutPanel(); panel.Width = width; panel.Height = height; panel.BorderBrush = new SolidColorBrush(Colors.Red); panel.BorderThickness = borderThickness; panel.Padding = padding; var button = new Button { Content = "Button", VerticalAlignment = VerticalAlignment.Stretch, HorizontalAlignment = HorizontalAlignment.Stretch }; var expectedButtonLayoutSlot = new Rect { Width = width - borderThickness.Left - borderThickness.Right - padding.Left - padding.Right, Height = height - borderThickness.Top - borderThickness.Bottom - padding.Top - padding.Bottom, X = borderThickness.Left + padding.Left, Y = borderThickness.Top + padding.Top, }; panel.Children.Add(button); Content = panel; Content.UpdateLayout(); Verify.AreEqual(expectedButtonLayoutSlot, LayoutInformation.GetLayoutSlot(button), "Verify LayoutSlot of child Button"); }); } [TestMethod] public void VerifyPaddingAndBorderThicknessLayoutOffset_StackLayout() { RunOnUIThread.Execute(() => { double width = 400; double height = 400; Thickness borderThickness = new Thickness(5, 10, 15, 20); Thickness padding = new Thickness(2, 4, 6, 8); LayoutPanel panel = new LayoutPanel(); panel.Layout = new StackLayout(); panel.Width = width; panel.Height = height; panel.BorderBrush = new SolidColorBrush(Colors.Red); panel.BorderThickness = borderThickness; panel.Padding = padding; double unpaddedWidth = width - borderThickness.Left - borderThickness.Right - padding.Left - padding.Right; double itemHeight = 50; double unpaddedX = borderThickness.Left + padding.Left; double unpaddedY = borderThickness.Top + padding.Top; var button1 = new Button { Content = "Button", Height = itemHeight, HorizontalAlignment = HorizontalAlignment.Stretch }; var button2 = new Button { Content = "Button", Height = itemHeight, HorizontalAlignment = HorizontalAlignment.Stretch }; var expectedButton1LayoutSlot = new Rect { Width = unpaddedWidth, Height = itemHeight, X = unpaddedX, Y = unpaddedY, }; var expectedButton2LayoutSlot = new Rect { Width = unpaddedWidth, Height = itemHeight, X = unpaddedX, Y = unpaddedY + itemHeight, }; panel.Children.Add(button1); panel.Children.Add(button2); Content = panel; Content.UpdateLayout(); Verify.AreEqual(expectedButton1LayoutSlot, LayoutInformation.GetLayoutSlot(button1), "Verify LayoutSlot of child 1"); Verify.AreEqual(expectedButton2LayoutSlot, LayoutInformation.GetLayoutSlot(button2), "Verify LayoutSlot of child 2"); }); } [TestMethod] public void VerifySwitchingLayoutDynamically() { LayoutPanel panel = null; Button button1 = null; Button button2 = null; RunOnUIThread.Execute(() => { Log.Comment("Create LayoutPanel with StackLayout"); panel = new LayoutPanel() { Width = 400, Height = 400 }; var stackLayout = new StackLayout { Orientation = Orientation.Vertical }; panel.Layout = stackLayout; button1 = new Button { Height = 100, Content = "1" }; button2 = new Button { Height = 100, Content = "2" }; panel.Children.Add(button1); panel.Children.Add(button2); Content = panel; Content.UpdateLayout(); Log.Comment("Verify layout for StackLayout:"); Verify.AreEqual(new Rect(0, 0, 400, 100), LayoutInformation.GetLayoutSlot(button1), "Verify LayoutSlot of child 1"); Verify.AreEqual(new Rect(0, 100, 400, 100), LayoutInformation.GetLayoutSlot(button2), "Verify LayoutSlot of child 2"); }); IdleSynchronizer.Wait(); RunOnUIThread.Execute(() => { Log.Comment("Switch LayoutPanel to UniformGridLayout"); UniformGridLayout gridLayout = new UniformGridLayout(); gridLayout.MinItemWidth = 100; gridLayout.MinItemHeight = 100; panel.Layout = gridLayout; Content.UpdateLayout(); Log.Comment("Verify layout for UniformGridLayout:"); Verify.AreEqual(new Rect(0, 0, 100, 100), LayoutInformation.GetLayoutSlot(button1), "Verify LayoutSlot of child 1"); Verify.AreEqual(new Rect(100, 0, 100, 100), LayoutInformation.GetLayoutSlot(button2), "Verify LayoutSlot of child 2"); }); } [TestMethod] public void VerifyCustomNonVirtualizingLayout() { LayoutPanel panel = null; Button button1 = null; Button button2 = null; RunOnUIThread.Execute(() => { Log.Comment("Create LayoutPanel with MyCustomNonVirtualizingStackLayout"); panel = new LayoutPanel() { Width = 400, Height = 400 }; var customStackLayout = new MyCustomNonVirtualizingStackLayout(); panel.Layout = customStackLayout; button1 = new Button { Height = 100, Width = 400, Content = "1" }; button2 = new Button { Height = 100, Width = 400, Content = "2" }; panel.Children.Add(button1); panel.Children.Add(button2); Content = panel; Content.UpdateLayout(); Log.Comment("Verify layout for StackLayout:"); Verify.AreEqual(new Rect(0, 0, 400, 100), LayoutInformation.GetLayoutSlot(button1), "Verify LayoutSlot of child 1"); Verify.AreEqual(new Rect(0, 100, 400, 100), LayoutInformation.GetLayoutSlot(button2), "Verify LayoutSlot of child 2"); }); IdleSynchronizer.Wait(); } } #endif
LayoutPanelTests
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/src/Types/Types/Composite/Directives/InaccessibleDescriptorExtensions.cs
{ "start": 6143, "end": 6244 }
interface ____ descriptor to apply the directive to. /// </param> /// <returns> /// The
field
csharp
dotnet__BenchmarkDotNet
tests/BenchmarkDotNet.Analyzers.Tests/AnalyzerTests/General/BenchmarkClassAnalyzerTests.cs
{ "start": 47578, "end": 49844 }
class ____ { {{(useLocalConstants ? $"private const bool _xTrue = {(useConstantsFromOtherClass ? "Constants.Value1" : "true")};" : "")}} {{baselineBenchmarkAttributeUsage}} public void BaselineBenchmarkMethod3() { } } """; TestCode = testCode; ReferenceConstants(("bool", "true"), ("bool", "false")); AddSource(benchmarkClassAncestor1Document); AddSource(benchmarkClassAncestor2Document); AddExpectedDiagnostic(0); if (useDuplicateInSameClass) { AddExpectedDiagnostic(1); } await RunAsync(); } [Theory, CombinatorialData] public async Task Class_with_more_than_one_benchmark_method_marked_as_baseline_with_empty_category_should_trigger_diagnostic( [CombinatorialMemberData(nameof(ClassAbstractModifiersEnumerableLocal))] string abstractModifier, bool useConstantsFromOtherClass, bool useLocalConstants, [CombinatorialMemberData(nameof(EmptyBenchmarkCategoryAttributeEnumerableLocal))] string emptyBenchmarkCategoryAttribute, bool useDuplicateInSameClass) { var emptyBenchmarkCategoryAttributeUsages = string.Join("\n", Enumerable.Repeat(emptyBenchmarkCategoryAttribute, 3)); var baselineBenchmarkAttributeUsage = $"[Benchmark(Baseline = {(useLocalConstants ? "_xTrue" : useConstantsFromOtherClass ? "Constants.Value1" : "true")})]"; var baselineBenchmarkAttributeUsageWithLocationMarker = $"[Benchmark({{{{|#{{0}}:Baseline = {(useLocalConstants ? "_xTrue" : useConstantsFromOtherClass ? "Constants.Value1" : "true")}|}}}})]"; var nonBaselineBenchmarkAttributeUsage = $"[Benchmark(Baseline = {(useLocalConstants ? "_xFalse" : useConstantsFromOtherClass ? "Constants.Value2" : "false")})]"; var testCode = /* lang=c#-test */ $$""" using BenchmarkDotNet.Attributes;
BenchmarkClassAncestor2
csharp
getsentry__sentry-dotnet
test/Sentry.Tests/Internals/ConcurrentQueueLiteTests.cs
{ "start": 35, "end": 3634 }
public class ____ { [Fact] public void Enqueue_Test() { // Arrange var queue = new ConcurrentQueueLite<int>(); // Act queue.Enqueue(1); // Assert queue.Count.Should().Be(1); // Act queue.Enqueue(2); queue.Enqueue(3); // Assert queue.Count.Should().Be(3); var items = queue.ToArray(); items.Should().BeEquivalentTo([1, 2, 3]); } [Fact] public void TryDequeue_Test() { // Arrange var queue = new ConcurrentQueueLite<int>(); queue.Enqueue(1); queue.Enqueue(2); queue.Enqueue(3); // Act var result = queue.TryDequeue(out var dequeuedItem); // Assert result.Should().BeTrue(); dequeuedItem.Should().Be(1); queue.Count.Should().Be(2); } [Fact] public void TryDequeue_EmptyQueue_Test() { // Arrange var queue = new ConcurrentQueueLite<int>(); // Act var result = queue.TryDequeue(out var dequeuedItem); // Assert result.Should().BeFalse(); dequeuedItem.Should().Be(default(int)); } [Fact] public void Count_EmptyQueue_Test() { // Arrange var queue = new ConcurrentQueueLite<int>(); // Act & Assert queue.Count.Should().Be(0); } [Fact] public void IsEmpty_Test() { // Arrange var queue = new ConcurrentQueueLite<int>(); // Act & Assert queue.IsEmpty.Should().BeTrue(); queue.Enqueue(1); queue.IsEmpty.Should().BeFalse(); queue.TryDequeue(out var dequeuedItem); queue.IsEmpty.Should().BeTrue(); } [Fact] public void Clear_Test() { // Arrange var queue = new ConcurrentQueueLite<int>(); queue.Enqueue(1); queue.Enqueue(2); queue.Enqueue(3); // Act queue.Clear(); // Assert queue.Count.Should().Be(0); queue.IsEmpty.Should().BeTrue(); } [Fact] public void TryPeek_Test() { // Arrange var queue = new ConcurrentQueueLite<int>(); queue.Enqueue(1); queue.Enqueue(2); queue.Enqueue(3); // Act var result = queue.TryPeek(out var peekedItem); // Assert result.Should().BeTrue(); peekedItem.Should().Be(1); var items = queue.ToArray(); items.Should().BeEquivalentTo([1, 2, 3]); } [Fact] public void TryPeek_EmptyQueue_Test() { // Arrange var queue = new ConcurrentQueueLite<int>(); // Act var result = queue.TryPeek(out var peekedItem); // Assert result.Should().BeFalse(); peekedItem.Should().Be(default(int)); } [Fact] public async Task TestConcurrency() { // Arrange var queue = new ConcurrentQueueLite<int>(); var count = 100; var tasks = new Task[count * 2]; var received = 0; // Act for (var i = 0; i < count; i++) { var toAdd = i; tasks[i] = Task.Run(() => { queue.Enqueue(toAdd); Interlocked.Increment(ref received); }); tasks[i + count] = Task.Run(() => { queue.TryDequeue(out _); Interlocked.Increment(ref received); }); } await Task.WhenAll(tasks); // Assert received.Should().Be(count * 2); } }
ConcurrentQueueLiteTests
csharp
PrismLibrary__Prism
src/Maui/Prism.Maui/Mvvm/ViewModelLocator.cs
{ "start": 180, "end": 4494 }
public static class ____ { /// <summary> /// Instructs Prism whether or not to automatically create an instance of a ViewModel using a convention, and assign the associated View's <see cref="BindableObject.BindingContext"/> to that instance. /// </summary> public static readonly BindableProperty AutowireViewModelProperty = BindableProperty.CreateAttached("AutowireViewModel", typeof(ViewModelLocatorBehavior), typeof(ViewModelLocator), ViewModelLocatorBehavior.Automatic, propertyChanged: OnViewModelLocatorBehaviorChanged); private static void OnViewModelLocatorBehaviorChanged(BindableObject bindable, object oldValue, object newValue) { if (newValue is ViewModelLocatorBehavior behavior && behavior == ViewModelLocatorBehavior.Forced) { Autowire(bindable); } } internal static readonly BindableProperty ViewModelProperty = BindableProperty.CreateAttached("ViewModelType", typeof(Type), typeof(ViewModelLocator), null, propertyChanged: OnViewModelPropertyChanged); public static readonly BindableProperty NavigationNameProperty = BindableProperty.CreateAttached("NavigationName", typeof(string), typeof(ViewModelLocator), null, defaultValueCreator: CreateDefaultNavigationName); private static object CreateDefaultNavigationName(BindableObject bindable) => bindable.GetType().Name; public static string GetNavigationName(BindableObject bindable) => (string)bindable.GetValue(NavigationNameProperty); public static void SetNavigationName(BindableObject bindable, string name) => bindable.SetValue(NavigationNameProperty, name); /// <summary> /// Gets the AutowireViewModel property value. /// </summary> /// <param name="bindable"></param> /// <returns></returns> public static ViewModelLocatorBehavior GetAutowireViewModel(BindableObject bindable) { return (ViewModelLocatorBehavior)bindable.GetValue(AutowireViewModelProperty); } /// <summary> /// Sets the AutowireViewModel property value. If <c>true</c>, creates an instance of a ViewModel using a convention, and sets the associated View's <see cref="BindableObject.BindingContext"/> to that instance. /// </summary> /// <param name="bindable"></param> /// <param name="value"></param> public static void SetAutowireViewModel(BindableObject bindable, ViewModelLocatorBehavior value) { bindable.SetValue(AutowireViewModelProperty, value); } private static void OnViewModelPropertyChanged(BindableObject bindable, object oldValue, object newValue) { if (newValue == null || bindable.BindingContext != null) return; else if(newValue is Type) bindable.SetValue(AutowireViewModelProperty, ViewModelLocatorBehavior.Automatic); } internal static void Autowire(object view) { if (view is Element element && ((ViewModelLocatorBehavior)element.GetValue(AutowireViewModelProperty) == ViewModelLocatorBehavior.Disabled || (element.BindingContext is not null && element.BindingContext != element.Parent))) { return; } if (view is TabbedPage tabbed) { foreach (var child in tabbed.Children) Autowire(child); } else if(view is NavigationPage navigationPage && navigationPage.RootPage is not null) { Autowire(navigationPage.RootPage); } ViewModelLocationProvider.AutoWireViewModelChanged(view, Bind); if (view is BindableObject bindable && bindable.BindingContext is null) { bindable.BindingContext = new object(); } } /// <summary> /// Sets the <see cref="BindableObject.BindingContext"/> of a View /// </summary> /// <param name="view">The View to set the <see cref="BindableObject.BindingContext"/> on</param> /// <param name="viewModel">The object to use as the <see cref="BindableObject.BindingContext"/> for the View</param> private static void Bind(object view, object viewModel) { if (view is BindableObject element) { element.BindingContext = viewModel; } } }
ViewModelLocator
csharp
dotnet__orleans
src/api/Orleans.Serialization/Orleans.Serialization.cs
{ "start": 152709, "end": 153156 }
partial class ____ : Cloning.IDeepCopier<System.ValueTuple>, Cloning.IDeepCopier, Cloning.IOptionalDeepCopier { public System.ValueTuple DeepCopy(System.ValueTuple input, Cloning.CopyContext context) { throw null; } public bool IsShallowCopyable() { throw null; } object Cloning.IDeepCopier.DeepCopy(object input, Cloning.CopyContext context) { throw null; } } [RegisterCopier] public sealed
ValueTupleCopier
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.Background/DeviceManufacturerNotificationTrigger.cs
{ "start": 369, "end": 2726 }
public partial class ____ : global::Windows.ApplicationModel.Background.IBackgroundTrigger { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public bool OneShot { get { throw new global::System.NotImplementedException("The member bool DeviceManufacturerNotificationTrigger.OneShot is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20DeviceManufacturerNotificationTrigger.OneShot"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public string TriggerQualifier { get { throw new global::System.NotImplementedException("The member string DeviceManufacturerNotificationTrigger.TriggerQualifier is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20DeviceManufacturerNotificationTrigger.TriggerQualifier"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public DeviceManufacturerNotificationTrigger(string triggerQualifier, bool oneShot) { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Background.DeviceManufacturerNotificationTrigger", "DeviceManufacturerNotificationTrigger.DeviceManufacturerNotificationTrigger(string triggerQualifier, bool oneShot)"); } #endif // Forced skipping of method Windows.ApplicationModel.Background.DeviceManufacturerNotificationTrigger.DeviceManufacturerNotificationTrigger(string, bool) // Forced skipping of method Windows.ApplicationModel.Background.DeviceManufacturerNotificationTrigger.TriggerQualifier.get // Forced skipping of method Windows.ApplicationModel.Background.DeviceManufacturerNotificationTrigger.OneShot.get // Processing: Windows.ApplicationModel.Background.IBackgroundTrigger } }
DeviceManufacturerNotificationTrigger
csharp
dotnetcore__Util
src/Util.Validation/Validators/ValidatePattern.cs
{ "start": 79, "end": 378 }
public static class ____ { /// <summary> /// 手机号验证正则表达式 /// </summary> public static string MobilePhonePattern = "^1[0-9]{10}$"; /// <summary> /// 身份证验证正则表达式 /// </summary> public static string IdCardPattern = @"(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)"; }
ValidatePattern
csharp
duplicati__duplicati
Duplicati/WebserverCore/Endpoints/V1/Bugreport.cs
{ "start": 1379, "end": 2840 }
public class ____ : IEndpointV1 { public static void Map(RouteGroupBuilder group) { group.MapGet("/bugreport/{reportid}", async ([FromServices] Connection connection, [FromServices] IHttpContextAccessor httpContextAccessor, [FromServices] IJWTTokenProvider jWTTokenProvider, [FromRoute] long reportid, [FromQuery] string token, CancellationToken ct) => { // Custom authorization check var singleOperationToken = jWTTokenProvider.ReadSingleOperationToken(token); if (singleOperationToken.Operation != "bugreport") throw new UnauthorizedException("Invalid operation"); var tf = connection.GetTempFiles().FirstOrDefault(x => x.ID == reportid); if (tf == null) throw new NotFoundException("Invalid or missing bugreport id"); if (!File.Exists(tf.Path)) throw new NotFoundException("File is missing"); var response = httpContextAccessor.HttpContext!.Response; var filename = "bugreport.zip"; using (var fs = File.OpenRead(tf.Path)) { response.ContentLength = fs.Length; response.ContentType = "application/octet-stream"; response.Headers.Append("Content-Disposition", $"attachment; filename={filename}"); await fs.CopyToAsync(response.Body, ct).ConfigureAwait(false); } }); } }
Bugreport
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.UI.Composition/CompositionEffectBrush.cs
{ "start": 297, "end": 1775 }
public partial class ____ : global::Windows.UI.Composition.CompositionBrush { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ internal CompositionEffectBrush() { } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::Windows.UI.Composition.CompositionBrush GetSourceParameter(string name) { throw new global::System.NotImplementedException("The member CompositionBrush CompositionEffectBrush.GetSourceParameter(string name) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=CompositionBrush%20CompositionEffectBrush.GetSourceParameter%28string%20name%29"); } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public void SetSourceParameter(string name, global::Windows.UI.Composition.CompositionBrush source) { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.CompositionEffectBrush", "void CompositionEffectBrush.SetSourceParameter(string name, CompositionBrush source)"); } #endif } }
CompositionEffectBrush
csharp
grpc__grpc-dotnet
test/Grpc.AspNetCore.Server.Tests/GrpcEventSourceTests.cs
{ "start": 814, "end": 6739 }
public class ____ { [Test] public void MatchesNameAndGuid() { // Arrange & Act var eventSource = new GrpcEventSource(); // Assert Assert.AreEqual("Grpc.AspNetCore.Server", eventSource.Name); Assert.AreEqual(Guid.Parse("d442f1b8-5953-548b-3797-d96725947255"), eventSource.Guid); } [Test] public void CallStart() { // Arrange var expectedEventId = 1; var eventListener = new TestEventListener(expectedEventId); var grpcEventSource = GetGrpcEventSource(); eventListener.EnableEvents(grpcEventSource, EventLevel.Verbose); // Act grpcEventSource.CallStart("service/method"); // Assert var eventData = eventListener.EventData; Assert.NotNull(eventData); Assert.AreEqual(expectedEventId, eventData!.EventId); Assert.AreEqual("CallStart", eventData.EventName); Assert.AreEqual(EventLevel.Verbose, eventData.Level); Assert.AreSame(grpcEventSource, eventData.EventSource); Assert.AreEqual("service/method", eventData.Payload![0]); } [Test] public void CallStop() { // Arrange var expectedEventId = 2; var eventListener = new TestEventListener(expectedEventId); var grpcEventSource = GetGrpcEventSource(); eventListener.EnableEvents(grpcEventSource, EventLevel.Verbose); // Act grpcEventSource.CallStop(); // Assert var eventData = eventListener.EventData; Assert.NotNull(eventData); Assert.AreEqual(expectedEventId, eventData!.EventId); Assert.AreEqual("CallStop", eventData.EventName); Assert.AreEqual(EventLevel.Verbose, eventData.Level); Assert.AreSame(grpcEventSource, eventData.EventSource); Assert.AreEqual(0, eventData.Payload!.Count); } [Test] public void CallFailed() { // Arrange var expectedEventId = 3; var eventListener = new TestEventListener(expectedEventId); var grpcEventSource = GetGrpcEventSource(); eventListener.EnableEvents(grpcEventSource, EventLevel.Verbose); // Act grpcEventSource.CallFailed(StatusCode.DeadlineExceeded); // Assert var eventData = eventListener.EventData; Assert.NotNull(eventData); Assert.AreEqual(expectedEventId, eventData!.EventId); Assert.AreEqual("CallFailed", eventData.EventName); Assert.AreEqual(EventLevel.Error, eventData.Level); Assert.AreSame(grpcEventSource, eventData.EventSource); Assert.AreEqual(4, eventData.Payload![0]); } [Test] public void CallDeadlineExceeded() { // Arrange var expectedEventId = 4; var eventListener = new TestEventListener(expectedEventId); var grpcEventSource = GetGrpcEventSource(); eventListener.EnableEvents(grpcEventSource, EventLevel.Verbose); // Act grpcEventSource.CallDeadlineExceeded(); // Assert var eventData = eventListener.EventData; Assert.NotNull(eventData); Assert.AreEqual(expectedEventId, eventData!.EventId); Assert.AreEqual("CallDeadlineExceeded", eventData.EventName); Assert.AreEqual(EventLevel.Error, eventData.Level); Assert.AreSame(grpcEventSource, eventData.EventSource); Assert.AreEqual(0, eventData.Payload!.Count); } [Test] public void MessageSent() { // Arrange var expectedEventId = 5; var eventListener = new TestEventListener(expectedEventId); var grpcEventSource = GetGrpcEventSource(); eventListener.EnableEvents(grpcEventSource, EventLevel.Verbose); // Act grpcEventSource.MessageSent(); // Assert var eventData = eventListener.EventData; Assert.NotNull(eventData); Assert.AreEqual(expectedEventId, eventData!.EventId); Assert.AreEqual("MessageSent", eventData.EventName); Assert.AreEqual(EventLevel.Verbose, eventData.Level); Assert.AreSame(grpcEventSource, eventData.EventSource); Assert.AreEqual(0, eventData.Payload!.Count); } [Test] public void MessageReceived() { // Arrange var expectedEventId = 6; var eventListener = new TestEventListener(expectedEventId); var grpcEventSource = GetGrpcEventSource(); eventListener.EnableEvents(grpcEventSource, EventLevel.Verbose); // Act grpcEventSource.MessageReceived(); // Assert var eventData = eventListener.EventData; Assert.NotNull(eventData); Assert.AreEqual(expectedEventId, eventData!.EventId); Assert.AreEqual("MessageReceived", eventData.EventName); Assert.AreEqual(EventLevel.Verbose, eventData.Level); Assert.AreSame(grpcEventSource, eventData.EventSource); Assert.AreEqual(0, eventData.Payload!.Count); } [Test] public void CallUnimplemented() { // Arrange var expectedEventId = 7; var eventListener = new TestEventListener(expectedEventId); var grpcEventSource = GetGrpcEventSource(); eventListener.EnableEvents(grpcEventSource, EventLevel.Verbose); // Act grpcEventSource.CallUnimplemented("service/method"); // Assert var eventData = eventListener.EventData; Assert.NotNull(eventData); Assert.AreEqual(expectedEventId, eventData!.EventId); Assert.AreEqual("CallUnimplemented", eventData.EventName); Assert.AreEqual(EventLevel.Verbose, eventData.Level); Assert.AreSame(grpcEventSource, eventData.EventSource); Assert.AreEqual("service/method", eventData.Payload![0]); } private static GrpcEventSource GetGrpcEventSource() { return new GrpcEventSource(Guid.NewGuid().ToString()); }
GrpcEventSourceTests
csharp
ServiceStack__ServiceStack.OrmLite
tests/ServiceStack.OrmLite.Tests/DateTimeTests.cs
{ "start": 194, "end": 10156 }
public class ____ : OrmLiteProvidersTestBase { public DateTimeTests(DialectContext context) : base(context) {} [Test] public void Can_insert_and_query_with_Unspecified_DateStyle() { using var db = OpenDbConnection(); db.DropAndCreateTable<DateTimeObject>(); DateTime dateTime; DateTimeObject x; dateTime = new DateTime(2012, 1, 1, 1, 1, 1, DateTimeKind.Local); x = InsertAndSelectDateTime(db, dateTime); Assert.AreEqual(x.Test, dateTime); Assert.AreEqual(x.Test, x.TestNullable.Value); x = db.Select<DateTimeObject>(d => d.Test == dateTime).FirstOrDefault(); Assert.IsNotNull(x); dateTime = new DateTime(2012, 1, 1, 1, 1, 1, DateTimeKind.Utc); x = InsertAndSelectDateTime(db, dateTime); Assert.AreEqual(x.Test, dateTime); Assert.AreEqual(x.Test, x.TestNullable.Value); x = db.Select<DateTimeObject>(d => d.Test == dateTime).FirstOrDefault(); Assert.IsNotNull(x); dateTime = new DateTime(2012, 1, 1, 1, 1, 1, DateTimeKind.Unspecified); x = InsertAndSelectDateTime(db, dateTime); Assert.AreEqual(x.Test, dateTime); Assert.AreEqual(x.Test, x.TestNullable.Value); x = db.Select<DateTimeObject>(d => d.Test == dateTime).FirstOrDefault(); Assert.IsNotNull(x); } [Test] public void Does_return_Local_Dates_with_Local_DateStyle() { using var db = OpenDbConnection(); var dialectProvider = DialectProvider; var hold = dialectProvider.GetDateTimeConverter().DateStyle; dialectProvider.GetDateTimeConverter().DateStyle = DateTimeKind.Local; db.DropAndCreateTable<DateTimeObject>(); DateTime dateTime; DateTimeObject x; dateTime = new DateTime(2012, 1, 1, 1, 1, 1, DateTimeKind.Local); x = InsertAndSelectDateTime(db, dateTime); Assert.AreEqual(DateTimeKind.Local, x.Test.Kind); Assert.AreEqual(DateTimeKind.Local, x.TestNullable.Value.Kind); Assert.AreEqual(x.Test, x.TestNullable.Value); Assert.AreEqual(x.Test.ToUniversalTime(), dateTime.ToUniversalTime()); Assert.AreEqual(x.Test.ToLocalTime(), dateTime.ToLocalTime()); x = db.Select<DateTimeObject>(d => d.Test == dateTime).FirstOrDefault(); Assert.IsNotNull(x); dateTime = new DateTime(2012, 1, 1, 1, 1, 1, DateTimeKind.Utc); x = InsertAndSelectDateTime(db, dateTime); Assert.AreEqual(DateTimeKind.Local, x.Test.Kind); Assert.AreEqual(DateTimeKind.Local, x.TestNullable.Value.Kind); Assert.AreEqual(x.Test, x.TestNullable.Value); Assert.AreEqual(x.Test.ToUniversalTime(), dateTime.ToUniversalTime()); Assert.AreEqual(x.Test.ToLocalTime(), dateTime.ToLocalTime()); x = db.Select<DateTimeObject>(d => d.Test == dateTime).FirstOrDefault(); Assert.IsNotNull(x); dateTime = new DateTime(2012, 1, 1, 1, 1, 1, DateTimeKind.Unspecified); x = InsertAndSelectDateTime(db, dateTime); Assert.AreEqual(DateTimeKind.Local, x.Test.Kind); Assert.AreEqual(DateTimeKind.Local, x.TestNullable.Value.Kind); Assert.AreEqual(x.Test, x.TestNullable.Value); Assert.AreEqual(x.Test.ToUniversalTime(), dateTime); Assert.AreEqual(x.Test.ToLocalTime(), dateTime.ToLocalTime()); x = db.Select<DateTimeObject>(d => d.Test == dateTime).FirstOrDefault(); db.GetLastSql().Print(); Assert.IsNotNull(x); dialectProvider.GetDateTimeConverter().DateStyle = hold; } [Test] public void Does_return_UTC_Dates_with_UTC_DateStyle() { using var db = OpenDbConnection(); var dialectProvider = DialectProvider; var hold = dialectProvider.GetDateTimeConverter().DateStyle; dialectProvider.GetDateTimeConverter().DateStyle = DateTimeKind.Utc; db.DropAndCreateTable<DateTimeObject>(); DateTime dateTime; DateTimeObject x; dateTime = new DateTime(2012, 1, 1, 1, 1, 1, DateTimeKind.Local); x = InsertAndSelectDateTime(db, dateTime); Assert.That(x.Test.Kind, Is.EqualTo(DateTimeKind.Utc)); Assert.That(x.TestNullable.Value.Kind, Is.EqualTo(DateTimeKind.Utc)); Assert.That(x.Test, Is.EqualTo(x.TestNullable.Value)); Assert.That(x.Test.ToUniversalTime(), Is.EqualTo(dateTime.ToUniversalTime())); Assert.That(x.Test.ToLocalTime(), Is.EqualTo(dateTime.ToLocalTime())); x = db.Select<DateTimeObject>(d => d.Test == dateTime).FirstOrDefault(); Assert.That(x, Is.Not.Null); dateTime = new DateTime(2012, 1, 1, 1, 1, 1, DateTimeKind.Utc); x = InsertAndSelectDateTime(db, dateTime); Assert.That(x.Test.Kind, Is.EqualTo(DateTimeKind.Utc)); Assert.That(x.TestNullable.Value.Kind, Is.EqualTo(DateTimeKind.Utc)); Assert.That(x.Test, Is.EqualTo(x.TestNullable.Value)); Assert.That(x.Test.ToUniversalTime(), Is.EqualTo(dateTime.ToUniversalTime())); Assert.That(x.Test.ToLocalTime(), Is.EqualTo(dateTime.ToLocalTime())); x = db.Select<DateTimeObject>(d => d.Test == dateTime).FirstOrDefault(); Assert.That(x, Is.Not.Null); dateTime = new DateTime(2012, 1, 1, 1, 1, 1, DateTimeKind.Unspecified); x = InsertAndSelectDateTime(db, dateTime); Assert.That(x.Test.Kind, Is.EqualTo(DateTimeKind.Utc)); Assert.That(x.TestNullable.Value.Kind, Is.EqualTo(DateTimeKind.Utc)); Assert.That(x.Test, Is.EqualTo(x.TestNullable.Value)); Assert.That(x.Test.ToUniversalTime(), Is.EqualTo(dateTime)); Assert.That(x.Test.ToLocalTime(), Is.EqualTo(dateTime.ToLocalTime())); x = db.Select<DateTimeObject>(d => d.Test == dateTime).FirstOrDefault(); Assert.That(x, Is.Not.Null); dialectProvider.GetDateTimeConverter().DateStyle = hold; } [Test] public void Log_dialect_behavior() { Dialect.ToString().Print(); using var db = OpenDbConnection(); db.DropAndCreateTable<DateTimeObject>(); var dateStyles = new[] { DateTimeKind.Local, DateTimeKind.Utc, DateTimeKind.Unspecified }; foreach (var dateStyle in dateStyles) { db.DeleteAll<DateTimeObject>(); var dateTime = new DateTime(2012, 1, 1, 1, 1, 1, dateStyle); "#1 IN: {0} ({1}), UTC: {2}, Local: {3}".Print( dateTime.Kind, dateTime, dateTime.ToUniversalTime(), dateTime.ToLocalTime()); using (var cmd = db.OpenCommand()) { cmd.CommandText = "INSERT INTO {0} VALUES({1}, {2})" .Fmt(nameof(DateTimeObject).SqlTable(DialectProvider), DialectProvider.GetParam("p1"), DialectProvider.GetParam("p2")); cmd.Parameters.Add(cmd.CreateParam("p1", dateTime)); cmd.Parameters.Add(cmd.CreateParam("p2", dateTime)); cmd.ExecuteNonQuery(); } using (var cmd = db.OpenCommand()) { cmd.CommandText = "SELECT * FROM {0}".Fmt(nameof(DateTimeObject).SqlTable(DialectProvider)); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { var dbDateTime = reader.GetDateTime(0); "#1 IN: {0} ({1}), OUT: {2} ({3})".Print( dateTime.Kind, dateTime, dbDateTime.Kind, dbDateTime); } } } } } [Test] public void Can_Select_Date_with_SqlList() { using var db = OpenDbConnection(); db.DropAndCreateTable<DateTimeObject>(); var dateTime = new DateTime(2001, 1, 1, 1, 1, 1); db.DeleteAll<DateTimeObject>(); db.Insert(new DateTimeObject { Test = dateTime, TestNullable = dateTime }); var row = db.SqlList<DateTimeObject>( "SELECT * FROM {0} WHERE Test = @dateTime".Fmt("DateTimeObject".SqlTable(DialectProvider)), new { dateTime }); Assert.That(dateTime, Is.EqualTo(row[0].Test)); row = db.SqlList<DateTimeObject>( "SELECT * FROM {0} WHERE {1} = @dateTime".Fmt("DateTimeObject".SqlTable(DialectProvider), "TestNullable".SqlColumn(DialectProvider)), new { dateTime }); Assert.That(dateTime, Is.EqualTo(row[0].TestNullable)); DateTime? nullableDate = dateTime; row = db.SqlList<DateTimeObject>( "SELECT * FROM {0} WHERE {1} = @nullableDate".Fmt("DateTimeObject".SqlTable(DialectProvider), "TestNullable".SqlColumn(DialectProvider)), new { nullableDate }); Assert.That(dateTime, Is.EqualTo(row[0].TestNullable)); } private static DateTimeObject InsertAndSelectDateTime(IDbConnection db, DateTime dateTime) { db.DeleteAll<DateTimeObject>(); db.Insert(new DateTimeObject { Test = dateTime, TestNullable = dateTime }); var x = db.Select<DateTimeObject>().First(); return x; }
DateTimeTests
csharp
dotnet__aspnetcore
src/Components/test/E2ETest/Tests/HostedInAspNetTest.cs
{ "start": 424, "end": 1563 }
public class ____ : ServerTestBase<AspNetSiteServerFixture> { public HostedInAspNetTest( BrowserFixture browserFixture, AspNetSiteServerFixture serverFixture, ITestOutputHelper output) : base(browserFixture, serverFixture, output) { serverFixture.BuildWebHostMethod = HostedInAspNet.Server.Program.BuildWebHost; serverFixture.Environment = AspNetEnvironment.Development; } protected override void InitializeAsyncCore() { Navigate("/"); WaitUntilLoaded(); } [Fact] public void HasTitle() { Assert.Equal("Sample Blazor app", Browser.Title); } [Fact] public void ServesStaticAssetsFromClientAppWebRoot() { var javascriptExecutor = (IJavaScriptExecutor)Browser; var bootstrapTooltipType = javascriptExecutor .ExecuteScript("return window.customJsWasLoaded;"); Assert.True((bool)bootstrapTooltipType); } private void WaitUntilLoaded() { var app = Browser.Exists(By.TagName("app")); Browser.NotEqual("Loading...", () => app.Text); } }
HostedInAspNetTest
csharp
dotnet__efcore
test/EFCore.Tests/ChangeTracking/ChangeTrackerTest.cs
{ "start": 38698, "end": 84100 }
private class ____ : ValueGenerator<int> { private int _current; private bool _generatesTemporaryValues; public override bool GeneratesTemporaryValues => _generatesTemporaryValues; public override int Next(EntityEntry entry) => Interlocked.Increment(ref _current); public void Reset(bool generateTemporaryValues) { _generatesTemporaryValues = generateTemporaryValues; _current = 0; } } [ConditionalTheory, InlineData(false, CascadeTiming.OnSaveChanges, CascadeTiming.OnSaveChanges), InlineData(false, CascadeTiming.OnSaveChanges, CascadeTiming.Immediate), InlineData(false, CascadeTiming.OnSaveChanges, CascadeTiming.Never), InlineData(false, CascadeTiming.OnSaveChanges, null), InlineData(false, CascadeTiming.Immediate, CascadeTiming.OnSaveChanges), InlineData(false, CascadeTiming.Immediate, CascadeTiming.Immediate), InlineData(false, CascadeTiming.Immediate, CascadeTiming.Never), InlineData(false, CascadeTiming.Immediate, null), InlineData(false, CascadeTiming.Never, CascadeTiming.OnSaveChanges), InlineData(false, CascadeTiming.Never, CascadeTiming.Immediate), InlineData(false, CascadeTiming.Never, CascadeTiming.Never), InlineData(false, CascadeTiming.Never, null), InlineData(false, null, CascadeTiming.OnSaveChanges), InlineData(false, null, CascadeTiming.Immediate), InlineData(false, null, CascadeTiming.Never), InlineData(false, null, null), InlineData(true, CascadeTiming.OnSaveChanges, CascadeTiming.OnSaveChanges), InlineData(true, CascadeTiming.OnSaveChanges, CascadeTiming.Immediate), InlineData(true, CascadeTiming.OnSaveChanges, CascadeTiming.Never), InlineData(true, CascadeTiming.OnSaveChanges, null), InlineData(true, CascadeTiming.Immediate, CascadeTiming.OnSaveChanges), InlineData(true, CascadeTiming.Immediate, CascadeTiming.Immediate), InlineData(true, CascadeTiming.Immediate, CascadeTiming.Never), InlineData(true, CascadeTiming.Immediate, null), InlineData(true, CascadeTiming.Never, CascadeTiming.OnSaveChanges), InlineData(true, CascadeTiming.Never, CascadeTiming.Immediate), InlineData(true, CascadeTiming.Never, CascadeTiming.Never), InlineData(true, CascadeTiming.Never, null), InlineData(true, null, CascadeTiming.OnSaveChanges), InlineData(true, null, CascadeTiming.Immediate), InlineData(true, null, CascadeTiming.Never), InlineData(true, null, null)] public void Cascade_delete_is_logged( bool sensitive, CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { Seed(sensitive); using var context = sensitive ? new LikeAZooContextSensitive() : new LikeAZooContext(); if (cascadeDeleteTiming.HasValue) { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming.Value; } if (deleteOrphansTiming.HasValue) { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming.Value; } var cat = context.Cats.Include(e => e.Hats).Single(e => e.Id == 1); LogLevel? cascadeDeleteLevel = null; string? cascadeDeleteMessage = null; string? deleteOrphansMessage = null; void CaptureMessages() { (cascadeDeleteLevel, _, cascadeDeleteMessage, _, _) = _loggerFactory.Log.FirstOrDefault(e => e.Id.Id == CoreEventId.CascadeDelete.Id); (_, _, deleteOrphansMessage, _, _) = _loggerFactory.Log.FirstOrDefault(e => e.Id.Id == CoreEventId.CascadeDeleteOrphan.Id); } void ClearMessages() => _loggerFactory.Log.Clear(); switch (cascadeDeleteTiming) { case CascadeTiming.Immediate: case null: ClearMessages(); context.Entry(cat).State = EntityState.Deleted; CaptureMessages(); context.SaveChanges(); break; case CascadeTiming.OnSaveChanges: context.Entry(cat).State = EntityState.Deleted; ClearMessages(); context.SaveChanges(); CaptureMessages(); break; case CascadeTiming.Never: ClearMessages(); context.Entry(cat).State = EntityState.Deleted; Assert.Throws<InvalidOperationException>(() => context.SaveChanges()); CaptureMessages(); break; } Assert.Null(deleteOrphansMessage); if (cascadeDeleteTiming == CascadeTiming.Never) { Assert.Null(cascadeDeleteMessage); } else { Assert.Equal(LogLevel.Debug, cascadeDeleteLevel); Assert.Equal( sensitive ? CoreResources.LogCascadeDeleteSensitive(new TestLogger<TestLoggingDefinitions>()).GenerateMessage( nameof(Hat), "{Id: 77}", EntityState.Deleted, nameof(Cat), "{Id: 1}") : CoreResources.LogCascadeDelete(new TestLogger<TestLoggingDefinitions>()).GenerateMessage( nameof(Hat), EntityState.Deleted, nameof(Cat)), cascadeDeleteMessage); } } [ConditionalTheory, InlineData(false, CascadeTiming.OnSaveChanges, CascadeTiming.OnSaveChanges), InlineData(false, CascadeTiming.OnSaveChanges, CascadeTiming.Immediate), InlineData(false, CascadeTiming.OnSaveChanges, CascadeTiming.Never), InlineData(false, CascadeTiming.OnSaveChanges, null), InlineData(false, CascadeTiming.Immediate, CascadeTiming.OnSaveChanges), InlineData(false, CascadeTiming.Immediate, CascadeTiming.Immediate), InlineData(false, CascadeTiming.Immediate, CascadeTiming.Never), InlineData(false, CascadeTiming.Immediate, null), InlineData(false, CascadeTiming.Never, CascadeTiming.OnSaveChanges), InlineData(false, CascadeTiming.Never, CascadeTiming.Immediate), InlineData(false, CascadeTiming.Never, CascadeTiming.Never), InlineData(false, CascadeTiming.Never, null), InlineData(false, null, CascadeTiming.OnSaveChanges), InlineData(false, null, CascadeTiming.Immediate), InlineData(false, null, CascadeTiming.Never), InlineData(false, null, null), InlineData(true, CascadeTiming.OnSaveChanges, CascadeTiming.OnSaveChanges), InlineData(true, CascadeTiming.OnSaveChanges, CascadeTiming.Immediate), InlineData(true, CascadeTiming.OnSaveChanges, CascadeTiming.Never), InlineData(true, CascadeTiming.OnSaveChanges, null), InlineData(true, CascadeTiming.Immediate, CascadeTiming.OnSaveChanges), InlineData(true, CascadeTiming.Immediate, CascadeTiming.Immediate), InlineData(true, CascadeTiming.Immediate, CascadeTiming.Never), InlineData(true, CascadeTiming.Immediate, null), InlineData(true, CascadeTiming.Never, CascadeTiming.OnSaveChanges), InlineData(true, CascadeTiming.Never, CascadeTiming.Immediate), InlineData(true, CascadeTiming.Never, CascadeTiming.Never), InlineData(true, CascadeTiming.Never, null), InlineData(true, null, CascadeTiming.OnSaveChanges), InlineData(true, null, CascadeTiming.Immediate), InlineData(true, null, CascadeTiming.Never), InlineData(true, null, null)] public void Cascade_delete_orphan_is_logged( bool sensitive, CascadeTiming? cascadeDeleteTiming, CascadeTiming? deleteOrphansTiming) { Seed(sensitive); using var context = sensitive ? new LikeAZooContextSensitive() : new LikeAZooContext(); if (cascadeDeleteTiming.HasValue) { context.ChangeTracker.CascadeDeleteTiming = cascadeDeleteTiming.Value; } if (deleteOrphansTiming.HasValue) { context.ChangeTracker.DeleteOrphansTiming = deleteOrphansTiming.Value; } var cat = context.Cats.Include(e => e.Hats).Single(e => e.Id == 1); LogLevel? deleteOrphansLevel = null; string? cascadeDeleteMessage = null; string? deleteOrphansMessage = null; void CaptureMessages() { (_, _, cascadeDeleteMessage, _, _) = _loggerFactory.Log.FirstOrDefault(e => e.Id.Id == CoreEventId.CascadeDelete.Id); (deleteOrphansLevel, _, deleteOrphansMessage, _, _) = _loggerFactory.Log.FirstOrDefault(e => e.Id.Id == CoreEventId.CascadeDeleteOrphan.Id); } void ClearMessages() => _loggerFactory.Log.Clear(); switch (deleteOrphansTiming) { case CascadeTiming.Immediate: case null: ClearMessages(); cat.Hats.Clear(); context.ChangeTracker.DetectChanges(); CaptureMessages(); context.SaveChanges(); break; case CascadeTiming.OnSaveChanges: cat.Hats.Clear(); context.ChangeTracker.DetectChanges(); ClearMessages(); context.SaveChanges(); CaptureMessages(); break; case CascadeTiming.Never: ClearMessages(); cat.Hats.Clear(); context.ChangeTracker.DetectChanges(); Assert.Throws<InvalidOperationException>(() => context.SaveChanges()); CaptureMessages(); break; } Assert.Null(cascadeDeleteMessage); if (deleteOrphansTiming == CascadeTiming.Never) { Assert.Null(deleteOrphansMessage); } else { Assert.Equal(LogLevel.Debug, deleteOrphansLevel); Assert.Equal( sensitive ? CoreResources.LogCascadeDeleteOrphanSensitive(new TestLogger<TestLoggingDefinitions>()).GenerateMessage( nameof(Hat), "{Id: 77}", EntityState.Deleted, nameof(Cat)) : CoreResources.LogCascadeDeleteOrphan(new TestLogger<TestLoggingDefinitions>()) .GenerateMessage(nameof(Hat), EntityState.Deleted, nameof(Cat)), deleteOrphansMessage); } } [ConditionalTheory, InlineData(false), InlineData(true)] public async Task SaveChanges_is_logged(bool async) { Seed(); using var context = new LikeAZooContext(); var cat = context.Cats.Find(1)!; context.Entry(cat).State = EntityState.Deleted; _loggerFactory.Log.Clear(); if (async) { await context.SaveChangesAsync(); } else { context.SaveChanges(); } var (level, _, message, _, _) = _loggerFactory.Log.Single(e => e.Id.Id == CoreEventId.SaveChangesStarting.Id); Assert.Equal(LogLevel.Debug, level); Assert.Equal( CoreResources.LogSaveChangesStarting(new TestLogger<TestLoggingDefinitions>()).GenerateMessage(nameof(LikeAZooContext)), message); (level, _, message, _, _) = _loggerFactory.Log.Single(e => e.Id.Id == CoreEventId.SaveChangesCompleted.Id); Assert.Equal(LogLevel.Debug, level); Assert.Equal( CoreResources.LogSaveChangesCompleted(new TestLogger<TestLoggingDefinitions>()) .GenerateMessage(nameof(LikeAZooContext), 1), message); } [ConditionalFact] public void Context_Dispose_is_logged() { using (var context = new LikeAZooContext()) { context.Cats.Find(1); _loggerFactory.Log.Clear(); } var (level, _, message, _, _) = _loggerFactory.Log.Single(e => e.Id.Id == CoreEventId.ContextDisposed.Id); Assert.Equal(LogLevel.Debug, level); Assert.Equal( CoreResources.LogContextDisposed(new TestLogger<TestLoggingDefinitions>()).GenerateMessage(nameof(LikeAZooContext)), message); } [ConditionalFact] public void State_change_events_fire_from_query() { var tracking = new List<EntityTrackingEventArgs>(); var tracked = new List<EntityTrackedEventArgs>(); var changing = new List<EntityStateChangingEventArgs>(); var changed = new List<EntityStateChangedEventArgs>(); Seed(usePool: true); using (var scope = _poolProvider.CreateScope()) { var context = scope.ServiceProvider.GetRequiredService<LikeAZooContextPooled>(); RegisterEvents(context, tracking, tracked, changing, changed); Assert.Equal(2, context.Cats.OrderBy(e => e.Id).ToList().Count); Assert.Equal(2, tracking.Count); Assert.Equal(2, tracked.Count); Assert.Empty(changing); Assert.Empty(changed); AssertTrackedEvent(context, 1, EntityState.Unchanged, tracking[0], tracked[0], fromQuery: true); AssertTrackedEvent(context, 2, EntityState.Unchanged, tracking[1], tracked[1], fromQuery: true); } using (var scope = _poolProvider.CreateScope()) { var context = scope.ServiceProvider.GetRequiredService<LikeAZooContextPooled>(); Assert.Equal(2, context.Cats.OrderBy(e => e.Id).ToList().Count); Assert.Equal(2, tracked.Count); Assert.Empty(changed); } } [ConditionalFact] public void State_change_events_fire_from_Attach() { var tracking = new List<EntityTrackingEventArgs>(); var tracked = new List<EntityTrackedEventArgs>(); var changing = new List<EntityStateChangingEventArgs>(); var changed = new List<EntityStateChangedEventArgs>(); using var scope = _poolProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService<LikeAZooContextPooled>(); RegisterEvents(context, tracking, tracked, changing, changed); context.Attach(new Cat(1)); Assert.False(context.ChangeTracker.HasChanges()); Assert.Single(tracked); Assert.Empty(changed); AssertTrackedEvent(context, 1, EntityState.Unchanged, tracking[0], tracked[0], fromQuery: false); context.Entry(new Cat(2)).State = EntityState.Unchanged; Assert.False(context.ChangeTracker.HasChanges()); Assert.Equal(2, tracked.Count); Assert.Empty(changed); AssertTrackedEvent(context, 2, EntityState.Unchanged, tracking[1], tracked[1], fromQuery: false); } [ConditionalFact] public void State_change_events_fire_from_Add() { var tracking = new List<EntityTrackingEventArgs>(); var tracked = new List<EntityTrackedEventArgs>(); var changing = new List<EntityStateChangingEventArgs>(); var changed = new List<EntityStateChangedEventArgs>(); using var scope = _poolProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService<LikeAZooContextPooled>(); RegisterEvents(context, tracking, tracked, changing, changed); context.Add(new Cat(1)); Assert.True(context.ChangeTracker.HasChanges()); Assert.Single(tracked); Assert.Empty(changed); AssertTrackedEvent(context, 1, EntityState.Added, tracking[0], tracked[0], fromQuery: false); context.Entry(new Cat(2)).State = EntityState.Added; Assert.True(context.ChangeTracker.HasChanges()); Assert.Equal(2, tracked.Count); Assert.Empty(changed); AssertTrackedEvent(context, 2, EntityState.Added, tracking[1], tracked[1], fromQuery: false); } [ConditionalFact] public void State_change_events_fire_from_Update() { var tracking = new List<EntityTrackingEventArgs>(); var tracked = new List<EntityTrackedEventArgs>(); var changing = new List<EntityStateChangingEventArgs>(); var changed = new List<EntityStateChangedEventArgs>(); using var scope = _poolProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService<LikeAZooContextPooled>(); RegisterEvents(context, tracking, tracked, changing, changed); context.Update(new Cat(1)); Assert.True(context.ChangeTracker.HasChanges()); Assert.Single(tracked); Assert.Empty(changed); AssertTrackedEvent(context, 1, EntityState.Modified, tracking[0], tracked[0], fromQuery: false); context.Entry(new Cat(2)).State = EntityState.Modified; Assert.True(context.ChangeTracker.HasChanges()); Assert.Equal(2, tracked.Count); Assert.Empty(changed); AssertTrackedEvent(context, 2, EntityState.Modified, tracking[1], tracked[1], fromQuery: false); } [ConditionalFact] public void State_change_events_fire_for_tracked_state_changes() { var tracking = new List<EntityTrackingEventArgs>(); var tracked = new List<EntityTrackedEventArgs>(); var changing = new List<EntityStateChangingEventArgs>(); var changed = new List<EntityStateChangedEventArgs>(); using (var scope = _poolProvider.CreateScope()) { var context = scope.ServiceProvider.GetRequiredService<LikeAZooContextPooled>(); RegisterEvents(context, tracking, tracked, changing, changed); context.AddRange(new Cat(1), new Cat(2)); Assert.True(context.ChangeTracker.HasChanges()); Assert.Equal(2, tracked.Count); Assert.Empty(changed); AssertTrackedEvent(context, 1, EntityState.Added, tracking[0], tracked[0], fromQuery: false); AssertTrackedEvent(context, 2, EntityState.Added, tracking[1], tracked[1], fromQuery: false); context.Entry(context.Cats.Find(1)!).State = EntityState.Unchanged; context.Entry(context.Cats.Find(2)!).State = EntityState.Modified; Assert.Equal(2, tracked.Count); Assert.Equal(2, changed.Count); Assert.True(context.ChangeTracker.HasChanges()); AssertChangedEvent(context, 1, EntityState.Added, EntityState.Unchanged, changing[0], changed[0]); AssertChangedEvent(context, 2, EntityState.Added, EntityState.Modified, changing[1], changed[1]); context.Entry(context.Cats.Find(1)!).State = EntityState.Added; context.Entry(context.Cats.Find(2)!).State = EntityState.Deleted; Assert.Equal(2, tracked.Count); Assert.Equal(4, changed.Count); AssertChangedEvent(context, 1, EntityState.Unchanged, EntityState.Added, changing[2], changed[2]); AssertChangedEvent(context, 2, EntityState.Modified, EntityState.Deleted, changing[3], changed[3]); context.Remove(context.Cats.Find(1)!); context.Entry(context.Cats.Find(2)!).State = EntityState.Detached; Assert.False(context.ChangeTracker.HasChanges()); Assert.Equal(2, tracked.Count); Assert.Equal(6, changed.Count); AssertChangedEvent(context, null, EntityState.Added, EntityState.Detached, changing[4], changed[4]); AssertChangedEvent(context, null, EntityState.Deleted, EntityState.Detached, changing[5], changed[5]); } using (var scope = _poolProvider.CreateScope()) { var context = scope.ServiceProvider.GetRequiredService<LikeAZooContextPooled>(); context.AddRange(new Cat(1), new Cat(2)); context.Entry(context.Cats.Find(1)!).State = EntityState.Unchanged; context.Entry(context.Cats.Find(2)!).State = EntityState.Modified; context.Entry(context.Cats.Find(1)!).State = EntityState.Added; context.Entry(context.Cats.Find(2)!).State = EntityState.Deleted; context.Remove(context.Cats.Find(1)!); context.Entry(context.Cats.Find(2)!).State = EntityState.Detached; Assert.Equal(2, tracked.Count); Assert.Equal(6, changed.Count); } } [ConditionalTheory, InlineData(false), InlineData(true)] public void State_change_events_fire_when_saving_changes(bool callDetectChangesTwice) { var tracking = new List<EntityTrackingEventArgs>(); var tracked = new List<EntityTrackedEventArgs>(); var changing = new List<EntityStateChangingEventArgs>(); var changed = new List<EntityStateChangedEventArgs>(); Seed(usePool: true); using var scope = _poolProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService<LikeAZooContextPooled>(); RegisterEvents(context, tracking, tracked, changing, changed); var cat1 = context.Cats.Find(1)!; Assert.Single(tracked); Assert.Empty(changed); AssertTrackedEvent(context, 1, EntityState.Unchanged, tracking[0], tracked[0], fromQuery: true); context.Add(new Cat(3)); cat1.Name = "Clippy"; context.ChangeTracker.DetectChanges(); if (callDetectChangesTwice) { context.ChangeTracker.DetectChanges(); } Assert.Equal(2, tracked.Count); Assert.Single(changed); AssertTrackedEvent(context, 3, EntityState.Added, tracking[1], tracked[1], fromQuery: false); AssertChangedEvent(context, 1, EntityState.Unchanged, EntityState.Modified, changing[0], changed[0]); Assert.True(context.ChangeTracker.HasChanges()); context.SaveChanges(); Assert.False(context.ChangeTracker.HasChanges()); Assert.Equal(2, tracked.Count); Assert.Equal(3, changed.Count); AssertChangedEvent(context, 1, EntityState.Modified, EntityState.Unchanged, changing[2], changed[2]); AssertChangedEvent(context, 3, EntityState.Added, EntityState.Unchanged, changing[1], changed[1]); context.Database.EnsureDeleted(); } [ConditionalFact] public void State_change_events_fire_when_property_modified_flags_cause_state_change() { var tracking = new List<EntityTrackingEventArgs>(); var tracked = new List<EntityTrackedEventArgs>(); var changing = new List<EntityStateChangingEventArgs>(); var changed = new List<EntityStateChangedEventArgs>(); using var scope = _poolProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService<LikeAZooContextPooled>(); RegisterEvents(context, tracking, tracked, changing, changed); var cat = context.Attach( new Cat(3) { Name = "Achilles" }).Entity; Assert.False(context.ChangeTracker.HasChanges()); Assert.Single(tracked); Assert.Empty(changed); AssertTrackedEvent(context, 3, EntityState.Unchanged, tracking[0], tracked[0], fromQuery: false); context.Entry(cat).Property(e => e.Name).IsModified = true; Assert.True(context.ChangeTracker.HasChanges()); Assert.Single(tracked); Assert.Single(changed); AssertChangedEvent(context, 3, EntityState.Unchanged, EntityState.Modified, changing[0], changed[0]); context.Entry(cat).Property(e => e.Name).IsModified = false; Assert.False(context.ChangeTracker.HasChanges()); Assert.Single(tracked); Assert.Equal(2, changed.Count); AssertChangedEvent(context, 3, EntityState.Modified, EntityState.Unchanged, changing[1], changed[1]); } [ConditionalFact] public void State_change_events_are_limited_to_the_current_context() { var tracking1 = new List<EntityTrackingEventArgs>(); var tracked1 = new List<EntityTrackedEventArgs>(); var changing1 = new List<EntityStateChangingEventArgs>(); var changed1 = new List<EntityStateChangedEventArgs>(); var tracking2 = new List<EntityTrackingEventArgs>(); var tracked2 = new List<EntityTrackedEventArgs>(); var changing2 = new List<EntityStateChangingEventArgs>(); var changed2 = new List<EntityStateChangedEventArgs>(); Seed(usePool: true); using var scope = _poolProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService<LikeAZooContextPooled>(); RegisterEvents(context, tracking1, tracked1, changing1, changed1); using (var scope2 = _poolProvider.CreateScope()) { var context2 = scope2.ServiceProvider.GetRequiredService<LikeAZooContextPooled>(); RegisterEvents(context2, tracking2, tracked2, changing2, changed2); Assert.Equal(2, context2.Cats.OrderBy(e => e.Id).ToList().Count); Assert.Equal(2, tracked2.Count); Assert.Empty(changed2); context2.Entry(context2.Cats.Find(1)!).State = EntityState.Modified; Assert.Equal(2, tracked2.Count); Assert.Single(changed2); Assert.Empty(tracked1); Assert.Empty(changed1); } Assert.Equal(2, context.Cats.OrderBy(e => e.Id).ToList().Count); Assert.Equal(2, tracked1.Count); Assert.Empty(changed1); context.Entry(context.Cats.Find(1)!).State = EntityState.Modified; Assert.Equal(2, tracked1.Count); Assert.Single(changed1); Assert.Equal(2, tracked2.Count); Assert.Single(changed2); context.Database.EnsureDeleted(); } [ConditionalFact] public void DetectChanges_events_fire_for_no_change() { var detectingAll = new List<DetectChangesEventArgs>(); var detectedAll = new List<DetectedChangesEventArgs>(); var detectingEntity = new List<DetectEntityChangesEventArgs>(); var detectedEntity = new List<DetectedEntityChangesEventArgs>(); using var scope = _poolProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService<LikeAZooContextPooled>(); RegisterDetectAllEvents(context, detectingAll, detectedAll); RegisterDetectEntityEvents(context, detectingEntity, detectedEntity); context.AttachRange(new Cat(1), new Cat(2)); Assert.Empty(detectingAll); Assert.Empty(detectedAll); Assert.False(context.ChangeTracker.HasChanges()); Assert.Single(detectingAll); Assert.Single(detectedAll); Assert.Equal(2, detectingEntity.Count); Assert.Equal(2, detectedEntity.Count); Assert.False(detectedAll[0].ChangesFound); Assert.False(detectedEntity[0].ChangesFound); Assert.False(detectedEntity[1].ChangesFound); } [ConditionalFact] public void DetectChanges_events_fire_for_property_change() { var detectingAll = new List<DetectChangesEventArgs>(); var detectedAll = new List<DetectedChangesEventArgs>(); var detectingEntity = new List<DetectEntityChangesEventArgs>(); var detectedEntity = new List<DetectedEntityChangesEventArgs>(); using var scope = _poolProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService<LikeAZooContextPooled>(); RegisterDetectAllEvents(context, detectingAll, detectedAll); RegisterDetectEntityEvents(context, detectingEntity, detectedEntity); var cat = new Cat(1); context.AttachRange(cat, new Cat(2)); cat.Name = "Alice"; Assert.Empty(detectingAll); Assert.Empty(detectedAll); Assert.True(context.ChangeTracker.HasChanges()); Assert.Single(detectingAll); Assert.Single(detectedAll); Assert.Equal(2, detectingEntity.Count); Assert.Equal(2, detectedEntity.Count); Assert.True(detectedAll[0].ChangesFound); Assert.True(detectedEntity[0].ChangesFound); Assert.False(detectedEntity[1].ChangesFound); } [ConditionalFact] public void DetectChanges_events_fire_for_fk_change() { var detectingAll = new List<DetectChangesEventArgs>(); var detectedAll = new List<DetectedChangesEventArgs>(); var detectingEntity = new List<DetectEntityChangesEventArgs>(); var detectedEntity = new List<DetectedEntityChangesEventArgs>(); using var scope = _poolProvider.CreateScope(); using var context = new EarlyLearningCenter(); RegisterDetectAllEvents(context, detectingAll, detectedAll); RegisterDetectEntityEvents(context, detectingEntity, detectedEntity); var product = new Product { Category = new Category() }; context.Attach(product); product.CategoryId = 2; Assert.Empty(detectingAll); Assert.Empty(detectedAll); Assert.True(context.ChangeTracker.HasChanges()); Assert.Single(detectingAll); Assert.Single(detectedAll); Assert.Equal(2, detectingEntity.Count); Assert.Equal(2, detectedEntity.Count); Assert.True(detectedAll[0].ChangesFound); Assert.True(detectedEntity[0].ChangesFound); Assert.False(detectedEntity[1].ChangesFound); } [ConditionalFact] public void DetectChanges_events_fire_for_reference_navigation_change() { var detectingAll = new List<DetectChangesEventArgs>(); var detectedAll = new List<DetectedChangesEventArgs>(); var detectingEntity = new List<DetectEntityChangesEventArgs>(); var detectedEntity = new List<DetectedEntityChangesEventArgs>(); using var scope = _poolProvider.CreateScope(); using var context = new EarlyLearningCenter(); RegisterDetectAllEvents(context, detectingAll, detectedAll); RegisterDetectEntityEvents(context, detectingEntity, detectedEntity); var product = new Product { Category = new Category() }; context.Attach(product); product.Category = null; Assert.Empty(detectingAll); Assert.Empty(detectedAll); Assert.True(context.ChangeTracker.HasChanges()); Assert.Single(detectingAll); Assert.Single(detectedAll); Assert.Equal(2, detectingEntity.Count); Assert.Equal(2, detectedEntity.Count); Assert.True(detectedAll[0].ChangesFound); Assert.True(detectedEntity[0].ChangesFound); Assert.False(detectedEntity[1].ChangesFound); } [ConditionalFact] public void DetectChanges_events_fire_for_collection_navigation_change() { var detectingAll = new List<DetectChangesEventArgs>(); var detectedAll = new List<DetectedChangesEventArgs>(); var detectingEntity = new List<DetectEntityChangesEventArgs>(); var detectedEntity = new List<DetectedEntityChangesEventArgs>(); using var scope = _poolProvider.CreateScope(); using var context = new EarlyLearningCenter(); RegisterDetectAllEvents(context, detectingAll, detectedAll); RegisterDetectEntityEvents(context, detectingEntity, detectedEntity); var product = new Product { Category = new Category() }; context.Attach(product); product.Category.Products.Clear(); Assert.Empty(detectingAll); Assert.Empty(detectedAll); Assert.True(context.ChangeTracker.HasChanges()); Assert.Single(detectingAll); Assert.Single(detectedAll); Assert.Equal(2, detectingEntity.Count); Assert.Equal(2, detectedEntity.Count); Assert.True(detectedAll[0].ChangesFound); Assert.False(detectedEntity[0].ChangesFound); Assert.True(detectedEntity[1].ChangesFound); } [ConditionalFact] public void DetectChanges_events_fire_for_skip_navigation_change() { var detectingAll = new List<DetectChangesEventArgs>(); var detectedAll = new List<DetectedChangesEventArgs>(); var detectingEntity = new List<DetectEntityChangesEventArgs>(); var detectedEntity = new List<DetectedEntityChangesEventArgs>(); using var scope = _poolProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService<LikeAZooContextPooled>(); RegisterDetectAllEvents(context, detectingAll, detectedAll); RegisterDetectEntityEvents(context, detectingEntity, detectedEntity); var cat = new Cat(1) { Hats = { new Hat(2) } }; context.Attach(cat); cat.Hats.Clear(); Assert.Empty(detectingAll); Assert.Empty(detectedAll); Assert.True(context.ChangeTracker.HasChanges()); Assert.Single(detectingAll); Assert.Single(detectedAll); Assert.Equal(2, detectingEntity.Count); Assert.Equal(2, detectedEntity.Count); Assert.True(detectedAll[0].ChangesFound); Assert.True(detectedEntity[0].ChangesFound); Assert.False(detectedEntity[1].ChangesFound); } [ConditionalFact] public void Local_DetectChanges_events_fire_for_no_change() { var detectingAll = new List<DetectChangesEventArgs>(); var detectedAll = new List<DetectedChangesEventArgs>(); var detectingEntity = new List<DetectEntityChangesEventArgs>(); var detectedEntity = new List<DetectedEntityChangesEventArgs>(); using var scope = _poolProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService<LikeAZooContextPooled>(); RegisterDetectAllEvents(context, detectingAll, detectedAll); RegisterDetectEntityEvents(context, detectingEntity, detectedEntity); var cat = new Cat(1); context.AttachRange(cat, new Cat(2)); Assert.Empty(detectingEntity); Assert.Empty(detectedEntity); _ = context.Entry(cat); Assert.Empty(detectingAll); Assert.Empty(detectedAll); Assert.Single(detectingEntity); Assert.Single(detectedEntity); AssertLocalDetectChangesEvent(changesFound: false, detectingEntity[0], detectedEntity[0]); } [ConditionalFact] public void Local_DetectChanges_events_fire_for_property_change() { var detectingAll = new List<DetectChangesEventArgs>(); var detectedAll = new List<DetectedChangesEventArgs>(); var detectingEntity = new List<DetectEntityChangesEventArgs>(); var detectedEntity = new List<DetectedEntityChangesEventArgs>(); using var scope = _poolProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService<LikeAZooContextPooled>(); RegisterDetectAllEvents(context, detectingAll, detectedAll); RegisterDetectEntityEvents(context, detectingEntity, detectedEntity); var cat = new Cat(1); context.AttachRange(cat, new Cat(2)); cat.Name = "Alice"; Assert.Empty(detectingEntity); Assert.Empty(detectedEntity); _ = context.Entry(cat); Assert.Empty(detectingAll); Assert.Empty(detectedAll); Assert.Single(detectingEntity); Assert.Single(detectedEntity); AssertLocalDetectChangesEvent(changesFound: true, detectingEntity[0], detectedEntity[0]); } [ConditionalFact] public void Local_DetectChanges_events_fire_for_fk_change() { var detectingAll = new List<DetectChangesEventArgs>(); var detectedAll = new List<DetectedChangesEventArgs>(); var detectingEntity = new List<DetectEntityChangesEventArgs>(); var detectedEntity = new List<DetectedEntityChangesEventArgs>(); using var scope = _poolProvider.CreateScope(); using var context = new EarlyLearningCenter(); RegisterDetectAllEvents(context, detectingAll, detectedAll); RegisterDetectEntityEvents(context, detectingEntity, detectedEntity); var product = new Product { Category = new Category() }; context.Attach(product); product.CategoryId = 2; Assert.Empty(detectingEntity); Assert.Empty(detectedEntity); _ = context.Entry(product); Assert.Empty(detectingAll); Assert.Empty(detectedAll); Assert.Single(detectingEntity); Assert.Single(detectedEntity); AssertLocalDetectChangesEvent(changesFound: true, detectingEntity[0], detectedEntity[0]); } [ConditionalFact] public void Local_DetectChanges_events_fire_for_reference_navigation_change() { var detectingAll = new List<DetectChangesEventArgs>(); var detectedAll = new List<DetectedChangesEventArgs>(); var detectingEntity = new List<DetectEntityChangesEventArgs>(); var detectedEntity = new List<DetectedEntityChangesEventArgs>(); using var scope = _poolProvider.CreateScope(); using var context = new EarlyLearningCenter(); RegisterDetectAllEvents(context, detectingAll, detectedAll); RegisterDetectEntityEvents(context, detectingEntity, detectedEntity); var product = new Product { Category = new Category() }; context.Attach(product); product.Category = null; Assert.Empty(detectingEntity); Assert.Empty(detectedEntity); _ = context.Entry(product); Assert.Empty(detectingAll); Assert.Empty(detectedAll); Assert.Equal(2, detectingEntity.Count); Assert.Equal(2, detectedEntity.Count); AssertLocalDetectChangesEvent(changesFound: false, detectingEntity[0], detectedEntity[0]); AssertLocalDetectChangesEvent(changesFound: true, detectingEntity[1], detectedEntity[1]); } [ConditionalFact] public void Local_DetectChanges_events_fire_for_collection_navigation_change() { var detectingAll = new List<DetectChangesEventArgs>(); var detectedAll = new List<DetectedChangesEventArgs>(); var detectingEntity = new List<DetectEntityChangesEventArgs>(); var detectedEntity = new List<DetectedEntityChangesEventArgs>(); using var scope = _poolProvider.CreateScope(); using var context = new EarlyLearningCenter(); RegisterDetectAllEvents(context, detectingAll, detectedAll); RegisterDetectEntityEvents(context, detectingEntity, detectedEntity); var product = new Product { Category = new Category() }; context.Attach(product); product.Category.Products.Clear(); Assert.Empty(detectingEntity); Assert.Empty(detectedEntity); _ = context.Entry(product.Category); Assert.Empty(detectingAll); Assert.Empty(detectedAll); Assert.Single(detectingEntity); Assert.Single(detectedEntity); AssertLocalDetectChangesEvent(changesFound: true, detectingEntity[0], detectedEntity[0]); } [ConditionalFact] public void Local_DetectChanges_events_fire_for_skip_navigation_change() { var detectingAll = new List<DetectChangesEventArgs>(); var detectedAll = new List<DetectedChangesEventArgs>(); var detectingEntity = new List<DetectEntityChangesEventArgs>(); var detectedEntity = new List<DetectedEntityChangesEventArgs>(); using var scope = _poolProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService<LikeAZooContextPooled>(); RegisterDetectAllEvents(context, detectingAll, detectedAll); RegisterDetectEntityEvents(context, detectingEntity, detectedEntity); var cat = new Cat(1) { Hats = { new Hat(2) } }; context.Attach(cat); cat.Hats.Clear(); Assert.Empty(detectingEntity); Assert.Empty(detectedEntity); _ = context.Entry(cat); Assert.Empty(detectingAll); Assert.Empty(detectedAll); Assert.Single(detectingEntity); Assert.Single(detectedEntity); AssertLocalDetectChangesEvent(changesFound: true, detectingEntity[0], detectedEntity[0]); } [ConditionalFact] // Issue #26506 public void DetectChanges_event_can_be_used_to_know_when_all_properties_have_changed() { using var scope = _poolProvider.CreateScope(); var context = scope.ServiceProvider.GetRequiredService<LikeAZooContextPooled>(); var hat = new Hat(2) { Color = "Orange" }; var cat1 = new Cat(1) { Hats = { hat } }; var cat2 = new Cat(2); context.AttachRange(cat1, cat2); var stateChangedCalled = false; context.ChangeTracker.StateChanged += (s, a) => { stateChangedCalled = true; Assert.Equal("Black", a.Entry.Property(nameof(Hat.Color)).CurrentValue); Assert.Equal(1, a.Entry.Property(nameof(Hat.CatId)).CurrentValue); }; var detectedChangesCalled = false; context.ChangeTracker.DetectedEntityChanges += (s, a) => { if (a.ChangesFound) { detectedChangesCalled = true; Assert.Equal("Black", a.Entry.Property(nameof(Hat.Color)).CurrentValue); Assert.Equal(2, a.Entry.Property(nameof(Hat.CatId)).CurrentValue); } }; hat.Cat = cat2; hat.Color = "Black"; context.ChangeTracker.DetectChanges(); Assert.True(stateChangedCalled); Assert.True(detectedChangesCalled); Assert.Equal(2, hat.CatId); } private static void AssertTrackedEvent( LikeAZooContext context, int id, EntityState newState, EntityTrackingEventArgs tracking, EntityTrackedEventArgs tracked, bool fromQuery) { Assert.Same(tracking.Entry.Entity, tracked.Entry.Entity); Assert.Equal(newState, tracking.State); Assert.Equal(newState, tracked.Entry.State); Assert.Equal(fromQuery, tracking.FromQuery); Assert.Equal(fromQuery, tracked.FromQuery); Assert.Same(context.Cats.Find(id), tracked.Entry.Entity); } private static void AssertChangedEvent( LikeAZooContext context, int? id, EntityState oldState, EntityState newState, EntityStateChangingEventArgs changing, EntityStateChangedEventArgs changed) { Assert.Same(changing.Entry.Entity, changed.Entry.Entity); Assert.Equal(oldState, changing.OldState); Assert.Equal(newState, changing.NewState); Assert.Equal(oldState, changed.OldState); Assert.Equal(newState, changed.NewState); Assert.Equal(newState, changed.Entry.State); if (id != null) { Assert.Same(context.Cats.Find(id), changed.Entry.Entity); } } private static void AssertLocalDetectChangesEvent( bool changesFound, DetectEntityChangesEventArgs detectingEntity, DetectedEntityChangesEventArgs detectedEntity) { Assert.Same(detectingEntity.Entry.Entity, detectedEntity.Entry.Entity); Assert.Equal(changesFound, detectedEntity.ChangesFound); } private static void RegisterEvents( DbContext context, IList<EntityTrackingEventArgs> tracking, IList<EntityTrackedEventArgs> tracked, IList<EntityStateChangingEventArgs> changing, IList<EntityStateChangedEventArgs> changed) { context.ChangeTracker.Tracking += (s, e) => { Assert.Same(context.ChangeTracker, s); tracking.Add(e); }; context.ChangeTracker.Tracked += (s, e) => { Assert.Same(context.ChangeTracker, s); tracked.Add(e); }; context.ChangeTracker.StateChanging += (s, e) => { Assert.Same(context.ChangeTracker, s); Assert.Equal(e.OldState, e.Entry.State); changing.Add(e); }; context.ChangeTracker.StateChanged += (s, e) => { Assert.Same(context.ChangeTracker, s); Assert.Equal(e.NewState, e.Entry.State); changed.Add(e); }; } private static void RegisterDetectAllEvents( DbContext context, IList<DetectChangesEventArgs> detectingAll, IList<DetectedChangesEventArgs> detectedAll) { context.ChangeTracker.DetectingAllChanges += (s, e) => { _ = context.ChangeTracker.Entries().ToList(); // Should not recursively call DetectChanges Assert.Same(context.ChangeTracker, s); detectingAll.Add(e); }; context.ChangeTracker.DetectedAllChanges += (s, e) => { _ = context.ChangeTracker.Entries().ToList(); // Should not recursively call DetectChanges Assert.Same(context.ChangeTracker, s); detectedAll.Add(e); }; } private static void RegisterDetectEntityEvents( DbContext context, IList<DetectEntityChangesEventArgs> detectingEntity, IList<DetectedEntityChangesEventArgs> detectedEntity) { context.ChangeTracker.DetectingEntityChanges += (s, e) => { _ = context.ChangeTracker.Entries().ToList(); // Should not recursively call DetectChanges Assert.Same(context.ChangeTracker, s); Assert.NotNull(e.Entry); detectingEntity.Add(e); }; context.ChangeTracker.DetectedEntityChanges += (s, e) => { _ = context.ChangeTracker.Entries().ToList(); // Should not recursively call DetectChanges Assert.Same(context.ChangeTracker, s); Assert.NotNull(e.Entry); detectedEntity.Add(e); }; }
ResettableValueGenerator
csharp
dotnet__machinelearning
src/Microsoft.ML.FastTree/GamModelParameters.cs
{ "start": 37982, "end": 47703 }
public sealed class ____ { public int Index { get; } public string Name { get; } /// <summary> /// The upper bounds of each bin. /// </summary> public IEnumerable<double> UpperBounds { get; } /// <summary> /// The amount added to the model for a document falling in a given bin. /// </summary> public IEnumerable<double> BinEffects { get; } /// <summary> /// The number of documents in each bin. /// </summary> public IEnumerable<int> DocCounts { get; } /// <summary> /// The version of the GAM context that has these values. /// </summary> public long Version { get; } /// <summary> /// For features belonging to the same categorical, this value will be the same, /// Set to -1 for non-categoricals. /// </summary> public int CategoricalFeatureIndex { get; } private FeatureInfo(Context context, int index, int internalIndex, int[] catsMap) { Contracts.AssertValue(context); Contracts.Assert(context._pred._inputFeatureToShapeFunctionMap.ContainsKey(index) && context._pred._inputFeatureToShapeFunctionMap[index] == internalIndex); Index = index; var name = context._featNames.GetItemOrDefault(index).ToString(); Name = string.IsNullOrEmpty(name) ? $"f{index}" : name; var up = context._pred._binUpperBounds[internalIndex]; UpperBounds = up.Take(up.Length - 1); BinEffects = context._pred._binEffects[internalIndex]; DocCounts = context._binDocsList[internalIndex].Select(Utils.Size); Version = context._version; CategoricalFeatureIndex = -1; if (catsMap != null && index < catsMap[catsMap.Length - 1]) { for (int i = 0; i < catsMap.Length; i += 2) { if (index >= catsMap[i] && index <= catsMap[i + 1]) { CategoricalFeatureIndex = i; break; } } } } public static FeatureInfo GetInfoForIndex(Context context, int index) { Contracts.AssertValue(context); Contracts.Assert(0 <= index && index < context._pred._inputType.Size); lock (context._pred) { int internalIndex; if (!context._pred._inputFeatureToShapeFunctionMap.TryGetValue(index, out internalIndex)) return null; return new FeatureInfo(context, index, internalIndex, context._catsMap); } } public static FeatureInfo[] GetInfos(Context context) { lock (context._pred) { return Utils.BuildArray(context._pred.NumberOfShapeFunctions, i => new FeatureInfo(context, context._pred._shapeToInputMap[i], i, context._catsMap)); } } } } /// <summary> /// Attempts to initialize required items, from the input model file. It could throw if something goes wrong. /// </summary> /// <param name="ch">The channel</param> /// <returns>A structure containing essential information about the GAM dataset that enables /// operations on top of that structure.</returns> private Context Init(IChannel ch) { ILegacyDataLoader loader; IPredictor rawPred; RoleMappedSchema schema; LoadModelObjects(ch, true, out rawPred, true, out schema, out loader); bool hadCalibrator = false; // The rawPred has two possible types: // 1. CalibratedPredictorBase<BinaryClassificationGamModelParameters, PlattCalibrator> // 2. RegressionGamModelParameters // For (1), the trained model, GamModelParametersBase, is a field we need to extract. For (2), // we don't need to do anything because RegressionGamModelParameters is derived from GamModelParametersBase. var calibrated = rawPred as CalibratedModelParametersBase<GamBinaryModelParameters, PlattCalibrator>; while (calibrated != null) { hadCalibrator = true; rawPred = calibrated.SubModel; calibrated = rawPred as CalibratedModelParametersBase<GamBinaryModelParameters, PlattCalibrator>; } var pred = rawPred as GamModelParametersBase; ch.CheckUserArg(pred != null, nameof(ImplOptions.InputModelFile), "Predictor was not a " + nameof(GamModelParametersBase)); var data = new RoleMappedData(loader, schema.GetColumnRoleNames(), opt: true); if (hadCalibrator && !string.IsNullOrWhiteSpace(ImplOptions.OutputModelFile)) ch.Warning("If you save the GAM model, only the GAM model, not the wrapping calibrator, will be saved."); return new Context(ch, pred, data, InitEvaluator(pred)); } private IEvaluator InitEvaluator(GamModelParametersBase pred) { switch (pred.PredictionKind) { case PredictionKind.BinaryClassification: return new BinaryClassifierEvaluator(Host, new BinaryClassifierEvaluator.Arguments()); case PredictionKind.Regression: return new RegressionEvaluator(Host, new RegressionEvaluator.Arguments()); default: return null; } } private void Run(IChannel ch) { // First we're going to initialize a structure with lots of information about the predictor, trainer, etc. var context = Init(ch); // REVIEW: What to do with the data? Not sure. Take a sample? We could have // a very compressed one, since we can just "bin" everything based on pred._binUpperBounds. Anyway // whatever we choose to do, ultimately it will be exposed as some delegate on the server channel. // Maybe binning actually isn't wise, *if* we want people to be able to set their own split points // (which seems plausible). In the current version of the viz you can only set bin effects, but // "splitting" a bin might be desirable in some cases, maybe. Or not. // Now we have a gam predictor, AutoResetEvent ev = new AutoResetEvent(false); using (var server = InitServer(ch)) using (var sch = Host.StartServerChannel("predictor/gam")) { // The number of features. sch?.Register("numFeatures", () => context.NumFeatures); // Info for a particular feature. sch?.Register<int, Context.FeatureInfo>("info", context.GetInfoForIndex); // Info for all features. sch?.Register("infos", context.GetInfos); // Modification of the model. sch?.Register<int, int, double, long>("setEffect", context.SetEffect); // Getting the metrics. sch?.Register("metrics", context.GetMetrics); sch?.Register("canSave", () => !string.IsNullOrEmpty(ImplOptions.OutputModelFile)); sch?.Register("save", () => context.SaveIfNeeded(Host, ch, ImplOptions.OutputModelFile)); sch?.Register("quit", () => { var retVal = context.SaveIfNeeded(Host, ch, ImplOptions.OutputModelFile); ev.Set(); return retVal; }); // Targets and scores for data. sch?.Publish(); if (sch != null) { ch.Info("GAM viz server is ready and waiting."); Uri uri = server.BaseAddress; // Believe it or not, this is actually the recommended procedure according to MSDN. if (_open) System.Diagnostics.Process.Start(uri.AbsoluteUri + "content/GamViz/"); ev.WaitOne(); ch.Info("Quit signal received. Quitter."); } else ch.Info("No server, exiting immediately."); } } } } }
FeatureInfo
csharp
dotnetcore__WTM
demo/WalkingTec.Mvvm.Vue3Demo/Areas/testvue/ViewModels/SchoolVue3VMs/SchoolVue3ImportVM.cs
{ "start": 1554, "end": 1651 }
public class ____ : BaseImportVM<SchoolVue3TemplateVM, SchoolVue3> { } }
SchoolVue3ImportVM
csharp
AvaloniaUI__Avalonia
src/Browser/Avalonia.Browser/BrowserInputPane.cs
{ "start": 160, "end": 668 }
internal class ____ : InputPaneBase { public bool OnGeometryChange(double x, double y, double width, double height) { var oldState = (OccludedRect, State); OccludedRect = new Rect(x, y, width, height); State = OccludedRect.Width != 0 ? InputPaneState.Open : InputPaneState.Closed; if (oldState != (OccludedRect, State)) { OnStateChanged(new InputPaneStateEventArgs(State, null, OccludedRect)); } return true; } }
BrowserInputPane
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp/Modules/DependsOnAttribute.cs
{ "start": 160, "end": 295 }
class ____ from <see cref="AbpModule"/>. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
derived
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.Desktop/DesktopConfig.cs
{ "start": 175, "end": 1357 }
public class ____ { public static DesktopConfig Instance { get; } = new(); public List<ProxyConfig> ProxyConfigs { get; set; } = new(); public string AppName { get; set; } public List<string> ImportParams { get; set; } = new(); public string MinToolVersion { get; set; } public Action OnExit { get; set; } public Action<Exception> OnError { get; set; } public static Func<ScriptScopeContext, IntPtr> WindowFactory { get; set; } = RequestWindowFactory; public static IntPtr RequestWindowFactory(ScriptScopeContext scope) { if (scope.TryGetValue(ScriptConstants.Request, out var oRequest) && oRequest is IRequest req) { var info = req.GetHeader("X-Desktop-Info"); if (info != null) NativeWin.SetDesktopInfo(info.FromJsv<Dictionary<string, string>>()); var handle = req.GetHeader("X-Window-Handle"); if (handle != null && long.TryParse(handle, out var lHandle)) return (IntPtr)lHandle; } return IntPtr.Zero; } }
DesktopConfig
csharp
dotnet__efcore
src/EFCore.Relational/Query/RelationalQueryableMethodTranslatingExpressionVisitor.cs
{ "start": 54696, "end": 69380 }
private sealed class ____ : ExpressionVisitor { private ParameterExpression? _outerParameter; private bool _correlated; private bool _defaultIfEmpty; private bool _canLiftDefaultIfEmpty; public (LambdaExpression, bool, bool) IsCorrelated(LambdaExpression lambdaExpression) { Check.DebugAssert( lambdaExpression.Parameters.Count == 1, "Multi-parameter lambda passed to CorrelationFindingExpressionVisitor"); _correlated = false; _defaultIfEmpty = false; _canLiftDefaultIfEmpty = true; _outerParameter = lambdaExpression.Parameters[0]; var result = Visit(lambdaExpression.Body); return (Expression.Lambda(result, _outerParameter), _correlated, _defaultIfEmpty); } protected override Expression VisitParameter(ParameterExpression parameterExpression) { if (parameterExpression == _outerParameter) { _correlated = true; } return base.VisitParameter(parameterExpression); } protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression) { if (_canLiftDefaultIfEmpty && methodCallExpression.Method.IsGenericMethod && methodCallExpression.Method.GetGenericMethodDefinition() == QueryableMethods.DefaultIfEmptyWithoutArgument) { _defaultIfEmpty = true; return Expression.Call( _fakeDefaultIfEmptyMethodInfo.Value.MakeGenericMethod(methodCallExpression.Method.GetGenericArguments()[0]), Visit(methodCallExpression.Arguments[0])); } if (!SupportsLiftingDefaultIfEmpty(methodCallExpression.Method)) { // Set state to indicate that any DefaultIfEmpty encountered below this operator cannot be lifted out, since // doing so would change meaning. // For example, with blogs.SelectMany(b => b.Posts.DefaultIfEmpty().Select(p => p.Id)) we can lift // the DIE out, translating the SelectMany as a LEFT JOIN (or OUTER APPLY). // But with blogs.SelectMany(b => b.Posts.DefaultIfEmpty().Where(p => p.Id > 3)), we can't do that since that // what result in different results. _canLiftDefaultIfEmpty = false; } if (methodCallExpression.Arguments.Count == 0) { return base.VisitMethodCall(methodCallExpression); } // We need to visit the method call as usual, but the first argument - the source (other operators we're composed over) - // needs to be handled differently. For the purpose of lifting DefaultIfEmpty, we can only do so for DIE at the top-level // operator chain, and not some DIE embedded in e.g. the lambda argument of a Where clause. So we visit the source first, // and then set _canLiftDefaultIfEmpty to false to avoid lifting any DIEs encountered there (see e.g. #33343). // Note: we assume that the first argument is the source. var newObject = Visit(methodCallExpression.Object); var arguments = methodCallExpression.Arguments; Expression[]? newArguments = null; var newSource = Visit(arguments[0]); if (!ReferenceEquals(newSource, arguments[0])) { newArguments = new Expression[arguments.Count]; newArguments[0] = newSource; } var previousCanLiftDefaultIfEmpty = _canLiftDefaultIfEmpty; _canLiftDefaultIfEmpty = false; for (var i = 1; i < arguments.Count; i++) { var newArgument = Visit(arguments[i]); if (newArguments is not null) { newArguments[i] = newArgument; } else if (!ReferenceEquals(newArgument, arguments[i])) { newArguments = new Expression[arguments.Count]; newArguments[0] = newSource; for (var j = 1; j < i; j++) { newArguments[j] = arguments[j]; } newArguments[i] = newArgument; } } _canLiftDefaultIfEmpty = previousCanLiftDefaultIfEmpty; return methodCallExpression.Update(newObject, newArguments ?? (IEnumerable<Expression>)arguments); static bool SupportsLiftingDefaultIfEmpty(MethodInfo methodInfo) => methodInfo.IsGenericMethod && methodInfo.GetGenericMethodDefinition() is var definition && (definition == QueryableMethods.Select || definition == QueryableMethods.OrderBy || definition == QueryableMethods.OrderByDescending || definition == QueryableMethods.Reverse); } } /// <inheritdoc /> protected override ShapedQueryExpression? TranslateSelectMany(ShapedQueryExpression source, LambdaExpression selector) { var innerParameter = Expression.Parameter(selector.ReturnType.GetSequenceType(), "i"); var resultSelector = Expression.Lambda( innerParameter, Expression.Parameter(source.Type.GetSequenceType()), innerParameter); return TranslateSelectMany(source, selector, resultSelector); } /// <inheritdoc /> protected override ShapedQueryExpression? TranslateSingleOrDefault( ShapedQueryExpression source, LambdaExpression? predicate, Type returnType, bool returnDefault) { if (predicate != null) { var translatedSource = TranslateWhere(source, predicate); if (translatedSource == null) { return null; } source = translatedSource; } var selectExpression = (SelectExpression)source.QueryExpression; ApplyLimit(selectExpression, TranslateExpression(Expression.Constant(_subquery ? 1 : 2))!); return source.ShaperExpression.Type != returnType ? source.UpdateShaperExpression(Expression.Convert(source.ShaperExpression, returnType)) : source; } /// <inheritdoc /> protected override ShapedQueryExpression? TranslateSkip(ShapedQueryExpression source, Expression count) { var selectExpression = (SelectExpression)source.QueryExpression; var translation = TranslateExpression(count); if (translation == null) { return null; } if (!IsOrdered(selectExpression)) { _queryCompilationContext.Logger.RowLimitingOperationWithoutOrderByWarning(); } selectExpression.ApplyOffset(translation); return source; } /// <inheritdoc /> protected override ShapedQueryExpression? TranslateSkipWhile(ShapedQueryExpression source, LambdaExpression predicate) => null; /// <inheritdoc /> protected override ShapedQueryExpression? TranslateSum(ShapedQueryExpression source, LambdaExpression? selector, Type resultType) => TranslateAggregateWithSelector(source, selector, QueryableMethods.GetSumWithoutSelector, resultType); /// <inheritdoc /> protected override ShapedQueryExpression? TranslateTake(ShapedQueryExpression source, Expression count) { var selectExpression = (SelectExpression)source.QueryExpression; var translation = TranslateExpression(count); if (translation == null) { return null; } if (!IsOrdered(selectExpression)) { _queryCompilationContext.Logger.RowLimitingOperationWithoutOrderByWarning(); } ApplyLimit(selectExpression, translation); return source; } private void ApplyLimit(SelectExpression selectExpression, SqlExpression limit) { var oldLimit = selectExpression.Limit; if (oldLimit is null) { selectExpression.SetLimit(limit); return; } if (oldLimit is SqlConstantExpression { Value: int oldConst } && limit is SqlConstantExpression { Value: int newConst }) { // if both the old and new limit are constants, use the smaller one // (aka constant-fold LEAST(constA, constB)) if (oldConst > newConst) { selectExpression.SetLimit(limit); } return; } if (oldLimit.Equals(limit)) { return; } // if possible, use LEAST(oldLimit, limit); otherwise, use nested queries if (_sqlTranslator.GenerateLeast([oldLimit, limit], limit.Type) is { } newLimit) { selectExpression.SetLimit(newLimit); } else { selectExpression.ApplyLimit(limit); } } /// <inheritdoc /> protected override ShapedQueryExpression? TranslateTakeWhile(ShapedQueryExpression source, LambdaExpression predicate) => null; /// <inheritdoc /> protected override ShapedQueryExpression? TranslateThenBy( ShapedQueryExpression source, LambdaExpression keySelector, bool ascending) { var translation = TranslateLambdaExpression(source, keySelector); if (translation == null) { return null; } ((SelectExpression)source.QueryExpression).AppendOrdering(new OrderingExpression(translation, ascending)); return source; } /// <inheritdoc /> protected override ShapedQueryExpression TranslateUnion(ShapedQueryExpression source1, ShapedQueryExpression source2) { ((SelectExpression)source1.QueryExpression).ApplyUnion((SelectExpression)source2.QueryExpression, distinct: true); return source1.UpdateShaperExpression( MatchShaperNullabilityForSetOperation(source1.ShaperExpression, source2.ShaperExpression, makeNullable: true)); } /// <inheritdoc /> protected override ShapedQueryExpression? TranslateWhere(ShapedQueryExpression source, LambdaExpression predicate) { var translation = TranslateLambdaExpression(source, predicate); if (translation == null) { return null; } ((SelectExpression)source.QueryExpression).ApplyPredicate(translation); return source; } /// <summary> /// Translates the given expression into equivalent SQL representation. /// </summary> /// <param name="expression">An expression to translate.</param> /// <param name="applyDefaultTypeMapping"> /// Whether to apply the default type mapping on the top-most element if it has none. Defaults to <see langword="true" />. /// </param> /// <returns>A <see cref="SqlExpression" /> which is translation of given expression or <see langword="null" />.</returns> protected virtual SqlExpression? TranslateExpression(Expression expression, bool applyDefaultTypeMapping = true) { var translation = _sqlTranslator.Translate(expression, applyDefaultTypeMapping); if (translation is null) { if (_sqlTranslator.TranslationErrorDetails != null) { AddTranslationErrorDetails(_sqlTranslator.TranslationErrorDetails); } } return translation; } private Expression? TranslateProjection(Expression expression, bool applyDefaultTypeMapping = true) { var translation = _sqlTranslator.TranslateProjection(expression, applyDefaultTypeMapping); if (translation is null) { if (_sqlTranslator.TranslationErrorDetails != null) { AddTranslationErrorDetails(_sqlTranslator.TranslationErrorDetails); } } return translation; } /// <summary> /// Translates the given lambda expression for the <see cref="ShapedQueryExpression" /> source into equivalent SQL representation. /// </summary> /// <param name="shapedQueryExpression">A <see cref="ShapedQueryExpression" /> on which the lambda expression is being applied.</param> /// <param name="lambdaExpression">A <see cref="LambdaExpression" /> to translate into SQL.</param> /// <returns>A <see cref="SqlExpression" /> which is translation of given lambda expression or <see langword="null" />.</returns> protected virtual SqlExpression? TranslateLambdaExpression( ShapedQueryExpression shapedQueryExpression, LambdaExpression lambdaExpression) => TranslateExpression(RemapLambdaBody(shapedQueryExpression, lambdaExpression)); /// <summary> /// Determines whether the given <see cref="SelectExpression" /> is ordered, typically because orderings have been added to it. /// </summary> /// <param name="selectExpression">The <see cref="SelectExpression" /> to check for ordering.</param> /// <returns>Whether <paramref name="selectExpression" /> is ordered.</returns> protected virtual bool IsOrdered(SelectExpression selectExpression) => selectExpression.Orderings.Count > 0; /// <summary> /// Determines whether the given <see cref="SelectExpression" /> is naturally ordered, meaning that any ordering has been added /// automatically by EF to preserve e.g. the natural ordering of a JSON array, and not because the original LINQ query contained /// an explicit ordering. /// </summary> /// <param name="selectExpression">The <see cref="SelectExpression" /> to check for ordering.</param> /// <returns>Whether <paramref name="selectExpression" /> is ordered.</returns> protected virtual bool IsNaturallyOrdered(SelectExpression selectExpression) => false; private Expression RemapLambdaBody(ShapedQueryExpression shapedQueryExpression, LambdaExpression lambdaExpression) { var lambdaBody = ReplacingExpressionVisitor.Replace( lambdaExpression.Parameters.Single(), shapedQueryExpression.ShaperExpression, lambdaExpression.Body); return ExpandSharedTypeEntities((SelectExpression)shapedQueryExpression.QueryExpression, lambdaBody); } private Expression ExpandSharedTypeEntities(SelectExpression selectExpression, Expression lambdaBody) => _sharedTypeEntityExpandingExpressionVisitor.Expand(selectExpression, lambdaBody);
CorrelationFindingExpressionVisitor
csharp
microsoft__PowerToys
src/modules/launcher/Plugins/Community.PowerToys.Run.Plugin.VSCodeWorkspaces/SshConfigParser/SshHost.cs
{ "start": 300, "end": 1640 }
public class ____ { public string IdentityFile { get => this[nameof(IdentityFile)]?.ToString(); set => this[nameof(IdentityFile)] = value; } public string Host { get => this[nameof(Host)]?.ToString(); set => this[nameof(Host)] = value; } public string HostName { get => this[nameof(HostName)]?.ToString(); set => this[nameof(HostName)] = value; } public string User { get => this[nameof(User)]?.ToString(); set => this[nameof(User)] = value; } public string ForwardAgent { get => this[nameof(ForwardAgent)]?.ToString(); set => this[nameof(ForwardAgent)] = value; } internal Dictionary<string, object> Properties { get; } = new Dictionary<string, object>(); public object this[string key] { get { if (Properties.TryGetValue(key, out var value)) { return value; } return null; } set { Properties[key] = value; } } public IEnumerable<string> Keys => Properties.Keys; } }
SshHost
csharp
CommunityToolkit__WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.SampleApp/SamplePages/Shadows/AttachedDropShadowPage.xaml.cs
{ "start": 333, "end": 1022 }
partial class ____ : IXamlRenderListener { public AttachedDropShadowPage() { InitializeComponent(); } public void OnXamlRendered(FrameworkElement control) { // This is done as we don't have x:Bind in live xaml, so we find and attach after. var castToTarget = control.FindChild("ShadowTarget"); if (castToTarget != null) { if (control.Resources.TryGetValue("CommonShadow", out var resource) && resource is AttachedDropShadow shadow) { shadow.CastTo = castToTarget; } } } } }
AttachedDropShadowPage
csharp
AutoMapper__AutoMapper
src/UnitTests/MappingInheritance/IgnoreShouldBeInherited.cs
{ "start": 2882, "end": 2993 }
class ____ { public string FooText { get; set; } public string Text { get; set; } }
Foo
csharp
PrismLibrary__Prism
src/Maui/Prism.Maui/Navigation/Regions/AllActiveRegion.cs
{ "start": 183, "end": 1255 }
public class ____ : Region { /// <summary> /// Creates a new <see cref="AllActiveRegion"/>. /// </summary> /// <param name="regionNavigationService"></param> public AllActiveRegion(IRegionNavigationService regionNavigationService) : base(regionNavigationService) { } /// <summary> /// Gets a readonly view of the collection of all the active views in the region. These are all the added views. /// </summary> /// <value>An <see cref="IViewsCollection"/> of all the active views.</value> public override IViewsCollection ActiveViews => Views; /// <summary> /// Deactivate is not valid in this Region. This method will always throw <see cref="InvalidOperationException"/>. /// </summary> /// <param name="view">The view to deactivate.</param> /// <exception cref="InvalidOperationException">Every time this method is called.</exception> public override void Deactivate(object view) { throw new InvalidOperationException(Resources.DeactiveNotPossibleException); } }
AllActiveRegion
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.UI.Core.Preview/SystemNavigationManagerPreview.cs
{ "start": 258, "end": 1848 }
public partial class ____ { // Forced skipping of method Windows.UI.Core.Preview.SystemNavigationManagerPreview.CloseRequested.add // Forced skipping of method Windows.UI.Core.Preview.SystemNavigationManagerPreview.CloseRequested.remove // Skipping already declared method Windows.UI.Core.Preview.SystemNavigationManagerPreview.GetForCurrentView() #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public event global::System.EventHandler<global::Windows.UI.Core.Preview.SystemNavigationCloseRequestedPreviewEventArgs> CloseRequested { [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] add { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Core.Preview.SystemNavigationManagerPreview", "event EventHandler<SystemNavigationCloseRequestedPreviewEventArgs> SystemNavigationManagerPreview.CloseRequested"); } [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] remove { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Core.Preview.SystemNavigationManagerPreview", "event EventHandler<SystemNavigationCloseRequestedPreviewEventArgs> SystemNavigationManagerPreview.CloseRequested"); } } #endif } }
SystemNavigationManagerPreview
csharp
dotnet__machinelearning
src/Microsoft.ML.Data/Commands/TrainTestCommand.cs
{ "start": 802, "end": 13054 }
public sealed class ____ : DataCommand.ArgumentsBase { [Argument(ArgumentType.AtMostOnce, IsInputFileName = true, HelpText = "The test data file", ShortName = "test", SortOrder = 1)] public string TestFile; [Argument(ArgumentType.Multiple, HelpText = "Trainer to use", ShortName = "tr", SignatureType = typeof(SignatureTrainer))] public IComponentFactory<ITrainer> Trainer; [Argument(ArgumentType.Multiple, HelpText = "Scorer to use", NullName = "<Auto>", SortOrder = 101, SignatureType = typeof(SignatureDataScorer))] public IComponentFactory<IDataView, ISchemaBoundMapper, RoleMappedSchema, IDataScorerTransform> Scorer; [Argument(ArgumentType.Multiple, HelpText = "Evaluator to use", ShortName = "eval", NullName = "<Auto>", SortOrder = 102, SignatureType = typeof(SignatureMamlEvaluator))] public IComponentFactory<IMamlEvaluator> Evaluator; [Argument(ArgumentType.AtMostOnce, HelpText = "Results summary filename", ShortName = "sf")] public string SummaryFilename; [Argument(ArgumentType.LastOccurrenceWins, HelpText = "Column to use for features", ShortName = "feat", SortOrder = 2)] public string FeatureColumn = DefaultColumnNames.Features; [Argument(ArgumentType.LastOccurrenceWins, HelpText = "Column to use for labels", ShortName = "lab", SortOrder = 3)] public string LabelColumn = DefaultColumnNames.Label; [Argument(ArgumentType.LastOccurrenceWins, HelpText = "Column to use for example weight", ShortName = "weight", SortOrder = 4)] public string WeightColumn = DefaultColumnNames.Weight; [Argument(ArgumentType.LastOccurrenceWins, HelpText = "Column to use for grouping", ShortName = "group", SortOrder = 5)] public string GroupColumn = DefaultColumnNames.GroupId; [Argument(ArgumentType.AtMostOnce, HelpText = "Name column name", ShortName = "name", SortOrder = 6)] public string NameColumn = DefaultColumnNames.Name; [Argument(ArgumentType.LastOccurrenceWins, HelpText = "Columns with custom kinds declared through key assignments, for example, col[Kind]=Name to assign column named 'Name' kind 'Kind'", Name = "CustomColumn", ShortName = "col", SortOrder = 10)] public KeyValuePair<string, string>[] CustomColumns; [Argument(ArgumentType.LastOccurrenceWins, HelpText = "Normalize option for the feature column", ShortName = "norm")] public NormalizeOption NormalizeFeatures = NormalizeOption.Auto; [Argument(ArgumentType.AtMostOnce, IsInputFileName = true, HelpText = "The validation data file", ShortName = "valid")] public string ValidationFile; [Argument(ArgumentType.LastOccurrenceWins, HelpText = "Whether we should cache input training data", ShortName = "cache")] public bool? CacheData; [Argument(ArgumentType.Multiple, HelpText = "Output calibrator", ShortName = "cali", NullName = "<None>", SignatureType = typeof(SignatureCalibrator))] public IComponentFactory<ICalibratorTrainer> Calibrator = new PlattCalibratorTrainerFactory(); [Argument(ArgumentType.LastOccurrenceWins, HelpText = "Number of instances to train the calibrator", ShortName = "numcali")] public int MaxCalibrationExamples = 1000000000; [Argument(ArgumentType.AtMostOnce, HelpText = "File to save per-instance predictions and metrics to", ShortName = "dout")] public string OutputDataFile; [Argument(ArgumentType.LastOccurrenceWins, HelpText = "Whether we should load predictor from input model and use it as the initial model state", ShortName = "cont")] public bool ContinueTrain; } internal const string Summary = "Trains a predictor using the train file and then scores and evaluates the predictor using the test file."; public const string LoadName = "TrainTest"; public TrainTestCommand(IHostEnvironment env, Arguments args) : base(env, args, nameof(TrainTestCommand)) { Utils.CheckOptionalUserDirectory(args.SummaryFilename, nameof(args.SummaryFilename)); Utils.CheckOptionalUserDirectory(args.OutputDataFile, nameof(args.OutputDataFile)); TrainUtils.CheckTrainer(Host, args.Trainer, args.DataFile); if (string.IsNullOrWhiteSpace(args.TestFile)) throw Host.ExceptUserArg(nameof(args.TestFile), "Test file must be defined."); } public override void Run() { using (var ch = Host.Start(LoadName)) using (var server = InitServer(ch)) { var settings = CmdParser.GetSettings(Host, ImplOptions, new Arguments()); string cmd = string.Format("maml.exe {0} {1}", LoadName, settings); ch.Info(cmd); SendTelemetry(Host); using (new TimerScope(Host, ch)) { RunCore(ch, cmd); } } } protected override void SendTelemetryCore(IPipe<TelemetryMessage> pipe) { SendTelemetryComponent(pipe, ImplOptions.Trainer); base.SendTelemetryCore(pipe); } private void RunCore(IChannel ch, string cmd) { Host.AssertValue(ch); Host.AssertNonEmpty(cmd); ch.Trace("Constructing trainer"); ITrainer trainer = ImplOptions.Trainer.CreateComponent(Host); IPredictor inputPredictor = null; if (ImplOptions.ContinueTrain && !TrainUtils.TryLoadPredictor(ch, Host, ImplOptions.InputModelFile, out inputPredictor)) ch.Warning("No input model file specified or model file did not contain a predictor. The model state cannot be initialized."); ch.Trace("Constructing the training pipeline"); IDataView trainPipe = CreateLoader(); var schema = trainPipe.Schema; string label = TrainUtils.MatchNameOrDefaultOrNull(ch, schema, nameof(Arguments.LabelColumn), ImplOptions.LabelColumn, DefaultColumnNames.Label); string features = TrainUtils.MatchNameOrDefaultOrNull(ch, schema, nameof(Arguments.FeatureColumn), ImplOptions.FeatureColumn, DefaultColumnNames.Features); string group = TrainUtils.MatchNameOrDefaultOrNull(ch, schema, nameof(Arguments.GroupColumn), ImplOptions.GroupColumn, DefaultColumnNames.GroupId); string weight = TrainUtils.MatchNameOrDefaultOrNull(ch, schema, nameof(Arguments.WeightColumn), ImplOptions.WeightColumn, DefaultColumnNames.Weight); string name = TrainUtils.MatchNameOrDefaultOrNull(ch, schema, nameof(Arguments.NameColumn), ImplOptions.NameColumn, DefaultColumnNames.Name); TrainUtils.AddNormalizerIfNeeded(Host, ch, trainer, ref trainPipe, features, ImplOptions.NormalizeFeatures); ch.Trace("Binding columns"); var customCols = TrainUtils.CheckAndGenerateCustomColumns(ch, ImplOptions.CustomColumns); var data = new RoleMappedData(trainPipe, label, features, group, weight, name, customCols); RoleMappedData validData = null; if (!string.IsNullOrWhiteSpace(ImplOptions.ValidationFile)) { if (!trainer.Info.SupportsValidation) { ch.Warning("Ignoring validationFile: Trainer does not accept validation dataset."); } else { ch.Trace("Constructing the validation pipeline"); IDataView validPipe = CreateRawLoader(dataFile: ImplOptions.ValidationFile); validPipe = ApplyTransformUtils.ApplyAllTransformsToData(Host, trainPipe, validPipe); validData = new RoleMappedData(validPipe, data.Schema.GetColumnRoleNames()); } } // In addition to the training set, some trainers can accept two data sets, validation set and test set, // in training phase. The major difference between validation set and test set is that training process may // indirectly use validation set to improve the model but the learned model should totally independent of test set. // Similar to validation set, the trainer can report the scores computed using test set. RoleMappedData testDataUsedInTrainer = null; if (!string.IsNullOrWhiteSpace(ImplOptions.TestFile)) { // In contrast to the if-else block for validation above, we do not throw a warning if test file is provided // because this is TrainTest command. if (trainer.Info.SupportsTest) { ch.Trace("Constructing the test pipeline"); IDataView testPipeUsedInTrainer = CreateRawLoader(dataFile: ImplOptions.TestFile); testPipeUsedInTrainer = ApplyTransformUtils.ApplyAllTransformsToData(Host, trainPipe, testPipeUsedInTrainer); testDataUsedInTrainer = new RoleMappedData(testPipeUsedInTrainer, data.Schema.GetColumnRoleNames()); } } var predictor = TrainUtils.Train(Host, ch, data, trainer, validData, ImplOptions.Calibrator, ImplOptions.MaxCalibrationExamples, ImplOptions.CacheData, inputPredictor, testDataUsedInTrainer); ILegacyDataLoader testPipe; bool hasOutfile = !string.IsNullOrEmpty(ImplOptions.OutputModelFile); var tempFilePath = hasOutfile ? null : Path.Combine(((IHostEnvironmentInternal)Host).TempFilePath, Path.GetRandomFileName()); using (var file = new SimpleFileHandle(ch, hasOutfile ? ImplOptions.OutputModelFile : tempFilePath, true, !hasOutfile)) { TrainUtils.SaveModel(Host, ch, file, predictor, data, cmd); ch.Trace("Constructing the testing pipeline"); using (var stream = file.OpenReadStream()) using (var rep = RepositoryReader.Open(stream, ch)) testPipe = LoadLoader(rep, ImplOptions.TestFile, true); } // Score. ch.Trace("Scoring and evaluating"); ch.Assert(ImplOptions.Scorer == null || ImplOptions.Scorer is ICommandLineComponentFactory, "TrainTestCommand should only be used from the command line."); IDataScorerTransform scorePipe = ScoreUtils.GetScorer(ImplOptions.Scorer, predictor, testPipe, features, group, customCols, Host, data.Schema); // Evaluate. var evaluator = ImplOptions.Evaluator?.CreateComponent(Host) ?? EvaluateUtils.GetEvaluator(Host, scorePipe.Schema); var dataEval = new RoleMappedData(scorePipe, label, features, group, weight, name, customCols, opt: true); var metrics = evaluator.Evaluate(dataEval); MetricWriter.PrintWarnings(ch, metrics); evaluator.PrintFoldResults(ch, metrics); if (!metrics.TryGetValue(MetricKinds.OverallMetrics, out var overall)) throw ch.Except("No overall metrics found"); overall = evaluator.GetOverallResults(overall); MetricWriter.PrintOverallMetrics(Host, ch, ImplOptions.SummaryFilename, overall, 1); evaluator.PrintAdditionalMetrics(ch, metrics); Dictionary<string, IDataView>[] metricValues = { metrics }; SendTelemetryMetric(metricValues); if (!string.IsNullOrWhiteSpace(ImplOptions.OutputDataFile)) { var perInst = evaluator.GetPerInstanceMetrics(dataEval); var perInstData = new RoleMappedData(perInst, label, null, group, weight, name, customCols); var idv = evaluator.GetPerInstanceDataViewToSave(perInstData); MetricWriter.SavePerInstance(Host, ch, ImplOptions.OutputDataFile, idv); } } } }
Arguments
csharp
Cysharp__UniTask
src/UniTask.NetCoreTests/WhenEachTest.cs
{ "start": 215, "end": 1780 }
public class ____ { [Fact] public async Task Each() { var a = Delay(1, 3000); var b = Delay(2, 1000); var c = Delay(3, 2000); var l = new List<int>(); await foreach (var item in UniTask.WhenEach(a, b, c)) { l.Add(item.Result); } l.Should().Equal(2, 3, 1); } [Fact] public async Task Error() { var a = Delay2(1, 3000); var b = Delay2(2, 1000); var c = Delay2(3, 2000); var l = new List<WhenEachResult<int>>(); await foreach (var item in UniTask.WhenEach(a, b, c)) { l.Add(item); } l[0].IsCompletedSuccessfully.Should().BeTrue(); l[0].IsFaulted.Should().BeFalse(); l[0].Result.Should().Be(2); l[1].IsCompletedSuccessfully.Should().BeFalse(); l[1].IsFaulted.Should().BeTrue(); l[1].Exception.Message.Should().Be("ERROR"); l[2].IsCompletedSuccessfully.Should().BeTrue(); l[2].IsFaulted.Should().BeFalse(); l[2].Result.Should().Be(1); } async UniTask<int> Delay(int id, int sleep) { await Task.Delay(sleep); return id; } async UniTask<int> Delay2(int id, int sleep) { await Task.Delay(sleep); if (id == 3) throw new Exception("ERROR"); return id; } } }
WhenEachTest
csharp
smartstore__Smartstore
src/Smartstore.Core/Platform/Security/Configuration/CaptchaSettings.cs
{ "start": 1941, "end": 5117 }
public static class ____ { public const string Login = "Login"; public const string Registration = "Registration"; public const string PasswordRecovery = "PasswordRecovery"; public const string ContactUs = "ContactUs"; public const string ShareWishlist = "ShareWishlist"; public const string ShareProduct = "ShareProduct"; public const string ProductInquiry = "ProductInquiry"; public const string BlogComment = "BlogComment"; public const string NewsComment = "NewsComment"; public const string Forum = "Forum"; public const string ProductReview = "ProductReview"; public static readonly IReadOnlyList<string> All = [ Login, Registration, PasswordRecovery, ContactUs, ShareWishlist, ShareProduct, ProductInquiry, BlogComment, NewsComment, Forum, ProductReview ]; public static IDictionary<string, string> GetLegacySettingNames() { return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { [nameof(ShowOnLoginPage)] = Login, [nameof(ShowOnRegistrationPage)] = Registration, [nameof(ShowOnPasswordRecoveryPage)] = PasswordRecovery, [nameof(ShowOnContactUsPage)] = ContactUs, [nameof(ShowOnEmailWishlistToFriendPage)] = ShareWishlist, [nameof(ShowOnEmailProductToFriendPage)] = ShareProduct, [nameof(ShowOnAskQuestionPage)] = ProductInquiry, [nameof(ShowOnBlogCommentPage)] = BlogComment, [nameof(ShowOnNewsCommentPage)] = NewsComment, [nameof(ShowOnForumPage)] = Forum, [nameof(ShowOnProductReviewPage)] = ProductReview }; } const string ResPrefix = "Admin.Configuration.Settings.GeneralCommon.CaptchaShowOnTargets.Option."; public static IDictionary<string, string> GetDisplayResourceKeys() { return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { [Login] = ResPrefix + "Login", [Registration] = ResPrefix + "Registration", [PasswordRecovery] = ResPrefix + "PasswordRecovery", [ContactUs] = ResPrefix + "ContactUs", [ShareWishlist] = ResPrefix + "ShareWishlist", [ShareProduct] = ResPrefix + "ShareProduct", [ProductInquiry] = ResPrefix + "ProductInquiry", [BlogComment] = ResPrefix + "BlogComment", [NewsComment] = ResPrefix + "NewsComment", [Forum] = ResPrefix + "Forum", [ProductReview] = ResPrefix + "ProductReview" }; } } #endregion } }
Targets
csharp
ChilliCream__graphql-platform
src/HotChocolate/Fusion-vnext/test/Fusion.AspNetCore.Tests/ConditionalTests.cs
{ "start": 36078, "end": 36447 }
interface ____ { id: ID! } type Discussion implements Node { id: ID! title: String } """); using var server2 = CreateSourceSchema( "B", """ type Query { node(id: ID!): Node @lookup @shareable }
Node
csharp
dotnet__aspnetcore
src/Mvc/Mvc.TagHelpers/src/Cache/DistributedCacheTagHelperStorage.cs
{ "start": 416, "end": 1363 }
public class ____ : IDistributedCacheTagHelperStorage { private readonly IDistributedCache _distributedCache; /// <summary> /// Creates a new <see cref="DistributedCacheTagHelperStorage"/>. /// </summary> /// <param name="distributedCache">The <see cref="IDistributedCache"/> to use.</param> public DistributedCacheTagHelperStorage(IDistributedCache distributedCache) { _distributedCache = distributedCache; } /// <inheritdoc /> public Task<byte[]> GetAsync(string key) { ArgumentNullException.ThrowIfNull(key); return _distributedCache.GetAsync(key); } /// <inheritdoc /> public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options) { ArgumentNullException.ThrowIfNull(key); ArgumentNullException.ThrowIfNull(value); return _distributedCache.SetAsync(key, value, options); } }
DistributedCacheTagHelperStorage
csharp
AutoMapper__AutoMapper
src/UnitTests/ConfigurationFeatureTest.cs
{ "start": 3191, "end": 3627 }
public abstract class ____ : IGlobalFeature { public int Value { get; } public List<IConfigurationProvider> ConfigurationProviders { get; } = new List<IConfigurationProvider>(); protected ConfigurationExpressionFeatureBase(int value) { Value = value; } public abstract void Configure(IGlobalConfiguration configurationProvider); }
ConfigurationExpressionFeatureBase
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/test/Execution.Tests/Processing/VariableCoercionHelperTests.cs
{ "start": 232, "end": 22173 }
public class ____ { [Fact] public void VariableCoercionHelper_Schema_Is_Null() { // arrange var variableDefinitions = new List<VariableDefinitionNode> { new(null, new VariableNode("abc"), description: null, new NamedTypeNode("String"), new StringValueNode("def"), Array.Empty<DirectiveNode>()) }; var variableValues = new Dictionary<string, object?>(); var coercedValues = new Dictionary<string, VariableValueOrLiteral>(); var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); // act void Action() => helper.CoerceVariableValues( null!, variableDefinitions, variableValues, coercedValues); // assert Assert.Throws<ArgumentNullException>(Action); } [Fact] public void VariableCoercionHelper_VariableDefinitions_Is_Null() { // arrange var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); var variableValues = new Dictionary<string, object?>(); var coercedValues = new Dictionary<string, VariableValueOrLiteral>(); var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); // act void Action() => helper.CoerceVariableValues(schema, null!, variableValues, coercedValues); // assert Assert.Throws<ArgumentNullException>(Action); } [Fact] public void VariableCoercionHelper_VariableValues_Is_Null() { // arrange var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); var variableDefinitions = new List<VariableDefinitionNode> { new VariableDefinitionNode( null, new VariableNode("abc"), description: null, new NamedTypeNode("String"), new StringValueNode("def"), Array.Empty<DirectiveNode>()) }; var coercedValues = new Dictionary<string, VariableValueOrLiteral>(); var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); // act void Action() => helper.CoerceVariableValues( schema, variableDefinitions, null!, coercedValues); // assert Assert.Throws<ArgumentNullException>(Action); } [Fact] public void VariableCoercionHelper_CoercedValues_Is_Null() { // arrange var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); var variableDefinitions = new List<VariableDefinitionNode> { new VariableDefinitionNode( null, new VariableNode("abc"), description: null, new NamedTypeNode("String"), new StringValueNode("def"), Array.Empty<DirectiveNode>()) }; var variableValues = new Dictionary<string, object?>(); var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); // act void Action() => helper.CoerceVariableValues( schema, variableDefinitions, variableValues, null!); // assert Assert.Throws<ArgumentNullException>(Action); } [Fact] public void Coerce_Nullable_String_Variable_With_Default_Where_Value_Is_Not_Provided() { // arrange var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); var variableDefinitions = new List<VariableDefinitionNode> { new VariableDefinitionNode( null, new VariableNode("abc"), description: null, new NamedTypeNode("String"), new StringValueNode("def"), Array.Empty<DirectiveNode>()) }; var variableValues = new Dictionary<string, object?>(); var coercedValues = new Dictionary<string, VariableValueOrLiteral>(); var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); // act helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); // assert Assert.Collection(coercedValues, t => { Assert.Equal("abc", t.Key); Assert.Equal("String", Assert.IsType<StringType>(t.Value.Type).Name); Assert.Equal("def", t.Value.Value); Assert.Equal("def", Assert.IsType<StringValueNode>(t.Value.ValueLiteral).Value); }); } [Fact] public void Coerce_Nullable_String_Variable_Where_Value_Is_Not_Provided() { // arrange var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); var variableDefinitions = new List<VariableDefinitionNode> { new VariableDefinitionNode( null, new VariableNode("abc"), description: null, new NamedTypeNode("String"), null, Array.Empty<DirectiveNode>()) }; var variableValues = new Dictionary<string, object?>(); var coercedValues = new Dictionary<string, VariableValueOrLiteral>(); var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); // act helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); // assert Assert.Empty(coercedValues); } [Fact] public void Coerce_Nullable_String_Variable_With_Default_Where_Value_Is_Provided() { // arrange var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); var variableDefinitions = new List<VariableDefinitionNode> { new VariableDefinitionNode( null, new VariableNode("abc"), description: null, new NamedTypeNode("String"), new StringValueNode("def"), Array.Empty<DirectiveNode>()) }; var variableValues = new Dictionary<string, object?> { {"abc", new StringValueNode("xyz")} }; var coercedValues = new Dictionary<string, VariableValueOrLiteral>(); var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); // act helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); // assert Assert.Collection(coercedValues, t => { Assert.Equal("abc", t.Key); Assert.Equal("String", Assert.IsType<StringType>(t.Value.Type).Name); Assert.Equal("xyz", t.Value.Value); Assert.Equal("xyz", Assert.IsType<StringValueNode>(t.Value.ValueLiteral).Value); }); } [Fact] public void Coerce_Nullable_String_Variable_With_Default_Where_Plain_Value_Is_Provided() { // arrange var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); var variableDefinitions = new List<VariableDefinitionNode> { new VariableDefinitionNode( null, new VariableNode("abc"), description: null, new NamedTypeNode("String"), new StringValueNode("def"), Array.Empty<DirectiveNode>()) }; var variableValues = new Dictionary<string, object?> { {"abc", "xyz"} }; var coercedValues = new Dictionary<string, VariableValueOrLiteral>(); var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); // act helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); // assert Assert.Collection(coercedValues, t => { Assert.Equal("abc", t.Key); Assert.Equal("String", Assert.IsType<StringType>(t.Value.Type).Name); Assert.Equal("xyz", t.Value.Value); t.Value.ValueLiteral.ToString().MatchSnapshot(); }); } [Fact] public void Coerce_Nullable_String_Variable_With_Default_Where_Null_Is_Provided() { // arrange var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); var variableDefinitions = new List<VariableDefinitionNode> { new VariableDefinitionNode( null, new VariableNode("abc"), description: null, new NamedTypeNode("String"), new StringValueNode("def"), Array.Empty<DirectiveNode>()) }; var variableValues = new Dictionary<string, object?> { {"abc", NullValueNode.Default} }; var coercedValues = new Dictionary<string, VariableValueOrLiteral>(); var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); // act helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); // assert Assert.Collection(coercedValues, t => { Assert.Equal("abc", t.Key); Assert.Equal("String", Assert.IsType<StringType>(t.Value.Type).Name); Assert.Null(t.Value.Value); Assert.IsType<NullValueNode>(t.Value.ValueLiteral); }); } [Fact] public void Coerce_Nullable_String_Variable_With_Default_Where_Plain_Null_Is_Provided() { // arrange var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); var variableDefinitions = new List<VariableDefinitionNode> { new VariableDefinitionNode( null, new VariableNode("abc"), description: null, new NamedTypeNode("String"), new StringValueNode("def"), Array.Empty<DirectiveNode>()) }; var variableValues = new Dictionary<string, object?> { {"abc", null} }; var coercedValues = new Dictionary<string, VariableValueOrLiteral>(); var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); // act helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); // assert Assert.Collection(coercedValues, t => { Assert.Equal("abc", t.Key); Assert.Equal("String", Assert.IsType<StringType>(t.Value.Type).Name); Assert.Null(t.Value.Value); Assert.IsType<NullValueNode>(t.Value.ValueLiteral); }); } [Fact] public void Coerce_Nullable_ReviewInput_Variable_With_Object_Literal() { // arrange var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); var variableDefinitions = new List<VariableDefinitionNode> { new VariableDefinitionNode( null, new VariableNode("abc"), description: null, new NamedTypeNode("ReviewInput"), new StringValueNode("def"), Array.Empty<DirectiveNode>()) }; var variableValues = new Dictionary<string, object?> { {"abc", new ObjectValueNode(new ObjectFieldNode("stars", 5))} }; var coercedValues = new Dictionary<string, VariableValueOrLiteral>(); var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); // act helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); // assert Assert.Collection(coercedValues, t => { Assert.Equal("abc", t.Key); Assert.Equal("ReviewInput", Assert.IsType<ReviewInputType>(t.Value.Type).Name); Assert.Equal(5, Assert.IsType<Review>(t.Value.Value).Stars); Assert.IsType<ObjectValueNode>(t.Value.ValueLiteral); }); } [Fact] public void Coerce_Nullable_ReviewInput_Variable_With_Dictionary() { // arrange var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); var variableDefinitions = new List<VariableDefinitionNode> { new VariableDefinitionNode( null, new VariableNode("abc"), description: null, new NamedTypeNode("ReviewInput"), new StringValueNode("def"), Array.Empty<DirectiveNode>()) }; var variableValues = new Dictionary<string, object?> { {"abc", new Dictionary<string, object> { {"stars", 5} }} }; var coercedValues = new Dictionary<string, VariableValueOrLiteral>(); var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); // act helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); // assert Assert.Collection(coercedValues, t => { Assert.Equal("abc", t.Key); Assert.Equal("ReviewInput", Assert.IsType<ReviewInputType>(t.Value.Type).Name); Assert.Equal(5, Assert.IsType<Review>(t.Value.Value).Stars); t.Value.ValueLiteral.ToString().MatchSnapshot(); }); } [Fact] public void Coerce_Nullable_ReviewInput_Variable_With_Review_Object() { // arrange var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); var variableDefinitions = new List<VariableDefinitionNode> { new VariableDefinitionNode( null, new VariableNode("abc"), description: null, new NamedTypeNode("ReviewInput"), new StringValueNode("def"), Array.Empty<DirectiveNode>()) }; var variableValues = new Dictionary<string, object?> { { "abc", new Review(stars: 5) } }; var coercedValues = new Dictionary<string, VariableValueOrLiteral>(); var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); // act helper.CoerceVariableValues(schema, variableDefinitions, variableValues, coercedValues); // assert Assert.Collection(coercedValues, t => { Assert.Equal("abc", t.Key); Assert.Equal("ReviewInput", Assert.IsType<ReviewInputType>(t.Value.Type).Name); Assert.Equal(5, Assert.IsType<Review>(t.Value.Value).Stars); t.Value.ValueLiteral.ToString().MatchSnapshot(); }); } [Fact] public void Error_When_Value_Is_Null_On_Non_Null_Variable() { // arrange var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); var variableDefinitions = new List<VariableDefinitionNode> { new VariableDefinitionNode( null, new VariableNode("abc"), description: null, new NonNullTypeNode(new NamedTypeNode("String")), new StringValueNode("def"), Array.Empty<DirectiveNode>()) }; var variableValues = new Dictionary<string, object?> { {"abc", NullValueNode.Default} }; var coercedValues = new Dictionary<string, VariableValueOrLiteral>(); var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); // act void Action() => helper.CoerceVariableValues( schema, variableDefinitions, variableValues, coercedValues); // assert Assert.Throws<GraphQLException>(Action).Errors.MatchSnapshot(); } [Fact] public void Error_When_PlainValue_Is_Null_On_Non_Null_Variable() { // arrange var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); var variableDefinitions = new List<VariableDefinitionNode> { new VariableDefinitionNode( null, new VariableNode("abc"), description: null, new NonNullTypeNode(new NamedTypeNode("String")), new StringValueNode("def"), Array.Empty<DirectiveNode>()) }; var variableValues = new Dictionary<string, object?> { {"abc", null} }; var coercedValues = new Dictionary<string, VariableValueOrLiteral>(); var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); // act void Action() => helper.CoerceVariableValues( schema, variableDefinitions, variableValues, coercedValues); // assert Assert.Throws<GraphQLException>(Action).Errors.MatchSnapshot(); } [Fact] public void Error_When_Value_Type_Does_Not_Match_Variable_Type() { // arrange var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); var variableDefinitions = new List<VariableDefinitionNode> { new VariableDefinitionNode( null, new VariableNode("abc"), description: null, new NamedTypeNode("String"), new StringValueNode("def"), Array.Empty<DirectiveNode>()) }; var variableValues = new Dictionary<string, object?> { {"abc", new IntValueNode(1)} }; var coercedValues = new Dictionary<string, VariableValueOrLiteral>(); var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); // act void Action() => helper.CoerceVariableValues( schema, variableDefinitions, variableValues, coercedValues); // assert Assert.Throws<SerializationException>(Action) .Errors.Select(t => t.WithException(null)) .ToList() .MatchSnapshot(); } [Fact] public void Error_When_PlainValue_Type_Does_Not_Match_Variable_Type() { // arrange var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); var variableDefinitions = new List<VariableDefinitionNode> { new(null, new VariableNode("abc"), description: null, new NamedTypeNode("String"), new StringValueNode("def"), Array.Empty<DirectiveNode>()) }; var variableValues = new Dictionary<string, object?> { { "abc", 1 } }; var coercedValues = new Dictionary<string, VariableValueOrLiteral>(); var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); // act void Action() => helper.CoerceVariableValues( schema, variableDefinitions, variableValues, coercedValues); // assert Assert.Throws<SerializationException>(Action).Errors.MatchSnapshot(); } [Fact] public void Variable_Type_Is_Not_An_Input_Type() { // arrange var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); var variableDefinitions = new List<VariableDefinitionNode> { new(null, new VariableNode("abc"), description: null, new NamedTypeNode("Human"), new StringValueNode("def"), Array.Empty<DirectiveNode>()) }; var variableValues = new Dictionary<string, object?> { { "abc", 1 } }; var coercedValues = new Dictionary<string, VariableValueOrLiteral>(); var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); // act void Action() => helper.CoerceVariableValues( schema, variableDefinitions, variableValues, coercedValues); // assert Assert.Throws<GraphQLException>(Action).Errors.MatchSnapshot(); } [Fact] public void Error_When_Input_Field_Has_Different_Properties_Than_Defined() { // arrange var schema = SchemaBuilder.New().AddStarWarsTypes().Create(); var variableDefinitions = new List<VariableDefinitionNode> { new(null, new VariableNode("abc"), description: null, new NamedTypeNode("ReviewInput"), new StringValueNode("def"), Array.Empty<DirectiveNode>()) }; var variableValues = new Dictionary<string, object?> { { "abc", new ObjectValueNode(new ObjectFieldNode("abc", "def")) } }; var coercedValues = new Dictionary<string, VariableValueOrLiteral>(); var helper = new VariableCoercionHelper(new(), new(new DefaultTypeConverter())); // act void Action() => helper.CoerceVariableValues( schema, variableDefinitions, variableValues, coercedValues); // assert Assert.Throws<SerializationException>(Action) .Errors.Select(t => t.WithException(null)) .ToList() .MatchSnapshot(); } [Fact] public void StringValues_Representing_EnumValues_In_Lists_ShouldBe_Rewritten() { // arrange var schema = SchemaBuilder.New() .AddDocumentFromString( @" type Query { test(list: [FooInput]): String } input FooInput { enum: TestEnum }
VariableCoercionHelperTests
csharp
dotnet__maui
src/Controls/Foldable/src/Android/HingeSensor.cs
{ "start": 874, "end": 2329 }
public partial class ____ { // This string will detect hinge sensors on other foldable devices // and should be used with a comparison to the `sensor.Name` const string HINGE_SENSOR_NAME = "Hinge"; SensorManager sensorManager; Sensor hingeSensor; HingeSensorEventListener sensorListener; public event EventHandler<HingeSensorChangedEventArgs> OnSensorChanged; public HingeSensor(Context context) { sensorManager = SensorManager.FromContext(context); var sensors = sensorManager.GetSensorList(SensorType.All); foreach (var sensor in sensors) { // Use generic "hinge" sensor name, to match on a variety of folding device types if (sensor.Name.Contains(HINGE_SENSOR_NAME, StringComparison.InvariantCultureIgnoreCase)) { hingeSensor = sensor; break; } } } public bool HasHinge => hingeSensor != null; public void StartListening() { if (sensorManager != null && hingeSensor != null) { sensorListener ??= new HingeSensorEventListener { SensorChangedHandler = se => { if (se.Sensor == hingeSensor) OnSensorChanged?.Invoke(hingeSensor, new HingeSensorChangedEventArgs(se)); } }; sensorManager.RegisterListener(sensorListener, hingeSensor, SensorDelay.Normal); } } public void StopListening() { if (sensorManager != null && hingeSensor != null) sensorManager.UnregisterListener(sensorListener, hingeSensor); }
HingeSensor
csharp
StackExchange__StackExchange.Redis
src/StackExchange.Redis/RedisTransaction.cs
{ "start": 159, "end": 7050 }
internal sealed class ____ : RedisDatabase, ITransaction { private List<ConditionResult>? _conditions; private List<QueuedMessage>? _pending; private object SyncLock => this; public RedisTransaction(RedisDatabase wrapped, object? asyncState) : base(wrapped.multiplexer, wrapped.Database, asyncState ?? wrapped.AsyncState) { // need to check we can reliably do this... var commandMap = multiplexer.CommandMap; commandMap.AssertAvailable(RedisCommand.MULTI); commandMap.AssertAvailable(RedisCommand.EXEC); commandMap.AssertAvailable(RedisCommand.DISCARD); } public ConditionResult AddCondition(Condition condition) { if (condition == null) throw new ArgumentNullException(nameof(condition)); var commandMap = multiplexer.CommandMap; lock (SyncLock) { if (_conditions == null) { // we don't demand these unless the user is requesting conditions, but we need both... commandMap.AssertAvailable(RedisCommand.WATCH); commandMap.AssertAvailable(RedisCommand.UNWATCH); _conditions = new List<ConditionResult>(); } condition.CheckCommands(commandMap); var result = new ConditionResult(condition); _conditions.Add(result); return result; } } public void Execute() => Execute(CommandFlags.FireAndForget); public bool Execute(CommandFlags flags) { var msg = CreateMessage(flags, out ResultProcessor<bool>? proc); return base.ExecuteSync(msg, proc); // need base to avoid our local "not supported" override } public Task<bool> ExecuteAsync(CommandFlags flags) { var msg = CreateMessage(flags, out ResultProcessor<bool>? proc); return base.ExecuteAsync(msg, proc); // need base to avoid our local wrapping override } internal override Task<T> ExecuteAsync<T>(Message? message, ResultProcessor<T>? processor, T defaultValue, ServerEndPoint? server = null) { if (message == null) return CompletedTask<T>.FromDefault(defaultValue, asyncState); multiplexer.CheckMessage(message); multiplexer.Trace("Wrapping " + message.Command, "Transaction"); // prepare the inner command as a task Task<T> task; if (message.IsFireAndForget) { task = CompletedTask<T>.FromDefault(defaultValue, null); // F+F explicitly does not get async-state } else { var source = TaskResultBox<T>.Create(out var tcs, asyncState); message.SetSource(source, processor); task = tcs.Task; } QueueMessage(message); return task; } internal override Task<T?> ExecuteAsync<T>(Message? message, ResultProcessor<T>? processor, ServerEndPoint? server = null) where T : default { if (message == null) return CompletedTask<T>.Default(asyncState); multiplexer.CheckMessage(message); multiplexer.Trace("Wrapping " + message.Command, "Transaction"); // prepare the inner command as a task Task<T?> task; if (message.IsFireAndForget) { task = CompletedTask<T>.Default(null); // F+F explicitly does not get async-state } else { var source = TaskResultBox<T?>.Create(out var tcs, asyncState); message.SetSource(source!, processor); task = tcs.Task; } QueueMessage(message); return task; } private void QueueMessage(Message message) { // prepare an outer-command that decorates that, but expects QUEUED var queued = new QueuedMessage(message); var wasQueued = SimpleResultBox<bool>.Create(); queued.SetSource(wasQueued, QueuedProcessor.Default); // store it, and return the task of the *outer* command // (there is no task for the inner command) lock (SyncLock) { (_pending ??= new List<QueuedMessage>()).Add(queued); switch (message.Command) { case RedisCommand.UNKNOWN: case RedisCommand.EVAL: case RedisCommand.EVALSHA: var server = multiplexer.SelectServer(message); if (server != null && server.SupportsDatabases) { // people can do very naughty things in an EVAL // including change the DB; change it back to what we // think it should be! var sel = PhysicalConnection.GetSelectDatabaseCommand(message.Db); queued = new QueuedMessage(sel); wasQueued = SimpleResultBox<bool>.Create(); queued.SetSource(wasQueued, QueuedProcessor.Default); _pending.Add(queued); } break; } } } internal override T? ExecuteSync<T>(Message? message, ResultProcessor<T>? processor, ServerEndPoint? server = null, T? defaultValue = default) where T : default { throw new NotSupportedException("ExecuteSync cannot be used inside a transaction"); } private Message? CreateMessage(CommandFlags flags, out ResultProcessor<bool>? processor) { List<ConditionResult>? cond; List<QueuedMessage>? work; lock (SyncLock) { work = _pending; _pending = null; // any new operations go into a different queue cond = _conditions; _conditions = null; // any new conditions go into a different queue } if ((work == null || work.Count == 0) && (cond == null || cond.Count == 0)) { if ((flags & CommandFlags.FireAndForget) != 0) { processor = null; return null; // they won't notice if we don't do anything... } processor = ResultProcessor.DemandPONG; return Message.Create(-1, flags, RedisCommand.PING); } processor = TransactionProcessor.Default; return new TransactionMessage(Database, flags, cond, work); }
RedisTransaction
csharp
jellyfin__jellyfin
Jellyfin.Server/Migrations/Routines/ReaddDefaultPluginRepository.cs
{ "start": 466, "end": 1693 }
public class ____ : IMigrationRoutine #pragma warning restore CS0618 // Type or member is obsolete { private readonly IServerConfigurationManager _serverConfigurationManager; private readonly RepositoryInfo _defaultRepositoryInfo = new RepositoryInfo { Name = "Jellyfin Stable", Url = "https://repo.jellyfin.org/releases/plugin/manifest-stable.json" }; /// <summary> /// Initializes a new instance of the <see cref="ReaddDefaultPluginRepository"/> class. /// </summary> /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param> public ReaddDefaultPluginRepository(IServerConfigurationManager serverConfigurationManager) { _serverConfigurationManager = serverConfigurationManager; } /// <inheritdoc/> public void Perform() { // Only add if repository list is empty if (_serverConfigurationManager.Configuration.PluginRepositories.Length == 0) { _serverConfigurationManager.Configuration.PluginRepositories = new[] { _defaultRepositoryInfo }; _serverConfigurationManager.SaveConfiguration(); } } }
ReaddDefaultPluginRepository
csharp
microsoft__FASTER
cs/src/core/Index/FASTER/Implementation/InternalRMW.cs
{ "start": 13239, "end": 13576 }
record ____ thread is in V) case Phase.IN_PROGRESS: // Thread is in v+1 case Phase.WAIT_INDEX_CHECKPOINT: case Phase.WAIT_FLUSH: if (IsRecordVersionNew(stackCtx.recSrc.LogicalAddress)) break; // Normal Processing; V+1 thread encountered a
when
csharp
MassTransit__MassTransit
src/MassTransit.Abstractions/SendEndpointExtensions.cs
{ "start": 129, "end": 2068 }
public static class ____ { /// <summary> /// Send a dynamically typed message initialized by a loosely typed dictionary of values. MassTransit will /// create and populate an object instance with the properties of the <paramref name="values" /> argument. /// </summary> /// <param name="messageType">The message type to publish</param> /// <param name="values"> /// The dictionary of values to become hydrated and published under the type of the interface. /// </param> /// <param name="cancellationToken"></param> /// <param name="publishEndpoint"></param> public static Task Send(this ISendEndpoint publishEndpoint, Type messageType, object values, CancellationToken cancellationToken = default) { return SendEndpointConverterCache.SendInitializer(publishEndpoint, messageType, values, cancellationToken); } /// <summary> /// Send a dynamically typed message initialized by a loosely typed dictionary of values. MassTransit will /// create and populate an object instance with the properties of the <paramref name="values" /> argument. /// </summary> /// <param name="messageType">The message type to publish</param> /// <param name="values"> /// The dictionary of values to become hydrated and published under the type of the interface. /// </param> /// <param name="pipe"></param> /// <param name="cancellationToken"></param> /// <param name="publishEndpoint"></param> public static Task Send(this ISendEndpoint publishEndpoint, Type messageType, object values, IPipe<SendContext> pipe, CancellationToken cancellationToken = default) { return SendEndpointConverterCache.SendInitializer(publishEndpoint, messageType, values, pipe, cancellationToken); } } }
SendEndpointExtensions
csharp
dotnet__aspnetcore
src/Validation/src/ValidatableParameterInfo.cs
{ "start": 451, "end": 5369 }
public abstract class ____ : IValidatableInfo { private RequiredAttribute? _requiredAttribute; /// <summary> /// Creates a new instance of <see cref="ValidatableParameterInfo"/>. /// </summary> /// <param name="parameterType">The <see cref="Type"/> associated with the parameter.</param> /// <param name="name">The parameter name.</param> /// <param name="displayName">The display name for the parameter.</param> protected ValidatableParameterInfo( Type parameterType, string name, string displayName) { ParameterType = parameterType; Name = name; DisplayName = displayName; } /// <summary> /// Gets the parameter type. /// </summary> internal Type ParameterType { get; } /// <summary> /// Gets the parameter name. /// </summary> internal string Name { get; } /// <summary> /// Gets the display name for the parameter. /// </summary> internal string DisplayName { get; } /// <summary> /// Gets the validation attributes for this parameter. /// </summary> /// <returns>An array of validation attributes to apply to this parameter.</returns> protected abstract ValidationAttribute[] GetValidationAttributes(); /// <inheritdoc /> /// <remarks> /// If the parameter is a collection, each item in the collection will be validated. /// If the parameter is not a collection but has a validatable type, the single value will be validated. /// </remarks> public virtual async Task ValidateAsync(object? value, ValidateContext context, CancellationToken cancellationToken) { // Skip validation if value is null and parameter is optional if (value == null && ParameterType.IsNullable()) { return; } context.ValidationContext.DisplayName = DisplayName; context.ValidationContext.MemberName = Name; var validationAttributes = GetValidationAttributes(); if (_requiredAttribute is not null || validationAttributes.TryGetRequiredAttribute(out _requiredAttribute)) { var result = _requiredAttribute.GetValidationResult(value, context.ValidationContext); if (result is not null && result != ValidationResult.Success && result.ErrorMessage is not null) { var key = string.IsNullOrEmpty(context.CurrentValidationPath) ? Name : $"{context.CurrentValidationPath}.{Name}"; context.AddValidationError(Name, key, [result.ErrorMessage], null); return; } } // Validate against validation attributes for (var i = 0; i < validationAttributes.Length; i++) { var attribute = validationAttributes[i]; try { var result = attribute.GetValidationResult(value, context.ValidationContext); if (result is not null && result != ValidationResult.Success && result.ErrorMessage is not null) { var key = string.IsNullOrEmpty(context.CurrentValidationPath) ? Name : $"{context.CurrentValidationPath}.{Name}"; context.AddOrExtendValidationErrors(Name, key, [result.ErrorMessage], null); } } catch (Exception ex) { var key = string.IsNullOrEmpty(context.CurrentValidationPath) ? Name : $"{context.CurrentValidationPath}.{Name}"; context.AddValidationError(Name, key, [ex.Message], null); } } // If the parameter is a collection, validate each item if (ParameterType.IsEnumerable() && value is IEnumerable enumerable) { var index = 0; var currentPrefix = context.CurrentValidationPath; foreach (var item in enumerable) { if (item != null) { context.CurrentValidationPath = string.IsNullOrEmpty(currentPrefix) ? $"{Name}[{index}]" : $"{currentPrefix}.{Name}[{index}]"; if (context.ValidationOptions.TryGetValidatableTypeInfo(item.GetType(), out var validatableType)) { await validatableType.ValidateAsync(item, context, cancellationToken); } } index++; } context.CurrentValidationPath = currentPrefix; } // If not enumerable, validate the single value else if (value != null) { var valueType = value.GetType(); if (context.ValidationOptions.TryGetValidatableTypeInfo(valueType, out var validatableType)) { await validatableType.ValidateAsync(value, context, cancellationToken); } } } }
ValidatableParameterInfo
csharp
dotnet__extensions
src/Libraries/Microsoft.Extensions.AI.OpenAI/OpenAIRealtimeConversationClient.cs
{ "start": 276, "end": 896 }
internal sealed class ____ { public static ConversationFunctionTool ToOpenAIConversationFunctionTool(AIFunctionDeclaration aiFunction, ChatOptions? options = null) { bool? strict = OpenAIClientExtensions.HasStrict(aiFunction.AdditionalProperties) ?? OpenAIClientExtensions.HasStrict(options?.AdditionalProperties); return new ConversationFunctionTool(aiFunction.Name) { Description = aiFunction.Description, Parameters = OpenAIClientExtensions.ToOpenAIFunctionParameters(aiFunction, strict), }; } }
OpenAIRealtimeConversationClient
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.Extensions.Tests/Protoc/Services.cs
{ "start": 1930199, "end": 1949217 }
partial class ____ : pb::IMessage<QueryRockstarAlbums> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<QueryRockstarAlbums> _parser = new pb::MessageParser<QueryRockstarAlbums>(() => new QueryRockstarAlbums()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<QueryRockstarAlbums> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::ServiceStack.Extensions.Tests.Protoc.ServicesReflection.Descriptor.MessageTypes[153]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public QueryRockstarAlbums() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public QueryRockstarAlbums(QueryRockstarAlbums other) : this() { skip_ = other.skip_; take_ = other.take_; orderBy_ = other.orderBy_; orderByDesc_ = other.orderByDesc_; include_ = other.include_; fields_ = other.fields_; meta_ = other.meta_.Clone(); id_ = other.id_; rockstarId_ = other.rockstarId_; name_ = other.name_; genre_ = other.genre_; idBetween_ = other.idBetween_.Clone(); _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public QueryRockstarAlbums Clone() { return new QueryRockstarAlbums(this); } /// <summary>Field number for the "Skip" field.</summary> public const int SkipFieldNumber = 1; private int skip_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int Skip { get { return skip_; } set { skip_ = value; } } /// <summary>Field number for the "Take" field.</summary> public const int TakeFieldNumber = 2; private int take_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int Take { get { return take_; } set { take_ = value; } } /// <summary>Field number for the "OrderBy" field.</summary> public const int OrderByFieldNumber = 3; private string orderBy_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string OrderBy { get { return orderBy_; } set { orderBy_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "OrderByDesc" field.</summary> public const int OrderByDescFieldNumber = 4; private string orderByDesc_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string OrderByDesc { get { return orderByDesc_; } set { orderByDesc_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "Include" field.</summary> public const int IncludeFieldNumber = 5; private string include_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Include { get { return include_; } set { include_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "Fields" field.</summary> public const int FieldsFieldNumber = 6; private string fields_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Fields { get { return fields_; } set { fields_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "Meta" field.</summary> public const int MetaFieldNumber = 7; private static readonly pbc::MapField<string, string>.Codec _map_meta_codec = new pbc::MapField<string, string>.Codec(pb::FieldCodec.ForString(10, ""), pb::FieldCodec.ForString(18, ""), 58); private readonly pbc::MapField<string, string> meta_ = new pbc::MapField<string, string>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::MapField<string, string> Meta { get { return meta_; } } /// <summary>Field number for the "Id" field.</summary> public const int IdFieldNumber = 201; private int id_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int Id { get { return id_; } set { id_ = value; } } /// <summary>Field number for the "RockstarId" field.</summary> public const int RockstarIdFieldNumber = 202; private int rockstarId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int RockstarId { get { return rockstarId_; } set { rockstarId_ = value; } } /// <summary>Field number for the "Name" field.</summary> public const int NameFieldNumber = 203; private string name_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "Genre" field.</summary> public const int GenreFieldNumber = 204; private string genre_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Genre { get { return genre_; } set { genre_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "IdBetween" field.</summary> public const int IdBetweenFieldNumber = 205; private static readonly pb::FieldCodec<int> _repeated_idBetween_codec = pb::FieldCodec.ForInt32(1640); private readonly pbc::RepeatedField<int> idBetween_ = new pbc::RepeatedField<int>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::RepeatedField<int> IdBetween { get { return idBetween_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as QueryRockstarAlbums); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(QueryRockstarAlbums other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Skip != other.Skip) return false; if (Take != other.Take) return false; if (OrderBy != other.OrderBy) return false; if (OrderByDesc != other.OrderByDesc) return false; if (Include != other.Include) return false; if (Fields != other.Fields) return false; if (!Meta.Equals(other.Meta)) return false; if (Id != other.Id) return false; if (RockstarId != other.RockstarId) return false; if (Name != other.Name) return false; if (Genre != other.Genre) return false; if(!idBetween_.Equals(other.idBetween_)) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Skip != 0) hash ^= Skip.GetHashCode(); if (Take != 0) hash ^= Take.GetHashCode(); if (OrderBy.Length != 0) hash ^= OrderBy.GetHashCode(); if (OrderByDesc.Length != 0) hash ^= OrderByDesc.GetHashCode(); if (Include.Length != 0) hash ^= Include.GetHashCode(); if (Fields.Length != 0) hash ^= Fields.GetHashCode(); hash ^= Meta.GetHashCode(); if (Id != 0) hash ^= Id.GetHashCode(); if (RockstarId != 0) hash ^= RockstarId.GetHashCode(); if (Name.Length != 0) hash ^= Name.GetHashCode(); if (Genre.Length != 0) hash ^= Genre.GetHashCode(); hash ^= idBetween_.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Skip != 0) { output.WriteRawTag(8); output.WriteInt32(Skip); } if (Take != 0) { output.WriteRawTag(16); output.WriteInt32(Take); } if (OrderBy.Length != 0) { output.WriteRawTag(26); output.WriteString(OrderBy); } if (OrderByDesc.Length != 0) { output.WriteRawTag(34); output.WriteString(OrderByDesc); } if (Include.Length != 0) { output.WriteRawTag(42); output.WriteString(Include); } if (Fields.Length != 0) { output.WriteRawTag(50); output.WriteString(Fields); } meta_.WriteTo(output, _map_meta_codec); if (Id != 0) { output.WriteRawTag(200, 12); output.WriteInt32(Id); } if (RockstarId != 0) { output.WriteRawTag(208, 12); output.WriteInt32(RockstarId); } if (Name.Length != 0) { output.WriteRawTag(218, 12); output.WriteString(Name); } if (Genre.Length != 0) { output.WriteRawTag(226, 12); output.WriteString(Genre); } idBetween_.WriteTo(output, _repeated_idBetween_codec); if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Skip != 0) { output.WriteRawTag(8); output.WriteInt32(Skip); } if (Take != 0) { output.WriteRawTag(16); output.WriteInt32(Take); } if (OrderBy.Length != 0) { output.WriteRawTag(26); output.WriteString(OrderBy); } if (OrderByDesc.Length != 0) { output.WriteRawTag(34); output.WriteString(OrderByDesc); } if (Include.Length != 0) { output.WriteRawTag(42); output.WriteString(Include); } if (Fields.Length != 0) { output.WriteRawTag(50); output.WriteString(Fields); } meta_.WriteTo(ref output, _map_meta_codec); if (Id != 0) { output.WriteRawTag(200, 12); output.WriteInt32(Id); } if (RockstarId != 0) { output.WriteRawTag(208, 12); output.WriteInt32(RockstarId); } if (Name.Length != 0) { output.WriteRawTag(218, 12); output.WriteString(Name); } if (Genre.Length != 0) { output.WriteRawTag(226, 12); output.WriteString(Genre); } idBetween_.WriteTo(ref output, _repeated_idBetween_codec); if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Skip != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Skip); } if (Take != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Take); } if (OrderBy.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(OrderBy); } if (OrderByDesc.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(OrderByDesc); } if (Include.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Include); } if (Fields.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Fields); } size += meta_.CalculateSize(_map_meta_codec); if (Id != 0) { size += 2 + pb::CodedOutputStream.ComputeInt32Size(Id); } if (RockstarId != 0) { size += 2 + pb::CodedOutputStream.ComputeInt32Size(RockstarId); } if (Name.Length != 0) { size += 2 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Genre.Length != 0) { size += 2 + pb::CodedOutputStream.ComputeStringSize(Genre); } size += idBetween_.CalculateSize(_repeated_idBetween_codec); if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(QueryRockstarAlbums other) { if (other == null) { return; } if (other.Skip != 0) { Skip = other.Skip; } if (other.Take != 0) { Take = other.Take; } if (other.OrderBy.Length != 0) { OrderBy = other.OrderBy; } if (other.OrderByDesc.Length != 0) { OrderByDesc = other.OrderByDesc; } if (other.Include.Length != 0) { Include = other.Include; } if (other.Fields.Length != 0) { Fields = other.Fields; } meta_.Add(other.meta_); if (other.Id != 0) { Id = other.Id; } if (other.RockstarId != 0) { RockstarId = other.RockstarId; } if (other.Name.Length != 0) { Name = other.Name; } if (other.Genre.Length != 0) { Genre = other.Genre; } idBetween_.Add(other.idBetween_); _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { Skip = input.ReadInt32(); break; } case 16: { Take = input.ReadInt32(); break; } case 26: { OrderBy = input.ReadString(); break; } case 34: { OrderByDesc = input.ReadString(); break; } case 42: { Include = input.ReadString(); break; } case 50: { Fields = input.ReadString(); break; } case 58: { meta_.AddEntriesFrom(input, _map_meta_codec); break; } case 1608: { Id = input.ReadInt32(); break; } case 1616: { RockstarId = input.ReadInt32(); break; } case 1626: { Name = input.ReadString(); break; } case 1634: { Genre = input.ReadString(); break; } case 1642: case 1640: { idBetween_.AddEntriesFrom(input, _repeated_idBetween_codec); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 8: { Skip = input.ReadInt32(); break; } case 16: { Take = input.ReadInt32(); break; } case 26: { OrderBy = input.ReadString(); break; } case 34: { OrderByDesc = input.ReadString(); break; } case 42: { Include = input.ReadString(); break; } case 50: { Fields = input.ReadString(); break; } case 58: { meta_.AddEntriesFrom(ref input, _map_meta_codec); break; } case 1608: { Id = input.ReadInt32(); break; } case 1616: { RockstarId = input.ReadInt32(); break; } case 1626: { Name = input.ReadString(); break; } case 1634: { Genre = input.ReadString(); break; } case 1642: case 1640: { idBetween_.AddEntriesFrom(ref input, _repeated_idBetween_codec); break; } } } } #endif } public sealed
QueryRockstarAlbums
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.NetFramework/SmartThreadPool/Interfaces.cs
{ "start": 1953, "end": 14034 }
public interface ____ { /// <summary> /// Get/Set the name of the WorkItemsGroup /// </summary> string Name { get; set; } /// <summary> /// Get/Set the maximum number of workitem that execute cocurrency on the thread pool /// </summary> int Concurrency { get; set; } /// <summary> /// Get the number of work items waiting in the queue. /// </summary> int WaitingCallbacks { get; } /// <summary> /// Get an array with all the state objects of the currently running items. /// The array represents a snap shot and impact performance. /// </summary> object[] GetStates(); /// <summary> /// Get the WorkItemsGroup start information /// </summary> WIGStartInfo WIGStartInfo { get; } /// <summary> /// Starts to execute work items /// </summary> void Start(); /// <summary> /// Cancel all the work items. /// Same as Cancel(false) /// </summary> void Cancel(); /// <summary> /// Cancel all work items using thread abortion /// </summary> /// <param name="abortExecution">True to stop work items by raising ThreadAbortException</param> void Cancel(bool abortExecution); /// <summary> /// Wait for all work item to complete. /// </summary> void WaitForIdle(); /// <summary> /// Wait for all work item to complete, until timeout expired /// </summary> /// <param name="timeout">How long to wait for the work items to complete</param> /// <returns>Returns true if work items completed within the timeout, otherwise false.</returns> bool WaitForIdle(TimeSpan timeout); /// <summary> /// Wait for all work item to complete, until timeout expired /// </summary> /// <param name="millisecondsTimeout">How long to wait for the work items to complete in milliseconds</param> /// <returns>Returns true if work items completed within the timeout, otherwise false.</returns> bool WaitForIdle(int millisecondsTimeout); /// <summary> /// IsIdle is true when there are no work items running or queued. /// </summary> bool IsIdle { get; } /// <summary> /// This event is fired when all work items are completed. /// (When IsIdle changes to true) /// This event only work on WorkItemsGroup. On SmartThreadPool /// it throws the NotImplementedException. /// </summary> event WorkItemsGroupIdleHandler OnIdle; #region QueueWorkItem /// <summary> /// Queue a work item /// </summary> /// <param name="callback">A callback to execute</param> /// <returns>Returns a work item result</returns> IWorkItemResult QueueWorkItem(WorkItemCallback callback); /// <summary> /// Queue a work item /// </summary> /// <param name="callback">A callback to execute</param> /// <param name="workItemPriority">The priority of the work item</param> /// <returns>Returns a work item result</returns> IWorkItemResult QueueWorkItem(WorkItemCallback callback, WorkItemPriority workItemPriority); /// <summary> /// Queue a work item /// </summary> /// <param name="callback">A callback to execute</param> /// <param name="state"> /// The context object of the work item. Used for passing arguments to the work item. /// </param> /// <returns>Returns a work item result</returns> IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state); /// <summary> /// Queue a work item /// </summary> /// <param name="callback">A callback to execute</param> /// <param name="state"> /// The context object of the work item. Used for passing arguments to the work item. /// </param> /// <param name="workItemPriority">The work item priority</param> /// <returns>Returns a work item result</returns> IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state, WorkItemPriority workItemPriority); /// <summary> /// Queue a work item /// </summary> /// <param name="callback">A callback to execute</param> /// <param name="state"> /// The context object of the work item. Used for passing arguments to the work item. /// </param> /// <param name="postExecuteWorkItemCallback"> /// A delegate to call after the callback completion /// </param> /// <returns>Returns a work item result</returns> IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state, PostExecuteWorkItemCallback postExecuteWorkItemCallback); /// <summary> /// Queue a work item /// </summary> /// <param name="callback">A callback to execute</param> /// <param name="state"> /// The context object of the work item. Used for passing arguments to the work item. /// </param> /// <param name="postExecuteWorkItemCallback"> /// A delegate to call after the callback completion /// </param> /// <param name="workItemPriority">The work item priority</param> /// <returns>Returns a work item result</returns> IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state, PostExecuteWorkItemCallback postExecuteWorkItemCallback, WorkItemPriority workItemPriority); /// <summary> /// Queue a work item /// </summary> /// <param name="callback">A callback to execute</param> /// <param name="state"> /// The context object of the work item. Used for passing arguments to the work item. /// </param> /// <param name="postExecuteWorkItemCallback"> /// A delegate to call after the callback completion /// </param> /// <param name="callToPostExecute">Indicates on which cases to call to the post execute callback</param> /// <returns>Returns a work item result</returns> IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state, PostExecuteWorkItemCallback postExecuteWorkItemCallback, CallToPostExecute callToPostExecute); /// <summary> /// Queue a work item /// </summary> /// <param name="callback">A callback to execute</param> /// <param name="state"> /// The context object of the work item. Used for passing arguments to the work item. /// </param> /// <param name="postExecuteWorkItemCallback"> /// A delegate to call after the callback completion /// </param> /// <param name="callToPostExecute">Indicates on which cases to call to the post execute callback</param> /// <param name="workItemPriority">The work item priority</param> /// <returns>Returns a work item result</returns> IWorkItemResult QueueWorkItem(WorkItemCallback callback, object state, PostExecuteWorkItemCallback postExecuteWorkItemCallback, CallToPostExecute callToPostExecute, WorkItemPriority workItemPriority); /// <summary> /// Queue a work item /// </summary> /// <param name="workItemInfo">Work item info</param> /// <param name="callback">A callback to execute</param> /// <returns>Returns a work item result</returns> IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WorkItemCallback callback); /// <summary> /// Queue a work item /// </summary> /// <param name="workItemInfo">Work item information</param> /// <param name="callback">A callback to execute</param> /// <param name="state"> /// The context object of the work item. Used for passing arguments to the work item. /// </param> /// <returns>Returns a work item result</returns> IWorkItemResult QueueWorkItem(WorkItemInfo workItemInfo, WorkItemCallback callback, object state); #endregion #region QueueWorkItem(Action<...>) /// <summary> /// Queue a work item. /// </summary> /// <returns>Returns a IWorkItemResult object, but its GetResult() will always return null</returns> IWorkItemResult QueueWorkItem(Action action, WorkItemPriority priority = SmartThreadPool.DefaultWorkItemPriority); /// <summary> /// Queue a work item. /// </summary> /// <returns>Returns a IWorkItemResult object, but its GetResult() will always return null</returns> IWorkItemResult QueueWorkItem<T>(Action<T> action, T arg, WorkItemPriority priority = SmartThreadPool.DefaultWorkItemPriority); /// <summary> /// Queue a work item. /// </summary> /// <returns>Returns a IWorkItemResult object, but its GetResult() will always return null</returns> IWorkItemResult QueueWorkItem<T1, T2>(Action<T1, T2> action, T1 arg1, T2 arg2, WorkItemPriority priority = SmartThreadPool.DefaultWorkItemPriority); /// <summary> /// Queue a work item. /// </summary> /// <returns>Returns a IWorkItemResult object, but its GetResult() will always return null</returns> IWorkItemResult QueueWorkItem<T1, T2, T3>(Action<T1, T2, T3> action, T1 arg1, T2 arg2, T3 arg3, WorkItemPriority priority = SmartThreadPool.DefaultWorkItemPriority); /// <summary> /// Queue a work item. /// </summary> /// <returns>Returns a IWorkItemResult object, but its GetResult() will always return null</returns> IWorkItemResult QueueWorkItem<T1, T2, T3, T4>(Action<T1, T2, T3, T4> action, T1 arg1, T2 arg2, T3 arg3, T4 arg4, WorkItemPriority priority = SmartThreadPool.DefaultWorkItemPriority); #endregion #region QueueWorkItem(Func<...>) /// <summary> /// Queue a work item. /// </summary> /// <returns>Returns a IWorkItemResult&lt;TResult&gt; object. /// its GetResult() returns a TResult object</returns> IWorkItemResult<TResult> QueueWorkItem<TResult>(Func<TResult> func, WorkItemPriority priority = SmartThreadPool.DefaultWorkItemPriority); /// <summary> /// Queue a work item. /// </summary> /// <returns>Returns a IWorkItemResult&lt;TResult&gt; object. /// its GetResult() returns a TResult object</returns> IWorkItemResult<TResult> QueueWorkItem<T, TResult>(Func<T, TResult> func, T arg, WorkItemPriority priority = SmartThreadPool.DefaultWorkItemPriority); /// <summary> /// Queue a work item. /// </summary> /// <returns>Returns a IWorkItemResult&lt;TResult&gt; object. /// its GetResult() returns a TResult object</returns> IWorkItemResult<TResult> QueueWorkItem<T1, T2, TResult>(Func<T1, T2, TResult> func, T1 arg1, T2 arg2, WorkItemPriority priority = SmartThreadPool.DefaultWorkItemPriority); /// <summary> /// Queue a work item. /// </summary> /// <returns>Returns a IWorkItemResult&lt;TResult&gt; object. /// its GetResult() returns a TResult object</returns> IWorkItemResult<TResult> QueueWorkItem<T1, T2, T3, TResult>(Func<T1, T2, T3, TResult> func, T1 arg1, T2 arg2, T3 arg3, WorkItemPriority priority = SmartThreadPool.DefaultWorkItemPriority); /// <summary> /// Queue a work item. /// </summary> /// <returns>Returns a IWorkItemResult&lt;TResult&gt; object. /// its GetResult() returns a TResult object</returns> IWorkItemResult<TResult> QueueWorkItem<T1, T2, T3, T4, TResult>(Func<T1, T2, T3, T4, TResult> func, T1 arg1, T2 arg2, T3 arg3, T4 arg4, WorkItemPriority priority = SmartThreadPool.DefaultWorkItemPriority); #endregion } #endregion #region CallToPostExecute enumerator [Flags]
IWorkItemsGroup
csharp
louthy__language-ext
LanguageExt.Rx/Validation.Extensions.cs
{ "start": 130, "end": 993 }
public static class ____ { /// <summary> /// Match the two states of the Validation and return an observable stream of non-null R2s. /// </summary> [Pure] public static IObservable<R2> MatchObservable<F, A, R2>( this Validation<F, A> ma, Func<A, IObservable<R2>> Succ, Func<F, R2> Fail) where F : Monoid<F>, Eq<F> => ma.Match( Succ: Succ, Fail: x => Observable.Return(Fail(x))); /// <summary> /// Match the two states of the Validation and return an observable stream of non-null R2s. /// </summary> [Pure] public static IObservable<R2> MatchObservable<F, A, R2>( this Validation<F, A> ma, Func<A, IObservable<R2>> Succ, Func<F, IObservable<R2>> Fail) where F : Monoid<F>, Eq<F> => ma.Match(Succ: Succ, Fail: Fail); }
ValidationRxExtensions
csharp
NLog__NLog
src/NLog/SetupLoadConfigurationExtensions.cs
{ "start": 1977, "end": 3291 }
public static class ____ { /// <summary> /// Configures the global time-source used for all logevents /// </summary> /// <remarks> /// Available by default: <see cref="Time.AccurateLocalTimeSource"/>, <see cref="Time.AccurateUtcTimeSource"/>, <see cref="Time.FastLocalTimeSource"/>, <see cref="Time.FastUtcTimeSource"/> /// </remarks> public static ISetupLoadConfigurationBuilder SetTimeSource(this ISetupLoadConfigurationBuilder configBuilder, NLog.Time.TimeSource timeSource) { NLog.Time.TimeSource.Current = timeSource; return configBuilder; } /// <summary> /// Updates the dictionary <see cref="GlobalDiagnosticsContext"/> ${gdc:item=} with the name-value-pair /// </summary> public static ISetupLoadConfigurationBuilder SetGlobalContextProperty(this ISetupLoadConfigurationBuilder configBuilder, string name, string value) { GlobalDiagnosticsContext.Set(name, value); return configBuilder; } /// <summary> /// Defines <see cref="LoggingRule" /> for redirecting output from matching <see cref="Logger"/> to wanted targets. /// </summary> /// <param name="configBuilder">Fluent
SetupLoadConfigurationExtensions
csharp
dotnet__efcore
test/EFCore.Sqlite.FunctionalTests/Types/SqliteNumericTypeTest.cs
{ "start": 410, "end": 607 }
public class ____ : SqliteTypeFixture<byte> { public override byte Value { get; } = byte.MinValue; public override byte OtherValue { get; } = byte.MaxValue; } }
ByteTypeFixture
csharp
dotnet__maui
src/Controls/src/Core/PlatformConfiguration/iOSSpecific/TimePicker.cs
{ "start": 363, "end": 1973 }
public static class ____ { /// <summary>Bindable property for <see cref="UpdateMode"/>.</summary> public static readonly BindableProperty UpdateModeProperty = BindableProperty.Create( nameof(UpdateMode), typeof(UpdateMode), typeof(TimePicker), default(UpdateMode)); /// <include file="../../../../docs/Microsoft.Maui.Controls.PlatformConfiguration.iOSSpecific/TimePicker.xml" path="//Member[@MemberName='GetUpdateMode']/Docs/*" /> public static UpdateMode GetUpdateMode(BindableObject element) { return (UpdateMode)element.GetValue(UpdateModeProperty); } /// <include file="../../../../docs/Microsoft.Maui.Controls.PlatformConfiguration.iOSSpecific/TimePicker.xml" path="//Member[@MemberName='SetUpdateMode'][1]/Docs/*" /> public static void SetUpdateMode(BindableObject element, UpdateMode value) { element.SetValue(UpdateModeProperty, value); } /// <include file="../../../../docs/Microsoft.Maui.Controls.PlatformConfiguration.iOSSpecific/TimePicker.xml" path="//Member[@MemberName='UpdateMode']/Docs/*" /> public static UpdateMode UpdateMode(this IPlatformElementConfiguration<iOS, FormsElement> config) { return GetUpdateMode(config.Element); } /// <include file="../../../../docs/Microsoft.Maui.Controls.PlatformConfiguration.iOSSpecific/TimePicker.xml" path="//Member[@MemberName='SetUpdateMode'][2]/Docs/*" /> public static IPlatformElementConfiguration<iOS, FormsElement> SetUpdateMode(this IPlatformElementConfiguration<iOS, FormsElement> config, UpdateMode value) { SetUpdateMode(config.Element, value); return config; } } }
TimePicker
csharp
ServiceStack__ServiceStack
ServiceStack.Azure/src/ServiceStack.Azure/Messaging/ServiceBusMqMessageFactory.cs
{ "start": 428, "end": 8540 }
public class ____ : IMessageFactory { private long timesStarted; private long doOperation = WorkerOperation.NoOp; private long noOfErrors = 0; private int noOfContinuousErrors = 0; private string lastExMsg = null; #if NETCORE public Action<Microsoft.Azure.ServiceBus.Message,IMessage> PublishMessageFilter { get; set; } #else public Action<BrokeredMessage,IMessage> PublishMessageFilter { get; set; } #endif protected internal readonly string address; #if !NETCORE protected internal readonly NamespaceManager namespaceManager; #else protected internal readonly ManagementClient managementClient; #endif internal Dictionary<Type, IMessageHandlerFactory> handlerMap; Dictionary<string, Type> queueMap; // A list of all Service Bus QueueClients - one per type & queue (priorityq, inq, outq, and dlq) private static readonly ConcurrentDictionary<string, QueueClient> sbClients = new(); public ServiceBusMqServer MqServer { get; } public ServiceBusMqMessageFactory(ServiceBusMqServer mqServer, string address) { this.MqServer = mqServer; this.address = address; #if !NETCORE this.namespaceManager = NamespaceManager.CreateFromConnectionString(address); #else this.managementClient = new ManagementClient(address); #endif } public IMessageProducer CreateMessageProducer() { return new ServiceBusMqMessageProducer(this) { PublishMessageFilter = PublishMessageFilter, }; } public IMessageQueueClient CreateMessageQueueClient() { return new ServiceBusMqClient(this); } public IMessageHandler GetMessageHandler(Type msgType) { var messageHandlerFactory = handlerMap[msgType]; var messageHandler = messageHandlerFactory.CreateMessageHandler(); return messageHandler; } public void Dispose() { this.status = WorkerStatus.Disposed; } protected internal void StartQueues(Dictionary<Type, IMessageHandlerFactory> handlerMap, Dictionary<Type, int> handlerThreadCountMap) { this.status = WorkerStatus.Starting; // Create queues for each registered type this.handlerMap = handlerMap; queueMap = new Dictionary<string, Type>(); var mqSuffixes = new[] {".inq", ".outq", ".priorityq", ".dlq"}; foreach (var type in this.handlerMap.Keys) { foreach (var mqSuffix in mqSuffixes) { var queueName = QueueNames.ResolveQueueNameFn(type.Name, mqSuffix); queueName = queueName.SafeQueueName()!; if (!queueMap.ContainsKey(queueName)) queueMap.Add(queueName, type); var mqDesc = new QueueDescription(queueName); #if !NETCORE if (!namespaceManager.QueueExists(queueName)) namespaceManager.CreateQueue(mqDesc); #else // Prefer GetAwaiter().GetResult() so that the StackTrace // is easier to use, see: // https://stackoverflow.com/a/36427080 if (!managementClient.QueueExistsAsync(mqDesc.Path).GetAwaiter().GetResult()) managementClient.CreateQueueAsync(mqDesc).GetAwaiter().GetResult(); #endif } var mqNames = new QueueNames(type); AddQueueHandler(type, mqNames.In, handlerThreadCountMap[type]); AddQueueHandler(type, mqNames.Priority, handlerThreadCountMap[type]); } this.status = WorkerStatus.Started; } List<ServiceBusMqWorker> workers = new(); private void AddQueueHandler(Type queueType, string queueName, int threadCount=1) { queueName = queueName.SafeQueueName()!; #if NETCORE var sbClient = new QueueClient(address, queueName, ReceiveMode.PeekLock); var messageHandler = this.GetMessageHandler(queueType); var sbWorker = new ServiceBusMqWorker(messageHandler, CreateMessageQueueClient(), queueName, sbClient); workers.Add(sbWorker); sbClient.RegisterMessageHandler(sbWorker.HandleMessageAsync, new MessageHandlerOptions( (eventArgs) => Task.CompletedTask) { MaxConcurrentCalls = threadCount, AutoComplete = false }); #else var sbClient = QueueClient.CreateFromConnectionString(address, queueName, ReceiveMode.PeekLock); var options = new OnMessageOptions { // Cannot use AutoComplete because our HandleMessage throws errors into SS's handlers; this would // normally release the BrokeredMessage back to the Azure Service Bus queue, which we don't actually want AutoComplete = false, //AutoRenewTimeout = new TimeSpan() MaxConcurrentCalls = threadCount }; var messageHandler = this.GetMessageHandler(queueType); var sbWorker = new ServiceBusMqWorker(messageHandler, CreateMessageQueueClient(), queueName, sbClient); workers.Add(sbWorker); sbClient.OnMessage(sbWorker.HandleMessage, options); #endif sbClients.GetOrAdd(queueName, sbClient); } protected internal void StopQueues() { this.status = WorkerStatus.Stopping; #if NETCORE sbClients.Each(async kvp => await kvp.Value.CloseAsync()); #else sbClients.Each(kvp => kvp.Value.Close()); #endif sbClients.Clear(); this.status = WorkerStatus.Stopped; } protected internal QueueClient GetOrCreateClient(string queueName) { queueName = queueName.SafeQueueName()!; if (sbClients.ContainsKey(queueName)) return sbClients[queueName]; var qd = new QueueDescription(queueName); #if !NETCORE // Create queue on ServiceBus namespace if it doesn't exist if (!namespaceManager.QueueExists(queueName)) { try { namespaceManager.CreateQueue(qd); } catch (MessagingEntityAlreadyExistsException) { /* ignore */ } } var sbClient = QueueClient.CreateFromConnectionString(address, qd.Path); #else if (!managementClient.QueueExistsAsync(queueName).GetAwaiter().GetResult()) { try { managementClient.CreateQueueAsync(qd).GetAwaiter().GetResult(); } catch (MessagingEntityAlreadyExistsException) { /* ignore */ } } var sbClient = new QueueClient(address, queueName); #endif sbClient = sbClients.GetOrAdd(queueName, sbClient); return sbClient; } public IMessageHandlerStats GetStats() { lock (workers) { var total = new MessageHandlerStats("All Handlers"); workers.ForEach(x => total.Add(x.GetStats())); return total; } } int status = 0; public string GetStatus() => WorkerStatus.ToString(status); public string GetStatsDescription() { lock (workers) { var sb = StringBuilderCache.Allocate() .Append("#MQ SERVER STATS:\n"); sb.AppendLine("==============="); sb.AppendLine("Current Status: " + GetStatus()); sb.AppendLine("Listening On: " + string.Join(", ", workers.Select(x => x.QueueName).ToArray())); sb.AppendLine("Times Started: " + Interlocked.CompareExchange(ref timesStarted, 0, 0)); sb.AppendLine("Num of Errors: " + Interlocked.CompareExchange(ref noOfErrors, 0, 0)); sb.AppendLine("Num of Continuous Errors: " + Interlocked.CompareExchange(ref noOfContinuousErrors, 0, 0)); sb.AppendLine("Last ErrorMsg: " + lastExMsg); sb.AppendLine("==============="); foreach (var worker in workers) { sb.AppendLine(worker.MessageHandler.GetStats().ToString()); sb.AppendLine("---------------\n"); } return StringBuilderCache.ReturnAndFree(sb); } } }
ServiceBusMqMessageFactory
csharp
cake-build__cake
src/Cake.Common/Build/AzurePipelines/IAzurePipelinesCommands.cs
{ "start": 1080, "end": 1308 }
record ____ current task. /// </summary> /// <param name="message">The error message.</param> void WriteError(string message); /// <summary> /// Log an error with detailed data to timeline
of
csharp
dotnet__aspnetcore
src/Validation/src/IValidatableInfoResolver.cs
{ "start": 506, "end": 1690 }
public interface ____ { /// <summary> /// Gets validation information for the specified type. /// </summary> /// <param name="type">The type to get validation information for.</param> /// <param name="validatableInfo"> /// When this method returns, contains the validatable information if found. /// </param> /// <returns><see langword="true" /> if the validatable type information was found; otherwise, <see langword="false" />.</returns> bool TryGetValidatableTypeInfo(Type type, [NotNullWhen(true)] out IValidatableInfo? validatableInfo); /// <summary> /// Gets validation information for the specified parameter. /// </summary> /// <param name="parameterInfo">The parameter to get validation information for.</param> /// <param name="validatableInfo">When this method returns, contains the validatable information if found.</param> /// <returns><see langword="true" /> if the validatable parameter information was found; otherwise, <see langword="false" />.</returns> bool TryGetValidatableParameterInfo(ParameterInfo parameterInfo, [NotNullWhen(true)] out IValidatableInfo? validatableInfo); }
IValidatableInfoResolver
csharp
smartstore__Smartstore
src/Smartstore.Core/Platform/DataExchange/Domain/DataExchangeEnums.cs
{ "start": 121, "end": 549 }
public enum ____ { /// <summary> /// No abortion. Go on with processing. /// </summary> None = 0, /// <summary> /// Break item processing but not the rest of the execution. Typically used for demo limitations. /// </summary> Soft, /// <summary> /// Break processing immediately. /// </summary> Hard }
DataExchangeAbortion
csharp
PrismLibrary__Prism
src/Wpf/Prism.Wpf/Modularity/ModuleCatalog.cs
{ "start": 1187, "end": 1545 }
public class ____ : ModuleCatalogBase, IModuleGroupsCatalog { /// <summary> /// Initializes a new instance of the <see cref="ModuleCatalog"/> class. /// </summary> public ModuleCatalog() : base() { } /// <summary> /// Initializes a new instance of the <see cref="ModuleCatalog"/>
ModuleCatalog
csharp
NLog__NLog
tests/NLog.UnitTests/Conditions/ConditionParserTests.cs
{ "start": 12974, "end": 13144 }
public class ____ { public static bool CheckIt(string s) { return s == "X"; } } } }
MyConditionMethods
csharp
louthy__language-ext
LanguageExt.Core/DataTypes/Record/RecordType.cs
{ "start": 1835, "end": 2173 }
internal static class ____<A> { internal static readonly bool IncludeBase; static RecordTypeIncludeBase() => IncludeBase = !typeof(A).CustomAttributes .AsIterable() .Exists(a => a.AttributeType.Name == nameof(IgnoreBaseAttribute)); }
RecordTypeIncludeBase
csharp
EventStore__EventStore
src/KurrentDB.Core.Tests/Services/UserManagementService/user_management_service.cs
{ "start": 15090, "end": 16440 }
public class ____<TLogFormat, TStreamId> : TestFixtureWithUserManagementService<TLogFormat, TStreamId> { protected override IEnumerable<WhenStep> GivenCommands() { var replyTo = Envelope; yield return new UserManagementMessage.Create( replyTo, SystemAccounts.System, "user1", "John Doe", new[] { "admin", "other" }, "Johny123!"); yield return new UserManagementMessage.Disable(replyTo, SystemAccounts.System, "user1"); } protected override IEnumerable<WhenStep> When() { yield return new UserManagementMessage.Update( Envelope, SystemAccounts.System, "user1", "Doe John", new[] { "good" }); } [Test] public void replies_success() { var updateResults = HandledMessages.OfType<UserManagementMessage.UpdateResult>().ToList(); Assert.AreEqual(1, updateResults.Count); Assert.IsTrue(updateResults[0].Success); } [Test] public void does_not_update_enabled() { _users.Handle(new UserManagementMessage.Get(Envelope, SystemAccounts.System, "user1")); _queue.Process(); var user = HandledMessages.OfType<UserManagementMessage.UserDetailsResult>().SingleOrDefault(); Assert.NotNull(user); Assert.AreEqual(true, user.Data.Disabled); } } [TestFixture(typeof(LogFormat.V2), typeof(string))] [TestFixture(typeof(LogFormat.V3), typeof(uint))]
when_updating_a_disabled_user_account_details
csharp
dotnet__aspnetcore
src/Middleware/ResponseCaching/src/ResponseCachingMiddleware.cs
{ "start": 511, "end": 19770 }
public class ____ { private static readonly TimeSpan DefaultExpirationTimeSpan = TimeSpan.FromSeconds(10); // see https://tools.ietf.org/html/rfc7232#section-4.1 private static readonly string[] HeadersToIncludeIn304 = new[] { "Cache-Control", "Content-Location", "Date", "ETag", "Expires", "Vary" }; private readonly RequestDelegate _next; private readonly ResponseCachingOptions _options; private readonly ILogger _logger; private readonly IResponseCachingPolicyProvider _policyProvider; private readonly IResponseCache _cache; private readonly IResponseCachingKeyProvider _keyProvider; /// <summary> /// Creates a new <see cref="ResponseCachingMiddleware"/>. /// </summary> /// <param name="next">The <see cref="RequestDelegate"/> representing the next middleware in the pipeline.</param> /// <param name="options">The options for this middleware.</param> /// <param name="loggerFactory">The <see cref="ILoggerFactory"/> used for logging.</param> /// <param name="poolProvider">The <see cref="ObjectPoolProvider"/> used for creating <see cref="ObjectPool"/> instances.</param> public ResponseCachingMiddleware( RequestDelegate next, IOptions<ResponseCachingOptions> options, ILoggerFactory loggerFactory, ObjectPoolProvider poolProvider) : this( next, options, loggerFactory, new ResponseCachingPolicyProvider(), new MemoryResponseCache(new MemoryCache(new MemoryCacheOptions { SizeLimit = options.Value.SizeLimit })), new ResponseCachingKeyProvider(poolProvider, options)) { } // for testing internal ResponseCachingMiddleware( RequestDelegate next, IOptions<ResponseCachingOptions> options, ILoggerFactory loggerFactory, IResponseCachingPolicyProvider policyProvider, IResponseCache cache, IResponseCachingKeyProvider keyProvider) { ArgumentNullException.ThrowIfNull(next); ArgumentNullException.ThrowIfNull(options); ArgumentNullException.ThrowIfNull(loggerFactory); ArgumentNullException.ThrowIfNull(policyProvider); ArgumentNullException.ThrowIfNull(cache); ArgumentNullException.ThrowIfNull(keyProvider); _next = next; _options = options.Value; _logger = loggerFactory.CreateLogger<ResponseCachingMiddleware>(); _policyProvider = policyProvider; _cache = cache; _keyProvider = keyProvider; } /// <summary> /// Invokes the logic of the middleware. /// </summary> /// <param name="httpContext">The <see cref="HttpContext"/>.</param> /// <returns>A <see cref="Task"/> that completes when the middleware has completed processing.</returns> public async Task Invoke(HttpContext httpContext) { var context = new ResponseCachingContext(httpContext, _logger); // Should we attempt any caching logic? if (_policyProvider.AttemptResponseCaching(context)) { // Can this request be served from cache? if (_policyProvider.AllowCacheLookup(context) && await TryServeFromCacheAsync(context)) { return; } // Should we store the response to this request? if (_policyProvider.AllowCacheStorage(context)) { // Hook up to listen to the response stream ShimResponseStream(context); try { await _next(httpContext); // If there was no response body, check the response headers now. We can cache things like redirects. StartResponse(context); // Finalize the cache entry FinalizeCacheBody(context); } finally { UnshimResponseStream(context); } return; } } // Response should not be captured but add IResponseCachingFeature which may be required when the response is generated AddResponseCachingFeature(httpContext); try { await _next(httpContext); } finally { RemoveResponseCachingFeature(httpContext); } } internal async Task<bool> TryServeCachedResponseAsync(ResponseCachingContext context, IResponseCacheEntry? cacheEntry) { if (!(cacheEntry is CachedResponse cachedResponse)) { return false; } context.CachedResponse = cachedResponse; context.CachedResponseHeaders = cachedResponse.Headers; context.ResponseTime = _options.TimeProvider.GetUtcNow(); var cachedEntryAge = context.ResponseTime.Value - context.CachedResponse.Created; context.CachedEntryAge = cachedEntryAge > TimeSpan.Zero ? cachedEntryAge : TimeSpan.Zero; if (_policyProvider.IsCachedEntryFresh(context)) { // Check conditional request rules if (ContentIsNotModified(context)) { _logger.NotModifiedServed(); context.HttpContext.Response.StatusCode = StatusCodes.Status304NotModified; if (context.CachedResponseHeaders != null) { foreach (var key in HeadersToIncludeIn304) { if (context.CachedResponseHeaders.TryGetValue(key, out var values)) { context.HttpContext.Response.Headers[key] = values; } } } } else { var response = context.HttpContext.Response; // Copy the cached status code and response headers response.StatusCode = context.CachedResponse.StatusCode; foreach (var header in context.CachedResponse.Headers) { response.Headers[header.Key] = header.Value; } // Note: int64 division truncates result and errors may be up to 1 second. This reduction in // accuracy of age calculation is considered appropriate since it is small compared to clock // skews and the "Age" header is an estimate of the real age of cached content. response.Headers.Age = HeaderUtilities.FormatNonNegativeInt64(context.CachedEntryAge.Value.Ticks / TimeSpan.TicksPerSecond); // Copy the cached response body var body = context.CachedResponse.Body; if (body.Length > 0) { try { await body.CopyToAsync(response.BodyWriter, context.HttpContext.RequestAborted); } catch (OperationCanceledException) { context.HttpContext.Abort(); } } _logger.CachedResponseServed(); } return true; } return false; } internal async Task<bool> TryServeFromCacheAsync(ResponseCachingContext context) { context.BaseKey = _keyProvider.CreateBaseKey(context); var cacheEntry = _cache.Get(context.BaseKey); if (cacheEntry is CachedVaryByRules cachedVaryByRules) { // Request contains vary rules, recompute key(s) and try again context.CachedVaryByRules = cachedVaryByRules; foreach (var varyKey in _keyProvider.CreateLookupVaryByKeys(context)) { if (await TryServeCachedResponseAsync(context, _cache.Get(varyKey))) { return true; } } } else { if (await TryServeCachedResponseAsync(context, cacheEntry)) { return true; } } if (HeaderUtilities.ContainsCacheDirective(context.HttpContext.Request.Headers.CacheControl, CacheControlHeaderValue.OnlyIfCachedString)) { _logger.GatewayTimeoutServed(); context.HttpContext.Response.StatusCode = StatusCodes.Status504GatewayTimeout; return true; } _logger.NoResponseServed(); return false; } /// <summary> /// Finalize cache headers. /// </summary> /// <param name="context"></param> /// <returns><c>true</c> if a vary by entry needs to be stored in the cache; otherwise <c>false</c>.</returns> private bool OnFinalizeCacheHeaders(ResponseCachingContext context) { if (_policyProvider.IsResponseCacheable(context)) { var storeVaryByEntry = false; context.ShouldCacheResponse = true; // Create the cache entry now var response = context.HttpContext.Response; var headers = response.Headers; var varyHeaders = new StringValues(headers.GetCommaSeparatedValues(HeaderNames.Vary)); var varyQueryKeys = new StringValues(context.HttpContext.Features.Get<IResponseCachingFeature>()?.VaryByQueryKeys); context.CachedResponseValidFor = context.ResponseSharedMaxAge ?? context.ResponseMaxAge ?? (context.ResponseExpires - context.ResponseTime!.Value) ?? DefaultExpirationTimeSpan; // Generate a base key if none exist if (string.IsNullOrEmpty(context.BaseKey)) { context.BaseKey = _keyProvider.CreateBaseKey(context); } // Check if any vary rules exist if (!StringValues.IsNullOrEmpty(varyHeaders) || !StringValues.IsNullOrEmpty(varyQueryKeys)) { // Normalize order and casing of vary by rules var normalizedVaryHeaders = GetOrderCasingNormalizedStringValues(varyHeaders); var normalizedVaryQueryKeys = GetOrderCasingNormalizedStringValues(varyQueryKeys); // Update vary rules if they are different if (context.CachedVaryByRules == null || !StringValues.Equals(context.CachedVaryByRules.QueryKeys, normalizedVaryQueryKeys) || !StringValues.Equals(context.CachedVaryByRules.Headers, normalizedVaryHeaders)) { context.CachedVaryByRules = new CachedVaryByRules { VaryByKeyPrefix = FastGuid.NewGuid().IdString, Headers = normalizedVaryHeaders, QueryKeys = normalizedVaryQueryKeys }; } // Always overwrite the CachedVaryByRules to update the expiry information _logger.VaryByRulesUpdated(normalizedVaryHeaders.ToString(), normalizedVaryQueryKeys.ToString()); storeVaryByEntry = true; context.StorageVaryKey = _keyProvider.CreateStorageVaryByKey(context); } // Ensure date header is set if (!context.ResponseDate.HasValue) { context.ResponseDate = context.ResponseTime!.Value; // Setting the date on the raw response headers. headers.Date = HeaderUtilities.FormatDate(context.ResponseDate.Value); } // Store the response on the state context.CachedResponse = new CachedResponse { Created = context.ResponseDate.Value, StatusCode = response.StatusCode, Headers = new HeaderDictionary() }; foreach (var header in headers) { if (!string.Equals(header.Key, HeaderNames.Age, StringComparison.OrdinalIgnoreCase)) { context.CachedResponse.Headers[header.Key] = header.Value; } } return storeVaryByEntry; } context.ResponseCachingStream.DisableBuffering(); return false; } internal void FinalizeCacheHeaders(ResponseCachingContext context) { if (OnFinalizeCacheHeaders(context)) { _cache.Set(context.BaseKey, context.CachedVaryByRules, context.CachedResponseValidFor); } } internal void FinalizeCacheBody(ResponseCachingContext context) { if (context.ShouldCacheResponse && context.ResponseCachingStream.BufferingEnabled) { var contentLength = context.HttpContext.Response.ContentLength; var cachedResponseBody = context.ResponseCachingStream.GetCachedResponseBody(); if (!contentLength.HasValue || contentLength == cachedResponseBody.Length || (cachedResponseBody.Length == 0 && HttpMethods.IsHead(context.HttpContext.Request.Method))) { var response = context.HttpContext.Response; // Add a content-length if required if (!response.ContentLength.HasValue && StringValues.IsNullOrEmpty(response.Headers.TransferEncoding)) { context.CachedResponse.Headers.ContentLength = cachedResponseBody.Length; } context.CachedResponse.Body = cachedResponseBody; _logger.ResponseCached(); _cache.Set(context.StorageVaryKey ?? context.BaseKey, context.CachedResponse, context.CachedResponseValidFor); } else { _logger.ResponseContentLengthMismatchNotCached(); } } else { _logger.LogResponseNotCached(); } } /// <summary> /// Mark the response as started and set the response time if no response was started yet. /// </summary> /// <param name="context"></param> /// <returns><c>true</c> if the response was not started before this call; otherwise <c>false</c>.</returns> private bool OnStartResponse(ResponseCachingContext context) { if (!context.ResponseStarted) { context.ResponseStarted = true; context.ResponseTime = _options.TimeProvider.GetUtcNow(); return true; } return false; } internal void StartResponse(ResponseCachingContext context) { if (OnStartResponse(context)) { FinalizeCacheHeaders(context); } } internal static void AddResponseCachingFeature(HttpContext context) { if (context.Features.Get<IResponseCachingFeature>() != null) { throw new InvalidOperationException($"Another instance of {nameof(ResponseCachingFeature)} already exists. Only one instance of {nameof(ResponseCachingMiddleware)} can be configured for an application."); } context.Features.Set<IResponseCachingFeature>(new ResponseCachingFeature()); } internal void ShimResponseStream(ResponseCachingContext context) { // Shim response stream context.OriginalResponseStream = context.HttpContext.Response.Body; context.ResponseCachingStream = new ResponseCachingStream( context.OriginalResponseStream, _options.MaximumBodySize, StreamUtilities.BodySegmentSize, () => StartResponse(context)); context.HttpContext.Response.Body = context.ResponseCachingStream; // Add IResponseCachingFeature AddResponseCachingFeature(context.HttpContext); } internal static void RemoveResponseCachingFeature(HttpContext context) => context.Features.Set<IResponseCachingFeature?>(null); internal static void UnshimResponseStream(ResponseCachingContext context) { // Unshim response stream context.HttpContext.Response.Body = context.OriginalResponseStream; // Remove IResponseCachingFeature RemoveResponseCachingFeature(context.HttpContext); } internal static bool ContentIsNotModified(ResponseCachingContext context) { var cachedResponseHeaders = context.CachedResponseHeaders; var ifNoneMatchHeader = context.HttpContext.Request.Headers.IfNoneMatch; if (!StringValues.IsNullOrEmpty(ifNoneMatchHeader)) { if (ifNoneMatchHeader.Count == 1 && StringSegment.Equals(ifNoneMatchHeader[0], EntityTagHeaderValue.Any.Tag, StringComparison.OrdinalIgnoreCase)) { context.Logger.NotModifiedIfNoneMatchStar(); return true; } EntityTagHeaderValue? eTag; if (!StringValues.IsNullOrEmpty(cachedResponseHeaders.ETag) && EntityTagHeaderValue.TryParse(cachedResponseHeaders.ETag.ToString(), out eTag) && EntityTagHeaderValue.TryParseList(ifNoneMatchHeader, out var ifNoneMatchEtags)) { for (var i = 0; i < ifNoneMatchEtags.Count; i++) { var requestETag = ifNoneMatchEtags[i]; if (eTag.Compare(requestETag, useStrongComparison: false)) { context.Logger.NotModifiedIfNoneMatchMatched(requestETag); return true; } } } } else { var ifModifiedSince = context.HttpContext.Request.Headers.IfModifiedSince; if (!StringValues.IsNullOrEmpty(ifModifiedSince)) { DateTimeOffset modified; if (!HeaderUtilities.TryParseDate(cachedResponseHeaders.LastModified.ToString(), out modified) && !HeaderUtilities.TryParseDate(cachedResponseHeaders.Date.ToString(), out modified)) { return false; } DateTimeOffset modifiedSince; if (HeaderUtilities.TryParseDate(ifModifiedSince.ToString(), out modifiedSince) && modified <= modifiedSince) { context.Logger.NotModifiedIfModifiedSinceSatisfied(modified, modifiedSince); return true; } } } return false; } // Normalize order and casing internal static StringValues GetOrderCasingNormalizedStringValues(StringValues stringValues) { if (stringValues.Count == 1) { return new StringValues(stringValues.ToString().ToUpperInvariant()); } else { var originalArray = stringValues.ToArray(); var newArray = new string[originalArray.Length]; for (var i = 0; i < originalArray.Length; i++) { newArray[i] = originalArray[i]!.ToUpperInvariant(); } // Since the casing has already been normalized, use Ordinal comparison Array.Sort(newArray, StringComparer.Ordinal); return new StringValues(newArray); } } }
ResponseCachingMiddleware
csharp
MassTransit__MassTransit
src/MassTransit.Abstractions/Contracts/ReceiveEndpointCompleted.cs
{ "start": 29, "end": 435 }
public interface ____ : ReceiveEndpointEvent { /// <summary> /// The number of messages delivered to the receive endpoint /// </summary> long DeliveryCount { get; } /// <summary> /// The maximum concurrent messages delivery to the receive endpoint /// </summary> long ConcurrentDeliveryCount { get; } } }
ReceiveEndpointCompleted
csharp
dotnet__maui
src/Graphics/samples/GraphicsTester.Portable/Scenarios/DrawTextRotatedAtPoint.cs
{ "start": 70, "end": 1614 }
public class ____ : AbstractScenario { public DrawTextRotatedAtPoint() : base(1024, 720) { } public override void Draw(ICanvas canvas) { canvas.SaveState(); canvas.Rotate(90, 360, 640); canvas.StrokeColor = Colors.Blue; canvas.StrokeSize = 1f; canvas.FontColor = Colors.Red; canvas.FontSize = 12f; canvas.DrawLine(50, 50, 250, 50); canvas.DrawString("Red - Align Left", 50, 50, HorizontalAlignment.Left); canvas.DrawLine(50, 100, 250, 100); canvas.DrawString("Red - Align Center", 150, 100, HorizontalAlignment.Center); canvas.DrawLine(50, 150, 250, 150); canvas.DrawString("Red - Align Right", 250, 150, HorizontalAlignment.Right); canvas.SaveState(); canvas.SetShadow(CanvasDefaults.DefaultShadowOffset, CanvasDefaults.DefaultShadowBlur, CanvasDefaults.DefaultShadowColor); canvas.DrawString("Red - Shadowed", 50, 200, HorizontalAlignment.Left); canvas.RestoreState(); var blurrableCanvas = canvas as IBlurrableCanvas; if (blurrableCanvas != null) { canvas.SaveState(); blurrableCanvas.SetBlur(CanvasDefaults.DefaultShadowBlur); canvas.DrawString("Red - Shadowed", 50, 250, HorizontalAlignment.Left); canvas.RestoreState(); } canvas.SaveState(); canvas.Font = Font.DefaultBold; canvas.DrawString("Bold System Font", 50, 350, HorizontalAlignment.Left); canvas.Font = Font.Default; canvas.DrawString("System Font", 50, 400, HorizontalAlignment.Left); canvas.RestoreState(); canvas.RestoreState(); } } }
DrawTextRotatedAtPoint
csharp
dotnet__efcore
src/EFCore.Relational/Extensions/RelationalElementTypeBuilderExtensions.cs
{ "start": 474, "end": 6754 }
public static class ____ { /// <summary> /// Configures the data type of the elements of the collection. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information and examples. /// </remarks> /// <param name="elementTypeBuilder">The builder for the elements being configured.</param> /// <param name="typeName">The name of the data type of the elements.</param> /// <returns>The same builder instance so that multiple calls can be chained.</returns> public static ElementTypeBuilder HasStoreType( this ElementTypeBuilder elementTypeBuilder, string? typeName) { Check.NullButNotEmpty(typeName); elementTypeBuilder.Metadata.SetStoreType(typeName); return elementTypeBuilder; } /// <summary> /// Configures the data type of the elements of the collection. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information and examples. /// </remarks> /// <param name="elementTypeBuilder"> builder for the elements being configured.</param> /// <param name="typeName">The name of the data type of the elements.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns>The same builder instance if the configuration was applied, <see langword="null" /> otherwise.</returns> public static IConventionElementTypeBuilder? HasStoreType( this IConventionElementTypeBuilder elementTypeBuilder, string? typeName, bool fromDataAnnotation = false) { if (!elementTypeBuilder.CanSetStoreType(typeName, fromDataAnnotation)) { return null; } elementTypeBuilder.Metadata.SetStoreType(typeName, fromDataAnnotation); return elementTypeBuilder; } /// <summary> /// Returns a value indicating whether the given data type can be set for the elements. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information and examples. /// </remarks> /// <param name="elementTypeBuilder"> builder for the elements being configured.</param> /// <param name="typeName">The name of the data type of the elements.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns><see langword="true" /> if the given data type can be set for the property.</returns> public static bool CanSetStoreType( this IConventionElementTypeBuilder elementTypeBuilder, string? typeName, bool fromDataAnnotation = false) => elementTypeBuilder.CanSetAnnotation(RelationalAnnotationNames.StoreType, typeName, fromDataAnnotation); /// <summary> /// Configures the elements as capable of storing only fixed-length data, such as strings. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information and examples. /// </remarks> /// <param name="elementTypeBuilder">The builder for the elements being configured.</param> /// <param name="fixedLength">A value indicating whether the elements are constrained to fixed length values.</param> /// <returns>The same builder instance so that multiple configuration calls can be chained.</returns> public static ElementTypeBuilder IsFixedLength( this ElementTypeBuilder elementTypeBuilder, bool fixedLength = true) { elementTypeBuilder.Metadata.SetIsFixedLength(fixedLength); return elementTypeBuilder; } /// <summary> /// Configures the elements as capable of storing only fixed-length data, such as strings. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information and examples. /// </remarks> /// <param name="elementTypeBuilder"> builder for the elements being configured.</param> /// <param name="fixedLength">A value indicating whether the elements are constrained to fixed length values.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns> The same builder instance if the configuration was applied, <see langword="null" /> otherwise.</returns> public static IConventionElementTypeBuilder? IsFixedLength( this IConventionElementTypeBuilder elementTypeBuilder, bool? fixedLength, bool fromDataAnnotation = false) { if (!elementTypeBuilder.CanSetFixedLength(fixedLength, fromDataAnnotation)) { return null; } elementTypeBuilder.Metadata.SetIsFixedLength(fixedLength, fromDataAnnotation); return elementTypeBuilder; } /// <summary> /// Returns a value indicating whether the elements can be configured as being fixed length or not. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-modeling">Modeling entity types and relationships</see> for more information and examples. /// </remarks> /// <param name="elementTypeBuilder"> builder for the elements being configured.</param> /// <param name="fixedLength">A value indicating whether the elements are constrained to fixed length values.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns><see langword="true" /> if the elements can be configured as being fixed length or not.</returns> public static bool CanSetFixedLength( this IConventionElementTypeBuilder elementTypeBuilder, bool? fixedLength, bool fromDataAnnotation = false) => elementTypeBuilder.CanSetAnnotation(RelationalAnnotationNames.IsFixedLength, fixedLength, fromDataAnnotation); }
RelationalElementTypeBuilderExtensions
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp/ObjectComparators/ObjectComparatorBase.cs
{ "start": 2502, "end": 3311 }
public abstract class ____<TBaseType, TEnumCompareTypes> : ObjectComparatorBase<TBaseType> where TEnumCompareTypes : Enum { public override ImmutableList<string> CompareTypes { get; } protected ObjectComparatorBase() { CompareTypes = Enum.GetNames(typeof(TEnumCompareTypes)).ToImmutableList(); } protected abstract bool Compare(TBaseType baseObject, TBaseType compareObject, TEnumCompareTypes compareType); protected sealed override bool Compare(TBaseType baseObject, TBaseType compareObject, string compareType) { var compareTypeEnum = (TEnumCompareTypes)Enum.Parse(typeof(TEnumCompareTypes), compareType); return Compare(baseObject, compareObject, compareTypeEnum); } } }
ObjectComparatorBase
csharp
dotnet__reactive
Rx.NET/Samples/RxRemoteMouseMoves/RxMouseServer/Program.cs
{ "start": 124, "end": 1195 }
partial class ____ { [STAThread] static void Main(string[] args) { Console.WriteLine("Server"); int port; ParseArgs(args, out port); var observer = Remoting(port); var frm = new Form(); frm.Load += (o, e) => { var g = frm.CreateGraphics(); var mme = (from mm in Observable.FromEventPattern<MouseEventArgs>(frm, "MouseMove") select mm.EventArgs.Location) .DistinctUntilChanged() .Do(pt => { g.DrawEllipse(Pens.Red, pt.X, pt.Y, 1, 1); }); mme.Subscribe(observer); }; Application.Run(frm); } static void ParseArgs(string[] args, out int port) { port = 9090; if (args.Length == 1) { port = int.Parse(args[0]); } } } }
Program
csharp
OrchardCMS__OrchardCore
test/OrchardCore.Tests/DisplayManagement/CompositeTests.cs
{ "start": 1355, "end": 1467 }
public class ____ : Composite { public string Kind { get; set; } public string Color { get; set; } }
Animal
csharp
cake-build__cake
src/Cake.Common.Tests/Unit/Tools/NuGet/Pack/NuGetPackerTests.cs
{ "start": 44021, "end": 58710 }
public sealed class ____ { [Fact] public void Should_Throw_If_Nuspec_File_Path_Is_Null() { // Given var fixture = new NuGetPackerWithProjectFileFixture(); fixture.ProjectFilePath = null; // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsArgumentNullException(result, "filePath"); } [Fact] public void Should_Throw_If_Settings_Is_Null() { // Given var fixture = new NuGetPackerWithProjectFileFixture(); fixture.Settings = null; // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsArgumentNullException(result, "settings"); } [Fact] public void Should_Throw_If_NuGet_Executable_Was_Not_Found() { // Given var fixture = new NuGetPackerWithProjectFileFixture(); fixture.GivenDefaultToolDoNotExist(); // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsCakeException(result, "NuGet: Could not locate executable."); } [Theory] [InlineData("/bin/nuget/nuget.exe", "/bin/nuget/nuget.exe")] [InlineData("./tools/nuget/nuget.exe", "/Working/tools/nuget/nuget.exe")] public void Should_Use_NuGet_Executable_From_Tool_Path_If_Provided(string toolPath, string expected) { // Given var fixture = new NuGetPackerWithProjectFileFixture(); fixture.Settings.ToolPath = toolPath; fixture.GivenSettingsToolPathExist(); // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Path.FullPath); } [WindowsTheory] [InlineData("C:/nuget/nuget.exe", "C:/nuget/nuget.exe")] public void Should_Use_NuGet_Executable_From_Tool_Path_If_Provided_On_Windows(string toolPath, string expected) { // Given var fixture = new NuGetPackerWithProjectFileFixture(); fixture.Settings.ToolPath = toolPath; fixture.GivenSettingsToolPathExist(); // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Path.FullPath); } [Fact] public void Should_Find_NuGet_Executable_If_Tool_Path_Not_Provided() { // Given var fixture = new NuGetPackerWithProjectFileFixture(); // When var result = fixture.Run(); // Then Assert.Equal("/Working/tools/NuGet.exe", result.Path.FullPath); } [Fact] public void Should_Throw_If_Process_Was_Not_Started() { // Given var fixture = new NuGetPackerWithProjectFileFixture(); fixture.GivenProcessCannotStart(); // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsCakeException(result, "NuGet: Process was not started."); } [Fact] public void Should_Throw_If_Process_Has_A_Non_Zero_Exit_Code() { // Given var fixture = new NuGetPackerWithProjectFileFixture(); fixture.GivenProcessExitsWithCode(1); // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsCakeException(result, "NuGet: Process returned an error (exit code 1)."); } [Fact] public void Should_Not_Create_Transformed_Nuspec() { // Given var fixture = new NuGetPackerWithProjectFileFixture(); // When fixture.Run(); // Then Assert.False(fixture.FileSystem.Exist((FilePath)"/Working/existing.temp.nuspec")); } [Fact] public void Should_Add_Version_To_Arguments_If_Not_Null() { // Given var fixture = new NuGetPackerWithProjectFileFixture(); fixture.Settings.Version = "1.0.0"; // When var result = fixture.Run(); // Then Assert.Equal("pack -Version \"1.0.0\" \"/Working/existing.csproj\"", result.Args); } [Fact] public void Should_Add_Base_Path_To_Arguments_If_Not_Null() { // Given var fixture = new NuGetPackerWithProjectFileFixture(); fixture.Settings.BasePath = "./build"; // When var result = fixture.Run(); // Then Assert.Equal("pack -BasePath \"/Working/build\" " + "\"/Working/existing.csproj\"", result.Args); } [Fact] public void Should_Add_Output_Directory_To_Arguments_If_Not_Null() { // Given var fixture = new NuGetPackerWithProjectFileFixture(); fixture.Settings.OutputDirectory = "./build/output"; // When var result = fixture.Run(); // Then Assert.Equal("pack -OutputDirectory \"/Working/build/output\" " + "\"/Working/existing.csproj\"", result.Args); } [Fact] public void Should_Add_No_Package_Analysis_Flag_To_Arguments_If_Set() { // Given var fixture = new NuGetPackerWithProjectFileFixture(); fixture.Settings.NoPackageAnalysis = true; // When var result = fixture.Run(); // Then Assert.Equal("pack \"/Working/existing.csproj\" -NoPackageAnalysis", result.Args); } [Fact] public void Should_Add_IncludeReferencedProjects_Flag_To_Arguments_If_Set() { // Given var fixture = new NuGetPackerWithProjectFileFixture(); fixture.Settings.IncludeReferencedProjects = true; // When var result = fixture.Run(); // Then Assert.Equal("pack \"/Working/existing.csproj\" -IncludeReferencedProjects", result.Args); } [Fact] public void Should_Add_Symbols_Flag_To_Arguments_If_Set() { // Given var fixture = new NuGetPackerWithProjectFileFixture(); fixture.Settings.Symbols = true; // When var result = fixture.Run(); // Then Assert.Equal("pack \"/Working/existing.csproj\" -Symbols", result.Args); } [Fact] public void Should_Add_SymbolPackageFormat_To_Arguments_If_Set() { // Given var fixture = new NuGetPackerWithProjectFileFixture(); fixture.Settings.Symbols = true; fixture.Settings.SymbolPackageFormat = "snupkg"; // When var result = fixture.Run(); // Then Assert.Equal("pack \"/Working/existing.csproj\" -Symbols -SymbolPackageFormat snupkg", result.Args); } [Theory] [InlineData(NuGetVerbosity.Detailed, "pack \"/Working/existing.csproj\" -Verbosity detailed")] [InlineData(NuGetVerbosity.Normal, "pack \"/Working/existing.csproj\" -Verbosity normal")] [InlineData(NuGetVerbosity.Quiet, "pack \"/Working/existing.csproj\" -Verbosity quiet")] public void Should_Add_Verbosity_To_Arguments_If_Set(NuGetVerbosity verbosity, string expected) { // Given var fixture = new NuGetPackerWithProjectFileFixture(); fixture.Settings.Verbosity = verbosity; // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Args); } [Fact] public void Should_Add_Properties_To_Arguments_If_Set() { // Given var fixture = new NuGetPackerWithProjectFileFixture(); fixture.Settings.Properties = new Dictionary<string, string> { { "Configuration", "Release" } }; // When var result = fixture.Run(); // Then Assert.Equal("pack \"/Working/existing.csproj\" -Properties \"Configuration=Release\"", result.Args); } [Fact] public void Should_Separate_Properties_With_Semicolon() { // Given var fixture = new NuGetPackerWithProjectFileFixture(); fixture.Settings.Properties = new Dictionary<string, string> { { "Configuration", "Release" }, { "Foo", "Bar" } }; // When var result = fixture.Run(); // Then Assert.Equal("pack \"/Working/existing.csproj\" -Properties \"Configuration=Release;Foo=Bar\"", result.Args); } [Theory] [InlineData("")] [InlineData(" ")] // We don't need to check for a null key because the dictionary won't allow it in the first place public void Should_Throw_For_Invalid_Properties_Keys(string key) { // Given var fixture = new NuGetPackerWithProjectFileFixture(); fixture.Settings.Properties = new Dictionary<string, string> { { "Configuration", "Release" }, { key, "Bar" } }; // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsCakeException(result, "Properties keys can not be null or empty."); } [Theory] [InlineData(null)] [InlineData("")] [InlineData(" ")] public void Should_Throw_For_Invalid_Properties_Values(string value) { // Given var fixture = new NuGetPackerWithProjectFileFixture(); fixture.Settings.Properties = new Dictionary<string, string> { { "Configuration", "Release" }, { "Foo", value } }; // When var result = Record.Exception(() => fixture.Run()); // Then AssertEx.IsCakeException(result, "Properties values can not be null or empty."); } [Theory] [InlineData(NuGetMSBuildVersion.MSBuild4, "pack \"/Working/existing.csproj\" -MSBuildVersion 4")] [InlineData(NuGetMSBuildVersion.MSBuild12, "pack \"/Working/existing.csproj\" -MSBuildVersion 12")] [InlineData(NuGetMSBuildVersion.MSBuild14, "pack \"/Working/existing.csproj\" -MSBuildVersion 14")] [InlineData(NuGetMSBuildVersion.MSBuild15_9, "pack \"/Working/existing.csproj\" -MSBuildVersion 15.9")] [InlineData(NuGetMSBuildVersion.MSBuild16_0, "pack \"/Working/existing.csproj\" -MSBuildVersion 16.0")] public void Should_Add_MSBuildVersion_To_Arguments_If_Set(NuGetMSBuildVersion msBuildVersion, string expected) { // Given var fixture = new NuGetPackerWithProjectFileFixture(); fixture.Settings.MSBuildVersion = msBuildVersion; // When var result = fixture.Run(); // Then Assert.Equal(expected, result.Args); } [Fact] public void Should_Not_Modify_ContentFiles_Element_If_Files_Specified() { // Given var fixture = new NuGetPackerWithNuSpecFixture(); fixture.WithNuSpecXml(Resources.Nuspec_ContentFiles); fixture.Settings.Files = new[] { new NuSpecContent { Source = "Cake.Core.dll", Target = "lib/net45" }, new NuSpecContent { Source = "Cake.Core.xml", Target = "lib/net45" }, new NuSpecContent { Source = "Cake.Core.pdb", Target = "lib/net45" }, new NuSpecContent { Source = "LICENSE" } }; // When var result = fixture.Run(); // Then Assert.Equal( Resources.Nuspec_ContentFiles.NormalizeLineEndings(), result.NuspecContent.NormalizeLineEndings()); } }
WithProjectFile
csharp
duplicati__duplicati
Duplicati/Library/Main/ResultClasses.cs
{ "start": 26461, "end": 26635 }
internal sealed record ____(long Version, DateTime Time, string Path, long Size, bool IsDirectory, bool IsSymlink, DateTime LastModified) : IListFileVersion;
ListFileVersion
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/test/Types.Queries.Tests/CodeFirstSchemaTests.cs
{ "start": 17761, "end": 17862 }
public class ____ { public Task<FieldResult<Foo>> Foo() => null!; }
InvalidQueryTask
csharp
Cysharp__MemoryPack
src/MemoryPack.Core/Formatters/ImmutableCollectionFormatters.cs
{ "start": 27812, "end": 30495 }
public sealed class ____<TKey, TValue> : MemoryPackFormatter<IImmutableDictionary<TKey, TValue?>?> where TKey : notnull { readonly IEqualityComparer<TKey>? keyEqualityComparer; readonly IEqualityComparer<TValue?>? valueEqualityComparer; public InterfaceImmutableDictionaryFormatter() : this(null, null) { } public InterfaceImmutableDictionaryFormatter(IEqualityComparer<TKey>? keyEqualityComparer, IEqualityComparer<TValue?>? valueEqualityComparer) { this.keyEqualityComparer = keyEqualityComparer; this.valueEqualityComparer = valueEqualityComparer; } [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, scoped ref IImmutableDictionary<TKey, TValue?>? value) { if (value == null) { writer.WriteNullCollectionHeader(); return; } var keyFormatter = writer.GetFormatter<TKey>(); var valueFormatter = writer.GetFormatter<TValue>(); writer.WriteCollectionHeader(value.Count); foreach (var item in value) { KeyValuePairFormatter.Serialize(keyFormatter, valueFormatter, ref writer, item!); } } [Preserve] public override void Deserialize(ref MemoryPackReader reader, scoped ref IImmutableDictionary<TKey, TValue?>? value) { if (!reader.TryReadCollectionHeader(out var length)) { value = null; return; } if (length == 0) { if (keyEqualityComparer != null || valueEqualityComparer != null) { value = ImmutableDictionary<TKey, TValue?>.Empty.WithComparers(keyEqualityComparer, valueEqualityComparer); } else { value = ImmutableDictionary<TKey, TValue?>.Empty; } return; } var keyFormatter = reader.GetFormatter<TKey>(); var valueFormatter = reader.GetFormatter<TValue>(); var builder = ImmutableDictionary.CreateBuilder<TKey, TValue?>(keyEqualityComparer, valueEqualityComparer); for (int i = 0; i < length; i++) { KeyValuePairFormatter.Deserialize(keyFormatter, valueFormatter, ref reader, out var k, out var v); builder.Add(k!, v); } value = builder.ToImmutable(); } } [Preserve]
InterfaceImmutableDictionaryFormatter
csharp
npgsql__npgsql
src/Npgsql/NpgsqlNestedDataReader.cs
{ "start": 9461, "end": 12693 }
record ____"); for (var i = 0; i < _compositeType.Fields.Count; i++) { if (_compositeType.Fields[i].Name == name) return i; } for (var i = 0; i < _compositeType.Fields.Count; i++) { if (string.Compare(_compositeType.Fields[i].Name, name, CultureInfo.InvariantCulture, CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase | CompareOptions.IgnoreKanaType) == 0) return i; } throw new IndexOutOfRangeException("Field not found in row: " + name); } /// <inheritdoc /> [UnconditionalSuppressMessage("ILLink", "IL2093", Justification = "No members are dynamically accessed by Npgsql via NpgsqlNestedDataReader.GetFieldType.")] public override Type GetFieldType(int ordinal) { var column = CheckRowAndColumn(ordinal); return column.GetObjectOrDefaultInfo().TypeToConvert; } /// <inheritdoc /> public override object GetValue(int ordinal) { var columnLength = CheckRowAndColumnAndSeek(ordinal, out var column); var info = column.GetObjectOrDefaultInfo(); if (columnLength == -1) return DBNull.Value; using var _ = PgReader.BeginNestedRead(columnLength, info.BufferRequirement); return info.Converter.ReadAsObject(PgReader); } /// <inheritdoc /> public override int GetValues(object[] values) { ArgumentNullException.ThrowIfNull(values); CheckOnRow(); var count = Math.Min(FieldCount, values.Length); for (var i = 0; i < count; i++) values[i] = GetValue(i); return count; } /// <inheritdoc /> public override bool IsDBNull(int ordinal) => CheckRowAndColumnAndSeek(ordinal, out _) == -1; /// <inheritdoc /> public override T GetFieldValue<T>(int ordinal) { if (typeof(T) == typeof(Stream)) return (T)(object)GetStream(ordinal); if (typeof(T) == typeof(TextReader)) return (T)(object)GetTextReader(ordinal); var columnLength = CheckRowAndColumnAndSeek(ordinal, out var column); var info = GetOrAddConverterInfo(typeof(T), column, ordinal, out var asObject); if (columnLength == -1) { // When T is a Nullable<T> (and only in that case), we support returning null if (default(T) is null && typeof(T).IsValueType) return default!; if (typeof(T) == typeof(object)) return (T)(object)DBNull.Value; ThrowHelper.ThrowInvalidCastException_NoValue(); } using var _ = PgReader.BeginNestedRead(columnLength, info.BufferRequirement); return asObject ? (T)info.Converter.ReadAsObject(PgReader)! : info.Converter.UnsafeDowncast<T>().Read(PgReader); } /// <inheritdoc /> public override bool Read() { CheckResultSet(); PgReader.Seek(_nextRowBufferPos); if (_nextRowIndex == _numRows) { _readerState = ReaderState.AfterRows; return false; } if (_nextRowIndex++ != 0) PgReader.ReadInt32(); // Length of
type
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.UI.Input.Inking.Core/CoreWetStrokeDisposition.cs
{ "start": 266, "end": 698 }
public enum ____ { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ Inking = 0, #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ Completed = 1, #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ Canceled = 2, #endif } #endif }
CoreWetStrokeDisposition
csharp
microsoft__PowerToys
src/modules/fancyzones/editor/FancyZonesEditor/Models/MonitorConfigurationTypeEnumExtensions.cs
{ "start": 225, "end": 1231 }
public static class ____ { private const string HorizontalJsonTag = "horizontal"; private const string VerticalJsonTag = "vertical"; public static string TypeToString(this MonitorConfigurationType value) { switch (value) { case MonitorConfigurationType.Horizontal: return HorizontalJsonTag; case MonitorConfigurationType.Vertical: return VerticalJsonTag; } return HorizontalJsonTag; } public static MonitorConfigurationType TypeFromString(string value) { switch (value) { case HorizontalJsonTag: return MonitorConfigurationType.Horizontal; case VerticalJsonTag: return MonitorConfigurationType.Vertical; } return MonitorConfigurationType.Horizontal; } } }
MonitorConfigurationTypeEnumExtensions
csharp
MassTransit__MassTransit
src/MassTransit/SagaStateMachine/SendByConventionExtensions.cs
{ "start": 19521, "end": 20231 }
class ____ TException : Exception { return source.Add(new FaultedSendActivity<TInstance, TException, TMessage>(_ => GetDestinationAddress<TMessage>(), MessageFactory<TMessage>.Create(message, callback))); } public static ExceptionActivityBinder<TInstance, TException> Send<TInstance, TException, TMessage>( this ExceptionActivityBinder<TInstance, TException> source, EventExceptionMessageFactory<TInstance, TException, TMessage> messageFactory, SendExceptionContextCallback<TInstance, TException, TMessage> callback) where TInstance : class, SagaStateMachineInstance where TMessage :
where
csharp
nuke-build__nuke
source/Nuke.Common/Tools/VSWhere/VSWhere.Generated.cs
{ "start": 961, "end": 4598 }
public partial class ____ : ToolTasks, IRequireNuGetPackage { public static string VSWherePath { get => new VSWhereTasks().GetToolPathInternal(); set => new VSWhereTasks().SetToolPath(value); } public const string PackageId = "vswhere"; public const string PackageExecutable = "vswhere.exe"; /// <summary><p>VSWhere is designed to be a redistributable, single-file executable that can be used in build or deployment scripts to find where Visual Studio - or other products in the Visual Studio family - is located.</p><p>For more details, visit the <a href="https://github.com/Microsoft/vswhere">official website</a>.</p></summary> public static IReadOnlyCollection<Output> VSWhere(ArgumentStringHandler arguments, string workingDirectory = null, IReadOnlyDictionary<string, string> environmentVariables = null, int? timeout = null, bool? logOutput = null, bool? logInvocation = null, Action<OutputType, string> logger = null, Func<IProcess, object> exitHandler = null) => new VSWhereTasks().Run(arguments, workingDirectory, environmentVariables, timeout, logOutput, logInvocation, logger, exitHandler); /// <summary><p>VSWhere is designed to be a redistributable, single-file executable that can be used in build or deployment scripts to find where Visual Studio - or other products in the Visual Studio family - is located.</p><p>For more details, visit the <a href="https://github.com/Microsoft/vswhere">official website</a>.</p></summary> /// <remarks><p>This is a <a href="https://www.nuke.build/docs/common/cli-tools/#fluent-api">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p><ul><li><c>-all</c> via <see cref="VSWhereSettings.All"/></li><li><c>-format</c> via <see cref="VSWhereSettings.Format"/></li><li><c>-latest</c> via <see cref="VSWhereSettings.Latest"/></li><li><c>-legacy</c> via <see cref="VSWhereSettings.Legacy"/></li><li><c>-nologo</c> via <see cref="VSWhereSettings.NoLogo"/></li><li><c>-prerelease</c> via <see cref="VSWhereSettings.Prerelease"/></li><li><c>-products</c> via <see cref="VSWhereSettings.Products"/></li><li><c>-property</c> via <see cref="VSWhereSettings.Property"/></li><li><c>-requires</c> via <see cref="VSWhereSettings.Requires"/></li><li><c>-requiresAny</c> via <see cref="VSWhereSettings.RequiresAny"/></li><li><c>-utf8</c> via <see cref="VSWhereSettings.UTF8"/></li><li><c>-version</c> via <see cref="VSWhereSettings.Version"/></li></ul></remarks> public static (List<VSWhereResult> Result, IReadOnlyCollection<Output> Output) VSWhere(VSWhereSettings options = null) => new VSWhereTasks().Run<VSWhereSettings, List<VSWhereResult>>(options); /// <inheritdoc cref="VSWhereTasks.VSWhere(Nuke.Common.Tools.VSWhere.VSWhereSettings)"/> public static (List<VSWhereResult> Result, IReadOnlyCollection<Output> Output) VSWhere(Configure<VSWhereSettings> configurator) => new VSWhereTasks().Run<VSWhereSettings, List<VSWhereResult>>(configurator.Invoke(new VSWhereSettings())); /// <inheritdoc cref="VSWhereTasks.VSWhere(Nuke.Common.Tools.VSWhere.VSWhereSettings)"/> public static IEnumerable<(VSWhereSettings Settings, List<VSWhereResult> Result, IReadOnlyCollection<Output> Output)> VSWhere(CombinatorialConfigure<VSWhereSettings> configurator, int degreeOfParallelism = 1, bool completeOnFailure = false) => configurator.Invoke(VSWhere, degreeOfParallelism, completeOnFailure); } #region VSWhereSettings /// <inheritdoc cref="VSWhereTasks.VSWhere(Nuke.Common.Tools.VSWhere.VSWhereSettings)"/> [PublicAPI] [ExcludeFromCodeCoverage] [Command(Type = typeof(VSWhereTasks), Command = nameof(VSWhereTasks.VSWhere))]
VSWhereTasks
csharp
jellyfin__jellyfin
src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/StationDto.cs
{ "start": 206, "end": 1964 }
public class ____ { /// <summary> /// Gets or sets the station id. /// </summary> [JsonPropertyName("stationID")] public string? StationId { get; set; } /// <summary> /// Gets or sets the name. /// </summary> [JsonPropertyName("name")] public string? Name { get; set; } /// <summary> /// Gets or sets the callsign. /// </summary> [JsonPropertyName("callsign")] public string? Callsign { get; set; } /// <summary> /// Gets or sets the broadcast language. /// </summary> [JsonPropertyName("broadcastLanguage")] public IReadOnlyList<string> BroadcastLanguage { get; set; } = Array.Empty<string>(); /// <summary> /// Gets or sets the description language. /// </summary> [JsonPropertyName("descriptionLanguage")] public IReadOnlyList<string> DescriptionLanguage { get; set; } = Array.Empty<string>(); /// <summary> /// Gets or sets the broadcaster. /// </summary> [JsonPropertyName("broadcaster")] public BroadcasterDto? Broadcaster { get; set; } /// <summary> /// Gets or sets the affiliate. /// </summary> [JsonPropertyName("affiliate")] public string? Affiliate { get; set; } /// <summary> /// Gets or sets the logo. /// </summary> [JsonPropertyName("logo")] public LogoDto? Logo { get; set; } /// <summary> /// Gets or sets a value indicating whether it is commercial free. /// </summary> [JsonPropertyName("isCommercialFree")] public bool? IsCommercialFree { get; set; } } }
StationDto
csharp
EventStore__EventStore
src/KurrentDB.Core.Tests/Http/Users/users.cs
{ "start": 5349, "end": 6245 }
class ____<TLogFormat, TStreamId> : with_admin_user<TLogFormat, TStreamId> { private HttpResponseMessage _response; protected override async Task Given() { var response = await MakeJsonPost( "/users/", new { LoginName = "test1", FullName = "User Full Name", Password = "Pa55w0rd!" }, _admin); Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); } protected override async Task When() { _response = await MakeJsonPost( "/users/", new { LoginName = "test1", FullName = "User Full Name", Password = "Pa55w0rd!" }, _admin); } [Test] public void returns_create_status_code_and_location() { Assert.AreEqual(HttpStatusCode.Created, _response.StatusCode); } } [Category("LongRunning")] [TestFixture(typeof(LogFormat.V2), typeof(string))] [TestFixture(typeof(LogFormat.V3), typeof(uint))]
when_creating_an_already_existing_user_account
csharp
jellyfin__jellyfin
src/Jellyfin.Networking/Manager/NetworkManager.cs
{ "start": 43957, "end": 45121 }
internal interface ____ there is one. bindAddress = _interfaces.Where(x => IsInLocalNetwork(x.Address)) .OrderByDescending(x => NetworkUtils.SubnetContainsAddress(x.Subnet, source)) .ThenByDescending(x => x.Subnet.PrefixLength) .ThenBy(x => x.Index) .Select(x => x.Address) .FirstOrDefault(); if (bindAddress is not null) { result = NetworkUtils.FormatIPString(bindAddress); _logger.LogDebug("{Source}: Internal request received, matching internal bind address found: {Result}", source, result); return true; } } return false; } /// <summary> /// Attempts to match the source against external interfaces. /// </summary> /// <param name="source">IP source address to use.</param> /// <param name="result">The result, if a match is found.</param> /// <returns><c>true</c> if a match is found, <c>false</c> otherwise.</returns> private bool MatchesExternalInterface(IPAddress source, out string result) { // Get the first external
if
csharp
nopSolutions__nopCommerce
src/Plugins/Nop.Plugin.MultiFactorAuth.GoogleAuthenticator/Infrastructure/RouteProvider.cs
{ "start": 276, "end": 890 }
public class ____ : IRouteProvider { /// <summary> /// Register routes /// </summary> /// <param name="endpointRouteBuilder">Route builder</param> public void RegisterRoutes(IEndpointRouteBuilder endpointRouteBuilder) { endpointRouteBuilder.MapControllerRoute(GoogleAuthenticatorDefaults.ConfigurationRouteName, "Plugins/GoogleAuthenticator/Configure", new { controller = "GoogleAuthenticator", action = "Configure", area = AreaNames.ADMIN }); } /// <summary> /// Gets a priority of route provider /// </summary> public int Priority => 0; }
RouteProvider
csharp
unoplatform__uno
src/Uno.UWP/Globalization/DateTimeFormatting/DateTimeTemplateParser/TemplateNodes.cs
{ "start": 9917, "end": 13343 }
internal sealed class ____ : TemplateNode { public static TemplateShortTimeNode DefaultShortTimeInstance { get; } = new(null, null, null); public TemplateShortTimeNode(TemplateNode? first, TemplateNode? second, TemplateNode? third = null) { First = first; Second = second; Third = third; } public TemplateNode? First { get; } public TemplateNode? Second { get; } public TemplateNode? Third { get; } internal override void Traverse(DateTimeTemplateInfo state) { if (ReferenceEquals(this, DefaultShortTimeInstance)) { state.IsShortTime = true; } else { First!.Traverse(state); Second!.Traverse(state); Third?.Traverse(state); } } } // <longtime> ::= "longtime" | // <hour> <whitespace> <minute> <whitespace> <second> | // <hour> <whitespace> <second> <whitespace> <minute> | // <minute> <whitespace> <hour> <whitespace> <second> | // <minute> <whitespace> <second> <whitespace> <hour> | // <second> <whitespace> <minute> <whitespace> <hour> | // <second> <whitespace> <hour> <whitespace> <minute> | // <timezone> <whitespace> <hour> <whitespace> <minute> <whitespace> <second> | // <timezone> <whitespace> <hour> <whitespace> <second> <whitespace> <minute> | // <timezone> <whitespace> <minute> <whitespace> <hour> <whitespace> <second> | // <timezone> <whitespace> <minute> <whitespace> <second> <whitespace> <hour> | // <timezone> <whitespace> <second> <whitespace> <minute> <whitespace> <hour> | // <timezone> <whitespace> <second> <whitespace> <hour> <whitespace> <minute> | // <hour> <whitespace> <timezone> <whitespace> <minute> <whitespace> <second> | // <hour> <whitespace> <timezone> <whitespace> <second> <whitespace> <minute> | // <minute> <whitespace> <timezone> <whitespace> <hour> <whitespace> <second> | // <minute> <whitespace> <timezone> <whitespace> <second> <whitespace> <hour> | // <second> <whitespace> <timezone> <whitespace> <minute> <whitespace> <hour> | // <second> <whitespace> <timezone> <whitespace> <hour> <whitespace> <minute> | // <hour> <whitespace> <minute> <whitespace> <timezone> <whitespace> <second> | // <hour> <whitespace> <second> <whitespace> <timezone> <whitespace> <minute> | // <minute> <whitespace> <hour> <whitespace> <timezone> <whitespace> <second> | // <minute> <whitespace> <second> <whitespace> <timezone> <whitespace> <hour> | // <second> <whitespace> <minute> <whitespace> <timezone> <whitespace> <hour> | // <second> <whitespace> <hour> <whitespace> <timezone> <whitespace> <minute> | // <hour> <whitespace> <minute> <whitespace> <second> <whitespace> <timezone> | // <hour> <whitespace> <second> <whitespace> <minute> <whitespace> <timezone> | // <minute> <whitespace> <hour> <whitespace> <second> <whitespace> <timezone> | // <minute> <whitespace> <second> <whitespace> <hour> <whitespace> <timezone> | // <second> <whitespace> <minute> <whitespace> <hour> <whitespace> <timezone> | // <second> <whitespace> <hour> <whitespace> <minute> <whitespace> <timezone>
TemplateShortTimeNode
csharp
dotnet__aspnetcore
src/Http/Http.Results/test/ResultsOfTTests.Generated.cs
{ "start": 83977, "end": 84366 }
abstract class ____ : IResult { public ChecksumResult(int checksum = 0) { Checksum = checksum; } public int Checksum { get; } public Task ExecuteAsync(HttpContext httpContext) { httpContext.Items[nameof(ChecksumResult.Checksum)] = Checksum; return Task.CompletedTask; } }
ChecksumResult
csharp
JamesNK__Newtonsoft.Json
Src/Newtonsoft.Json.Tests/TestObjects/IPrivateOverriddenImplementation.cs
{ "start": 1203, "end": 1314 }
public interface ____ { object OverriddenProperty { get; set; } } }
IPrivateOverriddenImplementation
csharp
nopSolutions__nopCommerce
src/Presentation/Nop.Web/Models/Order/CustomerRecurringPaymentListModel.cs
{ "start": 151, "end": 423 }
public partial record ____ : BaseNopModel { #region Properties public List<CustomerRecurringPaymentModel> RecurringPayments { get; set; } = new(); public List<string> RecurringPaymentErrors { get; set; } = new(); #endregion }
CustomerRecurringPaymentListModel
csharp
dotnet__maui
src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue24734.cs
{ "start": 114, "end": 507 }
public class ____ : _IssuesUITest { public Issue24734(TestDevice device) : base(device) { } public override string Issue => "TapGestureRecognizer ButtonMask always return 0"; [Test] [Category(UITestCategories.Gestures)] public void ButtonMaskShouldNotReturnZero() { App.WaitForElement("LabelwithGesture"); App.Tap("LabelwithGesture"); App.WaitForElement("Success"); } }
Issue24734
csharp
grpc__grpc-dotnet
src/Grpc.Net.Common/ConnectivityState.cs
{ "start": 853, "end": 1328 }
public enum ____ { /// <summary> /// Not trying to create a connection. /// </summary> Idle, /// <summary> /// Establishing a connection. /// </summary> Connecting, /// <summary> /// Connection ready. /// </summary> Ready, /// <summary> /// A transient failure on connection. /// </summary> TransientFailure, /// <summary> /// Connection shutdown. /// </summary> Shutdown } #endif
ConnectivityState
csharp
PrismLibrary__Prism
src/Maui/Prism.Maui/Ioc/RegionNavigationRegistrationExtensions.cs
{ "start": 339, "end": 9172 }
public static class ____ { /// <summary> /// Registers a <see cref="View"/> for region navigation. /// </summary> /// <typeparam name="TView">The Type of <see cref="View"/> to register</typeparam> /// <param name="containerRegistry"><see cref="IContainerRegistry"/> used to register type for Navigation.</param> /// <param name="name">The unique name to register with the View</param> public static IContainerRegistry RegisterForRegionNavigation<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] TView>(this IContainerRegistry containerRegistry, string name = null) where TView : View => containerRegistry.RegisterForNavigationWithViewModel(typeof(TView), null, name); /// <summary> /// Registers a <see cref="View"/> for region navigation. /// </summary> /// <typeparam name="TView">The Type of <see cref="View" />to register</typeparam> /// <typeparam name="TViewModel">The ViewModel to use as the BindingContext for the View</typeparam> /// <param name="name">The unique name to register with the View</param> /// <param name="containerRegistry"></param> public static IContainerRegistry RegisterForRegionNavigation<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] TView, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] TViewModel>(this IContainerRegistry containerRegistry, string name = null) where TView : View where TViewModel : class => containerRegistry.RegisterForNavigationWithViewModel(typeof(TView), typeof(TViewModel), name); public static IContainerRegistry RegisterForRegionNavigation(this IContainerRegistry containerRegistry, Type viewType, Type viewModelType, string name = null) => containerRegistry.RegisterForNavigationWithViewModel(viewType, viewModelType, name); private static IContainerRegistry RegisterForNavigationWithViewModel(this IContainerRegistry containerRegistry, Type viewType, Type viewModelType, string name) { if (string.IsNullOrWhiteSpace(name)) name = viewType.Name; if (viewModelType is not null) containerRegistry.Register(viewModelType); containerRegistry.Register(viewType) .RegisterInstance(new ViewRegistration { Name = name, Type = ViewType.Region, View = viewType, ViewModel = viewModelType }); return containerRegistry; } /// <summary> /// Registers a <see cref="View"/> for region navigation. /// </summary> /// <typeparam name="TView">The Type of <see cref="View"/> to register</typeparam> /// <param name="services"><see cref="IServiceCollection"/> used to register type for Navigation.</param> /// <param name="name">The unique name to register with the View</param> public static IServiceCollection RegisterForRegionNavigation<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] TView>(this IServiceCollection services, string name = null) where TView : View => services.RegisterForNavigationWithViewModel(typeof(TView), null, name); /// <summary> /// Registers a <see cref="View"/> for region navigation. /// </summary> /// <typeparam name="TView">The Type of <see cref="View" />to register</typeparam> /// <typeparam name="TViewModel">The ViewModel to use as the BindingContext for the View</typeparam> /// <param name="name">The unique name to register with the View</param> /// <param name="services"></param> public static IServiceCollection RegisterForRegionNavigation<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] TView, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] TViewModel>(this IServiceCollection services, string name = null) where TView : View where TViewModel : class => services.RegisterForNavigationWithViewModel(typeof(TView), typeof(TViewModel), name); public static IServiceCollection RegisterForRegionNavigation(this IServiceCollection services, Type viewType, Type viewModelType, string name = null) => services.RegisterForNavigationWithViewModel(viewType, viewModelType, name); private static IServiceCollection RegisterForNavigationWithViewModel(this IServiceCollection services, Type viewType, Type viewModelType, string name) { if (string.IsNullOrWhiteSpace(name)) name = viewType.Name; if (viewModelType is not null) services.AddTransient(viewModelType); services.AddTransient(viewType) .AddSingleton(new ViewRegistration { Name = name, Type = ViewType.Region, View = viewType, ViewModel = viewModelType }); return services; } internal static IContainerRegistry RegisterRegionServices(this IContainerRegistry containerRegistry, Action<RegionAdapterMappings> configureAdapters = null, Action<IRegionBehaviorFactory> configureBehaviors = null) { containerRegistry.TryRegister<IRegionNavigationRegistry, RegionNavigationRegistry>(); containerRegistry.RegisterSingleton<RegionAdapterMappings>(p => { var regionAdapterMappings = new RegionAdapterMappings(); configureAdapters?.Invoke(regionAdapterMappings); regionAdapterMappings.RegisterDefaultMapping<CarouselView, CarouselViewRegionAdapter>(); // TODO: CollectionView is buggy with only last View showing despite multiple Active Views // BUG: iOS Crash with CollectionView https://github.com/xamarin/Xamarin.Forms/issues/9970 //regionAdapterMappings.RegisterDefaultMapping<CollectionView, CollectionViewRegionAdapter>(); regionAdapterMappings.RegisterDefaultMapping<Microsoft.Maui.Controls.Compatibility.Layout<View>, LayoutViewRegionAdapter>(); regionAdapterMappings.RegisterDefaultMapping<Layout, LayoutRegionAdapter>(); regionAdapterMappings.RegisterDefaultMapping<ScrollView, ScrollViewRegionAdapter>(); regionAdapterMappings.RegisterDefaultMapping<ContentView, ContentViewRegionAdapter>(); return regionAdapterMappings; }); containerRegistry.TryRegisterSingleton<IRegionManager, RegionManager>(); containerRegistry.TryRegisterSingleton<IRegionNavigationContentLoader, RegionNavigationContentLoader>(); containerRegistry.TryRegisterSingleton<IRegionViewRegistry, RegionViewRegistry>(); containerRegistry.TryRegister<RegionBehaviorFactory>(); containerRegistry.RegisterSingleton<IRegionBehaviorFactory>(p => { var regionBehaviors = p.Resolve<RegionBehaviorFactory>(); regionBehaviors.AddIfMissing<BindRegionContextToVisualElementBehavior>(BindRegionContextToVisualElementBehavior.BehaviorKey); regionBehaviors.AddIfMissing<RegionActiveAwareBehavior>(RegionActiveAwareBehavior.BehaviorKey); regionBehaviors.AddIfMissing<SyncRegionContextWithHostBehavior>(SyncRegionContextWithHostBehavior.BehaviorKey); regionBehaviors.AddIfMissing<RegionManagerRegistrationBehavior>(RegionManagerRegistrationBehavior.BehaviorKey); regionBehaviors.AddIfMissing<RegionMemberLifetimeBehavior>(RegionMemberLifetimeBehavior.BehaviorKey); regionBehaviors.AddIfMissing<ClearChildViewsRegionBehavior>(ClearChildViewsRegionBehavior.BehaviorKey); regionBehaviors.AddIfMissing<AutoPopulateRegionBehavior>(AutoPopulateRegionBehavior.BehaviorKey); regionBehaviors.AddIfMissing<DestructibleRegionBehavior>(DestructibleRegionBehavior.BehaviorKey); configureBehaviors?.Invoke(regionBehaviors); return regionBehaviors; }); containerRegistry.TryRegister<IRegionNavigationJournalEntry, RegionNavigationJournalEntry>(); containerRegistry.TryRegister<IRegionNavigationJournal, RegionNavigationJournal>(); containerRegistry.TryRegister<IRegionNavigationService, RegionNavigationService>(); //containerRegistry.RegisterManySingleton<RegionResolverOverrides>(typeof(IResolverOverridesHelper), typeof(IActiveRegionHelper)); return containerRegistry.TryRegisterSingleton<IRegionManager, RegionManager>(); } }
RegionNavigationRegistrationExtensions