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
domaindrivendev__Swashbuckle.AspNetCore
test/WebSites/Basic/Swagger/AssignRequestBodyVendorExtensions.cs
{ "start": 94, "end": 493 }
public class ____ : IRequestBodyFilter { public void Apply(IOpenApiRequestBody requestBody, RequestBodyFilterContext context) { if (requestBody is OpenApiRequestBody body) { body.Extensions ??= new Dictionary<string, IOpenApiExtension>(); body.Extensions.Add("x-purpose", new JsonNodeExtension("test")); } } }
AssignRequestBodyVendorExtensions
csharp
fluentassertions__fluentassertions
Src/FluentAssertions/Equivalency/Steps/EquivalencyValidationContextExtensions.cs
{ "start": 77, "end": 367 }
internal static class ____ { public static IEquivalencyValidationContext AsCollectionItem<TItem>(this IEquivalencyValidationContext context, int index) => context.AsCollectionItem<TItem>(index.ToString(CultureInfo.InvariantCulture)); }
EquivalencyValidationContextExtensions
csharp
protobuf-net__protobuf-net
src/protobuf-net.Core/Serializers/MapSerializer.cs
{ "start": 363, "end": 1843 }
partial class ____ { /// <summary>Create a map serializer that operates on dictionaries</summary> [MethodImpl(ProtoReader.HotPath)] public static MapSerializer<Dictionary<TKey, TValue>, TKey, TValue> CreateDictionary<[DynamicallyAccessedMembers(DynamicAccess.ContractType)] TKey, [DynamicallyAccessedMembers(DynamicAccess.ContractType)] TValue>() => SerializerCache<DictionarySerializer<TKey, TValue>>.InstanceField; /// <summary>Create a map serializer that operates on dictionaries</summary> [MethodImpl(ProtoReader.HotPath)] public static MapSerializer<TCollection, TKey, TValue> CreateDictionary<TCollection, [DynamicallyAccessedMembers(DynamicAccess.ContractType)] TKey, [DynamicallyAccessedMembers(DynamicAccess.ContractType)] TValue>() where TCollection : IDictionary<TKey, TValue> => SerializerCache<DictionarySerializer<TCollection, TKey, TValue>>.InstanceField; /// <summary>Create a map serializer that operates on dictionaries</summary> [MethodImpl(ProtoReader.HotPath)] public static MapSerializer<IReadOnlyDictionary<TKey, TValue>, TKey, TValue> CreateIReadOnlyDictionary<[DynamicallyAccessedMembers(DynamicAccess.ContractType)] TKey, [DynamicallyAccessedMembers(DynamicAccess.ContractType)] TValue>() => SerializerCache<DictionaryOfIReadOnlyDictionarySerializer<TKey, TValue>>.InstanceField; } /// <summary> /// Base
MapSerializer
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.OpenId/ViewModels/OpenIdScopeIndexViewModel.cs
{ "start": 182, "end": 416 }
public class ____ { public string Description { get; set; } public string DisplayName { get; set; } public string Id { get; set; } public bool IsChecked { get; set; } public string Name { get; set; } }
OpenIdScopeEntry
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp/Application/Services/CrudAppServiceBase.cs
{ "start": 330, "end": 500 }
class ____ CrudAppService and AsyncCrudAppService classes. /// Inherit either from CrudAppService or AsyncCrudAppService, not from this class. /// </summary>
for
csharp
louthy__language-ext
LanguageExt.Core/Class Instances/Eq/EqIterable.cs
{ "start": 1490, "end": 2014 }
public struct ____<A> : Eq<Iterable<A>> { /// <summary> /// Equality check /// </summary> [Pure] public static bool Equals(Iterable<A> x, Iterable<A> y) => EqIterable<EqDefault<A>, A>.Equals(x, y); /// <summary> /// Get hash code of the value /// </summary> /// <param name="x">Value to get the hash code of</param> /// <returns>The hash code of x</returns> [Pure] public static int GetHashCode(Iterable<A> x) => HashableIterable<A>.GetHashCode(x); }
EqIterable
csharp
dotnet__orleans
src/api/Orleans.Core/Orleans.Core.cs
{ "start": 20615, "end": 21229 }
partial class ____ { public bool CancelRequestOnTimeout { get { throw null; } set { } } public bool DropExpiredMessages { get { throw null; } set { } } public int MaxMessageBodySize { get { throw null; } set { } } public int MaxMessageHeaderSize { get { throw null; } set { } } public System.TimeSpan ResponseTimeout { get { throw null; } set { } } public System.TimeSpan ResponseTimeoutWithDebugger { get { throw null; } set { } } public bool WaitForCancellationAcknowledgement { get { throw null; } set { } } } public static
MessagingOptions
csharp
dotnet__aspnetcore
src/Shared/RoslynUtils/ParsabilityHelper.cs
{ "start": 10170, "end": 10299 }
internal enum ____ { String, IParsable, Enum, TryParse, TryParseWithFormatProvider, Uri, }
ParsabilityMethod
csharp
MassTransit__MassTransit
src/MassTransit/Courier/RoutingSlipResponseProxy.cs
{ "start": 3932, "end": 4098 }
public abstract class ____<TRequest, TResponse> : RoutingSlipResponseProxy<TRequest, TResponse, Fault<TRequest>> where TRequest :
RoutingSlipResponseProxy
csharp
dotnet__machinelearning
src/Microsoft.ML.Transforms/Expression/Tokens.cs
{ "start": 4026, "end": 4418 }
internal sealed class ____ : NumLitToken { public readonly float Value; public FltLitToken(TextSpan span, float val) : base(span, TokKind.FltLit) { Value = val; } public override string ToString() { if (float.IsPositiveInfinity(Value)) return "1e1000f"; return Value.ToString("R") + "f"; } }
FltLitToken
csharp
NEventStore__NEventStore
src/NEventStore.Persistence.AcceptanceTests/PersistenceTests.Async.cs
{ "start": 16026, "end": 16950 }
public class ____ : PersistenceEngineConcernAsync { private CommitAttempt? _failedAttempt; private Exception? _thrown; protected override async Task ContextAsync() { string streamId = Guid.NewGuid().ToString(); CommitAttempt successfulAttempt = streamId.BuildAttempt(); await Persistence.CommitAsync(successfulAttempt, CancellationToken.None); _failedAttempt = streamId.BuildAttempt(); } protected override async Task BecauseAsync() { _thrown = await Catch.ExceptionAsync(() => Persistence.CommitAsync(_failedAttempt!, CancellationToken.None)); } [Fact] public void should_throw_a_ConcurrencyException() { _thrown.Should().BeOfType<ConcurrencyException>(); } } #if MSTEST [TestClass] #endif
when_attempting_to_overwrite_a_committed_sequence
csharp
cake-build__cake
src/Cake.Core/IO/Globbing/Nodes/RelativeRootNode.cs
{ "start": 304, "end": 556 }
internal sealed class ____ : GlobNode { [DebuggerStepThrough] public override void Accept(GlobVisitor globber, GlobVisitorContext context) { globber.VisitRelativeRoot(this, context); } } }
RelativeRootNode
csharp
cake-build__cake
src/Cake.Common.Tests/Fixtures/Build/BambooInfoFixture.cs
{ "start": 328, "end": 3240 }
internal sealed class ____ { public ICakeEnvironment Environment { get; set; } public BambooInfoFixture() { Environment = Substitute.For<ICakeEnvironment>(); // BambooBuildInfo Environment.GetEnvironmentVariable("bamboo_build_working_directory").Returns("C:\\build\\CAKE-CAKE-JOB1"); Environment.GetEnvironmentVariable("bamboo_buildNumber").Returns("28"); Environment.GetEnvironmentVariable("bamboo_buildKey").Returns("CAKE-CAKE-JOB1"); Environment.GetEnvironmentVariable("bamboo_buildResultKey").Returns("CAKE-CAKE-JOB1-28"); Environment.GetEnvironmentVariable("bamboo_buildResultsUrl").Returns("https://cakebuild.atlassian.net/builds/browse/CAKE-CAKE-JOB1-28"); Environment.GetEnvironmentVariable("bamboo_buildTimeStamp").Returns("2015-12-15T22:53:37.847+01:00"); // BambooCustomBuildInfo Environment.GetEnvironmentVariable("bamboo_customRevision").Returns("Cake with Iceing"); // BambooCommitInfo Environment.GetEnvironmentVariable("bamboo_planRepository_revision").Returns("d4a3a4cb304548450e3cab2ff735f778ffe58d03"); // BambooPlanInfo Environment.GetEnvironmentVariable("bamboo_planKey").Returns("CAKE-CAKE"); Environment.GetEnvironmentVariable("bamboo_planName").Returns("cake-bamboo - dev"); Environment.GetEnvironmentVariable("bamboo_shortJobKey").Returns("JOB1"); Environment.GetEnvironmentVariable("bamboo_shortJobName").Returns("Build Cake"); Environment.GetEnvironmentVariable("bamboo_shortPlanKey").Returns("CAKE"); Environment.GetEnvironmentVariable("bamboo_shortPlanName").Returns("Cake"); // BambooRepositoryInfo Environment.GetEnvironmentVariable("bamboo_planRepository_type").Returns("git"); Environment.GetEnvironmentVariable("bamboo_repository_name").Returns("Cake/Develop"); Environment.GetEnvironmentVariable("bamboo_planRepository_branch").Returns("develop"); } public BambooBuildInfo CreateBuildInfo() { return new BambooBuildInfo(Environment); } public BambooPlanInfo CreatePlanInfo() { return new BambooPlanInfo(Environment); } public BambooCommitInfo CreateCommitInfo() { return new BambooCommitInfo(Environment); } public BambooRepositoryInfo CreateRepositoryInfo() { return new BambooRepositoryInfo(Environment); } public BambooCustomBuildInfo CreateCustomBuildInfo() { return new BambooCustomBuildInfo(Environment); } public BambooEnvironmentInfo CreateEnvironmentInfo() { return new BambooEnvironmentInfo(Environment); } } }
BambooInfoFixture
csharp
dotnet__BenchmarkDotNet
tests/BenchmarkDotNet.IntegrationTests/MemoryDiagnoserTests.cs
{ "start": 9019, "end": 10522 }
public class ____ { [Benchmark] public byte[] SixtyFourBytesArray() { // this benchmark should hit allocation quantum problem // it allocates a little of memory, but it takes a lot of time to execute so we can't run in thousands of times! Thread.Sleep(TimeSpan.FromSeconds(0.5)); return new byte[64]; } } [TheoryEnvSpecific("Full Framework cannot measure precisely enough for low invocation counts.", EnvRequirement.DotNetCoreOnly)] [MemberData(nameof(GetToolchains), DisableDiscoveryEnumeration = true)] [Trait(Constants.Category, Constants.BackwardCompatibilityCategory)] public void AllocationQuantumIsNotAnIssueForNetCore21Plus(IToolchain toolchain) { long objectAllocationOverhead = IntPtr.Size * 2; // pointer to method table + object header word long arraySizeOverhead = IntPtr.Size; // array length int warmupCount = OsDetector.IsMacOS() ? 5 // Workaround setting for macos. https://github.com/dotnet/BenchmarkDotNet/issues/2779 : 0; // Other OS don't need warmup AssertAllocations(toolchain, typeof(TimeConsuming), new Dictionary<string, long> { { nameof(TimeConsuming.SixtyFourBytesArray), 64 + objectAllocationOverhead + arraySizeOverhead } }, warmupCount: warmupCount); }
TimeConsuming
csharp
abpframework__abp
modules/cms-kit/src/Volo.CmsKit.Public.Application/Volo/CmsKit/Public/GlobalResources/GlobalResourcePublicAppService.cs
{ "start": 406, "end": 1224 }
public class ____ : CmsKitPublicAppServiceBase, IGlobalResourcePublicAppService { public GlobalResourceManager GlobalResourceManager { get; } public GlobalResourcePublicAppService(GlobalResourceManager globalResourceManager) { GlobalResourceManager = globalResourceManager; } public virtual async Task<GlobalResourceDto> GetGlobalScriptAsync() { var globalScript = await GlobalResourceManager.GetGlobalScriptAsync(); return ObjectMapper.Map<GlobalResource, GlobalResourceDto>(globalScript); } public virtual async Task<GlobalResourceDto> GetGlobalStyleAsync() { var globalStyle = await GlobalResourceManager.GetGlobalStyleAsync(); return ObjectMapper.Map<GlobalResource, GlobalResourceDto>(globalStyle); } }
GlobalResourcePublicAppService
csharp
MassTransit__MassTransit
tests/MassTransit.Azure.Table.Tests/Saga/ReadOnly_Specs.cs
{ "start": 3931, "end": 4033 }
class ____ { public Guid CorrelationId { get; set; } } } }
StartupComplete
csharp
dotnet__aspnetcore
src/Hosting/Hosting/test/Internal/HostingEventSourceTests.cs
{ "start": 392, "end": 9136 }
public class ____ : LoggedTest { [Fact] public void MatchesNameAndGuid() { // Arrange & Act var eventSource = new HostingEventSource(); // Assert Assert.Equal("Microsoft.AspNetCore.Hosting", eventSource.Name); Assert.Equal(Guid.Parse("9ded64a4-414c-5251-dcf7-1e4e20c15e70", CultureInfo.InvariantCulture), eventSource.Guid); } [Fact] public void HostStart() { // Arrange var expectedEventId = 1; var eventListener = new TestEventListener(expectedEventId); var hostingEventSource = GetHostingEventSource(); eventListener.EnableEvents(hostingEventSource, EventLevel.Informational); // Act hostingEventSource.HostStart(); // Assert var eventData = eventListener.EventData; Assert.NotNull(eventData); Assert.Equal(expectedEventId, eventData.EventId); Assert.Equal("HostStart", eventData.EventName); Assert.Equal(EventLevel.Informational, eventData.Level); Assert.Same(hostingEventSource, eventData.EventSource); Assert.Null(eventData.Message); Assert.Empty(eventData.Payload); } [Fact] public void HostStop() { // Arrange var expectedEventId = 2; var eventListener = new TestEventListener(expectedEventId); var hostingEventSource = GetHostingEventSource(); eventListener.EnableEvents(hostingEventSource, EventLevel.Informational); // Act hostingEventSource.HostStop(); // Assert var eventData = eventListener.EventData; Assert.NotNull(eventData); Assert.Equal(expectedEventId, eventData.EventId); Assert.Equal("HostStop", eventData.EventName); Assert.Equal(EventLevel.Informational, eventData.Level); Assert.Same(hostingEventSource, eventData.EventSource); Assert.Null(eventData.Message); Assert.Empty(eventData.Payload); } public static TheoryData<DefaultHttpContext, string[]> RequestStartData { get { var variations = new TheoryData<DefaultHttpContext, string[]>(); var context = new DefaultHttpContext(); context.Request.Method = "GET"; context.Request.Path = "/Home/Index"; variations.Add( context, new string[] { "GET", "/Home/Index" }); context = new DefaultHttpContext(); context.Request.Method = "POST"; context.Request.Path = "/"; variations.Add( context, new string[] { "POST", "/" }); return variations; } } [Theory] [MemberData(nameof(RequestStartData))] public void RequestStart(DefaultHttpContext httpContext, string[] expected) { // Arrange var expectedEventId = 3; var eventListener = new TestEventListener(expectedEventId); var hostingEventSource = GetHostingEventSource(); eventListener.EnableEvents(hostingEventSource, EventLevel.Informational); // Act hostingEventSource.RequestStart(httpContext.Request.Method, httpContext.Request.Path); // Assert var eventData = eventListener.EventData; Assert.NotNull(eventData); Assert.Equal(expectedEventId, eventData.EventId); Assert.Equal("RequestStart", eventData.EventName); Assert.Equal(EventLevel.Informational, eventData.Level); Assert.Same(hostingEventSource, eventData.EventSource); Assert.Null(eventData.Message); var payloadList = eventData.Payload; Assert.Equal(expected.Length, payloadList.Count); for (var i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], payloadList[i]); } } [Fact] public void RequestStop() { // Arrange var expectedEventId = 4; var eventListener = new TestEventListener(expectedEventId); var hostingEventSource = GetHostingEventSource(); eventListener.EnableEvents(hostingEventSource, EventLevel.Informational); // Act hostingEventSource.RequestStop(); // Assert var eventData = eventListener.EventData; Assert.Equal(expectedEventId, eventData.EventId); Assert.Equal("RequestStop", eventData.EventName); Assert.Equal(EventLevel.Informational, eventData.Level); Assert.Same(hostingEventSource, eventData.EventSource); Assert.Null(eventData.Message); Assert.Empty(eventData.Payload); } [Fact] public void UnhandledException() { // Arrange var expectedEventId = 5; var eventListener = new TestEventListener(expectedEventId); var hostingEventSource = GetHostingEventSource(); eventListener.EnableEvents(hostingEventSource, EventLevel.Informational); // Act hostingEventSource.UnhandledException(); // Assert var eventData = eventListener.EventData; Assert.Equal(expectedEventId, eventData.EventId); Assert.Equal("UnhandledException", eventData.EventName); Assert.Equal(EventLevel.Error, eventData.Level); Assert.Same(hostingEventSource, eventData.EventSource); Assert.Null(eventData.Message); Assert.Empty(eventData.Payload); } [Fact] public async Task VerifyCountersFireWithCorrectValues() { // Arrange var hostingEventSource = GetHostingEventSource(); // requests-per-second isn't tested because the value can't be reliably tested because of time using var eventListener = new TestCounterListener(LoggerFactory, hostingEventSource.Name, [ "total-requests", "current-requests", "failed-requests" ]); using var timeoutTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(30)); timeoutTokenSource.Token.Register(() => Logger.LogError("Timeout while waiting for counter value.")); var totalRequestValues = eventListener.GetCounterValues("total-requests", timeoutTokenSource.Token); var currentRequestValues = eventListener.GetCounterValues("current-requests", timeoutTokenSource.Token); var failedRequestValues = eventListener.GetCounterValues("failed-requests", timeoutTokenSource.Token); eventListener.EnableEvents(hostingEventSource, EventLevel.Informational, EventKeywords.None, new Dictionary<string, string> { { "EventCounterIntervalSec", "1" } }); // Act & Assert Logger.LogInformation(nameof(HostingEventSource.RequestStart)); hostingEventSource.RequestStart("GET", "/"); await WaitForCounterValue(totalRequestValues, expectedValue: 1, Logger); await WaitForCounterValue(currentRequestValues, expectedValue: 1, Logger); await WaitForCounterValue(failedRequestValues, expectedValue: 0, Logger); Logger.LogInformation(nameof(HostingEventSource.RequestStop)); hostingEventSource.RequestStop(); await WaitForCounterValue(totalRequestValues, expectedValue: 1, Logger); await WaitForCounterValue(currentRequestValues, expectedValue: 0, Logger); await WaitForCounterValue(failedRequestValues, expectedValue: 0, Logger); Logger.LogInformation(nameof(HostingEventSource.RequestStart)); hostingEventSource.RequestStart("POST", "/"); await WaitForCounterValue(totalRequestValues, expectedValue: 2, Logger); await WaitForCounterValue(currentRequestValues, expectedValue: 1, Logger); await WaitForCounterValue(failedRequestValues, expectedValue: 0, Logger); Logger.LogInformation(nameof(HostingEventSource.RequestFailed)); hostingEventSource.RequestFailed(); Logger.LogInformation(nameof(HostingEventSource.RequestStop)); hostingEventSource.RequestStop(); await WaitForCounterValue(totalRequestValues, expectedValue: 2, Logger); await WaitForCounterValue(currentRequestValues, expectedValue: 0, Logger); await WaitForCounterValue(failedRequestValues, expectedValue: 1, Logger); } private static async Task WaitForCounterValue(CounterValues values, double expectedValue, ILogger logger) { await values.Values.WaitForValueAsync(expectedValue, values.CounterName, logger); } private static HostingEventSource GetHostingEventSource() { return new HostingEventSource(Guid.NewGuid().ToString()); } }
HostingEventSourceTests
csharp
protobuf-net__protobuf-net
assorted/MetroDto/MyDtos.cs
{ "start": 478, "end": 569 }
class ____ : Attribute { public TagAttribute(int i) { } }
TagAttribute
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/AsyncTaskTests.cs
{ "start": 7559, "end": 9667 }
public class ____ : IService { public object Any(GetFactorialSync request) { return new GetFactorialResponse { Result = GetFactorial(request.ForNumber) }; } public Task<GetFactorialResponse> Any(GetFactorialGenericAsync request) { return Task.Factory.StartNew(() => { return new GetFactorialResponse { Result = GetFactorial(request.ForNumber) }; }); } public object Any(GetFactorialObjectAsync request) { return Task.Factory.StartNew(() => { return new GetFactorialResponse { Result = GetFactorial(request.ForNumber) }; }); } public async Task<GetFactorialResponse> Any(GetFactorialAwaitAsync request) { return await Task.Factory.StartNew(() => { return new GetFactorialResponse { Result = GetFactorial(request.ForNumber) }; }); } public async Task<GetFactorialResponse> Any(GetFactorialDelayAsync request) { await Task.Delay(1000); return await Task.Factory.StartNew(() => { return new GetFactorialResponse { Result = GetFactorial(request.ForNumber) }; }); } public Task<GetFactorialResponse> Any(GetFactorialNewTaskAsync request) { return new Task<GetFactorialResponse>(() => new GetFactorialResponse { Result = GetFactorial(request.ForNumber) }); } public Task<GetFactorialResponse> Any(GetFactorialNewTcsAsync request) { return new GetFactorialResponse { Result = GetFactorial(request.ForNumber) }.AsTaskResult(); } public async Task<GetFactorialResponse> Any(ThrowErrorAwaitAsync request) { await Task.Delay(0); throw new HttpError(HttpStatusCode.Forbidden, HttpStatusCode.Forbidden.ToString(), request.Message ?? "Request is forbidden"); } public async Task Any(VoidAsync request) { await Task.Delay(1); } public static long GetFactorial(long n) { return n > 1 ? n * GetFactorial(n - 1) : 1; } } [Ignore("Load Test"), TestFixture]
GetFactorialAsyncService
csharp
dotnet__aspnetcore
src/Servers/HttpSys/test/FunctionalTests/Listener/RequestTests.cs
{ "start": 285, "end": 8519 }
public class ____ { [ConditionalTheory] [InlineData("/path%")] [InlineData("/path%XY")] [InlineData("/path%F")] [InlineData("/path with spaces")] public async Task Request_MalformedPathReturns400StatusCode(string requestPath) { string root; using (var server = Utilities.CreateHttpServerReturnRoot("/", out root)) { var responseTask = SendSocketRequestAsync(root, requestPath); var contextTask = server.AcceptAsync(Utilities.DefaultTimeout); var response = await responseTask; var responseStatusCode = response.Substring(9); // Skip "HTTP/1.1 " Assert.Equal("400", responseStatusCode); } } [ConditionalFact] public async Task Request_OptionsStar_EmptyPath() { string root; using (var server = Utilities.CreateHttpServerReturnRoot("/", out root)) { var responseTask = SendSocketRequestAsync(root, "*", "OPTIONS"); var context = await server.AcceptAsync(Utilities.DefaultTimeout).Before(responseTask); Assert.Equal("", context.Request.PathBase); Assert.Equal("", context.Request.Path); Assert.Equal("*", context.Request.RawUrl); context.Dispose(); } } [ConditionalTheory] [InlineData("%D0%A4", "Ф")] [InlineData("%d0%a4", "Ф")] [InlineData("%E0%A4%AD", "भ")] [InlineData("%e0%A4%Ad", "भ")] [InlineData("%F0%A4%AD%A2", "𤭢")] [InlineData("%F0%a4%Ad%a2", "𤭢")] [InlineData("%48%65%6C%6C%6F%20%57%6F%72%6C%64", "Hello World")] [InlineData("%48%65%6C%6C%6F%2D%C2%B5%40%C3%9F%C3%B6%C3%A4%C3%BC%C3%A0%C3%A1", "Hello-µ@ßöäüàá")] // Test the borderline cases of overlong UTF8. [InlineData("%C2%80", "\u0080")] [InlineData("%E0%A0%80", "\u0800")] [InlineData("%F0%90%80%80", "\U00010000")] [InlineData("%63", "c")] [InlineData("%32", "2")] [InlineData("%20", " ")] // Internationalized [InlineData("%C3%84ra%20Benetton", "Ära Benetton")] [InlineData("%E6%88%91%E8%87%AA%E6%A8%AA%E5%88%80%E5%90%91%E5%A4%A9%E7%AC%91%E5%8E%BB%E7%95%99%E8%82%9D%E8%83%86%E4%B8%A4%E6%98%86%E4%BB%91", "我自横刀向天笑去留肝胆两昆仑")] // Skip forward slash [InlineData("%2F", "%2F")] [InlineData("foo%2Fbar", "foo%2Fbar")] [InlineData("foo%2F%20bar", "foo%2F bar")] public async Task Request_PathDecodingValidUTF8(string requestPath, string expect) { string root; string actualPath; using (var server = Utilities.CreateHttpServerReturnRoot("/", out root)) { var responseTask = SendSocketRequestAsync(root, "/" + requestPath); var context = await server.AcceptAsync(Utilities.DefaultTimeout).Before(responseTask); actualPath = context.Request.Path; context.Dispose(); var response = await responseTask; Assert.Equal("200", response.Substring(9)); } Assert.Equal(expect, actualPath.TrimStart('/')); } [ConditionalTheory] [InlineData("/%%32")] [InlineData("/%%20")] [InlineData("/%F0%8F%8F%BF")] [InlineData("/%")] [InlineData("/%%")] [InlineData("/%A")] [InlineData("/%Y")] public async Task Request_PathDecodingInvalidUTF8(string requestPath) { string root; using (var server = Utilities.CreateHttpServerReturnRoot("/", out root)) { var responseTask = SendSocketRequestAsync(root, requestPath); var contextTask = server.AcceptAsync(Utilities.DefaultTimeout); var response = await responseTask; Assert.Equal("400", response.Substring(9)); } } [ConditionalTheory] // Overlong ASCII [InlineData("/%C0%A4", "/%C0%A4")] [InlineData("/%C1%BF", "/%C1%BF")] [InlineData("/%E0%80%AF", "/%E0%80%AF")] [InlineData("/%E0%9F%BF", "/%E0%9F%BF")] [InlineData("/%F0%80%80%AF", "/%F0%80%80%AF")] [InlineData("/%F0%80%BF%BF", "/%F0%80%BF%BF")] // Mixed [InlineData("/%C0%A4%32", "/%C0%A42")] [InlineData("/%32%C0%A4%32", "/2%C0%A42")] [InlineData("/%C0%32%A4", "/%C02%A4")] public async Task Request_OverlongUTF8Path(string requestPath, string expectedPath) { string root; using (var server = Utilities.CreateHttpServerReturnRoot("/", out root)) { var responseTask = SendSocketRequestAsync(root, requestPath); var context = await server.AcceptAsync(Utilities.DefaultTimeout).Before(responseTask); Assert.Equal(expectedPath, context.Request.Path); context.Dispose(); var response = await responseTask; Assert.Equal("200", response.Substring(9)); } } [ConditionalTheory] [InlineData("/", "/", "", "/")] [InlineData("/base", "/base", "/base", "")] [InlineData("/base", "/baSe", "/baSe", "")] [InlineData("/base", "/baSe/", "/baSe", "/")] [InlineData("/base", "/base/path", "/base", "/path")] [InlineData("/base", "///base/path1/path2", "///base", "/path1/path2")] [InlineData("/base/ball", @"/baSe\ball//path1//path2", @"/baSe\ball", "//path1//path2")] [InlineData("/base/ball", @"/base%2fball//path1//path2", @"/base%2fball", "//path1//path2")] [InlineData("/base/ball", @"/base%2Fball//path1//path2", @"/base%2Fball", "//path1//path2")] [InlineData("/base/ball", @"/base%5cball//path1//path2", @"/base\ball", "//path1//path2")] [InlineData("/base/ball", @"/base%5Cball//path1//path2", @"/base\ball", "//path1//path2")] [InlineData("/base/ball", "///baSe//ball//path1//path2", "///baSe//ball", "//path1//path2")] [InlineData("/base/ball", @"/base/\ball//path1//path2", @"/base/\ball", "//path1//path2")] [InlineData("/base/ball", @"/base/%2fball//path1//path2", @"/base/%2fball", "//path1//path2")] [InlineData("/base/ball", @"/base/%2Fball//path1//path2", @"/base/%2Fball", "//path1//path2")] [InlineData("/base/ball", @"/base/%5cball//path1//path2", @"/base/\ball", "//path1//path2")] [InlineData("/base/ball", @"/base/%5Cball//path1//path2", @"/base/\ball", "//path1//path2")] [InlineData("/base/ball", @"/base/call/../ball//path1//path2", @"/base/ball", "//path1//path2")] // The results should be "/base/ball", "//path1//path2", but Http.Sys collapses the "//" before the "../" // and we don't have a good way of emulating that. [InlineData("/base/ball", @"/base/call//../ball//path1//path2", @"", "/base/call/ball//path1//path2")] [InlineData("/base/ball", @"/base/call/.%2e/ball//path1//path2", @"/base/ball", "//path1//path2")] [InlineData("/base/ball", @"/base/call/.%2E/ball//path1//path2", @"/base/ball", "//path1//path2")] public async Task Request_WithPathBase(string pathBase, string requestPath, string expectedPathBase, string expectedPath) { using var server = Utilities.CreateHttpServerReturnRoot(pathBase, out var root); var responseTask = SendSocketRequestAsync(root, requestPath); var context = await server.AcceptAsync(Utilities.DefaultTimeout).Before(responseTask); Assert.Equal(expectedPathBase, context.Request.PathBase); Assert.Equal(expectedPath, context.Request.Path); context.Dispose(); var response = await responseTask; Assert.Equal("200", response.Substring(9)); } private async Task<string> SendSocketRequestAsync(string address, string path, string method = "GET") { var uri = new Uri(address); StringBuilder builder = new StringBuilder(); builder.AppendLine(FormattableString.Invariant($"{method} {path} HTTP/1.1")); builder.AppendLine("Connection: close"); builder.Append("HOST: "); builder.AppendLine(uri.Authority); builder.AppendLine(); byte[] request = Encoding.ASCII.GetBytes(builder.ToString()); using (var socket = new Socket(SocketType.Stream, ProtocolType.Tcp)) { socket.Connect(uri.Host, uri.Port); socket.Send(request); var response = new byte[12]; await Task.Run(() => socket.Receive(response)); return Encoding.ASCII.GetString(response); } } }
RequestTests
csharp
ChilliCream__graphql-platform
src/HotChocolate/MongoDb/src/Types/MongoDbScalarNames.cs
{ "start": 144, "end": 506 }
public static class ____ { /// <summary> /// The name of the ObjectId scalar type. /// sequences. /// </summary> public static readonly string ObjectId = nameof(ObjectId); /// <summary> /// The name of the Bson scalar type. /// sequences. /// </summary> public static readonly string Bson = nameof(Bson); }
MongoDbScalarNames
csharp
nopSolutions__nopCommerce
src/Presentation/Nop.Web.Framework/Mvc/Routing/RoutePublisher.cs
{ "start": 189, "end": 1433 }
public partial class ____ : IRoutePublisher { #region Fields /// <summary> /// Type finder /// </summary> protected readonly ITypeFinder _typeFinder; #endregion #region Ctor /// <summary> /// Ctor /// </summary> /// <param name="typeFinder">Type finder</param> public RoutePublisher(ITypeFinder typeFinder) { _typeFinder = typeFinder; } #endregion #region Methods /// <summary> /// Register routes /// </summary> /// <param name="endpointRouteBuilder">Route builder</param> public virtual void RegisterRoutes(IEndpointRouteBuilder endpointRouteBuilder) { //find route providers provided by other assemblies var routeProviders = _typeFinder.FindClassesOfType<IRouteProvider>(); //create and sort instances of route providers var instances = routeProviders .Select(routeProvider => (IRouteProvider)Activator.CreateInstance(routeProvider)) .OrderByDescending(routeProvider => routeProvider.Priority); //register all provided routes foreach (var routeProvider in instances) routeProvider.RegisterRoutes(endpointRouteBuilder); } #endregion }
RoutePublisher
csharp
dotnet__maui
src/Controls/tests/Core.UnitTests/BindingBaseUnitTests.cs
{ "start": 275, "end": 458 }
public abstract class ____ : BaseTestFixture { protected abstract BindingBase CreateBinding(BindingMode mode = BindingMode.Default, string stringFormat = null);
BindingBaseUnitTests
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Driver.Tests/GridFS/GridFSChunkExceptionTests.cs
{ "start": 782, "end": 1981 }
public class ____ { [Fact] public void constructor_should_initialize_instance() { var result = new GridFSChunkException(123, 2, "missing"); result.Message.Should().Contain("file id 123"); result.Message.Should().Contain("chunk 2"); result.Message.Should().Contain("missing"); } [Fact] public void constructor_should_throw_when_id_is_null() { Action action = () => new GridFSChunkException(null, 2, "missing"); action.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be("id"); } [Fact] public void constructor_should_throw_when_n_is_negative() { Action action = () => new GridFSChunkException(123, -2, "missing"); action.ShouldThrow<ArgumentException>().And.ParamName.Should().Be("n"); } [Fact] public void constructor_should_throw_when_reason_is_null() { Action action = () => new GridFSChunkException(123, 2, null); action.ShouldThrow<ArgumentNullException>().And.ParamName.Should().Be("reason"); } } }
GridFSChunkExceptionTests
csharp
dotnet__orleans
test/Orleans.CodeGenerator.Tests/snapshots/OrleansSourceGeneratorTests.TestGrainMethodAnnotatedWithInvokableBaseType.verified.cs
{ "start": 15615, "end": 16136 }
internal sealed class ____ : global::Orleans.Serialization.Activators.IActivator<global::TestProject.HelloGrain> { public global::TestProject.HelloGrain Create() => new global::TestProject.HelloGrain(); } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("OrleansCodeGen", "10.0.0.0"), global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never), global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute]
Activator_HelloGrain
csharp
MassTransit__MassTransit
src/MassTransit/Initializers/PropertyInitializers/DictionaryCopyPropertyInitializer.cs
{ "start": 642, "end": 1443 }
class ____ TInput : class, IDictionary<string, TProperty> { readonly string _key; readonly IWriteProperty<TMessage, TProperty> _messageProperty; public DictionaryCopyPropertyInitializer(PropertyInfo propertyInfo, string key) { if (propertyInfo == null) throw new ArgumentNullException(nameof(propertyInfo)); _key = key; _messageProperty = WritePropertyCache<TMessage>.GetProperty<TProperty>(propertyInfo); } public Task Apply(InitializeContext<TMessage, TInput> context) { if (context.HasInput && context.Input.TryGetValue(_key, out var value)) _messageProperty.Set(context.Message, value); return Task.CompletedTask; } } }
where
csharp
dotnet__aspnetcore
src/Framework/AspNetCoreAnalyzers/test/RouteEmbeddedLanguage/RoutePatternClassifierTests.cs
{ "start": 709, "end": 1761 }
public class ____ { private readonly ITestOutputHelper _output; private TestDiagnosticAnalyzerRunner Runner { get; } = new(new RenderTreeBuilderAnalyzer()); protected async Task TestAsync( string code, params FormattedClassification[] expected) { MarkupTestFile.GetSpans(code, out var rewrittenCode, out ImmutableArray<TextSpan> spans); Assert.True(spans.Length == 1); var actual = await Runner.GetClassificationSpansAsync(spans.Single(), rewrittenCode); var actualOrdered = actual.OrderBy(t1 => t1.TextSpan.Start).ToList(); var actualFormatted = actualOrdered.Select(a => new FormattedClassification(rewrittenCode.Substring(a.TextSpan.Start, a.TextSpan.Length), a.ClassificationType)).ToArray(); Assert.Equal(expected, actualFormatted); } public RoutePatternClassifierTests(ITestOutputHelper output) { _output = output; } [Fact] public async Task CommentOnString_Classified() { await TestAsync( @"
RoutePatternClassifierTests
csharp
bchavez__Bogus
Source/Bogus.Tests/RandomizerTest.cs
{ "start": 415, "end": 14467 }
public enum ____ { ExcludeMe, A, B, C, D } [Fact] public void pick_an_enum() { var f = r.Enum<Foo>(); f.Should().Be(Foo.C); } [Fact] public void exclude_an_enum() { //seeded value of 14 gets "ExcludeMe", ensure exclude works. Randomizer.Seed = new Random(14); var f = r.Enum(exclude: Foo.ExcludeMe); f.ToString().Dump(); f.Should().NotBe(Foo.ExcludeMe); } [Fact] public void exclude_all_throws_an_error() { Action act = () => r.Enum(Foo.ExcludeMe, Foo.A, Foo.B, Foo.C, Foo.D); act.Should().Throw<ArgumentException>(); } [Fact] public void can_replace_numbers_or_letters_using_asterisk() { r.Replace("***") .Should().Be("CQ6"); } [Fact] public void can_get_random_word() { r.Word().Should().Be("Court"); r.Word().Should().Be("bluetooth"); r.Word().Should().Be("Movies & Clothing"); } [Fact] public void can_get_some_random_words() { r.Words().Should().Be("Soft deposit"); r.Words().Should().Be("Handcrafted Granite Gloves Directives"); r.Words().Should().Be("Corner Handcrafted Frozen Chair transmitting"); } [Fact] public void can_shuffle_some_enumerable() { new string(r.Shuffle("123456789").ToArray()) .Should().Be("628753491"); } [Fact] public void can_get_random_locale() { r.RandomLocale().Should().Be("ja"); } [Fact] public void can_include_int_maxvalue_number() { var max = r.Number(int.MaxValue, int.MaxValue); max.Should().Be(int.MaxValue); } [Fact] public void can_handle_full_int_range() { r.Number(int.MinValue, int.MaxValue); } [Fact] public void detects_invalid_Even_range() { Action act1 = () => r.Even(min: 1, max: 0); act1.Should().Throw<ArgumentException>() .Where( ex => ex.Message.StartsWith("The min/max range is invalid. The minimum value '1' is greater than the maximum value '0'.")); Action act2 = () => r.Even(min: int.MaxValue, max: int.MinValue); act2.Should().Throw<ArgumentException>() .Where( ex => ex.Message.StartsWith("The min/max range is invalid. The minimum value '2147483647' is greater than the maximum value '-2147483648'.")); } [Fact] public void detects_empty_Even_range() { Action act1 = () => r.Even(min: 1, max: 1); act1.Should().Throw<ArgumentException>() .Where(ex => ex.Message.StartsWith("The specified range does not contain any even numbers.")); Action act2 = () => r.Even(min: int.MaxValue, max: int.MaxValue); act2.Should().Throw<ArgumentException>() .Where(ex => ex.Message.StartsWith("The specified range does not contain any even numbers.")); Action act3 = () => r.Even(min: int.MinValue + 1, max: int.MinValue + 1); act3.Should().Throw<ArgumentException>() .Where(ex => ex.Message.StartsWith("The specified range does not contain any even numbers.")); } [Fact] public void can_handle_extreme_Even_range() { r.Even(min: int.MinValue, max: int.MinValue).Should().Be(int.MinValue); r.Even(min: int.MaxValue & ~1, max: int.MaxValue & ~1).Should().Be(int.MaxValue & ~1); } [Fact] public void detects_invalid_Odd_range() { Action act1 = () => r.Odd(min: 1, max: 0); act1.Should().Throw<ArgumentException>() .Where(ex => ex.Message.StartsWith("The min/max range is invalid. The minimum value '1' is greater than the maximum value '0'.")); Action act2 = () => r.Odd(min: int.MaxValue, max: int.MinValue); act2.Should().Throw<ArgumentException>() .Where(ex => ex.Message.StartsWith("The min/max range is invalid. The minimum value '2147483647' is greater than the maximum value '-2147483648'.")); } [Fact] public void detects_empty_Odd_range() { Action act1 = () => r.Odd(min: 0, max: 0); act1.Should().Throw<ArgumentException>() .Where(ex => ex.Message.StartsWith("The specified range does not contain any odd numbers.")); Action act2 = () => r.Odd(min: int.MaxValue - 1, max: int.MaxValue - 1); act2.Should().Throw<ArgumentException>() .Where(ex => ex.Message.StartsWith("The specified range does not contain any odd numbers.")); Action act3 = () => r.Odd(min: int.MinValue, max: int.MinValue); act3.Should().Throw<ArgumentException>() .Where(ex => ex.Message.StartsWith("The specified range does not contain any odd numbers.")); } [Fact] public void can_handle_extreme_Odd_range() { r.Odd(min: int.MinValue | 1, max: int.MinValue | 1).Should().Be(int.MinValue | 1); r.Odd(min: int.MaxValue, max: int.MaxValue).Should().Be(int.MaxValue); } [Fact] public void random_bool() { r.Bool().Should().BeFalse(); } [Fact] public void can_get_some_alpha_chars() { r.AlphaNumeric(20).Should().Be("l3tn1m1ohax6ql31pw1u"); } [Fact] public void generate_double_with_min_and_max() { r.Double(2.5, 2.9).Should().BeInRange(2.74140891332244, 2.74140891332246); } [Fact] public void generate_decimal_with_min_and_max() { r.Decimal(2.2m, 5.2m).Should().Be(4.0105668499183690m); } [Fact] public void generate_float_with_min_and_max() { r.Float(2.7f, 3.9f).Should().BeInRange(3.424226f, 3.424228f); } [Fact] public void generate_byte() { r.Byte(1, 128).Should().Be(78); } [Fact] public void generate_some_bytes() { r.Bytes(20).Should() .Equal(218, 35, 156, 76, 224, 196, 45, 215, 227, 196, 168, 150, 23, 242, 85, 178, 101, 200, 89, 189); } [Fact] public void generate__sbyte() { r.SByte(max: 0).Should().Be(-51); } [Fact] public void generate_uint32() { r.UInt(99, 200).Should().Be(160); } [Fact] public void generate_unit32_many() { r.UInt().Should().Be(2592108469u); r.UInt().Should().Be(471320134u); r.UInt().Should().Be(3498684729u); r.UInt().Should().Be(2775978649u); } [Fact] public void generate_int32() { r.Int(max: 0).Should().Be(-425714706); } [Fact] public void generate_int32_many() { r.Int().Should().Be(1077349347); r.Int().Should().Be(1155054345); r.Int().Should().Be(-1904480771); r.Int().Should().Be(2101046113); r.Int().Should().Be(1223601157); r.Int().Should().Be(-594397672); } [Fact] public void generate_uint64() { r.ULong(99, 9999).Should().Be(6074); } [Fact] public void generate_uint64_many() { r.ULong().Should().Be(11133021102928879616UL); r.ULong().Should().Be(2024304562418978048UL); r.ULong().Should().Be(15026736492772024320UL); r.ULong().Should().Be(11922737513106253824UL); } [Fact] public void generate_int64() { r.Long(max: 0).Should().Be(-3656861485390335055L); } [Fact] public void generate_int64_many() { r.Long().Should().Be(1909649066074105698L); r.Long().Should().Be(-7199067474435792608L); r.Long().Should().Be(5803364455917250112L); r.Long().Should().Be(2699365476251477286L); r.Long().Should().Be(-8566699986853958425L); } [Fact] public void generate_int16() { r.Short(max: 0).Should().Be(-12992); } [Fact] public void generate_int16_many() { r.Short().Should().Be(6784); r.Short().Should().Be(-25576); r.Short().Should().Be(20617); r.Short().Should().Be(9589); } [Fact] public void generate_uint16() { r.UShort().Should().Be(39552); } [Fact] public void generate_char() { r.Char().Should().Be('\u9a80'); } [Fact] public void generate_some_chars() { r.Chars(count: 10).Should().Equal( '\u9a80', '\u1c17', '\ud089', '\ua576', '\u091c', '\u9fdb', '\u0cfa', '\ub0d6', '\u7a91', '\u4d58'); } [Fact] public void generate_string_range_check() { r.String() .Length.Should() .BeGreaterOrEqualTo(40) .And .BeLessOrEqualTo(80); } [Fact] public void generate_string_byte_check() { var x = r.String(3); x.Length.Should().Be(3); var rawBytes = new byte[] { 233, 170, 128, 225, 176, 151, 237, 130, 137 }; Encoding.UTF8.GetBytes(x) .Should().Equal(rawBytes); } [Fact] public void generate_string_AZ() { r.String(minChar: 'A', maxChar: 'Z') .Should().Be("CVQAQBRMHYESPCASXAVVIPPCRZKFPOFICRUEYZGQKYXUWMHOBLCFHCHMFOJRRMXT"); } [Fact] public void generate_string2_pool() { r.String2(5).Should().Be("pcvqa"); } [Fact] public void generate_string2_pool_custom() { r.String2(5, "abc").Should().Be("bacba"); } [Fact] public void generate_string2_pool_min_max() { var x = r.String2(5, 10, "xyz"); x.Length.Should() .BeGreaterOrEqualTo(5) .And .BeLessOrEqualTo(10); x.Should().Be("xzyxyxzy"); } [Fact] public void generate_hash() { r.Hash().Should().Be("91da090b74f2b910be0dd5991af6398351ac2ef3"); } [Fact] public void generate_small_hash() { r.Hash(20).Should().Be("91da090b74f2b910be0d"); } [Fact] public void random_word_tests() { //r.Words(3).Should().Be(""); //r.Words(5).Split(' ').Length.Should().Be(4); r.WordsArray(5).Length.Should().Be(5); r.WordsArray(1, 80).Length.Should().BeInRange(1, 80); //.Should().BeInRange(1, 80); r.WordsArray(10, 20).Length.Should().BeInRange(10, 20); } [Fact] public void can_pick_random_item_from_ICollection() { var x = new List<int> {1, 2, 3} as ICollection<int>; r.CollectionItem(x).Should().BeOneOf(1, 2, 3); } [Fact] public void throw_an_exception_when_picking_nothing_from_collection() { var x = new List<int>() as ICollection<int>; Action act = () => r.CollectionItem(x); act.Should().Throw<ArgumentException>(); } [Fact] public void can_pick_random_item_from_ilist() { var x = new List<int> {1, 2, 3} as IList<int>; r.ListItem(x).Should().BeOneOf(1, 2, 3); } [Fact] public void can_pick_random_item_from_list() { var x = new List<int> {1, 2, 3}; r.ListItem(x).Should().BeOneOf(1, 2, 3); } [Fact] public void can_generate_hexdec_string() { r.Hexadecimal().Should().StartWith("0x").And.Be("0x9"); r.Hexadecimal(20).Should().Be("0x1da090b74f2b910be0dd"); r.Hexadecimal(prefix: "").Should().Be("5"); } [Fact] public void can_get_random_subset_of_an_array() { var a = new[] {"a", "b", "c"}; r.ArrayElements(a).Should().Equal("a"); r.ArrayElements(a, 2).Should().Equal("c", "a"); } [Fact] public void can_get_random_subset_of_a_list() { var a = new List<string> {"a", "b", "c"}; r.ListItems(a).Should().Equal("a"); r.ListItems(a, 2).Should().Equal("c", "a"); } [Fact] public void can_get_a_weighted_true_value() { var bools = Enumerable.Range(1, 100).Select(i => r.Bool(0.20f)); var truths = bools.Count(b => b) / 100f; truths.Should().BeLessThan(0.25f); // roughly } public static IEnumerable<object[]> ExactLenUtf16(int maxTest) { return Enumerable.Range(1, maxTest) .Select(i => new object[] {i, i}); } public static IEnumerable<object[]> VarLenUtf16(int maxTest) { return Enumerable.Range(1, maxTest) .Select(i => new object[] { i, i+20 }); } [Theory] [MemberData(nameof(ExactLenUtf16), parameters: 100)] [MemberData(nameof(VarLenUtf16), parameters: 100)] public void can_generate_valid_utf16_string_with_surrogates(int min, int max) { var x = r.Utf16String(min, max); x.Length.Should().BeGreaterOrEqualTo(min) .And .BeLessOrEqualTo(max); for( int i = 0; i < x.Length; i++ ) { var current = x[i]; if( char.IsSurrogate(current) ) { char.IsLetterOrDigit(x, i).Should().BeTrue(); i++; } else { char.IsLetterOrDigit(current).Should().BeTrue(); } } } [Theory] [MemberData(nameof(ExactLenUtf16), parameters: 100)] [MemberData(nameof(VarLenUtf16), parameters: 100)] public void can_generate_valid_utf16_without_surrogates(int min, int max) { var x = r.Utf16String(min, max, excludeSurrogates: true); x.Length.Should().BeGreaterOrEqualTo(min) .And .BeLessOrEqualTo(max); x.Any(char.IsSurrogate).Should().BeFalse(); x.All(char.IsLetterOrDigit).Should().BeTrue(); } [Fact] public void static_utf16_tests() { r.Utf16String().Should().Be("𦊕𡰴ဩਢۥ侀ゞᜡﷴ𠸮𝒾ⶱﹱຂⱪ𝒟𝚪𝒩𝝵ೡཧΐ뢫ⱜੳ𣽇𐨖ਆ𐀼ฏളᄎ𐏈𦵻𐠸𝕋ꡨ𝔇ずరᢔﬣ𐨟𝔚ઐష"); r.Utf16String().Should().Be("னమወ𡂑ப𐠁ஞ𦂰ઐ𢂍ᬒ𒀓𨴽𝜅𧊆𦑆ආ𝜂ଭ𐀪ಋΊ౦౨ㆳꠁⶺ𝛈𡓎𡯸ᜑ𐁁𝜹લ𩠺ଐ𦕲ﬔჁⶂム𝐾𣭄ງヾ༤𝒪ᙵͼ၅𦛃𩕾ﷸ𝜦ⱶ"); } [Fact] public void empty_collection_throws_better_exception_message_rather_than_index_out_of_bounds() { var x = new int[] { }; Action arrayAction = () => r.ArrayElement(x); arrayAction.Should().Throw<ArgumentException>() .Where(ex => ex.Message.StartsWith("The array is empty. There are no items to select.")); Action listAction = () => r.ListItem(x); listAction.Should().Throw<ArgumentException>() .Where(ex => ex.Message.StartsWith("The list is empty. There are no items to select.")); Action collectionAction = () => r.CollectionItem(x); collectionAction.Should().Throw<ArgumentException>() .Where(ex => ex.Message.StartsWith("The collection is empty. There are no items to select.")); } }
Foo
csharp
dotnet__maui
src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue22715.cs
{ "start": 362, "end": 804 }
public class ____ : _IssuesUITest { public Issue22715(TestDevice device) : base(device) { } public override string Issue => "Page should not scroll when focusing element above keyboard"; [Test] [Category(UITestCategories.Entry)] public void PageShouldNotScroll () { App.WaitForElement("EntNumber").GetRect(); App.WaitForElement("TopLabel").GetRect(); VerifyScreenshot(); } } #endif
Issue22715
csharp
graphql-dotnet__graphql-dotnet
src/GraphQL.Tests/Bugs/Issue1004.cs
{ "start": 1300, "end": 1559 }
public class ____ : InterfaceGraphType { public Issue1004Interface() { Field<StringGraphType>("field1").Description("Very important field1"); Field<StringGraphType>("field2").Description("Very important field2"); } }
Issue1004Interface
csharp
microsoft__garnet
test/Garnet.test.cluster/RedirectTests/BaseCommand.cs
{ "start": 35951, "end": 36943 }
internal class ____ : BaseCommand { public override bool IsArrayCommand => true; public override bool ArrayResponse => false; public override string Command => nameof(SMOVE); public override string[] GetSingleSlotRequest() { var ssk = GetSingleSlotKeys; return [ssk[0], ssk[1], "a"]; } public override string[] GetCrossSlotRequest() { var csk = GetCrossSlotKeys; return [csk[0], csk[1], "a"]; } public override ArraySegment<string>[] SetupSingleSlotRequest() { var ssk = GetSingleSlotKeys; var setup = new ArraySegment<string>[3]; setup[0] = new ArraySegment<string>(["SADD", ssk[1], "a", "b", "c"]); setup[1] = new ArraySegment<string>(["SADD", ssk[2], "d", "e", "f"]); setup[2] = new ArraySegment<string>(["SADD", ssk[3], "g", "h", "i"]); return setup; } }
SMOVE
csharp
Cysharp__UniTask
src/UniTask/Assets/Plugins/UniTask/Runtime/Triggers/MonoBehaviourMessagesTriggers.cs
{ "start": 64257, "end": 64762 }
partial class ____ { public static AsyncMouseUpAsButtonTrigger GetAsyncMouseUpAsButtonTrigger(this GameObject gameObject) { return GetOrAddComponent<AsyncMouseUpAsButtonTrigger>(gameObject); } public static AsyncMouseUpAsButtonTrigger GetAsyncMouseUpAsButtonTrigger(this Component component) { return component.gameObject.GetAsyncMouseUpAsButtonTrigger(); } } [DisallowMultipleComponent]
AsyncTriggerExtensions
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/test/Execution.Tests/Integration/TypeConverter/TypeConverterTests.ExceptionPropagation.cs
{ "start": 222, "end": 10108 }
public record ____([StringSyntax("graphql")] string QueryString, string DisplayName) { public override string ToString() => DisplayName; } public static readonly TheoryData<TestCase> TestCases = [ new("""{ fieldWithScalarInput(arg: "foo") }""", "ScalarInput"), new("""{ fieldWithNonNullScalarInput(arg: "foo") }""", "NonNullScalarInput"), new("""{ fieldWithObjectInput(arg: { id: "foo" }) }""", "ObjectInput"), new("""{ fieldWithNestedObjectInput(arg: { inner: { id: "foo" } }) }""", "NestedObjectInput"), new("""{ fieldWithListOfScalarsInput(arg: ["foo"]) }""", "ListOfScalarsInput"), new("""{ fieldWithListOfScalarsInput(arg: ["ok", "foo"]) }""", "ListOfScalarsInputWithOkValue"), new("""{ fieldWithObjectWithListOfScalarsInput(arg: { ids: ["foo"] }) }""", "ObjectWithListOfScalarsInput"), new("""{ fieldWithListOfObjectsInput(arg: { items: [{ id: "foo" }] }) }""", "ListOfObjectsInput"), new("""query($v: String!) { fieldWithScalarInput(arg: $v) }""", "VariableInput"), new("""query($v: String!) { fieldWithNestedObjectInput(arg: { inner: { id: $v } }) }""", "NestedVariableInput"), new("""{ echo(arg: "foo") @boom(arg: "foo") }""", "DirectiveInput"), new("""{ nestedObjectOutput { inner { id @boom(arg: "foo") } } }""", "NestedDirectiveInput") ]; public static readonly TheoryData<TestCase> TestCasesForMutationConventions = [ new("""mutation{ fieldWithScalarInput(input: { arg: "foo" }) { string } }""", "ScalarInput"), new("""mutation{ fieldWithNonNullScalarInput(input: { arg: "foo" }) { string } }""", "NonNullScalarInput"), new("""mutation{ fieldWithObjectInput(input: { arg: { id: "foo" } }) { string } }""", "ObjectInput"), new("""mutation{ fieldWithNestedObjectInput(input: { arg: { inner: { id: "foo" } } }) { string } }""", "NestedObjectInput"), new("""mutation{ fieldWithListOfScalarsInput(input: { arg: ["foo"] }) { string } }""", "ListOfScalarsInput"), new("""mutation{ fieldWithListOfScalarsInput(input: { arg: ["ok", "foo"] }) { string } }""", "ListOfScalarsInputWithOkValue"), new("""mutation{ fieldWithObjectWithListOfScalarsInput(input: { arg: { ids: ["foo"] } }) { string } }""", "ObjectWithListOfScalarsInput"), new("""mutation{ fieldWithListOfObjectsInput(input: { arg: { items: [{ id: "foo" }] } }) { string } }""", "ListOfObjectsInput"), new("""mutation($v: String!) { fieldWithScalarInput(input: { arg: $v }) { string } }""", "VariableInput"), new("""mutation($v: String!) { fieldWithNestedObjectInput(input: { arg: { inner: { id: $v } } }) { string } }""", "NestedVariableInput"), new("""mutation{ echo(input: { arg: "foo"}) @boom(arg: "foo") { string } }""", "DirectiveInput"), new("""mutation { nestedObjectOutput { nestedObject { inner { id @boom(arg: "foo") } } } }""", "NestedDirectiveInput") ]; public static readonly TheoryData<TestCase> TestCasesForQueryConventions = [ new("""{ fieldWithScalarInput(arg: "foo") { ... on ObjectWithId { id } } }""", "ScalarInput"), new("""{ fieldWithNonNullScalarInput(arg: "foo") { ... on ObjectWithId { id } } }""", "NonNullScalarInput"), new("""{ fieldWithObjectInput(arg: { id: "foo" }) { ... on ObjectWithId { id } } }""", "ObjectInput"), new("""{ fieldWithNestedObjectInput(arg: { inner: { id: "foo" } }) { ... on ObjectWithId { id } } }""", "NestedObjectInput"), new("""{ fieldWithListOfScalarsInput(arg: ["foo"]) { ... on ObjectWithId { id } } }""", "ListOfScalarsInput"), new("""{ fieldWithListOfObjectsInput(arg: { items: [{ id: "foo" }] }) { ... on ObjectWithId { id } } }""", "ListOfObjectsInput"), new("""{ fieldWithObjectWithListOfScalarsInput(arg: { ids: ["foo"] }) { ... on ObjectWithId { id } } }""", "ObjectWithListOfScalarsInput"), new("""query($v: String!) { fieldWithScalarInput(arg: $v) { ... on ObjectWithId { id } } }""", "VariableInput"), new("""{ echo(arg: "foo") @boom(arg: "foo") { ... on ObjectWithId { id } } }""", "DirectiveInput"), new("""{ nestedObjectOutput { ... on NestedObject { inner { id @boom(arg: "foo") } } } }""", "NestedDirectiveInput") ]; [Theory] [MemberData(nameof(TestCases))] public async Task Exception_IsAvailableInErrorFilter(TestCase testCase) { // arrange Exception? caughtException = null; var executor = await new ServiceCollection() .AddGraphQLServer() .AddQueryType<SomeQuery>() .AddDirectiveType<BoomDirectiveType>() .AddTypeConverter<string, BrokenType>(x => x == "ok" ? new BrokenType(1) : throw new CustomIdSerializationException("Boom")) .BindRuntimeType<BrokenType, StringType>() .ModifyRequestOptions(x => x.IncludeExceptionDetails = true) .AddErrorFilter(x => { caughtException = x.Exception; return x; }) .BuildRequestExecutorAsync(); // act var variableValues = testCase.DisplayName.Contains("VariableInput") ? new Dictionary<string, object?> { ["v"] = "foo" } : []; var result = await executor.ExecuteAsync(testCase.QueryString, variableValues: variableValues); // assert Assert.IsType<CustomIdSerializationException>(caughtException); result.MatchSnapshot(postFix: testCase.DisplayName); } [Theory] [MemberData(nameof(TestCases))] public async Task Exception_IsAvailableInErrorFilter_Mutation(TestCase testCase) { // arrange Exception? caughtException = null; var executor = await new ServiceCollection() .AddGraphQLServer() .AddMutationType<SomeQuery>() .AddDirectiveType<BoomDirectiveType>() .AddTypeConverter<string, BrokenType>(x => x == "ok" ? new BrokenType(1) : throw new CustomIdSerializationException("Boom")) .BindRuntimeType<BrokenType, StringType>() .ModifyRequestOptions(x => x.IncludeExceptionDetails = true) .ModifyOptions(x => x.StrictValidation = false) .AddErrorFilter(x => { caughtException = x.Exception; return x; }) .BuildRequestExecutorAsync(); // act var variableValues = testCase.DisplayName.Contains("VariableInput") ? new Dictionary<string, object?> { ["v"] = "foo" } : []; var mutation = $"mutation{testCase.QueryString.TrimStart("query")}"; var result = await executor.ExecuteAsync(mutation, variableValues: variableValues); // assert Assert.IsType<CustomIdSerializationException>(caughtException); result.MatchSnapshot(postFix: testCase.DisplayName); } [Theory] [MemberData(nameof(TestCasesForMutationConventions))] public async Task Exception_IsAvailableInErrorFilter_Mutation_WithMutationConventions(TestCase testCase) { // arrange Exception? caughtException = null; var executor = await new ServiceCollection() .AddGraphQLServer() .AddMutationType<SomeQuery>() .AddMutationConventions() .AddDirectiveType<BoomDirectiveType>() .AddTypeConverter<string, BrokenType>(_ => throw new CustomIdSerializationException("Boom")) .BindRuntimeType<BrokenType, StringType>() .ModifyRequestOptions(x => x.IncludeExceptionDetails = true) .ModifyOptions(x => x.StrictValidation = false) .AddErrorFilter(x => { caughtException = x.Exception; return x; }) .BuildRequestExecutorAsync(); // act var variableValues = testCase.DisplayName.Contains("VariableInput") ? new Dictionary<string, object?> { ["v"] = "foo" } : []; var result = await executor.ExecuteAsync(testCase.QueryString, variableValues: variableValues); // assert Assert.IsType<CustomIdSerializationException>(caughtException); result.MatchSnapshot(postFix: testCase.DisplayName); } [Theory] [MemberData(nameof(TestCasesForQueryConventions))] public async Task Exception_IsAvailableInErrorFilter_WithQueryConventions(TestCase testCase) { // arrange Exception? caughtException = null; var executor = await new ServiceCollection() .AddGraphQLServer() .AddQueryType<SomeQueryConventionFriendlyQueryType>() .AddQueryConventions() .AddDirectiveType<BoomDirectiveType>() .AddTypeConverter<string, BrokenType>(_ => throw new CustomIdSerializationException("Boom")) .BindRuntimeType<BrokenType, StringType>() .ModifyRequestOptions(x => x.IncludeExceptionDetails = true) .ModifyOptions(x => x.StrictValidation = false) .AddErrorFilter(x => { caughtException = x.Exception; return x; }) .BuildRequestExecutorAsync(); // act var variableValues = testCase.DisplayName.Contains("VariableInput") ? new Dictionary<string, object?> { ["v"] = "foo" } : []; var result = await executor.ExecuteAsync(testCase.QueryString, variableValues: variableValues); // assert Assert.IsType<CustomIdSerializationException>(caughtException); result.MatchSnapshot(postFix: testCase.DisplayName); }
TestCase
csharp
ChilliCream__graphql-platform
src/StrawberryShake/CodeGeneration/test/CodeGeneration.CSharp.Tests/Integration/StarWarsOnReviewSubGraphQLSSETest.Client.cs
{ "start": 28268, "end": 29457 }
public partial class ____ : global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsOnReviewSubGraphQLSSE.IStarWarsOnReviewSubGraphQLSSEClient { private readonly global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsOnReviewSubGraphQLSSE.IOnReviewSubSubscription _onReviewSub; public StarWarsOnReviewSubGraphQLSSEClient(global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsOnReviewSubGraphQLSSE.IOnReviewSubSubscription onReviewSub) { _onReviewSub = onReviewSub ?? throw new global::System.ArgumentNullException(nameof(onReviewSub)); } public static global::System.String ClientName => "StarWarsOnReviewSubGraphQLSSEClient"; public global::StrawberryShake.CodeGeneration.CSharp.Integration.StarWarsOnReviewSubGraphQLSSE.IOnReviewSubSubscription OnReviewSub => _onReviewSub; } // StrawberryShake.CodeGeneration.CSharp.Generators.ClientInterfaceGenerator /// <summary> /// Represents the StarWarsOnReviewSubGraphQLSSEClient GraphQL client /// </summary> [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "11.0.0")]
StarWarsOnReviewSubGraphQLSSEClient
csharp
dotnet__aspnetcore
src/Mvc/test/WebSites/RazorWebSite/Controllers/DataAnnotationController.cs
{ "start": 236, "end": 392 }
public class ____ : Controller { public IActionResult Enum() { return View(new EnumModel { Id = ModelEnum.FirstOption }); } }
EnumController
csharp
louthy__language-ext
LanguageExt.Core/Class Instances/Eq/EqLst.cs
{ "start": 346, "end": 1386 }
public struct ____<EQ, A> : Eq<Lst<A>> where EQ : Eq<A> { [Pure] public static bool Equals(Lst<A> x, Lst<A> y) { if (x.Count != y.Count) return false; using var enumx = x.GetEnumerator(); using var enumy = y.GetEnumerator(); var count = x.Count; for (var i = 0; i < count; i++) { enumx.MoveNext(); enumy.MoveNext(); if (!EQ.Equals(enumx.Current, enumy.Current)) return false; } return true; } /// <summary> /// Get hash code of the value /// </summary> /// <param name="x">Value to get the hash code of</param> /// <returns>The hash code of x</returns> [Pure] public static int GetHashCode(Lst<A> x) => HashableLst<EQ, A>.GetHashCode(x); } /// <summary> /// Equality test /// </summary> /// <param name="x">The left hand side of the equality operation</param> /// <param name="y">The right hand side of the equality operation</param> /// <returns>True if x and y are equal</returns>
EqLst
csharp
Tyrrrz__DiscordChatExporter
DiscordChatExporter.Core/Markdown/FormattingKind.cs
{ "start": 47, "end": 160 }
internal enum ____ { Bold, Italic, Underline, Strikethrough, Spoiler, Quote, }
FormattingKind
csharp
neuecc__MessagePack-CSharp
src/MessagePack/Resolvers/ResolverUtilities.cs
{ "start": 266, "end": 1737 }
internal static class ____ { internal static IMessagePackFormatter ActivateFormatter(Type formatterType, object?[]? args = null) { if (args == null || args.Length == 0) { if (formatterType.GetConstructor(Type.EmptyTypes) is ConstructorInfo ctor) { return (IMessagePackFormatter)ctor.Invoke(Array.Empty<object>()); } else if (FetchSingletonField(formatterType) is FieldInfo instance) { return (IMessagePackFormatter)(instance.GetValue(null) ?? throw new InvalidOperationException($"{instance.ReflectedType?.FullName}.{instance.Name} return null.")); } else { throw new MessagePackSerializationException($"The {formatterType.FullName} formatter has no default constructor nor implements the singleton pattern."); } } else { return (IMessagePackFormatter)Activator.CreateInstance(formatterType, args)!; } } internal static FieldInfo? FetchSingletonField(Type formatterType) { if (formatterType.GetField("Instance", BindingFlags.Static | BindingFlags.Public) is FieldInfo fieldInfo && fieldInfo.IsInitOnly) { return fieldInfo; } return null; } } }
ResolverUtilities
csharp
ChilliCream__graphql-platform
src/HotChocolate/Raven/test/Data.Raven.Paging.Tests/RavenQueryableTests.cs
{ "start": 8409, "end": 12748 }
public class ____ { public string? Id { get; set; } public string Bar { get; set; } = null!; } private Func<IResolverContext, IRavenQueryable<TResult>> BuildResolver<TResult>( IDocumentStore store, IEnumerable<TResult> results) where TResult : class { using var session = store.OpenSession(); foreach (var item in results) { session.Store(item); } session.SaveChanges(); return ctx => ((IAsyncDocumentSession)ctx.LocalContextData["session"]!).Query<TResult>(); } private ValueTask<IRequestExecutor> CreateSchemaAsync() { var database = _resource.CreateDatabase(); return new ServiceCollection() .AddSingleton(database) .AddGraphQL() .AddRavenPagingProviders() .AddRavenFiltering() .AddQueryType( descriptor => { descriptor .Field("foos") .Resolve(BuildResolver(database, _foos)) .Type<ListType<ObjectType<Foo>>>() .Use( next => async context => { using (var session = database.OpenAsyncSession()) { context.LocalContextData = context.LocalContextData.SetItem("session", session); await next(context); } }) .Use( next => async context => { await next(context); if (context.Result is IRavenQueryable<Foo> queryable) { context.ContextData["sql"] = queryable.ToString(); } }) .UsePaging<ObjectType<Foo>>( options: new PagingOptions { IncludeTotalCount = true }); descriptor .Field("foosOffset") .Resolve(BuildResolver(database, _foos)) .Type<ListType<ObjectType<Foo>>>() .Use( next => async context => { using (var session = database.OpenAsyncSession()) { context.LocalContextData = context.LocalContextData.SetItem("session", session); await next(context); } }) .Use( next => async context => { await next(context); if (context.Result is IRavenQueryable<Foo> queryable) { context.ContextData["sql"] = queryable.ToString(); } }) .UseOffsetPaging<ObjectType<Foo>>( options: new PagingOptions { IncludeTotalCount = true }); }) .UseRequest( (_, next) => async context => { await next(context); if (context.ContextData.TryGetValue("query", out var queryString)) { context.Result = OperationResultBuilder .FromResult(context.Result!.ExpectOperationResult()) .SetContextData("query", queryString) .Build(); } }) .ModifyRequestOptions(x => x.IncludeExceptionDetails = true) .UseDefaultPipeline() .Services .BuildServiceProvider() .GetRequiredService<IRequestExecutorProvider>() .GetExecutorAsync(); } }
Foo
csharp
neuecc__MessagePack-CSharp
benchmark/SerializerBenchmark/Serializers/MessagePackSerializer.cs
{ "start": 4105, "end": 4758 }
public class ____ : SerializerBase { public override T Deserialize<T>(object input) { return oldmsgpack::MessagePack.LZ4MessagePackSerializer.Deserialize<T>((byte[])input, oldmsgpack::MessagePack.Resolvers.ContractlessStandardResolver.Instance); } public override object Serialize<T>(T input) { return oldmsgpack::MessagePack.LZ4MessagePackSerializer.Serialize<T>(input, oldmsgpack::MessagePack.Resolvers.ContractlessStandardResolver.Instance); } public override string ToString() { return "MsgPack_v1_str_lz4"; } }
MsgPack_v1_str_lz4
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/Rendering/Composition/Server/IServerClockItem.cs
{ "start": 50, "end": 108 }
internal interface ____ { void OnTick(); }
IServerClockItem
csharp
dotnet__reactive
Ix.NET/Source/System.Interactive/System/Linq/Operators/Share.cs
{ "start": 3920, "end": 5472 }
private sealed class ____ : IEnumerator<T> { private readonly SharedBuffer<T> _parent; private bool _disposed; public ShareEnumerator(SharedBuffer<T> parent) { _parent = parent; Current = default!; } public T Current { get; private set; } object? IEnumerator.Current => Current; public void Dispose() => _disposed = true; public bool MoveNext() { if (_disposed) { return false; } if (_parent._disposed) { throw new ObjectDisposedException(""); } var hasValue = false; var src = _parent._source; lock (src) { hasValue = src.MoveNext(); if (hasValue) { Current = src.Current; } } if (hasValue) { return true; } _disposed = true; Current = default!; return false; } public void Reset() => throw new NotSupportedException(); } } } }
ShareEnumerator
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.Jobs/BackgroundJobsWorker.cs
{ "start": 96, "end": 2394 }
public class ____ : IDisposable { public string? Name { get; set; } public ConcurrentQueue<BackgroundJob> Queue { get; } = new(); public Task? BackgroundTask => bgTask; private Task? bgTask; private long running = 0; public bool Running => Interlocked.Read(ref running) == 1; DateTime? lastRunStarted = null; public TimeSpan? RunningTime => lastRunStarted != null ? DateTime.UtcNow - (lastRunStarted ?? DateTime.UtcNow) : null; private long tasksStarted = 0; private long received = 0; private long retries = 0; private long failed = 0; private long completed = 0; private readonly IBackgroundJobs jobs; private readonly CancellationToken ct; private readonly CancellationTokenSource workerCts; private readonly bool transient; private bool cancelled; private bool disposed; private int defaultTimeOutSecs; private BackgroundJob? runningJob; public BackgroundJob? RunningJob => runningJob; public BackgroundJobsWorker(IBackgroundJobs jobs, CancellationToken ct, bool transient, int defaultTimeOutSecs) { this.jobs = jobs; workerCts = CancellationTokenSource.CreateLinkedTokenSource(ct); this.ct = workerCts.Token; this.transient = transient; this.defaultTimeOutSecs = defaultTimeOutSecs; } public WorkerStats GetStats() => new() { Name = Name ?? "None", Queued = Queue.Count, Received = received, Completed = completed, Retries = retries, Failed = failed, RunningJob = runningJob?.Id, RunningTime = RunningTime, }; public void Cancel(bool throwOnFirstException=false) { cancelled = true; workerCts.Cancel(throwOnFirstException); } public void Enqueue(BackgroundJob job) { Interlocked.Increment(ref received); Queue.Enqueue(job); if (Interlocked.CompareExchange(ref running, 1, 0) == 0) { Interlocked.Increment(ref tasksStarted); bgTask = Task.Factory.StartNew(RunAsync, new JobWorkerContext(Queue, jobs, ct), ct); } } public bool HasJobQueued(long jobId) { return runningJob?.Id == jobId || Queue.Any(x => x.Id == jobId); }
BackgroundJobsWorker
csharp
atata-framework__atata
test/Atata.UnitTests/DataProvision/SubjectTests.cs
{ "start": 1410, "end": 2287 }
public sealed class ____ { private Subject<Dictionary<string, int>> _subject = null!; [SetUp] public void SetUpTest() => _subject = CreateDictionarySubject(); [Test] public void ProviderName_OfProperty() => _subject.ValueOf(x => x.Count) .ProviderName.Should().Be("subject.Count"); [Test] public void ProviderName_OfFunction() => _subject.ValueOf(x => x.ContainsKey("a")) .ProviderName.Should().Be("subject.ContainsKey(\"a\")"); [Test] public void ProviderName_OfProperty_AfterMultipleActions() => _subject .Act(x => x.Add("d", 4)) .Act(x => x.Add("e", 5)) .ValueOf(x => x.Count).ProviderName.Should().Be("subject{ Add(\"d\", 4); Add(\"e\", 5) }.Count"); }
ValueOf
csharp
EventStore__EventStore
src/KurrentDB.Core.Tests/Http/Streams/feed.cs
{ "start": 26004, "end": 28926 }
public class ____(string postContentType, string getContentType) : with_admin_user { private JObject _feed; private string advertisedAddress = "127.0.10.1"; private int advertisedPort = 2116; protected override MiniNode<LogFormat.V2, string> CreateMiniNode() { return new MiniNode<LogFormat.V2, string>(PathName, advertisedExtHostAddress: advertisedAddress, advertisedHttpPort: advertisedPort); } protected override async Task Given() { var response = await MakeArrayEventsPost( TestStream, new[] { new { EventId = Guid.NewGuid(), EventType = "event-type", Data = new { Number = 1 } } }, contentType: postContentType); Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); } protected string GetLink(JObject feed, string relation) { var rel = (from JObject link in feed["links"] from JProperty attr in link where attr.Name == "relation" && (string)attr.Value == relation select link).SingleOrDefault(); return (rel == null) ? (string)null : (string)rel["uri"]; } protected string GetFirstEntryLink(JObject feed) { var rel = (from JObject entry in feed["entries"] from JObject link in entry["links"] from JProperty attr in link where attr.Name == "relation" && (string)attr.Value == "edit" select link).FirstOrDefault(); return (rel == null) ? (string)null : (string)rel["uri"]; } protected override async Task When() { Console.WriteLine("Getting feed"); _feed = await GetJson<JObject>(TestStream, getContentType); Console.WriteLine("Feed: {0}", _feed); } [Test] public void returns_ok_status_code() { Assert.AreEqual(HttpStatusCode.OK, _lastResponse.StatusCode); } [Test] public void contains_a_link_rel_previous_using_advertised_ip_and_port() { var rel = GetLink(_feed, "previous"); Assert.IsNotEmpty(rel); var uri = new Uri(rel); Assert.AreEqual(advertisedAddress.ToString(), uri.Host); Assert.AreEqual(advertisedPort, uri.Port); } [Test] public void contains_a_link_rel_self_using_advertised_ip_and_port() { var rel = GetLink(_feed, "self"); Assert.IsNotEmpty(rel); var uri = new Uri(rel); Assert.AreEqual(advertisedAddress.ToString(), uri.Host); Assert.AreEqual(advertisedPort, uri.Port); } [Test] public void contains_a_link_rel_first_using_advertised_ip_and_port() { var rel = GetLink(_feed, "first"); Assert.IsNotEmpty(rel); var uri = new Uri(rel); Assert.AreEqual(advertisedAddress.ToString(), uri.Host); Assert.AreEqual(advertisedPort, uri.Port); } [Test] public void contains_an_entry_with_rel_link_using_advertised_ip_and_port() { var rel = GetFirstEntryLink(_feed); Assert.IsNotEmpty(rel); var uri = new Uri(rel); Assert.AreEqual(advertisedAddress.ToString(), uri.Host); Assert.AreEqual(advertisedPort, uri.Port); } } }
when_retrieving_feed_head_and_http_advertise_ip_is_set
csharp
neuecc__MessagePack-CSharp
sandbox/DynamicCodeDumper/Program.cs
{ "start": 11157, "end": 11295 }
public class ____ { public int MyProperty { get; set; } public string? MyProperty2 { get; set; } }
Contractless2
csharp
MassTransit__MassTransit
src/MassTransit/DependencyInjection/Configuration/DependencyInjectionSagaStateMachineRegistrationExtensions.cs
{ "start": 5081, "end": 5793 }
class ____<TStateMachine, TSaga> : ISagaRegistrar where TStateMachine : class, SagaStateMachine<TSaga> where TSaga : class, SagaStateMachineInstance { public virtual ISagaRegistration Register(IServiceCollection collection, IContainerRegistrar registrar) { collection.AddSingleton<TStateMachine>(); collection.AddSingleton<SagaStateMachine<TSaga>>(provider => provider.GetRequiredService<TStateMachine>()); return registrar.GetOrAddRegistration<ISagaRegistration>(typeof(TSaga), _ => new SagaStateMachineRegistration<TStateMachine, TSaga>(registrar)); } }
SagaRegistrar
csharp
bitwarden__server
src/Core/Dirt/Reports/ReportFeatures/Interfaces/IAddPasswordHealthReportApplicationCommand.cs
{ "start": 145, "end": 504 }
public interface ____ { Task<PasswordHealthReportApplication> AddPasswordHealthReportApplicationAsync(AddPasswordHealthReportApplicationRequest request); Task<IEnumerable<PasswordHealthReportApplication>> AddPasswordHealthReportApplicationAsync(IEnumerable<AddPasswordHealthReportApplicationRequest> requests); }
IAddPasswordHealthReportApplicationCommand
csharp
aspnetboilerplate__aspnetboilerplate
test/Abp.EntityFrameworkCore.Dapper.Tests/Tests/Transaction_Tests.cs
{ "start": 317, "end": 4471 }
public class ____ : AbpEfCoreDapperTestApplicationBase { private readonly IDapperRepository<Blog> _blogDapperRepository; private readonly IRepository<Blog> _blogRepository; private readonly IUnitOfWorkManager _uowManager; public Transaction_Tests() { _uowManager = Resolve<IUnitOfWorkManager>(); _blogRepository = Resolve<IRepository<Blog>>(); _blogDapperRepository = Resolve<IDapperRepository<Blog>>(); } [Fact] public async Task Should_Rollback_Transaction_On_Failure() { const string exceptionMessage = "This is a test exception!"; string blogName = Guid.NewGuid().ToString("N"); try { using (_uowManager.Begin()) { await _blogRepository.InsertAsync( new Blog(blogName, $"http://{blogName}.com/") ); throw new Exception(exceptionMessage); } } catch (Exception ex) when (ex.Message == exceptionMessage) { } var blog = await _blogRepository.FirstOrDefaultAsync(x => x.Name == blogName); blog.ShouldBeNull(); } [Fact] public void Dapper_and_EfCore_should_work_under_same_unitofwork_and_when_any_exception_appears_then_rollback_should_be_consistent_for_two_orm() { Resolve<IEventBus>().Register<EntityCreatingEventData<Blog>>( eventData => { eventData.Entity.Name.ShouldBe("Oguzhan_Same_Uow"); throw new Exception("Uow Rollback"); }); try { using (IUnitOfWorkCompleteHandle uow = Resolve<IUnitOfWorkManager>().Begin()) { var blogId = _blogDapperRepository.InsertAndGetId( new Blog("Oguzhan_Same_Uow", "www.oguzhansoykan.com") ); Blog person = _blogRepository.Get(blogId); person.ShouldNotBeNull(); uow.Complete(); } } catch (Exception) { //no handling. } _blogDapperRepository.FirstOrDefault(x => x.Name == "Oguzhan_Same_Uow").ShouldBeNull(); _blogRepository.FirstOrDefault(x => x.Name == "Oguzhan_Same_Uow").ShouldBeNull(); } [Fact] public async Task inline_sql_with_dapper_should_rollback_when_uow_fails() { Resolve<IEventBus>().Register<EntityCreatingEventData<Blog>>(eventData => { eventData.Entity.Name.ShouldBe("Oguzhan_Same_Uow"); }); var blogId = 0; using (var uow = Resolve<IUnitOfWorkManager>().Begin()) { blogId = await _blogDapperRepository.InsertAndGetIdAsync( new Blog("Oguzhan_Same_Uow", "www.aspnetboilerplate.com") ); var person = await _blogRepository.GetAsync(blogId); person.ShouldNotBeNull(); await uow.CompleteAsync(); } try { using (IUnitOfWorkCompleteHandle uow = Resolve<IUnitOfWorkManager>() .Begin(new UnitOfWorkOptions { IsTransactional = true })) { await _blogDapperRepository.ExecuteAsync( "Update Blogs Set Name = @name where Id =@id", new { id = blogId, name = "Oguzhan_New_Blog" } ); throw new Exception("uow rollback"); // Unreachable code. // await uow.CompleteAsync(); } } catch (Exception) { //no handling. } (await _blogDapperRepository.FirstOrDefaultAsync(x => x.Name == "Oguzhan_New_Blog")).ShouldBeNull(); (await _blogRepository.FirstOrDefaultAsync(x => x.Name == "Oguzhan_New_Blog")).ShouldBeNull(); (await _blogDapperRepository.FirstOrDefaultAsync(x => x.Name == "Oguzhan_Same_Uow")).ShouldNotBeNull(); (await _blogRepository.FirstOrDefaultAsync(x => x.Name == "Oguzhan_Same_Uow")).ShouldNotBeNull(); } }
Transaction_Tests
csharp
neuecc__MessagePack-CSharp
src/MessagePack/Formatters/StandardClassLibraryFormatter.cs
{ "start": 2259, "end": 2844 }
public sealed class ____ : IMessagePackFormatter<string?> { public static readonly NullableStringFormatter Instance = new NullableStringFormatter(); private NullableStringFormatter() { } public void Serialize(ref MessagePackWriter writer, string? value, MessagePackSerializerOptions options) { writer.Write(value); } public string? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options) { return reader.ReadString(); } }
NullableStringFormatter
csharp
dotnet__aspire
src/Aspire.Hosting/api/Aspire.Hosting.cs
{ "start": 68853, "end": 69295 }
partial class ____ { public int? Group { get { throw null; } set { } } public System.IO.UnixFileMode Mode { get { throw null; } set { } } public string Name { get { throw null; } set { } } public int? Owner { get { throw null; } set { } } } [System.Diagnostics.DebuggerDisplay("Type = {GetType().Name,nq}, Image = {Image}, Tag = {Tag}, SHA256 = {SHA256}")] public sealed
ContainerFileSystemItem
csharp
smartstore__Smartstore
src/Smartstore/Utilities/Html/HtmlSanitizerOptions.cs
{ "start": 79, "end": 2888 }
public class ____ { public static HtmlSanitizerOptions Default { get; } = new(); public static HtmlSanitizerOptions UserCommentSuitable { get; } = new HtmlSanitizerOptions { AllowedTags = new HashSet<string> { "abbr", "acronym", "address", "b", "big", "blockquote", "br", "cite", "dd", "del", "dfn", "dir", "dl", "dt", "em", "hr", "i", "ins", "kbd", "ul", "ol", "li", "pre", "samp", "small", "span", "strike", "strong", "sub", "sup", "tt", "u", "var", // Text-level semantics "data", "time", "mark", "ruby", "rt", "rp", "bdi", "wbr", }, DisallowedAttributes = new HashSet<string> { "style", "class" } }; public static ISet<string> DefaultAllowedTags { get; } = HtmlSanitizerDefaults.AllowedTags; public static ISet<string> DefaultAllowedAttributes { get; } = HtmlSanitizerDefaults.AllowedAttributes; public static ISet<string> DefaultUriAttributes { get; } = HtmlSanitizerDefaults.UriAttributes; /// <summary> /// Gets or sets a value indicating whether to keep child nodes of elements that are removed. Default is <c>false</c>. /// </summary> public bool KeepChildNodes { get; set; } = HtmlSanitizer.DefaultKeepChildNodes; /// <summary> /// Allow all HTML5 data attributes; the attributes prefixed with data-. Default: <c>false</c>. /// </summary> public bool AllowDataAttributes { get; set; } = HtmlSanitizer.DefaultKeepChildNodes; /// <summary> /// The allowed tag names such as "a" and "div". When <c>null</c>, uses <see cref="DefaultAllowedTags"/> /// </summary> public ISet<string>? AllowedTags { get; set; } /// <summary> /// The disallowed tag names such as "a" and "div". /// </summary> public ISet<string>? DisallowedTags { get; set; } /// <summary> /// The allowed HTML attributes such as "href" and "alt". When <c>null</c>, uses <see cref="DefaultAllowedAttributes"/> /// </summary> public ISet<string>? AllowedAttributes { get; set; } /// <summary> /// The disallowed HTML attributes such as "href" and "alt". /// </summary> public ISet<string>? DisallowedAttributes { get; set; } /// <summary> /// The allowed CSS classes. When <c>null</c>, all classes are allowed. /// </summary> public ISet<string>? AllowedCssClasses { get; set; } /// <summary> /// The HTML attributes that can contain a URI such as "href". When <c>null</c>, uses <see cref="DefaultUriAttributes"/> /// </summary> public ISet<string>? UriAttributes { get; set; } } }
HtmlSanitizerOptions
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/SagaStateMachineTests/Fault_Specs.cs
{ "start": 3825, "end": 6039 }
class ____ : MassTransitStateMachine<Instance> { public TestStateMachine() { InstanceState(x => x.CurrentState); Event(() => StartFaulted, x => x.CorrelateById(context => context.Message.Message.CorrelationId)); Event(() => Stopped, x => x.OnMissingInstance(m => m.Fault())); Initially( When(Started) .Then(context => { throw new NotSupportedException("This is expected, but nonetheless exceptional"); }) .TransitionTo(Running), When(Initialized) .TransitionTo(WaitingToStart), When(Created) .Then(context => { throw new NotSupportedException("This is expected, but nonetheless exceptional"); }) .TransitionTo(Running)); During(WaitingToStart, When(Started) .Then(instance => { throw new NotSupportedException("This is expected, but nonetheless exceptional"); }) .TransitionTo(Running), When(StartFaulted) .TransitionTo(FailedToStart)); During(Running, When(Stopped) .TransitionTo(Complete)); } public State WaitingToStart { get; private set; } public State FailedToStart { get; private set; } public State Running { get; private set; } public State Complete { get; private set; } public Event<Start> Started { get; private set; } public Event<Initialize> Initialized { get; private set; } public Event<Create> Created { get; private set; } public Event<Fault<Start>> StartFaulted { get; private set; } public Event<Stop> Stopped { get; private set; } }
TestStateMachine
csharp
dotnet__maui
src/Controls/tests/Core.UnitTests/FontUnitTests.cs
{ "start": 97, "end": 3139 }
public class ____ : BaseTestFixture { [Fact] public void TestFontForSize() { var font = Font.OfSize("Foo", 12); Assert.Equal("Foo", font.Family); Assert.Equal(12, font.Size); } [Fact] public void TestFontForSizeDouble() { var font = Font.OfSize("Foo", 12.7); Assert.Equal("Foo", font.Family); Assert.Equal(12.7, font.Size); } [Fact] public void TestFontForNamedSize() { var size = Device.GetNamedSize(NamedSize.Large, null, false); var font = Font.OfSize("Foo", size); Assert.Equal("Foo", font.Family); Assert.Equal(size, font.Size); } [Fact] public void TestSystemFontOfSize() { var font = Font.SystemFontOfSize(12); Assert.Null(font.Family); Assert.Equal(12, font.Size); var size = Device.GetNamedSize(NamedSize.Medium, null, false); font = Font.SystemFontOfSize(size); Assert.Null(font.Family); Assert.Equal(size, font.Size); } [Theory, InlineData("en-US"), InlineData("tr-TR"), InlineData("fr-FR")] public void CultureTestSystemFontOfSizeDouble(string culture) { System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(culture); var font = Font.SystemFontOfSize(12.7); Assert.Null(font.Family); Assert.Equal(12.7, font.Size); var size = Device.GetNamedSize(NamedSize.Medium, null, false); font = Font.SystemFontOfSize(size); Assert.Null(font.Family); Assert.Equal(size, font.Size); } [Fact] public void TestEquality() { var font1 = Font.SystemFontOfSize(12); var font2 = Font.SystemFontOfSize(12); Assert.True(font1 == font2); Assert.False(font1 != font2); font2 = Font.SystemFontOfSize(13); Assert.False(font1 == font2); Assert.True(font1 != font2); } [Fact] public void TestHashCode() { var font1 = Font.SystemFontOfSize(12); var font2 = Font.SystemFontOfSize(12); Assert.True(font1.GetHashCode() == font2.GetHashCode()); font2 = Font.SystemFontOfSize(13); Assert.False(font1.GetHashCode() == font2.GetHashCode()); } [Fact] public void TestEquals() { var font = Font.SystemFontOfSize(12); Assert.False(font.Equals(null)); Assert.True(font.Equals(font)); Assert.False(font.Equals("Font")); Assert.True(font.Equals(Font.SystemFontOfSize(12))); } [Fact] public void TestFontParsing() { var input = "PTM55FT#PTMono-Regular"; var input2 = "PTM55FT.ttf#PTMono-Regular"; var input3 = "CuteFont-Regular"; var font1 = FontFile.FromString(input); var font2 = FontFile.FromString(input2); var font3 = FontFile.FromString(input3); Assert.Equal("PTM55FT", font1.FileName); Assert.Equal("PTMono-Regular", font1.PostScriptName); Assert.Null(font1.Extension); Assert.Equal("PTM55FT", font2.FileName); Assert.Equal("PTMono-Regular", font2.PostScriptName); Assert.Equal(".ttf", font2.Extension); Assert.Equal("CuteFont-Regular", font3.FileName); Assert.Equal("CuteFont-Regular", font3.PostScriptName); Assert.Null(font3.Extension); } } }
FontUnitTests
csharp
microsoft__semantic-kernel
dotnet/src/VectorData/InMemory/InMemoryCollectionOptions.cs
{ "start": 253, "end": 334 }
public sealed class ____ : VectorStoreCollectionOptions { }
InMemoryCollectionOptions
csharp
ServiceStack__ServiceStack
ServiceStack/tests/NorthwindAuto/ServiceModel/Issues.cs
{ "start": 182, "end": 370 }
public record ____(DateOnly Date, int TemperatureC, string? Summary) : IGet, IReturn<Forecast[]> { public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); } [Tag("issues")]
Forecast
csharp
unoplatform__uno
src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml_Controls/Given_ComboBox.cs
{ "start": 1357, "end": 44641 }
public class ____ { private ResourceDictionary _testsResources; private Style CounterComboBoxContainerStyle => _testsResources["CounterComboBoxContainerStyle"] as Style; private Style ComboBoxItemContainerStyle => _testsResources["ComboBoxItemContainerStyle"] as Style; private Style ComboBoxWithSeparatorStyle => _testsResources["ComboBoxWithSeparatorStyle"] as Style; private DataTemplate CounterItemTemplate => _testsResources["CounterItemTemplate"] as DataTemplate; private ItemsPanelTemplate MeasureCountCarouselPanelTemplate => _testsResources["MeasureCountCarouselPanel"] as ItemsPanelTemplate; [TestInitialize] public void Init() { _testsResources = new TestsResources(); CounterGrid.Reset(); CounterGrid2.Reset(); MeasureCountCarouselPanel.Reset(); } const int BorderThicknessAdjustment = 2; // Deduct BorderThickness on PopupBorder #if HAS_UNO [TestMethod] [DataRow(0)] [DataRow(1)] [DataRow(2)] public async Task When_ReOpened_Remains_Selected_VisualState(int selectedIndex) { var SUT = new ComboBox(); var items = new[] { "First", "Second", "Third" }; SUT.ItemsSource = items; await UITestHelper.Load(SUT); SUT.IsDropDownOpen = true; await TestServices.WindowHelper.WaitForIdle(); SUT.SelectedIndex = selectedIndex; await TestServices.WindowHelper.WaitForIdle(); SUT.IsDropDownOpen = false; await TestServices.WindowHelper.WaitForIdle(); SUT.IsDropDownOpen = true; await TestServices.WindowHelper.WaitForIdle(); var container = (ComboBoxItem)SUT.ContainerFromItem(items[selectedIndex]); Assert.AreEqual("Selected", VisualStateManager.GetCurrentState(container, "CommonStates").Name); } #endif [TestMethod] public async Task When_IsEditable_False() { // EditableText is only available in fluent style. var SUT = new ComboBox(); await UITestHelper.Load(SUT); Assert.IsFalse(SUT.IsEditable); Assert.AreEqual(Visibility.Collapsed, GetEditableText(SUT).Visibility); } [TestMethod] public async Task When_IsEditable_True() { // EditableText is only available in fluent style. var SUT = new ComboBox() { IsEditable = true }; await UITestHelper.Load(SUT); Assert.IsTrue(SUT.IsEditable); Assert.AreEqual(Visibility.Visible, GetEditableText(SUT).Visibility); } [TestMethod] public async Task When_IsEditable_False_Changes_To_True() { if (!ApiInformation.IsPropertyPresent("Microsoft.UI.Xaml.Controls.ComboBox, Uno.UI", "IsEditable")) { Assert.Inconclusive(); } // EditableText is only available in fluent style. var SUT = new ComboBox(); await UITestHelper.Load(SUT); Assert.IsFalse(SUT.IsEditable); Assert.AreEqual(Visibility.Collapsed, GetEditableText(SUT).Visibility); SUT.IsEditable = true; Assert.IsTrue(SUT.IsEditable); Assert.AreEqual(Visibility.Visible, GetEditableText(SUT).Visibility); } private TextBox GetEditableText(ComboBox comboBox) => comboBox.FindFirstChild<TextBox>(c => c.Name == "EditableText"); [TestMethod] public async Task When_ComboBox_MinWidth() { var source = Enumerable.Range(0, 5).ToArray(); const int minWidth = 172; const int expectedItemWidth = minWidth - BorderThicknessAdjustment; var SUT = new ComboBox { MinWidth = minWidth, ItemsSource = source }; try { WindowHelper.WindowContent = SUT; await WindowHelper.WaitForLoaded(SUT); await WindowHelper.WaitFor(() => SUT.ActualWidth == minWidth); // Needed for iOS where ComboBox may be initially too wide, for some reason SUT.IsDropDownOpen = true; ComboBoxItem cbi = null; foreach (var item in source) { await WindowHelper.WaitFor(() => (cbi = SUT.ContainerFromItem(item) as ComboBoxItem) != null); await WindowHelper.WaitForLoaded(cbi); // Required on Android Assert.AreEqual(expectedItemWidth, cbi.ActualWidth); } } finally { SUT.IsDropDownOpen = false; WindowHelper.WindowContent = null; } } [TestMethod] public async Task When_ComboBox_Constrained_By_Parent() { var source = Enumerable.Range(0, 5).ToArray(); const int width = 133; const int expectedItemWidth = width - BorderThicknessAdjustment; var SUT = new ComboBox { HorizontalAlignment = HorizontalAlignment.Stretch, ItemsSource = source }; var grid = new Grid { Width = width }; grid.Children.Add(SUT); try { WindowHelper.WindowContent = grid; await WindowHelper.WaitForLoaded(SUT); SUT.IsDropDownOpen = true; ComboBoxItem cbi = null; foreach (var item in source) { await WindowHelper.WaitFor(() => (cbi = SUT.ContainerFromItem(item) as ComboBoxItem) != null); await WindowHelper.WaitForLoaded(cbi); // Required on Android Assert.AreEqual(expectedItemWidth, cbi.ActualWidth, 0.5); // Account for layout rounding } } finally { SUT.IsDropDownOpen = false; WindowHelper.WindowContent = null; } } #if HAS_UNO [TestMethod] #if !HAS_INPUT_INJECTOR [Ignore("InputInjector is not supported on this platform.")] #endif public async Task When_PointerWheel() { var SUT = new ComboBox(); var items = new[] { "First", "Second", "Third" }; SUT.ItemsSource = items; var rect = await UITestHelper.Load(SUT); SUT.SelectedIndex = 0; SUT.Focus(FocusState.Programmatic); var injector = InputInjector.TryCreate() ?? throw new InvalidOperationException("Failed to init the InputInjector"); using var mouse = injector.GetMouse(); mouse.MoveTo(rect.X + 2, rect.Y + 2); mouse.WheelDown(); Assert.AreEqual(1, SUT.SelectedIndex); await WindowHelper.WaitForIdle(); mouse.WheelUp(); Assert.AreEqual(0, SUT.SelectedIndex); await WindowHelper.WaitForIdle(); mouse.WheelUp(); Assert.AreEqual(0, SUT.SelectedIndex); } #endif [TestMethod] public async Task Check_Creation_Count_Few_Items() { var source = Enumerable.Range(0, 5).ToArray(); using (FeatureConfigurationHelper.UseTemplatePooling()) // If pooling is disabled, then the 'is template a container' check creates an extra template root { var SUT = new ComboBox { ItemsSource = source, ItemContainerStyle = CounterComboBoxContainerStyle, ItemTemplate = CounterItemTemplate }; try { Assert.AreEqual(0, CounterGrid.CreationCount); Assert.AreEqual(0, CounterGrid2.CreationCount); WindowHelper.WindowContent = SUT; await WindowHelper.WaitForLoaded(SUT); #if !__ANDROID__ && !__APPLE_UIKIT__ // This does not hold on Android or iOS, possibly because ComboBox is not virtualized Assert.AreEqual(0, CounterGrid.CreationCount); Assert.AreEqual(0, CounterGrid2.CreationCount); #endif SUT.IsDropDownOpen = true; ComboBoxItem cbi = null; await WindowHelper.WaitFor(() => (cbi = SUT.ContainerFromItem(source[0]) as ComboBoxItem) != null); await WindowHelper.WaitForLoaded(cbi); // Required on Android Assert.AreEqual(5, CounterGrid.CreationCount); Assert.AreEqual(5, CounterGrid2.CreationCount); Assert.AreEqual(5, CounterGrid.BindCount); Assert.AreEqual(5, CounterGrid2.BindCount); } finally { SUT.IsDropDownOpen = false; WindowHelper.WindowContent = null; } } } [TestMethod] #if __APPLE_UIKIT__ || __ANDROID__ [Ignore("ComboBox is currently not virtualized on iOS and Android - #556")] // https://github.com/unoplatform/uno/issues/556 #endif public async Task Check_Creation_Count_Many_Items() { var source = Enumerable.Range(0, 500).ToArray(); var SUT = new ComboBox { ItemsSource = source, ItemContainerStyle = CounterComboBoxContainerStyle, ItemTemplate = CounterItemTemplate }; try { WindowHelper.WindowContent = SUT; await WindowHelper.WaitForLoaded(SUT); Assert.AreEqual(0, CounterGrid.CreationCount); Assert.AreEqual(0, CounterGrid2.CreationCount); SUT.IsDropDownOpen = true; ComboBoxItem cbi = null; await WindowHelper.WaitFor(() => source.Any(i => (cbi = SUT.ContainerFromItem(i) as ComboBoxItem) != null)); // Windows loads up CarouselPanel with no selected item around the middle, other platforms may not //await WindowHelper.WaitFor(() => (cbi = SUT.ContainerFromItem(source[0]) as ComboBoxItem) != null); await WindowHelper.WaitForLoaded(cbi); // Required on Android const int maxCount = 30; NumberAssert.Less(CounterGrid.CreationCount, maxCount); NumberAssert.Less(CounterGrid2.CreationCount, maxCount); } finally { SUT.IsDropDownOpen = false; WindowHelper.WindowContent = null; } } #if __APPLE_UIKIT__ [TestMethod] [RunsOnUIThread] public async Task Check_DropDown_Flyout_Margin_When_In_Modal() { MultiFrame multiFrame = new(); var showModalButton = new Button(); multiFrame.Children.Add(showModalButton); var source = Enumerable.Range(0, 6).ToArray(); var SUT = new ComboBox { ItemsSource = source, Text = "Alignment", VerticalAlignment = VerticalAlignment.Center, PlaceholderText = "Testing", Style = ComboBoxWithSeparatorStyle }; var modalPage = new Page(); var gridContainer = new Grid() { Background = SolidColorBrushHelper.LightGreen }; async void OpenModal(object sender, RoutedEventArgs e) { gridContainer.Children.Add(SUT); modalPage.Content = gridContainer; await multiFrame.OpenModal(FrameSectionsTransitionInfo.NativeiOSModal, modalPage); } try { var homePage = new Page(); showModalButton.Click += OpenModal; homePage.Content = multiFrame; WindowHelper.WindowContent = homePage; await WindowHelper.WaitForLoaded(homePage); // Open Modal showModalButton.RaiseClick(); await WindowHelper.WaitForLoaded(modalPage); SUT.IsDropDownOpen = true; await WindowHelper.WaitForIdle(); var locationX = SUT.GetAbsoluteBoundsRect().Location.X; var popup = SUT.FindFirstChild<Popup>(); var childX = popup?.Child?.Frame.X ?? 0; Assert.IsNotNull(ComboBoxWithSeparatorStyle); Assert.IsNotNull(popup); Assert.IsTrue(popup.IsOpen); Assert.AreEqual(locationX, childX, "ComboBox vs ComboBox.PopUp.Child Frame.X are not equal"); } finally { showModalButton.Click -= OpenModal; SUT.IsDropDownOpen = false; await multiFrame.CloseModal(); WindowHelper.WindowContent = null; } } #endif [TestMethod] public async Task Check_Dropdown_Measure_Count() { var source = Enumerable.Range(0, 500).ToArray(); var SUT = new ComboBox { ItemsSource = source, ItemsPanel = MeasureCountCarouselPanelTemplate }; try { WindowHelper.WindowContent = SUT; await WindowHelper.WaitForLoaded(SUT); Assert.AreEqual(0, MeasureCountCarouselPanel.MeasureCount); Assert.AreEqual(0, MeasureCountCarouselPanel.ArrangeCount); SUT.IsDropDownOpen = true; ComboBoxItem cbi = null; await WindowHelper.WaitFor(() => source.Any(i => (cbi = SUT.ContainerFromItem(i) as ComboBoxItem) != null)); // Windows loads up CarouselPanel with no selected item around the middle, other platforms may not await WindowHelper.WaitForLoaded(cbi); // Required on Android NumberAssert.Greater(MeasureCountCarouselPanel.MeasureCount, 0); NumberAssert.Greater(MeasureCountCarouselPanel.ArrangeCount, 0); #if __APPLE_UIKIT__ const int MaxAllowedCount = 15; // TODO: figure out why iOS measures more times #else const int MaxAllowedCount = 5; #endif NumberAssert.Less(MeasureCountCarouselPanel.MeasureCount, MaxAllowedCount); NumberAssert.Less(MeasureCountCarouselPanel.ArrangeCount, MaxAllowedCount); } finally { SUT.IsDropDownOpen = false; WindowHelper.WindowContent = null; } } [TestMethod] public async Task When_CB_Fluent_And_Theme_Changed() { var comboBox = new ComboBox { ItemsSource = new[] { 1, 2, 3 }, PlaceholderText = "Select..." }; WindowHelper.WindowContent = comboBox; await WindowHelper.WaitForLoaded(comboBox); var placeholderTextBlock = comboBox.FindFirstChild<TextBlock>(tb => tb.Name == "PlaceholderTextBlock"); Assert.IsNotNull(placeholderTextBlock); var lightThemeForeground = TestsColorHelper.ToColor("#9E000000"); var darkThemeForeground = TestsColorHelper.ToColor("#C5FFFFFF"); Assert.AreEqual(lightThemeForeground, (placeholderTextBlock.Foreground as SolidColorBrush)?.Color); using (ThemeHelper.UseDarkTheme()) { Assert.AreEqual(darkThemeForeground, (placeholderTextBlock.Foreground as SolidColorBrush)?.Color); } Assert.AreEqual(lightThemeForeground, (placeholderTextBlock.Foreground as SolidColorBrush)?.Color); } [TestMethod] public async Task When_SelectedItem_Set_Before_ItemsSource() { var SUT = new ComboBox(); var items = Enumerable.Range(0, 10); await UITestHelper.Load(SUT); SUT.SelectedItem = 5; await WindowHelper.WaitForIdle(); Assert.IsNull(SUT.SelectedItem); SUT.ItemsSource = items; await WindowHelper.WaitForIdle(); Assert.AreEqual(5, SUT.SelectedItem); } [TestMethod] public async Task When_SelectedItem_Set_Then_SelectedIndex_Then_ItemsSource() { var SUT = new ComboBox(); var items = Enumerable.Range(0, 10); await UITestHelper.Load(SUT); SUT.SelectedIndex = 3; await WindowHelper.WaitForIdle(); Assert.IsNull(SUT.SelectedItem); Assert.AreEqual(-1, SUT.SelectedIndex); SUT.SelectedItem = 5; await WindowHelper.WaitForIdle(); Assert.IsNull(SUT.SelectedItem); Assert.AreEqual(-1, SUT.SelectedIndex); SUT.ItemsSource = items; await WindowHelper.WaitForIdle(); Assert.AreEqual(5, SUT.SelectedItem); Assert.AreEqual(5, SUT.SelectedIndex); } [TestMethod] public async Task When_Tabbed() { var SUT = new ComboBox { Items = { new ComboBoxItem { Content = new TextBox { Text = "item1" } }, new ComboBoxItem { Content = new TextBox { Text = "item2" } } } }; var btn = new Button(); var grid = new Grid { Children = { SUT, btn } }; WindowHelper.WindowContent = grid; await WindowHelper.WaitForIdle(); SUT.Focus(FocusState.Programmatic); await WindowHelper.WaitForIdle(); Assert.AreEqual(SUT, FocusManager.GetFocusedElement(SUT.XamlRoot)); await KeyboardHelper.Tab(); await WindowHelper.WaitForIdle(); Assert.AreEqual(btn, FocusManager.GetFocusedElement(SUT.XamlRoot)); } [TestMethod] public async Task When_Popup_Open_Tabbed() { var SUT = new ComboBox { Items = { new ComboBoxItem { Content = new TextBox { Text = "item1" } }, new ComboBoxItem { Content = new TextBox { Text = "item2" } } } }; var btn = new Button(); var grid = new Grid { Children = { SUT, btn } }; WindowHelper.WindowContent = grid; await WindowHelper.WaitForIdle(); SUT.Focus(FocusState.Programmatic); await WindowHelper.WaitForIdle(); Assert.AreEqual(SUT, FocusManager.GetFocusedElement(SUT.XamlRoot)); await KeyboardHelper.Space(); await WindowHelper.WaitForIdle(); Assert.IsTrue(SUT.IsDropDownOpen); Assert.IsTrue(FocusManager.GetFocusedElement(SUT.XamlRoot) is ComboBoxItem); await KeyboardHelper.Tab(); await WindowHelper.WaitForIdle(); Assert.IsFalse(SUT.IsDropDownOpen); Assert.AreEqual(btn, FocusManager.GetFocusedElement(SUT.XamlRoot)); } [TestMethod] public void When_Index_Is_Out_Of_Range_And_Later_Becomes_Valid() { var comboBox = new ComboBox(); comboBox.SelectedIndex = 2; Assert.AreEqual(-1, comboBox.SelectedIndex); comboBox.Items.Add(new ComboBoxItem()); Assert.AreEqual(-1, comboBox.SelectedIndex); comboBox.Items.Add(new ComboBoxItem()); Assert.AreEqual(-1, comboBox.SelectedIndex); comboBox.Items.Add(new ComboBoxItem()); Assert.AreEqual(2, comboBox.SelectedIndex); } [TestMethod] public void When_Index_Set_With_No_Items_Repeated() { var comboBox = new ComboBox(); comboBox.SelectedIndex = 1; Assert.AreEqual(-1, comboBox.SelectedIndex); comboBox.Items.Add(new ComboBoxItem()); Assert.AreEqual(-1, comboBox.SelectedIndex); comboBox.Items.Add(new ComboBoxItem()); Assert.AreEqual(1, comboBox.SelectedIndex); comboBox.Items.Clear(); Assert.AreEqual(-1, comboBox.SelectedIndex); comboBox.SelectedIndex = 2; comboBox.Items.Add(new ComboBoxItem()); Assert.AreEqual(-1, comboBox.SelectedIndex); comboBox.Items.Add(new ComboBoxItem()); Assert.AreEqual(-1, comboBox.SelectedIndex); comboBox.Items.Add(new ComboBoxItem()); Assert.AreEqual(2, comboBox.SelectedIndex); } [TestMethod] public void When_Index_Set_Out_Of_Range_When_Items_Exist() { var comboBox = new ComboBox(); comboBox.Items.Add(new ComboBoxItem()); Assert.ThrowsExactly<ArgumentException>(() => comboBox.SelectedIndex = 2); } [TestMethod] public void When_Index_Set_Negative_Out_Of_Range_When_Items_Exist() { var comboBox = new ComboBox(); comboBox.Items.Add(new ComboBoxItem()); Assert.ThrowsExactly<ArgumentException>(() => comboBox.SelectedIndex = -2); } [TestMethod] public void When_Index_Set_Negative_Out_Of_Range_When_Items_Do_Not_Exist() { var comboBox = new ComboBox(); comboBox.SelectedIndex = -2; Assert.AreEqual(-1, comboBox.SelectedIndex); comboBox.Items.Add(new ComboBoxItem()); Assert.AreEqual(-1, comboBox.SelectedIndex); } [TestMethod] public void When_Index_Is_Explicitly_Set_To_Negative_After_Out_Of_Range_Value() { var comboBox = new ComboBox(); comboBox.SelectedIndex = 2; Assert.AreEqual(-1, comboBox.SelectedIndex); comboBox.SelectedIndex = -1; // While SelectedIndex was already -1 (assert above), this *does* make a difference. comboBox.Items.Add(new ComboBoxItem()); Assert.AreEqual(-1, comboBox.SelectedIndex); comboBox.Items.Add(new ComboBoxItem()); Assert.AreEqual(-1, comboBox.SelectedIndex); comboBox.Items.Add(new ComboBoxItem()); Assert.AreEqual(-1, comboBox.SelectedIndex); // Will no longer become 2 } [TestMethod] public async Task When_Collection_Reset() { var SUT = new ComboBox(); try { WindowHelper.WindowContent = SUT; var c = new MyObservableCollection<string>(); c.Add("One"); c.Add("Two"); c.Add("Three"); SUT.ItemsSource = c; await WindowHelper.WaitForIdle(); Assert.AreEqual(3, SUT.Items.Count); using (c.BatchUpdate()) { c.Add("Four"); c.Add("Five"); } SUT.IsDropDownOpen = true; // Items are materialized when the popup is opened await WindowHelper.WaitForIdle(); Assert.AreEqual(5, SUT.Items.Count); Assert.IsNotNull(SUT.ContainerFromItem("One")); Assert.IsNotNull(SUT.ContainerFromItem("Four")); Assert.IsNotNull(SUT.ContainerFromItem("Five")); } finally { SUT.IsDropDownOpen = false; } } [TestMethod] public async Task When_ComboBoxItem_DataContext_Cleared() { // Arrange var stackPanel = new StackPanel(); stackPanel.DataContext = Guid.NewGuid().ToString(); var comboBox = new ComboBox(); var originalSource = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; comboBox.ItemsSource = originalSource; comboBox.SelectedIndex = 0; stackPanel.Children.Add(comboBox); WindowHelper.WindowContent = stackPanel; await WindowHelper.WaitForLoaded(stackPanel); FrameworkElement itemContainer = null; // Act comboBox.IsDropDownOpen = true; await WindowHelper.WaitFor(() => (itemContainer = comboBox.ContainerFromIndex(0) as ComboBoxItem) is not null); itemContainer.DataContextChanged += (s, e) => { // Assert Assert.AreNotEqual(stackPanel.DataContext, itemContainer.DataContext); }; comboBox.IsDropDownOpen = false; await WindowHelper.WaitForIdle(); comboBox.IsDropDownOpen = true; await WindowHelper.WaitForIdle(); comboBox.IsDropDownOpen = false; var updatedSource = new List<int>() { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; comboBox.ItemsSource = updatedSource; await WindowHelper.WaitForIdle(); comboBox.IsDropDownOpen = true; await WindowHelper.WaitForIdle(); comboBox.IsDropDownOpen = false; } [TestMethod] public async Task When_Binding_Change() { var SUT = new ComboBox(); try { WindowHelper.WindowContent = SUT; var c = new ObservableCollection<string>(); c.Add("One"); c.Add("Two"); c.Add("Three"); c.Add("Four"); c.Add("Five"); c.Add("Six"); c.Add("2-One"); c.Add("2-Two"); c.Add("2-Three"); c.Add("2-Four"); c.Add("2-Five"); c.Add("2-Six"); SUT.SetBinding(ComboBox.ItemsSourceProperty, new Microsoft.UI.Xaml.Data.Binding() { Path = new("MySource") }); SUT.SetBinding(ComboBox.SelectedItemProperty, new Microsoft.UI.Xaml.Data.Binding() { Path = new("SelectedItem"), Mode = Microsoft.UI.Xaml.Data.BindingMode.TwoWay }); SUT.DataContext = new { MySource = c, SelectedItem = "One" }; await WindowHelper.WaitForIdle(); SUT.IsDropDownOpen = true; await Task.Delay(100); WindowHelper.WindowContent = null; await Task.Delay(100); SUT.DataContext = null; await WindowHelper.WaitForIdle(); WindowHelper.WindowContent = SUT; SUT.DataContext = new { MySource = c, SelectedItem = "Two" }; Assert.AreEqual(12, SUT.Items.Count); } finally { SUT.IsDropDownOpen = false; } } #if HAS_UNO [TestMethod] public async Task When_Full_Collection_Reset() { var SUT = new ComboBox(); SUT.ItemTemplate = new DataTemplate(() => { var tb = new TextBlock(); tb.SetBinding(TextBlock.TextProperty, new Microsoft.UI.Xaml.Data.Binding { Path = "Text" }); tb.SetBinding(TextBlock.NameProperty, new Microsoft.UI.Xaml.Data.Binding { Path = "Text" }); return tb; }); try { WindowHelper.WindowContent = SUT; var c = new MyObservableCollection<ItemModel>(); c.Add(new ItemModel { Text = "One" }); c.Add(new ItemModel { Text = "Two" }); c.Add(new ItemModel { Text = "Three" }); SUT.ItemsSource = c; await WindowHelper.WaitForIdle(); SUT.IsDropDownOpen = true; await WindowHelper.WaitForIdle(); SUT.IsDropDownOpen = false; // Not required on WinUI. Fixing this in Uno requires porting ComboBox. await WindowHelper.WaitForIdle(); Assert.AreEqual(3, SUT.Items.Count); using (c.BatchUpdate()) { c.Clear(); c.Add(new ItemModel { Text = "Five" }); c.Add(new ItemModel { Text = "Six" }); c.Add(new ItemModel { Text = "Seven" }); } SUT.IsDropDownOpen = true; // Items are materialized when the popup is opened await WindowHelper.WaitForIdle(); Assert.AreEqual(3, SUT.Items.Count); Assert.IsNotNull(SUT.ContainerFromItem(c[0])); Assert.IsNotNull(SUT.ContainerFromItem(c[1])); Assert.IsNotNull(SUT.ContainerFromItem(c[2])); Assert.IsNotNull(SUT.FindName("Seven")); Assert.IsNotNull(SUT.FindName("Five")); Assert.IsNotNull(SUT.FindName("Six")); } finally { SUT.IsDropDownOpen = false; } } #endif #if HAS_UNO [TestMethod] public async Task When_Recycling_Explicit_Items() { var SUT = new ComboBox(); SUT.ItemTemplate = new DataTemplate(() => { var tb = new TextBlock(); tb.SetBinding(TextBlock.TextProperty, new Microsoft.UI.Xaml.Data.Binding { Path = "Text" }); tb.SetBinding(TextBlock.NameProperty, new Microsoft.UI.Xaml.Data.Binding { Path = "Text" }); return tb; }); try { WindowHelper.WindowContent = SUT; var c = new MyObservableCollection<ComboBoxItem>(); c.Add(new ComboBoxItem { Content = "One" }); c.Add(new ComboBoxItem { Content = "Two" }); c.Add(new ComboBoxItem { Content = "Three" }); SUT.ItemsSource = c; await WindowHelper.WaitForIdle(); SUT.IsDropDownOpen = true; await WindowHelper.WaitForIdle(); Assert.AreEqual(3, SUT.Items.Count); Assert.IsNotNull(SUT.ContainerFromItem(c[0])); Assert.IsNotNull(SUT.ContainerFromItem(c[1])); Assert.IsNotNull(SUT.ContainerFromItem(c[2])); Assert.AreEqual("One", c[0].Content); Assert.AreEqual("Two", c[1].Content); Assert.AreEqual("Three", c[2].Content); await WindowHelper.WaitForIdle(); SUT.IsDropDownOpen = false; await WindowHelper.WaitForIdle(); // Open again to ensure that the items are recycled SUT.IsDropDownOpen = true; await WindowHelper.WaitForIdle(); Assert.AreEqual(3, SUT.Items.Count); Assert.IsNotNull(SUT.ContainerFromItem(c[0])); Assert.IsNotNull(SUT.ContainerFromItem(c[1])); Assert.IsNotNull(SUT.ContainerFromItem(c[2])); Assert.AreEqual("One", c[0].Content); Assert.AreEqual("Two", c[1].Content); Assert.AreEqual("Three", c[2].Content); } finally { SUT.IsDropDownOpen = false; } } #endif #if HAS_UNO [TestMethod] public async Task When_SelectedItem_TwoWay_Binding() { var itemsControl = new ItemsControl() { ItemsPanel = new ItemsPanelTemplate(() => new StackPanel()), ItemTemplate = new DataTemplate(() => { var comboBox = new ComboBox(); comboBox.Name = "combo"; comboBox.SetBinding(ComboBox.ItemsSourceProperty, new Binding { Path = new("Numbers") }); comboBox.SetBinding( ComboBox.SelectedItemProperty, new Binding { Path = new("SelectedNumber"), Mode = BindingMode.TwoWay }); return comboBox; }) }; var test = new[] { new TwoWayBindingItem() }; WindowHelper.WindowContent = itemsControl; itemsControl.ItemsSource = test; await WindowHelper.WaitForIdle(); var comboBox = itemsControl.FindName("combo") as ComboBox; Assert.AreEqual(3, test[0].SelectedNumber); Assert.AreEqual(3, comboBox.SelectedItem); } #endif [TestMethod] [RunsOnUIThread] public async Task When_SelectedItem_Active_VisualState() { var source = Enumerable.Range(0, 10).ToArray(); var SUT = new ComboBox { ItemsSource = source, ItemContainerStyle = ComboBoxItemContainerStyle, ItemTemplate = CounterItemTemplate }; SUT.SelectedItem = 2; WindowHelper.WindowContent = SUT; await WindowHelper.WaitForLoaded(SUT); try { // force ItemsPanel to materialized, otherwise ContainerFromIndex will always return 0 // and also while closed, the CBI's "CommonStates" will be forced to "Normal". // at least, _should be_ forced to "Normal" as winui suggests. SUT.IsDropDownOpen = true; await WindowHelper.WaitForIdle(); var container2 = SUT.ContainerFromItem(SUT.SelectedItem) as SelectorItem; Assert.IsNotNull(container2, "failed to resolve container#2"); var container2States = VisualStateHelper.GetCurrentVisualStateName(container2).ToArray(); Assert.IsTrue(container2States.Any(x => x.Contains("Selected")), $"container#2 is not selected: states={container2States.JoinBy("|")}"); // changing selection to 6 SUT.SelectedItem = 6; await WindowHelper.WaitForIdle(); var container6 = SUT.ContainerFromItem(SUT.SelectedItem) as SelectorItem; Assert.IsNotNull(container6, "failed to resolve container#6"); var container2PostStates = VisualStateHelper.GetCurrentVisualStateName(container2).ToArray(); var container6PostStates = VisualStateHelper.GetCurrentVisualStateName(container6).ToArray(); Assert.IsFalse(container2PostStates.Any(x => x.Contains("Selected")), $"container#2 is still selected: states={container2PostStates.JoinBy("|")}"); Assert.IsTrue(container6PostStates.Any(x => x.Contains("Selected")), $"container#6 is not selected: states={container6PostStates.JoinBy("|")}"); } finally { SUT.IsDropDownOpen = false; } } #if HAS_UNO [TestMethod] [RequiresFullWindow] [RunsOnUIThread] [Ignore("Test is not valid - the Popup is not actually rendered in the screenshots")] public async Task When_Mouse_Opened_And_Closed() { // Create a comboBox with some sample items ComboBox comboBox = new ComboBox(); for (int i = 0; i < 10; i++) { comboBox.Items.Add(i); } var stackPanel = new StackPanel() { Orientation = Orientation.Horizontal, Spacing = 10, Padding = new Thickness(10), VerticalAlignment = VerticalAlignment.Top }; var text = new TextBlock() { Text = "Click me", VerticalAlignment = VerticalAlignment.Top }; stackPanel.Children.Add(comboBox); stackPanel.Children.Add(text); // Set the comboBox as Window content WindowHelper.WindowContent = stackPanel; // Wait for it to load await WindowHelper.WaitForLoaded(comboBox); comboBox.SelectedItem = 5; await WindowHelper.WaitForIdle(); // Take a screenshot of the comboBox before opening var screenshotBefore = await TakeScreenshot(stackPanel); // Use input injection to tap the comboBox and open the popup var comboBoxCenter = comboBox.GetAbsoluteBounds().GetCenter(); using var finger = InputInjector.TryCreate().GetFinger(); finger.MoveTo(comboBoxCenter); finger.Press(comboBoxCenter); await WindowHelper.WaitForIdle(); finger.Release(); // Wait for the popup to load and render await WindowHelper.WaitFor(() => VisualTreeHelper.GetOpenPopupsForXamlRoot(WindowHelper.XamlRoot).Count > 0); await WindowHelper.WaitForIdle(); // Take a screenshot of the UI after opening the comboBox var screenshotOpened = await TakeScreenshot(stackPanel); // Verify that the UI changed await ImageAssert.AreNotEqualAsync(screenshotBefore, screenshotOpened); var textCenter = text.GetAbsoluteBounds().GetCenter(); finger.Press(textCenter.X, textCenter.Y + 100); finger.Release(); await WindowHelper.WaitForIdle(); // Wait for the popup to close and the UI to stabilize // Take a screenshot of the UI after closing the comboBox var screenshotAfter = await TakeScreenshot(stackPanel); // Verify that the UI looks the same as at the beginning await ImageAssert.AreSimilarAsync(screenshotBefore, screenshotAfter); } [TestMethod] [RequiresFullWindow] [RunsOnUIThread] [Ignore("Test is not valid - the Popup is not actually rendered in the screenshots")] public async Task When_Mouse_Opened_And_Closed_Uwp() { using var _ = StyleHelper.UseUwpStyles(); await When_Mouse_Opened_And_Closed(); } private async Task<RawBitmap> TakeScreenshot(FrameworkElement SUT) { var renderer = new RenderTargetBitmap(); await renderer.RenderAsync(SUT); var result = await RawBitmap.From(renderer, SUT); return result; } #endif [TestMethod] public async Task When_SelectedItem_TwoWay_Binding_Clear() { var root = new Grid(); var comboBox = new ComboBox(); root.Children.Add(comboBox); comboBox.SetBinding(ComboBox.ItemsSourceProperty, new Binding { Path = new("Items") }); comboBox.SetBinding(ComboBox.SelectedItemProperty, new Binding { Path = new("Item"), Mode = BindingMode.TwoWay }); WindowHelper.WindowContent = root; var dc = new TwoWayBindingClearViewModel(); root.DataContext = dc; await WindowHelper.WaitForIdle(); dc.Dispose(); root.DataContext = null; Assert.AreEqual(1, dc.ItemGetCount); Assert.AreEqual(1, dc.ItemSetCount); } [TestMethod] [CombinatorialData] public async Task When_ComboBox_IsTextSearchEnabled_DropDown_Closed(bool isTextSearchEnabled) { var comboBox = new ComboBox(); comboBox.Items.Add("Cat"); comboBox.Items.Add("Dog"); comboBox.Items.Add("Rabbit"); comboBox.Items.Add("Elephant"); // Assert the default value of IsTextSearchEnabled. Assert.IsTrue(comboBox.IsTextSearchEnabled); // Set the isTextSearchEnabled value being tested. comboBox.IsTextSearchEnabled = isTextSearchEnabled; await UITestHelper.Load(comboBox); comboBox.Focus(FocusState.Programmatic); Assert.AreEqual(-1, comboBox.SelectedIndex); Assert.IsFalse(comboBox.IsDropDownOpen); await KeyboardHelper.PressKeySequence("$d$_r#$u$_r"); var expectedSelectedIndex = isTextSearchEnabled ? 2 : -1; var expectedSelectedItem = isTextSearchEnabled ? "Rabbit" : null; Assert.AreEqual(expectedSelectedIndex, comboBox.SelectedIndex); Assert.AreEqual(expectedSelectedItem, comboBox.SelectedItem); } [TestMethod] [CombinatorialData] public async Task When_ComboBox_IsTextSearchEnabled_DropDown_Opened(bool isTextSearchEnabled) { var comboBox = new ComboBox(); comboBox.Items.Add("Cat"); comboBox.Items.Add("Dog"); comboBox.Items.Add("Rabbit"); comboBox.Items.Add("Elephant"); comboBox.SelectedIndex = 3; // Assert the default value of IsTextSearchEnabled. Assert.IsTrue(comboBox.IsTextSearchEnabled); // Set the isTextSearchEnabled value being tested. comboBox.IsTextSearchEnabled = isTextSearchEnabled; await UITestHelper.Load(comboBox); comboBox.Focus(FocusState.Programmatic); comboBox.IsDropDownOpen = true; await WindowHelper.WaitForIdle(); Assert.AreEqual(3, comboBox.SelectedIndex); await KeyboardHelper.PressKeySequence("$d$_r#$u$_r"); var expectedSelectedIndex = isTextSearchEnabled ? 2 : 3; var expectedSelectedItem = isTextSearchEnabled ? "Rabbit" : "Elephant"; Assert.AreEqual(expectedSelectedIndex, comboBox.SelectedIndex); Assert.AreEqual(expectedSelectedItem, comboBox.SelectedItem); Assert.IsTrue(comboBox.IsDropDownOpen); await KeyboardHelper.Space(); Assert.AreEqual(isTextSearchEnabled, comboBox.IsDropDownOpen); await Task.Delay(1100); // Make sure to wait enough so that HasSearchStringTimedOut becomes true. await KeyboardHelper.Space(); Assert.AreEqual(!isTextSearchEnabled, comboBox.IsDropDownOpen); } [TestMethod] [RequiresFullWindow] [RunsOnUIThread] [DataRow(PopupPlacementMode.Bottom, 0)] [DataRow(PopupPlacementMode.Top, 0)] [DataRow(PopupPlacementMode.Bottom, 20)] [DataRow(PopupPlacementMode.Top, -20)] [GitHubWorkItem("https://github.com/unoplatform/nventive-private/issues/509")] #if RUNTIME_NATIVE_AOT [Ignore("DataRowAttribute.GetData() wraps data in an extra array under NativeAOT; not yet understood why.")] #endif // RUNTIME_NATIVE_AOT public async Task When_Customized_Popup_Placement(PopupPlacementMode mode, double verticalOffset) { var grid = new Grid(); var comboBox = new PopupPlacementComboBox(); comboBox.Margin = new Thickness(150, 150, 0, 0); // Add items as itmes source comboBox.ItemsSource = new List<string> { "Cat", "Dog" }; comboBox.DesiredPlacement = mode; comboBox.VerticalOffset = verticalOffset; grid.Children.Add(comboBox); try { TestServices.WindowHelper.WindowContent = grid; await TestServices.WindowHelper.WaitForLoaded(comboBox); comboBox.ApplyPlacement(); comboBox.IsDropDownOpen = true; await WindowHelper.WaitForIdle(); var popup = VisualTreeHelper.GetOpenPopupsForXamlRoot(comboBox.XamlRoot).FirstOrDefault(); Assert.IsNotNull(popup); var child = (FrameworkElement)popup.Child; await WindowHelper.WaitFor(() => child.ActualHeight > 0); var popupBounds = child.TransformToVisual(null).TransformBounds(new Rect(0, 0, child.ActualWidth, child.ActualHeight)); var comboBoxBounds = comboBox.TransformToVisual(null).TransformBounds(new Rect(0, 0, comboBox.ActualWidth, comboBox.ActualHeight)); // For some reason WinUI's ComboBox popup border has a -1 vertical Margin, which pushes it up by 1 pixel, and can be inacurrate due to rounding double tolerance = 1.5; if (mode == PopupPlacementMode.Bottom) { Assert.AreEqual(comboBoxBounds.Bottom + verticalOffset, popupBounds.Top, tolerance); } else { Assert.AreEqual(comboBoxBounds.Top + verticalOffset, popupBounds.Bottom, tolerance); } } finally { comboBox.IsDropDownOpen = false; } } [TestMethod] [RunsOnUIThread] public async Task When_Items_Are_Enum_Values() { var comboBox = new ComboBox(); comboBox.ItemsSource = Enum.GetValues<PickerLocationId>(); comboBox.SelectedIndex = 0; TestServices.WindowHelper.WindowContent = comboBox; await TestServices.WindowHelper.WaitForLoaded(comboBox); await ComboBoxHelper.OpenComboBox(comboBox, ComboBoxHelper.OpenMethod.Programmatic); await TestServices.WindowHelper.WaitForIdle(); Assert.IsTrue(comboBox.IsDropDownOpen); await TestServices.WindowHelper.WaitForIdle(); var popup = VisualTreeHelper.GetOpenPopupsForXamlRoot(comboBox.XamlRoot).FirstOrDefault(); Assert.IsNotNull(popup); var child = (FrameworkElement)popup.Child; var comboBoxItems = child.GetAllChildren().OfType<ComboBoxItem>().ToArray(); Assert.AreEqual(Enum.GetValues<PickerLocationId>().Length, comboBoxItems.Length); } #if HAS_UNO [TestMethod] [RunsOnUIThread] public async Task When_ComboPopup_Rearrange_ScrollShouldNotReset() { var SUT = new ComboBox() { ItemsSource = Enumerable.Range(0, 50).Select(x => $"Item {x}").ToArray(), SelectedIndex = 0, }; await UITestHelper.Load(SUT); // open down-drop SUT.IsDropDownOpen = true; var host = SUT.GetTemplateChild<Border>("PopupBorder") ?? throw new InvalidOperationException("Failed to find Border#PopupBorder"); await WindowHelper.WaitForLoaded(host); await UITestHelper.WaitForIdle(); // scroll to 2 screens away var sv = host.Child as ScrollViewer ?? throw new InvalidOperationException("Failed to find Border#PopupBorder>ScrollViewer"); var origin = sv.VerticalOffset; var destination = origin + sv.ViewportHeight * 2; sv.ChangeView(null, verticalOffset: destination, null, disableAnimation: true); await UITestHelper.WaitForIdle(); Assert.IsTrue(Math.Abs(destination - sv.VerticalOffset) < 1.0, $"Expect sv.VerticalOffset to be near {destination:0.##}, got: {sv.VerticalOffset:0.##}"); // force an arrange var cbi = sv.FindFirstChild<ComboBoxItem>(); cbi.InvalidateArrange(); await UITestHelper.WaitForIdle(); Assert.IsTrue(Math.Abs(destination - sv.VerticalOffset) < 1.0, $"Expect sv.VerticalOffset to be still near {destination:0.##}, got: {sv.VerticalOffset:0.##}"); } #endif #if __SKIA__ // Requires input injection [TestMethod] [RequiresFullWindow] [RunsOnUIThread] [GitHubWorkItem("https://github.com/unoplatform/uno/issues/15531")] public async Task When_Tap_Twice() { var grid = new Grid(); var comboBox = new PopupPlacementComboBox(); comboBox.Margin = new Thickness(200); // Add items as itmes source comboBox.ItemsSource = new List<string> { "Cat", "Dog", "Rabbit", "Elephant" }; comboBox.DesiredPlacement = PopupPlacementMode.Bottom; comboBox.VerticalOffset = 50; grid.Children.Add(comboBox); try { TestServices.WindowHelper.WindowContent = grid; await TestServices.WindowHelper.WaitForLoaded(comboBox); comboBox.ApplyPlacement(); TestServices.InputHelper.Tap(comboBox); await WindowHelper.WaitForIdle(); Assert.IsTrue(comboBox.IsDropDownOpen); TestServices.InputHelper.Tap(comboBox); await WindowHelper.WaitForIdle(); Assert.IsFalse(comboBox.IsDropDownOpen); } finally { comboBox.IsDropDownOpen = false; } } #endif [TestMethod] public async Task When_ComboBox_Popup_Dismissed() { // test case built against https://github.com/unoplatform/uno/issues/20014 var sut = new ComboBox() { ItemsSource = Enumerable.Range(0, 3).ToArray(), Visibility = Visibility.Collapsed, }; // load the collapsed control into the visual tree await UITestHelper.Load(sut, x => x.IsLoaded); // then let it become visible sut.Visibility = Visibility.Visible; await UITestHelper.WaitForLoaded(sut); var popup = sut.FindFirstDescendantOrThrow<Popup>("Popup"); // focus the control // This is required, otherwise DropDownClosed would be triggered by focus shift instead, which is not what we are testing here. // [ComboBox > ComboBoxItem > ComboBox] doesnt trigger that mechanism, but [other-control > ComboBoxItem > ComboBox] will do. // We are trying to validate if the ComboBox properly subscribes to the Popup::Closed event, and in turn raises DropDownClosed. sut.Focus(FocusState.Programmatic); // open the popup sut.IsDropDownOpen = true; await UITestHelper.WaitFor(() => popup.IsOpen, timeoutMS: 2000, "timed out waiting on the popup to open"); // track event firing var dropDownClosedFired = false; sut.DropDownClosed += (s, e) => dropDownClosedFired = true; // close the popup as if the user had light-dismissed it popup.IsOpen = false; await UITestHelper.WaitForIdle(); Assert.IsFalse(sut.IsDropDownOpen, "ComboBox.IsDropDownOpen is still true"); Assert.IsTrue(dropDownClosedFired, "DropDownClosed event was not fired"); } [TestMethod] [PlatformCondition(ConditionMode.Exclude, RuntimeTestPlatforms.NativeIOS | RuntimeTestPlatforms.NativeAndroid)] // https://github.com/unoplatform/uno-private/issues/1297 public Task When_ComboBox_ScrollIntoView_SelectedItem() => When_ComboBox_ScrollIntoView_Selection(viaIndex: false); [TestMethod] [PlatformCondition(ConditionMode.Exclude, RuntimeTestPlatforms.NativeIOS | RuntimeTestPlatforms.NativeAndroid)] // https://github.com/unoplatform/uno-private/issues/1297 public Task When_ComboBox_ScrollIntoView_SelectedIndex() => When_ComboBox_ScrollIntoView_Selection(viaIndex: true); private async Task When_ComboBox_ScrollIntoView_Selection(bool viaIndex) { var source = ( // 12x20=240 items, enough to overflow from a in "qwerasdfzxcv" from b in Enumerable.Range(0, 20) select string.Concat(a, b) ).ToArray(); var sut = new ComboBox { ItemsSource = source, }; await UITestHelper.Load(sut, x => x.IsLoaded); var popup = sut.FindFirstDescendantOrThrow<Popup>("Popup"); // open the popup sut.IsDropDownOpen = true; await UITestHelper.WaitFor(() => popup.IsOpen, timeoutMS: 2000, "timed out waiting on the popup to open"); // wait until the dropdown panel is ready await UITestHelper.WaitFor(() => sut.ItemsPanelRoot is { }, timeoutMS: 2000, "timed out waiting on the ItemsPanelRoot"); // set selection if (viaIndex) { sut.SelectedIndex = source.Length - 3; } else { sut.SelectedItem = source[^3]; } await UITestHelper.WaitForIdle(); // sanity check Assert.AreEqual(source.Length - 3, sut.SelectedIndex, "SelectedIndex should be the 3rd last"); Assert.AreEqual(source[^3], sut.SelectedItem, "SelectedItem should be the 3rd last"); var sv = sut.ItemsPanelRoot.FindFirstAncestorOrThrow<ScrollViewer>(); var cbi = sut.ContainerFromIndex(sut.SelectedIndex) as FrameworkElement; Assert.IsNotNull(cbi, "Selected container should not be null"); var cbiAbsRect = new Rect(cbi.ActualOffset.X, cbi.ActualOffset.Y, cbi.ActualWidth, cbi.ActualHeight); var viewportAbsRect = new Rect(sv.HorizontalOffset, sv.VerticalOffset, sv.ViewportWidth, sv.ViewportHeight); var intersection = viewportAbsRect; intersection.Intersect(cbiAbsRect); Assert.IsTrue(cbiAbsRect == intersection, $"Selected container should be fully within viewport: CBI={PrettyPrint.FormatRect(cbiAbsRect)}, VP={PrettyPrint.FormatRect(viewportAbsRect)}"); }
Given_ComboBox
csharp
dotnet__machinelearning
src/Microsoft.ML.Transforms/RandomFourierFeaturizing.cs
{ "start": 30570, "end": 30866 }
internal static class ____ { public const int Rank = 1000; public const bool UseCosAndSinBases = false; } /// <summary> /// Describes how the transformer handles one Gcn column pair. /// </summary> [BestFriend]
Defaults
csharp
MonoGame__MonoGame
MonoGame.Framework.Content.Pipeline/Serialization/Compiler/EnumWriter.cs
{ "start": 448, "end": 509 }
enum ____ to write.</typeparam> [ContentTypeWriter]
type
csharp
nunit__nunit
src/NUnitFramework/framework/Interfaces/TestOutput.cs
{ "start": 308, "end": 2832 }
public class ____ { /// <summary> /// Construct with text, output destination type and /// the name of the test that produced the output. /// </summary> /// <param name="text">Text to be output</param> /// <param name="stream">Name of the stream or channel to which the text should be written</param> /// <param name="testId">Id of the test that produced the output</param> /// <param name="testName">FullName of test that produced the output</param> public TestOutput(string text, string stream, string? testId, string? testName) { Guard.ArgumentNotNull(text, nameof(text)); Guard.ArgumentNotNull(stream, nameof(stream)); Text = text; Stream = stream; TestId = testId; TestName = testName; } /// <summary> /// Return string representation of the object for debugging /// </summary> /// <returns></returns> public override string ToString() { return Stream + ": " + Text; } /// <summary> /// Get the text /// </summary> public string Text { get; } /// <summary> /// Get the output type /// </summary> public string Stream { get; } /// <summary> /// Get the name of the test that created the output /// </summary> public string? TestName { get; } /// <summary> /// Get the id of the test that created the output /// </summary> public string? TestId { get; } /// <summary> /// Convert the TestOutput object to an XML string /// </summary> public string ToXml() { using var stringWriter = new StringWriter(); using (var writer = XmlWriter.Create(stringWriter, XmlExtensions.FragmentWriterSettings)) { ToXml(writer); } return stringWriter.ToString(); } internal void ToXml(XmlWriter writer) { writer.WriteStartElement("test-output"); writer.WriteAttributeString("stream", Stream); if (TestId is not null) writer.WriteAttributeString("testid", TestId); if (TestName is not null) writer.WriteAttributeStringSafe("testname", TestName); writer.WriteCDataSafe(Text); writer.WriteEndElement(); } } }
TestOutput
csharp
Cysharp__UniTask
src/UniTask/Assets/Plugins/UniTask/Runtime/EnumerableAsyncExtensions.cs
{ "start": 181, "end": 1146 }
public static class ____ { // overload resolver - .Select(async x => { }) : IEnumerable<UniTask<T>> public static IEnumerable<UniTask> Select<T>(this IEnumerable<T> source, Func<T, UniTask> selector) { return System.Linq.Enumerable.Select(source, selector); } public static IEnumerable<UniTask<TR>> Select<T, TR>(this IEnumerable<T> source, Func<T, UniTask<TR>> selector) { return System.Linq.Enumerable.Select(source, selector); } public static IEnumerable<UniTask> Select<T>(this IEnumerable<T> source, Func<T, int, UniTask> selector) { return System.Linq.Enumerable.Select(source, selector); } public static IEnumerable<UniTask<TR>> Select<T, TR>(this IEnumerable<T> source, Func<T, int, UniTask<TR>> selector) { return System.Linq.Enumerable.Select(source, selector); } } }
EnumerableAsyncExtensions
csharp
nunit__nunit
src/NUnitFramework/tests/Internal/Execution/ParallelExecutionTests.cs
{ "start": 567, "end": 23360 }
public class ____ : ITestListener { private readonly TestSuite _testSuite; private readonly Expectations _expectations; private ConcurrentQueue<TestEvent> _events; private TestResult _result; private IEnumerable<TestEvent> AllEvents => _events.AsEnumerable(); private IEnumerable<TestEvent> ShiftEvents => AllEvents.Where(e => e.Action == TestAction.ShiftStarted || e.Action == TestAction.ShiftFinished); private IEnumerable<TestEvent> TestEvents => AllEvents.Where(e => e.Action == TestAction.TestStarting || e.Action == TestAction.TestFinished); public ParallelExecutionTests(TestSuite testSuite, Expectations expectations) { _testSuite = testSuite; _expectations = expectations; } [OneTimeSetUp] public void RunTestSuite() { _events = new ConcurrentQueue<TestEvent>(); var dispatcher = new ParallelWorkItemDispatcher(4); var context = new TestExecutionContext { Dispatcher = dispatcher, Listener = this }; dispatcher.ShiftStarting += (shift) => { _events.Enqueue(new TestEvent() { Action = TestAction.ShiftStarted, ShiftName = shift.Name }); }; dispatcher.ShiftFinished += (shift) => { _events.Enqueue(new TestEvent() { Action = TestAction.ShiftFinished, ShiftName = shift.Name }); }; var workItem = TestBuilder.CreateWorkItem(_testSuite, context); dispatcher.Start(workItem); workItem.WaitForCompletion(); _result = workItem.Result; } [Test] public void AllTestsPassed() { if (_result.ResultState != ResultState.Success || _result.PassCount != _testSuite.TestCaseCount) Assert.Fail(DumpEvents("Not all tests passed")); } [Test] public void OnlyOneShiftIsActiveAtSameTime() { int count = 0; foreach (var e in _events) { if (e.Action == TestAction.ShiftStarted && ++count > 1) Assert.Fail(DumpEvents("Shift started while another shift was active")); if (e.Action == TestAction.ShiftFinished) --count; } } [Test] public void CorrectInitialShift() { string expected = "NonParallel"; if (_testSuite.Properties.ContainsKey(PropertyNames.ParallelScope)) { var scope = (ParallelScope)_testSuite.Properties.Get(PropertyNames.ParallelScope)!; if ((scope & ParallelScope.Self) != 0) expected = "Parallel"; } var e = _events.First(); Assert.That(e.Action, Is.EqualTo(TestAction.ShiftStarted)); Assert.That(e.ShiftName, Is.EqualTo(expected)); } [Test] public void TestsRunOnExpectedWorkers() { Assert.Multiple(() => { foreach (var e in TestEvents) _expectations.Verify(e); }); } #region Test Data private static IEnumerable<TestFixtureData> GetParallelSuites() { const string nonParallelWorker = "NUnit.Fw.NonParallelWorker"; const string parallelWorker = "NUnit.Fw.ParallelWorker"; yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("NUnit") .Containing(Suite("Tests") .Containing(Fixture(typeof(TestFixture1))))), Expecting( That("fake-assembly.dll").RunsOn(nonParallelWorker), That("NUnit").RunsOn(nonParallelWorker), That("Tests").RunsOn(nonParallelWorker), That("TestFixture1").RunsOn(nonParallelWorker), That("TestFixture1_Test").RunsOn(nonParallelWorker))) .SetName("SingleFixture_Default"); yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("NUnit") .Containing(Suite("Tests") .Containing(Fixture(typeof(TestFixture1)).NonParallelizable()))), Expecting( That("fake-assembly.dll").RunsOn(nonParallelWorker), That("NUnit").RunsOn(nonParallelWorker), That("Tests").RunsOn(nonParallelWorker), That("TestFixture1").RunsOn(nonParallelWorker), That("TestFixture1_Test").RunsOn(nonParallelWorker))) .SetName("SingleFixture_NonParallelizable"); yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("NUnit") .Containing(Suite("Tests") .Containing(Fixture(typeof(TestFixture1)).Parallelizable()))), Expecting( That("fake-assembly.dll").StartsOn(nonParallelWorker).FinishesOn(parallelWorker), That("NUnit").StartsOn(nonParallelWorker).FinishesOn(parallelWorker), That("Tests").StartsOn(nonParallelWorker).FinishesOn(parallelWorker), That("TestFixture1").RunsOn(parallelWorker), That("TestFixture1_Test").RunsOn(parallelWorker))) .SetName("SingleFixture_Parallelizable"); yield return new TestFixtureData( Suite("fake-assembly.dll").NonParallelizable() .Containing(Suite("NUnit") .Containing(Suite("Tests") .Containing(Fixture(typeof(TestFixture1))))), Expecting( That("fake-assembly.dll").RunsOn(nonParallelWorker), That("NUnit").RunsOn(nonParallelWorker), That("Tests").RunsOn(nonParallelWorker), That("TestFixture1").RunsOn(nonParallelWorker), That("TestFixture1_Test").RunsOn(nonParallelWorker))) .SetName("SingleFixture_AssemblyNonParallelizable"); yield return new TestFixtureData( Suite("fake-assembly.dll").Parallelizable() .Containing(Suite("NUnit") .Containing(Suite("Tests") .Containing(Fixture(typeof(TestFixture1))))), Expecting( That("fake-assembly.dll").StartsOn(parallelWorker).FinishesOn(nonParallelWorker), That("NUnit").StartsOn(parallelWorker).FinishesOn(nonParallelWorker), That("Tests").StartsOn(parallelWorker).FinishesOn(nonParallelWorker), That("TestFixture1").RunsOn(nonParallelWorker), That("TestFixture1_Test").RunsOn(nonParallelWorker))) .SetName("SingleFixture_AssemblyParallelizable"); yield return new TestFixtureData( Suite("fake-assembly.dll").Parallelizable() .Containing(Suite("NUnit") .Containing(Suite("Tests") .Containing(Fixture(typeof(TestFixture1)).Parallelizable()))), Expecting( That("fake-assembly.dll").RunsOn(parallelWorker), That("NUnit").RunsOn(parallelWorker), That("Tests").RunsOn(parallelWorker), That("TestFixture1").RunsOn(parallelWorker), That("TestFixture1_Test").RunsOn(parallelWorker))) .SetName("SingleFixture_AssemblyAndFixtureParallelizable"); yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("NUnit") .Containing(Suite("Tests") .Containing(Fixture(typeof(TestFixtureWithParallelParameterizedTest))))), Expecting( That("fake-assembly.dll").RunsOn(nonParallelWorker), That("NUnit").RunsOn(nonParallelWorker), That("Tests").RunsOn(nonParallelWorker), That("TestFixtureWithParallelParameterizedTest").RunsOn(nonParallelWorker), That("ParameterizedTest").StartsOn(nonParallelWorker).FinishesOn(parallelWorker), That("ParameterizedTest(1)").RunsOn(parallelWorker), That("ParameterizedTest(2)").RunsOn(parallelWorker), That("ParameterizedTest(3)").RunsOn(parallelWorker))) .SetName("SingleFixture_ParameterizedTest"); yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("NUnit") .Containing(Suite("TestData") .Containing(Fixture(typeof(SetUpFixture1)) .Containing( Fixture(typeof(TestFixture1)), Fixture(typeof(TestFixture2)), Fixture(typeof(TestFixture3)))))), Expecting( That("fake-assembly.dll").RunsOn(nonParallelWorker), That("NUnit").RunsOn(nonParallelWorker), That("TestData").RunsOn(nonParallelWorker), That("ParallelExecutionData").RunsOn(nonParallelWorker), // SetUpFixture1 That("TestFixture1").RunsOn(nonParallelWorker), That("TestFixture1_Test").RunsOn(nonParallelWorker), That("TestFixture2").RunsOn(nonParallelWorker), That("TestFixture2_Test").RunsOn(nonParallelWorker), That("TestFixture3").RunsOn(nonParallelWorker), That("TestFixture3_Test").RunsOn(nonParallelWorker))) .SetName("ThreeFixtures_SetUpFixture_Default"); yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("NUnit") .Containing(Suite("TestData") .Containing(Fixture(typeof(SetUpFixture1)) .Containing( Fixture(typeof(TestFixture1)).Parallelizable(), Fixture(typeof(TestFixture2)), Fixture(typeof(TestFixture3)).Parallelizable())))), Expecting( That("fake-assembly.dll").RunsOn(nonParallelWorker), That("NUnit").RunsOn(nonParallelWorker), That("TestData").RunsOn(nonParallelWorker), That("ParallelExecutionData").RunsOn(nonParallelWorker), // SetUpFixture1 That("TestFixture1").RunsOn(parallelWorker), That("TestFixture1_Test").RunsOn(parallelWorker), That("TestFixture2").RunsOn(nonParallelWorker), That("TestFixture2_Test").RunsOn(nonParallelWorker), That("TestFixture3").RunsOn(parallelWorker), That("TestFixture3_Test").RunsOn(parallelWorker))) .SetName("ThreeFixtures_TwoParallelizable_SetUpFixture"); yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("NUnit") .Containing(Suite("TestData") .Containing(Fixture(typeof(SetUpFixture1)).Parallelizable() .Containing( Fixture(typeof(TestFixture1)).Parallelizable(), Fixture(typeof(TestFixture2)), Fixture(typeof(TestFixture3)).Parallelizable())))), Expecting( That("fake-assembly.dll").StartsOn(nonParallelWorker), That("NUnit").StartsOn(nonParallelWorker), That("TestData").StartsOn(nonParallelWorker), That("ParallelExecutionData").RunsOn(parallelWorker), // SetUpFixture1 That("TestFixture1").RunsOn(parallelWorker), That("TestFixture1_Test").RunsOn(parallelWorker), That("TestFixture2").RunsOn(nonParallelWorker), That("TestFixture2_Test").RunsOn(nonParallelWorker), That("TestFixture3").RunsOn(parallelWorker), That("TestFixture3_Test").RunsOn(parallelWorker))) .SetName("ThreeFixtures_TwoParallelizable_ParallelizableSetUpFixture"); yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("NUnit") .Containing(Suite("TestData") .Containing(Fixture(typeof(SetUpFixture1)).Parallelizable() .Containing(Fixture(typeof(SetUpFixture2)).Parallelizable() .Containing( Fixture(typeof(TestFixture1)).Parallelizable(), Fixture(typeof(TestFixture2)), Fixture(typeof(TestFixture3)).Parallelizable()))))), Expecting( That("fake-assembly.dll").StartsOn(nonParallelWorker), That("NUnit").StartsOn(nonParallelWorker), That("TestData").StartsOn(nonParallelWorker), That("ParallelExecutionData").RunsOn(parallelWorker), // SetUpFixture1 && SetUpFixture2 That("TestFixture1").RunsOn(parallelWorker), That("TestFixture1_Test").RunsOn(parallelWorker), That("TestFixture2").RunsOn(nonParallelWorker), That("TestFixture2_Test").RunsOn(nonParallelWorker), That("TestFixture3").RunsOn(parallelWorker), That("TestFixture3_Test").RunsOn(parallelWorker))) .SetName("ThreeFixtures_TwoSetUpFixturesInSameNamespace_BothParallelizable"); yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("NUnit") .Containing(Suite("TestData") .Containing(Fixture(typeof(SetUpFixture1)) .Containing(Fixture(typeof(SetUpFixture2)) .Containing( Fixture(typeof(TestFixture1)).Parallelizable(), Fixture(typeof(TestFixture2)), Fixture(typeof(TestFixture3)).Parallelizable()))))), Expecting( That("fake-assembly.dll").RunsOn(nonParallelWorker), That("NUnit").RunsOn(nonParallelWorker), That("TestData").RunsOn(nonParallelWorker), That("ParallelExecutionData").RunsOn("*"), // SetUpFixture1 && SetUpFixture2 That("TestFixture1").RunsOn(parallelWorker), That("TestFixture1_Test").RunsOn(parallelWorker), That("TestFixture2").RunsOn(nonParallelWorker), That("TestFixture2_Test").RunsOn(nonParallelWorker), That("TestFixture3").RunsOn(parallelWorker), That("TestFixture3_Test").RunsOn(parallelWorker))) .SetName("ThreeFixtures_TwoSetUpFixturesInSameNamespace_NeitherParallelizable"); yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("NUnit") .Containing(Suite("TestData") .Containing(Fixture(typeof(SetUpFixture1)).Parallelizable() .Containing(Fixture(typeof(SetUpFixture2)) .Containing( Fixture(typeof(TestFixture1)).Parallelizable(), Fixture(typeof(TestFixture2)), Fixture(typeof(TestFixture3)).Parallelizable()))))), Expecting( That("fake-assembly.dll").StartsOn(nonParallelWorker), That("NUnit").StartsOn(nonParallelWorker), That("TestData").StartsOn(nonParallelWorker), That("ParallelExecutionData").RunsOn("*"), // SetUpFixture1 && SetUpFixture2 (we can't distinguish the two) That("TestFixture1").RunsOn(parallelWorker), That("TestFixture1_Test").RunsOn(parallelWorker), That("TestFixture2").RunsOn(nonParallelWorker), That("TestFixture2_Test").RunsOn(nonParallelWorker), That("TestFixture3").RunsOn(parallelWorker), That("TestFixture3_Test").RunsOn(parallelWorker))) .SetName("ThreeFixtures_TwoSetUpFixturesInSameNamespace_FirstOneParallelizable"); yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("NUnit") .Containing(Suite("TestData") .Containing(Fixture(typeof(SetUpFixture1)) .Containing(Fixture(typeof(SetUpFixture2)).Parallelizable() .Containing( Fixture(typeof(TestFixture1)).Parallelizable(), Fixture(typeof(TestFixture2)), Fixture(typeof(TestFixture3)).Parallelizable()))))), Expecting( That("fake-assembly.dll").StartsOn(nonParallelWorker), That("NUnit").StartsOn(nonParallelWorker), That("TestData").StartsOn(nonParallelWorker), That("ParallelExecutionData").RunsOn("*"), // SetUpFixture1 && SetUpFixture2 (we can't distinguish the two) That("TestFixture1").RunsOn(parallelWorker), That("TestFixture1_Test").RunsOn(parallelWorker), That("TestFixture2").RunsOn(nonParallelWorker), That("TestFixture2_Test").RunsOn(nonParallelWorker), That("TestFixture3").RunsOn(parallelWorker), That("TestFixture3_Test").RunsOn(parallelWorker))) .SetName("ThreeFixtures_TwoSetUpFixturesInSameNamespace_SecondOneParallelizable"); yield return new TestFixtureData( Suite("fake-assembly.dll") .Containing(Suite("SomeNamespace") .Containing(Fixture(typeof(SetUpFixture1))) .Containing(Fixture(typeof(TestFixture1)))) .Containing(Suite("OtherNamespace") .Containing(Fixture(typeof(TestFixture2)))), Expecting( That("fake-assembly.dll").RunsOn(nonParallelWorker), That("SomeNamespace").RunsOn(nonParallelWorker), That("ParallelExecutionData").RunsOn(nonParallelWorker), // SetUpFixture1 That("TestFixture1").RunsOn(nonParallelWorker), That("TestFixture1_Test").RunsOn(nonParallelWorker), That("OtherNamespace").RunsOn(nonParallelWorker), That("TestFixture2").RunsOn(nonParallelWorker), That("TestFixture2_Test").RunsOn(nonParallelWorker))) .SetName("Issue-2464"); if (new PlatformHelper().IsPlatformSupported(new PlatformAttribute { Include = "Win, Mono" })) { const string nunitFwParallelSTAWorker = "NUnit.Fw.ParallelSTAWorker"; yield return new TestFixtureData( Suite("fake-assembly.dll").Parallelizable() .Containing(Fixture(typeof(STAFixture)).Parallelizable()), Expecting( That("fake-assembly.dll").StartsOn(parallelWorker), That("STAFixture").RunsOn(nunitFwParallelSTAWorker), That("STAFixture_Test").RunsOn(nunitFwParallelSTAWorker))) .SetName("Issue-2467"); } } #endregion #region ITestListener implementation void ITestListener.TestStarted(ITest test) { _events.Enqueue(new TestEvent() { Action = TestAction.TestStarting, TestName = test.Name, ThreadName = Thread.CurrentThread.Name ?? "NoThreadName", }); } void ITestListener.TestFinished(ITestResult result) { _events.Enqueue(new TestEvent() { Action = TestAction.TestFinished, TestName = result.Name, Result = result.ResultState.ToString(), ThreadName = Thread.CurrentThread.Name ?? "NoThreadName", }); } void ITestListener.TestOutput(TestOutput output) { } void ITestListener.SendMessage(TestMessage message) { } #endregion #region Helper Methods private static TestSuite Suite(string name) { return TestBuilder.MakeSuite(name); } private static TestSuite Fixture(Type type) { return TestBuilder.MakeFixture(type); } private static Expectations Expecting(params Expectation[] expectations) { return new Expectations(expectations); } private static Expectation That(string testName) { return new Expectation(testName); } private string DumpEvents(string message) { var sb = new StringBuilder().AppendLine(message); foreach (var e in _events) sb.AppendLine(e.ToString()); return sb.ToString(); } #endregion #region Nested Types
ParallelExecutionTests
csharp
npgsql__npgsql
src/Npgsql/NpgsqlDataSourceBuilder.cs
{ "start": 21911, "end": 22321 }
enum ____ in the database. /// If null, the name translator given in <paramref name="nameTranslator"/> will be used. /// </param> /// <param name="nameTranslator"> /// A component which will be used to translate CLR names (e.g. SomeClass) into database names (e.g. some_class). /// Defaults to <see cref="DefaultNameTranslator" />. /// </param> /// <typeparam name="TEnum">The .NET
type
csharp
microsoft__PowerToys
src/modules/MouseUtils/MouseUtils.UITests/MouseHighlighterTests.cs
{ "start": 449, "end": 23570 }
public class ____ : UITestBase { [TestMethod("MouseUtils.MouseHighlighter.EnableMouseHighlighter")] [TestCategory("Mouse Utils #17")] [TestCategory("Mouse Utils #18")] [TestCategory("Mouse Utils #19")] [TestCategory("Mouse Utils #20")] [TestCategory("Mouse Utils #21")] public void TestEnableMouseHighlighter() { LaunchFromSetting(); var foundCustom0 = this.Find<Custom>(By.AccessibilityId(MouseUtilsSettings.AccessibilityIds.FindMyMouse)); if (foundCustom0 != null) { foundCustom0.Find<ToggleSwitch>(By.AccessibilityId(MouseUtilsSettings.AccessibilityIds.FindMyMouseToggle)).Toggle(false); } else { Assert.Fail("Find My Mouse custom not found."); } var settings = new MouseHighlighterSettings(); settings.PrimaryButtonHighlightColor = "FFFF0000"; settings.SecondaryButtonHighlightColor = "FF00FF00"; settings.AlwaysHighlightColor = "004cFF71"; settings.Radius = "50"; settings.FadeDelay = "0"; settings.FadeDuration = "90"; var foundCustom = this.Find<Custom>(By.AccessibilityId(MouseUtilsSettings.AccessibilityIds.MouseHighlighter)); if (foundCustom != null) { foundCustom.Find<ToggleSwitch>(By.AccessibilityId(MouseUtilsSettings.AccessibilityIds.MouseHighlighterToggle)).Toggle(true); foundCustom.Find<ToggleSwitch>(By.AccessibilityId(MouseUtilsSettings.AccessibilityIds.MouseHighlighterToggle)).Toggle(false); var xy = Session.GetMousePosition(); Session.MoveMouseTo(xy.Item1, xy.Item2 - 100); Session.PerformMouseAction(MouseActionType.ScrollDown); Session.PerformMouseAction(MouseActionType.ScrollDown); Session.PerformMouseAction(MouseActionType.ScrollDown); foundCustom.Find<ToggleSwitch>(By.AccessibilityId(MouseUtilsSettings.AccessibilityIds.MouseHighlighterToggle)).Toggle(true); // Change the shortcut key for MouseHighlighter // [TestCase]Change activation shortcut and test it var activationShortcutButton = foundCustom.Find<Button>("Activation shortcut"); Assert.IsNotNull(activationShortcutButton); activationShortcutButton.Click(); Task.Delay(500).Wait(); var activationShortcutWindow = Session.Find<Window>("Activation shortcut"); Assert.IsNotNull(activationShortcutWindow); // Invalid shortcut key Session.SendKeySequence(Key.H); // IOUtil.SimulateKeyPress(0x41); var invalidShortcutText = activationShortcutWindow.Find<TextBlock>("Invalid shortcut"); Assert.IsNotNull(invalidShortcutText); // IOUtil.SimulateShortcut(0x5B, 0x10, 0x45); Session.SendKeys(Key.Win, Key.Shift, Key.H); // Assert.IsNull(activationShortcutWindow.Find<TextBlock>("Invalid shortcut")); var saveButton = activationShortcutWindow.Find<Button>("Save"); Assert.IsNotNull(saveButton); saveButton.Click(false, 500, 1000); SetMouseHighlighterAppearanceBehavior(ref foundCustom, ref settings); var xy0 = Session.GetMousePosition(); Session.MoveMouseTo(xy0.Item1 - 100, xy0.Item2); Session.PerformMouseAction(MouseActionType.LeftClick); // Check the mouse highlighter is enabled Session.SendKeys(Key.Win, Key.Shift, Key.H); // IOUtil.SimulateShortcut(0x5B, 0x10, 0x45); Task.Delay(1000).Wait(); // MouseSimulator.LeftClick(); // [Test Case] Press the activation shortcut and press left and right click somewhere, verifying the highlights are applied. // [Test Case] Press the activation shortcut again and verify no highlights appear when the mouse buttons are clicked. VerifyMouseHighlighterAppears(ref settings, "leftClick"); VerifyMouseHighlighterAppears(ref settings, "rightClick"); // Disable mouse highlighter Session.SendKeys(Key.Win, Key.Shift, Key.H); Task.Delay(1000).Wait(); VerifyMouseHighlighterNotAppears(ref settings, "leftClick"); VerifyMouseHighlighterNotAppears(ref settings, "rightClick"); // [Test Case] Disable Mouse Highlighter and verify that the module is not activated when you press the activation shortcut. foundCustom.Find<ToggleSwitch>(By.AccessibilityId(MouseUtilsSettings.AccessibilityIds.MouseHighlighterToggle)).Toggle(false); xy = Session.GetMousePosition(); Session.MoveMouseTo(xy.Item1 - 100, xy.Item2); Session.SendKeys(Key.Win, Key.Shift, Key.H); Task.Delay(1000).Wait(); VerifyMouseHighlighterNotAppears(ref settings, "leftClick"); VerifyMouseHighlighterNotAppears(ref settings, "rightClick"); // [Test Case] With left mouse button pressed, drag the mouse and verify the highlight is dragged with the pointer. // [Test Case] With right mouse button pressed, drag the mouse and verify the highlight is dragged with the pointer. foundCustom.Find<ToggleSwitch>(By.AccessibilityId(MouseUtilsSettings.AccessibilityIds.MouseHighlighterToggle)).Toggle(true); xy = Session.GetMousePosition(); Session.MoveMouseTo(xy.Item1 - 100, xy.Item2); Session.SendKeys(Key.Win, Key.Shift, Key.H); Task.Delay(1000).Wait(); VerifyMouseHighlighterDrag(ref settings, "leftClick"); VerifyMouseHighlighterDrag(ref settings, "rightClick"); } else { Assert.Fail("Mouse Highlighter Custom not found."); } Task.Delay(500).Wait(); } [TestMethod("MouseUtils.MouseHighlighter.MouseHighlighterDifferentSettings")] [TestCategory("Mouse Utils #22")] [TestCategory("Mouse Utils #23")] [TestCategory("Mouse Utils #24")] public void TestMouseHighlighterDifferentSettings() { LaunchFromSetting(); var foundCustom0 = this.Find<Custom>(By.AccessibilityId(MouseUtilsSettings.AccessibilityIds.FindMyMouse)); if (foundCustom0 != null) { foundCustom0.Find<ToggleSwitch>(By.AccessibilityId(MouseUtilsSettings.AccessibilityIds.FindMyMouseToggle)).Toggle(false); } else { Assert.Fail("Find My Mouse custom not found."); } var settings = new MouseHighlighterSettings(); settings.PrimaryButtonHighlightColor = "FF000000"; settings.SecondaryButtonHighlightColor = "FFFFFFFF"; settings.AlwaysHighlightColor = "004cFF71"; settings.Radius = "70"; settings.FadeDelay = "0"; settings.FadeDuration = "90"; var foundCustom = this.Find<Custom>(By.AccessibilityId(MouseUtilsSettings.AccessibilityIds.MouseHighlighter)); if (foundCustom != null) { foundCustom.Find<ToggleSwitch>(By.AccessibilityId(MouseUtilsSettings.AccessibilityIds.MouseHighlighterToggle)).Toggle(true); foundCustom.Find<ToggleSwitch>(By.AccessibilityId(MouseUtilsSettings.AccessibilityIds.MouseHighlighterToggle)).Toggle(false); var xy = Session.GetMousePosition(); Session.MoveMouseTo(xy.Item1, xy.Item2 - 100); Session.PerformMouseAction(MouseActionType.ScrollDown); Session.PerformMouseAction(MouseActionType.ScrollDown); Session.PerformMouseAction(MouseActionType.ScrollDown); foundCustom.Find<ToggleSwitch>(By.AccessibilityId(MouseUtilsSettings.AccessibilityIds.MouseHighlighterToggle)).Toggle(true); // Change the shortcut key for MouseHighlighter // [TestCase] Test the different settings and verify they apply - Change activation shortcut and test it // [Test Case] Test the different settings and verify they apply - Left button highlight color // [Test Case] Test the different settings and verify they apply - Right button highlight color // [Test Case] Test the different settings and verify they apply - Radius var activationShortcutButton = foundCustom.Find<Button>("Activation shortcut"); Assert.IsNotNull(activationShortcutButton); activationShortcutButton.Click(); Task.Delay(500).Wait(); var activationShortcutWindow = Session.Find<Window>("Activation shortcut"); Assert.IsNotNull(activationShortcutWindow); // Invalid shortcut key Session.SendKeySequence(Key.H); // IOUtil.SimulateKeyPress(0x41); var invalidShortcutText = activationShortcutWindow.Find<TextBlock>("Invalid shortcut"); Assert.IsNotNull(invalidShortcutText); // IOUtil.SimulateShortcut(0x5B, 0x10, 0x45); Session.SendKeys(Key.Win, Key.Shift, Key.O); // Assert.IsNull(activationShortcutWindow.Find<TextBlock>("Invalid shortcut")); var saveButton = activationShortcutWindow.Find<Button>("Save"); Assert.IsNotNull(saveButton); saveButton.Click(false, 500, 1000); SetMouseHighlighterAppearanceBehavior(ref foundCustom, ref settings); var xy0 = Session.GetMousePosition(); Session.MoveMouseTo(xy0.Item1 - 100, xy0.Item2); Session.PerformMouseAction(MouseActionType.LeftClick); // Check the mouse highlighter is enabled Session.SendKeys(Key.Win, Key.Shift, Key.O); Task.Delay(1000).Wait(); VerifyMouseHighlighterAppears(ref settings, "leftClick"); VerifyMouseHighlighterAppears(ref settings, "rightClick"); } else { Assert.Fail("Mouse Highlighter Custom not found."); } Task.Delay(500).Wait(); } private void VerifyMouseHighlighterDrag(ref MouseHighlighterSettings settings, string action = "leftClick") { Task.Delay(500).Wait(); string expectedColor = string.Empty; if (action == "leftClick") { IOUtil.SimulateMouseDown(true); expectedColor = settings.PrimaryButtonHighlightColor.Substring(2); } else if (action == "rightClick") { IOUtil.SimulateMouseDown(false); expectedColor = settings.SecondaryButtonHighlightColor.Substring(2); } else { Assert.Fail("Invalid action specified."); } expectedColor = "#" + expectedColor; Task.Delay(100).Wait(); var location = Session.GetMousePosition(); int radius = int.Parse(settings.Radius, CultureInfo.InvariantCulture); var colorLeftClick = this.GetPixelColorString(location.Item1, location.Item2); Assert.AreEqual(expectedColor, colorLeftClick); var colorLeftClick2 = this.GetPixelColorString(location.Item1 + radius - 1, location.Item2); Assert.AreEqual(expectedColor, colorLeftClick2); var colorBackground = this.GetPixelColorString(location.Item1 + radius + 50, location.Item2 + radius + 50); Assert.AreNotEqual(expectedColor, colorBackground); // Drag the mouse // Session.MoveMouseTo(location.Item1 - 400, location.Item2); for (int i = 0; i < 500; i++) { IOUtil.MoveMouseBy(-1, 0); Task.Delay(10).Wait(); } Task.Delay(2000).Wait(); location = Session.GetMousePosition(); colorLeftClick = this.GetPixelColorString(location.Item1, location.Item2); Assert.AreEqual(expectedColor, colorLeftClick); colorLeftClick2 = this.GetPixelColorString(location.Item1 + radius - 1, location.Item2); Assert.AreEqual(expectedColor, colorLeftClick2); colorBackground = this.GetPixelColorString(location.Item1 + radius + 50, location.Item2 + radius + 50); Assert.AreNotEqual(expectedColor, colorBackground); if (action == "leftClick") { IOUtil.SimulateMouseUp(true); } else if (action == "rightClick") { IOUtil.SimulateMouseUp(false); } int duration = int.Parse(settings.FadeDuration, CultureInfo.InvariantCulture); Task.Delay(duration + 100).Wait(); colorLeftClick = this.GetPixelColorString(location.Item1, location.Item2); Assert.AreNotEqual("#" + settings.PrimaryButtonHighlightColor, colorLeftClick); } private void VerifyMouseHighlighterNotAppears(ref MouseHighlighterSettings settings, string action = "leftClick") { Task.Delay(500).Wait(); string expectedColor = string.Empty; if (action == "leftClick") { // MouseSimulator.LeftDown(); Session.PerformMouseAction(MouseActionType.LeftDown); expectedColor = settings.PrimaryButtonHighlightColor.Substring(2); } else if (action == "rightClick") { // MouseSimulator.RightDown(); Session.PerformMouseAction(MouseActionType.RightDown); expectedColor = settings.SecondaryButtonHighlightColor.Substring(2); } else { Assert.Fail("Invalid action specified."); } expectedColor = "#" + expectedColor; var location = Session.GetMousePosition(); int radius = int.Parse(settings.Radius, CultureInfo.InvariantCulture); var colorLeftClick = this.GetPixelColorString(location.Item1, location.Item2); Assert.AreNotEqual(expectedColor, colorLeftClick); var colorLeftClick2 = this.GetPixelColorString(location.Item1 + radius - 1, location.Item2); Assert.AreNotEqual(expectedColor, colorLeftClick2); if (action == "leftClick") { Session.PerformMouseAction(MouseActionType.LeftUp); } else if (action == "rightClick") { Session.PerformMouseAction(MouseActionType.RightUp); } } private void VerifyMouseHighlighterAppears(ref MouseHighlighterSettings settings, string action = "leftClick") { Task.Delay(500).Wait(); string expectedColor = string.Empty; if (action == "leftClick") { // MouseSimulator.LeftDown(); Session.PerformMouseAction(MouseActionType.LeftDown); expectedColor = settings.PrimaryButtonHighlightColor.Substring(2); } else if (action == "rightClick") { // MouseSimulator.RightDown(); Session.PerformMouseAction(MouseActionType.RightDown); expectedColor = settings.SecondaryButtonHighlightColor.Substring(2); } else { Assert.Fail("Invalid action specified."); } expectedColor = "#" + expectedColor; var location = Session.GetMousePosition(); int radius = int.Parse(settings.Radius, CultureInfo.InvariantCulture); var colorLeftClick = this.GetPixelColorString(location.Item1, location.Item2); Assert.AreEqual(expectedColor, colorLeftClick); var colorLeftClick2 = this.GetPixelColorString(location.Item1 + radius - 1, location.Item2); Assert.AreEqual(expectedColor, colorLeftClick2); Task.Delay(500).Wait(); var colorBackground = this.GetPixelColorString(location.Item1 + radius + 50, location.Item2 + radius + 50); Assert.AreNotEqual(expectedColor, colorBackground); if (action == "leftClick") { // MouseSimulator.LeftUp(); Session.PerformMouseAction(MouseActionType.LeftUp); } else if (action == "rightClick") { // MouseSimulator.RightUp(); Session.PerformMouseAction(MouseActionType.RightUp); } int duration = int.Parse(settings.FadeDuration, CultureInfo.InvariantCulture); Task.Delay(duration + 100).Wait(); colorLeftClick = this.GetPixelColorString(location.Item1, location.Item2); Assert.AreNotEqual("#" + settings.PrimaryButtonHighlightColor, colorLeftClick); } private void SetColor(ref Custom foundCustom, string colorName = "Primary button highlight color", string colorValue = "000000", string opacity = "0") { Assert.IsNotNull(foundCustom); var groupAppearanceBehavior = foundCustom.Find<Group>(By.AccessibilityId(MouseUtilsSettings.AccessibilityIds.MouseHighlighterAppearanceBehavior)); if (groupAppearanceBehavior != null) { if (foundCustom.FindAll<TextBox>("Fade duration (ms) Minimum0").Count == 0) { groupAppearanceBehavior.Click(); } // Set primary button highlight color var primaryButtonHighlightColor = foundCustom.Find<Group>(colorName); Assert.IsNotNull(primaryButtonHighlightColor); var button = primaryButtonHighlightColor.Find<Button>(By.XPath(".//Button")); Assert.IsNotNull(button); button.Click(false, 500, 700); var popupWindow = Session.Find<Window>("Popup"); Assert.IsNotNull(popupWindow); var colorModelComboBox = this.Find<ComboBox>("Color model"); Assert.IsNotNull(colorModelComboBox); colorModelComboBox.Click(false, 500, 700); var selectedItem = colorModelComboBox.Find<NavigationViewItem>("RGB"); selectedItem.Click(); var rgbHexEdit = this.Find<TextBox>("RGB hex"); Assert.IsNotNull(rgbHexEdit); Task.Delay(500).Wait(); rgbHexEdit.SetText(colorValue); int retry = 5; while (retry > 0) { Task.Delay(500).Wait(); rgbHexEdit.SetText(colorValue); Task.Delay(500).Wait(); string rgbHex = rgbHexEdit.Text; bool isValid = rgbHex.StartsWith('#') && rgbHex.Length == 9 && rgbHex.Substring(1) == colorValue; Task.Delay(500).Wait(); if (isValid) { break; } retry--; } Task.Delay(500).Wait(); button.Click(); } } private void SetMouseHighlighterAppearanceBehavior(ref Custom foundCustom, ref MouseHighlighterSettings settings) { Assert.IsNotNull(foundCustom); var groupAppearanceBehavior = foundCustom.Find<Group>(By.AccessibilityId(MouseUtilsSettings.AccessibilityIds.MouseHighlighterAppearanceBehavior)); if (groupAppearanceBehavior != null) { // groupAppearanceBehavior.Click(); if (foundCustom.FindAll<TextBox>(settings.GetElementName(MouseHighlighterSettings.SettingsUIElements.FadeDurationEdit)).Count == 0) { groupAppearanceBehavior.Click(); } // Set primary button highlight color SetColor(ref foundCustom, settings.GetElementName(MouseHighlighterSettings.SettingsUIElements.PrimaryButtonHighlightColorGroup), settings.PrimaryButtonHighlightColor); // Set secondary button highlight color SetColor(ref foundCustom, settings.GetElementName(MouseHighlighterSettings.SettingsUIElements.SecondaryButtonHighlightColorGroup), settings.SecondaryButtonHighlightColor); // Set the duration to duration ms var fadeDurationEdit = foundCustom.Find<TextBox>(settings.GetElementName(MouseHighlighterSettings.SettingsUIElements.FadeDurationEdit)); Assert.IsNotNull(fadeDurationEdit); fadeDurationEdit.SetText(settings.FadeDuration); Assert.AreEqual(settings.FadeDuration, fadeDurationEdit.Text); // Set Fade delay(ms) var fadeDelayEdit = foundCustom.Find<TextBox>(settings.GetElementName(MouseHighlighterSettings.SettingsUIElements.FadeDelayEdit)); Assert.IsNotNull(fadeDelayEdit); fadeDelayEdit.SetText(settings.FadeDelay); Assert.AreEqual(settings.FadeDelay, fadeDelayEdit.Text); // Set the fade radius (px) var fadeRadiusEdit = foundCustom.Find<TextBox>(settings.GetElementName(MouseHighlighterSettings.SettingsUIElements.RadiusEdit)); Assert.IsNotNull(fadeRadiusEdit); fadeRadiusEdit.SetText(settings.Radius); Assert.AreEqual(settings.Radius, fadeRadiusEdit.Text); // Set always highlight color SetColor(ref foundCustom, settings.GetElementName(MouseHighlighterSettings.SettingsUIElements.AlwaysHighlightColorGroup), settings.AlwaysHighlightColor); } else { Assert.Fail("MouseHighlighter Appearance & behavior group not found."); } } private void LaunchFromSetting(bool showWarning = false, bool launchAsAdmin = false) { this.Session.SetMainWindowSize(WindowSize.Large); // Goto Mouse utilities setting page if (this.FindAll(By.AccessibilityId(MouseUtilsSettings.AccessibilityIds.MouseUtilitiesNavItem)).Count == 0) { // Expand Input / Output list-group if needed this.Find(By.AccessibilityId(MouseUtilsSettings.AccessibilityIds.InputOutputNavItem)).Click(); } this.Find(By.AccessibilityId(MouseUtilsSettings.AccessibilityIds.MouseUtilitiesNavItem)).Click(); } } }
MouseHighlighterTests
csharp
dotnet__maui
src/Essentials/test/UnitTests/Email_Tests.cs
{ "start": 3835, "end": 4898 }
public class ____ { [Theory] [ClassData(typeof(EmailDataGenerator))] public void GetMailToUri_Returns_RFC2368_Valid_Url(EmailMessage message, string expectedUrl) { var result = EmailImplementation.GetMailToUri(message); Assert.Equal(expectedUrl, result); } [Fact] public void GetMailToUri_Ignores_Attachments() { var message = new EmailMessage { To = new List<string> { "mom@maui.net" }, Attachments = new List<EmailAttachment> { new EmailAttachment("/my/lovely/path/selfie.jpeg") } }; var result = EmailImplementation.GetMailToUri(message); Assert.DoesNotContain("selfie", result, StringComparison.InvariantCultureIgnoreCase); } [Fact] public void GetMailToUri_Ingores_BodyFormat() { var message = new EmailMessage { To = new List<string> { "mom@maui.net" }, BodyFormat = EmailBodyFormat.Html, Body = "Hi Mom!" }; var result = EmailImplementation.GetMailToUri(message); Assert.Contains("Hi%20Mom%21", result, StringComparison.InvariantCulture); } } }
Email_Tests
csharp
dotnet__reactive
Rx.NET/Source/src/System.Reactive/Linq/Observable/Delay.cs
{ "start": 19810, "end": 20254 }
sealed class ____ : Base<Relative>.S { public S(Relative parent, IObserver<TSource> observer) : base(parent, observer) { } protected override void RunCore(Relative parent) { _ready = true; _delay = Scheduler.Normalize(parent._dueTime); } } private new
S
csharp
graphql-dotnet__graphql-dotnet
src/GraphQL/Reflection/SingleMethodAccessor.cs
{ "start": 97, "end": 1099 }
internal class ____ : IAccessor { public SingleMethodAccessor(Type declaringType, MethodInfo method) { DeclaringType = declaringType; // may be a derived type rather than method.DeclaringType MethodInfo = method; } public string FieldName => MethodInfo.Name; public Type ReturnType => MethodInfo.ReturnType; public Type DeclaringType { get; } public ParameterInfo[] Parameters => MethodInfo.GetParameters(); public MethodInfo MethodInfo { get; } public IEnumerable<T> GetAttributes<T>() where T : Attribute => MethodInfo.GetCustomAttributes<T>(); public object? GetValue(object target, object?[]? arguments) { try { return MethodInfo.Invoke(target, arguments); } catch (TargetInvocationException ex) { ExceptionDispatchInfo.Capture(ex.InnerException!).Throw(); return null; // never executed, necessary only for intellisense } } }
SingleMethodAccessor
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/src/Types/Utilities/TypeConverterExtensions.cs
{ "start": 54, "end": 1397 }
public static class ____ { public static bool TryConvert( this ITypeConverter typeConverter, Type to, object source, out object converted) => typeConverter.TryConvert(typeof(object), to, source, out converted, out _); public static bool TryConvert<TFrom, TTo>( this ITypeConverter typeConverter, TFrom source, out TTo converted) => TryConvert(typeConverter, source, out converted, out _); public static bool TryConvert<TFrom, TTo>( this ITypeConverter typeConverter, TFrom source, out TTo converted, out Exception conversionException) { ArgumentNullException.ThrowIfNull(typeConverter); if (typeConverter.TryConvert( typeof(TFrom), typeof(TTo), source, out var c, out conversionException) && c is TTo convertedCasted) { converted = convertedCasted; return true; } converted = default; return false; } public static TTo Convert<TFrom, TTo>( this ITypeConverter typeConverter, object source) { ArgumentNullException.ThrowIfNull(typeConverter); return (TTo)typeConverter.Convert( typeof(TFrom), typeof(TTo), source); } }
TypeConverterExtensions
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.Interfaces/AI/IPromptProviderFactory.cs
{ "start": 94, "end": 177 }
public interface ____ { IPromptProvider Get(string name); }
IPromptProviderFactory
csharp
dotnet__efcore
test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs
{ "start": 347177, "end": 347397 }
public class ____ { public int Id { get; set; } public RelatedEntity1592 ParentEntity { get; set; } public IEnumerable<RelatedEntity1594> ChildEntities { get; set; } }
RelatedEntity1593
csharp
CommunityToolkit__dotnet
tests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests/Test_SourceGeneratorsDiagnostics.cs
{ "start": 56024, "end": 56391 }
public partial class ____ { [RelayCommand] [property: MyTest] private void Test() { } } } namespace MyAttributes { [AttributeUsage(AttributeTargets.Property)]
MyViewModel
csharp
dotnet__aspnetcore
src/Components/Components/src/Rendering/RendererSynchronizationContext.cs
{ "start": 291, "end": 2015 }
internal sealed class ____ : SynchronizationContext { private readonly object _lock; private Task _taskQueue; public event UnhandledExceptionEventHandler? UnhandledException; public RendererSynchronizationContext() : this(new object(), Task.CompletedTask) { } private RendererSynchronizationContext(object @lock, Task taskQueue) { _lock = @lock; _taskQueue = taskQueue; } /// <inheritdoc /> public override SynchronizationContext CreateCopy() => new RendererSynchronizationContext(_lock, _taskQueue); // The following two Action/Func<TResult> overloads can be more optimized than their // async equivalents, as they don't need to deal with the possibility of the callback // posting back to this context. As a result, they can use the Task for the InvokeAsync // operation as the object to use in the task queue itself if the operation is the next // in line. For the async overloads, the callbacks might await and need to post back // to the current synchronization context, in which case their continuation could end // up seeing the InvokeAsync task as the antecedent, which would lead to deadlock. As // such, those operations must use a different task for the task queue. Note that this // requires these synchronous callbacks not doing sync-over-async with any work that // blocks waiting for this sync ctx to do work, but such cases are perilous, anyway, // as they invariably lead to deadlock. public Task InvokeAsync(Action action) { var completion = AsyncTaskMethodBuilder.Create(); var t = completion.Task; // lazy initialize before passing around the
RendererSynchronizationContext
csharp
ServiceStack__ServiceStack.OrmLite
tests/ServiceStack.OrmLite.SqliteTests/SqliteReadOnlyTests.cs
{ "start": 227, "end": 1213 }
class ____ : OrmLiteTestBase { [Test] public void Can_open_readonly_connection_to_file_database() { var dbPath = "~/App_Data/northwind.sqlite".MapProjectPlatformPath(); var connectionString = $"Data Source={dbPath};Read Only=true"; connectionString.Print(); var dbFactory = new OrmLiteConnectionFactory(connectionString, SqliteDialect.Provider); using (var db = dbFactory.OpenDbConnection()) { var count = db.Count<Customer>(); Assert.That(count, Is.GreaterThan(1)); try { db.DropAndCreateTable<DisableWrites>(); Assert.Fail("should thow"); } catch (Exception ex) { Assert.That(ex.Message, Does.Contain("attempt to write a readonly database")); } } } } }
SqliteReadOnlyTests
csharp
smartstore__Smartstore
src/Smartstore.Core/Content/Menus/Services/MenuProviders/EntityMenuItemProvider.cs
{ "start": 302, "end": 2219 }
public class ____ : MenuItemProviderBase { private readonly ILinkResolver _linkResolver; public EntityMenuItemProvider(ILinkResolver linkResolver) { _linkResolver = linkResolver; } protected override async Task ApplyLinkAsync(MenuItemProviderRequest request, TreeNode<MenuItem> node) { // Always resolve against current store, current customer and working language. var result = await _linkResolver.ResolveAsync(request.Entity.Model); var item = node.Value; item.Url = result.Link; item.ImageId = result.PictureId; if (item.Text.IsEmpty()) { item.Text = result.Label; } if (result.EntityId.HasValue && !request.IsEditMode) { item.EntityId = result.EntityId.Value; item.EntityName = result.EntityName; } if (result.Expression.LinkTarget.HasValue()) { item.LinkHtmlAttributes.Add("target", result.Expression.LinkTarget); } if (request.IsEditMode) { var info = _linkResolver.GetBuilderMetadata().FirstOrDefault(x => x.Schema == result.Expression.Schema); if (info != null) { item.Summary = T(info.ResKey); item.Icon = info.Icon; } if (info == null || item.Url.IsEmpty()) { item.Text = null; item.ResKey = "Admin.ContentManagement.Menus.SpecifyLinkTarget"; } } else { // For edit mode, only apply MenuItemRecord.Published. item.Visible = result.Status == LinkStatus.Ok; } } } }
EntityMenuItemProvider
csharp
graphql-dotnet__graphql-dotnet
src/GraphQL.Tests/Bugs/Bug2839NewtonsoftJson.cs
{ "start": 2158, "end": 2554 }
public class ____ : DateTimeGraphType { public MyDateTimeGraphType() { Name = "DateTime"; } public override object? Serialize(object? value) => value switch { DateTime _ => value, DateTimeOffset _ => value, null => null, _ => ThrowSerializationError(value) }; } }
MyDateTimeGraphType
csharp
nuke-build__nuke
source/Nuke.Common/Tools/Helm/Helm.Generated.cs
{ "start": 151349, "end": 153867 }
public partial class ____ : HelmOptionsBase { /// <summary>Chart repository url where to locate the requested chart.</summary> [Argument(Format = "--ca-file {value}", Secret = false)] public string CaFile => Get<string>(() => CaFile); /// <summary>Verify certificates of HTTPS-enabled servers using this CA bundle.</summary> [Argument(Format = "--cert-file {value}", Secret = false)] public string CertFile => Get<string>(() => CertFile); /// <summary>Use development versions, too. Equivalent to version '&gt;0.0.0-0'. If --version is set, this is ignored.</summary> [Argument(Format = "--devel", Secret = false)] public bool? Devel => Get<bool?>(() => Devel); /// <summary>Identify HTTPS client using this SSL key file.</summary> [Argument(Format = "--key-file {value}", Secret = false)] public string KeyFile => Get<string>(() => KeyFile); /// <summary>Path to the keyring containing public verification keys (default "~/.gnupg/pubring.gpg").</summary> [Argument(Format = "--keyring {value}", Secret = false)] public string Keyring => Get<string>(() => Keyring); /// <summary>Chart repository password where to locate the requested chart.</summary> [Argument(Format = "--password {value}", Secret = true)] public string Password => Get<string>(() => Password); /// <summary>Chart repository url where to locate the requested chart.</summary> [Argument(Format = "--repo {value}", Secret = false)] public string Repo => Get<string>(() => Repo); /// <summary>Chart repository username where to locate the requested chart.</summary> [Argument(Format = "--username {value}", Secret = false)] public string Username => Get<string>(() => Username); /// <summary>Verify the provenance data for this chart.</summary> [Argument(Format = "--verify", Secret = false)] public bool? Verify => Get<bool?>(() => Verify); /// <summary>Version of the chart. By default, the newest chart is shown.</summary> [Argument(Format = "--version {value}", Secret = false)] public string Version => Get<string>(() => Version); /// <summary>The name of the chart to inspect.</summary> [Argument(Format = "{value}")] public string Chart => Get<string>(() => Chart); } #endregion #region HelmInstallSettings /// <inheritdoc cref="HelmTasks.HelmInstall(Nuke.Common.Tools.Helm.HelmInstallSettings)"/> [PublicAPI] [ExcludeFromCodeCoverage] [Command(Type = typeof(HelmTasks), Command = nameof(HelmTasks.HelmInstall), Arguments = "install")]
HelmInspectValuesSettings
csharp
unoplatform__uno
src/Uno.UI/UI/Xaml/Controls/CalendarView/CalendarViewBaseItem.h.cs
{ "start": 460, "end": 5185 }
public partial class ____ : Control { internal CalendarViewBaseItem() // Make sure the ctor is not publically visible { m_pParentCalendarView = null; #if DEBUG m_eraForDebug = 0; m_yearForDebug = 0; m_monthForDebug = 0; m_dayForDebug = 0; #endif // Uno only Initialize_CalendarViewBaseItemChrome(); #if !__NETSTD_REFERENCE__ this.Loaded += (_, _) => { #if !UNO_HAS_BORDER_VISUAL _borderRenderer ??= new(this); #endif #if !UNO_HAS_ENHANCED_LIFECYCLE EnterImpl(); #endif }; #endif } //protected: //// this base panel implementation is hidden from IDL //private void QueryInterfaceImpl( REFIID iid, out void* ppObject) //{ // if (InlineIsEqualGUID(iid, __uuidof(ICalendarViewBaseItem))) // { // ppObject = (ICalendarViewBaseItem)(this); // } // else // { // return CalendarViewBaseItemGenerated.QueryInterfaceImpl(iid, ppObject); // } // AddRefOuter(); // return; //} //// Called when the user presses a pointer down over the //// CalendarViewBaseItem. //IFACEMETHOD(OnPointerPressed)( // xaml_input.IPointerRoutedEventArgs pArgs) // override; //// Called when the user releases a pointer over the //// CalendarViewBaseItem. //IFACEMETHOD(OnPointerReleased)( // xaml_input.IPointerRoutedEventArgs pArgs) // override; //// Called when a pointer enters a CalendarViewBaseItem. //IFACEMETHOD(OnPointerEntered)( // xaml_input.IPointerRoutedEventArgs pArgs) // override; //// Called when a pointer leaves a CalendarViewBaseItem. //IFACEMETHOD(OnPointerExited)( // xaml_input.IPointerRoutedEventArgs pArgs) // override; //// Called when the CalendarViewBaseItem or its children lose pointer capture. //IFACEMETHOD(OnPointerCaptureLost)( // xaml_input.IPointerRoutedEventArgs pArgs) // override; //// Called when the CalendarViewBaseItem receives focus. //IFACEMETHOD(OnGotFocus)( // xaml.IRoutedEventArgs pArgs) // override; //// Called when the CalendarViewBaseItem loses focus. //IFACEMETHOD(OnLostFocus)( // xaml.IRoutedEventArgs pArgs) // override; //IFACEMETHOD(OnRightTapped)( xaml_input.IRightTappedRoutedEventArgs pArgs) override; //// Called when the IsEnabled property changes. //private void OnIsEnabledChanged( DirectUI.IsEnabledChangedEventArgs pArgs) override; //// Called when the element enters the tree. Refreshes visual state. //private void EnterImpl( // XBOOL bLive, // XBOOL bSkipNameRegistration, // XBOOL bCoercedIsEnabled, // XBOOL bUseLayoutRounding) override sealed; //public: //void SetParentCalendarView( CalendarView pCalendarView); //CalendarView GetParentCalendarView(); //private void SetIsToday( bool state); //private void SetIsKeyboardFocused( bool state); //private void SetIsSelected( bool state); //private void SetIsBlackout( bool state); //private void SetIsHovered( bool state); //private void SetIsPressed( bool state); //private void SetIsOutOfScope( bool state); //private void UpdateText( string mainText, string labelText, bool showLabel); //private void UpdateMainText( string mainText); //private void UpdateLabelText( string labelText); //private void ShowLabelText( bool showLabel); //private void GetMainText(out HSTRING pMainText); // CalendarViewItem and CalendarViewDayItem will override this method. internal virtual DateTime DateBase { get => throw new NotImplementedException(); set => throw new NotImplementedException(); // For debug purpose only } //private void FocusSelfOrChild( // xaml.FocusState focusState, // out bool pFocused, // xaml_input.FocusNavigationDirection focusNavigationDirection = xaml_input.FocusNavigationDirection.FocusNavigationDirection_None); //// invalidate render to make sure chrome properties (background, border, ...) get updated //private void InvalidateRender(); //private void UpdateTextBlockForeground(); //private void UpdateTextBlockFontProperties(); //private void UpdateTextBlockAlignments(); #if DEBUG && false // DateTime has an int64 member which is not intutive enough. This method will convert it // into numbers that we can easily read. private void SetDateForDebug(DateTime value); #endif //protected: // private void ChangeVisualState(bool useTransitions = true) override; //private: // private void UpdateVisualStateInternal(); //private: private CalendarView m_pParentCalendarView; #if DEBUG private int m_eraForDebug; private int m_yearForDebug; private int m_monthForDebug; private int m_dayForDebug; #endif } }
CalendarViewBaseItem
csharp
AutoFixture__AutoFixture
Src/AutoFixture/MutableValueTypeGenerator.cs
{ "start": 1025, "end": 1478 }
struct ____ possible; otherwise a <see cref="NoSpecimen"/> instance. /// </returns> public object Create(object request, ISpecimenContext context) { Type type = request as Type; if (type == null || !this.valueTypeWithoutConstructorsSpecification.IsSatisfiedBy(type)) { return new NoSpecimen(); } return Activator.CreateInstance(type); } } }
if
csharp
ChilliCream__graphql-platform
src/HotChocolate/Raven/src/Data/Filtering/Extensions/RavenFilteringConvention.cs
{ "start": 194, "end": 1400 }
internal sealed class ____ : FilterConvention { private ITypeInspector _typeInspector = null!; protected override void Configure(IFilterConventionDescriptor descriptor) { descriptor .AddDefaultOperations() .BindDefaultTypes() .Provider<RavenQueryableFilterProvider>(); } protected override void Complete(IConventionContext context) { base.Complete(context); _typeInspector = context.DescriptorContext.TypeInspector; } public override ExtendedTypeReference GetFieldType(MemberInfo member) { ArgumentNullException.ThrowIfNull(member); var runtimeType = _typeInspector.GetReturnType(member, true); if (runtimeType.IsArrayOrList) { if (runtimeType.ElementType is { } && TryCreateFilterType(runtimeType.ElementType, out var elementType)) { return _typeInspector.GetTypeRef( typeof(RavenListFilterInputType<>).MakeGenericType(elementType), TypeContext.Input, Scope); } } return base.GetFieldType(member); } }
RavenFilteringConvention
csharp
MassTransit__MassTransit
src/MassTransit.Abstractions/Contexts/CompensateActivityContext.cs
{ "start": 292, "end": 521 }
class ____ TActivity : class, ICompensateActivity<TLog> { /// <summary> /// The activity that was created/used for this compensation /// </summary> TActivity Activity { get; } } }
where
csharp
CommunityToolkit__Maui
src/CommunityToolkit.Maui/Behaviors/Validators/EmailValidationBehavior.shared.cs
{ "start": 969, "end": 2143 }
public partial class ____ : TextValidationBehavior { /// <summary> /// A <see cref="Regex"/> to match an input is a valid email address /// Generated by <see cref="GeneratedRegexAttribute"/> /// </summary> /// <returns>Generated <see cref="Regex"/></returns> [GeneratedRegex(@"^[^@\s]+@[^@\s]+\.[^@\s]+$", RegexOptions.IgnoreCase, 250)] protected static partial Regex EmailRegex(); /// <summary> /// A <see cref="Regex"/> to match the domain of an email address /// Generated by <see cref="GeneratedRegexAttribute"/> /// </summary> /// <returns>Generated <see cref="Regex"/></returns> [GeneratedRegex(@"(@)(.+)$", RegexOptions.None, 250)] protected static partial Regex EmailDomainRegex(); /// <summary> /// Examines the email address domain and normalizes it to ASCII /// </summary> /// <param name="match"></param> /// <returns></returns> /// <exception cref="ArgumentException"></exception> private protected static string DomainMapper(Match match) { var domainName = match.Groups[2].Value; if (domainName.StartsWith('-')) { throw new ArgumentException("Domain name cannot start with hyphen."); } // Use IdnMapping
EmailValidationBehavior
csharp
abpframework__abp
framework/src/Volo.Abp.Core/System/Reflection/AbpMemberInfoExtensions.cs
{ "start": 124, "end": 1592 }
public static class ____ { /// <summary> /// Gets a single attribute for a member. /// </summary> /// <typeparam name="TAttribute">Type of the attribute</typeparam> /// <param name="memberInfo">The member that will be checked for the attribute</param> /// <param name="inherit">Include inherited attributes</param> /// <returns>Returns the attribute object if found. Returns null if not found.</returns> public static TAttribute? GetSingleAttributeOrNull<TAttribute>(this MemberInfo memberInfo, bool inherit = true) where TAttribute : Attribute { if (memberInfo == null) { throw new ArgumentNullException(nameof(memberInfo)); } var attrs = memberInfo.GetCustomAttributes(typeof(TAttribute), inherit).ToArray(); if (attrs.Length > 0) { return (TAttribute)attrs[0]; } return default; } public static TAttribute? GetSingleAttributeOfTypeOrBaseTypesOrNull<TAttribute>(this Type type, bool inherit = true) where TAttribute : Attribute { var attr = type.GetTypeInfo().GetSingleAttributeOrNull<TAttribute>(); if (attr != null) { return attr; } if (type.GetTypeInfo().BaseType == null) { return null; } return type.GetTypeInfo().BaseType?.GetSingleAttributeOfTypeOrBaseTypesOrNull<TAttribute>(inherit); } }
AbpMemberInfoExtensions
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.Flows/Indexing/FlowPartIndexHandler.cs
{ "start": 148, "end": 1613 }
public class ____ : ContentPartIndexHandler<FlowPart> { private readonly IServiceProvider _serviceProvider; public FlowPartIndexHandler(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public override async Task BuildIndexAsync(FlowPart FlowPart, BuildPartIndexContext context) { var options = context.Settings.ToOptions(); if (options == DocumentIndexOptions.None) { return; } if (FlowPart.Widgets.Count != 0) { // Lazy resolution to prevent cyclic dependency. var contentItemIndexHandlers = _serviceProvider.GetServices<IDocumentIndexHandler>(); foreach (var contentItemIndexHandler in contentItemIndexHandlers) { foreach (var contentItem in FlowPart.Widgets) { var keys = new List<string> { contentItem.ContentType, }; foreach (var key in context.Keys) { keys.Add($"{key}.{contentItem.ContentType}"); } var buildIndexContext = new BuildDocumentIndexContext(context.DocumentIndex, contentItem, keys, context.Settings); await contentItemIndexHandler.BuildIndexAsync(buildIndexContext); } } } } }
FlowPartIndexHandler
csharp
simplcommerce__SimplCommerce
src/Modules/SimplCommerce.Module.Reviews/Areas/Reviews/Controllers/ReplyController.cs
{ "start": 389, "end": 1555 }
public class ____ : Controller { private readonly IRepository<Models.Reply> _replyRepository; private readonly IWorkContext _workContext; public ReplyController(IRepository<Models.Reply> replyRepository, IWorkContext workContext) { _replyRepository = replyRepository; _workContext = workContext; } [Authorize] [HttpPost] public async Task<IActionResult> AddReply(ReplyForm model) { if (ModelState.IsValid) { var user = await _workContext.GetCurrentUser(); model.ReplierName = user.FullName; var reply = new Models.Reply { ReviewId = model.ReviewId, UserId = user.Id, Comment = model.Comment, ReplierName = user.FullName }; _replyRepository.Add(reply); _replyRepository.SaveChanges(); return PartialView("_ReplyFormSuccess", model); } return PartialView("_ReplyForm", model); } } }
ReplyController
csharp
graphql-dotnet__graphql-dotnet
src/GraphQL/Execution/IDocumentBuilder.cs
{ "start": 203, "end": 443 }
public interface ____ { /// <summary> /// Parse a GraphQL request and return a <see cref="GraphQLDocument">Document</see> representing the GraphQL request AST /// </summary> GraphQLDocument Build(string body); }
IDocumentBuilder
csharp
abpframework__abp
framework/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/ContentFormatters/RemoteStreamContentTestController.cs
{ "start": 253, "end": 2201 }
public class ____ : AbpController { [HttpGet] [Route("Download")] public async Task<IRemoteStreamContent> DownloadAsync() { var memoryStream = new MemoryStream(); await memoryStream.WriteAsync(Encoding.UTF8.GetBytes("DownloadAsync")); memoryStream.Position = 0; return new RemoteStreamContent(memoryStream, "download.rtf", "application/rtf"); } [HttpGet] [Route("Download-With-Custom-Content-Disposition")] public async Task<IRemoteStreamContent> Download_With_Custom_Content_Disposition_Async() { var memoryStream = new MemoryStream(); await memoryStream.WriteAsync(Encoding.UTF8.GetBytes("DownloadAsync")); memoryStream.Position = 0; Response.Headers.Append("Content-Disposition", "attachment; filename=myDownload.rtf"); return new RemoteStreamContent(memoryStream, "download.rtf", "application/rtf"); } [HttpGet] [Route("Download_With_Chinese_File_Name")] public async Task<IRemoteStreamContent> Download_With_Chinese_File_Name_Async() { var memoryStream = new MemoryStream(); await memoryStream.WriteAsync(Encoding.UTF8.GetBytes("DownloadAsync")); memoryStream.Position = 0; return new RemoteStreamContent(memoryStream, "下载文件.rtf", "application/rtf"); } [HttpPost] [Route("Upload")] public async Task<string> UploadAsync(IRemoteStreamContent file) { using (var reader = new StreamReader(file.GetStream())) { return await reader.ReadToEndAsync() + ":" + file.ContentType + ":" + file.FileName; } } [HttpPost] [Route("Upload-Raw")] public async Task<string> UploadRawAsync(IRemoteStreamContent file) { using (var reader = new StreamReader(file.GetStream())) { return await reader.ReadToEndAsync() + ":" + file.ContentType; } } }
RemoteStreamContentTestController
csharp
jbogard__MediatR
test/MediatR.Benchmarks/DotTraceDiagnoser.cs
{ "start": 790, "end": 4676 }
internal sealed class ____ : IDiagnoser { private const string DotTraceExecutableNotFoundErrorMessage = "dotTrace executable was not found. " + "Make sure it is part of the PATH or install JetBrains.dotTrace.GlobalTools"; private readonly string _saveLocation; public DotTraceDiagnoser() { _saveLocation = $"C:\\temp\\MediatR\\{DateTimeOffset.Now.UtcDateTime:yyyy-MM-dd-HH_mm_ss}.bench.dtp"; } /// <inheritdoc /> public RunMode GetRunMode(BenchmarkCase benchmarkCase) => RunMode.ExtraRun; /// <inheritdoc /> public void Handle(HostSignal signal, DiagnoserActionParameters parameters) { if (signal != HostSignal.BeforeActualRun) { return; } try { if (!CanRunDotTrace()) { Console.WriteLine(DotTraceExecutableNotFoundErrorMessage); return; } // The directory must exist or an error is thrown by dotTrace. Directory.CreateDirectory(_saveLocation); RunDotTrace(parameters); } catch (Exception e) { Console.Error.WriteLine(e.ToString()); throw; } } private void RunDotTrace(DiagnoserActionParameters parameters) { var dotTrace = new Process { StartInfo = PrepareProcessStartInfo(parameters) }; dotTrace.ErrorDataReceived += (sender, eventArgs) => Console.Error.WriteLine(eventArgs.Data); dotTrace.OutputDataReceived += (sender, eventArgs) => Console.WriteLine(eventArgs.Data); dotTrace.Start(); dotTrace.BeginErrorReadLine(); dotTrace.BeginOutputReadLine(); dotTrace.Exited += (sender, args) => dotTrace.Dispose(); } private ProcessStartInfo PrepareProcessStartInfo(DiagnoserActionParameters parameters) { return new ProcessStartInfo( "dottrace", $"attach {parameters.Process.Id} --save-to={_saveLocation}") { RedirectStandardError = true, RedirectStandardOutput = true, WindowStyle = ProcessWindowStyle.Hidden, UseShellExecute = false, CreateNoWindow = true, }; } /// <inheritdoc /> public IEnumerable<Metric> ProcessResults(DiagnoserResults results) => Enumerable.Empty<Metric>(); /// <inheritdoc /> public void DisplayResults(ILogger logger) { } /// <inheritdoc /> public IEnumerable<ValidationError> Validate(ValidationParameters validationParameters) => Enumerable.Empty<ValidationError>(); /// <inheritdoc /> public IEnumerable<string> Ids => new[] { nameof(DotTraceDiagnoser) }; /// <inheritdoc /> public IEnumerable<IExporter> Exporters => Enumerable.Empty<IExporter>(); public IEnumerable<IAnalyser> Analysers { get; } = Enumerable.Empty<IAnalyser>(); private static bool CanRunDotTrace() { try { var startInfo = new ProcessStartInfo("dottrace") { RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true, }; using var process = new Process { StartInfo = startInfo }; process.Start(); process.WaitForExit(); return true; } catch (Exception) { return false; } } } }
DotTraceDiagnoser
csharp
dotnet__aspnetcore
src/Components/WebAssembly/Server/src/WebAssemblyEndpointProvider.cs
{ "start": 2274, "end": 3445 }
private class ____(IServiceProvider serviceProvider, IApplicationBuilder applicationBuilder) : IEndpointRouteBuilder { public IServiceProvider ServiceProvider { get; } = serviceProvider; public ICollection<EndpointDataSource> DataSources { get; } = []; public IApplicationBuilder CreateApplicationBuilder() { return applicationBuilder.New(); } internal IEnumerable<RouteEndpointBuilder> GetEndpoints() { foreach (var ds in DataSources) { foreach (var endpoint in ds.Endpoints) { var routeEndpoint = (RouteEndpoint)endpoint; var builder = new RouteEndpointBuilder(endpoint.RequestDelegate, routeEndpoint.RoutePattern, routeEndpoint.Order); for (var i = 0; i < routeEndpoint.Metadata.Count; i++) { var metadata = routeEndpoint.Metadata[i]; builder.Metadata.Add(metadata); } yield return builder; } } } } }
WebAssemblyEndpointRouteBuilder
csharp
dotnet__maui
src/Controls/samples/Controls.Sample/Pages/Controls/CollectionViewGalleries/TextCodeCollectionViewGallery.cs
{ "start": 119, "end": 851 }
internal class ____ : ContentPage { public TextCodeCollectionViewGallery(IItemsLayout itemsLayout) { var layout = new Grid { RowDefinitions = new RowDefinitionCollection { new RowDefinition { Height = GridLength.Auto }, new RowDefinition { Height = GridLength.Star } } }; var collectionView = new CollectionView { ItemsLayout = itemsLayout, SelectionMode = SelectionMode.Single, AutomationId = "collectionview" }; var generator = new ItemsSourceGenerator(collectionView); layout.Children.Add(generator); Grid.SetRow(collectionView, 1); layout.Children.Add(collectionView); Content = layout; generator.GenerateItems(); } } }
TextCodeCollectionViewGallery
csharp
MassTransit__MassTransit
src/MassTransit/Scheduling/ScheduleMessageCommand.cs
{ "start": 78, "end": 955 }
public class ____<T> : ScheduleMessage where T : class { public ScheduleMessageCommand() { } public ScheduleMessageCommand(DateTime scheduledTime, Uri destination, T payload, Guid tokenId) { CorrelationId = tokenId; ScheduledTime = scheduledTime.Kind == DateTimeKind.Local ? scheduledTime.ToUniversalTime() : scheduledTime; Destination = destination; Payload = payload; PayloadType = MessageTypeCache<T>.MessageTypeNames; } public Guid CorrelationId { get; set; } public DateTime ScheduledTime { get; set; } public string[] PayloadType { get; set; } public Uri Destination { get; set; } public object Payload { get; set; } } [Serializable]
ScheduleMessageCommand
csharp
grandnode__grandnode2
src/Web/Grand.Web/Models/ShoppingCart/AddCartFromWishlistModel.cs
{ "start": 43, "end": 175 }
public class ____ { public Guid? CustomerGuid { get; set; } public string ShoppingCartId { get; set; } }
AddCartFromWishlistModel
csharp
domaindrivendev__Swashbuckle.AspNetCore
test/WebSites/DocumentationSnippets/TagDescriptionsDocumentFilter.cs
{ "start": 161, "end": 568 }
public class ____ : IDocumentFilter { public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { swaggerDoc.Tags = new HashSet<OpenApiTag>() { new() { Name = "Products", Description = "Browse/manage the product catalog" }, new() { Name = "Orders", Description = "Submit orders" } }; } } // end-snippet
TagDescriptionsDocumentFilter
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Security.Cryptography.Core/SymmetricAlgorithmNames.cs
{ "start": 322, "end": 12716 }
partial class ____ { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static string AesCbc { get { throw new global::System.NotImplementedException("The member string SymmetricAlgorithmNames.AesCbc is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20SymmetricAlgorithmNames.AesCbc"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static string AesCbcPkcs7 { get { throw new global::System.NotImplementedException("The member string SymmetricAlgorithmNames.AesCbcPkcs7 is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20SymmetricAlgorithmNames.AesCbcPkcs7"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static string AesCcm { get { throw new global::System.NotImplementedException("The member string SymmetricAlgorithmNames.AesCcm is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20SymmetricAlgorithmNames.AesCcm"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static string AesEcb { get { throw new global::System.NotImplementedException("The member string SymmetricAlgorithmNames.AesEcb is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20SymmetricAlgorithmNames.AesEcb"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static string AesEcbPkcs7 { get { throw new global::System.NotImplementedException("The member string SymmetricAlgorithmNames.AesEcbPkcs7 is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20SymmetricAlgorithmNames.AesEcbPkcs7"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static string AesGcm { get { throw new global::System.NotImplementedException("The member string SymmetricAlgorithmNames.AesGcm is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20SymmetricAlgorithmNames.AesGcm"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static string DesCbc { get { throw new global::System.NotImplementedException("The member string SymmetricAlgorithmNames.DesCbc is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20SymmetricAlgorithmNames.DesCbc"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static string DesCbcPkcs7 { get { throw new global::System.NotImplementedException("The member string SymmetricAlgorithmNames.DesCbcPkcs7 is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20SymmetricAlgorithmNames.DesCbcPkcs7"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static string DesEcb { get { throw new global::System.NotImplementedException("The member string SymmetricAlgorithmNames.DesEcb is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20SymmetricAlgorithmNames.DesEcb"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static string DesEcbPkcs7 { get { throw new global::System.NotImplementedException("The member string SymmetricAlgorithmNames.DesEcbPkcs7 is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20SymmetricAlgorithmNames.DesEcbPkcs7"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static string Rc2Cbc { get { throw new global::System.NotImplementedException("The member string SymmetricAlgorithmNames.Rc2Cbc is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20SymmetricAlgorithmNames.Rc2Cbc"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static string Rc2CbcPkcs7 { get { throw new global::System.NotImplementedException("The member string SymmetricAlgorithmNames.Rc2CbcPkcs7 is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20SymmetricAlgorithmNames.Rc2CbcPkcs7"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static string Rc2Ecb { get { throw new global::System.NotImplementedException("The member string SymmetricAlgorithmNames.Rc2Ecb is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20SymmetricAlgorithmNames.Rc2Ecb"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static string Rc2EcbPkcs7 { get { throw new global::System.NotImplementedException("The member string SymmetricAlgorithmNames.Rc2EcbPkcs7 is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20SymmetricAlgorithmNames.Rc2EcbPkcs7"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static string Rc4 { get { throw new global::System.NotImplementedException("The member string SymmetricAlgorithmNames.Rc4 is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20SymmetricAlgorithmNames.Rc4"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static string TripleDesCbc { get { throw new global::System.NotImplementedException("The member string SymmetricAlgorithmNames.TripleDesCbc is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20SymmetricAlgorithmNames.TripleDesCbc"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static string TripleDesCbcPkcs7 { get { throw new global::System.NotImplementedException("The member string SymmetricAlgorithmNames.TripleDesCbcPkcs7 is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20SymmetricAlgorithmNames.TripleDesCbcPkcs7"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static string TripleDesEcb { get { throw new global::System.NotImplementedException("The member string SymmetricAlgorithmNames.TripleDesEcb is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20SymmetricAlgorithmNames.TripleDesEcb"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public static string TripleDesEcbPkcs7 { get { throw new global::System.NotImplementedException("The member string SymmetricAlgorithmNames.TripleDesEcbPkcs7 is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20SymmetricAlgorithmNames.TripleDesEcbPkcs7"); } } #endif // Forced skipping of method Windows.Security.Cryptography.Core.SymmetricAlgorithmNames.DesCbc.get // Forced skipping of method Windows.Security.Cryptography.Core.SymmetricAlgorithmNames.DesEcb.get // Forced skipping of method Windows.Security.Cryptography.Core.SymmetricAlgorithmNames.TripleDesCbc.get // Forced skipping of method Windows.Security.Cryptography.Core.SymmetricAlgorithmNames.TripleDesEcb.get // Forced skipping of method Windows.Security.Cryptography.Core.SymmetricAlgorithmNames.Rc2Cbc.get // Forced skipping of method Windows.Security.Cryptography.Core.SymmetricAlgorithmNames.Rc2Ecb.get // Forced skipping of method Windows.Security.Cryptography.Core.SymmetricAlgorithmNames.AesCbc.get // Forced skipping of method Windows.Security.Cryptography.Core.SymmetricAlgorithmNames.AesEcb.get // Forced skipping of method Windows.Security.Cryptography.Core.SymmetricAlgorithmNames.AesGcm.get // Forced skipping of method Windows.Security.Cryptography.Core.SymmetricAlgorithmNames.AesCcm.get // Forced skipping of method Windows.Security.Cryptography.Core.SymmetricAlgorithmNames.AesCbcPkcs7.get // Forced skipping of method Windows.Security.Cryptography.Core.SymmetricAlgorithmNames.AesEcbPkcs7.get // Forced skipping of method Windows.Security.Cryptography.Core.SymmetricAlgorithmNames.DesCbcPkcs7.get // Forced skipping of method Windows.Security.Cryptography.Core.SymmetricAlgorithmNames.DesEcbPkcs7.get // Forced skipping of method Windows.Security.Cryptography.Core.SymmetricAlgorithmNames.TripleDesCbcPkcs7.get // Forced skipping of method Windows.Security.Cryptography.Core.SymmetricAlgorithmNames.TripleDesEcbPkcs7.get // Forced skipping of method Windows.Security.Cryptography.Core.SymmetricAlgorithmNames.Rc2CbcPkcs7.get // Forced skipping of method Windows.Security.Cryptography.Core.SymmetricAlgorithmNames.Rc2EcbPkcs7.get // Forced skipping of method Windows.Security.Cryptography.Core.SymmetricAlgorithmNames.Rc4.get } }
SymmetricAlgorithmNames
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp/Configuration/Startup/IEventBusConfiguration.cs
{ "start": 176, "end": 564 }
public interface ____ { /// <summary> /// True, to use <see cref="EventBus.Default"/>. /// False, to create per <see cref="IIocManager"/>. /// This is generally set to true. But, for unit tests, /// it can be set to false. /// Default: true. /// </summary> bool UseDefaultEventBus { get; set; } } }
IEventBusConfiguration
csharp
dotnet__efcore
test/EFCore.Analyzers.Tests/TestUtilities/CSharpCodeFixVerifier.cs
{ "start": 1596, "end": 2568 }
public class ____ : CSharpCodeFixTest<TAnalyzer, TCodeFix, XUnitVerifier> #pragma warning restore CS0618 // Type or member is obsolete { protected override async Task<Project> CreateProjectImplAsync( EvaluatedProjectState primaryProject, ImmutableArray<EvaluatedProjectState> additionalProjects, CancellationToken cancellationToken) { var metadataReferences = DependencyContext.Load(GetType().Assembly)! .CompileLibraries .SelectMany(c => c.ResolveReferencePaths()) .Select(path => MetadataReference.CreateFromFile(path)) .Cast<MetadataReference>() .ToList(); var project = await base.CreateProjectImplAsync(primaryProject, additionalProjects, cancellationToken).ConfigureAwait(false); return project.WithMetadataReferences(metadataReferences); } } }
Test
csharp
unoplatform__uno
src/Uno.UI.Composition/Win2D/Microsoft/Graphics/Canvas/CanvasImageInterpolation.cs
{ "start": 39, "end": 193 }
internal enum ____ { NearestNeighbor = 0, Linear = 1, Cubic = 2, MultiSampleLinear = 3, Anisotropic = 4, HighQualityCubic = 5 }
CanvasImageInterpolation
csharp
ChilliCream__graphql-platform
src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs
{ "start": 689703, "end": 690086 }
public partial interface ____ : IOnClientVersionPublishUpdated_OnClientVersionPublishingUpdate_Deployment_Errors_Changes_Changes_3, IInterfaceImplementationAdded { } [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
IOnClientVersionPublishUpdated_OnClientVersionPublishingUpdate_Deployment_Errors_Changes_Changes_InterfaceImplementationAdded
csharp
grandnode__grandnode2
src/Web/Grand.Web/Models/ShoppingCart/ShoppingCartModel.cs
{ "start": 179, "end": 1221 }
public class ____ : BaseModel { public bool ShowSku { get; set; } public bool ShowProductImages { get; set; } public bool IsEditable { get; set; } public bool IsAllowOnHold { get; set; } public bool TermsOfServicePopup { get; set; } public IList<ShoppingCartItemModel> Items { get; set; } = new List<ShoppingCartItemModel>(); public string CheckoutAttributeInfo { get; set; } public IList<CheckoutAttributeModel> CheckoutAttributes { get; set; } = new List<CheckoutAttributeModel>(); public IList<string> Warnings { get; set; } = new List<string>(); public string MinOrderSubtotalWarning { get; set; } public bool ShowCheckoutAsGuestButton { get; set; } public bool IsGuest { get; set; } public bool TermsOfServiceOnShoppingCartPage { get; set; } public bool TermsOfServiceOnOrderConfirmPage { get; set; } public DiscountBoxModel DiscountBox { get; set; } = new(); public GiftVoucherBoxModel GiftVoucherBox { get; set; } = new(); #region Nested Classes
ShoppingCartModel
csharp
microsoft__semantic-kernel
dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/AI21Labs/AI21JurassicRequest.cs
{ "start": 404, "end": 3211 }
internal sealed class ____ { /// <summary> /// The input prompt as required by AI21 Labs Jurassic. /// </summary> [JsonPropertyName("prompt")] public string? Prompt { get; set; } /// <summary> /// Use a lower value to decrease randomness in the response. /// </summary> [JsonPropertyName("temperature")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public float? Temperature { get; set; } /// <summary> /// Use a lower value to ignore less probable options. /// </summary> [JsonPropertyName("topP")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public float? TopP { get; set; } /// <summary> /// Specify the maximum number of tokens to use in the generated response. /// </summary> [JsonPropertyName("maxTokens")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public int? MaxTokens { get; set; } /// <summary> /// Configure stop sequences that the model recognizes and after which it stops generating further tokens. Press the Enter key to insert a newline character in a stop sequence. Use the Tab key to finish inserting a stop sequence. /// </summary> [JsonPropertyName("stopSequences")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public IList<string>? StopSequences { get; set; } /// <summary> /// Use a higher value to lower the probability of generating new tokens that already appear at least once in the prompt or in the completion. Proportional to the number of appearances. /// </summary> [JsonPropertyName("countPenalty")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public AI21JurassicPenalties? CountPenalty { get; set; } /// <summary> /// Use a higher value to lower the probability of generating new tokens that already appear at least once in the prompt or in the completion. /// </summary> [JsonPropertyName("presencePenalty")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public AI21JurassicPenalties? PresencePenalty { get; set; } /// <summary> /// Use a high value to lower the probability of generating new tokens that already appear at least once in the prompt or in the completion. The value is proportional to the frequency of the token appearances (normalized to text length). /// </summary> [JsonPropertyName("frequencyPenalty")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] public AI21JurassicPenalties? FrequencyPenalty { get; set; } } }
AI21JurassicTextGenerationRequest
csharp
AutoMapper__AutoMapper
src/UnitTests/ConfigurationValidation.cs
{ "start": 16990, "end": 17076 }
public class ____ { public List<DestinationItem> Items; }
Destination