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
ServiceStack__ServiceStack
ServiceStack.Azure/tests/ServiceStack.Azure.Tests/Storage/AzureBlobVirtualPathProviderTests.cs
{ "start": 1997, "end": 2234 }
public class ____ : VirtualPathProviderTests { public override IVirtualPathProvider GetPathProvider() { return new MemoryVirtualFiles(); } } [TestFixture]
InMemoryVirtualPathProviderTests
csharp
JamesNK__Newtonsoft.Json
Src/Newtonsoft.Json.Tests/FileSystemEntityModel.Designer.cs
{ "start": 10822, "end": 18595 }
public partial class ____ : EntityObject { #region Factory Method /// <summary> /// Create a new Folder object. /// </summary> /// <param name="folderId">Initial value of the FolderId property.</param> /// <param name="name">Initial value of the Name property.</param> /// <param name="description">Initial value of the Description property.</param> /// <param name="createdDate">Initial value of the CreatedDate property.</param> public static Folder CreateFolder(global::System.Guid folderId, global::System.String name, global::System.String description, global::System.DateTime createdDate) { Folder folder = new Folder(); folder.FolderId = folderId; folder.Name = name; folder.Description = description; folder.CreatedDate = createdDate; return folder; } #endregion #region Primitive Properties /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.Guid FolderId { get { return _FolderId; } set { if (_FolderId != value) { OnFolderIdChanging(value); ReportPropertyChanging("FolderId"); _FolderId = StructuralObject.SetValidValue(value); ReportPropertyChanged("FolderId"); OnFolderIdChanged(); } } } private global::System.Guid _FolderId; partial void OnFolderIdChanging(global::System.Guid value); partial void OnFolderIdChanged(); /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.String Name { get { return _Name; } set { OnNameChanging(value); ReportPropertyChanging("Name"); _Name = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("Name"); OnNameChanged(); } } private global::System.String _Name; partial void OnNameChanging(global::System.String value); partial void OnNameChanged(); /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.String Description { get { return _Description; } set { OnDescriptionChanging(value); ReportPropertyChanging("Description"); _Description = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("Description"); OnDescriptionChanged(); } } private global::System.String _Description; partial void OnDescriptionChanging(global::System.String value); partial void OnDescriptionChanged(); /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.DateTime CreatedDate { get { return _CreatedDate; } set { OnCreatedDateChanging(value); ReportPropertyChanging("CreatedDate"); _CreatedDate = StructuralObject.SetValidValue(value); ReportPropertyChanged("CreatedDate"); OnCreatedDateChanged(); } } private global::System.DateTime _CreatedDate; partial void OnCreatedDateChanging(global::System.DateTime value); partial void OnCreatedDateChanged(); #endregion #region Navigation Properties /// <summary> /// No Metadata Documentation available. /// </summary> [XmlIgnoreAttribute()] [SoapIgnoreAttribute()] [DataMemberAttribute()] [EdmRelationshipNavigationPropertyAttribute("DataServicesTestDatabaseModel", "FK_File_Folder", "File")] public EntityCollection<File> Files { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<File>("DataServicesTestDatabaseModel.FK_File_Folder", "File"); } set { if ((value != null)) { ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<File>("DataServicesTestDatabaseModel.FK_File_Folder", "File", value); } } } /// <summary> /// No Metadata Documentation available. /// </summary> [XmlIgnoreAttribute()] [SoapIgnoreAttribute()] [DataMemberAttribute()] [EdmRelationshipNavigationPropertyAttribute("DataServicesTestDatabaseModel", "FK_Folder_Folder", "Folder1")] public EntityCollection<Folder> ChildFolders { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<Folder>("DataServicesTestDatabaseModel.FK_Folder_Folder", "Folder1"); } set { if ((value != null)) { ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<Folder>("DataServicesTestDatabaseModel.FK_Folder_Folder", "Folder1", value); } } } /// <summary> /// No Metadata Documentation available. /// </summary> [XmlIgnoreAttribute()] [SoapIgnoreAttribute()] [DataMemberAttribute()] [EdmRelationshipNavigationPropertyAttribute("DataServicesTestDatabaseModel", "FK_Folder_Folder", "Folder")] public Folder ParentFolder { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Folder>("DataServicesTestDatabaseModel.FK_Folder_Folder", "Folder").Value; } set { ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Folder>("DataServicesTestDatabaseModel.FK_Folder_Folder", "Folder").Value = value; } } /// <summary> /// No Metadata Documentation available. /// </summary> [BrowsableAttribute(false)] [DataMemberAttribute()] public EntityReference<Folder> ParentFolderReference { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<Folder>("DataServicesTestDatabaseModel.FK_Folder_Folder", "Folder"); } set { if ((value != null)) { ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<Folder>("DataServicesTestDatabaseModel.FK_Folder_Folder", "Folder", value); } } } #endregion } #endregion } #endif
Folder
csharp
MassTransit__MassTransit
src/Transports/MassTransit.KafkaIntegration/KafkaIntegration/KafkaClientContext.cs
{ "start": 136, "end": 455 }
public class ____ : BasePipeContext, ClientContext { public KafkaClientContext(ClientConfig config, CancellationToken cancellationToken) : base(cancellationToken) { Config = config; } public ClientConfig Config { get; } } }
KafkaClientContext
csharp
FastEndpoints__FastEndpoints
Src/Library/Endpoint/Endpoint.cs
{ "start": 17591, "end": 17783 }
class ____ defining endpoints that doesn't need a request dto. usually used for routes that doesn't have any parameters. /// </summary> [UsedImplicitly(ImplicitUseTargetFlags.WithInheritors)]
for
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/MessageData/DataBus_Specs.cs
{ "start": 23107, "end": 23360 }
public interface ____ { IHaveNoMessageDataEither Child { get; } IHaveNoMessageDataEither[] Children { get; } IDictionary<string, IHaveNoMessageDataEither> ChildIndex { get; } }
IHaveNoMessageData
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.Appointments.DataProvider/AppointmentCalendarCancelMeetingRequest.cs
{ "start": 325, "end": 6295 }
public partial class ____ { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ internal AppointmentCalendarCancelMeetingRequest() { } #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 AppointmentCalendarLocalId { get { throw new global::System.NotImplementedException("The member string AppointmentCalendarCancelMeetingRequest.AppointmentCalendarLocalId is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20AppointmentCalendarCancelMeetingRequest.AppointmentCalendarLocalId"); } } #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 AppointmentLocalId { get { throw new global::System.NotImplementedException("The member string AppointmentCalendarCancelMeetingRequest.AppointmentLocalId is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20AppointmentCalendarCancelMeetingRequest.AppointmentLocalId"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::System.DateTimeOffset? AppointmentOriginalStartTime { get { throw new global::System.NotImplementedException("The member DateTimeOffset? AppointmentCalendarCancelMeetingRequest.AppointmentOriginalStartTime is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=DateTimeOffset%3F%20AppointmentCalendarCancelMeetingRequest.AppointmentOriginalStartTime"); } } #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 Comment { get { throw new global::System.NotImplementedException("The member string AppointmentCalendarCancelMeetingRequest.Comment is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20AppointmentCalendarCancelMeetingRequest.Comment"); } } #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 bool NotifyInvitees { get { throw new global::System.NotImplementedException("The member bool AppointmentCalendarCancelMeetingRequest.NotifyInvitees is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20AppointmentCalendarCancelMeetingRequest.NotifyInvitees"); } } #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 Subject { get { throw new global::System.NotImplementedException("The member string AppointmentCalendarCancelMeetingRequest.Subject is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20AppointmentCalendarCancelMeetingRequest.Subject"); } } #endif // Forced skipping of method Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarCancelMeetingRequest.AppointmentCalendarLocalId.get // Forced skipping of method Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarCancelMeetingRequest.AppointmentLocalId.get // Forced skipping of method Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarCancelMeetingRequest.AppointmentOriginalStartTime.get // Forced skipping of method Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarCancelMeetingRequest.Subject.get // Forced skipping of method Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarCancelMeetingRequest.Comment.get // Forced skipping of method Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarCancelMeetingRequest.NotifyInvitees.get #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::Windows.Foundation.IAsyncAction ReportCompletedAsync() { throw new global::System.NotImplementedException("The member IAsyncAction AppointmentCalendarCancelMeetingRequest.ReportCompletedAsync() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IAsyncAction%20AppointmentCalendarCancelMeetingRequest.ReportCompletedAsync%28%29"); } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::Windows.Foundation.IAsyncAction ReportFailedAsync() { throw new global::System.NotImplementedException("The member IAsyncAction AppointmentCalendarCancelMeetingRequest.ReportFailedAsync() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IAsyncAction%20AppointmentCalendarCancelMeetingRequest.ReportFailedAsync%28%29"); } #endif } }
AppointmentCalendarCancelMeetingRequest
csharp
unoplatform__uno
src/Uno.UI.RemoteControl.VS/Notifications/InfoBar.cs
{ "start": 388, "end": 1694 }
public class ____ { private IVsInfoBarUIFactory _infoBarUIFactory; private readonly IVsShell _shell; private List<InfoBar> _infoBars = new(); public InfoBarFactory(IVsInfoBarUIFactory infoBarUIFactory, IVsShell shell) { _infoBarUIFactory = infoBarUIFactory; _shell = shell; } /// <summary> /// Creates a new InfoBar in the main window. /// </summary> /// <param name="model">A model representing the text, icon, and actions of the InfoBar.</param> public async Task<InfoBar?> CreateAsync(InfoBarModel model) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); _shell.GetProperty((int)__VSSPROPID7.VSSPROPID_MainWindowInfoBarHost, out var value); if (value is IVsInfoBarHost host) { var infoBar = new InfoBar(this, host, _infoBarUIFactory, model); _infoBars.Add(infoBar); return infoBar; } return null; } internal void RemoveInfoBar(InfoBar infoBar) { _infoBars.Remove(infoBar); } internal void RemoveAllInfoBars() { ThreadHelper.ThrowIfNotOnUIThread(); foreach (var infoBar in _infoBars.ToArray()) { infoBar.Close(); } } internal void Dispose() { ThreadHelper.ThrowIfNotOnUIThread(); RemoveAllInfoBars(); } } /// <summary> /// An instance of an InfoBar (also known as Yellow- or Gold bar). /// </summary>
InfoBarFactory
csharp
JamesNK__Newtonsoft.Json
Src/Newtonsoft.Json.Tests/Issues/Issue1321.cs
{ "start": 1659, "end": 6263 }
public class ____ : TestFixtureBase { [Test] public void Test() { ExceptionAssert.Throws<JsonWriterException>(() => { JsonConvert.DeserializeObject( @"[""1"",", new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.None, MaxDepth = 1024 }); }, "Unexpected end when reading token. Path ''."); } [Test] public void Test2() { JArray a = new JArray(); var writer = a.CreateWriter(); JsonTextReader reader = new JsonTextReader(new StringReader(@"[""1"",")); ExceptionAssert.Throws<JsonWriterException>(() => { writer.WriteToken(reader); }, "Unexpected end when reading token. Path ''."); } #if !(NET20 || NET35 || NET40 || PORTABLE40) [Test] public async Task Test2_Async() { JArray a = new JArray(); var writer = a.CreateWriter(); JsonTextReader reader = new JsonTextReader(new StringReader(@"[""1"",")); await ExceptionAssert.ThrowsAsync<JsonWriterException>(async () => { await writer.WriteTokenAsync(reader); }, "Unexpected end when reading token. Path ''."); } #endif [Test] public void Test3() { JArray a = new JArray(); var writer = a.CreateWriter(); JsonTextReader reader = new JsonTextReader(new StringReader(@"[""1"",")); reader.Read(); ExceptionAssert.Throws<JsonWriterException>(() => { writer.WriteToken(reader); }, "Unexpected end when reading token. Path ''."); } #if !(NET20 || NET35 || NET40 || PORTABLE40) [Test] public async Task Test3_Async() { JArray a = new JArray(); var writer = a.CreateWriter(); JsonTextReader reader = new JsonTextReader(new StringReader(@"[""1"",")); await reader.ReadAsync(); await ExceptionAssert.ThrowsAsync<JsonWriterException>(async () => { await writer.WriteTokenAsync(reader); }, "Unexpected end when reading token. Path ''."); } #endif [Test] public void Test4() { JArray a = new JArray(); var writer = a.CreateWriter(); JsonTextReader reader = new JsonTextReader(new StringReader(@"[[""1"",")); reader.Read(); reader.Read(); ExceptionAssert.Throws<JsonWriterException>(() => { writer.WriteToken(reader); }, "Unexpected end when reading token. Path ''."); } #if !(NET20 || NET35 || NET40 || PORTABLE40) [Test] public async Task Test4_Async() { JArray a = new JArray(); var writer = a.CreateWriter(); JsonTextReader reader = new JsonTextReader(new StringReader(@"[[""1"",")); await reader.ReadAsync(); await reader.ReadAsync(); await ExceptionAssert.ThrowsAsync<JsonWriterException>(async () => { await writer.WriteTokenAsync(reader); }, "Unexpected end when reading token. Path ''."); } #endif [Test] public void Test5() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteStartArray(); JsonTextReader reader = new JsonTextReader(new StringReader(@"[[""1"",")); reader.Read(); reader.Read(); ExceptionAssert.Throws<JsonWriterException>(() => { writer.WriteToken(reader); }, "Unexpected end when reading token. Path '[0]'."); } #if !(NET20 || NET35 || NET40 || PORTABLE40) [Test] public async Task Test5_Async() { StringWriter sw = new StringWriter(); JsonTextWriter writer = new JsonTextWriter(sw); writer.WriteStartArray(); JsonTextReader reader = new JsonTextReader(new StringReader(@"[[""1"",")); await reader.ReadAsync(); await reader.ReadAsync(); await ExceptionAssert.ThrowsAsync<JsonWriterException>(async () => { await writer.WriteTokenAsync(reader); }, "Unexpected end when reading token. Path '[0]'."); } #endif } }
Issue1321
csharp
nopSolutions__nopCommerce
src/Plugins/Nop.Plugin.Payments.PayPalCommerce/Data/SchemaMigration.cs
{ "start": 291, "end": 549 }
public class ____ : AutoReversingMigration { #region Methods /// <summary> /// Collect the UP migration expressions /// </summary> public override void Up() { Create.TableFor<PayPalToken>(); } #endregion }
SchemaMigration
csharp
microsoft__semantic-kernel
dotnet/samples/Concepts/Agents/ChatCompletion_Streaming.cs
{ "start": 4750, "end": 5431 }
public sealed class ____ { [KernelFunction, Description("Provides a list of specials from the menu.")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1024:Use properties where appropriate", Justification = "Too smart")] public string GetSpecials() { return @" Special Soup: Clam Chowder Special Salad: Cobb Salad Special Drink: Chai Tea "; } [KernelFunction, Description("Provides the price of the requested menu item.")] public string GetItemPrice( [Description("The name of the menu item.")] string menuItem) { return "$9.99"; } } }
MenuPlugin
csharp
abpframework__abp
framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/Pages/Shared/Components/AbpPageToolbar/Button/AbpPageToolbarButtonViewComponent.cs
{ "start": 349, "end": 1516 }
public class ____ : AbpViewComponent { protected IStringLocalizerFactory StringLocalizerFactory { get; } public AbpPageToolbarButtonViewComponent(IStringLocalizerFactory stringLocalizerFactory) { StringLocalizerFactory = stringLocalizerFactory; } public async Task<IViewComponentResult> InvokeAsync( ILocalizableString text, string name, string icon, string id, ILocalizableString? busyText, FontIconType iconType, AbpButtonType type, AbpButtonSize size, bool disabled) { Check.NotNull(text, nameof(text)); return View( "~/Pages/Shared/Components/AbpPageToolbar/Button/Default.cshtml", new AbpPageToolbarButtonViewModel( await text.LocalizeAsync(StringLocalizerFactory), name, icon, id, busyText == null ? null : (await busyText.LocalizeAsync(StringLocalizerFactory)).ToString(), iconType, type, size, disabled ) ); }
AbpPageToolbarButtonViewComponent
csharp
dotnetcore__FreeSql
FreeSql.Tests/FreeSql.Tests/Firebird/Curd/FirebirdSelectTest.cs
{ "start": 16777, "end": 17862 }
public class ____ { [Column(IsPrimary = true, StringLength = 6)] public string Code { get; set; } [Column(StringLength = 20, IsNullable = false)] public string Name { get; set; } [Column(StringLength = 6)] public string ParentCode { get; set; } [Navigate(nameof(ParentCode))] public District Parent { get; set; } [Navigate(nameof(ParentCode))] public List<District> Childs { get; set; } } [Fact] public void ToDictionary() { g.firebird.Insert(new Topic { Title = "xxx" }).ExecuteAffrows(); var testDto1 = select.Limit(10).ToDictionary(a => a.Id); var testDto2 = select.Limit(10).ToDictionary(a => a.Id, a => new { a.Id, a.Title }); var repo = g.firebird.GetRepository<Topic>(); var dic = repo.Select.Limit(10).ToDictionary(a => a.Id); var first = dic.First().Value; first.Clicks++; repo.Update(first); }
District
csharp
smartstore__Smartstore
src/Smartstore/Engine/Modularity/IProvider.cs
{ "start": 219, "end": 282 }
interface ____ a user editable provider /// </summary>
for
csharp
dotnet__maui
src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue29562.cs
{ "start": 115, "end": 471 }
public class ____ : _IssuesUITest { public Issue29562(TestDevice testDevice) : base(testDevice) { } public override string Issue => "Maui.Graphics GetStringSize Inverts Width and Height"; [Test] [Category(UITestCategories.GraphicsView)] public void GraphicsViewShouldNotWrapText() { App.WaitForElement("Label"); VerifyScreenshot(); } }
Issue29562
csharp
getsentry__sentry-dotnet
src/Sentry/Integrations/AutoSessionTrackingIntegration.cs
{ "start": 32, "end": 263 }
internal class ____ : ISdkIntegration { public void Register(IHub hub, SentryOptions options) { if (options.AutoSessionTracking) { hub.StartSession(); } } }
AutoSessionTrackingIntegration
csharp
CommunityToolkit__Maui
src/CommunityToolkit.Maui.UnitTests/Converters/IsStringNotNullOrWhiteSpaceConverterTests.cs
{ "start": 110, "end": 2710 }
public class ____ : BaseOneWayConverterTest<IsStringNotNullOrWhiteSpaceConverter> { [Theory] [InlineData("Test", true)] [InlineData(null, false)] [InlineData("", false)] [InlineData(" ", false)] [InlineData(" ", false)] public void IsNotNullOrWhiteSpaceConverter_ValidStringValue(string? value, bool expectedResult) { var isNotNullOrWhiteSpaceConverter = new IsStringNotNullOrWhiteSpaceConverter(); var convertResult = (bool?)((ICommunityToolkitValueConverter)isNotNullOrWhiteSpaceConverter).Convert(value, typeof(bool), null, null); var convertFromResult = isNotNullOrWhiteSpaceConverter.ConvertFrom(value); Assert.Equal(expectedResult, convertResult); Assert.Equal(expectedResult, convertFromResult); } [Theory] [InlineData("Test", true)] [InlineData(null, false)] [InlineData("", false)] [InlineData(" ", false)] [InlineData(" ", false)] public void IsStringNotNullOrWhiteSpaceConverter_ShouldConvert_WhenTargetTypeIsNullableBool(string? value, bool expectedResult) { var isNotNullOrWhiteSpaceConverter = new IsStringNotNullOrWhiteSpaceConverter(); var convertResult = (bool?)((ICommunityToolkitValueConverter)isNotNullOrWhiteSpaceConverter).Convert(value, typeof(bool?), null, null); var convertFromResult = isNotNullOrWhiteSpaceConverter.ConvertFrom(value); Assert.Equal(expectedResult, convertResult); Assert.Equal(expectedResult, convertFromResult); } [Theory] [InlineData(17)] [InlineData(true)] [InlineData('c')] public void IsNotNullOrWhiteSpaceConverter_InvalidValue(object value) { var isNotNullOrWhiteSpaceConverter = new IsStringNotNullOrWhiteSpaceConverter(); Assert.Throws<ArgumentException>(() => ((ICommunityToolkitValueConverter)isNotNullOrWhiteSpaceConverter).Convert(value, typeof(bool), null, null)); } [Fact] public void IsStringNotNullOrWhiteSpaceConverterNullInputTest() { #pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. Assert.Throws<ArgumentNullException>(() => ((ICommunityToolkitValueConverter)new IsStringNotNullOrWhiteSpaceConverter()).Convert(string.Empty, null, null, null)); Assert.Throws<ArgumentNullException>(() => ((ICommunityToolkitValueConverter)new IsStringNotNullOrWhiteSpaceConverter()).ConvertBack(true, null, null, null)); Assert.Throws<ArgumentNullException>(() => ((ICommunityToolkitValueConverter)new IsStringNotNullOrWhiteSpaceConverter()).ConvertBack(null, typeof(string), null, null)); #pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type. } }
IsStringNotNullOrWhiteSpaceConverterTests
csharp
VerifyTests__Verify
src/Verify.MSTest/Verifier.cs
{ "start": 1674, "end": 3037 }
class ____ a `[UsesVerify]` attribute (or inherits from `VerifyBase`)."); } return context; } [Pure] public static SettingsTask Verify( object? target, IEnumerable<Target> rawTargets, VerifySettings? settings = null, [CallerFilePath] string sourceFile = "") => Verify(settings, sourceFile, _ => _.Verify(target, rawTargets)); [Pure] public static SettingsTask Verify( IEnumerable<Target> targets, VerifySettings? settings = null, [CallerFilePath] string sourceFile = "") => Verify(settings, sourceFile, _ => _.Verify(targets)); [Pure] public static SettingsTask Verify( Target target, VerifySettings? settings = null, [CallerFilePath] string sourceFile = "") => Verify(settings, sourceFile, _ => _.Verify(target)); static SettingsTask Verify( VerifySettings? settings, string sourceFile, Func<InnerVerifier, Task<VerifyResult>> verify, bool useUniqueDirectory = false) { Guards.AgainstBadSourceFile(sourceFile); return new( settings, async settings => { using var verifier = BuildVerifier(settings, sourceFile, useUniqueDirectory); return await verify(verifier); }); } }
has
csharp
EventStore__EventStore
src/KurrentDB.Auth.LegacyAuthorizationWithStreamAuthorizationDisabled/ClaimValueMatchesParameterValueAssertion.cs
{ "start": 376, "end": 1317 }
public class ____ : IAssertion { private readonly string _claimType; private readonly string _parameterName; public ClaimValueMatchesParameterValueAssertion(string claimType, string parameterName, Grant grant) { _claimType = claimType; _parameterName = parameterName; Grant = grant; Information = new AssertionInformation("match", $"{_claimType} : {_parameterName}", Grant); } public AssertionInformation Information { get; } public Grant Grant { get; } public ValueTask<bool> Evaluate(ClaimsPrincipal cp, Operation operation, PolicyInformation policy, EvaluationContext context) { if (cp.FindFirst(_claimType) is Claim matchedClaim && operation.Parameters.Span.Contains(new Parameter(_parameterName, matchedClaim.Value))) { context.Add(new AssertionMatch(policy, Information, matchedClaim)); return new ValueTask<bool>(true); } return new ValueTask<bool>(false); } }
ClaimValueMatchesParameterValueAssertion
csharp
xunit__xunit
src/xunit.v3.runner.inproc.console.tests/TestingPlatform/SpyTestPlatformOutputDevice.cs
{ "start": 170, "end": 448 }
public class ____ : IOutputDevice { public List<IOutputDeviceData> DisplayedData { get; } = []; public Task DisplayAsync( IOutputDeviceDataProducer producer, IOutputDeviceData data) { DisplayedData.Add(data); return Task.CompletedTask; } }
SpyTestPlatformOutputDevice
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Bson/IO/IBsonWriter.cs
{ "start": 750, "end": 7869 }
public interface ____ : IDisposable { // properties /// <summary> /// Gets the position. /// Not all writers are able to report the position. Those that can't simply return zero. /// </summary> /// <value> /// The position. /// </value> long Position { get; } /// <summary> /// Gets the current serialization depth. /// </summary> int SerializationDepth { get; } /// <summary> /// Gets the settings of the writer. /// </summary> BsonWriterSettings Settings { get; } // methods /// <summary> /// Gets the current state of the writer. /// </summary> BsonWriterState State { get; } // methods /// <summary> /// Closes the writer. /// </summary> void Close(); /// <summary> /// Flushes any pending data to the output destination. /// </summary> void Flush(); /// <summary> /// Pops the element name validator. /// </summary> /// <returns>The popped element validator.</returns> void PopElementNameValidator(); /// <summary> /// Pops the settings. /// </summary> void PopSettings(); /// <summary> /// Pushes the element name validator. /// </summary> /// <param name="validator">The validator.</param> void PushElementNameValidator(IElementNameValidator validator); /// <summary> /// Pushes new settings for the writer. /// </summary> /// <param name="configurator">The settings configurator.</param> void PushSettings(Action<BsonWriterSettings> configurator); /// <summary> /// Writes BSON binary data to the writer. /// </summary> /// <param name="binaryData">The binary data.</param> void WriteBinaryData(BsonBinaryData binaryData); /// <summary> /// Writes a BSON Boolean to the writer. /// </summary> /// <param name="value">The Boolean value.</param> void WriteBoolean(bool value); /// <summary> /// Writes BSON binary data to the writer. /// </summary> /// <param name="bytes">The bytes.</param> void WriteBytes(byte[] bytes); /// <summary> /// Writes a BSON DateTime to the writer. /// </summary> /// <param name="value">The number of milliseconds since the Unix epoch.</param> void WriteDateTime(long value); /// <summary> /// Writes a BSON Decimal128 to the writer. /// </summary> /// <param name="value">The <see cref="Decimal128"/> value.</param> void WriteDecimal128(Decimal128 value); /// <summary> /// Writes a BSON Double to the writer. /// </summary> /// <param name="value">The Double value.</param> void WriteDouble(double value); /// <summary> /// Writes the end of a BSON array to the writer. /// </summary> void WriteEndArray(); /// <summary> /// Writes the end of a BSON document to the writer. /// </summary> void WriteEndDocument(); /// <summary> /// Writes a Guid in Standard representation to the writer. /// </summary> /// <param name="guid">The Guid value.</param> void WriteGuid(Guid guid); /// <summary> /// Writes a Guid in the specified representation to the writer. /// </summary> /// <param name="guid">The Guid value.</param> /// <param name="guidRepresentation">The GuidRepresentation.</param> void WriteGuid(Guid guid, GuidRepresentation guidRepresentation); /// <summary> /// Writes a BSON Int32 to the writer. /// </summary> /// <param name="value">The Int32 value.</param> void WriteInt32(int value); /// <summary> /// Writes a BSON Int64 to the writer. /// </summary> /// <param name="value">The Int64 value.</param> void WriteInt64(long value); /// <summary> /// Writes a BSON JavaScript to the writer. /// </summary> /// <param name="code">The JavaScript code.</param> void WriteJavaScript(string code); /// <summary> /// Writes a BSON JavaScript to the writer (call WriteStartDocument to start writing the scope). /// </summary> /// <param name="code">The JavaScript code.</param> void WriteJavaScriptWithScope(string code); /// <summary> /// Writes a BSON MaxKey to the writer. /// </summary> void WriteMaxKey(); /// <summary> /// Writes a BSON MinKey to the writer. /// </summary> void WriteMinKey(); /// <summary> /// Writes the name of an element to the writer. /// </summary> /// <param name="name">The name of the element.</param> void WriteName(string name); /// <summary> /// Writes a BSON null to the writer. /// </summary> void WriteNull(); /// <summary> /// Writes a BSON ObjectId to the writer. /// </summary> /// <param name="objectId">The ObjectId.</param> void WriteObjectId(ObjectId objectId); /// <summary> /// Writes a raw BSON array. /// </summary> /// <param name="slice">The byte buffer containing the raw BSON array.</param> void WriteRawBsonArray(IByteBuffer slice); /// <summary> /// Writes a raw BSON document. /// </summary> /// <param name="slice">The byte buffer containing the raw BSON document.</param> void WriteRawBsonDocument(IByteBuffer slice); /// <summary> /// Writes a BSON regular expression to the writer. /// </summary> /// <param name="regex">A BsonRegularExpression.</param> void WriteRegularExpression(BsonRegularExpression regex); /// <summary> /// Writes the start of a BSON array to the writer. /// </summary> void WriteStartArray(); /// <summary> /// Writes the start of a BSON document to the writer. /// </summary> void WriteStartDocument(); /// <summary> /// Writes a BSON String to the writer. /// </summary> /// <param name="value">The String value.</param> void WriteString(string value); /// <summary> /// Writes a BSON Symbol to the writer. /// </summary> /// <param name="value">The symbol.</param> void WriteSymbol(string value); /// <summary> /// Writes a BSON timestamp to the writer. /// </summary> /// <param name="value">The combined timestamp/increment value.</param> void WriteTimestamp(long value); /// <summary> /// Writes a BSON undefined to the writer. /// </summary> void WriteUndefined(); } }
IBsonWriter
csharp
RicoSuter__NJsonSchema
src/NJsonSchema/Generation/JsonSchemaGeneratorSettings.cs
{ "start": 2286, "end": 3908 }
interface ____ abstract properties. Properties may defined multiple times in a inheritance hierarchy, default: false).</summary> public bool GenerateAbstractProperties { get; set; } /// <summary>Gets or sets a value indicating whether to flatten the inheritance hierarchy instead of using allOf to describe inheritance (default: false).</summary> public bool FlattenInheritanceHierarchy { get; set; } /// <summary>Gets or sets a value indicating whether to generate the x-abstract flag on schemas (default: true).</summary> public bool GenerateAbstractSchemas { get; set; } /// <summary>Gets or sets a value indicating whether to generate schemas for types in <see cref="KnownTypeAttribute"/> attributes (default: true).</summary> public bool GenerateKnownTypes { get; set; } = true; /// <summary>Gets or sets a value indicating whether to generate xmlObject representation for definitions (default: false).</summary> public bool GenerateXmlObjects { get; set; } /// <summary>Gets or sets a value indicating whether to ignore properties with the <see cref="T:ObsoleteAttribute"/>.</summary> public bool IgnoreObsoleteProperties { get; set; } /// <summary>Gets or sets a value indicating whether to use $ref references even if additional properties are /// defined on the object (otherwise allOf/oneOf with $ref is used, default: false).</summary> public bool AllowReferencesWithProperties { get; set; } /// <summary>Gets or sets a value indicating whether to generate a description with number to
and
csharp
dotnet__maui
src/Controls/src/Core/Shell/ShellTemplatedViewManager.cs
{ "start": 164, "end": 1375 }
public static class ____ { public static void SetView( ref View localView, View newView, Action<Element> OnChildRemoved, Action<Element> OnChildAdded) { if (localView == newView) return; if (localView != null) OnChildRemoved(localView); localView = newView; if (localView != null) OnChildAdded(localView); } public static void OnViewDataChanged( DataTemplate currentViewTemplate, ref View localViewRef, object newViewData, Action<Element> OnChildRemoved, Action<Element> OnChildAdded) { if (currentViewTemplate == null) { SetView(ref localViewRef, newViewData as View, OnChildRemoved, OnChildAdded); } } public static void OnViewTemplateChanged( DataTemplate newViewTemplate, ref View localViewRef, object currentViewData, Action<Element> OnChildRemoved, Action<Element> OnChildAdded, Shell shell) { View newContentView = currentViewData as View; if (newViewTemplate != null) { newContentView = (View)newViewTemplate.CreateContent(newViewTemplate, shell); } SetView(ref localViewRef, newContentView, OnChildRemoved, OnChildAdded); } } }
ShellTemplatedViewManager
csharp
dotnetcore__FreeSql
FreeSql.Tests/FreeSql.Tests.Provider.GBase/GBase/Curd/GBaseDeleteTest.cs
{ "start": 320, "end": 1623 }
class ____ { [Column(IsIdentity = true, IsPrimary = true)] public int Id { get; set; } public int Clicks { get; set; } public string Title { get; set; } public DateTime CreateTime { get; set; } } [Fact] public void Dywhere() { Assert.Null(g.gbase.Delete<Topic>().ToSql()); var sql = g.gbase.Delete<Topic>(new[] { 1, 2 }).ToSql(); Assert.Equal("DELETE FROM tb_topic_del WHERE (Id IN (1,2))", sql); sql = g.gbase.Delete<Topic>(new Topic { Id = 1, Title = "test" }).ToSql(); Assert.Equal("DELETE FROM tb_topic_del WHERE (Id = 1)", sql); sql = g.gbase.Delete<Topic>(new[] { new Topic { Id = 1, Title = "test" }, new Topic { Id = 2, Title = "test" } }).ToSql(); Assert.Equal("DELETE FROM tb_topic_del WHERE (Id IN (1,2))", sql); sql = g.gbase.Delete<Topic>(new { id = 1 }).ToSql(); Assert.Equal("DELETE FROM tb_topic_del WHERE (Id = 1)", sql); sql = g.gbase.Delete<MultiPkTopic>(new[] { new { Id1 = 1, Id2 = 10 }, new { Id1 = 2, Id2 = 20 } }).ToSql(); Assert.Equal("DELETE FROM MultiPkTopic WHERE (Id1 = 1 AND Id2 = 10 OR Id1 = 2 AND Id2 = 20)", sql); }
Topic
csharp
Cysharp__MemoryPack
src/MemoryPack.Core/Formatters/ArrayFormatters.cs
{ "start": 5091, "end": 6033 }
public sealed class ____<T> : MemoryPackFormatter<Memory<T?>> { [Preserve] public override void Serialize<TBufferWriter>(ref MemoryPackWriter<TBufferWriter> writer, scoped ref Memory<T?> value) { writer.WriteSpan(value.Span); } [Preserve] public override void Deserialize(ref MemoryPackReader reader, scoped ref Memory<T?> value) { if (!reader.TryReadCollectionHeader(out var length)) { value = null; return; } if (length == 0) { value = Memory<T?>.Empty; return; } var memory = ArrayPool<T?>.Shared.Rent(length).AsMemory(0, length); var span = memory.Span; reader.ReadSpanWithoutReadLengthHeader(length, ref span); value = memory; } } [Preserve]
MemoryPoolFormatter
csharp
dotnetcore__WTM
demo/WalkingTec.Mvvm.Demo/Models/LinkTest2.cs
{ "start": 254, "end": 430 }
public class ____ : TopBasePoco { public string name { get; set; } public List<LinkTestStudent> LinkStudent { get; set; } } [MiddleTable]
LinkTest2
csharp
microsoft__semantic-kernel
dotnet/src/Agents/AzureAI/Extensions/KernelFunctionExtensions.cs
{ "start": 269, "end": 1140 }
public static class ____ { /// <summary> /// Convert <see cref="KernelFunction"/> to an OpenAI tool model. /// </summary> /// <param name="function">The source function</param> /// <param name="pluginName">The plugin name</param> /// <returns>An OpenAI tool definition</returns> public static FunctionToolDefinition ToToolDefinition(this KernelFunction function, string pluginName) { if (function.Metadata.Parameters.Count > 0) { BinaryData parameterData = function.Metadata.CreateParameterSpec(); return new FunctionToolDefinition(FunctionName.ToFullyQualifiedName(function.Name, pluginName), function.Description, parameterData); } return new FunctionToolDefinition(FunctionName.ToFullyQualifiedName(function.Name, pluginName), function.Description); } }
KernelFunctionExtensions
csharp
aspnetboilerplate__aspnetboilerplate
test/Abp.EntityFrameworkCore.Dapper.Tests/Domain/Post.cs
{ "start": 153, "end": 742 }
public class ____ : AuditedEntity<Guid> { public Post() { } public Post(Blog blog, string title, string body) { Blog = blog; Title = title; Body = body; } public Post(int blogId, string title, string body) { BlogId = blogId; Title = title; Body = body; } [Required] public Blog Blog { get; set; } public Comment Comment { get; set; } public int CommentId { get; set; } public int BlogId { get; set; } public string Title { get; set; } public string Body { get; set; } }
Post
csharp
dotnet__orleans
src/Orleans.Runtime/Facet/IAttributeToFactoryMapper.cs
{ "start": 167, "end": 742 }
public interface ____<in TMetadata> where TMetadata : IFacetMetadata { /// <summary> /// Responsible for mapping a facet metadata to a cachable factory from the parameter and facet metadata. /// </summary> /// <param name="parameter">The parameter info.</param> /// <param name="metadata">The metadata.</param> /// <returns>The factory used to create facet instances for a grain.</returns> Factory<IGrainContext, object> GetFactory(ParameterInfo parameter, TMetadata metadata); } }
IAttributeToFactoryMapper
csharp
DapperLib__Dapper
Dapper/SqlMapper.IDataReader.cs
{ "start": 131, "end": 8626 }
partial class ____ { /// <summary> /// Parses a data reader to a sequence of data of the supplied type. Used for deserializing a reader without a connection, etc. /// </summary> /// <typeparam name="T">The type to parse from the <paramref name="reader"/>.</typeparam> /// <param name="reader">The data reader to parse results from.</param> public static IEnumerable<T> Parse<T>(this IDataReader reader) { var dbReader = GetDbDataReader(reader); if (dbReader.Read()) { var effectiveType = typeof(T); var deser = GetDeserializer(effectiveType, dbReader, 0, -1, false); var convertToType = Nullable.GetUnderlyingType(effectiveType) ?? effectiveType; do { object val = deser(dbReader); if (val is null || val is T) { yield return (T)val!; } else { yield return (T)Convert.ChangeType(val, convertToType, System.Globalization.CultureInfo.InvariantCulture); } } while (dbReader.Read()); } } /// <summary> /// Parses a data reader to a sequence of data of the supplied type (as object). Used for deserializing a reader without a connection, etc. /// </summary> /// <param name="reader">The data reader to parse results from.</param> /// <param name="type">The type to parse from the <paramref name="reader"/>.</param> public static IEnumerable<object> Parse(this IDataReader reader, Type type) { var dbReader = GetDbDataReader(reader); if (dbReader.Read()) { var deser = GetDeserializer(type, dbReader, 0, -1, false); do { yield return deser(dbReader); } while (dbReader.Read()); } } /// <summary> /// Parses a data reader to a sequence of dynamic. Used for deserializing a reader without a connection, etc. /// </summary> /// <param name="reader">The data reader to parse results from.</param> public static IEnumerable<dynamic> Parse(this IDataReader reader) { var dbReader = GetDbDataReader(reader); if (dbReader.Read()) { var deser = GetDapperRowDeserializer(dbReader, 0, -1, false); do { yield return deser(dbReader); } while (dbReader.Read()); } } /// <summary> /// Gets the row parser for a specific row on a data reader. This allows for type switching every row based on, for example, a TypeId column. /// You could return a collection of the base type but have each more specific. /// </summary> /// <param name="reader">The data reader to get the parser for the current row from</param> /// <param name="type">The type to get the parser for</param> /// <param name="startIndex">The start column index of the object (default 0)</param> /// <param name="length">The length of columns to read (default -1 = all fields following startIndex)</param> /// <param name="returnNullIfFirstMissing">Return null if we can't find the first column? (default false)</param> /// <returns>A parser for this specific object from this row.</returns> #if DEBUG // make sure we're not using this internally [Obsolete(nameof(DbDataReader) + " API should be preferred")] #endif [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Grandfathered")] public static Func<IDataReader, object> GetRowParser(this IDataReader reader, Type type, int startIndex = 0, int length = -1, bool returnNullIfFirstMissing = false) { return WrapObjectReader(GetDeserializer(type, GetDbDataReader(reader), startIndex, length, returnNullIfFirstMissing)); } /// <summary> /// Gets the row parser for a specific row on a data reader. This allows for type switching every row based on, for example, a TypeId column. /// You could return a collection of the base type but have each more specific. /// </summary> /// <param name="reader">The data reader to get the parser for the current row from</param> /// <param name="type">The type to get the parser for</param> /// <param name="startIndex">The start column index of the object (default 0)</param> /// <param name="length">The length of columns to read (default -1 = all fields following startIndex)</param> /// <param name="returnNullIfFirstMissing">Return null if we can't find the first column? (default false)</param> /// <returns>A parser for this specific object from this row.</returns> public static Func<DbDataReader, object> GetRowParser(this DbDataReader reader, Type type, int startIndex = 0, int length = -1, bool returnNullIfFirstMissing = false) { return GetDeserializer(type, reader, startIndex, length, returnNullIfFirstMissing); } /// <inheritdoc cref="GetRowParser{T}(DbDataReader, Type, int, int, bool)"/> #if DEBUG // make sure we're not using this internally [Obsolete(nameof(DbDataReader) + " API should be preferred")] #endif [System.Diagnostics.CodeAnalysis.SuppressMessage("ApiDesign", "RS0026:Do not add multiple public overloads with optional parameters", Justification = "Grandfathered")] public static Func<IDataReader, T> GetRowParser<T>(this IDataReader reader, Type? concreteType = null, int startIndex = 0, int length = -1, bool returnNullIfFirstMissing = false) { concreteType ??= typeof(T); var func = GetDeserializer(concreteType, GetDbDataReader(reader), startIndex, length, returnNullIfFirstMissing); return Wrap(func); // this is just to be very clear about what we're capturing static Func<IDataReader, T> Wrap(Func<DbDataReader, object> func) => reader => (T)func(GetDbDataReader(reader)); } /// <summary> /// Gets the row parser for a specific row on a data reader. This allows for type switching every row based on, for example, a TypeId column. /// You could return a collection of the base type but have each more specific. /// </summary> /// <typeparam name="T">The type of results to return.</typeparam> /// <param name="reader">The data reader to get the parser for the current row from.</param> /// <param name="concreteType">The type to get the parser for.</param> /// <param name="startIndex">The start column index of the object (default: 0).</param> /// <param name="length">The length of columns to read (default: -1 = all fields following startIndex).</param> /// <param name="returnNullIfFirstMissing">Return null if we can't find the first column? (default: false).</param> /// <returns>A parser for this specific object from this row.</returns> /// <example> /// var result = new List&lt;BaseType&gt;(); /// using (var reader = connection.ExecuteReader(@" /// select 'abc' as Name, 1 as Type, 3.0 as Value /// union all /// select 'def' as Name, 2 as Type, 4.0 as Value")) /// { /// if (reader.Read()) /// { /// var toFoo = reader.GetRowParser&lt;BaseType&gt;(typeof(Foo)); /// var toBar = reader.GetRowParser&lt;BaseType&gt;(typeof(Bar)); /// var col = reader.GetOrdinal("Type"); /// do /// { /// switch (reader.GetInt32(col)) /// { /// case 1: /// result.Add(toFoo(reader)); /// break; /// case 2: /// result.Add(toBar(reader)); /// break; /// } /// } while (reader.Read()); /// } /// } /// ///
SqlMapper
csharp
rabbitmq__rabbitmq-dotnet-client
projects/RabbitMQ.Client/IProtocol.cs
{ "start": 1571, "end": 2373 }
public interface ____ { /// <summary> /// Retrieve the protocol's API name, used for printing, /// configuration properties, IDE integration, Protocols.cs etc. /// </summary> string ApiName { get; } /// <summary> /// Retrieve the protocol's default TCP port. /// </summary> int DefaultPort { get; } /// <summary> /// Retrieve the protocol's major version number. /// </summary> int MajorVersion { get; } /// <summary> /// Retrieve the protocol's minor version number. /// </summary> int MinorVersion { get; } /// <summary> /// Retrieve the protocol's revision (if specified). /// </summary> int Revision { get; } } }
IProtocol
csharp
dotnetcore__FreeSql
FreeSql.Tests/FreeSql.Tests/UnitTest3.cs
{ "start": 4757, "end": 33021 }
public class ____ { public Guid Id { get; set; } public int cateId { get; set; } public tcate01 cate { get; set; } } [Fact] public void Test03() { g.sqlite.Delete<tcate01>().Where("1=1").ExecuteAffrows(); g.sqlite.Delete<tshop01>().Where("1=1").ExecuteAffrows(); var tshoprepo = g.sqlite.GetRepository<tcate01>(); tshoprepo.DbContextOptions.EnableCascadeSave = true; tshoprepo.Insert(new tcate01[] { new tcate01 { name = "tcate1", tshops = new List<tshop01>{ new tshop01(), new tshop01(), new tshop01() } }, new tcate01 { name = "tcate1", tshops = new List<tshop01>{ new tshop01(), new tshop01(), new tshop01() } } }); var tshop01sql = g.sqlite.Select<tshop01>().Include(a => a.cate).ToSql(); var tshop02sql = g.sqlite.Select<tshop01>().IncludeByPropertyName("cate").ToSql(); var tshop03sql = g.sqlite.Select<tshop01>().IncludeMany(a => a.cate.tshops).ToSql(); var tshop04sql = g.sqlite.Select<tshop01>().IncludeByPropertyName("cate.tshops").ToSql(); var tshop01lst = g.sqlite.Select<tshop01>().Include(a => a.cate).ToList(); var tshop02lst = g.sqlite.Select<tshop01>().IncludeByPropertyName("cate").ToList(); var tshop03lst = g.sqlite.Select<tshop01>().IncludeMany(a => a.cate.tshops).ToList(); var tshop04lst = g.sqlite.Select<tshop01>().IncludeByPropertyName("cate.tshops").ToList(); var testisnullsql1 = g.sqlite.Select<t102>().Where(a => SqlExt.IsNull(a.isxx, false).Equals( true)).ToSql(); var testisnullsql2 = g.sqlite.Select<t102>().Where(a => SqlExt.IsNull(a.isxx, false).Equals(false)).ToSql(); var guid1 = Guid.NewGuid(); var guid2 = Guid.NewGuid(); var guid3 = Guid.NewGuid(); var tqsql = g.sqlite.Select<tq01, t102, t102>() .WithSql( g.sqlite.Select<tq01>().As("sub1").Where(a => a.id == guid1).ToSql(), g.sqlite.Select<t102>().As("sub2").Where(a => a.id == guid2).ToSql(), g.sqlite.Select<t102>().As("sub3").Where(a => a.id == guid3).ToSql() ) .LeftJoin((a, b, c) => a.id == b.id) .LeftJoin((a, b, c) => b.id == c.id) .ToSql(); var updateSql = g.sqlite.Update<object>() .AsType(typeof(testInsertNullable)) .SetDto(new { str1 = "xxx" }) .WhereDynamic(1) .ToSql(); var sqlextMax112 = g.sqlserver.Select<EdiItem>() .GroupBy(a => a.Id) .ToSql(a => new { Id = a.Key, EdiId1 = SqlExt.Max(a.Key).Over().PartitionBy(new { a.Value.EdiId, a.Value.Id }).OrderByDescending(new { a.Value.EdiId, a.Value.Id }).ToValue(), EdiId2 = SqlExt.Max(a.Key).Over().PartitionBy(a.Value.EdiId).OrderByDescending(a.Value.Id).ToValue(), EdiId3 = SqlExt.Sum(a.Key).ToValue(), EdiId4 = a.Sum(a.Key) }); Assert.Throws<ArgumentException>(() => g.sqlite.Update<testUpdateNonePk>().SetSource(new testUpdateNonePk()).ExecuteAffrows()); g.sqlite.Insert(new testInsertNullable()).NoneParameter().ExecuteAffrows(); g.sqlite.Select<testInsertNullable>().Select(a => a.Id).ToList(); var ddlsql = g.sqlite.CodeFirst.GetComparisonDDLStatements(typeof(testInsertNullable), "tb123123"); Assert.Equal(@"CREATE TABLE IF NOT EXISTS ""main"".""tb123123"" ( ""Id"" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ""str1"" NVARCHAR(255) NOT NULL, ""int1"" INTEGER NOT NULL, ""int2"" INTEGER , ""price"" DECIMAL(10,5) ) ; ", ddlsql); var select16Sql1 = g.sqlite.Select<userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo>() .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => b.userid == a.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => c.userid == b.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => d.userid == c.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => e.userid == d.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => f.userid == e.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => g.userid == f.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => h.userid == g.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => i.userid == h.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => j.userid == i.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => k.userid == j.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => l.userid == k.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => m.userid == l.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => n.userid == m.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => o.userid == n.userid) .InnerJoin((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => p.userid == o.userid) .ToSql((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => p); Assert.Equal(@"SELECT p.""userid"" as1, p.""badgenumber"" as2, p.""ssn"" as3, p.""IDCardNo"" as4, p.""name"" as5, p.""title"" as6, p.""birthday"" as7, p.""hiredday"" as8, p.""hetongdate"" as9, p.""street"" as10, p.""zip"" as11, p.""ophone"" as12, p.""pager"" as13, p.""fphone"" as14, p.""CardNo"" as15, p.""email"" as16, p.""idcardvalidtime"" as17, p.""homeaddress"" as18, p.""minzu"" as19, p.""leavedate"" as20, p.""loginpass"" as21, p.""picurl"" as22, p.""managerid"" as23 FROM ""userinfo"" a INNER JOIN ""userinfo"" b ON b.""userid"" = a.""userid"" INNER JOIN ""userinfo"" c ON c.""userid"" = b.""userid"" INNER JOIN ""userinfo"" d ON d.""userid"" = c.""userid"" INNER JOIN ""userinfo"" e ON e.""userid"" = d.""userid"" INNER JOIN ""userinfo"" f ON f.""userid"" = e.""userid"" INNER JOIN ""userinfo"" g ON g.""userid"" = f.""userid"" INNER JOIN ""userinfo"" h ON h.""userid"" = g.""userid"" INNER JOIN ""userinfo"" i ON i.""userid"" = h.""userid"" INNER JOIN ""userinfo"" j ON j.""userid"" = i.""userid"" INNER JOIN ""userinfo"" k ON k.""userid"" = j.""userid"" INNER JOIN ""userinfo"" l ON l.""userid"" = k.""userid"" INNER JOIN ""userinfo"" m ON m.""userid"" = l.""userid"" INNER JOIN ""userinfo"" n ON n.""userid"" = m.""userid"" INNER JOIN ""userinfo"" o ON o.""userid"" = n.""userid"" INNER JOIN ""userinfo"" p ON p.""userid"" = o.""userid""", select16Sql1); var select16Sql2 = g.sqlite.Select<userinfo>() .From<userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo, userinfo>( (s, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => s .InnerJoin(a => b.userid == a.userid) .InnerJoin(a => c.userid == b.userid) .InnerJoin(a => d.userid == c.userid) .InnerJoin(a => e.userid == d.userid) .InnerJoin(a => f.userid == e.userid) .InnerJoin(a => g.userid == f.userid) .InnerJoin(a => h.userid == g.userid) .InnerJoin(a => i.userid == h.userid) .InnerJoin(a => j.userid == i.userid) .InnerJoin(a => k.userid == j.userid) .InnerJoin(a => l.userid == k.userid) .InnerJoin(a => m.userid == l.userid) .InnerJoin(a => n.userid == m.userid) .InnerJoin(a => o.userid == n.userid) .InnerJoin(a => p.userid == o.userid) ) .ToSql((a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) => p); Assert.Equal(@"SELECT p.""userid"" as1, p.""badgenumber"" as2, p.""ssn"" as3, p.""IDCardNo"" as4, p.""name"" as5, p.""title"" as6, p.""birthday"" as7, p.""hiredday"" as8, p.""hetongdate"" as9, p.""street"" as10, p.""zip"" as11, p.""ophone"" as12, p.""pager"" as13, p.""fphone"" as14, p.""CardNo"" as15, p.""email"" as16, p.""idcardvalidtime"" as17, p.""homeaddress"" as18, p.""minzu"" as19, p.""leavedate"" as20, p.""loginpass"" as21, p.""picurl"" as22, p.""managerid"" as23 FROM ""userinfo"" a INNER JOIN ""userinfo"" b ON b.""userid"" = a.""userid"" INNER JOIN ""userinfo"" c ON c.""userid"" = b.""userid"" INNER JOIN ""userinfo"" d ON d.""userid"" = c.""userid"" INNER JOIN ""userinfo"" e ON e.""userid"" = d.""userid"" INNER JOIN ""userinfo"" f ON f.""userid"" = e.""userid"" INNER JOIN ""userinfo"" g ON g.""userid"" = f.""userid"" INNER JOIN ""userinfo"" h ON h.""userid"" = g.""userid"" INNER JOIN ""userinfo"" i ON i.""userid"" = h.""userid"" INNER JOIN ""userinfo"" j ON j.""userid"" = i.""userid"" INNER JOIN ""userinfo"" k ON k.""userid"" = j.""userid"" INNER JOIN ""userinfo"" l ON l.""userid"" = k.""userid"" INNER JOIN ""userinfo"" m ON m.""userid"" = l.""userid"" INNER JOIN ""userinfo"" n ON n.""userid"" = m.""userid"" INNER JOIN ""userinfo"" o ON o.""userid"" = n.""userid"" INNER JOIN ""userinfo"" p ON p.""userid"" = o.""userid""", select16Sql2); var sqlxx = g.pgsql.InsertOrUpdate<userinfo>().SetSource(new userinfo { userid = 10 }).UpdateColumns(a => new { a.birthday, a.CardNo }).ToSql(); var aff1 = g.sqlite.GetRepository<Edi, long>().Delete(10086); var aff2 = g.sqlite.Delete<Edi>(10086).ExecuteAffrows(); Assert.Equal(aff1, aff2); g.sqlserver.Delete<Edi>().Where("1=1").ExecuteAffrows(); g.sqlserver.Delete<EdiItem>().Where("1=1").ExecuteAffrows(); g.sqlserver.Insert(new[] { new Edi { Id = 1 }, new Edi { Id = 2 }, new Edi { Id = 3 }, new Edi { Id = 4 }, new Edi { Id = 5 } }).ExecuteAffrows(); g.sqlserver.Insert(new[] { new EdiItem { Id = 1, EdiId = 1 }, new EdiItem { Id = 2, EdiId = 1 }, new EdiItem { Id = 3, EdiId = 1 } , new EdiItem { Id = 4, EdiId = 2 }, new EdiItem { Id = 5, EdiId = 2 }, new EdiItem { Id = 6, EdiId = 3 }, new EdiItem { Id = 7, EdiId = 3 }, new EdiItem { Id = 8, EdiId = 4 }, new EdiItem { Id = 9, EdiId = 4 }, new EdiItem { Id = 10, EdiId = 5 }, new EdiItem { Id = 11, EdiId = 5 }, }).ExecuteAffrows(); var testStringFormat = g.sqlite.Select<Edi>().First(a => new { str = $"x{a.Id}_{DateTime.Now.ToString("yyyyMM")}z", str2 = string.Format("{0}x{0}_{1}z", a.Id, DateTime.Now.ToString("yyyyMM")) }); var sql123 = g.sqlserver.Select<Edi>() .WithSql( g.sqlserver.Select<Edi>().ToSql(a => new { a.Id }, FieldAliasOptions.AsProperty) + " UNION ALL " + g.sqlserver.Select<Edi>().ToSql(a => new { a.Id }, FieldAliasOptions.AsProperty)) .Page(1, 10).ToSql("Id"); var sqlextMax1 = g.sqlserver.Select<EdiItem>() .GroupBy(a => a.Id) .ToSql(a => new { Id = a.Key, EdiId1 = SqlExt.Max(a.Key).Over().PartitionBy(new { a.Value.EdiId, a.Value.Id }).OrderByDescending(new { a.Value.EdiId, a.Value.Id }).ToValue(), EdiId2 = SqlExt.Max(a.Key).Over().PartitionBy(a.Value.EdiId).OrderByDescending(a.Value.Id).ToValue(), EdiId3 = SqlExt.Sum(a.Key).ToValue(), EdiId4 = a.Sum(a.Key) }); var sqlextIsNull = g.sqlserver.Select<EdiItem>() .ToSql(a => new { nvl = SqlExt.IsNull(a.EdiId, 0) }); var sqlextGroupConcat = g.mysql.Select<Edi, EdiItem>() .InnerJoin((a, b) => b.Id == a.Id) .ToSql((a, b) => new { Id = a.Id, EdiId = b.Id, case1 = SqlExt.Case() .When(a.Id == 1, 10) .When(a.Id == 2, 11) .When(a.Id == 3, 12) .When(a.Id == 4, 13) .When(a.Id == 5, SqlExt.Case().When(b.Id == 1, 10000).Else(999).End()) .End(), groupct1 = SqlExt.GroupConcat(a.Id).Distinct().OrderBy(b.EdiId).Separator("_").ToValue(), testb1 = b == null ? 1 : 0, testb2 = b != null ? 1 : 0, }); var sqlextGroupConcatToList = g.mysql.Select<Edi, EdiItem>() .InnerJoin((a, b) => b.Id == a.Id) .ToList((a, b) => new { Id = a.Id, EdiId = b.Id, case1 = SqlExt.Case() .When(a.Id == 1, 10) .When(a.Id == 2, 11) .When(a.Id == 3, 12) .When(a.Id == 4, 13) .When(a.Id == 5, SqlExt.Case().When(b.Id == 1, 10000).Else(999).End()) .End(), groupct1 = SqlExt.GroupConcat(a.Id).Distinct().OrderBy(b.EdiId).Separator("_").ToValue(), testb1 = b == null ? 1 : 0, testb2 = b != null ? 1 : 0, }); var sqlextCase = g.sqlserver.Select<Edi, EdiItem>() .InnerJoin((a, b) => b.Id == a.Id) .ToSql((a, b) => new { Id = a.Id, EdiId = b.Id, case1 = SqlExt.Case() .When(a.Id == 1, 10) .When(a.Id == 2, 11) .When(a.Id == 3, 12) .When(a.Id == 4, 13) .When(a.Id == 5, SqlExt.Case().When(b.Id == 1, 10000).Else(999).End()) .End(), over1 = SqlExt.Rank().Over().OrderBy(a.Id).OrderByDescending(b.EdiId).ToValue(), }); var sqlextCaseToList = g.sqlserver.Select<Edi, EdiItem>() .InnerJoin((a, b) => b.Id == a.Id) .ToList((a, b) => new { Id = a.Id, EdiId = b.Id, case1 = SqlExt.Case() .When(a.Id == 1, 10) .When(a.Id == 2, 11) .When(a.Id == 3, 12) .When(a.Id == 4, 13) .When(a.Id == 5, SqlExt.Case().When(b.Id == 1, 10000).Else(999).End()) .End(), over1 = SqlExt.Rank().Over().OrderBy(a.Id).OrderByDescending(b.EdiId).ToValue(), }); var sqlextCaseGroupBy1 = g.sqlserver.Select<Edi, EdiItem>() .InnerJoin((a, b) => b.Id == a.Id) .GroupBy((a, b) => new { aid = a.Id, bid = b.Id }) .ToDictionary(a => new { sum = a.Sum(a.Value.Item2.EdiId), testb1 = a.Value.Item2 == null ? 1 : 0, testb2 = a.Value.Item2 != null ? 1 : 0, }); var sqlextCaseGroupBy2 = g.sqlserver.Select<Edi, EdiItem>() .InnerJoin((a, b) => b.Id == a.Id) .GroupBy((a, b) => new { aid = a.Id, bid = b.Id }) .ToList(a => new { a.Key, sum = a.Sum(a.Value.Item2.EdiId), testb1 = a.Value.Item2 == null ? 1 : 0, testb2 = a.Value.Item2 != null ? 1 : 0, }); var sqlextOver = g.sqlserver.Select<Edi, EdiItem>() .InnerJoin((a, b) => b.Id == a.Id) .ToSql((a, b) => new { Id = a.Id, EdiId = b.Id, over1 = SqlExt.Rank().Over().OrderBy(a.Id).OrderByDescending(b.EdiId).ToValue() }); var sqlextOverToList = g.sqlserver.Select<Edi, EdiItem>() .InnerJoin((a, b) => b.Id == a.Id) .ToList((a, b) => new { Id = a.Id, EdiId = b.Id, over1 = SqlExt.Rank().Over().OrderBy(a.Id).OrderByDescending(b.EdiId).ToValue() }); var tttrule = 8; var tttid = new long[] { 18, 19, 4017 }; g.sqlserver.Update<Author123>().Set(it => it.SongId == (short)(it.SongId & ~tttrule)).Where(it => (it.SongId & tttrule) == tttrule && !tttid.Contains(it.Id)).ExecuteAffrows(); g.sqlite.Delete<Song123>().Where("1=1").ExecuteAffrows(); g.sqlite.Delete<Author123>().Where("1=1").ExecuteAffrows(); g.sqlite.Insert(new Song123(1)).ExecuteAffrows(); g.sqlite.Insert(new Author123(11, 1)).ExecuteAffrows(); var song = g.sqlite.Select<Song123>() .From<Author123>((a, b) => a.InnerJoin(a1 => a1.Id == b.SongId)) .First((a, b) => a); // throw error Console.WriteLine(song == null); g.sqlite.Select<Edi>().ToList(); var itemId2 = 2; var itemId = 1; var edi = g.sqlite.Select<Edi>() .Where(a => a.Id == itemId2 && g.sqlite.Select<EdiItem>().Where(b => b.Id == itemId).Any()) .First(a => a); //#231 var lksdjkg1 = g.sqlite.Select<Edi>() .AsQueryable().Where(a => a.Id > 0).Where(a => a.Id == 1).ToList(); var lksdjkg11 = g.sqlite.Select<Edi>() .AsQueryable().Where(a => a.Id > 0).Where(a => a.Id == 1).Any(); var lksdjkg2 = g.sqlite.Select<Edi>() .AsQueryable().Where(a => a.Id > 0).First(); var lksdjkg3 = g.sqlite.Select<Edi>() .AsQueryable().Where(a => a.Id > 0).FirstOrDefault(); var sql222efe = g.sqlite.Select<Edi, EdiItem>() .InnerJoin((a, b) => b.Id == g.sqlite.Select<EdiItem>().As("c").Where(c => c.EdiId == a.Id).OrderBy(c => c.Id).ToOne(c => c.Id)) .ToSql((a, b) => new { Id = a.Id, EdiId = b.Id }); var subSyetemId = "xxx"; var list = g.sqlite.Select<Menu, SubSystem>() .LeftJoin((a,b) => a.SubNameID == b.Id) .WhereIf(!string.IsNullOrEmpty(subSyetemId), (a, s) => a.SubNameID == subSyetemId) .ToList((a, s) => new Menu { ID = a.ID, SystemName = s.Name, SubNameID = s.Id, CreateTime = a.CreateTime, Description = a.Description, EnName = a.EnName, Name = a.Name, OperationIds = a.OperationIds, Parent = a.Parent, ParentID = a.ParentID, Url = a.Url, UserID = a.UserID }); var context = new TestDbContext(g.sqlite); var sql = context.Songs .Where(a => context.Authors //.Select //加上这句就不报错,不加上报 variable 'a' of type 'Song' referenced from scope '', but it is not defined .Where(b => b.SongId == a.Id) .Any()) .ToSql(a => a.Name); sql = context.Songs .Where(a => context.Authors .Select //加上这句就不报错,不加上报 variable 'a' of type 'Song' referenced from scope '', but it is not defined .Where(b => b.SongId == a.Id) .Any()) .ToSql(a => a.Name); //using (var conn = new SqlConnection("Data Source=.;Integrated Security=True;Initial Catalog=webchat-abc;Pooling=true;Max Pool Size=13")) //{ // conn.Open(); // conn.Close(); //} //using (var fsql = new FreeSql.FreeSqlBuilder() // .UseConnectionString(FreeSql.DataType.SqlServer, "Data Source=.;Integrated Security=True;Initial Catalog=webchat-abc;Pooling=true;Max Pool Size=13") // .UseAutoSyncStructure(true) // //.UseGenerateCommandParameterWithLambda(true) // .UseMonitorCommand( // cmd => Trace.WriteLine("\r\n线程" + Thread.CurrentThread.ManagedThreadId + ": " + cmd.CommandText) //监听SQL命令对象,在执行前 // //, (cmd, traceLog) => Console.WriteLine(traceLog) // ) // .UseLazyLoading(true) // .Build()) //{ // fsql.Select<ut3_t1>().ToList(); //} //var testByte = new TestByte { pic = File.ReadAllBytes(@"C:\Users\28810\Desktop\71500003-0ad69400-289e-11ea-85cb-36a54f52ebc0.png") }; //var sql = g.sqlserver.Insert(testByte).NoneParameter().ToSql(); //g.sqlserver.Insert(testByte).NoneParameter().ExecuteAffrows(); //var getTestByte = g.sqlserver.Select<TestByte>(testByte).First(); //File.WriteAllBytes(@"C:\Users\28810\Desktop\71500003-0ad69400-289e-11ea-85cb-36a54f52ebc0_write.png", getTestByte.pic); var ib = new IdleBus<IFreeSql>(TimeSpan.FromMinutes(10)); ib.Notice += (_, e2) => Trace.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] 线程{Thread.CurrentThread.ManagedThreadId}:{e2.Log}"); ib.Register("db1", () => new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=3") .UseAutoSyncStructure(true) .UseGenerateCommandParameterWithLambda(true) .UseMonitorCommand(cmd => Trace.WriteLine("\r\n线程" + Thread.CurrentThread.ManagedThreadId + ": " + cmd.CommandText)) .UseLazyLoading(true) .Build()); ib.Register("db2", () => new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.Oracle, "user id=1user;password=123456;data source=//127.0.0.1:1521/XE;Pooling=true;Max Pool Size=3") .UseAutoSyncStructure(true) .UseGenerateCommandParameterWithLambda(true) .UseLazyLoading(true) .UseNameConvert(FreeSql.Internal.NameConvertType.ToUpper) .UseMonitorCommand(cmd => Trace.WriteLine("\r\n线程" + Thread.CurrentThread.ManagedThreadId + ": " + cmd.CommandText)) .Build()); ib.Register("db3", () => new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|\document.db;Attachs=xxxtb.db;Pooling=true;Max Pool Size=3") .UseAutoSyncStructure(true) .UseGenerateCommandParameterWithLambda(true) .UseLazyLoading(true) .UseMonitorCommand(cmd => Trace.WriteLine("\r\n线程" + Thread.CurrentThread.ManagedThreadId + ": " + cmd.CommandText)) .Build()); //...注入很多个 var fsql = ib.Get("db1"); //使用的时候用 Get 方法,不要存其引用关系 var sqlparamId = 100; fsql.Select<ut3_t1>().Limit(10).Where(a => a.id == sqlparamId).ToList(); fsql = ib.Get("db2"); fsql.Select<ut3_t1>().Limit(10).Where(a => a.id == sqlparamId).ToList(); fsql = ib.Get("db3"); fsql.Select<ut3_t1>().Limit(10).Where(a => a.id == sqlparamId).ToList(); fsql = g.sqlserver; fsql.Insert<OrderMain>(new OrderMain { OrderNo = "1001", OrderTime = new DateTime(2019, 12, 01) }).ExecuteAffrows(); fsql.Insert<OrderDetail>(new OrderDetail { OrderNo = "1001", ItemNo = "I001", Qty = 1 }).ExecuteAffrows(); fsql.Insert<OrderDetail>(new OrderDetail { OrderNo = "1001", ItemNo = "I002", Qty = 1 }).ExecuteAffrows(); fsql.Insert<OrderDetail>(new OrderDetail { OrderNo = "1001", ItemNo = "I003", Qty = 1 }).ExecuteAffrows(); fsql.Insert<OrderMain>(new OrderMain { OrderNo = "1002", OrderTime = new DateTime(2019, 12, 02) }).ExecuteAffrows(); fsql.Insert<OrderDetail>(new OrderDetail { OrderNo = "1002", ItemNo = "I011", Qty = 1 }).ExecuteAffrows(); fsql.Insert<OrderDetail>(new OrderDetail { OrderNo = "1002", ItemNo = "I012", Qty = 1 }).ExecuteAffrows(); fsql.Insert<OrderDetail>(new OrderDetail { OrderNo = "1002", ItemNo = "I013", Qty = 1 }).ExecuteAffrows(); fsql.Ado.Query<object>("select * from OrderDetail left join OrderMain on OrderDetail.OrderNo=OrderMain.OrderNo where OrderMain.OrderNo='1001'"); g.oracle.Delete<SendInfo>().Where("1=1").ExecuteAffrows(); g.oracle.Insert(new[] { new SendInfo{ Code = "001", Binary = Encoding.UTF8.GetBytes("我是中国人") }, new SendInfo{ Code = "002", Binary = Encoding.UTF8.GetBytes("我是地球人") }, new SendInfo{ Code = "003", Binary = Encoding.UTF8.GetBytes("我是.net")}, new SendInfo{ Code = "004", Binary = Encoding.UTF8.GetBytes("我是freesql") }, new SendInfo{ Code = "005", Binary = Encoding.UTF8.GetBytes("我是freesql233") }, }) .NoneParameter() .BatchOptions(3, 200) .BatchProgress(a => Trace.WriteLine($"{a.Current}/{a.Total}")) .ExecuteAffrows(); var slslsl = g.oracle.Select<SendInfo>().ToList(); var slsls1Ids = slslsl.Select(a => a.ID).ToArray(); var slslss2 = g.oracle.Select<SendInfo>().Where(a => slsls1Ids.Contains(a.ID)).ToList(); var mt_codeId = Guid.Parse("2f48c5ca-7257-43c8-9ee2-0e16fa990253"); Assert.Equal(1, g.oracle.Insert(new SendInfo { ID = mt_codeId, Code = "mt_code", Binary = Encoding.UTF8.GetBytes("我是mt_code") }) .ExecuteAffrows()); var mt_code = g.oracle.Select<SendInfo>().Where(a => a.ID == mt_codeId).First(); Assert.NotNull(mt_code); Assert.Equal(mt_codeId, mt_code.ID); Assert.Equal("mt_code", mt_code.Code); mt_code = g.oracle.Select<SendInfo>().Where(a => a.ID == Guid.Parse("2f48c5ca725743c89ee20e16fa990253".ToUpper())).First(); Assert.NotNull(mt_code); Assert.Equal(mt_codeId, mt_code.ID); Assert.Equal("mt_code", mt_code.Code); mt_codeId = Guid.Parse("2f48c5ca-7257-43c8-9ee2-0e16fa990251"); Assert.Equal(1, g.oracle.Insert(new SendInfo { ID = mt_codeId, Code = "mt_code2", Binary = Encoding.UTF8.GetBytes("我是mt_code2") }) .NoneParameter() .ExecuteAffrows()); mt_code = g.oracle.Select<SendInfo>().Where(a => a.ID == mt_codeId).First(); Assert.NotNull(mt_code); Assert.Equal(mt_codeId, mt_code.ID); Assert.Equal("mt_code2", mt_code.Code); mt_code = g.oracle.Select<SendInfo>().Where(a => a.ID == Guid.Parse("2f48c5ca725743c89ee20e16fa990251".ToUpper())).First(); Assert.NotNull(mt_code); Assert.Equal(mt_codeId, mt_code.ID); Assert.Equal("mt_code2", mt_code.Code); var id = g.oracle.Insert(new TestORC12()).ExecuteIdentity(); }
tshop01
csharp
MassTransit__MassTransit
src/MassTransit/Futures/Futures/FutureRequest.cs
{ "start": 273, "end": 2613 }
class ____ TInput : class { ContextMessageFactory<BehaviorContext<FutureState, TInput>, TRequest> _factory; public FutureRequest() { _factory = new ContextMessageFactory<BehaviorContext<FutureState, TInput>, TRequest>(DefaultFactory); AddressProvider = PublishAddressProvider; } public RequestAddressProvider<TInput> AddressProvider { get; set; } public PendingFutureIdProvider<TRequest> PendingRequestIdProvider { get; set; } public ContextMessageFactory<BehaviorContext<FutureState, TInput>, TRequest> Factory { set => _factory = value; } public IEnumerable<ValidationResult> Validate() { if (_factory == null) yield return this.Failure("Response", "Factory", "Init or Create must be configured"); if (AddressProvider == null) yield return this.Failure("RequestAddressProvider", "must not be null"); } static Uri PublishAddressProvider<T>(BehaviorContext<FutureState, T> context) where T : class { return default; } public async Task SendRequest(BehaviorContext<FutureState, TInput> context) { var destinationAddress = AddressProvider(context); var endpoint = destinationAddress != null ? await context.GetSendEndpoint(destinationAddress).ConfigureAwait(false) : await context.ReceiveContext.PublishEndpointProvider.GetPublishEndpoint<TRequest>(context, default); await _factory.Use(context, async (ctx, s) => { var pipe = new FutureRequestPipe<TRequest>(s.Pipe, context.ReceiveContext.InputAddress, context.Saga.CorrelationId); await endpoint.Send(s.Message, pipe, ctx.CancellationToken).ConfigureAwait(false); if (PendingRequestIdProvider != null) { var pendingId = PendingRequestIdProvider(s.Message); context.Saga.Pending.Add(pendingId); } }); } static Task<SendTuple<TRequest>> DefaultFactory(BehaviorContext<FutureState, TInput> context) { return context.Init<TRequest>(context.Message); } } }
where
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/RequestFilter_Specs.cs
{ "start": 275, "end": 1342 }
public class ____ { [Test] public async Task Should_fault_instead_of_timeout() { await using var provider = new ServiceCollection() .AddMassTransitTestHarness(x => { x.AddConsumer<PingConsumer>(); x.UsingInMemory((context, cfg) => { cfg.UseConsumeFilter(typeof(RequestValidationScopedFilter<>), context); cfg.ConfigureEndpoints(context); }); }) .BuildServiceProvider(true); var harness = provider.GetTestHarness(); await harness.Start(); IRequestClient<PingMessage> client = harness.GetRequestClient<PingMessage>(); Assert.That(async () => await client.GetResponse<PongMessage>(new { CorrelationId = InVar.Id, }), Throws.TypeOf<RequestFaultException>()); }
Using_a_request_filter_with_request_client
csharp
dotnet__orleans
test/Grains/TestGrainInterfaces/IReentrancyGrain.cs
{ "start": 1258, "end": 1446 }
public interface ____ : IGrainWithIntegerKey { Task<int> GetCounter(); Task Ping(int seconds); Task SetDestination(long id); }
IReentrantSelfManagedGrain
csharp
dotnet__extensions
test/Generators/Microsoft.Gen.Logging/Unit/ParserTests.LogProperties.cs
{ "start": 7377, "end": 7495 }
public class ____ { public int Prop { get; set; } }
MyTransitiveClass
csharp
icsharpcode__ILSpy
ILSpy/Metadata/DebugDirectory/PdbChecksumTreeNode.cs
{ "start": 1381, "end": 2491 }
sealed class ____ : ILSpyTreeNode { readonly PdbChecksumDebugDirectoryData entry; public PdbChecksumTreeNode(PdbChecksumDebugDirectoryData entry) { this.entry = entry; } override public object Text => nameof(DebugDirectoryEntryType.PdbChecksum); public override object ToolTip => "The entry stores a crypto hash of the content of the symbol file the PE/COFF\n" + "file was built with. The hash can be used to validate that a given PDB file was\n" + "built with the PE/COFF file and not altered in any way. More than one entry can\n" + "be present if multiple PDBs were produced during the build of the PE/COFF file\n" + "(for example, private and public symbols)."; public override object Icon => Images.MetadataTable; public override bool View(TabPageModel tabPage) { tabPage.Title = Text.ToString(); tabPage.SupportsLanguageSwitching = false; var dataGrid = Helpers.PrepareDataGrid(tabPage, this); dataGrid.ItemsSource = new[] { new PdbChecksumDebugDirectoryDataEntry(entry) }; tabPage.Content = dataGrid; return true; }
PdbChecksumTreeNode
csharp
EventStore__EventStore
src/KurrentDB.Core.Tests/ClientAPI/read_all_events_forward_should.cs
{ "start": 602, "end": 3363 }
public class ____<TLogFormat, TStreamId> : SpecificationWithMiniNode<TLogFormat, TStreamId> { private EventData[] _testEvents; protected override async Task When() { await _conn.SetStreamMetadataAsync("$all", -1, StreamMetadata.Build().SetReadRole(SystemRoles.All), DefaultData.AdminCredentials); _testEvents = Enumerable.Range(0, 20).Select(x => TestEvent.NewTestEvent(x.ToString())).ToArray(); await _conn.AppendToStreamAsync("stream", ExpectedVersion.NoStream, _testEvents); } [Test, Category("LongRunning")] public async Task return_empty_slice_if_asked_to_read_from_end() { var read = await _conn.ReadAllEventsForwardAsync(Position.End, 1, false); Assert.That(read.IsEndOfStream, Is.True); Assert.That(read.Events.Length, Is.EqualTo(0)); } [Test, Category("LongRunning")] public async Task return_events_in_same_order_as_written() { var read = await _conn.ReadAllEventsForwardAsync(Position.Start, _testEvents.Length + 20, false); Assert.That(EventDataComparer.Equal( _testEvents.ToArray(), read.Events.Skip(read.Events.Length - _testEvents.Length).Select(x => x.Event).ToArray())); } [Test, Category("LongRunning")] public async Task be_able_to_read_all_one_by_one_until_end_of_stream() { var all = new List<RecordedEvent>(); var position = Position.Start; AllEventsSlice slice; while (!(slice = await _conn.ReadAllEventsForwardAsync(position, 1, false)).IsEndOfStream) { all.Add(slice.Events.Single().Event); position = slice.NextPosition; } Assert.That(EventDataComparer.Equal(_testEvents, all.Skip(all.Count - _testEvents.Length).ToArray())); } [Test, Category("LongRunning")] public async Task be_able_to_read_events_slice_at_time() { var all = new List<RecordedEvent>(); var position = Position.Start; AllEventsSlice slice; while (!(slice = await _conn.ReadAllEventsForwardAsync(position, 5, false)).IsEndOfStream) { all.AddRange(slice.Events.Select(x => x.Event)); position = slice.NextPosition; } Assert.That(EventDataComparer.Equal(_testEvents, all.Skip(all.Count - _testEvents.Length).ToArray())); } [Test, Category("LongRunning")] public async Task return_partial_slice_if_not_enough_events() { var read = await _conn.ReadAllEventsForwardAsync(Position.Start, 40, false); Assert.That(read.Events.Length, Is.LessThan(40)); Assert.That(EventDataComparer.Equal( _testEvents, read.Events.Skip(read.Events.Length - _testEvents.Length).Select(x => x.Event).ToArray())); } [Test] [Category("Network")] public async Task throw_when_got_int_max_value_as_maxcount() { await AssertEx.ThrowsAsync<ArgumentException>( () => _conn.ReadAllEventsForwardAsync(Position.Start, int.MaxValue, resolveLinkTos: false)); } }
read_all_events_forward_should
csharp
MaterialDesignInXAML__MaterialDesignInXamlToolkit
src/MaterialDesignThemes.Wpf/Converters/ToolBarOverflowButtonVisibilityConverter.cs
{ "start": 104, "end": 1016 }
public class ____ : IMultiValueConverter { public static readonly ToolBarOverflowButtonVisibilityConverter Instance = new(); public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var overflowMode = (OverflowMode)values[0]; var hasOverflowItems = (bool)values[1]; if (overflowMode == OverflowMode.AsNeeded && hasOverflowItems) { return Visibility.Visible; } else { return overflowMode switch { OverflowMode.Always => Visibility.Visible, OverflowMode.Never => Visibility.Hidden, _ => Visibility.Hidden, }; } } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => throw new NotImplementedException(); }
ToolBarOverflowButtonVisibilityConverter
csharp
JoshClose__CsvHelper
tests/CsvHelper.Tests/DynamicProxyTests.cs
{ "start": 494, "end": 1448 }
public class ____ { [Fact] public void WriteDynamicProxyObjectTest() { var list = new List<TestClass>(); var proxyGenerator = new Castle.DynamicProxy.ProxyGenerator(); for (var i = 0; i < 1; i++) { var proxy = proxyGenerator.CreateClassProxy<TestClass>(); proxy.Id = i + 1; proxy.Name = "name" + proxy.Id; list.Add(proxy); } using (var stream = new MemoryStream()) using (var reader = new StreamReader(stream)) using (var writer = new StreamWriter(stream)) using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture)) { csv.Context.RegisterClassMap<TestClassMap>(); csv.WriteRecords(list); writer.Flush(); stream.Position = 0; var data = reader.ReadToEnd(); var expected = new TestStringBuilder(csv.Configuration.NewLine); expected.AppendLine("id,name"); expected.AppendLine("1,name1"); Assert.Equal(expected.ToString(), data); } }
DynamicProxyTests
csharp
xunit__xunit
src/xunit.v2.tests/Sdk/TestFrameworkProxyTests.cs
{ "start": 1939, "end": 2835 }
public class ____ : ITestFrameworkTypeDiscoverer { public ThrowingDiscovererCtor() { throw new DivideByZeroException(); } public Type GetTestFrameworkType(IAttributeInfo attribute) { throw new NotImplementedException(); } } [CulturedFact("en-US")] public void Attribute_ThrowingDiscovererMethod() { var attribute = Mocks.TestFrameworkAttribute(typeof(AttributeWithThrowingDiscovererMethod)); var assembly = Mocks.AssemblyInfo(attributes: new[] { attribute }); var proxy = new TestFrameworkProxy(assembly, null, diagnosticSpy); Assert.IsType<XunitTestFramework>(proxy.InnerTestFramework); AssertSingleDiagnosticMessage("Exception thrown during test framework discoverer construction: System.DivideByZeroException: Attempted to divide by zero."); } [TestFrameworkDiscoverer("TestFrameworkProxyTests+ThrowingDiscoverer", "xunit.v2.tests")]
ThrowingDiscovererCtor
csharp
CommunityToolkit__WindowsCommunityToolkit
Microsoft.Toolkit.Uwp.UI.Animations/Expressions/ExpressionNodes/ValueKeywordKind.cs
{ "start": 335, "end": 576 }
internal enum ____ { /// <summary> /// The current value /// </summary> CurrentValue, /// <summary> /// The starting value /// </summary> StartingValue, } }
ValueKeywordKind
csharp
dotnet__aspnetcore
src/DataProtection/DataProtection/src/KeyManagement/KeyExtensions.cs
{ "start": 215, "end": 379 }
internal static class ____ { public static bool IsExpired(this IKey key, DateTimeOffset now) { return (key.ExpirationDate <= now); } }
KeyExtensions
csharp
JamesNK__Newtonsoft.Json
Src/Newtonsoft.Json.Tests/JsonConvertTest.cs
{ "start": 71935, "end": 72609 }
public sealed class ____ { private static readonly DateTime s_unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); [JsonProperty("exp")] private int _expiration { get { return (int)((Expiration - s_unixEpoch).TotalSeconds); } set { Expiration = s_unixEpoch.AddSeconds(value); } } public bool Active { get; set; } [JsonIgnore] public DateTime Expiration { get; set; } } } }
ItemsRequiredObjectWithIgnoredProperty
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/Serialization/SerializationTest.cs
{ "start": 226, "end": 6514 }
public abstract class ____ : InMemoryTestFixture { readonly Uri _destinationAddress = new Uri("loopback://localhost/destination"); readonly Uri _faultAddress = new Uri("loopback://localhost/fault"); protected readonly Guid _requestId = Guid.NewGuid(); readonly Uri _responseAddress = new Uri("loopback://localhost/response"); readonly Type _serializerType; readonly Uri _sourceAddress = new Uri("loopback://localhost/source"); protected IMessageDeserializer Deserializer; protected IMessageSerializer Serializer; public SerializationTest(Type serializerType) { _serializerType = serializerType; } [OneTimeSetUp] public void SetupSerializationTest() { if (_serializerType == typeof(NewtonsoftJsonMessageSerializer)) { Serializer = new NewtonsoftJsonMessageSerializer(); Deserializer = new NewtonsoftJsonMessageDeserializer(NewtonsoftJsonMessageSerializer.Deserializer); } else if (_serializerType == typeof(SystemTextJsonMessageSerializer)) { var serializer = new SystemTextJsonMessageSerializer(); Serializer = serializer; Deserializer = serializer; } else if (_serializerType == typeof(BsonMessageSerializer)) { Serializer = new BsonMessageSerializer(); Deserializer = new NewtonsoftBsonMessageDeserializer(BsonMessageSerializer.Deserializer); } else if (_serializerType == typeof(NewtonsoftXmlMessageSerializer)) { Serializer = new NewtonsoftXmlMessageSerializer(); Deserializer = new NewtonsoftXmlMessageDeserializer(NewtonsoftXmlJsonMessageSerializer.Deserializer); } else if (_serializerType == typeof(EncryptedMessageSerializer)) { ISymmetricKeyProvider keyProvider = new TestSymmetricKeyProvider(); var streamProvider = new AesCryptoStreamProvider(keyProvider, "default"); Serializer = new EncryptedMessageSerializer(streamProvider); Deserializer = new EncryptedMessageDeserializer(BsonMessageSerializer.Deserializer, streamProvider); } else if (_serializerType == typeof(EncryptedMessageSerializerV2)) { var key = new byte[] { 31, 182, 254, 29, 98, 114, 85, 168, 176, 48, 113, 206, 198, 176, 181, 125, 106, 134, 98, 217, 113, 158, 88, 75, 118, 223, 117, 160, 224, 1, 47, 162 }; var keyProvider = new ConstantSecureKeyProvider(key); var streamProvider = new AesCryptoStreamProviderV2(keyProvider); Serializer = new EncryptedMessageSerializerV2(streamProvider); Deserializer = new EncryptedMessageDeserializerV2(BsonMessageSerializer.Deserializer, streamProvider); } else if (_serializerType == typeof(MessagePackMessageSerializer)) { var messagePackSerializer = new MessagePackMessageSerializer(); Serializer = messagePackSerializer; Deserializer = messagePackSerializer; } else throw new ArgumentException("The serializer type is unknown"); } protected T SerializeAndReturn<T>(T obj) where T : class { var serializedMessageData = Serialize(obj); return Return<T>(serializedMessageData); } protected byte[] Serialize<T>(T obj) where T : class { var sendContext = new MessageSendContext<T>(obj) { SourceAddress = _sourceAddress, DestinationAddress = _destinationAddress, FaultAddress = _faultAddress, ResponseAddress = _responseAddress, RequestId = _requestId }; var serializedMessageData = Serializer.GetMessageBody(sendContext).GetBytes(); return serializedMessageData; } protected T Return<T>(byte[] serializedMessageData) where T : class { var message = new InMemoryTransportMessage(Guid.NewGuid(), serializedMessageData, Serializer.ContentType.MediaType); var receiveContext = new InMemoryReceiveContext(message, TestConsumeContext.GetContext()); var consumeContext = Deserializer.Deserialize(receiveContext); consumeContext.TryGetMessage(out ConsumeContext<T> messageContext); Assert.That(messageContext, Is.Not.Null); Assert.Multiple(() => { Assert.That(messageContext.SourceAddress, Is.EqualTo(_sourceAddress)); Assert.That(messageContext.DestinationAddress, Is.EqualTo(_destinationAddress)); Assert.That(messageContext.FaultAddress, Is.EqualTo(_faultAddress)); Assert.That(messageContext.ResponseAddress, Is.EqualTo(_responseAddress)); Assert.That(messageContext.RequestId.HasValue, Is.EqualTo(true)); Assert.That(messageContext.RequestId.Value, Is.EqualTo(_requestId)); }); return messageContext.Message; } protected virtual void TestSerialization<T>(T message) where T : class { var result = SerializeAndReturn(message); Assert.That(message, Is.EqualTo(result)); } } }
SerializationTest
csharp
dotnet__aspnetcore
src/Http/Http/perf/Microbenchmarks/ValidatableTypesBenchmark.cs
{ "start": 624, "end": 6402 }
public class ____ { private IValidatableInfo _simpleTypeInfo = null!; private IValidatableInfo _complexTypeInfo = null!; private IValidatableInfo _hierarchicalTypeInfo = null!; private IValidatableInfo _ivalidatableObjectTypeInfo = null!; private ValidateContext _context = null!; private SimpleModel _simpleModel = null!; private ComplexModel _complexModel = null!; private HierarchicalModel _hierarchicalModel = null!; private ValidatableObjectModel _validatableObjectModel = null!; [GlobalSetup] public void Setup() { var services = new ServiceCollection(); var mockResolver = new MockValidatableTypeInfoResolver(); services.AddValidation(options => { // Register our mock resolver options.Resolvers.Insert(0, mockResolver); }); var serviceProvider = services.BuildServiceProvider(); var validationOptions = serviceProvider.GetRequiredService<IOptions<ValidationOptions>>().Value; _context = new ValidateContext { ValidationOptions = validationOptions, ValidationContext = new ValidationContext(new object(), serviceProvider, null), ValidationErrors = new Dictionary<string, string[]>(StringComparer.Ordinal) }; // Create the model instances _simpleModel = new SimpleModel { Id = 1, Name = "Test Name", Email = "test@example.com" }; _complexModel = new ComplexModel { Id = 1, Name = "Complex Model", Properties = new Dictionary<string, string> { ["Prop1"] = "Value1", ["Prop2"] = "Value2" }, Items = ["Item1", "Item2", "Item3"], CreatedOn = DateTime.UtcNow }; _hierarchicalModel = new HierarchicalModel { Id = 1, Name = "Parent Model", Child = new ChildModel { Id = 2, Name = "Child Model", ParentId = 1 }, Siblings = [ new SimpleModel { Id = 3, Name = "Sibling 1", Email = "sibling1@example.com" }, new SimpleModel { Id = 4, Name = "Sibling 2", Email = "sibling2@example.com" } ] }; _validatableObjectModel = new ValidatableObjectModel { Id = 1, Name = "Validatable Model", CustomField = "Valid Value" }; // Get the type info instances from validation options using the mock resolver validationOptions.TryGetValidatableTypeInfo(typeof(SimpleModel), out _simpleTypeInfo); validationOptions.TryGetValidatableTypeInfo(typeof(ComplexModel), out _complexTypeInfo); validationOptions.TryGetValidatableTypeInfo(typeof(HierarchicalModel), out _hierarchicalTypeInfo); validationOptions.TryGetValidatableTypeInfo(typeof(ValidatableObjectModel), out _ivalidatableObjectTypeInfo); // Ensure we have all type infos (this should not be needed with our mock resolver) if (_simpleTypeInfo == null || _complexTypeInfo == null || _hierarchicalTypeInfo == null || _ivalidatableObjectTypeInfo == null) { throw new InvalidOperationException("Failed to register one or more type infos with mock resolver"); } } [Benchmark(Description = "Validate Simple Model")] [BenchmarkCategory("Simple")] public async Task ValidateSimpleModel() { _context.ValidationErrors.Clear(); await _simpleTypeInfo.ValidateAsync(_simpleModel, _context, default); } [Benchmark(Description = "Validate Complex Model")] [BenchmarkCategory("Complex")] public async Task ValidateComplexModel() { _context.ValidationErrors.Clear(); await _complexTypeInfo.ValidateAsync(_complexModel, _context, default); } [Benchmark(Description = "Validate Hierarchical Model")] [BenchmarkCategory("Hierarchical")] public async Task ValidateHierarchicalModel() { _context.ValidationErrors.Clear(); await _hierarchicalTypeInfo.ValidateAsync(_hierarchicalModel, _context, default); } [Benchmark(Description = "Validate IValidatableObject Model")] [BenchmarkCategory("IValidatableObject")] public async Task ValidateIValidatableObjectModel() { _context.ValidationErrors.Clear(); await _ivalidatableObjectTypeInfo.ValidateAsync(_validatableObjectModel, _context, default); } [Benchmark(Description = "Validate invalid Simple Model")] [BenchmarkCategory("Invalid")] public async Task ValidateInvalidSimpleModel() { _context.ValidationErrors.Clear(); _simpleModel.Email = "invalid-email"; await _simpleTypeInfo.ValidateAsync(_simpleModel, _context, default); } [Benchmark(Description = "Validate invalid IValidatableObject Model")] [BenchmarkCategory("Invalid")] public async Task ValidateInvalidIValidatableObjectModel() { _context.ValidationErrors.Clear(); _validatableObjectModel.CustomField = "Invalid"; await _ivalidatableObjectTypeInfo.ValidateAsync(_validatableObjectModel, _context, default); } #region Helper methods to create type info instances manually if needed private ValidatablePropertyInfo CreatePropertyInfo(string name, Type type, params ValidationAttribute[] attributes) { return new MockValidatablePropertyInfo( typeof(SimpleModel), type, name, name, attributes); } #endregion #region Test Models
ValidatableTypeInfoBenchmark
csharp
microsoft__PowerToys
src/modules/MouseWithoutBorders/App/Class/SocketStuff.cs
{ "start": 4929, "end": 5202 }
internal enum ____ : int { NA = 0, Resolving = 1, Connecting = 2, Handshaking = 3, Error = 4, ForceClosed = 5, InvalidKey = 6, Timeout = 7, SendError = 8, Connected = 9, }
SocketStatus
csharp
dotnet__efcore
src/EFCore.SqlServer/Query/Internal/SqlServerSqlTranslatingExpressionVisitor.cs
{ "start": 957, "end": 27608 }
public class ____ : RelationalSqlTranslatingExpressionVisitor { private readonly SqlServerQueryCompilationContext _queryCompilationContext; private readonly ISqlExpressionFactory _sqlExpressionFactory; private readonly IRelationalTypeMappingSource _typeMappingSource; private readonly ISqlServerSingletonOptions _sqlServerSingletonOptions; private static readonly HashSet<string> DateTimeDataTypes = [ "time", "date", "datetime", "datetime2", "datetimeoffset" ]; private static readonly HashSet<Type> DateTimeClrTypes = [ typeof(TimeOnly), typeof(DateOnly), typeof(TimeSpan), typeof(DateTime), typeof(DateTimeOffset) ]; private static readonly HashSet<ExpressionType> ArithmeticOperatorTypes = [ ExpressionType.Add, ExpressionType.Subtract, ExpressionType.Multiply, ExpressionType.Divide, ExpressionType.Modulo ]; private static readonly MethodInfo StringStartsWithMethodInfoString = typeof(string).GetRuntimeMethod(nameof(string.StartsWith), [typeof(string)])!; private static readonly MethodInfo StringStartsWithMethodInfoChar = typeof(string).GetRuntimeMethod(nameof(string.StartsWith), [typeof(char)])!; private static readonly MethodInfo StringEndsWithMethodInfoString = typeof(string).GetRuntimeMethod(nameof(string.EndsWith), [typeof(string)])!; private static readonly MethodInfo StringEndsWithMethodInfoChar = typeof(string).GetRuntimeMethod(nameof(string.EndsWith), [typeof(char)])!; private static readonly MethodInfo StringContainsMethodInfoString = typeof(string).GetRuntimeMethod(nameof(string.Contains), [typeof(string)])!; private static readonly MethodInfo StringContainsMethodInfoChar = typeof(string).GetRuntimeMethod(nameof(string.Contains), [typeof(char)])!; private static readonly MethodInfo StringJoinMethodInfo = typeof(string).GetRuntimeMethod(nameof(string.Join), [typeof(string), typeof(string[])])!; private static readonly MethodInfo EscapeLikePatternParameterMethod = typeof(SqlServerSqlTranslatingExpressionVisitor).GetTypeInfo().GetDeclaredMethod(nameof(ConstructLikePatternParameter))!; private const char LikeEscapeChar = '\\'; private const string LikeEscapeString = "\\"; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public SqlServerSqlTranslatingExpressionVisitor( RelationalSqlTranslatingExpressionVisitorDependencies dependencies, SqlServerQueryCompilationContext queryCompilationContext, QueryableMethodTranslatingExpressionVisitor queryableMethodTranslatingExpressionVisitor, ISqlServerSingletonOptions sqlServerSingletonOptions) : base(dependencies, queryCompilationContext, queryableMethodTranslatingExpressionVisitor) { _queryCompilationContext = queryCompilationContext; _sqlExpressionFactory = dependencies.SqlExpressionFactory; _typeMappingSource = dependencies.TypeMappingSource; _sqlServerSingletonOptions = sqlServerSingletonOptions; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> protected override Expression VisitBinary(BinaryExpression binaryExpression) { if (binaryExpression.NodeType == ExpressionType.ArrayIndex && binaryExpression.Left.Type == typeof(byte[])) { return TranslateByteArrayElementAccess( binaryExpression.Left, binaryExpression.Right, binaryExpression.Type); } var visitedExpression = base.VisitBinary(binaryExpression); if (visitedExpression is SqlBinaryExpression sqlBinaryExpression && ArithmeticOperatorTypes.Contains(sqlBinaryExpression.OperatorType)) { var inferredProviderType = GetProviderType(sqlBinaryExpression.Left) ?? GetProviderType(sqlBinaryExpression.Right); if (inferredProviderType != null) { if (DateTimeDataTypes.Contains(inferredProviderType)) { return QueryCompilationContext.NotTranslatedExpression; } } else { var leftType = sqlBinaryExpression.Left.Type; var rightType = sqlBinaryExpression.Right.Type; if (DateTimeClrTypes.Contains(leftType) || DateTimeClrTypes.Contains(rightType)) { return QueryCompilationContext.NotTranslatedExpression; } } } return visitedExpression; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> protected override Expression VisitUnary(UnaryExpression unaryExpression) { if (unaryExpression.NodeType == ExpressionType.ArrayLength && unaryExpression.Operand.Type == typeof(byte[])) { if (!(base.Visit(unaryExpression.Operand) is SqlExpression sqlExpression)) { return QueryCompilationContext.NotTranslatedExpression; } var isBinaryMaxDataType = GetProviderType(sqlExpression) == "varbinary(max)" || sqlExpression is SqlParameterExpression; var dataLengthSqlFunction = Dependencies.SqlExpressionFactory.Function( "DATALENGTH", [sqlExpression], nullable: true, argumentsPropagateNullability: Statics.TrueArrays[1], isBinaryMaxDataType ? typeof(long) : typeof(int)); return isBinaryMaxDataType ? Dependencies.SqlExpressionFactory.Convert(dataLengthSqlFunction, typeof(int)) : dataLengthSqlFunction; } return base.VisitUnary(unaryExpression); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> protected override Expression VisitMethodCall(MethodCallExpression methodCallExpression) { var method = methodCallExpression.Method; if (method.IsGenericMethod && method.GetGenericMethodDefinition() == EnumerableMethods.ElementAt && methodCallExpression.Arguments[0].Type == typeof(byte[])) { return TranslateByteArrayElementAccess( methodCallExpression.Arguments[0], methodCallExpression.Arguments[1], methodCallExpression.Type); } if ((method == StringStartsWithMethodInfoString || method == StringStartsWithMethodInfoChar) && TryTranslateStartsEndsWithContains( methodCallExpression.Object!, methodCallExpression.Arguments[0], StartsEndsWithContains.StartsWith, out var translation1)) { return translation1; } if ((method == StringEndsWithMethodInfoString || method == StringEndsWithMethodInfoChar) && TryTranslateStartsEndsWithContains( methodCallExpression.Object!, methodCallExpression.Arguments[0], StartsEndsWithContains.EndsWith, out var translation2)) { return translation2; } if ((method == StringContainsMethodInfoString || method == StringContainsMethodInfoChar) && TryTranslateStartsEndsWithContains( methodCallExpression.Object!, methodCallExpression.Arguments[0], StartsEndsWithContains.Contains, out var translation3)) { return translation3; } // Translate non-aggregate string.Join to CONCAT_WS (for aggregate string.Join, see SqlServerStringAggregateMethodTranslator) if (method == StringJoinMethodInfo && methodCallExpression.Arguments[1] is NewArrayExpression newArrayExpression && ((_sqlServerSingletonOptions.EngineType == SqlServerEngineType.SqlServer && _sqlServerSingletonOptions.SqlServerCompatibilityLevel >= 140) || (_sqlServerSingletonOptions.EngineType == SqlServerEngineType.AzureSql && _sqlServerSingletonOptions.AzureSqlCompatibilityLevel >= 140) || (_sqlServerSingletonOptions.EngineType == SqlServerEngineType.AzureSynapse))) { if (TranslationFailed(methodCallExpression.Arguments[0], Visit(methodCallExpression.Arguments[0]), out var delimiter)) { return QueryCompilationContext.NotTranslatedExpression; } var arguments = new SqlExpression[newArrayExpression.Expressions.Count + 1]; arguments[0] = delimiter!; var isUnicode = delimiter!.TypeMapping?.IsUnicode == true; for (var i = 0; i < newArrayExpression.Expressions.Count; i++) { var argument = newArrayExpression.Expressions[i]; if (TranslationFailed(argument, Visit(argument), out var sqlArgument)) { return QueryCompilationContext.NotTranslatedExpression; } // CONCAT_WS returns a type with a length that varies based on actual inputs (i.e. the sum of all argument lengths, plus // the length needed for the delimiters). We don't know column values (or even parameter values, so we always return max. // We do vary return varchar(max) or nvarchar(max) based on whether we saw any nvarchar mapping. if (sqlArgument!.TypeMapping?.IsUnicode == true) { isUnicode = true; } // CONCAT_WS filters out nulls, but string.Join treats them as empty strings; so coalesce (which is a no-op for non-nullable // arguments). arguments[i + 1] = Dependencies.SqlExpressionFactory.Coalesce(sqlArgument, _sqlExpressionFactory.Constant(string.Empty)); } // CONCAT_WS never returns null; a null delimiter is interpreted as an empty string, and null arguments are skipped // (but we coalesce them above in any case). return Dependencies.SqlExpressionFactory.Function( "CONCAT_WS", arguments, nullable: false, argumentsPropagateNullability: new bool[arguments.Length], typeof(string), _typeMappingSource.FindMapping(isUnicode ? "nvarchar(max)" : "varchar(max)")); } return base.VisitMethodCall(methodCallExpression); bool TryTranslateStartsEndsWithContains( Expression instance, Expression pattern, StartsEndsWithContains methodType, [NotNullWhen(true)] out SqlExpression? translation) { if (Visit(instance) is not SqlExpression translatedInstance || Visit(pattern) is not SqlExpression translatedPattern) { translation = null; return false; } var stringTypeMapping = ExpressionExtensions.InferTypeMapping(translatedInstance, translatedPattern); translatedInstance = _sqlExpressionFactory.ApplyTypeMapping(translatedInstance, stringTypeMapping); translatedPattern = _sqlExpressionFactory.ApplyTypeMapping(translatedPattern, stringTypeMapping); switch (translatedPattern) { case SqlConstantExpression patternConstant: { // The pattern is constant. Aside from null and empty string, we escape all special characters (%, _, \) and send a // simple LIKE translation = patternConstant.Value switch { null => _sqlExpressionFactory.Like( translatedInstance, _sqlExpressionFactory.Constant(null, typeof(string), stringTypeMapping)), // In .NET, all strings start with/end with/contain the empty string, but SQL LIKE return false for empty patterns. // Return % which always matches instead. // Note that we don't just return a true constant, since null strings shouldn't match even an empty string // (but SqlNullabilityProcess will convert this to a true constant if the instance is non-nullable) "" => _sqlExpressionFactory.Like(translatedInstance, _sqlExpressionFactory.Constant("%")), string s when !s.Any(IsLikeWildChar) => _sqlExpressionFactory.Like( translatedInstance, _sqlExpressionFactory.Constant( methodType switch { StartsEndsWithContains.StartsWith => s + '%', StartsEndsWithContains.EndsWith => '%' + s, StartsEndsWithContains.Contains => $"%{s}%", _ => throw new ArgumentOutOfRangeException(nameof(methodType), methodType, null) })), // Azure Synapse does not support ESCAPE clause in LIKE // fallback to translation like with column/expression string when _sqlServerSingletonOptions.EngineType is SqlServerEngineType.AzureSynapse => TranslateWithoutLike(patternIsNonEmptyConstantString: true), string s => _sqlExpressionFactory.Like( translatedInstance, _sqlExpressionFactory.Constant( methodType switch { StartsEndsWithContains.StartsWith => EscapeLikePattern(s) + '%', StartsEndsWithContains.EndsWith => '%' + EscapeLikePattern(s), StartsEndsWithContains.Contains => $"%{EscapeLikePattern(s)}%", _ => throw new ArgumentOutOfRangeException(nameof(methodType), methodType, null) }), _sqlExpressionFactory.Constant(LikeEscapeString)), char s when !IsLikeWildChar(s) => _sqlExpressionFactory.Like( translatedInstance, _sqlExpressionFactory.Constant( methodType switch { StartsEndsWithContains.StartsWith => s + "%", StartsEndsWithContains.EndsWith => "%" + s, StartsEndsWithContains.Contains => $"%{s}%", _ => throw new ArgumentOutOfRangeException(nameof(methodType), methodType, null) })), char s => _sqlExpressionFactory.Like( translatedInstance, _sqlExpressionFactory.Constant( methodType switch { StartsEndsWithContains.StartsWith => LikeEscapeChar + s + "%", StartsEndsWithContains.EndsWith => "%" + LikeEscapeChar + s, StartsEndsWithContains.Contains => $"%{LikeEscapeChar}{s}%", _ => throw new ArgumentOutOfRangeException(nameof(methodType), methodType, null) }), _sqlExpressionFactory.Constant(LikeEscapeString)), _ => throw new UnreachableException() }; return true; } // Azure Synapse does not support ESCAPE clause in LIKE // fall through to translation like with column/expression case SqlParameterExpression patternParameter when _sqlServerSingletonOptions.EngineType is not SqlServerEngineType.AzureSynapse: { // The pattern is a parameter, register a runtime parameter that will contain the rewritten LIKE pattern, where // all special characters have been escaped. var lambda = Expression.Lambda( Expression.Call( EscapeLikePatternParameterMethod, QueryCompilationContext.QueryContextParameter, Expression.Constant(patternParameter.Name), Expression.Constant(methodType)), QueryCompilationContext.QueryContextParameter); var escapedPatternParameter = _queryCompilationContext.RegisterRuntimeParameter( $"{patternParameter.Name}_{methodType.ToString().ToLower(CultureInfo.InvariantCulture)}", lambda); translation = _sqlExpressionFactory.Like( translatedInstance, new SqlParameterExpression(escapedPatternParameter.Name!, escapedPatternParameter.Type, stringTypeMapping), _sqlExpressionFactory.Constant(LikeEscapeString)); return true; } default: // The pattern is a column or a complex expression; the possible special characters in the pattern cannot be escaped, // preventing us from translating to LIKE. translation = TranslateWithoutLike(); return true; } SqlExpression TranslateWithoutLike(bool patternIsNonEmptyConstantString = false) { return methodType switch { // For StartsWith/EndsWith, use LEFT or RIGHT instead to extract substring and compare: // WHERE instance IS NOT NULL AND pattern IS NOT NULL AND LEFT(instance, LEN(pattern)) = pattern // This is less efficient than LIKE (i.e. StartsWith does an index scan instead of seek), but we have no choice. // Note that we compensate for the case where both the instance and the pattern are null (null.StartsWith(null)); a // simple equality would yield true in that case, but we want false. We technically StartsEndsWithContains.StartsWith or StartsEndsWithContains.EndsWith => _sqlExpressionFactory.AndAlso( _sqlExpressionFactory.IsNotNull(translatedInstance), _sqlExpressionFactory.AndAlso( _sqlExpressionFactory.IsNotNull(translatedPattern), _sqlExpressionFactory.Equal( _sqlExpressionFactory.Function( methodType is StartsEndsWithContains.StartsWith ? "LEFT" : "RIGHT", [ translatedInstance, _sqlExpressionFactory.Function( "LEN", [translatedPattern], nullable: true, argumentsPropagateNullability: Statics.TrueArrays[1], typeof(int)) ], nullable: true, argumentsPropagateNullability: Statics.TrueArrays[2], typeof(string), stringTypeMapping), translatedPattern))), // For Contains, just use CHARINDEX and check if the result is greater than 0. StartsEndsWithContains.Contains when patternIsNonEmptyConstantString => _sqlExpressionFactory.AndAlso( _sqlExpressionFactory.IsNotNull(translatedInstance), CharIndexGreaterThanZero()), // For Contains, just use CHARINDEX and check if the result is greater than 0. // Add a check to return null when the pattern is an empty string (and the string isn't null) StartsEndsWithContains.Contains => _sqlExpressionFactory.AndAlso( _sqlExpressionFactory.IsNotNull(translatedInstance), _sqlExpressionFactory.AndAlso( _sqlExpressionFactory.IsNotNull(translatedPattern), _sqlExpressionFactory.OrElse( CharIndexGreaterThanZero(), _sqlExpressionFactory.Like( translatedPattern, _sqlExpressionFactory.Constant(string.Empty, stringTypeMapping))))), _ => throw new UnreachableException() }; SqlExpression CharIndexGreaterThanZero() => _sqlExpressionFactory.GreaterThan( _sqlExpressionFactory.Function( "CHARINDEX", [translatedPattern, translatedInstance], nullable: true, argumentsPropagateNullability: Statics.TrueArrays[2], typeof(int)), _sqlExpressionFactory.Constant(0)); } } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [EntityFrameworkInternal] public static string? ConstructLikePatternParameter( QueryContext queryContext, string baseParameterName, StartsEndsWithContains methodType) => queryContext.Parameters[baseParameterName] switch { null => null, // In .NET, all strings start/end with the empty string, but SQL LIKE return false for empty patterns. // Return % which always matches instead. "" => "%", string s => methodType switch { StartsEndsWithContains.StartsWith => EscapeLikePattern(s) + '%', StartsEndsWithContains.EndsWith => '%' + EscapeLikePattern(s), StartsEndsWithContains.Contains => $"%{EscapeLikePattern(s)}%", _ => throw new ArgumentOutOfRangeException(nameof(methodType), methodType, null) }, char s when !IsLikeWildChar(s) => methodType switch { StartsEndsWithContains.StartsWith => s + "%", StartsEndsWithContains.EndsWith => "%" + s, StartsEndsWithContains.Contains => $"%{s}%", _ => throw new ArgumentOutOfRangeException(nameof(methodType), methodType, null) }, char s => methodType switch { StartsEndsWithContains.StartsWith => LikeEscapeChar + s + "%", StartsEndsWithContains.EndsWith => "%" + LikeEscapeChar + s, StartsEndsWithContains.Contains => $"%{LikeEscapeChar}{s}%", _ => throw new ArgumentOutOfRangeException(nameof(methodType), methodType, null) }, _ => throw new UnreachableException() }; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [EntityFrameworkInternal]
SqlServerSqlTranslatingExpressionVisitor
csharp
MapsterMapper__Mapster
src/Mapster.Tests/WhenCloningConfig.cs
{ "start": 171, "end": 2663 }
public class ____ { [TestCleanup] public void TestCleanup() { TypeAdapterConfig.GlobalSettings.Clear(); } [TestMethod] public void Alter_Config_After_Map_Should_Error() { TypeAdapterConfig<SimplePoco, SimpleDto>.NewConfig() .Map(dest => dest.Name, src => "a"); var poco = new SimplePoco { Id = Guid.NewGuid(), Name = "test", }; var result = TypeAdapter.Adapt<SimpleDto>(poco); result.Name.ShouldBe("a"); var ex = Should.Throw<InvalidOperationException>(() => TypeAdapterConfig<SimplePoco, SimpleDto>.ForType() .Map(dest => dest.Name, src => "b")); ex.Message.ShouldContain("TypeAdapter.Adapt was already called"); } [TestMethod] public void Clone() { TypeAdapterConfig<SimplePoco, SimpleDto>.NewConfig() .Map(dest => dest.Name, src => "a"); var poco = new SimplePoco { Id = Guid.NewGuid(), Name = "test", }; var result = TypeAdapter.Adapt<SimpleDto>(poco); result.Name.ShouldBe("a"); var config = TypeAdapterConfig.GlobalSettings.Clone(); var global = TypeAdapterConfig.GlobalSettings; config.ShouldNotBeSameAs(global); config.Default.ShouldNotBeSameAs(global.Default); config.Default.Settings.ShouldNotBeSameAs(global.Default.Settings); config.RuleMap.ShouldNotBeSameAs(global.RuleMap); foreach (var kvp in config.RuleMap) { var globalRule = global.RuleMap[kvp.Key]; kvp.Value.ShouldNotBeSameAs(globalRule); kvp.Value.Settings.ShouldNotBeSameAs(globalRule.Settings); } config.Rules.ShouldNotBeSameAs(global.Rules); for (var i = 0; i < config.Rules.Count; i++) { config.Rules[i].ShouldNotBeSameAs(global.Rules[i]); config.Rules[i].Settings.ShouldNotBeSameAs(global.Rules[i].Settings); } config.Rules.Any(rule => object.ReferenceEquals(rule.Settings, config.Default.Settings)).ShouldBeTrue(); config.Rules.ShouldContain(config.RuleMap[new TypeTuple(typeof(SimplePoco), typeof(SimpleDto))]); }
WhenCloningConfig
csharp
microsoft__PowerToys
src/modules/launcher/Plugins/Community.PowerToys.Run.Plugin.ValueGenerator/IComputeRequest.cs
{ "start": 262, "end": 560 }
public interface ____ { public byte[] Result { get; set; } public string Description { get; } public bool IsSuccessful { get; set; } public string ErrorMessage { get; set; } bool Compute(); public string ResultToString(); } }
IComputeRequest
csharp
Cysharp__UniTask
src/UniTask/Assets/Editor/PackageExporter.cs
{ "start": 2220, "end": 2293 }
public class ____ { public string version; } } #endif
Version
csharp
ChilliCream__graphql-platform
src/HotChocolate/Data/test/Data.Filters.Tests/Expression/QueryableFilterVisitorBooleanTests.cs
{ "start": 80, "end": 2278 }
public class ____ : FilterVisitorTestBase { [Fact] public void Create_BooleanEqual_Expression() { // arrange var value = Utf8GraphQLParser.Syntax.ParseValueLiteral("{ bar: { eq: true }}"); var tester = CreateProviderTester(new FooFilterInput()); // act var func = tester.Build<Foo>(value); // assert var a = new Foo { Bar = true }; Assert.True(func(a)); var b = new Foo { Bar = false }; Assert.False(func(b)); } [Fact] public void Create_BooleanNotEqual_Expression() { // arrange var value = Utf8GraphQLParser.Syntax.ParseValueLiteral("{ bar: { eq: false }}"); var tester = CreateProviderTester(new FooFilterInput()); // act var func = tester.Build<Foo>(value); // assert var a = new Foo { Bar = false }; Assert.True(func(a)); var b = new Foo { Bar = true }; Assert.False(func(b)); } [Fact] public void Create_NullableBooleanEqual_Expression() { // arrange var value = Utf8GraphQLParser.Syntax.ParseValueLiteral("{ bar: { eq: true }}"); var tester = CreateProviderTester(new FooNullableFilterInput()); // act var func = tester.Build<FooNullable>(value); // assert var a = new FooNullable { Bar = true }; Assert.True(func(a)); var b = new FooNullable { Bar = false }; Assert.False(func(b)); var c = new FooNullable { Bar = null }; Assert.False(func(c)); } [Fact] public void Create_NullableBooleanNotEqual_Expression() { // arrange var value = Utf8GraphQLParser.Syntax.ParseValueLiteral("{ bar: { eq: false }}"); var tester = CreateProviderTester(new FooNullableFilterInput()); // act var func = tester.Build<FooNullable>(value); // assert var a = new FooNullable { Bar = false }; Assert.True(func(a)); var b = new FooNullable { Bar = true }; Assert.False(func(b)); var c = new FooNullable { Bar = null }; Assert.False(func(c)); }
QueryableFilterVisitorBooleanTests
csharp
serilog__serilog
test/Serilog.Tests/Configuration/LoggerSinkConfigurationTests.cs
{ "start": 2461, "end": 3292 }
class ____ : ILogEventSink, ISetLoggingFailureListener { public ILoggingFailureListener? FailureListener { get; set; } public void Emit(LogEvent logEvent) { } public void SetFailureListener(ILoggingFailureListener failureListener) { FailureListener = failureListener; } } [Fact] public void FailureListenersCanTraverseWrappers() { var inner = new SupportsFailureListener(); var sink = LoggerSinkConfiguration.Wrap(s => new DummyWrappingSink(s), wt => wt.Sink(inner)); var sfl = Assert.IsAssignableFrom<ISetLoggingFailureListener>(sink); var listener = new CollectingFailureListener(); sfl.SetFailureListener(listener); Assert.Same(listener, inner.FailureListener); } }
SupportsFailureListener
csharp
protobuf-net__protobuf-net
src/protobuf-net.Reflection/Parsers.cs
{ "start": 1073, "end": 1393 }
public interface ____ { /// <summary> /// Indicates whether a specified file exists /// </summary> bool Exists(string path); /// <summary> /// Opens the specified file for text parsing /// </summary> TextReader OpenText(string path); }
IFileSystem
csharp
unoplatform__uno
src/Uno.UI.TestComparer/Comparer/CompareResultFile.cs
{ "start": 78, "end": 358 }
internal class ____ { public CompareResultFile() { } public List<CompareResultFileRun> ResultRun { get; internal set; } = new List<CompareResultFileRun>(); public string TestName { get; internal set; } public bool HasChanged { get; internal set; } } }
CompareResultFile
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore.Notifications.Core/Models/UserNotificationPreferencesPart.cs
{ "start": 83, "end": 383 }
public class ____ : ContentPart { /// <summary> /// Sorted methods. /// </summary> public string[] Methods { get; set; } /// <summary> /// List of methods the user does not want to use. /// </summary> public string[] Optout { get; set; } }
UserNotificationPreferencesPart
csharp
nopSolutions__nopCommerce
src/Plugins/Nop.Plugin.Misc.Zettle/Data/SchemaMigration.cs
{ "start": 255, "end": 514 }
public class ____ : AutoReversingMigration { #region Methods /// <summary> /// Collect the UP migration expressions /// </summary> public override void Up() { Create.TableFor<ZettleRecord>(); } #endregion }
SchemaMigration
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/src/Types/Extensions/MapMiddleware.cs
{ "start": 86, "end": 1145 }
internal sealed class ____ { private readonly FieldDelegate _next; private readonly FieldReference _fieldReference; private readonly FieldDelegate _fieldDelegate; public MapMiddleware( FieldDelegate next, FieldReference fieldReference, FieldDelegate fieldDelegate) { _next = next ?? throw new ArgumentNullException(nameof(next)); _fieldReference = fieldReference ?? throw new ArgumentNullException(nameof(fieldReference)); _fieldDelegate = fieldDelegate ?? throw new ArgumentNullException(nameof(fieldDelegate)); } public ValueTask InvokeAsync(IMiddlewareContext context) { return IsField(context.ObjectType.Name, context.Selection.Field.Name) ? _fieldDelegate(context) : _next(context); } private bool IsField(string typeName, string fieldName) { return _fieldReference.TypeName.EqualsOrdinal(typeName) && _fieldReference.FieldName.EqualsOrdinal(fieldName); } }
MapMiddleware
csharp
nunit__nunit
src/NUnitFramework/testdata/TestFixtureSourceData.cs
{ "start": 15488, "end": 15767 }
public abstract class ____ { private static readonly int[] DataSource = { 3, 5 }; protected DataSourcePrivateFieldInBaseClass(int data) { Data = data; } protected int Data { get; } }
DataSourcePrivateFieldInBaseClass
csharp
dotnet__BenchmarkDotNet
samples/BenchmarkDotNet.Samples/IntroSmokeValueTypes.cs
{ "start": 2338, "end": 2440 }
public struct ____ { public int _1, _2; } [Benchmark] public Int2 ReturnInt2() => new Int2();
Int2
csharp
nopSolutions__nopCommerce
src/Presentation/Nop.Web/Areas/Admin/Models/Common/UrlRecordSearchModel.cs
{ "start": 235, "end": 994 }
public partial record ____ : BaseSearchModel { #region Ctor public UrlRecordSearchModel() { AvailableLanguages = new List<SelectListItem>(); AvailableActiveOptions = new List<SelectListItem>(); } #endregion #region Properties [NopResourceDisplayName("Admin.System.SeNames.List.Name")] public string SeName { get; set; } [NopResourceDisplayName("Admin.System.SeNames.List.Language")] public int LanguageId { get; set; } [NopResourceDisplayName("Admin.System.SeNames.List.IsActive")] public int IsActiveId { get; set; } public IList<SelectListItem> AvailableLanguages { get; set; } public IList<SelectListItem> AvailableActiveOptions { get; set; } #endregion }
UrlRecordSearchModel
csharp
cake-build__cake
src/Cake.Common/Properties/Namespaces.cs
{ "start": 1092, "end": 1384 }
internal class ____ { } } // ReSharper disable once CheckNamespace namespace Cake.Common.Build.AppVeyor.Data { /// <summary> /// This namespace contain types /// representing data used for interaction with AppVeyor. /// </summary> [CompilerGenerated]
NamespaceDoc
csharp
NLog__NLog
src/NLog/Internal/PropertiesDictionary.cs
{ "start": 28291, "end": 29789 }
internal sealed class ____ { private readonly string _propertyName; public IgnoreCasePropertyKey(string propertyName) { _propertyName = propertyName; } public bool Equals(string propertyName) => Equals(_propertyName, propertyName); public override bool Equals(object obj) { if (obj is string stringObj) return Equals(_propertyName, stringObj); else if (obj is IgnoreCasePropertyKey ignoreCase) return Equals(_propertyName, ignoreCase._propertyName); else return false; } public override int GetHashCode() { return GetHashCode(_propertyName); } public override string ToString() => _propertyName; internal static int GetHashCode(string propertyName) { return StringComparer.OrdinalIgnoreCase.GetHashCode(propertyName); } internal static bool Equals(string x, string y) { return string.Equals(x, y, StringComparison.OrdinalIgnoreCase); } } /// <summary> /// Property-Key equality-comparer that uses string-hashcode from OrdinalIgnoreCase /// Enables case-insensitive lookup using <see cref="IgnoreCasePropertyKey"/> /// </summary>
IgnoreCasePropertyKey
csharp
dotnet__machinelearning
src/Microsoft.Data.Analysis/Computations/Arithmetic.netstandard.cs
{ "start": 68582, "end": 83763 }
internal class ____ : Arithmetic<int> { protected override void Add(ReadOnlySpan<int> x, ReadOnlySpan<int> y, Span<int> destination) { int i = 0; if (Vector.IsHardwareAccelerated) { ref int xRef = ref MemoryMarshal.GetReference(x); ref int yRef = ref MemoryMarshal.GetReference(y); ref int dRef = ref MemoryMarshal.GetReference(destination); var vectorSize = Vector<int>.Count; var oneVectorFromEnd = x.Length - vectorSize; if (oneVectorFromEnd >= 0) { // Loop handling one vector at a time. do { Arithmetic.AsVector(ref dRef, i) = (Arithmetic.AsVector(ref xRef, i) + Arithmetic.AsVector(ref yRef, i)); i += vectorSize; } while (i <= oneVectorFromEnd); } } while (i < x.Length) { destination[i] = (int)(x[i] + y[i]); i++; } } protected override void Add(ReadOnlySpan<int> x, int y, Span<int> destination) { int i = 0; while (i < x.Length) { destination[i] = (int)(x[i] + y); i++; } } protected override void Add(int x, ReadOnlySpan<int> y, Span<int> destination) { int i = 0; while (i < y.Length) { destination[i] = (int)(x + y[i]); i++; } } protected override void Subtract(ReadOnlySpan<int> x, ReadOnlySpan<int> y, Span<int> destination) { int i = 0; if (Vector.IsHardwareAccelerated) { ref int xRef = ref MemoryMarshal.GetReference(x); ref int yRef = ref MemoryMarshal.GetReference(y); ref int dRef = ref MemoryMarshal.GetReference(destination); var vectorSize = Vector<int>.Count; var oneVectorFromEnd = x.Length - vectorSize; if (oneVectorFromEnd >= 0) { // Loop handling one vector at a time. do { Arithmetic.AsVector(ref dRef, i) = (Arithmetic.AsVector(ref xRef, i) - Arithmetic.AsVector(ref yRef, i)); i += vectorSize; } while (i <= oneVectorFromEnd); } } while (i < x.Length) { destination[i] = (int)(x[i] - y[i]); i++; } } protected override void Subtract(ReadOnlySpan<int> x, int y, Span<int> destination) { int i = 0; while (i < x.Length) { destination[i] = (int)(x[i] - y); i++; } } protected override void Subtract(int x, ReadOnlySpan<int> y, Span<int> destination) { int i = 0; while (i < y.Length) { destination[i] = (int)(x - y[i]); i++; } } protected override void Multiply(ReadOnlySpan<int> x, ReadOnlySpan<int> y, Span<int> destination) { int i = 0; if (Vector.IsHardwareAccelerated) { ref int xRef = ref MemoryMarshal.GetReference(x); ref int yRef = ref MemoryMarshal.GetReference(y); ref int dRef = ref MemoryMarshal.GetReference(destination); var vectorSize = Vector<int>.Count; var oneVectorFromEnd = x.Length - vectorSize; if (oneVectorFromEnd >= 0) { // Loop handling one vector at a time. do { Arithmetic.AsVector(ref dRef, i) = (Arithmetic.AsVector(ref xRef, i) * Arithmetic.AsVector(ref yRef, i)); i += vectorSize; } while (i <= oneVectorFromEnd); } } while (i < x.Length) { destination[i] = (int)(x[i] * y[i]); i++; } } protected override void Multiply(ReadOnlySpan<int> x, int y, Span<int> destination) { int i = 0; while (i < x.Length) { destination[i] = (int)(x[i] * y); i++; } } protected override void Multiply(int x, ReadOnlySpan<int> y, Span<int> destination) { int i = 0; while (i < y.Length) { destination[i] = (int)(x * y[i]); i++; } } protected override int Divide(int x, int y) { return (int)(x / y); } protected override void Divide(ReadOnlySpan<int> x, ReadOnlySpan<int> y, Span<int> destination) { int i = 0; if (Vector.IsHardwareAccelerated) { ref int xRef = ref MemoryMarshal.GetReference(x); ref int yRef = ref MemoryMarshal.GetReference(y); ref int dRef = ref MemoryMarshal.GetReference(destination); var vectorSize = Vector<int>.Count; var oneVectorFromEnd = x.Length - vectorSize; if (oneVectorFromEnd >= 0) { // Loop handling one vector at a time. do { Arithmetic.AsVector(ref dRef, i) = (Arithmetic.AsVector(ref xRef, i) / Arithmetic.AsVector(ref yRef, i)); i += vectorSize; } while (i <= oneVectorFromEnd); } } while (i < x.Length) { destination[i] = (int)(x[i] / y[i]); i++; } } protected override void Divide(ReadOnlySpan<int> x, int y, Span<int> destination) { int i = 0; while (i < x.Length) { destination[i] = (int)(x[i] / y); i++; } } protected override void Divide(int x, ReadOnlySpan<int> y, Span<int> destination) { int i = 0; while (i < y.Length) { destination[i] = (int)(x / y[i]); i++; } } protected override int Modulo(int x, int y) { return (int)(x % y); } protected override void Modulo(ReadOnlySpan<int> x, ReadOnlySpan<int> y, Span<int> destination) { int i = 0; while (i < x.Length) { destination[i] = (int)(x[i] % y[i]); i++; } } protected override void Modulo(ReadOnlySpan<int> x, int y, Span<int> destination) { int i = 0; while (i < x.Length) { destination[i] = (int)(x[i] % y); i++; } } protected override void Modulo(int x, ReadOnlySpan<int> y, Span<int> destination) { int i = 0; while (i < y.Length) { destination[i] = (int)(x % y[i]); i++; } } protected override void And(ReadOnlySpan<int> x, ReadOnlySpan<int> y, Span<int> destination) { int i = 0; while (i < x.Length) { destination[i] = (int)(x[i] & y[i]); i++; } } protected override void And(ReadOnlySpan<int> x, int y, Span<int> destination) { int i = 0; while (i < x.Length) { destination[i] = (int)(x[i] & y); i++; } } protected override void And(int x, ReadOnlySpan<int> y, Span<int> destination) { int i = 0; while (i < y.Length) { destination[i] = (int)(x & y[i]); i++; } } protected override void Or(ReadOnlySpan<int> x, ReadOnlySpan<int> y, Span<int> destination) { int i = 0; while (i < x.Length) { destination[i] = (int)(x[i] | y[i]); i++; } } protected override void Or(ReadOnlySpan<int> x, int y, Span<int> destination) { int i = 0; while (i < x.Length) { destination[i] = (int)(x[i] | y); i++; } } protected override void Or(int x, ReadOnlySpan<int> y, Span<int> destination) { int i = 0; while (i < y.Length) { destination[i] = (int)(x | y[i]); i++; } } protected override void Xor(ReadOnlySpan<int> x, ReadOnlySpan<int> y, Span<int> destination) { int i = 0; while (i < x.Length) { destination[i] = (int)(x[i] ^ y[i]); i++; } } protected override void Xor(ReadOnlySpan<int> x, int y, Span<int> destination) { int i = 0; while (i < x.Length) { destination[i] = (int)(x[i] ^ y); i++; } } protected override void Xor(int x, ReadOnlySpan<int> y, Span<int> destination) { int i = 0; while (i < y.Length) { destination[i] = (int)(x ^ y[i]); i++; } } protected override void LeftShift(ReadOnlySpan<int> x, int y, Span<int> destination) { for (var i = 0; i < x.Length; i++) destination[i] = (int)(x[i] << y); } protected override void RightShift(ReadOnlySpan<int> x, int y, Span<int> destination) { for (var i = 0; i < x.Length; i++) destination[i] = (int)(x[i] >> y); } protected override void ElementwiseEquals(ReadOnlySpan<int> x, ReadOnlySpan<int> y, Span<bool> destination) { for (var i = 0; i < x.Length; i++) { destination[i] = (x[i] == y[i]); } } protected override void ElementwiseEquals(ReadOnlySpan<int> x, int y, Span<bool> destination) { for (var i = 0; i < x.Length; i++) { destination[i] = (x[i] == y); } } protected override void ElementwiseNotEquals(ReadOnlySpan<int> x, ReadOnlySpan<int> y, Span<bool> destination) { for (var i = 0; i < x.Length; i++) { destination[i] = (x[i] != y[i]); } } protected override void ElementwiseNotEquals(ReadOnlySpan<int> x, int y, Span<bool> destination) { for (var i = 0; i < x.Length; i++) { destination[i] = (x[i] != y); } } protected override void ElementwiseGreaterThanOrEqual(ReadOnlySpan<int> x, ReadOnlySpan<int> y, Span<bool> destination) { for (var i = 0; i < x.Length; i++) { destination[i] = (x[i] >= y[i]); } } protected override void ElementwiseGreaterThanOrEqual(ReadOnlySpan<int> x, int y, Span<bool> destination) { for (var i = 0; i < x.Length; i++) { destination[i] = (x[i] >= y); } } protected override void ElementwiseLessThanOrEqual(ReadOnlySpan<int> x, ReadOnlySpan<int> y, Span<bool> destination) { for (var i = 0; i < x.Length; i++) { destination[i] = (x[i] <= y[i]); } } protected override void ElementwiseLessThanOrEqual(ReadOnlySpan<int> x, int y, Span<bool> destination) { for (var i = 0; i < x.Length; i++) { destination[i] = (x[i] <= y); } } protected override void ElementwiseGreaterThan(ReadOnlySpan<int> x, ReadOnlySpan<int> y, Span<bool> destination) { for (var i = 0; i < x.Length; i++) { destination[i] = (x[i] > y[i]); } } protected override void ElementwiseGreaterThan(ReadOnlySpan<int> x, int y, Span<bool> destination) { for (var i = 0; i < x.Length; i++) { destination[i] = (x[i] > y); } } protected override void ElementwiseLessThan(ReadOnlySpan<int> x, ReadOnlySpan<int> y, Span<bool> destination) { for (var i = 0; i < x.Length; i++) { destination[i] = (x[i] < y[i]); } } protected override void ElementwiseLessThan(ReadOnlySpan<int> x, int y, Span<bool> destination) { for (var i = 0; i < x.Length; i++) { destination[i] = (x[i] < y); } } }
IntArithmetic
csharp
protobuf-net__protobuf-net
src/protobuf-net.FSharp/FSharpMapSerializer.cs
{ "start": 398, "end": 2413 }
public sealed class ____<TKey, TValue> : ExternalMapSerializer<FSharpMap<TKey, TValue>, TKey, TValue> { /// <inheritdoc/> protected override FSharpMap<TKey, TValue> Clear(FSharpMap<TKey, TValue> values, ISerializationContext context) => MapModule.Empty<TKey, TValue>(); /// <inheritdoc/> protected override FSharpMap<TKey, TValue> Initialize(FSharpMap<TKey, TValue> values, ISerializationContext context) => values ?? MapModule.Empty<TKey, TValue>(); /// <inheritdoc/> protected override FSharpMap<TKey, TValue> AddRange(FSharpMap<TKey, TValue> values, ref ArraySegment<KeyValuePair<TKey, TValue>> newValues, ISerializationContext context) { if (values == null || values.IsEmpty) { return MapModule.OfSeq<TKey, TValue>(newValues.Select(r => new Tuple<TKey, TValue>(r.Key, r.Value))); } var map = values; foreach (var pair in newValues) { map = MapModule.Add(pair.Key, pair.Value, map); } return map; } /// <inheritdoc/> protected override FSharpMap<TKey, TValue> SetValues(FSharpMap<TKey, TValue> values, ref ArraySegment<KeyValuePair<TKey, TValue>> newValues, ISerializationContext context) { if (values.IsEmpty) { return MapModule.OfSeq<TKey, TValue>(newValues.Select(r => new Tuple<TKey, TValue>(r.Key, r.Value))); } var dictionary = new Dictionary<TKey, TValue>(values.Count); foreach (var cur in values) { dictionary.Add(cur.Key, cur.Value); } foreach (var pair in newValues) { dictionary[pair.Key] = pair.Value; } return MapModule.OfSeq<TKey, TValue>(dictionary.Select(r => new Tuple<TKey, TValue>(r.Key, r.Value))); } } /// <summary> /// Factory
FSharpMapSerializer
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/src/Types.Scalars.Upload/StreamFile.cs
{ "start": 167, "end": 1931 }
public class ____ : IFile { private readonly Func<Stream> _openReadStream; /// <summary> /// Creates a new instance of <see cref="StreamFile"/>. /// </summary> /// <param name="name"> /// The file name. /// </param> /// <param name="openReadStream"> /// A delegate to open the stream. /// </param> /// <param name="length"> /// The file length if available. /// </param> /// <param name="contentType"> /// The file content-type. /// </param> /// <exception cref="ArgumentException"> /// <paramref name="name"/> is <c>null</c> or <see cref="string.Empty"/>. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="openReadStream"/> is <c>null</c>. /// </exception> public StreamFile( string name, Func<Stream> openReadStream, long? length = null, string? contentType = null) { ArgumentException.ThrowIfNullOrEmpty(name); Name = name; _openReadStream = openReadStream ?? throw new ArgumentNullException(nameof(openReadStream)); Length = length; ContentType = contentType; } /// <inheritdoc /> public string Name { get; } /// <inheritdoc /> public long? Length { get; } /// <inheritdoc /> public string? ContentType { get; } /// <inheritdoc /> public virtual async Task CopyToAsync( Stream target, CancellationToken cancellationToken = default) { await using var stream = OpenReadStream(); await stream.CopyToAsync(target, cancellationToken).ConfigureAwait(false); } /// <inheritdoc /> public virtual Stream OpenReadStream() => _openReadStream(); }
StreamFile
csharp
cake-build__cake
src/Cake.Common/Tools/DotNet/Workload/Search/DotNetWorkloadSearcher.cs
{ "start": 462, "end": 3621 }
public sealed class ____ : DotNetTool<DotNetWorkloadSearchSettings> { /// <summary> /// Initializes a new instance of the <see cref="DotNetWorkloadSearcher" /> 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 DotNetWorkloadSearcher( IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IToolLocator tools) : base(fileSystem, environment, processRunner, tools) { } /// <summary> /// Lists the latest available version of the .NET SDK and .NET Runtime, for each feature band. /// </summary> /// <param name="searchString">The workload ID to search for, or part of it.</param> /// <param name="settings">The settings.</param> /// <returns>The list of available workloads.</returns> public IEnumerable<DotNetWorkload> Search(string searchString, DotNetWorkloadSearchSettings settings) { ArgumentNullException.ThrowIfNull(settings); var processSettings = new ProcessSettings { RedirectStandardOutput = true }; IEnumerable<string> result = null; RunCommand(settings, GetArguments(searchString, settings), processSettings, process => result = process.GetStandardOutput()); return ParseResult(result).ToList(); } private ProcessArgumentBuilder GetArguments(string searchString, DotNetWorkloadSearchSettings settings) { var builder = CreateArgumentBuilder(settings); builder.Append("workload search"); if (!string.IsNullOrEmpty(searchString)) { builder.Append(searchString); } return builder; } private static IEnumerable<DotNetWorkload> ParseResult(IEnumerable<string> result) { bool first = true; int descriptionIndex = -1; foreach (var line in result) { if (first) { if (line?.StartsWith("Workload ID") == true && (descriptionIndex = line?.IndexOf("Description") ?? -1) > 11) { first = false; } continue; } if (string.IsNullOrWhiteSpace(line)) { continue; } var trimmedLine = line.Trim(); if (trimmedLine.Trim().All(c => c == '-')) { continue; } yield return new DotNetWorkload( string.Concat(trimmedLine.Take(descriptionIndex)).TrimEnd(), string.Concat(trimmedLine.Skip(descriptionIndex))); } } } }
DotNetWorkloadSearcher
csharp
unoplatform__uno
src/Uno.UI.RuntimeTests/Tests/Windows_Storage/Given_ApplicationStorage.cs
{ "start": 137, "end": 2305 }
public class ____ { [TestMethod] public async Task When_FileDoesNotExistsInPackage() { var fileExists = await Uno.UI.Toolkit.StorageFileHelper.ExistsInPackage("Asset_InvalidFile.xml"); Assert.IsFalse(fileExists); } [TestMethod] public async Task When_FileExistsInPackage_Nested() { var fileExists = await Uno.UI.Toolkit.StorageFileHelper.ExistsInPackage("Assets/Fonts/RoteFlora.ttf"); Assert.IsTrue(fileExists); } [TestMethod] public async Task When_FileExistsInPackage_RootPath() { var fileExists = await Uno.UI.Toolkit.StorageFileHelper.ExistsInPackage("Asset_GetFileFromApplicationUriAsync.xml"); Assert.IsTrue(fileExists); } [TestMethod] public async Task When_ResourceFileExistsInPackage_Nested() { var fileExists = await Uno.UI.Toolkit.StorageFileHelper.ExistsInPackage("Assets/Icons/menu.png"); Assert.IsTrue(fileExists); } [TestMethod] public async Task When_GetFileFromApplicationUriAsync_RootPath() { var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Asset_GetFileFromApplicationUriAsync.xml")); var content = await FileIO.ReadTextAsync(file); Assert.AreEqual("<SomeContent/>", content); } [TestMethod] public async Task When_GetFileFromApplicationUriAsync_Nested() { var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Asset_GetFileFromApplicationUriAsync_Nested.xml")); var content = await FileIO.ReadTextAsync(file); Assert.AreEqual("<SomeContent/>", content); } [TestMethod] public async Task When_GetFileFromApplicationUriAsync_Image() { var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Button.png")); Assert.IsTrue((await FileIO.ReadBufferAsync(file)).Length > 0); } [TestMethod] public async Task When_GetFileFromApplicationUriAsync_Image_Nested() { var file = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Icons/menu.png")); Assert.IsTrue((await FileIO.ReadBufferAsync(file)).Length > 0); } } }
Given_ApplicationStorage
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.Activation/IFileSavePickerActivatedEventArgs.cs
{ "start": 310, "end": 769 }
public partial interface ____ : global::Windows.ApplicationModel.Activation.IActivatedEventArgs { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ global::Windows.Storage.Pickers.Provider.FileSavePickerUI FileSavePickerUI { get; } #endif // Forced skipping of method Windows.ApplicationModel.Activation.IFileSavePickerActivatedEventArgs.FileSavePickerUI.get } }
IFileSavePickerActivatedEventArgs
csharp
getsentry__sentry-dotnet
test/Sentry.Maui.Tests/SentryMauiOptionsTests.cs
{ "start": 61, "end": 2796 }
public class ____ { private static SentryMauiOptions GetSut() => new() { NetworkStatusListener = FakeReliableNetworkStatusListener.Instance }; [Fact] public void IsEnvironmentUser_Default() { var options = GetSut(); Assert.False(options.IsEnvironmentUser); } [Fact] public void IncludeTextInBreadcrumbs_Default() { var options = GetSut(); Assert.False(options.IncludeTextInBreadcrumbs); } [Fact] public void IncludeTitleInBreadcrumbs_Default() { var options = GetSut(); Assert.False(options.IncludeTitleInBreadcrumbs); } [Fact] public void IncludeBackgroundingStateInBreadcrumbs_Default() { var options = GetSut(); Assert.False(options.IncludeBackgroundingStateInBreadcrumbs); } [Fact] public void AutoSessionTracking_Default() { var options = GetSut(); Assert.True(options.AutoSessionTracking); } [Fact] public void DetectStartupTime_Default() { var options = GetSut(); Assert.Equal(StartupTimeDetectionMode.Fast, options.DetectStartupTime); } [Fact] public void CacheDirectoryPath_Default() { var options = GetSut(); #if PLATFORM_NEUTRAL Assert.Null(options.CacheDirectoryPath); #else var expected = Microsoft.Maui.Storage.FileSystem.CacheDirectory; Assert.Equal(expected, options.CacheDirectoryPath); #endif } #if ANDROID [Fact] public void HandlerStrategy_Default() { // Arrange var expected = Android.LogCatIntegrationType.None; var options = GetSut(); // Assert Assert.Equal(expected, options.Android.LogCatIntegration); } [Fact] public void HandlerStrategy_Set() { // Arrange var expected = Android.LogCatIntegrationType.None; var options = GetSut(); // Act options.Android.LogCatIntegration = Android.LogCatIntegrationType.All; // Assert Assert.NotEqual(expected, options.Android.LogCatIntegration); } #endif [Fact] public void BeforeCaptureScreenshot_Set() { // Arrange var options = GetSut(); options.AttachScreenshot = true; // Act options.SetBeforeScreenshotCapture((@event, hint) => { return false; }); // Assert Assert.NotNull(options.BeforeCaptureInternal); } [Fact] public void BeforeCaptureScreenshot_NotSet() { // Arrange var options = GetSut(); options.AttachScreenshot = true; // Assert Assert.Null(options.BeforeCaptureInternal); } }
SentryMauiOptionsTests
csharp
dotnet__maui
src/Controls/tests/Xaml.UnitTests/Issues/Maui21839.xaml.cs
{ "start": 351, "end": 1308 }
class ____ { [SetUp] public void Setup() { Application.SetCurrentApplication(new MockApplication()); DispatcherProvider.SetCurrent(new DispatcherProviderStub()); } [TearDown] public void TearDown() => AppInfo.SetCurrent(null); [Test] public async Task VSMLeak([Values] XamlInflator inflator) { Application.Current.Resources.Add("buttonStyle", new Style(typeof(Button)) { Setters = { new Setter { Property = VisualStateManager.VisualStateGroupsProperty, Value = new VisualStateGroupList{ new VisualStateGroup { Name = "CommonStates", States = { new VisualState { Name = "Normal" }, new VisualState { Name = "Pressed" }, new VisualState { Name = "Disabled" } } } } } } }); var pagewr = new WeakReference(new Maui21839(inflator)); await Task.Delay(10); GC.Collect(); Assert.IsNull(pagewr.Target, "Page leaked"); } } }
Test
csharp
Tyrrrz__YoutubeExplode
YoutubeExplode.Tests/TestData/VideoIds.cs
{ "start": 43, "end": 1279 }
internal static class ____ { public const string Normal = "9bZkp7q19f0"; public const string Unlisted = "UGh4_HsibAE"; public const string Private = "pb_hHv3fByo"; public const string Deleted = "qld9w0b-1ao"; public const string EmbedRestrictedByYouTube = "_kmeFXjjGfk"; public const string EmbedRestrictedByAuthor = "MeJVWBSsPAY"; public const string ContentCheckViolent = "rXMX4YJ7Lks"; public const string ContentCheckSexual = "SkRSXFQerZs"; public const string ContentCheckSuicide = "4QXCPuwBz2E"; public const string RequiresPurchase = "p3dDcKOFXQg"; public const string RequiresPurchaseDistributed = "qs3NZHVM_Ik"; public const string LiveStream = "jfKfPfyJRdk"; public const string LiveStreamRecording = "rsAAeyAr-9Y"; public const string WithBrokenTitle = "4ZJWv6t-PfY"; public const string WithHighQualityStreams = "V5Fsj_sCKdg"; public const string WithOmnidirectionalStreams = "-xNN-bJQ4vI"; public const string WithHighDynamicRangeStreams = "vX2vsvdq8nw"; public const string WithClosedCaptions = "YltHGKX80Y8"; public const string WithBrokenClosedCaptions = "1VKIIw05JnE"; public const string WithMultipleAudioLanguages = "ngqcjXfggHQ"; }
VideoIds
csharp
NLog__NLog
examples/targets/Configuration API/ColoredConsole/Row Highlighting/Example.cs
{ "start": 52, "end": 1885 }
class ____ { static void Main(string[] args) { ColoredConsoleTarget target = new ColoredConsoleTarget(); target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}"; target.RowHighlightingRules.Add( new ConsoleRowHighlightingRule( "level >= LogLevel.Error and contains(message,'serious')", // condition ConsoleOutputColor.White, // foreground color ConsoleOutputColor.Red // background color ) ); target.RowHighlightingRules.Add( new ConsoleRowHighlightingRule( "starts-with(logger,'Example')", // condition ConsoleOutputColor.Yellow, // foreground color ConsoleOutputColor.DarkBlue) // background color ); LoggingConfiguration nlogConfig = new LoggingConfiguration(); nlogConfig.AddRuleForAllLevels(target); LogManager.Configuration = nlogConfig; // LogManager.Configuration = new NLog.Config.XmlLoggingConfiguration("ColoredConsoleTargetRowHighlighting.nlog"); Logger logger = LogManager.GetLogger("Example"); logger.Trace("trace log message"); logger.Debug("debug log message"); logger.Info("info log message"); logger.Warn("warn log message"); logger.Error("very serious error log message"); logger.Fatal("fatal log message, rather serious"); Logger logger2 = LogManager.GetLogger("Another"); logger2.Trace("trace log message"); logger2.Debug("debug log message"); logger2.Info("info log message"); logger2.Warn("warn log message"); logger2.Error("very serious error log message"); logger2.Fatal("fatal log message"); } }
Example
csharp
dotnet__efcore
src/EFCore.Relational/Metadata/IConventionEntityTypeMappingFragment.cs
{ "start": 469, "end": 2111 }
public interface ____ : IReadOnlyEntityTypeMappingFragment, IConventionAnnotatable { /// <summary> /// Gets the entity type for which the fragment is defined. /// </summary> new IConventionEntityType EntityType { get; } /// <summary> /// Gets the builder that can be used to configure this fragment. /// </summary> /// <exception cref="InvalidOperationException">If the fragment has been removed from the model.</exception> new IConventionEntityTypeMappingFragmentBuilder Builder { get; } /// <summary> /// Returns the configuration source for this fragment. /// </summary> /// <returns>The configuration source.</returns> ConfigurationSource GetConfigurationSource(); /// <summary> /// Sets a value indicating whether the associated table is ignored by Migrations. /// </summary> /// <param name="excluded">A value indicating whether the associated table is ignored by Migrations.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> bool? SetIsTableExcludedFromMigrations(bool? excluded, bool fromDataAnnotation = false); /// <summary> /// Gets the <see cref="ConfigurationSource" /> for <see cref="IReadOnlyEntityTypeMappingFragment.IsTableExcludedFromMigrations" />. /// </summary> /// <returns>The <see cref="ConfigurationSource" /> for <see cref="IReadOnlyEntityTypeMappingFragment.IsTableExcludedFromMigrations" />.</returns> ConfigurationSource? GetIsTableExcludedFromMigrationsConfigurationSource(); }
IConventionEntityTypeMappingFragment
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Bson.Tests/Serialization/Serializers/EnumSerializerTests.cs
{ "start": 2294, "end": 2439 }
public enum ____ : uint { Min = uint.MinValue, One = 1, Max = uint.MaxValue }
EnumUInt32
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Driver.Tests/Linq/Linq3Implementation/Jira/CSharp4861Tests.cs
{ "start": 778, "end": 2949 }
public class ____ : LinqIntegrationTest<CSharp4861Tests.ClassFixture> { public CSharp4861Tests(ClassFixture fixture) : base(fixture) { } [Fact] public void One_less_than_Count_should_work() { var collection = Fixture.Collection; var queryable = collection.AsQueryable() .Where(x => 1 < x.Set.Count); var stages = Translate(collection, queryable); AssertStages(stages, "{ $match : { 'Set.1' : { $exists : true } } }"); var results = queryable.ToList(); results.Select(x => x.Id).Should().Equal(2, 3); } [Fact] public void One_less_than_Length_should_work() { var collection = Fixture.Collection; var queryable = collection.AsQueryable() .Where(x => 1 < x.Array.Length); var stages = Translate(collection, queryable); AssertStages(stages, "{ $match : { 'Array.1' : { $exists : true } } }"); var results = queryable.ToList(); results.Select(x => x.Id).Should().Equal(2, 3); } [Fact] public void Count_greater_than_one_should_work() { var collection = Fixture.Collection; var queryable = collection.AsQueryable() .Where(x => x.Set.Count > 1); var stages = Translate(collection, queryable); AssertStages(stages, "{ $match : { 'Set.1' : { $exists : true } } }"); var results = queryable.ToList(); results.Select(x => x.Id).Should().Equal(2, 3); } [Fact] public void Length_greater_than_one_should_work() { var collection = Fixture.Collection; var queryable = collection.AsQueryable() .Where(x => x.Array.Length > 1); var stages = Translate(collection, queryable); AssertStages(stages, "{ $match : { 'Array.1' : { $exists : true } } }"); var results = queryable.ToList(); results.Select(x => x.Id).Should().Equal(2, 3); }
CSharp4861Tests
csharp
dotnet__aspnetcore
src/Http/Routing/src/Matching/FastPathTokenizer.cs
{ "start": 286, "end": 1436 }
internal static class ____ { // This section tokenizes the path by marking the sequence of slashes, and their // and the length of the text between them. // // If there is residue (text after last slash) then the length of the segment will // computed based on the string length. public static int Tokenize(string path, Span<PathSegment> segments) { // This can happen in test scenarios. if (string.IsNullOrEmpty(path)) { return 0; } int count = 0; int start = 1; // Paths always start with a leading / int end; var span = path.AsSpan(start); while ((end = span.IndexOf('/')) >= 0 && count < segments.Length) { segments[count++] = new PathSegment(start, end); start += end + 1; // resume search after the current character span = path.AsSpan(start); } // Residue var length = span.Length; if (length > 0 && count < segments.Length) { segments[count++] = new PathSegment(start, length); } return count; } }
FastPathTokenizer
csharp
dotnet__aspnetcore
src/Shared/ServerInfrastructure/Http2/Http2PeerSetting.cs
{ "start": 223, "end": 478 }
struct ____ { public Http2PeerSetting(Http2SettingsParameter parameter, uint value) { Parameter = parameter; Value = value; } public Http2SettingsParameter Parameter { get; } public uint Value { get; } }
Http2PeerSetting
csharp
DuendeSoftware__IdentityServer
bff/test/Bff.Tests/LicensingTests.cs
{ "start": 234, "end": 4837 }
public class ____(ITestOutputHelper output) : BffTestBase(output) { [Fact] public async Task Given_no_license_then_error_log() { Bff.LicenseKey = null; await InitializeAsync(); var bffLogMessages = Context.LogMessages.ToString().Split(Environment.NewLine).Where(x => x.StartsWith("bff")); bffLogMessages.ShouldContain(x => x.Contains("[Error]") && x.Contains("You do not have a valid license key for the Duende software.")); } [Fact] public async Task Given_expired_license_then_log_warning() { SetupExpiredLicense(); await InitializeAsync(); var bffLogMessages = Context.LogMessages.ToString().Split(Environment.NewLine).Where(x => x.StartsWith("bff")); bffLogMessages.ShouldContain(x => x.Contains("[Warning]") && x.Contains("Your license for the Duende software has expired")); } [Fact] public async Task Given_valid_but_expired_license_then_no_valid_or_trial_mode_logs() { SetupExpiredLicense(); await InitializeAsync(); AddOrUpdateFrontend(Some.BffFrontend()); for (var i = 0; i <= LicenseValidator.MaximumAllowedSessionsInTrialMode; i++) { var subjectId = Guid.NewGuid().ToString(); await Bff.BrowserClient.CreateIdentityServerSessionCookieAsync(IdentityServer, subjectId); await Bff.BrowserClient.Login(); } var bffLogMessages = Context.LogMessages.ToString().Split(Environment.NewLine).Where(x => x.StartsWith("bff")) .ToList(); bffLogMessages.ShouldNotContain(x => x.Contains("You do not have a valid license key for the Duende software.")); bffLogMessages.ShouldContain(x => x.Contains("Your license for the Duende software has expired on ")); bffLogMessages.ShouldNotContain(x => x.Contains("BFF is running in trial mode. The maximum number of allowed authenticated sessions ")); } [Fact] public async Task Should_not_log_error_when_below_trial_mode_authenticated_session_limit() { await InitializeAsync(); AddOrUpdateFrontend(Some.BffFrontend()); for (var i = 0; i < LicenseValidator.MaximumAllowedSessionsInTrialMode; i++) { var subjectId = Guid.NewGuid().ToString(); await Bff.BrowserClient.CreateIdentityServerSessionCookieAsync(IdentityServer, subjectId); await Bff.BrowserClient.Login(); } var bffLogMessages = Context.LogMessages.ToString().Split(Environment.NewLine).Where(x => x.StartsWith("bff")) .ToList(); bffLogMessages.ShouldNotContain(x => x.Contains("[Error]") && x.Contains("BFF is running in trial mode. The maximum number of allowed authenticated sessions ")); } [Fact] public async Task Should_log_error_when_trial_mode_authenticated_session_limit_exceeded() { await InitializeAsync(); AddOrUpdateFrontend(Some.BffFrontend()); for (var i = 0; i < LicenseValidator.MaximumAllowedSessionsInTrialMode + 6; i++) { var subjectId = Guid.NewGuid().ToString(); await Bff.BrowserClient.CreateIdentityServerSessionCookieAsync(IdentityServer, subjectId); await Bff.BrowserClient.Login(); } var bffLogMessages = Context.LogMessages.ToString().Split(Environment.NewLine).Where(x => x.StartsWith("bff")) .ToList(); var trialModeLogCount = bffLogMessages.Count(x => x.Contains("[Error]") && x.Contains("BFF is running in trial mode. The maximum number of allowed authenticated sessions ")); trialModeLogCount.ShouldBe(6); } private void SetupExpiredLicense() => Bff.LicenseKey = "eyJhbGciOiJQUzI1NiIsImtpZCI6IklkZW50aXR5U2VydmVyTGljZW5zZWtleS83Y2VhZGJiNzgxMzA0NjllODgwNjg5MTAyNTQxNGYxNiIsInR5cCI6ImxpY2Vuc2Urand0In0.eyJpc3MiOiJodHRwczovL2R1ZW5kZXNvZnR3YXJlLmNvbSIsImF1ZCI6IklkZW50aXR5U2VydmVyIiwiaWF0IjoxNzA0MDY3MjAwLCJleHAiOjE3MzE2Mjg4MDAsImNvbXBhbnlfbmFtZSI6Il90ZXN0IiwiY29udGFjdF9pbmZvIjoiam9lQGR1ZW5kZXNvZnR3YXJlLmNvbSIsImVkaXRpb24iOiJTdGFydGVyIiwiaWQiOiI3ODk2IiwiZmVhdHVyZSI6ImJmZiJ9.YcRGLlVuNBSqNuO1mdXk4GvvVEQFfQUNAnTkzs9W2iNKCxLXrZ5mDPuyTNsDSwEqsfXG8bUCVFxFGp1Bfkxs8hUIBiKuVXfeIB_lmpj5f-KueZ_XlWm0pYT-ROAzVbDdNgMR9YqCPAw8ANclk7HwRcXc0VnLNcKRFrZ0OOWNysFIanTmg7hRIQmDuMLNc2j8HCZSRJ06fijecS72lM4Vv9a6myJvAsASQhKnWTLzQvdzW7T99eobLy45qJu39LMTQkPkkJUS41YPmi2_kEmeMcRucgU4dQKHD5zT9KmzPVWJwsyowWIJ6U7lZ8FXZ8c9POsQeTeQEJY6FheJ2Ut-6Q"; }
LicensingTests
csharp
grpc__grpc-dotnet
src/Grpc.Net.Client/Balancer/CompletionContext.cs
{ "start": 941, "end": 1322 }
public sealed class ____ { /// <summary> /// Gets or sets the <see cref="BalancerAddress"/> a call was made with. Required. /// </summary> public BalancerAddress? Address { get; set; } /// <summary> /// Gets or sets the <see cref="Exception"/> thrown when making the call. /// </summary> public Exception? Error { get; set; } } #endif
CompletionContext
csharp
OrchardCMS__OrchardCore
test/OrchardCore.Tests/Extensions/ExtensionManagerTests.cs
{ "start": 2086, "end": 11038 }
private sealed class ____ : IModuleNamesProvider { private readonly string[] _moduleNames; public ModuleNamesProvider() { _moduleNames = [ "BaseThemeSample", "BaseThemeSample2", "DerivedThemeSample", "DerivedThemeSample2", "ModuleSample" ]; } public IEnumerable<string> GetModuleNames() { return _moduleNames; } } [Fact] public void ShouldReturnExtension() { var extensions = _moduleThemeScopedExtensionManager.GetExtensions() .Where(e => e.Manifest.ModuleInfo.Category == "Test"); Assert.Equal(5, extensions.Count()); } [Fact] public void ShouldReturnAllDependenciesIncludingFeatureForAGivenFeatureOrdered() { var features = _moduleScopedExtensionManager.GetFeatureDependencies("Sample3"); Assert.Equal(3, features.Count()); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); Assert.Equal("Sample3", features.ElementAt(2).Id); } [Fact] public void ShouldNotReturnFeaturesNotDependentOn() { var features = _moduleScopedExtensionManager.GetFeatureDependencies("Sample2"); Assert.Equal(2, features.Count()); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); } [Fact] public void GetDependentFeaturesShouldReturnAllFeaturesThatHaveADependencyOnAFeature() { var features = _moduleScopedExtensionManager.GetDependentFeatures("Sample1"); Assert.Equal(4, features.Count()); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); Assert.Equal("Sample3", features.ElementAt(2).Id); Assert.Equal("Sample4", features.ElementAt(3).Id); } [Fact] public void GetFeaturesShouldReturnAllFeaturesOrderedByDependency() { var features = _moduleScopedExtensionManager.GetFeatures() .Where(f => f.Category == "Test" && !f.IsTheme()); Assert.Equal(4, features.Count()); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); Assert.Equal("Sample3", features.ElementAt(2).Id); Assert.Equal("Sample4", features.ElementAt(3).Id); } [Fact] public void GetFeaturesWithAIdShouldReturnThatFeatureWithDependenciesOrdered() { var features = _moduleScopedExtensionManager.GetFeatures((IEnumerable<string>)["Sample2"]); Assert.Equal(2, features.Count()); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); } [Fact] public void GetFeaturesWithAIdShouldReturnThatFeatureWithDependenciesOrderedWithNoDuplicates() { var features = _moduleScopedExtensionManager.GetFeatures((IEnumerable<string>)["Sample2", "Sample3"]); Assert.Equal(3, features.Count()); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); Assert.Equal("Sample3", features.ElementAt(2).Id); } [Fact] public void GetFeaturesWithAIdShouldNotReturnFeaturesTheHaveADependencyOutsideOfGraph() { var features = _moduleScopedExtensionManager.GetFeatures((IEnumerable<string>)["Sample4"]); Assert.Equal(3, features.Count()); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); Assert.Equal("Sample4", features.ElementAt(2).Id); } /* Theme Base Theme Dependencies */ [Fact] public void GetFeaturesShouldReturnCorrectThemeHierarchy() { var features = _themeScopedExtensionManager.GetFeatures((IEnumerable<string>)["DerivedThemeSample"]); Assert.Equal(2, features.Count()); Assert.Equal("BaseThemeSample", features.ElementAt(0).Id); Assert.Equal("DerivedThemeSample", features.ElementAt(1).Id); } /* Theme and Module Dependencies */ [Fact] public void GetFeaturesShouldReturnBothThemesAndModules() { var features = _moduleThemeScopedExtensionManager.GetFeatures() .Where(f => f.Category == "Test"); Assert.Equal(8, features.Count()); } [Fact] public void GetFeaturesShouldReturnThemesAfterModules() { var features = _moduleThemeScopedExtensionManager.GetFeatures() .Where(f => f.Category == "Test"); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); Assert.Equal("Sample3", features.ElementAt(2).Id); Assert.Equal("Sample4", features.ElementAt(3).Id); Assert.Equal("BaseThemeSample", features.ElementAt(4).Id); Assert.Equal("BaseThemeSample2", features.ElementAt(5).Id); Assert.Equal("DerivedThemeSample", features.ElementAt(6).Id); Assert.Equal("DerivedThemeSample2", features.ElementAt(7).Id); } [Fact] public void GetFeaturesShouldReturnThemesAfterModulesWhenRequestingBoth() { var features = _moduleThemeScopedExtensionManager.GetFeatures((IEnumerable<string>)["DerivedThemeSample", "Sample3"]); Assert.Equal("Sample1", features.ElementAt(0).Id); Assert.Equal("Sample2", features.ElementAt(1).Id); Assert.Equal("Sample3", features.ElementAt(2).Id); Assert.Equal("BaseThemeSample", features.ElementAt(3).Id); Assert.Equal("DerivedThemeSample", features.ElementAt(4).Id); } [Fact] public void ShouldReturnNotFoundExtensionInfoWhenNotFound() { var extension = _moduleThemeScopedExtensionManager.GetExtension("NotFound"); Assert.False(extension.Exists); } /* The extension manager must populate the ITypeFeatureProvider correctly */ [Fact] public void TypeFeatureProviderIsPopulatedWithComponentTypes() { var feature = _moduleScopedExtensionManager.GetFeatures((IEnumerable<string>)["Sample1"]).First(); var types = _moduleScopedTypeFeatureProvider.GetTypesForFeature(feature); Assert.Equal(2, types.Count()); Assert.Contains(typeof(Sample1Startup), types); Assert.Contains(typeof(FeatureIndependentStartup), types); } [Fact] public void TypeFeatureProviderTypeMustBeMappedToAllFeatures() { // Types in modules that have no feature that matches the extension ID must be mapped to all features. var features = _moduleScopedExtensionManager.GetFeatures((IEnumerable<string>)["Sample1", "Sample2", "Sample3", "Sample4"]); foreach (var feature in features) { var types = _moduleScopedTypeFeatureProvider.GetTypesForFeature(feature); Assert.Contains(typeof(FeatureIndependentStartup), types); } } [Fact] public void TypeFeatureProviderTypeMustBeMappedToExtensionFeature() { // Types in modules that have a feature that matches the extension ID must be mapped to that feature. var feature = _moduleScopedExtensionManager.GetFeatures((IEnumerable<string>)["BaseThemeSample"]).First(); var types = _moduleScopedTypeFeatureProvider.GetTypesForFeature(feature); Assert.Equal(2, types.Count()); Assert.Contains(typeof(BaseThemeSampleStartup), types); Assert.Contains(typeof(BaseThemeFeatureIndependentStartup), types); } [Fact] public void TypeFeatureProviderTypeMustBeSkipped() { var feature = _moduleScopedExtensionManager.GetFeatures((IEnumerable<string>)["Sample2"]).First(); var types = _moduleScopedTypeFeatureProvider.GetTypesForFeature(feature); Assert.DoesNotContain(typeof(SkippedDependentType), types); } private static ExtensionManager CreateExtensionManager( IExtensionDependencyStrategy[] extensionDependencyStrategies, IExtensionPriorityStrategy[] extensionPriorityStrategies, ITypeFeatureProvider typeFeatureProvider, IFeaturesProvider featuresProvider) { var services = new ServiceCollection(); services .AddSingleton(_applicationContext) .AddSingleton(typeFeatureProvider) .AddSingleton(featuresProvider); foreach (var extensionDependencyStrategy in extensionDependencyStrategies) { services.AddSingleton(extensionDependencyStrategy); } foreach (var extensionPriorityStrategy in extensionPriorityStrategies) { services.AddSingleton(extensionPriorityStrategy); } var serviceProvider = services.BuildServiceProvider(); return new ExtensionManager(serviceProvider, new NullLogger<ExtensionManager>()); } }
ModuleNamesProvider
csharp
unoplatform__uno
src/Uno.UI/UI/Xaml/UIElementCollection.UIKit.cs
{ "start": 211, "end": 1964 }
public partial class ____ : IList<UIElement>, IEnumerable<UIElement> { private readonly BindableUIView _owner; public UIElementCollection(BindableUIView owner) { _owner = owner; } private int IndexOfCore(UIElement item) { return _owner.ChildrenShadow.IndexOf(item); } private void InsertCore(int index, UIElement item) { if (_owner.ChildrenShadow.Count == index) { _owner.AddSubview(item); } else { _owner.InsertSubview(item, index); } } private UIElement RemoveAtCore(int index) { var view = _owner.ChildrenShadow[index]; view.RemoveFromSuperview(); return view as UIElement; } private UIElement GetAtIndexCore(int index) { return _owner.ChildrenShadow[index] as UIElement; } private UIElement SetAtIndexCore(int index, UIElement value) { var view = _owner.ChildrenShadow[index]; RemoveAt(index); Insert(index, value); return view as UIElement; } private void AddCore(UIElement item) { _owner.AddSubview(item); } private IEnumerable<UIView> ClearCore() { var views = _owner.ChildrenShadow.ToList(); views.ForEach(v => v.RemoveFromSuperview()); return views; } private bool ContainsCore(UIElement item) { return _owner.ChildrenShadow.Contains(item); } private void CopyToCore(UIElement[] array, int arrayIndex) { _owner.ChildrenShadow.ToArray().CopyTo(array, arrayIndex); } private bool RemoveCore(UIElement item) { item.RemoveFromSuperview(); item.Shutdown(); return true; } private int CountCore() { return _owner.ChildrenShadow.Count; } private void MoveCore(uint oldIndex, uint newIndex) { _owner.MoveViewTo((int)oldIndex, (int)newIndex); } } }
UIElementCollection
csharp
AvaloniaUI__Avalonia
src/Avalonia.Controls/Platform/ITrayIconImpl.cs
{ "start": 124, "end": 962 }
public interface ____ : IDisposable { /// <summary> /// Sets the icon of this tray icon. /// </summary> void SetIcon(IWindowIconImpl? icon); /// <summary> /// Sets the icon of this tray icon. /// </summary> void SetToolTipText(string? text); /// <summary> /// Sets if the tray icon is visible or not. /// </summary> void SetIsVisible(bool visible); /// <summary> /// Gets the MenuExporter to allow native menus to be exported to the TrayIcon. /// </summary> INativeMenuExporter? MenuExporter { get; } /// <summary> /// Gets or Sets the Action that is called when the TrayIcon is clicked. /// </summary> Action? OnClicked { get; set; } } [Unstable]
ITrayIconImpl
csharp
ShareX__ShareX
ShareX.ScreenCaptureLib/Forms/StickerPackForm.cs
{ "start": 1160, "end": 4355 }
public partial class ____ : Form { public List<StickerPackInfo> Stickers { get; private set; } public StickerPackForm(List<StickerPackInfo> stickers) { Stickers = stickers; InitializeComponent(); ShareXResources.ApplyTheme(this, true); foreach (StickerPackInfo stickerPackInfo in Stickers) { cbStickers.Items.Add(stickerPackInfo); } if (cbStickers.Items.Count > 0) { cbStickers.SelectedIndex = 0; } UpdateEnabledStates(); } private StickerPackInfo GetCurrentStickerPack() { if (cbStickers.SelectedIndex > -1) { return cbStickers.SelectedItem as StickerPackInfo; } return null; } private void UpdateEnabledStates() { cbStickers.Enabled = btnRemove.Enabled = txtFolder.Enabled = btnFolderBrowse.Enabled = txtName.Enabled = cbStickers.SelectedIndex > -1; } private void cbStickers_SelectedIndexChanged(object sender, EventArgs e) { UpdateEnabledStates(); StickerPackInfo stickerPackInfo = GetCurrentStickerPack(); if (stickerPackInfo != null) { txtFolder.Text = stickerPackInfo.FolderPath; txtName.Text = stickerPackInfo.Name; } } private void btnAdd_Click(object sender, EventArgs e) { string selectedPath = FileHelpers.BrowseFolder(); if (!string.IsNullOrEmpty(selectedPath)) { StickerPackInfo stickerPackInfo = new StickerPackInfo(selectedPath); Stickers.Add(stickerPackInfo); cbStickers.Items.Add(stickerPackInfo); cbStickers.SelectedIndex = cbStickers.Items.Count - 1; } } private void btnRemove_Click(object sender, EventArgs e) { int selected = cbStickers.SelectedIndex; if (selected > -1) { Stickers.RemoveAt(selected); cbStickers.Items.RemoveAt(selected); cbStickers.SelectedIndex = cbStickers.Items.Count - 1; } UpdateEnabledStates(); } private void txtFolder_TextChanged(object sender, EventArgs e) { StickerPackInfo stickerPackInfo = GetCurrentStickerPack(); if (stickerPackInfo != null) { stickerPackInfo.FolderPath = txtFolder.Text; cbStickers.RefreshItems(); } } private void btnFolderBrowse_Click(object sender, EventArgs e) { FileHelpers.BrowseFolder(txtFolder, txtFolder.Text); } private void txtName_TextChanged(object sender, EventArgs e) { StickerPackInfo stickerPackInfo = GetCurrentStickerPack(); if (stickerPackInfo != null) { stickerPackInfo.Name = txtName.Text; cbStickers.RefreshItems(); } } } }
StickerPackForm
csharp
ardalis__SmartEnum
test/SmartEnum.JsonNet.UnitTests/TestEnums.cs
{ "start": 318, "end": 572 }
public sealed class ____ : SmartEnum<TestEnumInt16, short> { public static readonly TestEnumInt16 Instance = new TestEnumInt16(nameof(Instance), 1); TestEnumInt16(string name, short value) : base(name, value) { } }
TestEnumInt16
csharp
dotnet__aspnetcore
src/Mvc/Mvc.Abstractions/src/ModelBinding/ModelStateDictionary.cs
{ "start": 38764, "end": 39615 }
struct ____ : IEnumerable<string> { private readonly ModelStateDictionary _dictionary; /// <summary> /// Initializes a new instance of <see cref="KeyEnumerable"/>. /// </summary> /// <param name="dictionary">The <see cref="ModelStateDictionary"/>.</param> public KeyEnumerable(ModelStateDictionary dictionary) { _dictionary = dictionary; } /// <inheritdoc /> public KeyEnumerator GetEnumerator() => new KeyEnumerator(_dictionary, prefix: string.Empty); IEnumerator<string> IEnumerable<string>.GetEnumerator() => GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } /// <summary> /// An <see cref="IEnumerator{T}"/> for keys in <see cref="ModelStateDictionary"/>. /// </summary>
KeyEnumerable
csharp
AvaloniaUI__Avalonia
src/Markup/Avalonia.Markup.Xaml.Loader/CompilerExtensions/XamlIlBindingPathHelper.cs
{ "start": 24335, "end": 27046 }
class ____ : IXamlAstVisitor { private Stack<IXamlAstNode> _stack = new Stack<IXamlAstNode>(); private Stack<IXamlAstNode> _childScopesStack = new Stack<IXamlAstNode>(); private ScopeRegistrationFinder(string name) { Name = name; } string Name { get; } IXamlType? TargetType { get; set; } IXamlType? DataContextType { get; set; } public static (IXamlType Target, IXamlType? DataContextType)? GetTargetType(IXamlAstNode namescopeRoot, string name) { // If we start from the nested scope - skip it. if (namescopeRoot is NestedScopeMetadataNode scope) { namescopeRoot = scope.Value; } var finder = new ScopeRegistrationFinder(name); namescopeRoot.Visit(finder); return finder.TargetType is not null ? (finder.TargetType, finder.DataContextType) : null; } void IXamlAstVisitor.Pop() { var node = _stack.Pop(); if (_childScopesStack.Count > 0 && node == _childScopesStack.Peek()) { _childScopesStack.Pop(); } } void IXamlAstVisitor.Push(IXamlAstNode node) { _stack.Push(node); if (node is NestedScopeMetadataNode) { _childScopesStack.Push(node); } } IXamlAstNode IXamlAstVisitor.Visit(IXamlAstNode node) { // Ignore name registrations, if we are inside of the nested namescope. if (_childScopesStack.Count == 0) { if (node is AvaloniaNameScopeRegistrationXamlIlNode registration && registration.Name is XamlAstTextNode text && text.Text == Name) { TargetType = registration.TargetType; } // We are visiting nodes top to bottom. // If we have already found target type by its name, // it means all next nodes will be below, and not applicable for data context inheritance. else if (TargetType is null && node is AvaloniaXamlIlDataContextTypeMetadataNode dataContextTypeMetadata) { DataContextType = dataContextTypeMetadata.DataContextType; } } return node; } }
ScopeRegistrationFinder
csharp
ChilliCream__graphql-platform
src/HotChocolate/Fusion-vnext/src/Fusion.Composition/ValidationHelper.cs
{ "start": 59, "end": 952 }
internal sealed class ____ { public static bool SameTypeShape(IType typeA, IType typeB) { while (true) { if (typeA is NonNullType && typeB is not NonNullType) { typeA = typeA.InnerType(); continue; } if (typeB is NonNullType && typeA is not NonNullType) { typeB = typeB.InnerType(); continue; } if (typeA is ListType || typeB is ListType) { if (typeA is not ListType || typeB is not ListType) { return false; } typeA = typeA.InnerType(); typeB = typeB.InnerType(); continue; } return typeA.Equals(typeB, TypeComparison.Structural); } } }
ValidationHelper
csharp
bitwarden__server
src/Core/AdminConsole/Enums/Provider/ProviderStatusType.cs
{ "start": 50, "end": 143 }
public enum ____ : byte { Pending = 0, Created = 1, Billable = 2 }
ProviderStatusType
csharp
dotnet__efcore
test/EFCore.SqlServer.Tests/Storage/SqlServerRetryingExecutionStrategyTests.cs
{ "start": 229, "end": 1603 }
public class ____ { [ConditionalFact] public void GetNextDelay_returns_shorter_delay_for_InMemory_transient_errors() { var strategy = new TestSqlServerRetryingExecutionStrategy(CreateContext()); var inMemoryError = SqlExceptionFactory.CreateSqlException(41302); var delays = new List<TimeSpan>(); var delay = strategy.GetNextDelay(inMemoryError); while (delay != null) { delays.Add(delay.Value); delay = strategy.GetNextDelay(inMemoryError); } var expectedDelays = new List<TimeSpan> { TimeSpan.FromMilliseconds(0), TimeSpan.FromMilliseconds(1), TimeSpan.FromMilliseconds(3), TimeSpan.FromMilliseconds(7), TimeSpan.FromMilliseconds(15), TimeSpan.FromMilliseconds(31) }; Assert.Equal(expectedDelays.Count, delays.Count); for (var i = 0; i < expectedDelays.Count; i++) { Assert.True( Math.Abs((delays[i] - expectedDelays[i]).TotalMilliseconds) <= expectedDelays[i].TotalMilliseconds * 0.1 + 1, $"Expected: {expectedDelays[i]}; Actual: {delays[i]}"); } } protected DbContext CreateContext() => SqlServerTestHelpers.Instance.CreateContext(); }
SqlServerRetryingExecutionStrategyTests
csharp
dotnet__aspire
src/Aspire.Hosting.Docker/Resources/ServiceNodes/Build.cs
{ "start": 333, "end": 503 }
class ____ used to define various build parameters such as context, dockerfile, /// arguments, target stages, cache sources, and labels. /// </summary> [YamlSerializable]
is
csharp
dotnetcore__Util
test/Util.Core.Tests/Helpers/ConvertTest.cs
{ "start": 219, "end": 17330 }
public class ____ { #region ToInt /// <summary> /// 转换为整型 /// </summary> /// <param name="input">输入值</param> /// <param name="result">结果</param> [Theory] [InlineData( null, 0 )] [InlineData( "", 0 )] [InlineData( "1A", 0 )] [InlineData( "0", 0 )] [InlineData( "1", 1 )] [InlineData( "1778019.78", 1778020 )] [InlineData( "1778019.7801684", 1778020 )] public void TestToInt( object input, int result ) { Assert.Equal( result, Convert.ToInt( input ) ); } #endregion #region ToIntOrNull /// <summary> /// 转换为可空整型 /// </summary> /// <param name="input">输入值</param> /// <param name="result">结果</param> [Theory] [InlineData( null, null )] [InlineData( "", null )] [InlineData( "1A", null )] [InlineData( "0", 0 )] [InlineData( "1", 1 )] [InlineData( "1778019.78", 1778020 )] [InlineData( "1778019.7801684", 1778020 )] public void TestToIntOrNull( object input, int? result ) { Assert.Equal( result, Convert.ToIntOrNull( input ) ); } #endregion #region ToLong /// <summary> /// 转换为64位整型 /// </summary> /// <param name="input">输入值</param> /// <param name="result">结果</param> [Theory] [InlineData( null, 0 )] [InlineData( "", 0 )] [InlineData( "1A", 0 )] [InlineData( "0", 0 )] [InlineData( "1", 1 )] [InlineData( "1778019.7801684", 1778020 )] [InlineData( "177801978016841234", 177801978016841234 )] public void TestToLong( object input, long result ) { Assert.Equal( result, Convert.ToLong( input ) ); } #endregion #region ToLongOrNull /// <summary> /// 转换为64位可空整型 /// </summary> /// <param name="input">输入值</param> /// <param name="result">结果</param> [Theory] [InlineData( null, null )] [InlineData( "", null )] [InlineData( "1A", null )] [InlineData( "0", 0L )] [InlineData( "1", 1L )] [InlineData( "1778019.7801684", 1778020L )] [InlineData( "177801978016841234", 177801978016841234L )] public void TestToLongOrNull( object input, long? result ) { Assert.Equal( result, Convert.ToLongOrNull( input ) ); } #endregion #region ToFloat /// <summary> /// 转换为32位浮点型 /// </summary> /// <param name="input">输入值</param> /// <param name="result">结果</param> /// <param name="digits">小数位数</param> [Theory] [InlineData( null, 0, null )] [InlineData( "", 0, null )] [InlineData( "1A", 0, null )] [InlineData( "0", 0, null )] [InlineData( "1", 1, null )] [InlineData( "1.2", 1.2, null )] [InlineData( "12.346", 12.35, 2 )] public void TestToFloat( object input, float result, int? digits ) { Assert.Equal( result, Convert.ToFloat( input, digits ) ); } #endregion #region ToFloatOrNull /// <summary> /// 转换为32位可空浮点型 /// </summary> /// <param name="input">输入值</param> /// <param name="result">结果</param> /// <param name="digits">小数位数</param> [Theory] [InlineData( null, null, null )] [InlineData( "", null, null )] [InlineData( "1A", null, null )] [InlineData( "0", 0f, null )] [InlineData( "1", 1f, null )] [InlineData( "1.2", 1.2f, null )] [InlineData( "12.346", 12.35f, 2 )] public void TestToFloatOrNull( object input, float? result, int? digits ) { Assert.Equal( result, Convert.ToFloatOrNull( input, digits ) ); } #endregion #region ToDouble /// <summary> /// 转换为64位浮点型 /// </summary> /// <param name="input">输入值</param> /// <param name="result">结果</param> /// <param name="digits">小数位数</param> [Theory] [InlineData( null, 0, null )] [InlineData( "", 0, null )] [InlineData( "1A", 0, null )] [InlineData( "0", 0, null )] [InlineData( "1", 1, null )] [InlineData( "1.2", 1.2, null )] [InlineData( "12.235", 12.24, 2 )] [InlineData( "12.345", 12.34, 2 )] [InlineData( "12.3451", 12.35, 2 )] [InlineData( "12.346", 12.35, 2 )] public void TestToDouble( object input, double result, int? digits ) { Assert.Equal( result, Convert.ToDouble( input, digits ) ); } #endregion #region ToDoubleOrNull /// <summary> /// 转换为64位可空浮点型 /// </summary> /// <param name="input">输入值</param> /// <param name="result">结果</param> /// <param name="digits">小数位数</param> [Theory] [InlineData( null, null, null )] [InlineData( "", null, null )] [InlineData( "1A", null, null )] [InlineData( "0", 0d, null )] [InlineData( "1", 1d, null )] [InlineData( "1.2", 1.2, null )] [InlineData( "12.355", 12.36, 2 )] public void TestToDoubleOrNull( object input, double? result, int? digits ) { Assert.Equal( result, Convert.ToDoubleOrNull( input, digits ) ); } #endregion #region ToDecimal /// <summary> /// 转换为128位浮点型 /// </summary> /// <param name="input">输入值</param> /// <param name="result">结果</param> /// <param name="digits">小数位数</param> [Theory] [InlineData( null, 0, null )] [InlineData( "", 0, null )] [InlineData( "1A", 0, null )] [InlineData( "0", 0, null )] [InlineData( "1", 1, null )] [InlineData( "1.2", 1.2, null )] [InlineData( "12.235", 12.24, 2 )] [InlineData( "12.345", 12.34, 2 )] [InlineData( "12.3451", 12.35, 2 )] [InlineData( "12.346", 12.35, 2 )] public void TestToDecimal( object input, decimal result, int? digits ) { Assert.Equal( result, Convert.ToDecimal( input, digits ) ); } #endregion #region ToDecimalOrNull /// <summary> /// 转换为128位可空浮点型,验证 /// </summary> /// <param name="input">输入值</param> /// <param name="result">结果</param> /// <param name="digits">小数位数</param> [Theory] [InlineData( null, null, null )] [InlineData( "", null, null )] [InlineData( "1A", null, null )] [InlineData( "1A", null, 2 )] public void TestToDecimalOrNull_Validate( object input, decimal? result, int? digits ) { Assert.Equal( result, Convert.ToDecimalOrNull( input, digits ) ); } /// <summary> /// 转换为128位可空浮点型,输入值为"0" /// </summary> [Fact] public void TestToDecimalOrNull() { Assert.Equal( 0M, Convert.ToDecimalOrNull( "0" ) ); Assert.Equal( 1.2M, Convert.ToDecimalOrNull( "1.2" ) ); Assert.Equal( 23.46M, Convert.ToDecimalOrNull( "23.456", 2 ) ); } #endregion #region ToBool /// <summary> /// 转换为布尔型 /// </summary> /// <param name="input">输入值</param> /// <param name="result">结果</param> [Theory] [InlineData( null, null )] [InlineData( "false", false )] [InlineData( "true", true )] [InlineData( 0, false )] [InlineData( 1, true )] [InlineData( "0", false )] [InlineData( "1", true )] public void TestToBool( object input, bool result ) { Assert.Equal( result, Convert.ToBool( input ) ); } #endregion #region ToBoolOrNull /// <summary> /// 转换为可空布尔型 /// </summary> /// <param name="input">输入值</param> /// <param name="result">结果</param> [Theory] [InlineData( null, null )] [InlineData( "false", false )] [InlineData( "true", true )] [InlineData( 0, false )] [InlineData( 1, true )] [InlineData( "0", false )] [InlineData( "1", true )] public void TestToBoolOrNull( object input, bool? result ) { Assert.Equal( result, Convert.ToBoolOrNull( input ) ); } #endregion #region ToDateTime /// <summary> /// 转换为日期,验证 /// </summary> [Fact] public void TestToDateTime_Validate() { Assert.Equal( DateTime.MinValue, Convert.ToDateTime( null ) ); Assert.Equal( DateTime.MinValue, Convert.ToDateTime( "" ) ); Assert.Equal( DateTime.MinValue, Convert.ToDateTime( "1A" ) ); } /// <summary> /// 转换为日期 /// </summary> [Fact] public void TestToDateTime() { Assert.Equal( new DateTime( 2000, 1, 1 ), Convert.ToDateTime( "2000-1-1" ) ); } #endregion #region ToDateTimeOrNull /// <summary> /// 转换为可空日期,验证 /// </summary> /// <param name="input">输入值</param> /// <param name="result">结果</param> [Theory] [InlineData( null, null )] [InlineData( "", null )] [InlineData( "1A", null )] public void TestToDateTimeOrNull_Validate( object input, DateTime? result ) { Assert.Equal( result, Convert.ToDateTimeOrNull( input ) ); } /// <summary> /// 转换为可空日期 /// </summary> [Fact] public void TestToDateTimeOrNull() { Assert.Equal( new DateTime( 2000, 1, 1 ), Convert.ToDateTimeOrNull( "2000-1-1" ) ); } #endregion #region ToGuid /// <summary> /// 转换为Guid,验证 /// </summary> [Fact] public void TestToGuid_Validate() { Assert.Equal( Guid.Empty, Convert.ToGuid( null ) ); Assert.Equal( Guid.Empty, Convert.ToGuid( "" ) ); Assert.Equal( Guid.Empty, Convert.ToGuid( "1A" ) ); } /// <summary> /// 转换为Guid /// </summary> [Fact] public void TestToGuid() { Assert.Equal( new Guid( "B9EB56E9-B720-40B4-9425-00483D311DDC" ), Convert.ToGuid( "B9EB56E9-B720-40B4-9425-00483D311DDC" ) ); } #endregion #region ToGuidOrNull /// <summary> /// 转换为可空Guid,验证 /// </summary> /// <param name="input">输入值</param> /// <param name="result">结果</param> [Theory] [InlineData( null, null )] [InlineData( "", null )] [InlineData( "1A", null )] public void TestToGuidOrNull_Validate( object input, Guid? result ) { Assert.Equal( result, Convert.ToGuidOrNull( input ) ); } /// <summary> /// 转换为可空Guid - 转换字符串 /// </summary> [Fact] public void TestToGuidOrNull_1() { Assert.Equal( new Guid( "B9EB56E9-B720-40B4-9425-00483D311DDC" ), Convert.ToGuidOrNull( "B9EB56E9-B720-40B4-9425-00483D311DDC" ) ); } /// <summary> /// 转换为可空Guid - 转换字节数组 /// </summary> [Fact] public void TestToGuidOrNull_2() { var guid = Guid.NewGuid(); var bytes = guid.ToByteArray(); Assert.Equal( guid, Convert.ToGuidOrNull( bytes ) ); } /// <summary> /// 转换为可空Guid - 转换字节数组 - 空guid /// </summary> [Fact] public void TestToGuidOrNull_3() { var guid = Guid.Empty; var bytes = guid.ToByteArray(); Assert.Equal( guid, Convert.ToGuidOrNull( bytes ) ); } #endregion #region ToGuidList /// <summary> /// 转换为Guid集合 /// </summary> [Fact] public void TestToGuidList() { Assert.Empty( Convert.ToGuidList( null ) ); Assert.Empty( Convert.ToGuidList( "" ) ); const string guid = "83B0233C-A24F-49FD-8083-1337209EBC9A"; Assert.Single( Convert.ToGuidList( guid ) ); Assert.Equal( new Guid( guid ), Convert.ToGuidList( guid )[0] ); const string guid2 = "83B0233C-A24F-49FD-8083-1337209EBC9A,EAB523C6-2FE7-47BE-89D5-C6D440C3033A"; Assert.Equal( 2, Convert.ToGuidList( guid2 ).Count ); Assert.Equal( new Guid( "83B0233C-A24F-49FD-8083-1337209EBC9A" ), Convert.ToGuidList( guid2 )[0] ); Assert.Equal( new Guid( "EAB523C6-2FE7-47BE-89D5-C6D440C3033A" ), Convert.ToGuidList( guid2 )[1] ); } /// <summary> /// 转换为Guid集合 /// </summary> [Fact] public void TestToGuidList_2() { const string guid = "83B0233C-A24F-49FD-8083-1337209EBC9A,,EAB523C6-2FE7-47BE-89D5-C6D440C3033A,"; Assert.Equal( 2, Convert.ToGuidList( guid ).Count ); Assert.Equal( new Guid( "83B0233C-A24F-49FD-8083-1337209EBC9A" ), Convert.ToGuidList( guid )[0] ); Assert.Equal( new Guid( "EAB523C6-2FE7-47BE-89D5-C6D440C3033A" ), Convert.ToGuidList( guid )[1] ); } #endregion #region ToList /// <summary> /// 泛型集合转换 /// </summary> [Fact] public void TestToList() { Assert.Empty( Convert.ToList<string>( null ) ); Assert.Single( Convert.ToList<string>( "1" ) ); Assert.Equal( 2, Convert.ToList<string>( "1,2" ).Count ); Assert.Equal( 2, Convert.ToList<int>( "1,2" )[1] ); } #endregion #region To /// <summary> /// 测试通用泛型转换 /// </summary> [Fact] public void TestTo() { Assert.Null( Convert.To<string>( "" ) ); Assert.Equal( "1A", Convert.To<string>( "1A" ) ); Assert.Equal( 0, Convert.To<int>( null ) ); Assert.Equal( 0, Convert.To<int>( "" ) ); Assert.Equal( 0, Convert.To<int>( "2A" ) ); Assert.Equal( 1, Convert.To<int>( "1" ) ); Assert.Null( Convert.To<int?>( null ) ); Assert.Null( Convert.To<int?>( "" ) ); Assert.Null( Convert.To<int?>( "3A" ) ); Assert.Equal( Guid.Empty, Convert.To<Guid>( "" ) ); Assert.Equal( Guid.Empty, Convert.To<Guid>( "4A" ) ); Assert.Equal( new Guid( "B9EB56E9-B720-40B4-9425-00483D311DDC" ), Convert.To<Guid>( "B9EB56E9-B720-40B4-9425-00483D311DDC" ) ); Assert.Equal( new Guid( "B9EB56E9-B720-40B4-9425-00483D311DDC" ), Convert.To<Guid?>( "B9EB56E9-B720-40B4-9425-00483D311DDC" ) ); Assert.Equal( 12.5, Convert.To<double>( "12.5" ) ); Assert.Equal( 12.5, Convert.To<double?>( "12.5" ) ); Assert.Equal( 12.5M, Convert.To<decimal>( "12.5" ) ); Assert.True( Convert.To<bool>( "true" ) ); Assert.Equal( new DateTime( 2000, 1, 1 ), Convert.To<DateTime>( "2000-1-1" ) ); Assert.Equal( new DateTime( 2000, 1, 1 ), Convert.To<DateTime?>( "2000-1-1" ) ); var guid = Guid.NewGuid(); Assert.Equal( guid.ToString(), Convert.To<string>( guid ) ); Assert.Equal( EnumSample.C, Convert.To<EnumSample>( "c" ) ); } /// <summary> /// 测试通用泛型转换 - 转换对象副本 /// </summary> [Fact] public void TestTo_2() { Sample4 sample = new Sample4 { StringValue = "a" }; var result = Convert.To<Sample4>( sample.GetClone() ); Assert.Equal( "a", result?.StringValue ); } /// <summary> /// 测试通用泛型转换 - 转换Json元素 /// </summary> [Fact] public void TestTo_3() { //序列化再反序列化字典 var dic = new Dictionary<string, object> { {"a", new Sample3 {StringValue = "a"}}, {"b", new Sample3 {StringValue = "b"}} }; var json = Json.ToJson( dic ); dic = Json.ToObject<Dictionary<string, object>>( json ); //从字典中获取元素并转换 var element = dic["b"]; var result = Convert.To<Sample3>( element ); //验证 Assert.Equal( "b", result?.StringValue ); } #endregion #region ToDictionary /// <summary> /// 测试对象转换为属性名值对 /// </summary> [Fact] public void TestToDictionary_1() { var sample = new Sample2 { BoolValue = true, Description = "Description", StringValue = "StringValue", IntValue = 2, Display = "Display", NullableBoolValue = true, DisplayName = "DisplayName", DisplayName2 = "DisplayName2", Test3 = new Sample3 { StringValue = "a" }, TestList = new List<Sample3> { new() { StringValue = "a" }, new() { StringValue = "b" } } }; var result = Convert.ToDictionary( sample ); Assert.Equal( 10, result.Count ); Assert.Equal( "Description", result["Description"] ); Assert.Equal( "Display", result["Display"] ); Assert.Equal( "DisplayName", result["DisplayName"] ); Assert.Equal( "DisplayName2", result["DisplayName2"] ); Assert.Equal( 2, result["IntValue"] ); } /// <summary> /// 测试对象转换为属性名值对 /// </summary> [Fact] public void TestToDictionary_2() { var sample = new Sample2 { BoolValue = true, Description = "Description", StringValue = "StringValue", IntValue = 2, Display = "Display", NullableBoolValue = true, DisplayName = "DisplayName", DisplayName2 = "DisplayName2", Test3 = new Sample3 { StringValue = "a" }, TestList = new List<Sample3> { new() { StringValue = "a" }, new() { StringValue = "b" } } }; var result = Convert.ToDictionary( sample,true ); Assert.Equal( 10, result.Count ); Assert.Equal( "Description", result["描述"] ); Assert.Equal( "Display", result["Display"] ); Assert.Equal( "DisplayName", result["显示名"] ); Assert.Equal( "DisplayName2", result["DisplayName2"] ); Assert.Equal( 2, result["IntValue"] ); } /// <summary> /// 测试对象转换为属性名值对 - 传入字典 /// </summary> [Fact] public void TestToDictionary_3() { var content = new Dictionary<string, object> { { "Code", "a" }, { "Price", 0 } }; var result = Convert.ToDictionary( content ); Assert.Equal( 2, result.Count ); Assert.Equal( "a", result["Code"] ); Assert.Equal( 0, result["Price"] ); } #endregion }
ConvertTest
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Bson/Serialization/Serializers/BsonValueCSharpNullSerializer.cs
{ "start": 854, "end": 5225 }
public class ____<TBsonValue> : SerializerBase<TBsonValue> where TBsonValue : BsonValue { // private fields private readonly IBsonSerializer<TBsonValue> _wrappedSerializer; // constructors /// <summary> /// Initializes a new instance of the <see cref="BsonValueCSharpNullSerializer{TBsonValue}"/> class. /// </summary> /// <param name="wrappedSerializer">The wrapped serializer.</param> public BsonValueCSharpNullSerializer(IBsonSerializer<TBsonValue> wrappedSerializer) { _wrappedSerializer = wrappedSerializer; } // public methods /// <summary> /// Deserializes a value. /// </summary> /// <param name="context">The deserialization context.</param> /// <param name="args">The deserialization args.</param> /// <returns>A deserialized value.</returns> public override TBsonValue Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { var bsonReader = context.Reader; var bsonType = bsonReader.GetCurrentBsonType(); if (bsonType == BsonType.Document && IsCSharpNullRepresentation(bsonReader)) { // if IsCSharpNullRepresentation returns true it will have consumed the document representing C# null return null; } // handle BSON null for backward compatibility with existing data (new data would have _csharpnull) if (bsonType == BsonType.Null && (args.NominalType != typeof(BsonValue) && args.NominalType != typeof(BsonNull))) { bsonReader.ReadNull(); return null; } return _wrappedSerializer.Deserialize(context); } /// <inheritdoc/> public override bool Equals(object obj) { if (object.ReferenceEquals(obj, null)) { return false; } if (object.ReferenceEquals(this, obj)) { return true; } return base.Equals(obj) && obj is BsonValueCSharpNullSerializer<TBsonValue> other && object.Equals(_wrappedSerializer, other._wrappedSerializer); } /// <inheritdoc/> public override int GetHashCode() => 0; /// <summary> /// Serializes a value. /// </summary> /// <param name="context">The serialization context.</param> /// <param name="args">The serialization args.</param> /// <param name="value">The object.</param> public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, TBsonValue value) { if (value == null) { var bsonWriter = context.Writer; bsonWriter.WriteStartDocument(); bsonWriter.WriteBoolean("_csharpnull", true); bsonWriter.WriteEndDocument(); } else { _wrappedSerializer.Serialize(context, value); } } // private methods private bool IsCSharpNullRepresentation(IBsonReader bsonReader) { var bookmark = bsonReader.GetBookmark(); bsonReader.ReadStartDocument(); var bsonType = bsonReader.ReadBsonType(); if (bsonType == BsonType.Boolean) { var name = bsonReader.ReadName(); if (name == "_csharpnull" || name == "$csharpnull") { var value = bsonReader.ReadBoolean(); if (value) { bsonType = bsonReader.ReadBsonType(); if (bsonType == BsonType.EndOfDocument) { bsonReader.ReadEndDocument(); return true; } } } } bsonReader.ReturnToBookmark(bookmark); return false; } } /// <summary> /// Represents a serializer for a BsonValue that can round trip C# null and implements IBsonArraySerializer and IBsonDocumentSerializer. /// </summary> /// <typeparam name="TBsonValue">The type of the bson value.</typeparam>
BsonValueCSharpNullSerializer
csharp
MassTransit__MassTransit
src/MassTransit/SqlTransport/Configuration/SqlReceiveEndpointConfigurationExtensions.cs
{ "start": 57, "end": 1359 }
public static class ____ { /// <summary> /// Declare a ReceiveEndpoint using a unique generated queue name. This queue defaults to auto-delete /// and non-durable. By default all services bus instances include a default receiveEndpoint that is /// of this type (created automatically upon the first receiver binding). /// </summary> /// <param name="configurator"></param> /// <param name="configure"></param> public static void ReceiveEndpoint(this ISqlBusFactoryConfigurator configurator, Action<ISqlReceiveEndpointConfigurator>? configure = null) { configurator.ReceiveEndpoint(new TemporaryEndpointDefinition(), DefaultEndpointNameFormatter.Instance, configure); } /// <summary> /// Declare a receive endpoint using the endpoint <paramref name="definition"/>. /// </summary> /// <param name="configurator"></param> /// <param name="definition"></param> /// <param name="configure"></param> public static void ReceiveEndpoint(this ISqlBusFactoryConfigurator configurator, IEndpointDefinition definition, Action<ISqlReceiveEndpointConfigurator>? configure = null) { configurator.ReceiveEndpoint(definition, DefaultEndpointNameFormatter.Instance, configure); } }
SqlReceiveEndpointConfigurationExtensions
csharp
dotnet__maui
src/Graphics/src/Graphics/Size.cs
{ "start": 603, "end": 898 }
struct ____ equal width and height. /// </summary> /// <param name="size">The value to use for both width and height (default is 0).</param> public Size(double size = 0) { Width = size; Height = size; } /// <summary> /// Initializes a new instance of the <see cref="Size"/>
with
csharp
microsoft__garnet
libs/server/Auth/GarnetAclWithAadAuthenticator.cs
{ "start": 188, "end": 1741 }
class ____ : GarnetACLAuthenticator { /// <summary> /// Authenticator to validate username and password. /// </summary> private readonly IGarnetAuthenticator _garnetAuthenticator; public GarnetAclWithAadAuthenticator(AccessControlList accessControlList, IGarnetAuthenticator garnetAuthenticator, ILogger logger) : base(accessControlList, logger) { _garnetAuthenticator = garnetAuthenticator; } /// <summary> /// Authenticate the given user/password combination. /// </summary> /// <param name="userHandle"> User details to use for authentication.</param> /// <param name="password">Password to authenticate with.</param> /// <param name="username">Username to authenticate with. If empty, will authenticate default user.</param> /// <returns>true if authentication was successful</returns> protected override bool AuthenticateInternal(UserHandle userHandle, ReadOnlySpan<byte> username, ReadOnlySpan<byte> password) { if (userHandle.User.IsEnabled && password.Length > 0 && _garnetAuthenticator.Authenticate(password, username)) { _userHandle = userHandle; return true; } return false; } public override bool IsAuthenticated { get { return this._garnetAuthenticator.IsAuthenticated && base.IsAuthenticated; } } } }
GarnetAclWithAadAuthenticator
csharp
Antaris__RazorEngine
src/source/RazorEngine.Core/Compilation/DynamicObject/Impromtu/ImpromptuLateLibraryType.cs
{ "start": 489, "end": 1556 }
public class ____ : ImpromptuForwarder { /// <summary> /// Initializes a new instance of the <see cref="ImpromptuLateLibraryType"/> class. /// </summary> /// <param name="type">The type.</param> public ImpromptuLateLibraryType(Type type) : base(type) { } /// <summary> /// Initializes a new instance of the <see cref="ImpromptuLateLibraryType"/> class. /// </summary> /// <param name="typeName">Qualified Name of the type.</param> public ImpromptuLateLibraryType(string typeName) : base(Type.GetType(typeName, false)) { } /// <summary> /// Returns a late bound constructor /// </summary> /// <value>The late bound constructor</value> public dynamic @new { get { return new ConstructorForward((Type)Target); } } /// <summary> /// Forward argument to constructor including named arguments /// </summary>
ImpromptuLateLibraryType
csharp
graphql-dotnet__graphql-dotnet
src/GraphQL.Analyzers.Tests/FieldBuilderAnalyzerTests.cs
{ "start": 23059, "end": 24311 }
public class ____ : ObjectGraphType { public MyGraphType() { Field<StringGraphType>("name") .Description("description") .Resolve(context => "text"); } } """; var expected = VerifyCS.Diagnostic(FieldBuilderAnalyzer.DoNotUseObsoleteFieldMethods).WithLocation(0); var test = new VerifyCS.Test { TestCode = source, FixedCode = fix, ExpectedDiagnostics = { expected }, TestState = { AnalyzerConfigFiles = { ("/.editorconfig", $""" root = true [*] {FieldBuilderCodeFixProvider.ReformatOption} = true ") """) } } }; await test.RunAsync(); } [Fact] public async Task ReformatOptionIsTrue_SourceReformatted_CommentsPreserved() { const string source = """ using GraphQL.Types; namespace Sample.Server;
MyGraphType
csharp
PrismLibrary__Prism
tests/Wpf/Prism.Wpf.Tests/Regions/Behaviors/SyncRegionContextWithHostBehaviorFixture.cs
{ "start": 226, "end": 5227 }
public class ____ { [StaFact] public void ShouldForwardRegionContextValueToHostControl() { MockPresentationRegion region = new MockPresentationRegion(); SyncRegionContextWithHostBehavior behavior = new SyncRegionContextWithHostBehavior(); behavior.Region = region; DependencyObject mockDependencyObject = new MockDependencyObject(); behavior.HostControl = mockDependencyObject; behavior.Attach(); Assert.Null(region.Context); RegionContext.GetObservableContext(mockDependencyObject).Value = "NewValue"; Assert.Equal("NewValue", region.Context); } [StaFact] public void ShouldUpdateHostControlRegionContextValueWhenContextOfRegionChanges() { MockPresentationRegion region = new MockPresentationRegion(); SyncRegionContextWithHostBehavior behavior = new SyncRegionContextWithHostBehavior(); behavior.Region = region; DependencyObject mockDependencyObject = new MockDependencyObject(); behavior.HostControl = mockDependencyObject; ObservableObject<object> observableRegionContext = RegionContext.GetObservableContext(mockDependencyObject); behavior.Attach(); Assert.Null(observableRegionContext.Value); region.Context = "NewValue"; Assert.Equal("NewValue", observableRegionContext.Value); } [StaFact] public void ShouldGetInitialValueFromHostAndSetOnRegion() { MockPresentationRegion region = new MockPresentationRegion(); SyncRegionContextWithHostBehavior behavior = new SyncRegionContextWithHostBehavior(); behavior.Region = region; DependencyObject mockDependencyObject = new MockDependencyObject(); behavior.HostControl = mockDependencyObject; RegionContext.GetObservableContext(mockDependencyObject).Value = "NewValue"; Assert.Null(region.Context); behavior.Attach(); Assert.Equal("NewValue", region.Context); } [StaFact] public void AttachShouldNotThrowWhenHostControlNull() { MockPresentationRegion region = new MockPresentationRegion(); SyncRegionContextWithHostBehavior behavior = new SyncRegionContextWithHostBehavior(); behavior.Region = region; behavior.Attach(); } [StaFact] public void AttachShouldNotThrowWhenHostControlNullAndRegionContextSet() { MockPresentationRegion region = new MockPresentationRegion(); SyncRegionContextWithHostBehavior behavior = new SyncRegionContextWithHostBehavior(); behavior.Region = region; behavior.Attach(); region.Context = "Changed"; } [StaFact] public void ChangingRegionContextObservableObjectValueShouldAlsoChangeRegionContextDependencyProperty() { MockPresentationRegion region = new MockPresentationRegion(); SyncRegionContextWithHostBehavior behavior = new SyncRegionContextWithHostBehavior(); behavior.Region = region; DependencyObject hostControl = new MockDependencyObject(); behavior.HostControl = hostControl; behavior.Attach(); Assert.Null(RegionManager.GetRegionContext(hostControl)); RegionContext.GetObservableContext(hostControl).Value = "NewValue"; Assert.Equal("NewValue", RegionManager.GetRegionContext(hostControl)); } [StaFact] public void AttachShouldChangeRegionContextDependencyProperty() { MockPresentationRegion region = new MockPresentationRegion(); SyncRegionContextWithHostBehavior behavior = new SyncRegionContextWithHostBehavior(); behavior.Region = region; DependencyObject hostControl = new MockDependencyObject(); behavior.HostControl = hostControl; RegionContext.GetObservableContext(hostControl).Value = "NewValue"; Assert.Null(RegionManager.GetRegionContext(hostControl)); behavior.Attach(); Assert.Equal("NewValue", RegionManager.GetRegionContext(hostControl)); } [StaFact] public void SettingHostControlAfterAttachThrows() { var ex = Assert.Throws<InvalidOperationException>(() => { SyncRegionContextWithHostBehavior behavior = new SyncRegionContextWithHostBehavior(); DependencyObject hostControl1 = new MockDependencyObject(); behavior.HostControl = hostControl1; behavior.Attach(); DependencyObject hostControl2 = new MockDependencyObject(); behavior.HostControl = hostControl2; }); } } }
SyncRegionContextWithHostBehaviorFixture
csharp
icsharpcode__ILSpy
ICSharpCode.Decompiler.Tests/TypeSystem/TypeSystemTestCase.cs
{ "start": 9920, "end": 10204 }
public class ____ : IInterfaceWithIndexers, IGenericInterfaceWithIndexer<int> { public int this[int x] { get { return 0; } set { } } public int this[string x] { get { return 0; } set { } } public int this[int x, int y] { get { return 0; } set { } } }
ClassThatImplementsIndexers
csharp
dotnet__efcore
test/EFCore.Tests/ChangeTracking/Internal/InternalEntrySubscriberTest.cs
{ "start": 21969, "end": 24750 }
private class ____ : IChangeDetector { public List<Tuple<IInternalEntry, IPropertyBase>> Changing { get; } = []; public List<Tuple<IInternalEntry, IPropertyBase>> Changed { get; } = []; public void PropertyChanged(IInternalEntry entry, IPropertyBase property, bool setModified) => Changed.Add(Tuple.Create(entry, property)); public void PropertyChanging(IInternalEntry entry, IPropertyBase property) => Changing.Add(Tuple.Create(entry, property)); public void DetectChanges(IStateManager stateManager) { } public void DetectChanges(InternalEntityEntry entry) { } public (EventHandler<DetectChangesEventArgs> DetectingAllChanges, EventHandler<DetectedChangesEventArgs> DetectedAllChanges, EventHandler<DetectEntityChangesEventArgs> DetectingEntityChanges, EventHandler<DetectedEntityChangesEventArgs> DetectedEntityChanges) CaptureEvents() => (null, null, null, null); public void SetEvents( EventHandler<DetectChangesEventArgs> detectingAllChanges, EventHandler<DetectedChangesEventArgs> detectedAllChanges, EventHandler<DetectEntityChangesEventArgs> detectingEntityChanges, EventHandler<DetectedEntityChangesEventArgs> detectedEntityChanges) { } public event EventHandler<DetectEntityChangesEventArgs> DetectingEntityChanges; public void OnDetectingEntityChanges(InternalEntityEntry internalEntityEntry) => DetectingEntityChanges?.Invoke(null, null); public event EventHandler<DetectChangesEventArgs> DetectingAllChanges; public void OnDetectingAllChanges(IStateManager stateManager) => DetectingAllChanges?.Invoke(null, null); public event EventHandler<DetectedEntityChangesEventArgs> DetectedEntityChanges; public void OnDetectedEntityChanges(InternalEntityEntry internalEntityEntry, bool changesFound) => DetectedEntityChanges?.Invoke(null, null); public event EventHandler<DetectedChangesEventArgs> DetectedAllChanges; public void OnDetectedAllChanges(IStateManager stateManager, bool changesFound) => DetectedAllChanges?.Invoke(null, null); public void Suspend() { } public void Resume() { } public void ResetState() { } public void DetectChanges(InternalComplexEntry entry) => throw new NotImplementedException(); public bool DetectComplexCollectionChanges(InternalEntryBase entry, IComplexProperty complexProperty) => throw new NotImplementedException(); }
TestPropertyListener