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 | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Networking.NetworkOperators/NetworkDeviceStatus.cs | {
"start": 273,
"end": 1382
} | public enum ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
DeviceNotReady = 0,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
DeviceReady = 1,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
SimNotInserted = 2,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
BadSim = 3,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
DeviceHardwareFailure = 4,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
AccountNotActivated = 5,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
DeviceLocked = 6,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
DeviceBlocked = 7,
#endif
}
#endif
}
| NetworkDeviceStatus |
csharp | dotnet__efcore | test/EFCore.Tests/Metadata/Conventions/RelationshipDiscoveryConventionTest.cs | {
"start": 63185,
"end": 64139
} | private class ____
{
public int Id { get; set; }
public IEnumerable<MultipleNavigationsFirst> MultipleNavigationsFirsts { get; set; }
public MultipleNavigationsFirst MultipleNavigationsFirst { get; set; }
public static void IgnoreCollectionNavigation(IConventionEntityTypeBuilder entityTypeBuilder)
{
if (entityTypeBuilder.Metadata.ClrType == typeof(MultipleNavigationsSecond))
{
entityTypeBuilder.Ignore(nameof(MultipleNavigationsFirsts), fromDataAnnotation: true);
}
}
public static void IgnoreNonCollectionNavigation(IConventionEntityTypeBuilder entityTypeBuilder)
{
if (entityTypeBuilder.Metadata.ClrType == typeof(MultipleNavigationsSecond))
{
entityTypeBuilder.Ignore(nameof(MultipleNavigationsFirst), fromDataAnnotation: true);
}
}
}
| MultipleNavigationsSecond |
csharp | dotnet__efcore | test/EFCore.Tests/Metadata/Internal/PropertyTest.cs | {
"start": 21225,
"end": 21925
} | private class ____ : JsonValueReaderWriter<string>
{
private static JasonValueReaderWriterWithPrivateInstance Instance { get; } = new();
public override string FromJsonTyped(ref Utf8JsonReaderManager manager, object existingObject = null)
=> manager.CurrentReader.GetString()!;
public override void ToJsonTyped(Utf8JsonWriter writer, string value)
=> writer.WriteStringValue(value);
private readonly Expression<Func<JasonValueReaderWriterWithPrivateInstance>> _instanceLambda = () => Instance;
public override Expression ConstructorExpression
=> _instanceLambda.Body;
}
| JasonValueReaderWriterWithPrivateInstance |
csharp | nuke-build__nuke | source/Nuke.Build/NukeBuild.Interface.cs | {
"start": 340,
"end": 1760
} | partial class ____
{
IReadOnlyCollection<ExecutableTarget> INukeBuild.ExecutableTargets => ExecutableTargets;
bool INukeBuild.IsInterceptorExecution => IsInterceptorExecution;
string[] INukeBuild.LoadedLocalProfiles => LoadedLocalProfiles;
bool INukeBuild.IsOutputEnabled(DefaultOutput output) => IsOutputEnabled(output);
AbsolutePath INukeBuild.RootDirectory => RootDirectory;
AbsolutePath INukeBuild.TemporaryDirectory => TemporaryDirectory;
AbsolutePath INukeBuild.BuildAssemblyFile => BuildAssemblyFile;
AbsolutePath INukeBuild.BuildAssemblyDirectory => BuildAssemblyDirectory;
AbsolutePath INukeBuild.BuildProjectDirectory => BuildProjectDirectory;
AbsolutePath INukeBuild.BuildProjectFile => BuildProjectFile;
Verbosity INukeBuild.Verbosity => Verbosity;
Host INukeBuild.Host => Host;
bool INukeBuild.Plan => Plan;
bool INukeBuild.Help => Help;
bool INukeBuild.NoLogo => NoLogo;
bool INukeBuild.IsLocalBuild => IsLocalBuild;
bool INukeBuild.IsServerBuild => IsServerBuild;
bool INukeBuild.Continue => Continue;
T INukeBuild.TryGetValue<T>(Expression<Func<T>> parameterExpression)
{
return ValueInjectionUtility.TryGetValue(parameterExpression);
}
T INukeBuild.TryGetValue<T>(Expression<Func<object>> parameterExpression)
{
return ValueInjectionUtility.TryGetValue<T>(parameterExpression);
}
}
| NukeBuild |
csharp | dotnet__aspire | src/Aspire.Hosting.Azure.CosmosDB/AzureCosmosDBExtensions.cs | {
"start": 29761,
"end": 30656
} | internal class ____ : CosmosDBSqlRoleDefinition
{
private BicepValue<string>? _nameOverride;
public CosmosDBSqlRoleDefinition_Derived(string name) : base(name)
{
}
public static CosmosDBSqlRoleDefinition_Derived FromExisting(string bicepIdentifier)
{
return new CosmosDBSqlRoleDefinition_Derived(bicepIdentifier)
{
IsExistingResource = true
};
}
public BicepValue<string> NameOverride
{
get
{
Initialize();
return _nameOverride!;
}
set
{
Initialize();
_nameOverride!.Assign(value);
}
}
protected override void DefineProvisionableProperties()
{
base.DefineProvisionableProperties();
_nameOverride = DefineProperty<string>("Name", new string[1] { "name" });
}
}
| CosmosDBSqlRoleDefinition_Derived |
csharp | nunit__nunit | src/NUnitFramework/tests/Syntax/StringConstraintsTests.cs | {
"start": 686,
"end": 958
} | public class ____ : SyntaxTest
{
[SetUp]
public void SetUp()
{
ParseTree = @"<startswith ""X"">";
StaticSyntax = Does.StartWith("X");
BuilderSyntax = Builder().StartsWith("X");
}
}
| StartsWithTest |
csharp | SixLabors__ImageSharp | tests/ImageSharp.Tests/TestUtilities/Tests/TestImageProviderTests.cs | {
"start": 16807,
"end": 16955
} | private class ____ : ISpecializedDecoderOptions
{
public DecoderOptions GeneralOptions { get; init; } = new();
}
| TestDecoderOptions |
csharp | dotnet-architecture__eShopOnWeb | src/PublicApi/CatalogItemEndpoints/CreateCatalogItemEndpoint.cs | {
"start": 595,
"end": 3260
} | public class ____ : IEndpoint<IResult, CreateCatalogItemRequest, IRepository<CatalogItem>>
{
private readonly IUriComposer _uriComposer;
public CreateCatalogItemEndpoint(IUriComposer uriComposer)
{
_uriComposer = uriComposer;
}
public void AddRoute(IEndpointRouteBuilder app)
{
app.MapPost("api/catalog-items",
[Authorize(Roles = BlazorShared.Authorization.Constants.Roles.ADMINISTRATORS, AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] async
(CreateCatalogItemRequest request, IRepository<CatalogItem> itemRepository) =>
{
return await HandleAsync(request, itemRepository);
})
.Produces<CreateCatalogItemResponse>()
.WithTags("CatalogItemEndpoints");
}
public async Task<IResult> HandleAsync(CreateCatalogItemRequest request, IRepository<CatalogItem> itemRepository)
{
var response = new CreateCatalogItemResponse(request.CorrelationId());
var catalogItemNameSpecification = new CatalogItemNameSpecification(request.Name);
var existingCataloogItem = await itemRepository.CountAsync(catalogItemNameSpecification);
if (existingCataloogItem > 0)
{
throw new DuplicateException($"A catalogItem with name {request.Name} already exists");
}
var newItem = new CatalogItem(request.CatalogTypeId, request.CatalogBrandId, request.Description, request.Name, request.Price, request.PictureUri);
newItem = await itemRepository.AddAsync(newItem);
if (newItem.Id != 0)
{
//We disabled the upload functionality and added a default/placeholder image to this sample due to a potential security risk
// pointed out by the community. More info in this issue: https://github.com/dotnet-architecture/eShopOnWeb/issues/537
// In production, we recommend uploading to a blob storage and deliver the image via CDN after a verification process.
newItem.UpdatePictureUri("eCatalog-item-default.png");
await itemRepository.UpdateAsync(newItem);
}
var dto = new CatalogItemDto
{
Id = newItem.Id,
CatalogBrandId = newItem.CatalogBrandId,
CatalogTypeId = newItem.CatalogTypeId,
Description = newItem.Description,
Name = newItem.Name,
PictureUri = _uriComposer.ComposePicUri(newItem.PictureUri),
Price = newItem.Price
};
response.CatalogItem = dto;
return Results.Created($"api/catalog-items/{dto.Id}", response);
}
}
| CreateCatalogItemEndpoint |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/AutoQueryCrudModels.cs | {
"start": 6874,
"end": 7346
} | public class ____ : CreateAuditTenantBase<RockstarAuditTenant, RockstarWithIdAndResultResponse>, IHasBearerToken
{
public string BearerToken { get; set; } //Authenticate MQ Requests
public string FirstName { get; set; }
public string LastName { get; set; }
public int? Age { get; set; }
public DateTime DateOfBirth { get; set; }
public DateTime? DateDied { get; set; }
public LivingStatus LivingStatus { get; set; }
}
| CreateRockstarAuditTenant |
csharp | dotnet__orleans | src/api/Orleans.Core.Abstractions/Orleans.Core.Abstractions.cs | {
"start": 61697,
"end": 61941
} | partial class ____ : System.Attribute
{
}
[InvokableCustomInitializer("AddInvokeMethodOptions", CodeGeneration.InvokeMethodOptions.ReadOnly)]
[System.AttributeUsage(System.AttributeTargets.Method)]
public sealed | OneWayAttribute |
csharp | unoplatform__uno | src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/FrameTests/FrameTests_TransparentPage.xaml.cs | {
"start": 169,
"end": 398
} | partial class ____ : Page
{
public FrameTests_TransparentPage()
{
this.InitializeComponent();
}
/// <inheritdoc />
protected override void OnTapped(TappedRoutedEventArgs e)
=> e.Handled = true;
}
| FrameTests_TransparentPage |
csharp | neuecc__MessagePack-CSharp | src/MessagePack/Resolvers/DynamicObjectResolver.cs | {
"start": 89984,
"end": 98065
} | internal class ____
{
internal EmittableMember(MemberInfo memberInfo)
{
this.MemberInfo = memberInfo;
}
internal bool IsProperty => this.PropertyInfo is not null;
internal bool IsField => this.FieldInfo is not null;
internal bool IsWritable { get; set; }
internal bool IsWrittenByConstructor { get; set; }
/// <summary>
/// Gets a value indicating whether the property can only be set by an object initializer, a constructor, or another `init` member.
/// </summary>
internal bool IsInitOnly => this.PropertyInfo?.GetSetMethod(true)?.ReturnParameter.GetRequiredCustomModifiers().Any(modifierType => modifierType.FullName == "System.Runtime.CompilerServices.IsExternalInit") ?? false;
internal bool IsReadable { get; set; }
internal int IntKey { get; set; }
internal string? StringKey { get; set; }
internal Type Type => this.FieldInfo?.FieldType ?? this.PropertyInfo!.PropertyType;
internal MemberInfo MemberInfo { get; }
internal FieldInfo? FieldInfo => this.MemberInfo as FieldInfo;
internal string Name => this.PropertyInfo?.Name ?? this.FieldInfo!.Name;
internal PropertyInfo? PropertyInfo => this.MemberInfo as PropertyInfo;
internal bool IsValueType
{
get
{
Type t = this.PropertyInfo?.PropertyType ?? this.FieldInfo!.FieldType;
return t.IsValueType;
}
}
/// <summary>
/// Gets or sets a value indicating whether this member is explicitly opted in with an attribute.
/// </summary>
internal bool IsExplicitContract { get; set; }
#if !NET6_0_OR_GREATER
/// <summary>
/// Gets or sets a value indicating whether this member is a property with an <see langword="init" /> property setter
/// that must be set via a <see cref="DynamicMethod"/> rather than directly by a <see cref="MethodBuilder"/>.
/// </summary>
/// <remarks>
/// <see href="https://github.com/neuecc/MessagePack-CSharp/issues/1134">A bug</see> in <see cref="MethodBuilder"/>
/// blocks its ability to invoke property init accessors when in a generic class.
/// </remarks>
internal bool IsProblematicInitProperty { get; set; }
#endif
internal MessagePackFormatterAttribute? GetMessagePackFormatterAttribute()
{
return this.PropertyInfo is not null
? this.PropertyInfo.GetCustomAttribute<MessagePackFormatterAttribute>(true)
: this.FieldInfo!.GetCustomAttribute<MessagePackFormatterAttribute>(true);
}
internal DataMemberAttribute? GetDataMemberAttribute()
{
return this.PropertyInfo is not null
? this.PropertyInfo.GetCustomAttribute<DataMemberAttribute>(true)
: this.FieldInfo!.GetCustomAttribute<DataMemberAttribute>(true);
}
internal void EmitLoadValue(ILGenerator il)
{
if (this.PropertyInfo is not null)
{
il.EmitCall(this.PropertyInfo.GetGetMethod(true) ?? throw new Exception("No get accessor"));
}
else
{
il.Emit(OpCodes.Ldfld, this.FieldInfo!);
}
}
#if !NET6_0_OR_GREATER
private delegate void PropertySetterHelperForStructs<T, TValue>(ref T target, TValue value)
where T : struct;
private Delegate? setterHelperDelegate;
private FieldBuilder? setterHelperField;
internal void OnTypeCreated(TypeInfo formatterType)
{
if (this.setterHelperDelegate is not null && this.setterHelperField is not null)
{
// Set this delegate to a static field on the dynamic formatter so that we can invoke it here.
formatterType.GetField(this.setterHelperField.Name, BindingFlags.Static | BindingFlags.NonPublic)!.SetValue(null, this.setterHelperDelegate);
}
}
#endif
internal void EmitPreStoreValue(TypeBuilder typeBuilder, ILGenerator il, LocalBuilder localResult)
{
#if !NET6_0_OR_GREATER
if (this.PropertyInfo is not null && this.IsProblematicInitProperty)
{
// On all runtimes older than .NET 6 (i.e. .NET Framework), a bug prevents MethodBuilder from being able to generate code that calls
// a property "init" setter that belongs to a generic type.
// But DynamicMethod does not share that bug. So we'll use a DynamicMethod to workaround this and invoke that from our MethodBuilder code.
Type[] parameterTypes = [localResult.LocalType.IsClass ? this.MemberInfo.DeclaringType : this.MemberInfo.DeclaringType.MakeByRefType(), this.Type];
DynamicMethod dynamicMethod = new($"Set{this.Name}Helper", null, parameterTypes);
ILGenerator dynamicMethodIL = dynamicMethod.GetILGenerator();
dynamicMethodIL.Emit(OpCodes.Ldarg_0);
dynamicMethodIL.Emit(OpCodes.Ldarg_1);
dynamicMethodIL.EmitCall(this.PropertyInfo.GetSetMethod(true) ?? throw new Exception("No set accessor"));
dynamicMethodIL.Emit(OpCodes.Ret);
Type delegateType = (localResult.LocalType.IsClass ? typeof(Action<,>) : typeof(PropertySetterHelperForStructs<,>)).MakeGenericType([this.MemberInfo.DeclaringType, this.Type]);
this.setterHelperDelegate = dynamicMethod.CreateDelegate(delegateType);
// Define a static field on the formatter that will store the delegate once the formatter type is created.
this.setterHelperField = typeBuilder.DefineField($"{this.Name}Setter", delegateType, FieldAttributes.Private | FieldAttributes.Static);
// Now emit code which at runtime will read from that field to get the delegate onto the stack for invocation.
il.Emit(OpCodes.Ldsfld, this.setterHelperField);
}
#endif
if (localResult.LocalType.IsClass)
{
il.EmitLdloc(localResult);
}
else
{
il.EmitLdloca(localResult);
}
}
internal void EmitStoreValue(ILGenerator il, TypeBuilder typeBuilder)
{
if (this.PropertyInfo is not null)
{
#if !NET6_0_OR_GREATER
if (this.IsProblematicInitProperty)
{
// Use a DynamicMethod to workaround this.
if (this.setterHelperDelegate is null)
{
throw new Exception();
}
// EmitPreStoreValue loaded the delegate and target object onto the stack.
// Our caller then pushed the value to set onto the stack.
// All we need to do now is invoke the setter delegate.
il.Emit(OpCodes.Callvirt, this.setterHelperDelegate.GetType().GetMethod("Invoke") ?? throw new Exception("Unable to find Invoke method"));
}
else
#endif
{
il.EmitCall(this.PropertyInfo.GetSetMethod(true) ?? throw new Exception("No set accessor"));
}
}
else
{
il.Emit(OpCodes.Stfld, this.FieldInfo!);
}
}
}
| EmittableMember |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Fusion-vnext/test/Fusion.Composition.Tests/SourceSchemaEnricherTests.cs | {
"start": 193,
"end": 974
} | public sealed class ____
{
[Fact]
public void Enrich_SourceSchema_SetsIsKeyFieldAndIsShareableMetadata()
{
// arrange
var sourceSchemaText =
new SourceSchemaText(
"A",
"""
type Product
@key(fields: "id, category { id }")
@key(fields: "sku")
@key(fields: "alreadyShareable")
@key(fields: "externalField") {
id: ID!
category: Category!
sku: String!
alreadyShareable: String! @shareable
externalField: String! @external
nonKeyField: String
}
| SourceSchemaEnricherTests |
csharp | dotnet__efcore | test/EFCore.Tests/Metadata/Conventions/RelationshipDiscoveryConventionTest.cs | {
"start": 52882,
"end": 52957
} | private interface ____
{
int Id { get; set; }
}
| IInterface |
csharp | unoplatform__uno | src/Uno.UI.RuntimeTests/Tests/Windows_Storage/Given_StorageFile_Native.Android.cs | {
"start": 382,
"end": 801
} | public class ____ : Given_StorageFile_Native_Base
{
protected override Task<StorageFolder> GetRootFolderAsync()
{
var localCache = ApplicationData.Current.LocalCacheFolder.Path;
var directory = new File(localCache);
var documentFile = DocumentFile.FromFile(directory);
var rootFolder = StorageFolder.GetFromSafDocument(documentFile);
return Task.FromResult(rootFolder);
}
}
}
| Given_StorageFile_Native |
csharp | mongodb__mongo-csharp-driver | tests/MongoDB.Bson.Tests/Serialization/Serializers/TimeSpanSerializerTests.cs | {
"start": 2487,
"end": 3311
} | public class ____ : IC
{
public int Id { get; set; }
[BsonTimeSpanOptions(BsonType.Double, TimeSpanUnits.Days)]
public TimeSpan T { get; set; }
}
[Theory]
[InlineData(0.0)]
[InlineData(0.0000000000011574074074074074)] // 1 Tick
[InlineData(1.5)]
[InlineData(11.5)]
[InlineData(10675199.116730063)] // largest number of Days that can be represented by a TimeSpan
[InlineData(-1.5)]
[InlineData(-11.5)]
[InlineData(-10675199.116730064)] // largest number of Days that can be represented by a TimeSpan
public void TestDays(double days)
{
var ticks = (long)(days * TimeSpan.TicksPerDay);
TimeSpanSerializerTestsHelper<C>.TestValue(ticks, days);
}
}
| C |
csharp | StackExchange__StackExchange.Redis | src/StackExchange.Redis/ResultProcessor.cs | {
"start": 101925,
"end": 102170
} | internal sealed class ____ : InterleavedStreamInfoProcessorBase<StreamConsumerInfo>
{
protected override StreamConsumerInfo ParseItem(in RawResult result)
{
// Note: the base | StreamConsumerInfoProcessor |
csharp | serilog__serilog-extensions-logging | src/Serilog.Extensions.Logging/SerilogLoggingBuilderExtensions.cs | {
"start": 844,
"end": 1533
} | public static class ____
{
/// <summary>
/// Add Serilog to the logging pipeline.
/// </summary>
/// <param name="builder">The <see cref="T:Microsoft.Extensions.Logging.ILoggingBuilder" /> to add logging provider to.</param>
/// <param name="logger">The Serilog logger; if not supplied, the static <see cref="Serilog.Log"/> will be used.</param>
/// <param name="dispose">When true, dispose <paramref name="logger"/> when the framework disposes the provider. If the
/// logger is not specified but <paramref name="dispose"/> is true, the <see cref="Log.CloseAndFlush()"/> method will be
/// called on the static <see cref="Log"/> | SerilogLoggingBuilderExtensions |
csharp | Antaris__RazorEngine | src/source/RazorEngine.Core/Compilation/ICompilerServiceFactory.cs | {
"start": 184,
"end": 634
} | public interface ____
{
#region Methods
/// <summary>
/// Creates a <see cref="ICompilerService"/> that supports the specified language.
/// </summary>
/// <param name="language">The <see cref="Language"/>.</param>
/// <returns>An instance of <see cref="ICompilerService"/>.</returns>
ICompilerService CreateCompilerService(Language language);
#endregion
}
}
| ICompilerServiceFactory |
csharp | grandnode__grandnode2 | src/Web/Grand.Web/Models/Customer/CustomerInfoModel.cs | {
"start": 5951,
"end": 6175
} | public class ____ : BaseEntityModel
{
public string Email { get; set; }
public string ExternalIdentifier { get; set; }
public string AuthMethodName { get; set; }
}
| AssociatedExternalAuthModel |
csharp | unoplatform__uno | src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Controls/UniformGridLayoutItemsStretch.cs | {
"start": 224,
"end": 581
} | public enum ____
{
// Skipping already declared field Microsoft.UI.Xaml.Controls.UniformGridLayoutItemsStretch.None
// Skipping already declared field Microsoft.UI.Xaml.Controls.UniformGridLayoutItemsStretch.Fill
// Skipping already declared field Microsoft.UI.Xaml.Controls.UniformGridLayoutItemsStretch.Uniform
}
#endif
}
| UniformGridLayoutItemsStretch |
csharp | AutoMapper__AutoMapper | src/IntegrationTests/IncludeMembers.cs | {
"start": 574,
"end": 787
} | public class ____
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Title { get; set; }
}
| OtherInnerSource |
csharp | unoplatform__uno | src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Input/HoldingState.cs | {
"start": 216,
"end": 490
} | public enum ____
{
// Skipping already declared field Microsoft.UI.Input.HoldingState.Started
// Skipping already declared field Microsoft.UI.Input.HoldingState.Completed
// Skipping already declared field Microsoft.UI.Input.HoldingState.Canceled
}
#endif
}
| HoldingState |
csharp | dotnet__machinelearning | src/Microsoft.ML.Transforms/Expression/Node.cs | {
"start": 28085,
"end": 28902
} | internal sealed class ____ : ExprNode
{
public readonly ExprNode Arg;
public readonly UnaryOp Op;
public UnaryOpNode(Token tok, UnaryOp op, ExprNode arg)
: base(tok)
{
Contracts.AssertValue(arg);
Arg = arg;
Op = op;
}
public override NodeKind Kind { get { return NodeKind.UnaryOp; } }
public override UnaryOpNode AsUnaryOp { get { return this; } }
public override UnaryOpNode TestUnaryOp { get { return this; } }
public override void Accept(NodeVisitor visitor)
{
Contracts.AssertValue(visitor);
if (visitor.PreVisit(this))
{
Arg.Accept(visitor);
visitor.PostVisit(this);
}
}
}
| UnaryOpNode |
csharp | EventStore__EventStore | src/KurrentDB.SecondaryIndexing.Tests/Observability/MessagesBatchObserver.cs | {
"start": 743,
"end": 1707
} | public class ____ : IMessagesBatchObserver {
private long _totalCount;
public void On(TestMessageBatch batch) {
long messagesCount = batch.Messages.Length;
Categories.AddOrUpdate(batch.CategoryName, messagesCount, (_, current) => current + messagesCount);
foreach (var messagesByType in batch.Messages.GroupBy(e => e.EventType)) {
var eventTypeCount = (long)messagesByType.Count();
EventTypes.AddOrUpdate(messagesByType.Key, eventTypeCount, (_, current) => current + eventTypeCount);
}
Interlocked.Add(ref _totalCount, messagesCount);
}
public ConcurrentDictionary<string, long> Categories { get; } = new();
public ConcurrentDictionary<string, long> EventTypes { get; } = new();
public long TotalCount => Interlocked.Read(ref _totalCount);
public IndexingSummary Summary => new(
Categories.ToDictionary(ks => ks.Key, vs => vs.Value),
EventTypes.ToDictionary(ks => ks.Key, vs => vs.Value),
TotalCount
);
}
| SimpleMessagesBatchObserver |
csharp | xunit__xunit | src/xunit.v2.tests/Acceptance/Xunit2AcceptanceTests.cs | {
"start": 20864,
"end": 21459
} | class ____ : ClassWithAsyncLifetime
{
public ClassWithAsyncLifetime_FailingTest(ITestOutputHelper output) : base(output) { }
public override void TheTest()
{
base.TheTest();
throw new DivideByZeroException();
}
}
void AssertOperations(ITestResultMessage result, params string[] operations)
{
Assert.Collection(
result.Output.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries),
operations.Select<string, Action<string>>(expected => actual => Assert.Equal(expected, actual)).ToArray()
);
}
}
| ClassWithAsyncLifetime_FailingTest |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Input/FocusManager.mux.cs | {
"start": 791,
"end": 108750
} | public partial class ____ : IFocusManager
{
/// <summary>
/// Represents the content root with which this focus manager is associated.
/// </summary>
private readonly ContentRoot _contentRoot;
/// <summary>
/// Responsible for drawing the focus rectangles.
/// </summary>
private readonly FocusRectManager _focusRectManager = new FocusRectManager();
/// <summary>
/// Represents the currently focused element.
/// </summary>
private DependencyObject? _focusedElement;
/// <summary>
/// Represents the element being focused.
/// </summary>
private DependencyObject? _focusingElement;
/// <summary>
/// Focused element's AutomationPeer.
/// </summary>
private AutomationPeer? _focusedAutomationPeer;
/// <summary>
/// Represents the focus target.
/// </summary>
private DependencyObject? _focusTarget;
/// <summary>
/// Represents the focus visual.
/// </summary>
private WeakReference<UIElement>? _focusRectangleUIElement;
/// <summary>
/// Indicates whether plugin is focused.
/// </summary>
private bool _pluginFocused = true; //TODO Uno: In case of WASM we could check whether the tab is currently visible/focused.
/// <summary>
/// Represents the real focus state for the currently focused element.
/// </summary>
private FocusState _realFocusStateForFocusedElement;
/// <summary>
/// Foccus observer.
/// </summary>
private FocusObserver? _focusObserver;
/// <summary>
/// Represents the XY focus manager.
/// </summary>
private XYFocus _xyFocus = new XYFocus();
/// <summary>
/// This is a leftover from Silverlight times :-) .
/// When the platform cannot support tabbing out of plugin, we will act as if
/// there is an implicit top-level TabNavigation="Cycle"
/// So instead of tabbing out, we handle the "last" tab by cycling to the
/// "first" tab. This is deemed better than getting stuck at the end.
/// (Reverse "first" and "last" for Shift-Tab.)
/// </summary>
private static readonly bool _canTabOutOfPlugin =
OperatingSystem.IsBrowser(); // For WASM it is more appropriate to let the user escape from the app to tab into the browser toolbars.
private bool _isPrevFocusTextControl;
// TODO Uno: Control engagement is not yet properly supported.
/// <summary>
/// Represents the control which is focus-engaged.
/// </summary>
private Control? _engagedControl;
/// <summary>
/// Represents a value indicating whether focus is currently locked.
/// </summary>
private bool _focusLocked;
/// <summary>
/// During Window Activation/Deactivation, we lock focus. However, focus can move internally via the focused element becoming
/// unfocusable (ie. leaving the tree or changing visibility). This member will force focus manager to bypass the _focusLocked logic.
/// This should be used with care... if used irresponsibly, we can enable unsupported reentrancy scenarios.
/// </summary>
private bool _ignoreFocusLock;
/// <summary>
/// It is possible to continue with a focus operation, even though focus is locked. In this case, we need to ensure
/// that we persist the fact that focus should not be canceled.
/// </summary>
private bool _currentFocusOperationCancellable = true;
/// <summary>
/// Represents a valud indicating whether we are still to provide the initial focus.
/// </summary>
private bool _initialFocus;
/// <summary>
/// This represents the async operation that can initiated through a public async FocusManager method, such as TryFocusAsync.
/// We store it as a memeber because the operation can continue to run even after the api has finished executing.
/// </summary>
private FocusAsyncOperation? _asyncOperation;
internal FocusManager(ContentRoot contentRoot)
{
_contentRoot = contentRoot ?? throw new ArgumentNullException(nameof(contentRoot));
}
internal event EventHandler<FocusedElementRemovedEventArgs>? FocusedElementRemoved;
/// <summary>
/// Returns the current focused element.
/// </summary>
internal DependencyObject? FocusedElement => _focusedElement;
/// <summary>
/// Returns the element about to be focused when focus is changing
/// </summary>
internal DependencyObject? FocusingElement => _focusingElement;
/// <summary>
/// Returns the content root associated with this focus manager instance.
/// </summary>
internal ContentRoot ContentRoot => _contentRoot;
/// <summary>
/// Focus rect manager.
/// </summary>
internal FocusRectManager FocusRectManager => _focusRectManager;
/// <summary>
/// Gets a value indicating whether the user can tab out of plugin.
/// </summary>
internal bool CanTabOutOfPlugin => _canTabOutOfPlugin;
/// <summary>
/// Represents the control which is focus-engaged.
/// </summary>
internal Control? EngagedControl
{
get => _engagedControl;
set => _engagedControl = value;
}
//TODO Uno: Currently we set this only from Page, but should be set from other places as well.
/// <summary>
/// Represents a value indicating whether we are still to provide the initial focus.
/// </summary>
internal bool InitialFocus
{
get => _initialFocus;
set => _initialFocus = value;
}
internal void SetIgnoreFocusLock(bool ignore) => _ignoreFocusLock = ignore;
/// <summary>
/// Focus observer getter, checking for null.
/// </summary>
internal FocusObserver FocusObserver => _focusObserver ?? throw new InvalidOperationException("Focus observer was not set.");
/// <summary>
/// Sets the focus observer.
/// </summary>
/// <param name="focusObserver"></param>
internal void SetFocusObserver(FocusObserver focusObserver) => _focusObserver = focusObserver;
/// <summary>
/// Sets focused element based on FocusMovement, if target is not focusable, tries to find first
/// focusable in it. Validates whether the navigation direction matches the situation (tabbing).
/// In the end updates focus with UpdateFocus method.
/// </summary>
/// <param name="movement">Focus movement.</param>
/// <returns>Focus movement result.</returns>
internal FocusMovementResult SetFocusedElement(FocusMovement movement)
{
var focusTarget = movement.Target;
if (focusTarget == null)
{
return new FocusMovementResult();
}
if (!IsFocusable(focusTarget))
{
focusTarget = GetFirstFocusableElement(focusTarget);
if (focusTarget == null || !IsFocusable(focusTarget))
{
return new FocusMovementResult();
}
}
var navigationDirection = movement.Direction;
MUX_ASSERT(!movement.IsProcessingTab || (navigationDirection == FocusNavigationDirection.Next || navigationDirection == FocusNavigationDirection.Previous));
return UpdateFocus(new FocusMovement(focusTarget, movement));
}
/// <summary>
/// Clears the focus.
/// </summary>
/// <remarks>
/// Original code checks for "shutting down", which is not supported in Uno,
/// so we always go through UpdateFocus.
/// </remarks>
internal void ClearFocus() => UpdateFocus(new FocusMovement(null, FocusNavigationDirection.None, FocusState.Unfocused));
/// <summary>
/// Releases resources held by FocusManager's FocusRectManager. These
/// elements are automatically created on CFrameworkManager.UpdateFocus()
/// and must be released before core releases its main render target on
/// shutdown.
/// </summary>
internal void ReleaseFocusRectManagerResources()
{
// Releases references on UIElements held by CFocusRectManager
_focusRectManager.ReleaseResources(isDeviceLost: false, cleanupDComp: false, clearPCData: true);
}
/// <summary>
/// Cleans up device related resources.
/// </summary>
/// <param name="cleanupDComp">Cleanup.</param>
internal void CleanupDeviceRelatedResources(bool cleanupDComp) =>
_focusRectManager.ReleaseResources(isDeviceLost: true, cleanupDComp, clearPCData: false);
/// <summary>
/// Checks whether the focused element is hidden behind full
/// window media.
/// </summary>
/// <returns>True if hidden, false otherwise.</returns>
private bool FocusedElementIsBehindFullWindowMediaRoot()
{
var visualTree = _contentRoot.VisualTree;
return visualTree != null && visualTree.IsBehindFullWindowMediaRoot(_focusedElement);
}
/// <summary>
/// Returns first focusable element from root visual based on given direction (first/last).
/// </summary>
/// <param name="useReverseDirection">Should be reverse direction?</param>
/// <returns>Focusable element or null.</returns>
private DependencyObject? GetFirstFocusableElementFromRoot(bool useReverseDirection)
{
DependencyObject? pFocusableElement = null;
var activeRootVisual = _contentRoot.VisualTree.ActiveRootVisual;
if (activeRootVisual != null)
{
if (!useReverseDirection)
{
pFocusableElement = GetFirstFocusableElement(activeRootVisual, pFocusableElement);
}
else
{
pFocusableElement = GetLastFocusableElement(activeRootVisual, pFocusableElement);
}
}
return pFocusableElement;
}
/// <summary>
/// Returns the first focusable element from the specified visual tree.
/// </summary>
/// <param name="searchStartLocation">Location where to start searching.</param>
/// <param name="focusCandidate">First focused element candidate.</param>
/// <returns>First focusable element.</returns>
internal DependencyObject? GetFirstFocusableElement(DependencyObject searchStartLocation, DependencyObject? focusCandidate = null)
{
focusCandidate = GetFirstFocusableElementInternal(searchStartLocation, focusCandidate);
// GetFirstFocusableElementInternal can return the TabStop element that might not a focusable
// container like as UserControl(IsTabStop=false) even though it have a focusable child.
// If the pFirstFocus is not focusable and have a focusable child, the below code will find
// a first focusable child
// Keep finding the first focusable child
if (focusCandidate != null && !IsFocusable(focusCandidate) && CanHaveFocusableChildren(focusCandidate))
{
focusCandidate = GetFirstFocusableElement(focusCandidate, null);
}
return focusCandidate;
}
/// <summary>
/// Returns the first focusable element from the specified visual tree.
/// </summary>
/// <param name="searchStartLocation">Location where to start searching.</param>
/// <param name="firstFocusedElement">First focused element.</param>
/// <returns>First focusable element or null.</returns>
private DependencyObject? GetFirstFocusableElementInternal(DependencyObject searchStartLocation, DependencyObject? firstFocusedElement)
{
bool useFirstFocusableFromCallback = false;
// Ask UIElement for a first focusable suggestion(this is to solve ListViewBase focus issues).
var firstFocusableFromCallback = (searchStartLocation as UIElement)?.GetFirstFocusableElementOverride();
if (firstFocusableFromCallback != null)
{
useFirstFocusableFromCallback = IsFocusable(firstFocusableFromCallback) || CanHaveFocusableChildren(firstFocusableFromCallback);
}
if (useFirstFocusableFromCallback)
{
if (firstFocusedElement == null ||
(GetTabIndex(firstFocusableFromCallback) < GetTabIndex(firstFocusedElement)))
{
firstFocusedElement = firstFocusableFromCallback;
}
}
else
{
var children = FocusProperties.GetFocusChildrenInTabOrder(searchStartLocation);
foreach (var childNoRef in children)
{
if (childNoRef != null && IsVisible(childNoRef))
{
bool bHaveFocusableChild = CanHaveFocusableChildren(childNoRef);
if (IsPotentialTabStop(childNoRef))
{
if (firstFocusedElement == null && (IsFocusable(childNoRef) || bHaveFocusableChild))
{
firstFocusedElement = childNoRef;
}
if (IsFocusable(childNoRef) || bHaveFocusableChild)
{
if (GetTabIndex(childNoRef) < GetTabIndex(firstFocusedElement))
{
firstFocusedElement = childNoRef;
}
}
}
else if (bHaveFocusableChild)
{
firstFocusedElement = GetFirstFocusableElementInternal(childNoRef, firstFocusedElement);
}
}
}
}
return firstFocusedElement;
}
/// <summary>
/// Returns the last focusable element from the specified visual tree.
/// </summary>
/// <param name="searchStartLocation">Search start location.</param>
/// <param name="focusCandidate">Last foucsed element candidate.</param>
/// <returns></returns>
internal DependencyObject? GetLastFocusableElement(DependencyObject searchStartLocation, DependencyObject? focusCandidate = null)
{
focusCandidate = GetLastFocusableElementInternal(searchStartLocation, focusCandidate);
// GetLastFocusableElementInternal can return the TabStop element that might not a focusable
// container like as UserControl(IsTabStop=false) even though it have a focusable child.
// If the pLastFocus is not focusable and have a focusable child, the below code will find
// a last focusable child
if (focusCandidate != null && CanHaveFocusableChildren(focusCandidate))
{
focusCandidate = GetLastFocusableElement(focusCandidate, null);
}
return focusCandidate;
}
/// <summary>
/// Returns the last focusable element from the specified visual tree.
/// </summary>
/// <param name="searchStartLocation">Search start location.</param>
/// <param name="lastFocusedElement">Last focused elment.</param>
/// <returns>Last focusable element.</returns>
private DependencyObject? GetLastFocusableElementInternal(DependencyObject searchStartLocation, DependencyObject? lastFocusedElement)
{
bool useLastFocusableFromCallback = false;
// Ask UIElement for a first focusable suggestion(this is to solve ListViewBase focus issues).
var lastFocusableFromCallback = (searchStartLocation as UIElement)?.GetLastFocusableElementOverride();
if (lastFocusableFromCallback != null)
{
useLastFocusableFromCallback = IsFocusable(lastFocusableFromCallback) || CanHaveFocusableChildren(lastFocusableFromCallback);
}
if (useLastFocusableFromCallback)
{
if (lastFocusedElement == null ||
(GetTabIndex(lastFocusableFromCallback) >= GetTabIndex(lastFocusedElement)))
{
lastFocusedElement = lastFocusableFromCallback;
}
}
else
{
var children = FocusProperties.GetFocusChildrenInTabOrder(searchStartLocation);
foreach (var childNoRef in children)
{
if (childNoRef != null && IsVisible(childNoRef))
{
bool bHaveFocusableChild = CanHaveFocusableChildren(childNoRef);
if (IsPotentialTabStop(childNoRef))
{
if (lastFocusedElement == null && (IsFocusable(childNoRef) || bHaveFocusableChild))
{
lastFocusedElement = childNoRef;
}
if (IsFocusable(childNoRef) || bHaveFocusableChild)
{
if (GetTabIndex(childNoRef) >= GetTabIndex(lastFocusedElement))
{
lastFocusedElement = childNoRef;
}
}
}
else if (bHaveFocusableChild)
{
lastFocusedElement = GetLastFocusableElementInternal(childNoRef, lastFocusedElement);
}
}
}
}
return lastFocusedElement;
}
/// <summary>
/// Returns true if TabStop can be processed by us.
/// </summary>
/// <param name="isReverse">Use reverse direction?</param>
/// <returns></returns>
/// <remarks>
/// Checks whether FocusManager can process tab stop in a given direction.
/// First checks for popup, then if it is already on a boundary,
/// then includes special handling for once and cycle.
/// </remarks>
private bool CanProcessTabStop(bool isReverse)
{
bool canProcessTab = true;
bool isFocusOnFirst = false;
bool isFocusOnLast = false;
DependencyObject? pFocused = _focusedElement;
if (IsFocusedElementInPopup())
{
// focused element is inside a poup. Since we treat tabnavigation
// in popup as Cycle, we dont need to check if this element is
// the first or the last tabstop.
return true;
}
if (isReverse)
{
// Backward tab processing
isFocusOnFirst = IsFocusOnFirstTabStop();
}
else
{
// Forward tab processing
isFocusOnLast = IsFocusOnLastTabStop();
}
if (isFocusOnFirst || isFocusOnLast)
{
// Can't process tab from the focus on first or last
canProcessTab = false;
}
if (canProcessTab)
{
// Get the first/last focusable control. This is the opposite direction to check up
// the scope boundary. (e.g. Forward direction need to get the last focusable control)
DependencyObject? oppositeEdge = GetFirstFocusableElementFromRoot(!isReverse);
// Need to check the Once navigation mode to be out the plugin control
// if the current focus is on the edge boundary with Once mode.
if (oppositeEdge != null)
{
var oppositeEdgeParent = GetParentElement(oppositeEdge);
if (oppositeEdgeParent != null &&
GetTabNavigation(oppositeEdgeParent) == KeyboardNavigationMode.Once &&
oppositeEdgeParent == GetParentElement(pFocused))
{
// Can't process, so tab will be out of plugin
canProcessTab = false;
}
}
else
{
canProcessTab = false;
}
}
else
{
// We can process tab in case of Cycle navigation mode
// even though the focus is on the edge of plug-in control.
if (isFocusOnLast || isFocusOnFirst)
{
if (GetTabNavigation(pFocused) == KeyboardNavigationMode.Cycle)
{
canProcessTab = true;
}
else
{
UIElement? pFocusedParent = GetParentElement(pFocused);
while (pFocusedParent != null)
{
if (GetTabNavigation(pFocusedParent) == KeyboardNavigationMode.Cycle)
{
canProcessTab = true;
break;
}
pFocusedParent = GetParentElement(pFocusedParent);
}
}
}
}
return canProcessTab;
}
/// <summary>
/// Returns the candidate next or previous tab stop element.
/// </summary>
/// <param name="isReverse">Is shift pressed?</param>
/// <param name="queryOnly">Query only?</param>
/// <returns>Flag whether the search cycled at root visual scope and the candidate.</returns>
/// <remarks>
/// Retrieves the candidate for next tab stop depending on the direction
/// always taking two routes - next/prev.
/// </remarks>
private TabStopCandidateSearchResult GetTabStopCandidateElement(bool isReverse, bool queryOnly)
{
DependencyObject? pNewTabStop = null;
var didCycleFocusAtRootVisualScope = false;
var activeRoot = _contentRoot.VisualTree.ActiveRootVisual;
if (activeRoot == null)
{
return new TabStopCandidateSearchResult(false, null);
}
//------------------------------------------------------------------------
// Bug #29388
//
// The internalCycleWorkaround flag is a workaround for an issue in
// GetNextTabStop()/GetPreviousTabStop() where it fails to properly
// detect a TabNavigation="Cycle" in a root-level UserControl.
//
bool internalCycleWorkaround = false;
if (_focusedElement != null && _canTabOutOfPlugin)
{
// CanProcessTabStop() used to be an early-out test, but the heuristic
// is flawed and caused bugs like #25058.
internalCycleWorkaround = CanProcessTabStop(isReverse);
}
//------------------------------------------------------------------------
if (_focusedElement == null || FocusedElementIsBehindFullWindowMediaRoot())
{
if (!isReverse)
{
pNewTabStop = GetFirstFocusableElement(activeRoot, null);
}
else
{
pNewTabStop = GetLastFocusableElement(activeRoot, null);
}
didCycleFocusAtRootVisualScope = true;
}
else if (!isReverse)
{
pNewTabStop = GetNextTabStop();
// If we could not find a tab stop, see if we need to tab cycle.
if (pNewTabStop == null && (!_canTabOutOfPlugin || internalCycleWorkaround || queryOnly))
{
pNewTabStop = GetFirstFocusableElement(activeRoot, null);
didCycleFocusAtRootVisualScope = true;
}
}
else
{
pNewTabStop = GetPreviousTabStop();
// If we could not find a tab stop, see if we need to tab cycle.
if (pNewTabStop == null && (!_canTabOutOfPlugin || internalCycleWorkaround || queryOnly))
{
pNewTabStop = GetLastFocusableElement(activeRoot, null);
didCycleFocusAtRootVisualScope = true;
}
}
return new TabStopCandidateSearchResult(didCycleFocusAtRootVisualScope, pNewTabStop);
}
/// <summary>
/// Process TabStop to retrieve the next or previous tab stop element.
/// </summary>
/// <param name="isReverse">Is reverse direction?</param>
/// <param name="queryOnly">Query only.</param>
/// <returns>Next or previous tab stop element or null.</returns>
private DependencyObject? ProcessTabStopInternal(bool isReverse, bool queryOnly)
{
DependencyObject? ppNewTabStopElement = null;
bool isTabStopOverridden = false;
bool didCycleFocusAtRootVisualScope = false;
DependencyObject? pNewTabStop = null;
DependencyObject? pDefaultCandidateTabStop = null;
DependencyObject? pNewTabStopFromCallback = null;
// Get the default tab stoppable element.
var result = GetTabStopCandidateElement(isReverse, queryOnly);
didCycleFocusAtRootVisualScope = result.DidCycleFocusAtRootVisualScope;
pDefaultCandidateTabStop = result.Candidate;
// Ask UIElement for a new tab stop suggestion (this is to solve appbar focus issues)
var processResult = (_focusedElement as UIElement)?.ProcessTabStop(
_focusedElement,
pDefaultCandidateTabStop,
!!isReverse,
didCycleFocusAtRootVisualScope);
pNewTabStopFromCallback = processResult?.NewTabStop;
isTabStopOverridden = processResult?.IsOverriden ?? false;
if (isTabStopOverridden)
{
pNewTabStop = pNewTabStopFromCallback;
}
// If no suggestions from framework apply the regular logic
if (!isTabStopOverridden && pNewTabStop == null && pDefaultCandidateTabStop != null)
{
pNewTabStop = pDefaultCandidateTabStop;
}
if (pNewTabStop != null)
{
ppNewTabStopElement = pNewTabStop;
pNewTabStop = null;
}
return ppNewTabStopElement;
}
/// <summary>
/// Processes the TabStop navigation.
/// </summary>
/// <param name="isReverseDirection">Is shift pressed?</param>
/// <returns>Value indicating whether the request was handled.</returns>
internal bool ProcessTabStop(bool isReverseDirection)
{
var bHandled = false;
DependencyObject? spNewTabStop;
// Get the new tab stoppable element.
bool queryOnly = false;
spNewTabStop = ProcessTabStopInternal(isReverseDirection, queryOnly);
var navigationDirection = (isReverseDirection == true) ?
FocusNavigationDirection.Previous : FocusNavigationDirection.Next;
if (spNewTabStop != null)
{
// Set the focus to the new TabStop control
var result = SetFocusedElement(new FocusMovement(spNewTabStop, navigationDirection, FocusState.Keyboard));
bHandled = result.WasMoved;
}
else
{
Guid correlationId = Guid.NewGuid();
bool handled = false;
FocusObserver.DepartFocus(navigationDirection, correlationId, ref handled);
}
return bHandled;
}
/// <summary>
/// Returns the first focusable uielement from the root.
/// </summary>
/// <returns>First focusable element.</returns>
/// <remarks>
/// Special handling for popup, otherwise uses other method to do the work.
/// </remarks>
internal UIElement? GetFirstFocusableElement()
{
DependencyObject? pFirstFocus = null;
UIElement? pFirstFocusElement = null;
if (_contentRoot.VisualTree != null)
{
// First give focus to the topmost light-dismiss-enabled popup or a Flyout if any is open.
var pPopupRoot = _contentRoot.VisualTree.PopupRoot;
if (pPopupRoot != null)
{
Popup? pTopmostLightDismissPopup = pPopupRoot.GetTopmostPopup(PopupRoot.PopupFilter.LightDismissOrFlyout);
if (pTopmostLightDismissPopup != null)
{
pFirstFocusElement = pTopmostLightDismissPopup as UIElement;
}
}
if (pFirstFocusElement == null)
{
pFirstFocus = GetFirstFocusableElementFromRoot(false /* bReverse */);
if (pFirstFocus != null)
{
if (pFirstFocus is UIElement pFirstFocusAsUIE)
{
pFirstFocusElement = pFirstFocusAsUIE;
}
else
{
// When the first focusable element is not a Control, look for an
// appropriate reference to return to the caller who wants a Control.
// Example: Hyperlink -. Text control hosting the hyperlink
pFirstFocusElement = GetParentElement(pFirstFocus);
}
}
}
}
return pFirstFocusElement;
}
/// <summary>
/// Returns the next focusable element if it is available.
/// </summary>
/// <returns>Focusable element or null.</returns>
/// <remarks>
/// Includes special handling for Hyperlink.
/// </remarks>
private UIElement? GetNextFocusableElement()
{
DependencyObject? pNextFocus = GetNextTabStop();
UIElement? pNextFocusElement = null;
if (pNextFocus != null)
{
if (pNextFocus is UIElement uiElement)
{
pNextFocusElement = uiElement;
}
else
{
// When the first focusable element is not a Control, look for an
// appropriate reference to return to the caller who wants a Control.
// Example: Hyperlink -. Text control hosting the hyperlink
pNextFocusElement = GetParentElement(pNextFocus);
}
}
return pNextFocusElement;
}
/// <summary>
/// Returns the next TabStop control if it is available. Otherwise, return null.
/// </summary>
/// <param name="pCurrentTabStop">Current tab stop.</param>
/// <param name="bIgnoreCurrentTabStopScope">Should the current tab scope be ignored?</param>
/// <returns>Next tab stop or null.</returns>
/// <remarks>
/// Gets next tab stop, includes the full logic with special case handling
/// Calls internal version of the method which contains further logic
/// </remarks>
internal DependencyObject? GetNextTabStop(DependencyObject? pCurrentTabStop = null, bool bIgnoreCurrentTabStopScope = false)
{
DependencyObject? pNewTabStop = null;
DependencyObject? pFocused = pCurrentTabStop ?? _focusedElement;
DependencyObject? pCurrentCompare = null;
DependencyObject? pNewTabStopFromCallback = null;
if (pFocused == null || _contentRoot.VisualTree == null)
{
return null; // No next tab stop
}
// Assign the compare(TabIndex value) control with the focused control
pCurrentCompare = pFocused;
// #0. Ask UIElement for the next tab stop suggestion.
// For example, LightDismiss enabled Popup will process GetNextTabStop callbacks.
pNewTabStopFromCallback = (pFocused as UIElement)?.GetNextTabStopOverride();
pNewTabStop = pNewTabStopFromCallback;
// #1. Search TabStop from the children
if (pNewTabStop == null &&
!bIgnoreCurrentTabStopScope &&
(IsVisible(pFocused) && (CanHaveChildren(pFocused) || CanHaveFocusableChildren(pFocused))))
{
pNewTabStop = GetFirstFocusableElement(pFocused, pNewTabStop);
}
// #2. Search TabStop from the sibling of parent
if (pNewTabStop == null)
{
bool bCurrentPassed = false;
var pCurrent = pFocused;
var pParent = GetFocusParent(pFocused);
bool parentIsRootVisual = pParent == _contentRoot.VisualTree.RootVisual;
while (pParent != null && !parentIsRootVisual && pNewTabStop == null)
{
if (IsValidTabStopSearchCandidate(pCurrent) && GetTabNavigation(pCurrent) == KeyboardNavigationMode.Cycle)
{
if (pCurrent == GetParentElement(pFocused))
{
// The focus will be cycled under the focusable children if the current focused
// control is the cycle navigation mode
pNewTabStop = GetFirstFocusableElement(pCurrent!, null);
}
else
{
// The current can be focusable
pNewTabStop = GetFirstFocusableElement(pCurrent!, pCurrent);
}
break;
}
if (IsValidTabStopSearchCandidate(pParent) && GetTabNavigation(pParent) == KeyboardNavigationMode.Once)
{
pCurrent = pParent;
pParent = GetFocusParent(pParent);
if (pParent == null)
{
break;
}
}
else if (!IsValidTabStopSearchCandidate(pParent))
{
// Get the parent control whether it is a focusable or not
var pParentElement = GetParentElement(pParent);
if (pParentElement == null)
{
// if the focused element is under a popup and there is no control in its ancestry up until
// the popup, then consider tabnavigation as cycle within the popup subtree.
pParent = GetRootOfPopupSubTree(pCurrent);
if (pParent != null)
{
// try to find the next tabstop.
pNewTabStop = GetNextTabStopInternal(pParent, pCurrent, pNewTabStop, ref bCurrentPassed, ref pCurrentCompare);
// Retrieve the first tab stop from the current tab stop when the current tab stop is not focusable.
if (pNewTabStop != null && !IsFocusable(pNewTabStop))
{
pNewTabStop = GetFirstFocusableElement(pNewTabStop, null);
}
if (pNewTabStop == null)
{
// the focused element is the last tabstop. move the focus to the first
// focusable element within the popup.
pNewTabStop = GetFirstFocusableElement(pParent, null);
}
break;
}
pParent = _contentRoot.VisualTree.ActiveRootVisual;
}
else if (pParentElement != null && GetTabNavigation(pParentElement) == KeyboardNavigationMode.Once)
{
// We need to get out of the current scope in case of Once navigation mode, so
// reset the current and parent to search the next available focus control
pCurrent = pParentElement;
pParent = GetFocusParent(pParentElement);
if (pParent == null)
{
break;
}
}
else
{
// Assign the parent that can have a focusable children.
// If there is no parent that can be a TapStop, assign the root
// to figure out the next focusable element from the root
if (pParentElement != null)
{
pParent = pParentElement;
}
else
{
pParent = _contentRoot.VisualTree.ActiveRootVisual;
}
}
}
pNewTabStop = GetNextTabStopInternal(
pParent,
pCurrent,
pNewTabStop,
ref bCurrentPassed,
ref pCurrentCompare);
// GetNextTabStoopInternal can return the not focusable element which has a focusable child
if (pNewTabStop != null && !IsFocusable(pNewTabStop) && CanHaveFocusableChildren(pNewTabStop))
{
pNewTabStop = GetFirstFocusableElement(pNewTabStop, null);
}
if (pNewTabStop != null)
{
break;
}
// Only assign the current when the parent is a element that can TabStop
if (IsValidTabStopSearchCandidate(pParent))
{
pCurrent = pParent;
}
pParent = GetFocusParent(pParent);
bCurrentPassed = false;
parentIsRootVisual = pParent == _contentRoot.VisualTree.RootVisual;
}
}
return pNewTabStop;
}
/// <summary>
/// Return the next TabStop control if it is available.
/// Otherwise, return null.
/// </summary>
/// <param name="pParent">Parent element.</param>
/// <param name="pCurrent">Current element.</param>
/// <param name="pCandidate">Candidate.</param>
/// <param name="bCurrentPassed">Was current passed?</param>
/// <returns>Next tab stop.</returns>
private DependencyObject? GetNextTabStopInternal(
DependencyObject? pParent,
DependencyObject? pCurrent,
DependencyObject? pCandidate,
ref bool bCurrentPassed,
ref DependencyObject? pCurrentCompare)
{
DependencyObject? pNewTabStop = pCandidate;
DependencyObject? pChildStop = null;
// Update the compare(TabIndex value) control by searching the siblings of ancestor
if (IsValidTabStopSearchCandidate(pCurrent))
{
pCurrentCompare = pCurrent;
}
if (pParent != null)
{
int compareIndexResult;
bool bFoundCurrent = false;
// Find next TabStop from the children
var children = FocusProperties.GetFocusChildrenInTabOrder(pParent);
foreach (var childNoRef in children)
{
pChildStop = null;
if (childNoRef != null && childNoRef == pCurrent)
{
bFoundCurrent = true;
bCurrentPassed = true;
continue;
}
if (childNoRef != null && IsVisible(childNoRef))
{
// This will only hit in Pre-RS5 scenarios
if (childNoRef == pCurrent)
{
bFoundCurrent = true;
bCurrentPassed = true;
continue;
}
if (IsValidTabStopSearchCandidate(childNoRef))
{
// If we have a UIElement, such as a StackPanel, we want to check it's children for the next tab stop
if (!IsPotentialTabStop(childNoRef))
{
pChildStop = GetNextTabStopInternal(childNoRef, pCurrent, pNewTabStop, ref bCurrentPassed, ref pCurrentCompare);
}
else
{
pChildStop = childNoRef;
}
}
else if (CanHaveFocusableChildren(childNoRef))
{
pChildStop = GetNextTabStopInternal(childNoRef, pCurrent, pNewTabStop, ref bCurrentPassed, ref pCurrentCompare);
}
}
if (pChildStop != null && (IsFocusable(pChildStop) || CanHaveFocusableChildren(pChildStop)))
{
compareIndexResult = CompareTabIndex(pChildStop, pCurrentCompare);
if (compareIndexResult > 0 || ((bFoundCurrent || bCurrentPassed) && compareIndexResult == 0))
{
if (pNewTabStop != null)
{
if (CompareTabIndex(pChildStop, pNewTabStop) < 0)
{
pNewTabStop = pChildStop;
}
}
else
{
pNewTabStop = pChildStop;
}
}
}
}
}
return pNewTabStop;
}
/// <summary>
/// Return the previous TabStop control if it is available. Otherwise, return null.
/// </summary>
/// <param name="pCurrentTabStop">Current tab stop</param>
/// <returns>Previous tab stop.</returns>
internal DependencyObject? GetPreviousTabStop(DependencyObject? pCurrentTabStop = null)
{
DependencyObject? pFocused = pCurrentTabStop ?? _focusedElement;
DependencyObject? pNewTabStop = null;
DependencyObject? pCurrentCompare = null;
if (pFocused == null && _contentRoot.VisualTree == null)
{
return null; // No previous tab stop
}
// Assign the compare(TabIndex value) control with the focused control
pCurrentCompare = pFocused;
// #0. Ask UIElement for the previous tab stop suggestion.
// For example, LightDismiss enabled Popup will process GetPreviousTabStop callbacks.
var newTabStopFromCallback = (pFocused as UIElement)?.GetPreviousTabStopOverride();
pNewTabStop = newTabStopFromCallback;
// Search the previous TabStop from the sibling of parent
if (pNewTabStop == null)
{
bool bCurrentPassed = false;
var pCurrent = pFocused;
var parent = GetFocusParent(pFocused);
while (parent != null && !(parent is RootVisual) && pNewTabStop == null)
{
if (IsValidTabStopSearchCandidate(pCurrent) && GetTabNavigation(pCurrent) == KeyboardNavigationMode.Cycle)
{
pNewTabStop = GetLastFocusableElement(pCurrent!, pCurrent);
break;
}
if (IsValidTabStopSearchCandidate(parent) && GetTabNavigation(parent) == KeyboardNavigationMode.Once)
{
// Set focus on the parent if it is a focusable control. Otherwise, keep search it up.
if (IsFocusable(parent))
{
pNewTabStop = parent;
break;
}
else
{
pCurrent = parent;
parent = GetFocusParent(parent);
if (parent == null)
{
break;
}
}
}
else if (!IsValidTabStopSearchCandidate(parent))
{
// Get the parent control whether it is a focusable or not
var parentElement = GetParentElement(parent);
if (parentElement == null)
{
// if the focused element is under a popup and there is no control in its ancestry up until
// the popup, then consider tabnavigation as cycle within the popup subtree.
parent = GetRootOfPopupSubTree(pCurrent);
if (parent != null)
{
// find the previous tabstop
pNewTabStop = GetPreviousTabStopInternal(parent, pCurrent, pNewTabStop, ref bCurrentPassed, ref pCurrentCompare);
// Retrieve the last tab stop from the current tab stop when the current tab stop is not focusable.
if (pNewTabStop != null && !IsFocusable(pNewTabStop))
{
pNewTabStop = GetLastFocusableElement(pNewTabStop, null);
}
if (pNewTabStop == null)
{
// focused element is the first tabstop within the popup. move focus
// to the last tabstop within the popup
pNewTabStop = GetLastFocusableElement(parent, null);
}
break;
}
parent = _contentRoot.VisualTree.ActiveRootVisual;
}
else if (parentElement != null && GetTabNavigation(parentElement) == KeyboardNavigationMode.Once)
{
// Set focus on the parent control if it is a focusable control. Otherwise, keep search it up.
if (IsFocusable(parentElement))
{
pNewTabStop = parentElement;
break;
}
else
{
pCurrent = parent;
parent = parentElement;
}
}
else
{
// Assign the parent that can have a focusable children.
// If there is no parent that can be a TapStop, assign the root
// to figure out the next focusable element from the root
if (parentElement != null)
{
parent = parentElement;
}
else
{
parent = _contentRoot.VisualTree.ActiveRootVisual;
}
}
}
pNewTabStop = GetPreviousTabStopInternal(
parent,
pCurrent,
pNewTabStop,
ref bCurrentPassed,
ref pCurrentCompare);
if (pNewTabStop == null && IsPotentialTabStop(parent) && IsFocusable(parent))
{
if (parent != null && IsPotentialTabStop(parent) && GetTabNavigation(parent) == KeyboardNavigationMode.Cycle)
{
pNewTabStop = GetLastFocusableElement(parent, null /*LastFocusable*/);
}
else
{
pNewTabStop = parent;
}
}
else
{
// Find the last focusable element from the current focusable container
if (pNewTabStop != null && CanHaveFocusableChildren(pNewTabStop))
{
pNewTabStop = GetLastFocusableElement(pNewTabStop, null);
}
}
if (pNewTabStop != null)
{
break;
}
// Only assign the current when the parent is a element that can TapStop
if (IsValidTabStopSearchCandidate(parent))
{
pCurrent = parent;
}
parent = GetFocusParent(parent);
bCurrentPassed = false;
}
}
return pNewTabStop;
}
/// <summary>
/// Return the previous tab stop control if it is available.
/// Otherwise, return null.
/// </summary>
private DependencyObject? GetPreviousTabStopInternal(
DependencyObject? parent,
DependencyObject? pCurrent,
DependencyObject? pCandidate,
ref bool bCurrentPassed,
ref DependencyObject? pCurrentCompare)
{
DependencyObject? pNewTabStop = pCandidate;
DependencyObject? pChildStop = null;
// Update the compare(TabIndex value) control by searching the siblings of ancestor
if (IsValidTabStopSearchCandidate(pCurrent))
{
pCurrentCompare = pCurrent;
}
if (parent != null)
{
int compareIndexResult;
bool bFoundCurrent = false;
bool bCurrentCompare;
// Find previous TabStop from the children
var children = FocusProperties.GetFocusChildrenInTabOrder(parent);
foreach (var child in children)
{
bCurrentCompare = false;
pChildStop = null;
if (child != null && child == pCurrent)
{
bFoundCurrent = true;
bCurrentPassed = true;
continue;
}
if (child != null && IsVisible(child))
{
// This will only hit in Pre-RS5 scenarios
if (child == pCurrent)
{
bFoundCurrent = true;
bCurrentPassed = true;
continue;
}
if (IsValidTabStopSearchCandidate(child))
{
// If we have a UIElement, such as a StackPanel, we want to check it's children for the next tab stop
if (!IsPotentialTabStop(child))
{
pChildStop = GetPreviousTabStopInternal(
child,
pCurrent,
pNewTabStop,
ref bCurrentPassed,
ref pCurrentCompare);
bCurrentCompare = true;
}
else
{
pChildStop = child;
}
}
else if (CanHaveFocusableChildren(child))
{
pChildStop = GetPreviousTabStopInternal(
child,
pCurrent,
pNewTabStop,
ref bCurrentPassed,
ref pCurrentCompare);
bCurrentCompare = true;
}
}
if (pChildStop != null && (IsFocusable(pChildStop) || CanHaveFocusableChildren(pChildStop)))
{
compareIndexResult = CompareTabIndex(pChildStop, pCurrentCompare);
if (compareIndexResult < 0 ||
(((!bFoundCurrent && !bCurrentPassed) || bCurrentCompare) && compareIndexResult == 0))
{
if (pNewTabStop != null)
{
if (CompareTabIndex(pChildStop, pNewTabStop) >= 0)
{
pNewTabStop = pChildStop;
}
}
else
{
pNewTabStop = pChildStop;
}
}
}
}
}
return pNewTabStop;
}
/// <summary>
/// Compare TabIndex value between focusable(TabStop) controls.
/// </summary>
/// <param name="firstObject"></param>
/// <param name="secondObject"></param>
/// <returns></returns>
/// <remarks>
/// Return +1 if control1 > control2
/// Return = if control1 = control2
/// Return -1 if control1 < control2
/// </remarks>
private int CompareTabIndex(DependencyObject? firstObject, DependencyObject? secondObject)
{
if (GetTabIndex(firstObject) > GetTabIndex(secondObject))
{
return 1;
}
else if (GetTabIndex(firstObject) < GetTabIndex(secondObject))
{
return -1;
}
return 0;
}
/// <summary>
/// Checks whether focus is currently on the first tab stop.
/// </summary>
/// <returns>True if focus is in the first tab stop.</returns>
private bool IsFocusOnFirstTabStop()
{
DependencyObject? pFocused = _focusedElement;
DependencyObject? activeRoot = null;
DependencyObject? pFirstFocus = null;
if (pFocused == null || _contentRoot.VisualTree == null)
{
return false;
}
activeRoot = _contentRoot.VisualTree.ActiveRootVisual;
MUX_ASSERT(activeRoot != null);
pFirstFocus = GetFirstFocusableElement(activeRoot!, null);
if (pFocused == pFirstFocus)
{
return true;
}
return false;
}
/// <summary>
/// Checks whether focus is currently on the first tab stop.
/// </summary>
/// <returns>True if focus is in the first tab stop.</returns>
private bool IsFocusOnLastTabStop()
{
DependencyObject? pFocused = _focusedElement;
DependencyObject? activeRoot = null;
DependencyObject? pLastFocus = null;
if (pFocused == null || _contentRoot.VisualTree == null)
{
return false;
}
activeRoot = _contentRoot.VisualTree.ActiveRootVisual;
MUX_ASSERT(activeRoot != null);
pLastFocus = GetLastFocusableElement(activeRoot!, null);
if (pFocused == pLastFocus)
{
return true;
}
return false;
}
/// <summary>
/// Checks if there is a focusable child.
/// </summary>
/// <param name="pParent">Parent.</param>
/// <returns>True if a focusable child exists.</returns>
private bool CanHaveFocusableChildren(DependencyObject? pParent) =>
FocusProperties.CanHaveFocusableChildren(pParent);
/// <summary>
/// Returns the control of parent (ancestor) from the current control
/// </summary>
/// <param name="pCurrent">Current control.</param>
/// <returns>Parent UIElement or null.</returns>
private UIElement? GetParentElement(DependencyObject? pCurrent)
{
DependencyObject? pParent = null;
if (pCurrent != null)
{
pParent = GetFocusParent(pCurrent);
while (pParent != null)
{
if (IsValidTabStopSearchCandidate(pParent) && pParent is UIElement parentUiElement)
{
return parentUiElement;
}
pParent = GetFocusParent(pParent);
}
}
return null;
}
/// <summary>
/// Notify the focus changing that ensure the focused element visible with input host manager.
/// </summary>
/// <param name="bringIntoView">Bring into view?</param>
/// <param name="animateIfBringIntoView">Animate?</param>
private void NotifyFocusChanged(bool bringIntoView, bool animateIfBringIntoView)
{
if (_focusedElement != null) //&& static_cast<DependencyObject>(_focusedElement).GetContext())
{
_contentRoot.InputManager.NotifyFocusChanged(_focusedElement, bringIntoView, animateIfBringIntoView);
}
}
/// <summary>
/// Determine if a particular DependencyObject cares to take focus.
/// </summary>
/// <param name="dependencyObject">Dependency object.</param>
/// <returns>True if focusable.</returns>
private bool IsFocusable(DependencyObject? dependencyObject) => FocusProperties.IsFocusable(dependencyObject);
/// <summary>
/// Return the object that should be considered the parent for the purposes
/// of tab focus. This is not necessarily the same as the standard
/// DependencyObject.GetParent() object.
/// </summary>
/// <param name="dependencyObject">Dependency object.</param>
/// <returns>Parent or null.</returns>
private DependencyObject? GetFocusParent(DependencyObject? dependencyObject)
{
if (dependencyObject != null)
{
if (FocusableHelper.IsFocusableDO(dependencyObject))
{
return FocusableHelper.GetContainingFrameworkElementIfFocusable(dependencyObject);
}
else
{
var activeRoot = _contentRoot.VisualTree.ActiveRootVisual;
MUX_ASSERT(activeRoot != null);
// Root SV is located between the visual root and hidden root.
// GetFocusParent shouldn't return the ancestor of the visual root.
if (dependencyObject != activeRoot)
{
return dependencyObject.GetParent() as DependencyObject;
}
}
}
// null input -. null output
return null;
}
/// <summary>
/// Determines if the object is visible.
/// </summary>
/// <param name="pObject"></param>
/// <returns>True if visible.</returns>
private bool IsVisible(DependencyObject? pObject) => FocusProperties.IsVisible(pObject);
/// <summary>
/// Gets the value set by application developer to determine the tab
/// order. Default value is int.MaxValue which means to evaluate them in
/// their ordering of the focus children collection.
/// </summary>
/// <param name="dependencyObject">Dependency object.</param>
/// <returns>Tab index or int max value.</returns>
private int GetTabIndex(DependencyObject? dependencyObject)
{
if (dependencyObject != null)
{
if (dependencyObject is UIElement uiElement)
{
return uiElement.TabIndex;
}
else if (FocusableHelper.GetIFocusableForDO(dependencyObject) is IFocusable focusable)
{
return focusable.GetTabIndex();
}
}
return int.MaxValue;
}
/// <summary>
/// Determines if this object type can have children that should be considered
/// for tab ordering. Note that this doesn't necessarily mean if the object
/// instance has focusable children right now. CanHaveChildren() may be true
/// even though the focus children collection is empty.
/// </summary>
/// <param name="pObject"></param>
/// <returns></returns>
private bool CanHaveChildren(DependencyObject? pObject)
{
if (pObject is UIElement pUIElement) // Really INDEX_VISUAL but Visual is not in the publicly exposed hierarchy.
{
return pUIElement.CanHaveChildren();
}
return false;
}
/// <summary>
/// Returns non-null if the given object is within a popup.
/// </summary>
/// <param name="dependencyObject">Dependency object.</param>
/// <returns>Root of popup tree or null.</returns>
private DependencyObject? GetRootOfPopupSubTree(DependencyObject? dependencyObject)
{
DependencyObject? root = null;
if (dependencyObject != null)
{
if (dependencyObject is UIElement pUIElement)
{
root = pUIElement.GetRootOfPopupSubTree();
}
else
{
var parentElement = GetParentElement(dependencyObject);
if (parentElement != null)
{
root = parentElement.GetRootOfPopupSubTree();
}
}
}
return root;
}
/// <summary>
/// Returns the value of the TabNavigation property.
/// </summary>
/// <param name="pObject">Dependency object.</param>
/// <returns>Keyboard navigation mode.</returns>
private KeyboardNavigationMode GetTabNavigation(DependencyObject? pObject)
{
if (!(pObject is UIElement element))
{
return KeyboardNavigationMode.Local;
}
return element.GetTabNavigation();
}
/// <summary>
/// Tests to see if the parameter object's type supports being a tab stop.
/// Though the specific instance might not be a valid tab stop at the moment.
/// (Example: Disabled state)
/// </summary>
/// <param name="dependencyObject">Dependency object.</param>
/// <returns>True if input object is potential tab stop.</returns>
private bool IsPotentialTabStop(DependencyObject? dependencyObject) => FocusProperties.IsPotentialTabStop(dependencyObject);
/// <summary>
/// Allow the focus change event with the below condition
/// 1. Plugin has a focus
/// 2. FullScreen window mode
/// </summary>
/// <returns></returns>
private bool CanRaiseFocusEventChange()
{
bool bCanRaiseFocusEvent = false;
//if (_coreService != null)
{
if (IsPluginFocused())
{
bCanRaiseFocusEvent = true;
}
}
return bCanRaiseFocusEvent;
}
private bool ShouldUpdateFocus(DependencyObject? newFocus, FocusState focusState)
{
bool shouldUpdateFocus = true;
//TFS 5777889. There are some scenarios (mainly with SIP), where we want to interact with another element, but
//have the focus stay with the currently focused element
if (newFocus != null)
{
if (newFocus is FrameworkElement newFocusFrameworkElement)
{
shouldUpdateFocus = FocusSelection.ShouldUpdateFocus(
newFocusFrameworkElement,
focusState);
}
else if (newFocus is FlyoutBase newFocusFlyoutBase)
{
shouldUpdateFocus = FocusSelection.ShouldUpdateFocus(
newFocusFlyoutBase,
focusState);
}
else if (newFocus is TextElement newFocusTextElement)
{
shouldUpdateFocus = FocusSelection.ShouldUpdateFocus(
newFocusTextElement,
focusState);
}
}
return shouldUpdateFocus;
}
/// <summary>
/// Changes our currently focused element. FocusMovementResult.WasMoved indicates
/// whether the update is successful. We will also be responsible for raising focus related
/// events (GettingFocus/LosingFocus and GotFocus/LostFocus).
///
/// FocusMovementResult.WasMoved indicates that the process has executed successfully.
/// </summary>
/// <param name="movement"></param>
/// <returns></returns>
/// <remarks>
/// We have two ways (FocusMovementResult.GetHResult() and FocusMovementResult.WasMoved) to report success and failure.
/// This is because it is possible that the given pNewFocus could not actually take focus for
/// innocent reasons. (Currently in disabled state, etc.) This is not an important failure and GetHResult()
/// return S_OK even though WasMoved() is false.
///
/// A failing HRESULT is reserved for important failures like OOM conditions or
/// reentrancy prevention. This distinction is made in the interest of reducing noise
/// in tools like XcpMon.
///
/// Boundary cases:
/// - If pNewFocus is the object that already has current focus,
/// it is counted as success even though nothing was technically "updated".
///
/// - If a focus change is cancelled in a Getting/Losing Focus handler, it
/// is counted as success even though focus was technically not "updated".
/// </remarks>
private FocusMovementResult UpdateFocus(FocusMovement movement)
{
if (movement is null)
{
throw new ArgumentNullException(nameof(movement));
}
var newFocusTarget = movement.Target;
FocusNavigationDirection focusNavigationDirection = movement.Direction;
bool forceBringIntoView = movement.ForceBringIntoView;
bool animateIfBringIntoView = movement.AnimateIfBringIntoView;
FocusState nonCoercedFocusState = movement.FocusState;
FocusState coercedFocusState = CoerceFocusState(nonCoercedFocusState);
bool success = false;
bool focusCancelled = false;
bool shouldCompleteAsyncOperation = movement.ShouldCompleteAsyncOperation;
DependencyObject? oldFocusedElement = null;
bool shouldBringIntoView = false;
Guid correlationId = _asyncOperation != null ? _asyncOperation.CorrelationId : movement.CorrelationId;
LogTraceTraceUpdateFocusBegin();
InputDeviceType lastInputDeviceType = InputDeviceType.None;
//TODO:MZ:Exceptions can break focus forever
if (_asyncOperation != null && shouldCompleteAsyncOperation == false)
{
//throw new InvalidOperationException("An asynchronous operation is in progress.");
//return Cleanup();
}
if (_focusLocked && _ignoreFocusLock == false)
{
throw new InvalidOperationException("Focus change not allowed during focus changing.");
}
if (!ShouldUpdateFocus(newFocusTarget, nonCoercedFocusState))
{
return Cleanup();
}
if (_contentRoot.IsShuttingDown())
{
// Don't change focus setting in case of the processing of ResetVisualTree
return Cleanup();
}
// When navigating between pages, we need to clear the (prior focus) state on XYFocus
if (newFocusTarget == null
&& coercedFocusState == FocusState.Unfocused)
{
_xyFocus.ResetManifolds();
}
lastInputDeviceType = _contentRoot.InputManager.LastInputDeviceType;
if (lastInputDeviceType == InputDeviceType.GamepadOrRemote && __LinkerHints.Is_Microsoft_UI_Xaml_Controls_TextBox_Available)
{
var pElementAsTextBox = newFocusTarget as TextBox;
if (pElementAsTextBox != null)
{
//TODO Uno: We don't have special handling for Gamepad input.
//pElementAsTextBox.IncomingFocusFromGamepad();
}
}
if (newFocusTarget == _focusedElement)
{
UIElement? newFocusAsElement = newFocusTarget as UIElement;
if (newFocusAsElement != null && newFocusAsElement.FocusState != coercedFocusState)
{
// We do not raise GettingFocus here since the OldFocusedElement and NewFocusedElement
// would be the same element.
RaiseGotFocusEvent(_focusedElement!, correlationId);
// Make sure the FocusState is up-to-date.
newFocusAsElement.UpdateFocusState(coercedFocusState);
_realFocusStateForFocusedElement = nonCoercedFocusState;
}
else if (FocusableHelper.GetIFocusableForDO(newFocusTarget) is IFocusable newFocusAsIFocusable)
{
var value = (FocusState)newFocusTarget!.GetValue(newFocusAsIFocusable.GetFocusStatePropertyIndex());
if (coercedFocusState != value)
{
RaiseGotFocusEvent(_focusedElement!, correlationId);
value = coercedFocusState;
newFocusTarget.SetValue(newFocusAsIFocusable.GetFocusStatePropertyIndex(), value);
}
_realFocusStateForFocusedElement = nonCoercedFocusState;
}
success = true;
// No change in focus element - can skip the rest of this method.
return Cleanup();
}
if (movement.RaiseGettingLosingEvents)
{
if (CanRaiseFocusEventChange() &&
RaiseAndProcessGettingAndLosingFocusEvents(
_focusedElement,
newFocusTarget,
nonCoercedFocusState,
focusNavigationDirection,
movement.CanCancel,
correlationId).Canceled)
{
success = true;
focusCancelled = true;
return Cleanup();
}
}
MUX_ASSERT((newFocusTarget == null) || IsFocusable(newFocusTarget));
// Update the previous focused control
oldFocusedElement = _focusedElement; // Still has reference that will be freed in Cleanup.
_focusingElement = newFocusTarget;
if (oldFocusedElement != null && FocusableHelper.GetIFocusableForDO(oldFocusedElement) is IFocusable oldFocusFocusable)
{
oldFocusedElement.SetValue(
oldFocusFocusable.GetFocusStatePropertyIndex(),
FocusState.Unfocused);
}
else if (oldFocusedElement != null && oldFocusedElement is UIElement oldFocusedUIElement)
{
oldFocusedUIElement.UpdateFocusState(FocusState.Unfocused);
}
// Update the focused control
if (this.Log().IsEnabled(LogLevel.Debug))
{
_log.Value.LogDebug($"{nameof(UpdateFocus)}() - oldFocus={_focusedElement} ({_realFocusStateForFocusedElement}), newFocus={newFocusTarget} ({nonCoercedFocusState})");
}
_focusedElement = newFocusTarget;
_realFocusStateForFocusedElement = nonCoercedFocusState;
//
// NOTE:
//
// The calls to SetFocus will synchronously call into SetWindowFocus
// We have to be extra careful that _focusedElement is already set to avoid
// a reentrancy call to UpdateFocus
//
_contentRoot.FocusAdapter.SetFocus();
// Bring element into view when it is focused using the keyboard, so user
// can see the element that was tabbed to
if (_focusedElement != null
&& (nonCoercedFocusState == FocusState.Keyboard || forceBringIntoView))
{
var pFocusedElement = _focusedElement as UIElement;
if (pFocusedElement != null)
{
// Note that this is done before calling UpdateFocusState, so the
// control can use the state before it gains focus to decide whether it should
// be brought into view when focus is gained.
shouldBringIntoView = true;
}
else
{
// Other TabStop elements should be brought into view.
shouldBringIntoView = IsPotentialTabStop(_focusedElement);
}
}
// UpdateFocusState.
// Use pNewFocus for UpdateFocusState instead of _focusedElement because the .SetFocus call above can cause
// reentrancy and change _focusedElement.
if (newFocusTarget != null && FocusableHelper.GetIFocusableForDO(newFocusTarget) is IFocusable newFocusFocusable)
{
newFocusTarget.SetValue(newFocusFocusable.GetFocusStatePropertyIndex(), coercedFocusState);
}
else if (newFocusTarget is UIElement newFocusTargetUIElement)
{
// Some controls query this flag immediately - setting in OnGotFocus is too late.
newFocusTargetUIElement.UpdateFocusState(coercedFocusState);
}
// We don't need to do a complete UpdateFocusRect now (redrawing the rect), as NWDrawTree will call UpdateFocusRect
// when it needs it. But we do want to see if we can clean up FocusRectManager's secret children, particularly in
// the case when the previously focused item has been removed from the tree
//UpdateFocusRect(focusNavigationDirection, true /* cleanOnly */);
// TODO Uno specific: We need to do a full redraw, as render loop does not yet check for focus visuals rendering.
UpdateFocusRect(focusNavigationDirection, false);
FocusNative(_focusedElement as UIElement);
_contentRoot.InputManager.Pointers.NotifyFocusChanged(); // Note: This sounds like a duplicate of the NotifyFocusChanged done a few lines below (1944). We need to evaluate if this is still relevant or if we can just remove that uno-specific call.
// At this point the focused pointer has been switched. So success is true
// even in the case we run into trouble raising the event(s) to notify as such.
success = true;
// If the new focused element is not a Text Control then we need to
// call ClearLastSelectedTextElement since we are sure that
// there will be no selection rect drawn on the screen.
// This is to achieve the light text selection dismiss model.
if (_focusedElement == null || !TextCore.IsTextControl(_focusedElement))
{
if (_isPrevFocusTextControl)
{
var textCore = TextCore.Instance;
textCore.ClearLastSelectedTextElement();
_isPrevFocusTextControl = false;
}
}
else
{
_isPrevFocusTextControl = true;
}
// Fire focus changed event for UIAutomation
if (_focusedElement != null)
{
FireAutomationFocusChanged();
}
// Raise the focus Lost/GotFocus events
// Raise the focus event while plugin has a focus, on full screen mode or on windowless mode
if (CanRaiseFocusEventChange())
{
// Raise the LostFocus event to the old focused element
if (oldFocusedElement != null)
{
bool isNavigatedToByEngagingControl = newFocusTarget != null && NavigatedToByEngagingControl(newFocusTarget);
if (_engagedControl != null && !isNavigatedToByEngagingControl)
{
_engagedControl.RemoveFocusEngagement();
}
RaiseLostFocusEvent(oldFocusedElement, correlationId);
}
else
{
// Raise the FocusManagerLostFocus event asynchronously
// TODO Uno: We raise the events using dispatcher queue, which is a bit different from MUX
// which does everything via EventManager
_ = CoreDispatcher.Main.RunAsync(CoreDispatcherPriority.Normal, () =>
{
LostFocus?.Invoke(null, new FocusManagerLostFocusEventArgs(null, correlationId));
});
}
if (_focusedElement != null)
{
RaiseGotFocusEvent(_focusedElement, correlationId);
}
else
{
_ = CoreDispatcher.Main.RunAsync(CoreDispatcherPriority.Normal, () =>
{
GotFocus?.Invoke(null, new FocusManagerGotFocusEventArgs(_focusedElement, correlationId));
});
}
}
else if (oldFocusedElement != null && oldFocusedElement is Control control)
{
// Update the visual state of the old focused element even when IsPluginFocused() returns false so it no longer displays focus cues.
control.UpdateVisualState(true);
}
// Notify the focus changing on InputManager to ensure the focused element visible with
// Input Host Manager
NotifyFocusChanged(shouldBringIntoView, animateIfBringIntoView);
_contentRoot.AccessKeyExport.UpdateScope();
// Request the playing sound for changing focus with the keyboard, gamepad or remote input
if ((coercedFocusState == FocusState.Keyboard && _contentRoot.InputManager.ShouldRequestFocusSound()) &&
(lastInputDeviceType == InputDeviceType.Keyboard || lastInputDeviceType == InputDeviceType.GamepadOrRemote))
{
ElementSoundPlayerService.Instance.RequestInteractionSoundForElement(ElementSoundKind.Focus, newFocusTarget);
}
_focusingElement = null;
return Cleanup();
FocusMovementResult Cleanup()
{
TraceUpdateFocusEnd(newFocusTarget);
// Before RS2, UpdateFocus did not propagate errors. As a result, we want to limit the number of failure
// cases that callers should deal with to only those related to the new RS2 GettingFocus and LosingFocus events
FocusMovementResult result = new FocusMovementResult(success, focusCancelled);
if (_asyncOperation != null)
{
CancelCurrentAsyncOperation(result);
}
_currentFocusOperationCancellable = true;
return result;
}
}
private void FireAutomationFocusChanged()
{
AutomationPeer? pAP = null;
// TODO Uno: When automation is developed further, we want the second check to make sure not to create automation peers when not needed
if (_focusedElement != null) //&& S_OK == _pCoreService.UIAClientsAreListening(UIAXcp.AEAutomationFocusChanged))
{
pAP = (_focusedElement as UIElement)?.OnCreateAutomationPeerInternal();
// There's one specific circumstance that we want to handle: attempting to focus a ContentControl inside a popup.
// The ContentControl is able to be keyboard focused, but because ContentControlAutomationPeer doesn't exist,
// we won't raise any UIA focus changed event since we have no automation peer to raise it on.
// Since UIA clients like Narrator may be relying on this to transfer focus into an opened popup,
// we should raise the focus changed event on the popup containing the ContentControl,
// so that way we can ensure that UIA clients like Narrator have properly had focus trapped in the popup.
// TODO 10588657: Undo this change when we implement a ContentControlAutomationPeer.
if (pAP == null &&
_focusedElement is ContentControl contentControl)
{
var focusedElementAsUIE = _focusedElement as UIElement;
var popupToFocus = PopupRoot.GetOpenPopupForElement(focusedElementAsUIE!);
if (popupToFocus != null)
{
pAP = popupToFocus.OnCreateAutomationPeerInternal();
}
}
if (pAP != null)
{
_focusedAutomationPeer = pAP;
//TODO Uno: implement
//if (pAP.GetAPEventsSource())
//{
// pAP = pAP.GetAPEventsSource();
//}
//pAP.RaiseAutomationEvent(UIAXcp.AEAutomationFocusChanged);
}
}
if (pAP == null)
{
_focusedAutomationPeer = null;
}
}
/// <summary>
/// Raises the lost focus event asynchronously.
/// </summary>
/// <param name="pLostFocusElement">Element which lost focus.</param>
/// <param name="correlationId">Correlation ID.</param>
private void RaiseLostFocusEvent(
DependencyObject pLostFocusElement,
Guid correlationId)
{
if (pLostFocusElement is null)
{
throw new ArgumentNullException(nameof(pLostFocusElement));
}
// Create DO that represents the GotFocus event args
var spLostFocusEventArgs = new RoutedEventArgs();
var spFocusManagerLostFocusEventArgs = new FocusManagerLostFocusEventArgs(pLostFocusElement, correlationId);
// Set the GotFocus Source value on the routed event args
spLostFocusEventArgs.OriginalSource = pLostFocusElement;
// Raise the LostFocus event to the old focused element asynchronously
if (FocusableHelper.GetIFocusableForDO(pLostFocusElement) is IFocusable lostFocusElementFocusable)
{
// In the case of an IFocusable raise both <IFocusable>_LostFocus and UIElement_LostFocus.
// UIElement_LostFocus is used internally for to decide where focus rects should be rendered.
_ = CoreDispatcher.Main.RunAsync(CoreDispatcherPriority.Normal, () =>
{
lostFocusElementFocusable.OnLostFocus(spLostFocusEventArgs);
});
}
// Raise the LostFocus event to the new focused element asynchronously
_ = CoreDispatcher.Main.RunAsync(CoreDispatcherPriority.Normal, () =>
{
(pLostFocusElement as UIElement)?.RaiseEvent(UIElement.LostFocusEvent, spLostFocusEventArgs);
});
// Raise the FocusManagerLostFocus event to the focus manager asynchronously
_ = CoreDispatcher.Main.RunAsync(CoreDispatcherPriority.Normal, () =>
{
LostFocus?.Invoke(null, spFocusManagerLostFocusEventArgs);
});
}
/// <summary>
/// Returns true if pFocused was navigated to by engaging a control.
/// </summary>
/// <param name="pFocused">Focused element.</param>
/// <returns>True if focused was navigated to by engaging a control.</returns>
private bool NavigatedToByEngagingControl(DependencyObject focused)
{
DependencyObject? pFocused = focused;
bool isNavigatedTo = false;
if (_engagedControl != null)
{
bool isChild = false;
bool isElementChildOfPopupOpenedDuringEngagement = false;
bool isElementPopupOpenedDuringEngagement = false;
bool isSelf = _engagedControl == (pFocused as Control);
if (FocusableHelper.IsFocusableDO(pFocused))
{
pFocused = GetFocusParent(pFocused) as DependencyObject;
}
var pNewFocusedElement = pFocused as UIElement;
if (pNewFocusedElement != null)
{
isChild = _engagedControl.IsAncestorOf(pNewFocusedElement);
}
var pNewFocusedElementAsPopup = pFocused as Popup;
if (GetRootOfPopupSubTree(pNewFocusedElement) != null || pNewFocusedElementAsPopup != null)
{
var popupList = PopupRoot.GetPopupChildrenOpenedDuringEngagement(pFocused!);
foreach (var popup in popupList)
{
isElementPopupOpenedDuringEngagement = (popup == pNewFocusedElement);
if (isElementPopupOpenedDuringEngagement) { break; }
/*
In the case of a (Menu)Flyout, the new Focused Element could
be the actual popup, which is an ancestor of the (Menu)FlyoutPresenter
popup opened during engagement. This is a result of the fact that Flyouts (eg Button.Flyout)
are excluded from the Visual Tree.
In this situation, the new Focused element would be a Popup with no parent.
It's child would parent the 'popup' opened during engagement.
*/
bool isNewFocusedElementChildOfFlyoutOpenedDuringEngagement =
pNewFocusedElementAsPopup != null &&
(pNewFocusedElementAsPopup.Child != null) &&
(popup == pNewFocusedElementAsPopup.Child ||
pNewFocusedElementAsPopup.Child.IsAncestorOf(popup));
isElementChildOfPopupOpenedDuringEngagement =
isNewFocusedElementChildOfFlyoutOpenedDuringEngagement
|| popup.IsAncestorOf(pNewFocusedElement);
if (isElementChildOfPopupOpenedDuringEngagement)
{
break;
}
}
}
/*
The new focused element is navigated to during Engagement if:
1. It is the engaged control OR
2. It is a child of the engaged control OR
3. It is a popup opened during engagement OR
4. It is the descendant of a popup opened during engagement
*/
isNavigatedTo =
isChild ||
isSelf ||
isElementPopupOpenedDuringEngagement ||
isElementChildOfPopupOpenedDuringEngagement;
}
return isNavigatedTo;
}
/// <summary>
/// Raises the got focus event asynchronously.
/// </summary>
/// <param name="pGotFocusElement">Element that got focus.</param>
/// <param name="correlationId">Correlation Id</param>
private void RaiseGotFocusEvent(DependencyObject pGotFocusElement, Guid correlationId)
{
if (pGotFocusElement is null)
{
throw new ArgumentNullException(nameof(pGotFocusElement));
}
// Create DO that represents the GotFocus event args
var spGotFocusEventArgs = new RoutedEventArgs();
var spFocusManagerGotFocusEventArgs = new FocusManagerGotFocusEventArgs(_focusedElement, correlationId);
// Set the GotFocus Source value on the routed event args
spGotFocusEventArgs.OriginalSource = pGotFocusElement;
if (FocusableHelper.GetIFocusableForDO(pGotFocusElement) is IFocusable gotFocusElementFocusable)
{
_ = CoreDispatcher.Main.RunAsync(CoreDispatcherPriority.Normal, () =>
{
gotFocusElementFocusable.OnGotFocus(spGotFocusEventArgs);
});
}
// Raise the GotFocus event to the new focused element asynchronously
_ = CoreDispatcher.Main.RunAsync(CoreDispatcherPriority.Normal, () =>
{
(pGotFocusElement as UIElement)?.RaiseEvent(UIElement.GotFocusEvent, spGotFocusEventArgs);
});
// Raise the FocusManagerGotFocus event to the focus manager asynchronously
_ = CoreDispatcher.Main.RunAsync(CoreDispatcherPriority.Normal, () =>
{
GotFocus?.Invoke(null, spFocusManagerGotFocusEventArgs);
});
}
/// <summary>
/// Raises focus element removed event.
/// </summary>
/// <param name="currentNextFocusableElement">Current next focusable element.</param>
/// <returns>New focused element.</returns>
private DependencyObject? RaiseFocusElementRemovedEvent(DependencyObject? currentNextFocusableElement)
{
var eventArgs = new FocusedElementRemovedEventArgs(_focusedElement, currentNextFocusableElement);
FocusedElementRemoved?.Invoke(this, eventArgs);
return eventArgs.NewFocusedElement;
}
/// <summary>
/// Set the focus on the next focusable control. This method will look
/// up both the children and ancestor to find the next focusable control
/// </summary>
/// <param name="focusState">Focus state.</param>
/// <param name="shouldFireFocusedRemoved">Should fire focused removed event?</param>
internal void SetFocusOnNextFocusableElement(FocusState focusState, bool shouldFireFocusedRemoved)
{
bool focusSet = true;
// Find the next focusable element
DependencyObject? nextFocusableElement = GetNextFocusableElement();
if (nextFocusableElement == null)
{
// Find the first focusable element from the root
nextFocusableElement = GetFirstFocusableElement();
}
//On Xbox, we want to give them the power dictate where the focus should go when the currently focused element is
//leaving the tree
if (shouldFireFocusedRemoved)
{
nextFocusableElement = RaiseFocusElementRemovedEvent(nextFocusableElement);
}
if (nextFocusableElement != null && FocusableHelper.IsFocusableDO(nextFocusableElement))
{
var result = SetFocusedElement(new FocusMovement(nextFocusableElement, FocusNavigationDirection.Next, focusState));
focusSet = result.WasMoved;
}
// When the candidate element has AllowFocusOnInteraction set to false, we should still set focus on this element
if (nextFocusableElement is FrameworkElement focusableFrameworkElement)
{
if (!FocusSelection.ShouldUpdateFocus(focusableFrameworkElement, focusState))
{
focusState = FocusState.Programmatic;
}
}
UIElement? nextFocusableUIElement = nextFocusableElement as UIElement;
if (nextFocusableElement == null || !focusSet)
{
ClearFocus();
}
else if (nextFocusableUIElement != null)
{
bool focusUpdated = false;
focusUpdated = nextFocusableUIElement.Focus(focusState, false /*animateIfBringIntoView*/);
if (!focusUpdated)
{
// Failed to set focus. We need to clean the focus state
ClearFocus();
}
}
}
/// <summary>
/// Move the focus to the specified navigation direction(Next/Previous).
/// </summary>
/// <param name="focusNavigationDirection">Focus navigation direction.</param>
/// <returns>Was the move successful?</returns>
internal bool TryMoveFocusInstance(FocusNavigationDirection focusNavigationDirection)
{
var xyFocusOptions = XYFocusOptions.Default;
var result = FindAndSetNextFocus(new FocusMovement(xyFocusOptions, focusNavigationDirection, null));
return result.WasMoved;
}
internal bool FindAndSetNextFocus(FocusNavigationDirection direction)
{
var xyFocusOptions = XYFocusOptions.Default;
var result = FindAndSetNextFocus(new FocusMovement(xyFocusOptions, direction, null));
return result.WasMoved;
}
internal FocusMovementResult FindAndSetNextFocus(FocusMovement movement)
{
FocusMovementResult result = new FocusMovementResult();
var direction = movement.Direction;
bool queryOnly = true;
MUX_ASSERT(
direction == FocusNavigationDirection.Down ||
direction == FocusNavigationDirection.Left ||
direction == FocusNavigationDirection.Right ||
direction == FocusNavigationDirection.Up ||
direction == FocusNavigationDirection.Next ||
direction == FocusNavigationDirection.Previous);
MUX_ASSERT(movement.XYFocusOptions != null);
var xyFocusOptions = movement.XYFocusOptions!.Value;
if (_focusLocked)
{
throw new InvalidOperationException("Cannot change focus while focus is already changing.");
}
if (xyFocusOptions.UpdateManifoldsFromFocusHintRectangle && xyFocusOptions.FocusHintRectangle != null)
{
XYFocus.Manifolds manifolds = new XYFocus.Manifolds();
manifolds.Horizontal = (xyFocusOptions.FocusHintRectangle.Value.Top, xyFocusOptions.FocusHintRectangle.Value.Bottom);
manifolds.Vertical = (xyFocusOptions.FocusHintRectangle.Value.Left, xyFocusOptions.FocusHintRectangle.Value.Right);
_xyFocus.SetManifolds(manifolds);
}
queryOnly = !_contentRoot.FocusAdapter.ShouldDepartFocus(direction);
if (FindNextFocus(new FindFocusOptions(direction, queryOnly), xyFocusOptions, movement.Target, false) is DependencyObject nextFocusedElement)
{
result = SetFocusedElement(new FocusMovement(nextFocusedElement, movement));
if (result.WasMoved && !result.WasCanceled && xyFocusOptions.UpdateManifold)
{
Rect bounds = xyFocusOptions.FocusHintRectangle != null ? xyFocusOptions.FocusHintRectangle.Value : xyFocusOptions.FocusedElementBounds;
_xyFocus.UpdateManifolds(direction, bounds, nextFocusedElement!, xyFocusOptions.IgnoreClipping);
}
}
else if (movement.CanDepartFocus)
{
bool handled = false;
FocusObserver.DepartFocus(direction, movement.CorrelationId, ref handled);
}
return result;
}
internal DependencyObject? FindNextFocus(FocusNavigationDirection direction)
{
var options = XYFocusOptions.Default;
return FindNextFocus(new FindFocusOptions(direction), options);
}
internal DependencyObject? FindNextFocus(
FindFocusOptions findFocusOptions,
XYFocusOptions xyFocusOptions,
DependencyObject? component = null,
bool updateManifolds = true)
{
FocusNavigationDirection direction = findFocusOptions.Direction;
MUX_ASSERT(
direction == FocusNavigationDirection.Down ||
direction == FocusNavigationDirection.Left ||
direction == FocusNavigationDirection.Right ||
direction == FocusNavigationDirection.Up ||
direction == FocusNavigationDirection.Next ||
direction == FocusNavigationDirection.Previous);
switch (direction)
{
case FocusNavigationDirection.Next:
TraceXYFocusEnteredBegin("Next");
break;
case FocusNavigationDirection.Previous:
TraceXYFocusEnteredBegin("Previous");
break;
case FocusNavigationDirection.Up:
TraceXYFocusEnteredBegin("Up");
break;
case FocusNavigationDirection.Down:
TraceXYFocusEnteredBegin("Down");
break;
case FocusNavigationDirection.Left:
TraceXYFocusEnteredBegin("Left");
break;
case FocusNavigationDirection.Right:
TraceXYFocusEnteredBegin("Right");
break;
default:
TraceXYFocusEnteredBegin("Invalid");
break;
}
DependencyObject? nextFocusedElement = null;
var engagedControl = xyFocusOptions.ConsiderEngagement ? _engagedControl : null;
//If we're hosting a component (for e.g. WebView) and focus is moving from within one of our hosted component's children,
//we interpret the component (WebView) as previously focused element
var currentFocusedElementOrComponent = (component == null) ? _focusedElement : component;
if (direction == FocusNavigationDirection.Previous ||
direction == FocusNavigationDirection.Next ||
currentFocusedElementOrComponent == null)
{
bool bPressedShift = direction == FocusNavigationDirection.Previous;
// Get the move candidate element according to next/previous navigation direction.
//TODO:MZ: The original code checks FAILED status
nextFocusedElement = ProcessTabStopInternal(bPressedShift, findFocusOptions.QueryOnly);
if (nextFocusedElement == null)
{
return null;
}
}
else
{
{
var elementAsUI = currentFocusedElementOrComponent as UIElement;
if (elementAsUI == null && FocusableHelper.IsFocusableDO(currentFocusedElementOrComponent))
{
elementAsUI = GetFocusParent(currentFocusedElementOrComponent) as UIElement;
}
xyFocusOptions.FocusedElementBounds = elementAsUI?.GetGlobalBoundsLogical(xyFocusOptions.IgnoreClipping) ?? Rect.Empty;
}
nextFocusedElement = _xyFocus.GetNextFocusableElement(
direction,
currentFocusedElementOrComponent,
engagedControl,
_contentRoot.VisualTree,
updateManifolds,
xyFocusOptions);
}
TraceXYFocusEnteredEnd();
return nextFocusedElement;
}
/// <summary>
/// Get the focus target for this element if one exists (may return null, or a child element of given element).
/// </summary>
/// <param name="element">UI element.</param>
/// <returns>UI element.</returns>
private UIElement? GetFocusTargetDescendant(UIElement element)
{
if (element is Control control)
{
return control.FocusTargetDescendant;
}
return null;
}
/// <summary>
/// Get the element we need to draw the focus rect on. Returning null will cause the focus rectangle
/// to not be drawn.
/// </summary>
/// <returns>Focus target.</returns>
private DependencyObject? GetFocusTarget()
{
var candidate = _focusedElement;
if (candidate == null)
{
if (_focusRectangleUIElement != null &&
_focusRectangleUIElement.TryGetTarget(out var focusRectangleUIElement)) //&& focusRectangleUIElement.IsActive())
{
candidate = focusRectangleUIElement;
}
}
if (candidate == null)
{
return null;
}
if (!IsPluginFocused())
{
return null;
}
// don't draw focus rect for disabled FE(Got focus because of AllowFocusWhenDisabled is set)
if (candidate is FrameworkElement candidateAsFrameworkElement
&& candidateAsFrameworkElement.AllowFocusWhenDisabled
&& candidateAsFrameworkElement is Control { IsEnabled: false })
{
return null;
}
// Test for if the element doesn't have a child to draw to.
if (candidate is UIElement candidateAsUIElement
&& candidateAsUIElement.IsFocused
&& candidateAsUIElement.IsKeyboardFocused)
{
var useSystemFocusVisualsValue = candidateAsUIElement.UseSystemFocusVisuals;
if (useSystemFocusVisualsValue)
{
// Remember the focusTarget, it's different from the focused element in this case
var focusTargetDescendant = GetFocusTargetDescendant(candidateAsUIElement);
if (focusTargetDescendant != null)
{
return focusTargetDescendant;
}
else
{
return candidateAsUIElement;
}
}
}
// For Hyperlinks:
// * If we're not in high-visibility mode, CRichTextBlock.HWRenderFocusRects will do the drawing
if (FocusRectManager.AreHighVisibilityFocusRectsEnabled())
{
TextElement? textElement = GetTextElementForFocusRectCandidate();
if (textElement != null)
{
return textElement;
}
}
return null;
}
private TextElement? GetTextElementForFocusRectCandidate()
{
// Draw focus rect for HyperLink with conditions:
// - Window focused or we are delegating input (GameBar does this)
// - not in special case when focus is gained by SIP keyboard input
// - last input device is keyboard or gamepad
if (IsPluginFocused())
{
var focusedElement = _focusedElement;
if (focusedElement != null && FocusableHelper.IsFocusableDO(focusedElement))
{
var focusManager = VisualTree.GetFocusManagerForElement(focusedElement);
var inputManager = _contentRoot.InputManager;
if (inputManager.LastInputDeviceType == InputDeviceType.Keyboard &&
inputManager.LastInputWasNonFocusNavigationKeyFromSIP())
{
return null;
}
bool lastInputDeviceWasKeyboardWithProgrammaticFocusState = focusManager != null &&
(focusManager.GetRealFocusStateForFocusedElement() == FocusState.Programmatic) &&
(inputManager.LastInputDeviceType == InputDeviceType.Keyboard
|| inputManager.LastInputDeviceType == InputDeviceType.GamepadOrRemote);
bool currentFocusStateIsKeyboard = focusManager != null &&
(focusManager.GetRealFocusStateForFocusedElement() == FocusState.Keyboard);
if (currentFocusStateIsKeyboard || lastInputDeviceWasKeyboardWithProgrammaticFocusState)
{
// TODO: don't assume this will alays be a TextElement going forward
return focusedElement as TextElement;
}
}
}
return null;
}
private void UpdateFocusRect(FocusNavigationDirection focusNavigationDirection, bool cleanOnly)
{
_focusTarget = GetFocusTarget();
_focusRectManager.UpdateFocusRect(_focusedElement, _focusTarget, focusNavigationDirection, cleanOnly);
}
//TODO Uno: Send key press events here when keyboard handling is properly implemented
internal void OnFocusedElementKeyPressed()
{
_focusRectManager.OnFocusedElementKeyPressed();
}
//TODO Uno: Send key press events here when keyboard handling is properly implemented
internal void OnFocusedElementKeyReleased()
{
_focusRectManager.OnFocusedElementKeyReleased();
}
internal void RenderFocusRectForElementIfNeeded(UIElement element, IContentRenderer? renderer)
{
if (element == _focusTarget)
{
_focusRectManager.RenderFocusRectForElement(element, renderer);
}
}
/// <summary>
/// Call when properties of focus visual change. Specifically called when Application.FocusVisualKind
/// changes.
/// </summary>
internal void SetFocusVisualDirty()
{
DependencyObject? focusedObject = _focusedElement;
UIElement? focusedElement = focusedObject as UIElement;
if (focusedElement != null)
{
UIElement.NWSetContentDirty(focusedElement, DirtyFlags.Render);
}
else
{
if (focusedObject != null && FocusableHelper.IsFocusableDO(focusedObject))
{
var hyperlinkHost = FocusableHelper.GetContainingFrameworkElementIfFocusable(focusedObject);
if (hyperlinkHost != null)
{
UIElement.NWSetContentDirty(hyperlinkHost, DirtyFlags.Render);
}
}
}
}
internal void OnAccessKeyDisplayModeChanged()
{
// We should update the caret to visible/collapsed depending on if AK mode is active
if (__LinkerHints.Is_Microsoft_UI_Xaml_Controls_TextBox_Available && _focusedElement is TextBox pTextBox)
{
//TODO Uno: We don't support caret show/hide in TextBoxView yet
//pTextBox.GetView().ShowOrHideCaret();
}
}
private ChangingFocusEventRaiseResult RaiseChangingFocusEvent<TArgs>(
DependencyObject? losingFocusElement,
DependencyObject? gettingFocusElement,
FocusState newFocusState,
FocusNavigationDirection navigationDirection,
RoutedEvent routedEvent,
Guid correlationId,
ChangingFocusEventArgsFactory<TArgs> argsFactory)
where TArgs : RoutedEventArgs, IChangingFocusEventArgs
{
//Locking focus to prevent Focus changes in Getting/Losing focus handlers
_focusLocked = true;
try
{
var deviceKind = _contentRoot.InputManager.LastFocusInputDeviceKind;
var args = argsFactory(
losingFocusElement,
gettingFocusElement,
newFocusState,
navigationDirection,
deviceKind,
_currentFocusOperationCancellable,
correlationId);
UIElement? changingFocusTarget = null;
if (routedEvent == UIElement.LosingFocusEvent)
{
changingFocusTarget = losingFocusElement as UIElement;
}
else if (routedEvent == UIElement.GettingFocusEvent)
{
changingFocusTarget = gettingFocusElement as UIElement;
}
if (changingFocusTarget != null)
{
args.OriginalSource = changingFocusTarget;
changingFocusTarget.RaiseEvent(routedEvent, args);
}
// Always raises FocusManagerGettingFocus/LosingFocus synchronous event.
// sender - passing null for focus manager
if (routedEvent == UIElement.LosingFocusEvent)
{
LosingFocus?.Invoke(null, (args as LosingFocusEventArgs)!);
}
else
{
GettingFocus?.Invoke(null, (args as GettingFocusEventArgs)!);
}
var finalGettingFocusElement = args.NewFocusedElement;
// Check if :
// 1. Focus was redirected
// 2. The element to which we are redirecting focus is focusable.
// If this element is not focusable, look for the focusable child.
// If there is no focusable child, cancel the redirection.
if ((finalGettingFocusElement != gettingFocusElement) &&
finalGettingFocusElement != null &&
!IsFocusable(finalGettingFocusElement))
{
DependencyObject? childFocus = null;
if (navigationDirection == FocusNavigationDirection.Previous)
{
childFocus = GetLastFocusableElement(finalGettingFocusElement);
}
else
{
childFocus = GetFirstFocusableElement(finalGettingFocusElement);
}
finalGettingFocusElement = childFocus;
}
//We cancel the focus change if:
//1. The Cancel flag on the args is set
//2. The focus target is the same as the old focused element
//3. The focus was redirected to null
//4. The focus target after a redirection is not focusable and has no focusable children
if (args.Cancel
|| (finalGettingFocusElement == losingFocusElement)
|| (gettingFocusElement != null && (finalGettingFocusElement == null)))
{
return new ChangingFocusEventRaiseResult(canceled: true);
}
return new ChangingFocusEventRaiseResult(canceled: false, finalGettingFocusElement);
}
finally
{
_focusLocked = false;
}
}
/// <summary>
/// Returns true if the focus change is cancelled.
/// </summary>
private ChangingFocusEventRaiseResult RaiseAndProcessGettingAndLosingFocusEvents(
DependencyObject? pOldFocus,
DependencyObject? pFocusTarget,
FocusState focusState,
FocusNavigationDirection focusNavigationDirection,
bool focusChangeCancellable,
Guid correlationId)
{
DependencyObject? pNewFocus = pFocusTarget;
_currentFocusOperationCancellable = _currentFocusOperationCancellable && focusChangeCancellable;
bool focusRedirected = false;
var losingFocusRaiseResult = RaiseChangingFocusEvent(
pOldFocus,
pNewFocus,
focusState,
focusNavigationDirection,
UIElement.LosingFocusEvent,
correlationId,
CreateLosingFocusEventArgs);
if (losingFocusRaiseResult.Canceled)
{
return new ChangingFocusEventRaiseResult(canceled: true);
}
var pFinalNewFocus = losingFocusRaiseResult.FinalGettingFocusElement;
if (pNewFocus != pFinalNewFocus)
{
focusRedirected = true;
}
if (!focusRedirected)
{
pFinalNewFocus = null;
var gettingFocusRaiseResult = RaiseChangingFocusEvent(
pOldFocus,
pNewFocus,
focusState,
focusNavigationDirection,
UIElement.GettingFocusEvent,
correlationId,
CreateGettingFocusEventArgs);
if (gettingFocusRaiseResult.Canceled)
{
return new ChangingFocusEventRaiseResult(canceled: true);
}
pFinalNewFocus = gettingFocusRaiseResult.FinalGettingFocusElement;
if (pNewFocus != pFinalNewFocus)
{
focusRedirected = true;
}
}
if (focusRedirected)
{
if (!ShouldUpdateFocus(pFinalNewFocus, focusState))
{
return new ChangingFocusEventRaiseResult(canceled: true);
}
var redirectedRaiseResult = RaiseAndProcessGettingAndLosingFocusEvents(
pOldFocus,
pFinalNewFocus,
focusState,
focusNavigationDirection,
focusChangeCancellable,
correlationId);
if (redirectedRaiseResult.Canceled)
{
return new ChangingFocusEventRaiseResult(canceled: true);
}
pFinalNewFocus = redirectedRaiseResult.FinalGettingFocusElement;
pFocusTarget = pFinalNewFocus;
}
return new ChangingFocusEventRaiseResult(canceled: false, pFocusTarget);
}
private bool IsValidTabStopSearchCandidate(DependencyObject? element)
{
bool isValid = IsPotentialTabStop(element);
// If IsPotentialTabStop is false, we could have a UIElement that has TabFocusNavigation Set. If it does, then
// it is still a valid search candidate
if (isValid == false)
{
// We only care if we have a UIElement has TabFocusNavigation set
isValid = element is UIElement uiElement && uiElement.IsTabNavigationSet;
}
return isValid;
}
internal void RaiseNoFocusCandidateFoundEvent(FocusNavigationDirection navigationDirection)
{
var noFocusCandidateFoundTarget = _focusedElement as UIElement;
var focusedElementAsTextElement = _focusedElement as TextElement;
switch (navigationDirection)
{
case FocusNavigationDirection.Next:
TraceXYFocusNotFoundInfo(_focusedElement, "Next");
break;
case FocusNavigationDirection.Previous:
TraceXYFocusNotFoundInfo(_focusedElement, "Previous");
break;
case FocusNavigationDirection.Up:
TraceXYFocusNotFoundInfo(_focusedElement, "Up");
break;
case FocusNavigationDirection.Down:
TraceXYFocusNotFoundInfo(_focusedElement, "Down");
break;
case FocusNavigationDirection.Left:
TraceXYFocusNotFoundInfo(_focusedElement, "Left");
break;
case FocusNavigationDirection.Right:
TraceXYFocusNotFoundInfo(_focusedElement, "Right");
break;
default:
TraceXYFocusNotFoundInfo(_focusedElement, "Invalid");
break;
}
if (focusedElementAsTextElement != null)
{
//We get the containing framework element for all text elements till Bug 10065690 is resolved.
noFocusCandidateFoundTarget = focusedElementAsTextElement.GetContainingFrameworkElement();
}
Guid correlationId = Guid.NewGuid();
bool handled = false;
FocusObserver.DepartFocus(navigationDirection, correlationId, ref handled);
//We should never raise on a null source
if (noFocusCandidateFoundTarget != null)
{
FocusInputDeviceKind deviceKind = _contentRoot.InputManager.LastFocusInputDeviceKind;
var eventArgs = new NoFocusCandidateFoundEventArgs(navigationDirection, deviceKind);
//The source should be the focused element
eventArgs.OriginalSource = _focusedElement;
noFocusCandidateFoundTarget.RaiseEvent(UIElement.NoFocusCandidateFoundEvent, eventArgs);
}
}
private void SetPluginFocusStatus(bool pluginFocused)
{
_pluginFocused = pluginFocused;
}
// When setting focus to a new element and we don't have a FocusState to use, this function helps us
// decide a good focus state based on a recently-used input device type. This function assumes focus is
// actually being set, so it won't return "Unfocued" as a FocusState.
/*static*/
internal FocusState GetFocusStateFromInputDeviceType(InputDeviceType inputDeviceType)
{
switch (inputDeviceType)
{
case InputDeviceType.None:
return FocusState.Programmatic;
case InputDeviceType.Mouse:
case InputDeviceType.Touch:
case InputDeviceType.Pen:
return FocusState.Pointer;
case InputDeviceType.Keyboard:
case InputDeviceType.GamepadOrRemote:
return FocusState.Keyboard;
}
// Unexpected inputDeviceType
MUX_ASSERT(false);
return FocusState.Programmatic;
}
internal bool TrySetAsyncOperation(FocusAsyncOperation asyncOperation)
{
if (_asyncOperation != null)
{
return false;
}
_asyncOperation = asyncOperation;
return true;
}
private void CancelCurrentAsyncOperation(FocusMovementResult result)
{
if (_asyncOperation != null)
{
_asyncOperation.CoreSetResults(result);
_asyncOperation.CoreFireCompletion();
//_asyncOperation.CoreReleaseRef();
_asyncOperation = null;
}
}
private FocusState CoerceFocusState(FocusState focusState)
{
InputDeviceType lastInputDeviceType = _contentRoot.InputManager.LastInputDeviceType;
// Set the new focus state with the last input device type
// if the focus state set as programmatic.
if (focusState == FocusState.Programmatic)
{
/*
* On Programmatic focus, we look at the last input device to decide what could be the focus state.
* Depending on focus state we decide whether to show a focus rectangle or not.
* If focus state is keyboard we always show a rectangle.
* Focus state will be set to Keyboard iff last input device was
* a. GamepadOrRemote
* With GamepadOrRemote, we always show focus rectangle on Xbox unless developer explicitly wants us not to do so,
* in that case it will be set to FocusState.Pointer. Even, if SIP is open and input is any key
* we will display focus rectangle if user is using GamepadOrRemote to type on SIP
* b. Hardware Keyboard
* c. Software keyboard (SIP) and focus movement keys (Tab or Arrow keys)
* Otherwise we set focus state to default FocusState.Pointer state. Setting focus state to Pointer
* will make sure that focus rectangle will not be drawn
*/
switch (lastInputDeviceType)
{
case InputDeviceType.Keyboard:
// In case of non focus navigation keys from SIP, we do not want to display
// focus rectangle, hence setting new focus state as a Pointer.
if (_contentRoot.InputManager.LastInputWasNonFocusNavigationKeyFromSIP())
{
return FocusState.Pointer;
}
/*
* Intentional fall through in the case where input is
* a. any one of focus navigation key(Tab or an arrow key) from SIP or
* b. any key from actual hardware keyboard
*/
return FocusState.Keyboard;
case InputDeviceType.GamepadOrRemote:
return FocusState.Keyboard;
default:
// For all other rest of the cases, setting focus state to Pointer
// will make sure that focus rectangle will not be drawn
return FocusState.Pointer;
}
}
return focusState;
}
internal void SetWindowFocus(bool isFocused, bool isShiftDown)
{
Guid correlationId = Guid.NewGuid();
SetPluginFocusStatus(isFocused);
var focusedElement = _focusedElement;
// We cache the value of UISettings.AnimationsEnabled to avoid the expensive call
// to get it all the time. Unfortunately there is no notification mechanism yet when it
// changes. We work around that by re-evaluating it only when the app window focus changes.
// This is usually the case because in order to change the setting the user needs to switch
// to the settings app and back.
//_coreService.SetShouldReevaluateIsAnimationEnabled(true);
if (focusedElement == null && isFocused)
{
// Find the first focusable element from the root
// and set it as the new focused element.
focusedElement = GetFirstFocusableElementFromRoot(isShiftDown /*bReverse*/);
if (focusedElement != null)
{
FocusState initialFocusState = FocusState.Programmatic;
if (_contentRoot.InputManager.LastInputDeviceType == InputDeviceType.GamepadOrRemote)
{
initialFocusState = FocusState.Keyboard;
}
InitialFocus = true;
//If an error is propagated to the Input Manager here, we are in an invalid state.
var result = SetFocusedElement(new FocusMovement(focusedElement, FocusNavigationDirection.None, initialFocusState));
// Note that because of focus redirection, _focusedElement can be different than focusedElement
// For RS5, we are NOT going to fix this, so we will leave the next line commented.
// focusedElement = _focusedElement;
return;
}
}
if (focusedElement == null)
{
focusedElement = _contentRoot.VisualTree.PublicRootVisual;
}
if (focusedElement != null)
{
// Create the DO that represents the event args
var args = new RoutedEventArgs();
// Call raise event AND reset handled to false if this is not ours
if (isFocused)
{
DependencyObject? focusTarget = focusedElement;
bool wasFocusChangedDuringSyncEvents = false;
using var focusLockGuard = new UnsafeFocusLockOverrideGuard(this);
DependencyObject? currentlyFocusedElement = _focusedElement;
// Raise changing focus events. We cannot cancel or redirect focus here.
// RaiseAndProcessGettingAndLosingFocusEvents returns true if a focus change has been cancelled.
var gettingLosingRaiseResult = RaiseAndProcessGettingAndLosingFocusEvents(
null /*pOldFocus*/,
focusTarget,
GetRealFocusStateForFocusedElement(),
FocusNavigationDirection.None,
false /*focusChangeCancellable*/,
correlationId);
focusTarget = gettingLosingRaiseResult.FinalGettingFocusElement;
var focusChangeCancelled = gettingLosingRaiseResult.Canceled;
MUX_ASSERT(!focusChangeCancelled);
_currentFocusOperationCancellable = true;
// The focused element could have changed after raising the getting/losing events
if (currentlyFocusedElement != _focusedElement)
{
wasFocusChangedDuringSyncEvents = true;
focusedElement = _focusedElement;
}
// Set the Source value on the routed event args
args.OriginalSource = focusedElement;
// We only want to set the focused element as dirty if it is a uielement
if (focusedElement is UIElement uiElement)
{
UIElement.NWSetContentDirty(uiElement, DirtyFlags.Render);
}
// If focus changed, then the GotFocus event has already been raised for the focused element
if (wasFocusChangedDuringSyncEvents == false)
{
// TODO Uno: We raise the events using dispatcher queue, which is a bit different from MUX
// which does everything via EventManager
_ = CoreDispatcher.Main.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// In the case of hyperlink raise both Hyperlink_GotFocus and UIElement_GotFocus. UIElement_GotFocus
// is used internally for to decide where focus rects should be rendered.
if (focusedElement is Hyperlink hyperlink)
{
hyperlink.OnGotFocus(args);
}
// Raise the current focused element
(focusedElement as UIElement)?.RaiseEvent(UIElement.GotFocusEvent, args);
// Raise the FocusManagerLostFocus event to the focus manager asynchronously
LostFocus?.Invoke(null, new FocusManagerLostFocusEventArgs(null, correlationId));
// Raise the FocusManagerGotFocus event to the focus manager asynchronously
GotFocus?.Invoke(null, new FocusManagerGotFocusEventArgs(focusedElement, correlationId));
});
}
// Fire focus changed event for UIAutomation
FireAutomationFocusChanged();
}
else
{
using var focusLockGuard = new UnsafeFocusLockOverrideGuard(this);
DependencyObject? currentlyFocusedElement = _focusedElement;
// Raise changing focus events. We cannot cancel or redirect focus here.
// RaiseAndProcessGettingAndLosingFocusEvents returns true if a focus change has been cancelled.
var gettingLosingRaiseResult = RaiseAndProcessGettingAndLosingFocusEvents(
focusedElement,
null /*focusTarget*/,
FocusState.Unfocused,
FocusNavigationDirection.None,
false /*focusChangeCancellable*/,
correlationId);
bool focusChangeCancelled = gettingLosingRaiseResult.Canceled;
MUX_ASSERT(!focusChangeCancelled);
_currentFocusOperationCancellable = true;
// The focused element could have changed after raising the getting/losing events
if (currentlyFocusedElement != _focusedElement)
{
focusedElement = _focusedElement;
}
// Set the Source value on the routed event args
args.OriginalSource = focusedElement;
//Be wary of the fact that a got focus event also updates the visual. In this scenario, we preceed a lost focus event, so
//we don't have to worry about visuals being updated.
//Manually go and update the visuals. Raising a got focus here instead of calling to UpdateVisualState is risky since it is async
//and we cannot guarantee when it will complete.
//TODO: How will this affect third party apps?
if (focusedElement is Control focusedElementAsControl)
{
//We want to store the current focus state. We will simulate an unfocused state so that the visuals will change,
//but we will not actually change the focusedState.
FocusState focusedState = focusedElementAsControl.FocusState;
focusedElementAsControl.UpdateFocusState(FocusState.Unfocused);
(focusedElement as Control)?.UpdateVisualState(useTransitions: true);
//Restore the original focus state. We lie and say that the focused state is unfocused, although that isn't
//the case. This is done so that if this element is being inspected before a window activated has been received,
//we can ensure that the behavior doesn't change.
focusedElementAsControl.UpdateFocusState(focusedState);
}
// TODO Uno: We raise the events using dispatcher queue, which is a bit different from MUX
// which does everything via EventManager
_ = CoreDispatcher.Main.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// In the case of hyperlink raise both Hyperlink_LostFocus and UIElement_LostFocus. UIElement_LostFocus
// is used internally for to decide where focus rects should be rendered.
if (focusedElement is Hyperlink hyperlink)
{
hyperlink.OnLostFocus(args);
}
// Raise the current focused element
(focusedElement as UIElement)?.RaiseEvent(UIElement.LostFocusEvent, args);
// Raise the FocusManagerLostFocus event to the focus manager asynchronously
LostFocus?.Invoke(null, new FocusManagerLostFocusEventArgs(focusedElement, correlationId));
// Raise the FocusManagerGotFocus event to the focus manager asynchronously
GotFocus?.Invoke(null, new FocusManagerGotFocusEventArgs(null, correlationId));
});
}
}
}
/// <summary>
/// Checks whether the focused element is in a popup.
/// </summary>
/// <returns>True if in popup.</returns>
private bool IsFocusedElementInPopup() => _focusedElement != null && GetRootOfPopupSubTree(_focusedElement) != null;
internal void SetFocusRectangleUIElement(UIElement? newFocusRectangle)
{
if (newFocusRectangle == null)
{
_focusRectangleUIElement = null;
}
else
{
_focusRectangleUIElement = new WeakReference<UIElement>(newFocusRectangle);
}
}
/// <summary>
/// Checks whether plugin is focused.
/// </summary>
/// <returns>True if focused.</returns>
internal bool IsPluginFocused() => _pluginFocused;
internal FocusState GetRealFocusStateForFocusedElement() => _realFocusStateForFocusedElement;
private void TraceXYFocusEnteredBegin(string direction)
{
if (this.Log().IsEnabled(LogLevel.Trace))
{
this.Log().Trace($"XY focus entered begin for direction {direction}");
}
}
private void TraceXYFocusEnteredEnd()
{
if (this.Log().IsEnabled(LogLevel.Trace))
{
this.Log().Trace($"XY focus entered end");
}
}
private void LogTraceTraceUpdateFocusBegin()
{
if (this.Log().IsEnabled(LogLevel.Trace))
{
this.Log().Trace("Update focus begin");
}
}
private void TraceXYFocusNotFoundInfo(DependencyObject? focusedElement, string direction)
{
if (this.Log().IsEnabled(LogLevel.Trace))
{
this.Log().Trace($"Did not find XY focus from {focusedElement} in {direction}");
}
}
private void TraceUpdateFocusEnd(DependencyObject? focusedElement)
{
if (this.Log().IsEnabled(LogLevel.Trace))
{
this.Log().Trace($"Update focus ended for {focusedElement}");
}
}
private static LosingFocusEventArgs CreateLosingFocusEventArgs(
DependencyObject? oldFocusedElement,
DependencyObject? newFocusedElement,
FocusState focusState,
FocusNavigationDirection direction,
FocusInputDeviceKind inputDevice,
bool canCancelFocus,
Guid correlationId) =>
new LosingFocusEventArgs(
oldFocusedElement,
newFocusedElement,
focusState,
direction,
inputDevice,
canCancelFocus,
correlationId);
private static GettingFocusEventArgs CreateGettingFocusEventArgs(
DependencyObject? oldFocusedElement,
DependencyObject? newFocusedElement,
FocusState focusState,
FocusNavigationDirection direction,
FocusInputDeviceKind inputDevice,
bool canCancelFocus,
Guid correlationId) =>
new GettingFocusEventArgs(
oldFocusedElement,
newFocusedElement,
focusState,
direction,
inputDevice,
canCancelFocus,
correlationId);
DependencyObject? IFocusManager.FindNextFocus(FindFocusOptions findFocusOptions, XYFocusOptions xyFocusOptions, DependencyObject? component, bool updateManifolds) =>
FindNextFocus(findFocusOptions, xyFocusOptions, component, updateManifolds);
FocusMovementResult IFocusManager.SetFocusedElement(FocusMovement movement) => SetFocusedElement(movement);
}
}
| FocusManager |
csharp | ServiceStack__ServiceStack | ServiceStack.Text/tests/ServiceStack.Text.Tests/NUnitSetupFixture.cs | {
"start": 96,
"end": 309
} | public class ____
// {
// [OneTimeSetUp]
// public void Setup()
// {
//#if NETCORE
// ServiceStack.Memory.NetCoreMemory.Configure();
//#endif
// }
// }
//} | NUnitSetupFixture |
csharp | ChilliCream__graphql-platform | src/GreenDonut/src/GreenDonut/DependencyInjection/DataLoaderRegistration.cs | {
"start": 169,
"end": 1562
} | public sealed class ____
{
private readonly DataLoaderFactory _factory;
public DataLoaderRegistration(Type instanceType)
: this(instanceType, instanceType) { }
public DataLoaderRegistration(Type serviceType, Type instanceType)
{
ServiceType = serviceType;
InstanceType = instanceType;
var factory = ActivatorUtilities.CreateFactory(instanceType, []);
_factory = sp => (IDataLoader)factory.Invoke(sp, null);
}
public DataLoaderRegistration(Type serviceType, DataLoaderFactory factory)
: this(serviceType, serviceType, factory) { }
public DataLoaderRegistration(Type serviceType, Type instanceType, DataLoaderFactory factory)
{
ServiceType = serviceType;
InstanceType = instanceType;
_factory = factory;
}
/// <summary>
/// Gets the service type.
/// </summary>
public Type ServiceType { get; }
/// <summary>
/// Gets the instance type.
/// </summary>
public Type InstanceType { get; }
/// <summary>
/// Creates a new DataLoader instance.
/// </summary>
/// <param name="services">
/// The available services.
/// </param>
/// <returns>
/// Returns the new DataLoader instance.
/// </returns>
public IDataLoader CreateDataLoader(IServiceProvider services)
=> _factory(services);
}
| DataLoaderRegistration |
csharp | MassTransit__MassTransit | tests/MassTransit.Tests/SagaStateMachineTests/Dynamic Modify/UnobservedEvent_Specs.cs | {
"start": 2732,
"end": 2862
} | class ____
{
public int Volts { get; set; }
}
}
[TestFixture(Category = "Dynamic Modify")]
| A |
csharp | AvaloniaUI__Avalonia | src/Markup/Avalonia.Markup/Markup/Parsers/SelectorGrammar.cs | {
"start": 19970,
"end": 20168
} | public class ____ : ISyntax
{
public override bool Equals(object? obj)
{
return obj is DescendantSyntax;
}
}
| DescendantSyntax |
csharp | CommunityToolkit__dotnet | tests/CommunityToolkit.Mvvm.UnitTests/Test_Messenger.Request.cs | {
"start": 5480,
"end": 7776
} | public class ____ : AsyncRequestMessage<int>
{
}
[TestMethod]
[DataRow(typeof(StrongReferenceMessenger))]
[DataRow(typeof(WeakReferenceMessenger))]
public void Test_Messenger_CollectionRequestMessage_Ok_NoReplies(Type type)
{
IMessenger? messenger = (IMessenger)Activator.CreateInstance(type)!;
object? recipient = new();
static void Receive(object recipient, NumbersCollectionRequestMessage m)
{
}
messenger.Register<NumbersCollectionRequestMessage>(recipient, Receive);
IReadOnlyCollection<int>? results = messenger.Send<NumbersCollectionRequestMessage>().Responses;
Assert.IsEmpty(results);
GC.KeepAlive(recipient);
}
[TestMethod]
[DataRow(typeof(StrongReferenceMessenger))]
[DataRow(typeof(WeakReferenceMessenger))]
public void Test_Messenger_CollectionRequestMessage_Ok_MultipleReplies(Type type)
{
IMessenger? messenger = (IMessenger)Activator.CreateInstance(type)!;
object recipient1 = new();
object recipient2 = new();
object recipient3 = new();
object? r1 = null;
object? r2 = null;
object? r3 = null;
void Receive1(object recipient, NumbersCollectionRequestMessage m)
{
r1 = recipient;
m.Reply(1);
}
void Receive2(object recipient, NumbersCollectionRequestMessage m)
{
r2 = recipient;
m.Reply(2);
}
void Receive3(object recipient, NumbersCollectionRequestMessage m)
{
r3 = recipient;
m.Reply(3);
}
messenger.Register<NumbersCollectionRequestMessage>(recipient1, Receive1);
messenger.Register<NumbersCollectionRequestMessage>(recipient2, Receive2);
messenger.Register<NumbersCollectionRequestMessage>(recipient3, Receive3);
List<int> responses = new();
foreach (int response in messenger.Send<NumbersCollectionRequestMessage>())
{
responses.Add(response);
}
Assert.AreSame(r1, recipient1);
Assert.AreSame(r2, recipient2);
Assert.AreSame(r3, recipient3);
CollectionAssert.AreEquivalent(responses, new[] { 1, 2, 3 });
}
| AsyncNumberRequestMessage |
csharp | unoplatform__uno | src/SamplesApp/UITests.Shared/Windows_UI_Input/PointersTests/Nested_Exit.xaml.cs | {
"start": 256,
"end": 929
} | partial class ____ : Page
{
private bool _case1_exitedBlue;
public Nested_Exit()
{
this.InitializeComponent();
}
private void Case1_InitTest(object sender, RoutedEventArgs e)
{
Case1_out.Text = "--init--";
_case1_exitedBlue = false;
}
private void Case1_OnPointerExited(object sender, PointerRoutedEventArgs e)
{
switch ((sender as FrameworkElement)?.Name)
{
case "Case1_Blue":
_case1_exitedBlue = true;
break;
case "Case1_Pink" when _case1_exitedBlue:
Case1_out.Text = "Success";
break;
case "Case1_Pink":
Case1_out.Text = "Failed"; // Note: common failure case is to remain in "--init--" !
break;
}
}
}
| Nested_Exit |
csharp | dotnet__orleans | test/Grains/TestGrainInterfaces/IGeneratorTestDerivedGrain2.cs | {
"start": 43,
"end": 197
} | public interface ____ : IGeneratorTestGrain
{
Task<string> StringConcat(string str1, string str2, string str3);
}
} | IGeneratorTestDerivedGrain2 |
csharp | ServiceStack__ServiceStack | ServiceStack.Text/src/ServiceStack.Text/TaskUtils.cs | {
"start": 306,
"end": 4288
} | public static class ____
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Task<T> FromResult<T>(T result) => Task.FromResult(result);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Task<T> InTask<T>(this T result) => Task.FromResult(result);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Task<T> InTask<T>(this Exception ex)
{
var taskSource = new TaskCompletionSource<T>();
taskSource.TrySetException(ex);
return taskSource.Task;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsSuccess(this Task task) => !task.IsFaulted && task.IsCompleted;
public static Task<To> Cast<From, To>(this Task<From> task) where To : From => task.Then(x => (To)x);
public static TaskScheduler SafeTaskScheduler()
{
//Unit test runner
if (SynchronizationContext.Current != null)
return TaskScheduler.FromCurrentSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
return TaskScheduler.FromCurrentSynchronizationContext();
}
public static Task<To> Then<From, To>(this Task<From> task, Func<From, To> fn)
{
var tcs = new TaskCompletionSource<To>();
task.ContinueWith(t =>
{
if (t.IsFaulted)
tcs.TrySetException(t.Exception.InnerExceptions);
else if (t.IsCanceled)
tcs.TrySetCanceled();
else
tcs.TrySetResult(fn(t.Result));
}, TaskContinuationOptions.ExecuteSynchronously);
return tcs.Task;
}
public static Task Then(this Task task, Func<Task, Task> fn)
{
var tcs = new TaskCompletionSource<object>();
task.ContinueWith(t =>
{
if (t.IsFaulted)
tcs.TrySetException(t.Exception.InnerExceptions);
else if (t.IsCanceled)
tcs.TrySetCanceled();
else
tcs.TrySetResult(fn(t));
}, TaskContinuationOptions.ExecuteSynchronously);
return tcs.Task;
}
//http://stackoverflow.com/a/13904811/85785
public static Task EachAsync<T>(this IEnumerable<T> items, Func<T, int, Task> fn)
{
var tcs = new TaskCompletionSource<object>();
var enumerator = items.GetEnumerator();
var i = 0;
Action<Task> next = null;
next = t =>
{
if (t.IsFaulted)
tcs.TrySetException(t.Exception.InnerExceptions);
else if (t.IsCanceled)
tcs.TrySetCanceled();
else
StartNextIteration(tcs, fn, enumerator, ref i, next);
};
StartNextIteration(tcs, fn, enumerator, ref i, next);
tcs.Task.ContinueWith(_ => enumerator.Dispose(), TaskContinuationOptions.ExecuteSynchronously);
return tcs.Task;
}
static void StartNextIteration<T>(TaskCompletionSource<object> tcs,
Func<T, int, Task> fn,
IEnumerator<T> enumerator,
ref int i,
Action<Task> next)
{
bool moveNext;
try
{
moveNext = enumerator.MoveNext();
}
catch (Exception ex)
{
tcs.SetException(ex);
return;
}
if (!moveNext)
{
tcs.SetResult(null);
return;
}
Task iterationTask = null;
try
{
iterationTask = fn(enumerator.Current, i);
}
catch (Exception ex)
{
tcs.SetException(ex);
}
i++;
iterationTask?.ContinueWith(next, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
public static void Sleep(int timeMs)
{
Thread.Sleep(timeMs);
}
public static void Sleep(TimeSpan time)
{
Thread.Sleep(time);
}
} | TaskUtils |
csharp | bitwarden__server | bitwarden_license/src/Commercial.Core/SecretsManager/Queries/Secrets/SecretsSyncQuery.cs | {
"start": 294,
"end": 1745
} | public class ____ : ISecretsSyncQuery
{
private readonly ISecretRepository _secretRepository;
private readonly IServiceAccountRepository _serviceAccountRepository;
public SecretsSyncQuery(
ISecretRepository secretRepository,
IServiceAccountRepository serviceAccountRepository)
{
_secretRepository = secretRepository;
_serviceAccountRepository = serviceAccountRepository;
}
public async Task<(bool HasChanges, IEnumerable<Secret>? Secrets)> GetAsync(SecretsSyncRequest syncRequest)
{
if (syncRequest.LastSyncedDate == null)
{
return await GetSecretsAsync(syncRequest);
}
var serviceAccount = await _serviceAccountRepository.GetByIdAsync(syncRequest.ServiceAccountId);
if (serviceAccount == null)
{
throw new NotFoundException();
}
if (syncRequest.LastSyncedDate.Value <= serviceAccount.RevisionDate)
{
return await GetSecretsAsync(syncRequest);
}
return (HasChanges: false, null);
}
private async Task<(bool HasChanges, IEnumerable<Secret>? Secrets)> GetSecretsAsync(SecretsSyncRequest syncRequest)
{
var secrets = await _secretRepository.GetManyByOrganizationIdAsync(syncRequest.OrganizationId,
syncRequest.ServiceAccountId, syncRequest.AccessClientType);
return (HasChanges: true, Secrets: secrets);
}
}
| SecretsSyncQuery |
csharp | abpframework__abp | modules/identity/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityLinkUserManager.cs | {
"start": 214,
"end": 6360
} | public class ____ : DomainService
{
protected IIdentityLinkUserRepository IdentityLinkUserRepository { get; }
protected IdentityUserManager UserManager { get; }
protected new ICurrentTenant CurrentTenant { get; }
public IdentityLinkUserManager(IIdentityLinkUserRepository identityLinkUserRepository, IdentityUserManager userManager, ICurrentTenant currentTenant)
{
IdentityLinkUserRepository = identityLinkUserRepository;
UserManager = userManager;
CurrentTenant = currentTenant;
}
public async Task<List<IdentityLinkUser>> GetListAsync(IdentityLinkUserInfo linkUserInfo, bool includeIndirect = false, int batchSize = 100 * 100, CancellationToken cancellationToken = default)
{
using (CurrentTenant.Change(null))
{
var users = await IdentityLinkUserRepository.GetListAsync(linkUserInfo, cancellationToken: cancellationToken);
if (!includeIndirect)
{
return users;
}
var allUsers = await IdentityLinkUserRepository.GetListAsync(batchSize ,cancellationToken: cancellationToken);
return await GetAllRelatedLinksAsync(allUsers, linkUserInfo);
}
}
protected virtual Task<List<IdentityLinkUser>> GetAllRelatedLinksAsync(List<IdentityLinkUser> allUsers, IdentityLinkUserInfo userInfo)
{
var visited = new HashSet<(Guid, Guid?)>();
var result = new List<IdentityLinkUser>();
var queue = new Queue<(Guid, Guid?)>();
queue.Enqueue((userInfo.UserId, userInfo.TenantId));
visited.Add((userInfo.UserId, userInfo.TenantId));
while (queue.Count > 0)
{
var (currentUserId, currentTenantId) = queue.Dequeue();
var relatedLinks = allUsers.Where(x =>
(x.SourceUserId == currentUserId && x.SourceTenantId == currentTenantId) ||
(x.TargetUserId == currentUserId && x.TargetTenantId == currentTenantId)
).ToList();
foreach (var link in relatedLinks)
{
var node1 = (link.SourceUserId, link.SourceTenantId);
var node2 = (link.TargetUserId, link.TargetTenantId);
if (!result.Contains(link))
{
result.Add(link);
}
if (!visited.Contains(node1))
{
queue.Enqueue(node1);
visited.Add(node1);
}
if (!visited.Contains(node2))
{
queue.Enqueue(node2);
visited.Add(node2);
}
}
}
return Task.FromResult(result);
}
public virtual async Task LinkAsync(IdentityLinkUserInfo sourceLinkUser, IdentityLinkUserInfo targetLinkUser, CancellationToken cancellationToken = default)
{
using (CurrentTenant.Change(null))
{
if (sourceLinkUser.UserId == targetLinkUser.UserId && sourceLinkUser.TenantId == targetLinkUser.TenantId)
{
return;
}
if (await IsLinkedAsync(sourceLinkUser, targetLinkUser, cancellationToken: cancellationToken))
{
return;
}
var userLink = new IdentityLinkUser(
GuidGenerator.Create(),
sourceLinkUser,
targetLinkUser);
await IdentityLinkUserRepository.InsertAsync(userLink, true, cancellationToken);
}
}
public virtual async Task<bool> IsLinkedAsync(IdentityLinkUserInfo sourceLinkUser, IdentityLinkUserInfo targetLinkUser, bool includeIndirect = false, CancellationToken cancellationToken = default)
{
using (CurrentTenant.Change(null))
{
if (includeIndirect)
{
return (await GetListAsync(sourceLinkUser, true, cancellationToken: cancellationToken))
.Any(x => x.SourceTenantId == targetLinkUser.TenantId && x.SourceUserId == targetLinkUser.UserId ||
x.TargetTenantId == targetLinkUser.TenantId && x.TargetUserId == targetLinkUser.UserId);
}
return await IdentityLinkUserRepository.FindAsync(sourceLinkUser, targetLinkUser, cancellationToken) != null;
}
}
public virtual async Task UnlinkAsync(IdentityLinkUserInfo sourceLinkUser, IdentityLinkUserInfo targetLinkUser, CancellationToken cancellationToken = default)
{
using (CurrentTenant.Change(null))
{
if (!await IsLinkedAsync(sourceLinkUser, targetLinkUser, cancellationToken: cancellationToken))
{
return;
}
var linkedUser = await IdentityLinkUserRepository.FindAsync(sourceLinkUser, targetLinkUser, cancellationToken);
if (linkedUser != null)
{
await IdentityLinkUserRepository.DeleteAsync(linkedUser, cancellationToken: cancellationToken);
}
}
}
public virtual async Task<string> GenerateLinkTokenAsync(IdentityLinkUserInfo targetLinkUser, string tokenPurpose, CancellationToken cancellationToken = default)
{
using (CurrentTenant.Change(targetLinkUser.TenantId))
{
var user = await UserManager.GetByIdAsync(targetLinkUser.UserId);
return await UserManager.GenerateUserTokenAsync(
user,
LinkUserTokenProviderConsts.LinkUserTokenProviderName,
tokenPurpose);
}
}
public virtual async Task<bool> VerifyLinkTokenAsync(IdentityLinkUserInfo targetLinkUser, string token, string tokenPurpose, CancellationToken cancellationToken = default)
{
using (CurrentTenant.Change(targetLinkUser.TenantId))
{
var user = await UserManager.GetByIdAsync(targetLinkUser.UserId);
return await UserManager.VerifyUserTokenAsync(
user,
LinkUserTokenProviderConsts.LinkUserTokenProviderName,
tokenPurpose,
token);
}
}
}
| IdentityLinkUserManager |
csharp | JamesNK__Newtonsoft.Json | Src/Newtonsoft.Json.Tests/TestObjects/Name.cs | {
"start": 1237,
"end": 1478
} | public class ____
{
public string personsName;
public List<PhoneNumber> pNumbers = new List<PhoneNumber>();
public Name(string personsName)
{
this.personsName = personsName;
}
}
} | Name |
csharp | dotnet__maui | src/BlazorWebView/src/Maui/Windows/WinUIWebViewManager.cs | {
"start": 755,
"end": 1553
} | internal class ____ : WebView2WebViewManager
{
private readonly BlazorWebViewHandler _handler;
private readonly WebView2Control _webview;
private readonly string _hostPageRelativePath;
private readonly string _contentRootRelativeToAppRoot;
private static readonly bool _isPackagedApp;
private readonly ILogger _logger;
static WinUIWebViewManager()
{
try
{
_isPackagedApp = Package.Current != null;
}
catch
{
_isPackagedApp = false;
}
}
/// <summary>
/// Initializes a new instance of <see cref="WinUIWebViewManager"/>
/// </summary>
/// <param name="webview">A <see cref="WebView2Control"/> to access platform-specific WebView2 APIs.</param>
/// <param name="services">A service provider containing services to be used by this | WinUIWebViewManager |
csharp | dotnetcore__FreeSql | FreeSql.Tests/FreeSql.Tests/Issues/1549.cs | {
"start": 5797,
"end": 5974
} | public class ____
{
[Column(IsPrimary = true)]
public int Id { get; set; }
public string Name { get; set; }
}
}
}
| ExtEntity |
csharp | mongodb__mongo-csharp-driver | tests/MongoDB.Driver.Tests/Core/WireProtocol/Messages/Encoders/BinaryEncoders/CommandResponseMessageBinaryEncoderTests.cs | {
"start": 814,
"end": 4029
} | public class ____
{
[Fact]
public void constructor_should_initialize_instance()
{
var stream = new MemoryStream();
var encoderSettings = new MessageEncoderSettings();
var wrappedEncoder = new CommandMessageBinaryEncoder(stream, encoderSettings);
var result = new CommandResponseMessageBinaryEncoder(wrappedEncoder);
result._wrappedEncoder().Should().BeSameAs(wrappedEncoder);
}
[Fact]
public void ReadMessage_should_delegate_to_wrapped_encoder()
{
var document = new BsonDocument("x", 1);
var sections = new[] { new Type0CommandMessageSection<BsonDocument>(document, BsonDocumentSerializer.Instance) };
var message = new CommandMessage(1, 2, sections, false);
var bytes = CreateMessageBytes(message);
var stream = new MemoryStream(bytes);
var subject = CreateSubject(stream);
var result = subject.ReadMessage();
var resultMessage = result.Should().BeOfType<CommandResponseMessage>().Subject;
var wrappedMessage = resultMessage.WrappedMessage.Should().BeOfType<CommandMessage>().Subject;
wrappedMessage.RequestId.Should().Be(message.RequestId);
wrappedMessage.ResponseTo.Should().Be(message.ResponseTo);
wrappedMessage.MoreToCome.Should().Be(message.MoreToCome);
wrappedMessage.Sections.Should().HaveCount(1);
var wrappedMessageType0Section = wrappedMessage.Sections[0].Should().BeOfType<Type0CommandMessageSection<RawBsonDocument>>().Subject;
wrappedMessageType0Section.Document.Should().Be(document);
}
[Fact]
public void WriteMessage_should_delegate_to_wrapped_encoder()
{
var stream = new MemoryStream();
var subject = CreateSubject(stream);
var document = new BsonDocument("x", 1);
var sections = new[] { new Type0CommandMessageSection<BsonDocument>(document, BsonDocumentSerializer.Instance) };
var wrappedMessage = new CommandMessage(1, 2, sections, false);
var message = new CommandResponseMessage(wrappedMessage);
var expectedBytes = CreateMessageBytes(wrappedMessage);
subject.WriteMessage(message);
var result = stream.ToArray();
result.Should().Equal(expectedBytes);
}
// private methods
private byte[] CreateMessageBytes(CommandMessage message)
{
var stream = new MemoryStream();
var encoderSettings = new MessageEncoderSettings();
var encoder = new CommandMessageBinaryEncoder(stream, encoderSettings);
encoder.WriteMessage(message);
return stream.ToArray();
}
private CommandResponseMessageBinaryEncoder CreateSubject(Stream stream)
{
var encoderSettings = new MessageEncoderSettings();
var wrappedEncoder = new CommandMessageBinaryEncoder(stream, encoderSettings);
return new CommandResponseMessageBinaryEncoder(wrappedEncoder);
}
}
| CommandResponseMessageBinaryEncoderTests |
csharp | EventStore__EventStore | src/KurrentDB.Core/TransactionLog/Checkpoint/CheckpointMetric.cs | {
"start": 466,
"end": 1721
} | public class ____ {
private readonly IReadOnlyCheckpoint[] _checkpoints;
private readonly Measurement<long>[] _measurements;
private readonly KeyValuePair<string, object>[][] _tagss;
public CheckpointMetric(Meter meter, string name, params IReadOnlyCheckpoint[] checkpoints) {
_checkpoints = checkpoints;
_measurements = new Measurement<long>[checkpoints.Length];
_tagss = new KeyValuePair<string, object>[checkpoints.Length][];
for (var i = 0; i < checkpoints.Length; i++) {
_tagss[i] = new KeyValuePair<string, object>[] {
new("name", checkpoints[i].Name),
new("read", "non-flushed"),
};
}
// we could consider using ObservableCounter, but ICheckpoint does allow the values to
// go down as well as up, so we are currently supporting that here.
meter.CreateObservableUpDownCounter(name, Observe);
}
private IEnumerable<Measurement<long>> Observe() {
for (var i = 0; i < _checkpoints.Length; i++) {
// looks like the Measurement constructor will allocate an array for the tags but the
// other constructor overloads appear to allocate two
_measurements[i] = new Measurement<long>(
value: _checkpoints[i].ReadNonFlushed(),
tags: _tagss[i].AsSpan());
}
return _measurements;
}
}
| CheckpointMetric |
csharp | EventStore__EventStore | src/KurrentDB.Core/Metrics/IPersistentSubscriptionTracker.cs | {
"start": 283,
"end": 505
} | public interface ____ {
public static IPersistentSubscriptionTracker NoOp => NoOpTracker.Instance;
void OnNewStats(IReadOnlyList<MonitoringMessage.PersistentSubscriptionInfo> newStats);
}
file | IPersistentSubscriptionTracker |
csharp | nunit__nunit | src/NUnitFramework/framework/Internal/Execution/CompositeWorkItem.cs | {
"start": 515,
"end": 16699
} | public class ____ : WorkItem
{
// static Logger log = InternalTrace.GetLogger("CompositeWorkItem");
private readonly TestSuite _suite;
private readonly TestSuiteResult _suiteResult;
private TestCommand? _setupCommand;
private TestCommand? _teardownCommand;
/// <summary>
/// List of Child WorkItems
/// </summary>
public List<WorkItem> Children { get; } = new();
/// <summary>
/// Indicates whether this work item should use a separate dispatcher.
/// </summary>
public override bool IsolateChildTests => ExecutionStrategy == ParallelExecutionStrategy.NonParallel && Context.Dispatcher.LevelOfParallelism > 0;
private CountdownEvent? _childTestCountdown;
/// <summary>
/// Construct a CompositeWorkItem for executing a test suite
/// using a filter to select child tests.
/// </summary>
/// <param name="suite">The TestSuite to be executed</param>
/// <param name="childFilter">A filter used to select child tests</param>
public CompositeWorkItem(TestSuite suite, ITestFilter childFilter)
: base(suite, childFilter)
{
_suite = suite;
_suiteResult = (TestSuiteResult)Result;
}
/// <summary>
/// Method that actually performs the work. Overridden
/// in CompositeWorkItem to do one-time setup, run all child
/// items and then dispatch the one-time teardown work item.
/// </summary>
protected override void PerformWork()
{
if (!CheckForCancellation())
{
if (Test.RunState == RunState.Explicit && !Filter.IsExplicitMatch(Test))
{
SkipFixture(ResultState.Explicit, GetSkipReason(), null);
}
else
{
switch (Test.RunState)
{
default:
case RunState.Runnable:
case RunState.Explicit:
if (Children.Count > 0)
{
InitializeSetUpAndTearDownCommands();
PerformOneTimeSetUp();
if (!CheckForCancellation())
{
if ((Result.ResultState.Status is not TestStatus.Failed and not TestStatus.Skipped) &&
(Result.ResultState.Site != FailureSite.SetUp))
{
RunChildren();
return;
// Just return: completion event will take care
// of OneTimeTearDown when all tests are done.
}
else
{
SkipChildren(this, Result.ResultState.WithSite(FailureSite.Parent), "OneTimeSetUp: " + Result.Message, Result.StackTrace);
}
}
// Directly execute the OneTimeFixtureTearDown for tests that
// were skipped, failed or set to inconclusive in one time setup
// unless we are aborting.
if (Context.ExecutionStatus != TestExecutionStatus.AbortRequested)
PerformOneTimeTearDown();
}
else if (Test.TestType == "Theory")
{
Result.SetResult(ResultState.Failure, "No test cases were provided");
}
break;
case RunState.Skipped:
SkipFixture(ResultState.Skipped, GetSkipReason(), null);
break;
case RunState.Ignored:
SkipFixture(ResultState.Ignored, GetSkipReason(), null);
break;
case RunState.NotRunnable:
SkipFixture(ResultState.NotRunnable, GetSkipReason(), GetProviderStackTrace());
break;
}
}
}
// Fall through in case nothing was run.
// Otherwise, this is done in the completion event.
WorkItemComplete();
}
#region Helper Methods
private bool CheckForCancellation()
{
if (Context.ExecutionStatus != TestExecutionStatus.Running)
{
Result.SetResult(ResultState.Cancelled, "Test cancelled by user");
return true;
}
return false;
}
private void InitializeSetUpAndTearDownCommands()
{
var methodValidator = Test.HasLifeCycle(LifeCycle.InstancePerTestCase)
? new StaticMethodValidator(
$"Only static OneTimeSetUp and OneTimeTearDown are allowed for {nameof(LifeCycle.InstancePerTestCase)} mode.")
: null;
List<SetUpTearDownItem> setUpTearDownItems =
BuildSetUpTearDownList(_suite.OneTimeSetUpMethods, _suite.OneTimeTearDownMethods, methodValidator);
var actionItems = new List<TestActionItem>();
foreach (ITestAction action in Test.Actions)
{
// We need to go through all the actions on the test to determine which ones
// will be used immediately and which will go into the context for use by
// lower level tests.
//
// Special handling here for ParameterizedMethodSuite is a bit ugly. However,
// it is needed because Tests are not supposed to know anything about Action
// Attributes (or any attribute) and Attributes don't know where they were
// initially applied unless we tell them.
//
// ParameterizedMethodSuites and individual test cases both use the same
// MethodInfo as a source of attributes. We handle the Test and Default targets
// in the test case, so we don't want to doubly handle it here.
bool applyToSuite = action.Targets.HasFlag(ActionTargets.Suite)
|| action.Targets == ActionTargets.Default && !(Test is ParameterizedMethodSuite);
bool applyToTest = action.Targets.HasFlag(ActionTargets.Test)
&& !(Test is ParameterizedMethodSuite);
if (applyToSuite)
actionItems.Add(new TestActionItem(action));
if (applyToTest)
Context.UpstreamActions.Add(action);
}
_setupCommand = MakeOneTimeSetUpCommand(setUpTearDownItems, actionItems);
_teardownCommand = MakeOneTimeTearDownCommand(setUpTearDownItems, actionItems);
}
private TestCommand MakeOneTimeSetUpCommand(List<SetUpTearDownItem> setUpTearDown, List<TestActionItem> actions)
{
TestCommand command = new EmptyTestCommand(Test);
// Add Action Commands
int index = actions.Count;
while (--index >= 0)
command = new BeforeTestActionCommand(command, actions[index]);
if (Test.TypeInfo is not null)
{
// Build the OneTimeSetUpCommands
foreach (SetUpTearDownItem item in setUpTearDown)
command = new OneTimeSetUpCommand(command, item);
// Construct the fixture if necessary
if (!Test.TypeInfo.IsStaticClass && !Test.HasLifeCycle(LifeCycle.InstancePerTestCase))
command = new ConstructFixtureCommand(command);
}
// Prefix with any IApplyToContext items from attributes
foreach (var attr in Test.GetCustomAttributes<IApplyToContext>(true))
command = new ApplyChangesToContextCommand(command, attr);
return command;
}
private TestCommand MakeOneTimeTearDownCommand(List<SetUpTearDownItem> setUpTearDownItems, List<TestActionItem> actions)
{
TestCommand command = new EmptyTestCommand(Test);
// For Theories, follow with TheoryResultCommand to adjust result as needed
if (Test.TestType == "Theory")
command = new TheoryResultCommand(command);
// Create the AfterTestAction commands
int index = actions.Count;
while (--index >= 0)
command = new AfterTestActionCommand(command, actions[index]);
// Create the OneTimeTearDown commands
foreach (SetUpTearDownItem item in setUpTearDownItems)
command = new OneTimeTearDownCommand(command, item);
// Dispose of fixture if necessary
if (Test is IDisposableFixture && Test.TypeInfo is not null && DisposeHelper.IsDisposable(Test.TypeInfo.Type) && !Test.HasLifeCycle(LifeCycle.InstancePerTestCase))
command = new DisposeFixtureCommand(command);
return command;
}
private void PerformOneTimeSetUp()
{
try
{
_setupCommand?.Execute(Context);
// SetUp may have changed some things in the environment
Context.UpdateContextFromEnvironment();
}
catch (Exception ex)
{
Result.RecordException(ex.Unwrap(), FailureSite.SetUp);
}
}
private void RunChildren()
{
if (Test.TestType == "Theory")
Result.SetResult(ResultState.Inconclusive);
int childCount = Children.Count;
if (childCount == 0)
throw new InvalidOperationException("RunChildren called but item has no children");
_childTestCountdown = new CountdownEvent(childCount);
foreach (WorkItem child in Children)
{
if (CheckForCancellation())
break;
child.Completed += new EventHandler(OnChildItemCompleted);
child.InitializeContext(new TestExecutionContext(Context));
// In case we run directly, on same thread
child.TestWorker = TestWorker;
Context.Dispatcher.Dispatch(child);
childCount--;
}
// If run was cancelled, reduce countdown by number of
// child items not yet staged and check if we are done.
if (childCount > 0)
{
lock (_childCompletionLock)
{
_childTestCountdown.Signal(childCount);
if (_childTestCountdown.CurrentCount == 0)
OnAllChildItemsCompleted();
}
}
}
private void SkipFixture(ResultState resultState, string message, string? stackTrace)
{
Result.SetResult(resultState.WithSite(FailureSite.SetUp), message, StackFilter.DefaultFilter.Filter(stackTrace));
SkipChildren(this, resultState.WithSite(FailureSite.Parent), "OneTimeSetUp: " + message, stackTrace);
}
private void SkipChildren(CompositeWorkItem workItem, ResultState resultState, string message, string? stackTrace)
{
foreach (WorkItem child in workItem.Children)
{
SetChildWorkItemSkippedResult(child.Result, resultState, message, stackTrace);
_suiteResult.AddResult(child.Result);
// Some runners may depend on getting the TestFinished event
// even for tests that have been skipped at a higher level.
Context.Listener.TestFinished(child.Result);
if (child is CompositeWorkItem item)
SkipChildren(item, resultState, message, stackTrace);
}
}
private void SetChildWorkItemSkippedResult(TestResult result, ResultState resultState, string message, string? stackTrace)
{
result.SetResult(resultState, message, stackTrace);
result.StartTime = Context.StartTime;
result.EndTime = DateTime.UtcNow;
result.Duration = Context.Duration;
}
private void PerformOneTimeTearDown()
{
// Our child tests or even unrelated tests may have
// executed on the same thread since the time that
// this test started, so we have to re-establish
// the proper execution environment
Context.EstablishExecutionEnvironment();
_teardownCommand?.Execute(Context);
}
private string GetSkipReason()
{
return (string?)Test.Properties.Get(PropertyNames.SkipReason) ?? string.Empty;
}
private string? GetProviderStackTrace()
{
return (string?)Test.Properties.Get(PropertyNames.ProviderStackTrace);
}
private readonly object _childCompletionLock = new();
private void OnChildItemCompleted(object? sender, EventArgs e)
{
// Since child tests may be run on various threads, this
// method may be called simultaneously by different children.
// The lock is a member of the parent item and therefore
// only blocks its own children.
lock (_childCompletionLock)
{
if (sender is WorkItem childTask)
{
childTask.Completed -= new EventHandler(OnChildItemCompleted);
_suiteResult.AddResult(childTask.Result);
if (Context.StopOnError && childTask.Result.ResultState.Status == TestStatus.Failed)
Context.ExecutionStatus = TestExecutionStatus.StopRequested;
// Check to see if all children completed
// _childTestCountdown is created before running child tasks, so is not null here.
_childTestCountdown!.Signal();
if (_childTestCountdown.CurrentCount == 0)
OnAllChildItemsCompleted();
}
}
}
/// <summary>
///
/// </summary>
private void OnAllChildItemsCompleted()
{
if (Context.ExecutionStatus == TestExecutionStatus.AbortRequested)
WorkItemComplete();
else
Context.Dispatcher.Dispatch(new OneTimeTearDownWorkItem(this));
}
private readonly object _cancelLock = new();
/// <summary>
/// Cancel (abort or stop) a CompositeWorkItem and all of its children
/// </summary>
/// <param name="force">true if the CompositeWorkItem and all of its children should be aborted, false if it should allow all currently running tests to complete</param>
public override void Cancel(bool force)
{
lock (_cancelLock)
{
foreach (var child in Children)
{
var ctx = child.Context;
if (ctx is not null)
ctx.ExecutionStatus = force ? TestExecutionStatus.AbortRequested : TestExecutionStatus.StopRequested;
if (child.State == WorkItemState.Running)
child.Cancel(force);
}
}
}
#endregion
#region Nested OneTimeTearDownWorkItem Class
/// <summary>
/// OneTimeTearDownWorkItem represents the cleanup
/// and one-time teardown phase of a CompositeWorkItem
/// </summary>
| CompositeWorkItem |
csharp | unoplatform__uno | src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Controls/TabViewTabDroppedOutsideEventArgs.cs | {
"start": 261,
"end": 614
} | public partial class ____
{
// Skipping already declared property Item
// Skipping already declared property Tab
// Forced skipping of method Microsoft.UI.Xaml.Controls.TabViewTabDroppedOutsideEventArgs.Item.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.TabViewTabDroppedOutsideEventArgs.Tab.get
}
}
| TabViewTabDroppedOutsideEventArgs |
csharp | dotnet__efcore | src/EFCore.Relational/Query/Internal/RelationalValueConverterCompensatingExpressionVisitor.cs | {
"start": 743,
"end": 6034
} | public class ____ : ExpressionVisitor
{
private readonly ISqlExpressionFactory _sqlExpressionFactory;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public RelationalValueConverterCompensatingExpressionVisitor(
ISqlExpressionFactory sqlExpressionFactory)
=> _sqlExpressionFactory = sqlExpressionFactory;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected override Expression VisitExtension(Expression extensionExpression)
=> extensionExpression switch
{
ShapedQueryExpression shapedQuery => VisitShapedQueryExpression(shapedQuery),
CaseExpression @case => VisitCase(@case),
SelectExpression select => VisitSelect(select),
PredicateJoinExpressionBase join => VisitJoin(join),
_ => base.VisitExtension(extensionExpression)
};
private Expression VisitShapedQueryExpression(ShapedQueryExpression shapedQueryExpression)
{
var newQueryExpression = Visit(shapedQueryExpression.QueryExpression);
var newShaperExpression = Visit(shapedQueryExpression.ShaperExpression);
return shapedQueryExpression.Update(newQueryExpression, newShaperExpression);
}
private Expression VisitCase(CaseExpression caseExpression)
{
var testIsCondition = caseExpression.Operand == null;
var operand = (SqlExpression?)Visit(caseExpression.Operand);
var whenClauses = new List<CaseWhenClause>();
foreach (var whenClause in caseExpression.WhenClauses)
{
var test = (SqlExpression)Visit(whenClause.Test);
if (testIsCondition)
{
test = TryCompensateForBoolWithValueConverter(test);
}
var result = (SqlExpression)Visit(whenClause.Result);
whenClauses.Add(new CaseWhenClause(test, result));
}
var elseResult = (SqlExpression?)Visit(caseExpression.ElseResult);
return _sqlExpressionFactory.Case(operand, whenClauses, elseResult, caseExpression);
}
private Expression VisitSelect(SelectExpression selectExpression)
{
var projections = this.VisitAndConvert(selectExpression.Projection);
var tables = this.VisitAndConvert(selectExpression.Tables);
var predicate = TryCompensateForBoolWithValueConverter((SqlExpression?)Visit(selectExpression.Predicate));
var groupBy = this.VisitAndConvert(selectExpression.GroupBy);
var having = TryCompensateForBoolWithValueConverter((SqlExpression?)Visit(selectExpression.Having));
var orderings = this.VisitAndConvert(selectExpression.Orderings);
var offset = (SqlExpression?)Visit(selectExpression.Offset);
var limit = (SqlExpression?)Visit(selectExpression.Limit);
return selectExpression.Update(tables, predicate, groupBy, having, projections, orderings, offset, limit);
}
private Expression VisitJoin(PredicateJoinExpressionBase joinExpression)
{
var table = (TableExpressionBase)Visit(joinExpression.Table);
var joinPredicate = TryCompensateForBoolWithValueConverter((SqlExpression)Visit(joinExpression.JoinPredicate));
return joinExpression.Update(table, joinPredicate);
}
[return: NotNullIfNotNull(nameof(sqlExpression))]
private SqlExpression? TryCompensateForBoolWithValueConverter(SqlExpression? sqlExpression)
{
if ((sqlExpression is ColumnExpression or JsonScalarExpression)
&& sqlExpression.TypeMapping!.ClrType == typeof(bool)
&& sqlExpression.TypeMapping.Converter != null)
{
return _sqlExpressionFactory.Equal(
sqlExpression,
_sqlExpressionFactory.Constant(true, sqlExpression.TypeMapping));
}
if (sqlExpression is SqlUnaryExpression sqlUnaryExpression)
{
return sqlUnaryExpression.Update(
TryCompensateForBoolWithValueConverter(sqlUnaryExpression.Operand));
}
if (sqlExpression is SqlBinaryExpression { OperatorType: ExpressionType.AndAlso or ExpressionType.OrElse } sqlBinaryExpression)
{
return sqlBinaryExpression.Update(
TryCompensateForBoolWithValueConverter(sqlBinaryExpression.Left),
TryCompensateForBoolWithValueConverter(sqlBinaryExpression.Right));
}
return sqlExpression;
}
}
| RelationalValueConverterCompensatingExpressionVisitor |
csharp | aspnetboilerplate__aspnetboilerplate | src/Abp.ZeroCore/Zero/AbpZeroCoreModule.cs | {
"start": 310,
"end": 1916
} | public class ____ : AbpModule
{
public override void PreInitialize()
{
Configuration.Localization.Sources.Extensions.Add(
new LocalizationSourceExtensionInfo(
AbpZeroConsts.LocalizationSourceName,
new XmlEmbeddedFileLocalizationDictionaryProvider(
typeof(AbpZeroCoreModule).GetAssembly(), "Abp.Zero.Localization.SourceExt"
)
)
);
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(typeof(AbpZeroCoreModule).GetAssembly());
RegisterUserTokenExpirationWorker();
}
public override void PostInitialize()
{
if (Configuration.BackgroundJobs.IsJobExecutionEnabled)
{
using (var entityTypes = IocManager.ResolveAsDisposable<IAbpZeroEntityTypes>())
{
var implType = typeof(UserTokenExpirationWorker<,>)
.MakeGenericType(entityTypes.Object.Tenant, entityTypes.Object.User);
var workerManager = IocManager.Resolve<IBackgroundWorkerManager>();
workerManager.Add(IocManager.Resolve(implType) as IBackgroundWorker);
}
}
}
private void RegisterUserTokenExpirationWorker()
{
using (var entityTypes = IocManager.ResolveAsDisposable<IAbpZeroEntityTypes>())
{
var implType = typeof(UserTokenExpirationWorker<,>)
.MakeGenericType(entityTypes.Object.Tenant, entityTypes.Object.User);
IocManager.Register(implType);
}
}
} | AbpZeroCoreModule |
csharp | CommunityToolkit__WindowsCommunityToolkit | Microsoft.Toolkit.Uwp.SampleApp/SamplePages/ImageEx/ImageExLazyLoadingControl.xaml.cs | {
"start": 381,
"end": 917
} | partial class ____
{
public ImageExLazyLoadingControl()
{
InitializeComponent();
}
public event EventHandler CloseButtonClick;
private void CloseButton_Click(object sender, RoutedEventArgs e)
{
CloseButtonClick?.Invoke(this, EventArgs.Empty);
}
private async void ImageEx_ImageExOpened(object sender, ImageExOpenedEventArgs e)
{
await new MessageDialog("Image Opened").ShowAsync();
}
}
} | ImageExLazyLoadingControl |
csharp | dotnet__reactive | Rx.NET/Source/tests/Tests.System.Reactive/Tests/SystemClockTest.cs | {
"start": 26893,
"end": 27752
} | private class ____ : LocalScheduler
{
public override IDisposable Schedule<TState>(TState state, TimeSpan dueTime, Func<IScheduler, TState, IDisposable> action)
{
throw new NotImplementedException();
}
internal override void SystemClockChanged(object sender, SystemClockChangedEventArgs args)
{
var target = default(WeakReference<LocalScheduler>);
foreach (var entries in SystemClock.SystemClockChanged)
{
if (entries.TryGetTarget(out var local) && local == this)
{
target = entries;
break;
}
}
SystemClock.SystemClockChanged.Remove(target);
}
}
| RemoveScheduler |
csharp | dotnet__maui | src/Core/src/Handlers/Switch/SwitchHandler.Android.cs | {
"start": 1935,
"end": 2244
} | class ____ : Java.Lang.Object, CompoundButton.IOnCheckedChangeListener
{
public SwitchHandler? Handler { get; set; }
void CompoundButton.IOnCheckedChangeListener.OnCheckedChanged(CompoundButton? buttonView, bool isToggled)
{
Handler?.OnCheckedChanged(isToggled);
}
}
}
} | CheckedChangeListener |
csharp | dotnet__maui | src/Controls/tests/TestCases.HostApp/Issues/Issue28580.xaml.cs | {
"start": 130,
"end": 231
} | public partial class ____ : ContentPage
{
public Issue28580()
{
InitializeComponent();
}
} | Issue28580 |
csharp | DapperLib__Dapper | Dapper.ProviderTools/DbConnectionExtensions.cs | {
"start": 1372,
"end": 4981
} | private sealed class ____
{
private static readonly ConcurrentDictionary<Type, ByTypeHelpers> s_byType
= new ConcurrentDictionary<Type, ByTypeHelpers>();
private readonly Func<DbConnection, Guid>? _getClientConnectionId;
private readonly Action<DbConnection>? _clearPool;
private readonly Action? _clearAllPools;
public bool TryGetClientConnectionId(DbConnection connection, out Guid clientConnectionId)
{
if (_getClientConnectionId is null)
{
clientConnectionId = default;
return false;
}
clientConnectionId = _getClientConnectionId(connection);
return true;
}
public bool TryClearPool(DbConnection connection)
{
if (_clearPool is null) return false;
_clearPool(connection);
return true;
}
public bool TryClearAllPools()
{
if (_clearAllPools is null) return false;
_clearAllPools();
return true;
}
public static ByTypeHelpers Get(Type type)
{
if (!s_byType.TryGetValue(type, out var value))
{
s_byType[type] = value = new ByTypeHelpers(type);
}
return value;
}
private ByTypeHelpers(Type type)
{
_getClientConnectionId = TryGetInstanceProperty<Guid>("ClientConnectionId", type);
try
{
var clearAllPools = type.GetMethod("ClearAllPools", BindingFlags.Public | BindingFlags.Static,
null, Type.EmptyTypes, null);
if (clearAllPools is not null)
{
_clearAllPools = (Action)Delegate.CreateDelegate(typeof(Action), clearAllPools);
}
}
catch { }
try
{
var clearPool = type.GetMethod("ClearPool", BindingFlags.Public | BindingFlags.Static,
null, new[] { type }, null);
if (clearPool is not null)
{
var p = Expression.Parameter(typeof(DbConnection), "connection");
var body = Expression.Call(clearPool, Expression.Convert(p, type));
var lambda = Expression.Lambda<Action<DbConnection>>(body, p);
_clearPool = lambda.Compile();
}
}
catch { }
}
private static Func<DbConnection, T>? TryGetInstanceProperty<T>(string name, Type type)
{
try
{
var prop = type.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
if (prop is null || !prop.CanRead) return null;
if (prop.PropertyType != typeof(T)) return null;
var p = Expression.Parameter(typeof(DbConnection), "connection");
var body = Expression.Property(Expression.Convert(p, type), prop);
var lambda = Expression.Lambda<Func<DbConnection, T>>(body, p);
return lambda.Compile();
}
catch
{
return null;
}
}
}
}
}
| ByTypeHelpers |
csharp | dotnet__reactive | AsyncRx.NET/System.Reactive.Async/NotificationAsyncExtensions.cs | {
"start": 269,
"end": 1548
} | internal static class ____
{
/// <summary>
/// Invokes the observer's method corresponding to the notification.
/// </summary>
/// <typeparam name="T">The item type.</typeparam>
/// <param name="notification">The notification.</param>
/// <param name="observer">Observer to invoke the notification on.</param>
/// <returns>A task that completes when the observer is done.</returns>
/// <exception cref="ArgumentNullException"></exception>
/// <remarks>
/// The implementation of <see cref="Notification{T}"/> we get from System.Reactive is
/// missing the built-in support for this method that the version in System.Reactive.Shared
/// used to have (but is otherwise identical). This reproduces that as an extension method.
/// </remarks>
public static async ValueTask AcceptAsync<T>(this Notification<T> notification, IAsyncObserver<T> observer)
{
if (observer == null)
throw new ArgumentNullException(nameof(observer));
var adapter = new NotificationAdapter<T>(observer);
notification.Accept(adapter);
await adapter.Wait().ConfigureAwait(false);
}
| NotificationAsyncExtensions |
csharp | unoplatform__uno | src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Media/GeometryCollection.cs | {
"start": 258,
"end": 2694
} | public partial class ____ : global::System.Collections.Generic.IList<global::Microsoft.UI.Xaml.Media.Geometry>, global::System.Collections.Generic.IEnumerable<global::Microsoft.UI.Xaml.Media.Geometry>
{
// Skipping already declared property Size
// Skipping already declared method Microsoft.UI.Xaml.Media.GeometryCollection.GeometryCollection()
// Forced skipping of method Microsoft.UI.Xaml.Media.GeometryCollection.GeometryCollection()
// Forced skipping of method Microsoft.UI.Xaml.Media.GeometryCollection.GetAt(uint)
// Forced skipping of method Microsoft.UI.Xaml.Media.GeometryCollection.Size.get
// Forced skipping of method Microsoft.UI.Xaml.Media.GeometryCollection.GetView()
// Forced skipping of method Microsoft.UI.Xaml.Media.GeometryCollection.IndexOf(Microsoft.UI.Xaml.Media.Geometry, out uint)
// Forced skipping of method Microsoft.UI.Xaml.Media.GeometryCollection.SetAt(uint, Microsoft.UI.Xaml.Media.Geometry)
// Forced skipping of method Microsoft.UI.Xaml.Media.GeometryCollection.InsertAt(uint, Microsoft.UI.Xaml.Media.Geometry)
// Forced skipping of method Microsoft.UI.Xaml.Media.GeometryCollection.RemoveAt(uint)
// Forced skipping of method Microsoft.UI.Xaml.Media.GeometryCollection.Append(Microsoft.UI.Xaml.Media.Geometry)
// Forced skipping of method Microsoft.UI.Xaml.Media.GeometryCollection.RemoveAtEnd()
// Forced skipping of method Microsoft.UI.Xaml.Media.GeometryCollection.Clear()
// Forced skipping of method Microsoft.UI.Xaml.Media.GeometryCollection.GetMany(uint, Microsoft.UI.Xaml.Media.Geometry[])
// Forced skipping of method Microsoft.UI.Xaml.Media.GeometryCollection.ReplaceAll(Microsoft.UI.Xaml.Media.Geometry[])
// Forced skipping of method Microsoft.UI.Xaml.Media.GeometryCollection.First()
// Processing: System.Collections.Generic.IList<Microsoft.UI.Xaml.Media.Geometry>
// Skipping already implement System.Collections.Generic.IList<Microsoft.UI.Xaml.Media.Geometry>.this[int]
// Processing: System.Collections.Generic.ICollection<Microsoft.UI.Xaml.Media.Geometry>
// Skipping already implement System.Collections.Generic.ICollection<Microsoft.UI.Xaml.Media.Geometry>.Count
// Skipping already implement System.Collections.Generic.ICollection<Microsoft.UI.Xaml.Media.Geometry>.IsReadOnly
// Processing: System.Collections.Generic.IEnumerable<Microsoft.UI.Xaml.Media.Geometry>
// Processing: System.Collections.IEnumerable
}
}
| GeometryCollection |
csharp | AvaloniaUI__Avalonia | src/Avalonia.Base/Input/IKeyboardDevice.cs | {
"start": 112,
"end": 259
} | public enum ____
{
None = 0,
Alt = 1,
Control = 2,
Shift = 4,
Meta = 8,
}
[Flags]
| KeyModifiers |
csharp | atata-framework__atata | src/Atata/WebDriver/LogSections/ClickWithHoldLogSection.cs | {
"start": 19,
"end": 293
} | public class ____ : UIComponentLogSection
{
public ClickWithHoldLogSection(UIComponent component, TimeSpan interval)
: base(component) =>
Message = $"Click {component.ComponentFullName} with {interval.ToShortIntervalString()} hold";
}
| ClickWithHoldLogSection |
csharp | CommunityToolkit__WindowsCommunityToolkit | Microsoft.Toolkit.Uwp.SampleApp/SamplePages/WeatherLiveTileAndToast/WeatherLiveTileAndToastPage.xaml.cs | {
"start": 496,
"end": 12467
} | partial class ____
{
public WeatherLiveTileAndToastPage()
{
InitializeComponent();
}
public static ToastContent GenerateToastContent()
{
ToastContentBuilder builder = new ToastContentBuilder();
// Include launch string so we know what to open when user clicks toast
builder.AddArgument("action", "viewForecast");
builder.AddArgument("zip", 98008);
// We'll always have this summary text on our toast notification
// (it is required that your toast starts with a text element)
builder.AddText("Today will be mostly sunny with a high of 63 and a low of 42.");
// If Adaptive Toast Notifications are supported
if (IsAdaptiveToastSupported())
{
// Use the rich Tile-like visual layout
builder.AddVisualChild(new AdaptiveGroup()
{
Children =
{
GenerateSubgroup("Mon", "Mostly Cloudy.png", 63, 42),
GenerateSubgroup("Tue", "Cloudy.png", 57, 38),
GenerateSubgroup("Wed", "Sunny.png", 59, 43),
GenerateSubgroup("Thu", "Sunny.png", 62, 42),
GenerateSubgroup("Fri", "Sunny.png", 71, 66)
}
});
}
// Otherwise...
else
{
// We'll just add two simple lines of text
builder.AddText("Monday ⛅ 63° / 42°")
.AddText("Tuesday ☁ 57° / 38°");
}
// Set the base URI for the images, so we don't redundantly specify the entire path
builder.Content.Visual.BaseUri = new Uri("Assets/NotificationAssets/", UriKind.Relative);
return builder.Content;
}
public static TileContent GenerateTileContent()
{
TileContentBuilder builder = new TileContentBuilder();
// Small Tile
builder.AddTile(Notifications.TileSize.Small)
.SetTextStacking(TileTextStacking.Center, Notifications.TileSize.Small)
.AddText("Mon", Notifications.TileSize.Small, hintStyle: AdaptiveTextStyle.Body, hintAlign: AdaptiveTextAlign.Center)
.AddText("63°", Notifications.TileSize.Small, hintStyle: AdaptiveTextStyle.Base, hintAlign: AdaptiveTextAlign.Center);
// Medium Tile
builder.AddTile(Notifications.TileSize.Medium)
.AddAdaptiveTileVisualChild(
new AdaptiveGroup()
{
Children =
{
GenerateSubgroup("Mon", "Mostly Cloudy.png", 63, 42),
GenerateSubgroup("Tue", "Cloudy.png", 57, 38)
}
}, Notifications.TileSize.Medium);
// Wide Tile
builder.AddTile(Notifications.TileSize.Wide)
.AddAdaptiveTileVisualChild(
new AdaptiveGroup()
{
Children =
{
GenerateSubgroup("Mon", "Mostly Cloudy.png", 63, 42),
GenerateSubgroup("Tue", "Cloudy.png", 57, 38),
GenerateSubgroup("Wed", "Sunny.png", 59, 43),
GenerateSubgroup("Thu", "Sunny.png", 62, 42),
GenerateSubgroup("Fri", "Sunny.png", 71, 66)
}
}, Notifications.TileSize.Wide);
// Large tile
builder.AddTile(Notifications.TileSize.Large, GenerateLargeTileContent());
// Set the base URI for the images, so we don't redundantly specify the entire path
builder.Content.Visual.BaseUri = new Uri("Assets/NotificationAssets/", UriKind.Relative);
return builder.Content;
}
private static bool IsAdaptiveToastSupported()
{
switch (AnalyticsInfo.VersionInfo.DeviceFamily)
{
case "Windows.Desktop":
return true;
// Other device families do not support adaptive toasts
default:
return false;
}
}
private static TileBindingContentAdaptive GenerateLargeTileContent()
{
return new TileBindingContentAdaptive()
{
Children =
{
new AdaptiveGroup()
{
Children =
{
new AdaptiveSubgroup()
{
HintWeight = 30,
Children =
{
new AdaptiveImage() { Source = "Mostly Cloudy.png" }
}
},
new AdaptiveSubgroup()
{
Children =
{
new AdaptiveText()
{
Text = "Monday",
HintStyle = AdaptiveTextStyle.Base
},
new AdaptiveText()
{
Text = "63° / 42°"
},
new AdaptiveText()
{
Text = "20% chance of rain",
HintStyle = AdaptiveTextStyle.CaptionSubtle
},
new AdaptiveText()
{
Text = "Winds 5 mph NE",
HintStyle = AdaptiveTextStyle.CaptionSubtle
}
}
}
}
},
// For spacing
new AdaptiveText(),
new AdaptiveGroup()
{
Children =
{
GenerateLargeSubgroup("Tue", "Cloudy.png", 57, 38),
GenerateLargeSubgroup("Wed", "Sunny.png", 59, 43),
GenerateLargeSubgroup("Thu", "Sunny.png", 62, 42),
GenerateLargeSubgroup("Fri", "Sunny.png", 71, 66)
}
}
}
};
}
private static AdaptiveSubgroup GenerateSubgroup(string day, string img, int tempHi, int tempLo)
{
return new AdaptiveSubgroup()
{
HintWeight = 1,
Children =
{
// Day
new AdaptiveText()
{
Text = day,
HintAlign = AdaptiveTextAlign.Center
},
// Image
new AdaptiveImage()
{
Source = img,
HintRemoveMargin = true
},
// High temp
new AdaptiveText()
{
Text = tempHi + "°",
HintAlign = AdaptiveTextAlign.Center
},
// Low temp
new AdaptiveText()
{
Text = tempLo + "°",
HintAlign = AdaptiveTextAlign.Center,
HintStyle = AdaptiveTextStyle.CaptionSubtle
}
}
};
}
private static AdaptiveSubgroup GenerateLargeSubgroup(string day, string image, int high, int low)
{
// Generate the normal subgroup
var subgroup = GenerateSubgroup(day, image, high, low);
// Allow there to be padding around the image
(subgroup.Children[1] as AdaptiveImage).HintRemoveMargin = null;
return subgroup;
}
private static AdaptiveText GenerateLegacyToastText(string day, string weatherEmoji, int tempHi, int tempLo)
{
return new AdaptiveText()
{
Text = $"{day} {weatherEmoji} {tempHi}° / {tempLo}°"
};
}
private void ButtonPinTile_Click(object sender, RoutedEventArgs e)
{
PinTile();
}
private async void PinTile()
{
SecondaryTile tile = new SecondaryTile(DateTime.Now.Ticks.ToString())
{
DisplayName = "WeatherSample",
Arguments = "args"
};
tile.VisualElements.ShowNameOnSquare150x150Logo = true;
tile.VisualElements.ShowNameOnSquare310x310Logo = true;
tile.VisualElements.ShowNameOnWide310x150Logo = true;
tile.VisualElements.Square150x150Logo = Constants.Square150x150Logo;
tile.VisualElements.Wide310x150Logo = Constants.Wide310x150Logo;
tile.VisualElements.Square310x310Logo = Constants.Square310x310Logo;
if (!await tile.RequestCreateAsync())
{
return;
}
// Generate the tile notification content and update the tile
TileContent content = GenerateTileContent();
TileUpdateManager.CreateTileUpdaterForSecondaryTile(tile.TileId).Update(new TileNotification(content.GetXml()));
}
private void ButtonPopToast_Click(object sender, RoutedEventArgs e)
{
PopToast();
}
private void PopToast()
{
// Generate the toast notification content
ToastContentBuilder builder = new ToastContentBuilder();
// Include launch string so we know what to open when user clicks toast
builder.AddArgument("action", "viewForecast");
builder.AddArgument("zip", 98008);
// We'll always have this summary text on our toast notification
// (it is required that your toast starts with a text element)
builder.AddText("Today will be mostly sunny with a high of 63 and a low of 42.");
// If Adaptive Toast Notifications are supported
if (IsAdaptiveToastSupported())
{
// Use the rich Tile-like visual layout
builder.AddVisualChild(new AdaptiveGroup()
{
Children =
{
GenerateSubgroup("Mon", "Mostly Cloudy.png", 63, 42),
GenerateSubgroup("Tue", "Cloudy.png", 57, 38),
GenerateSubgroup("Wed", "Sunny.png", 59, 43),
GenerateSubgroup("Thu", "Sunny.png", 62, 42),
GenerateSubgroup("Fri", "Sunny.png", 71, 66)
}
});
}
// Otherwise...
else
{
// We'll just add two simple lines of text
builder
.AddText("Monday ⛅ 63° / 42°")
.AddText("Tuesday ☁ 57° / 38°");
}
// Set the base URI for the images, so we don't redundantly specify the entire path
builder.Content.Visual.BaseUri = new Uri("Assets/NotificationAssets/", UriKind.Relative);
// Show the toast
builder.Show();
}
}
} | WeatherLiveTileAndToastPage |
csharp | dotnet__efcore | test/EFCore.Relational.Tests/Infrastructure/RelationalModelValidatorTest.cs | {
"start": 149414,
"end": 149935
} | public class ____ : TpcBase
{
public string Value { get; set; }
}
}
protected override void SetBaseType(IMutableEntityType entityType, IMutableEntityType baseEntityType)
{
base.SetBaseType(entityType, baseEntityType);
baseEntityType.SetDiscriminatorProperty(baseEntityType.AddProperty("Discriminator", typeof(string)));
baseEntityType.SetDiscriminatorValue(baseEntityType.Name);
entityType.SetDiscriminatorValue(entityType.Name);
}
| TpcDerived |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 1076252,
"end": 1076519
} | public partial interface ____
{
public global::ChilliCream.Nitro.CommandLine.Cloud.Client.IListWorkspaceCommandQuery_Me? Me { get; }
}
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| IListWorkspaceCommandQueryResult |
csharp | AutoFixture__AutoFixture | Src/AutoFixtureUnitTest/CommandMock.cs | {
"start": 52,
"end": 320
} | public class ____<T>
{
public CommandMock()
{
this.OnCommand = x => { };
}
public Action<T> OnCommand { get; set; }
public void Command(T x)
{
this.OnCommand(x);
}
}
| CommandMock |
csharp | dotnet__BenchmarkDotNet | tests/BenchmarkDotNet.Analyzers.Tests/AnalyzerTests/General/BenchmarkClassAnalyzerTests.cs | {
"start": 27587,
"end": 28346
} | public class ____ : AnalyzerTestFixture<BenchmarkClassAnalyzer>
{
public OnlyOneMethodCanBeBaseline() : base(BenchmarkClassAnalyzer.OnlyOneMethodCanBeBaselineRule) { }
[Theory, CombinatorialData]
public async Task Class_with_only_one_benchmark_method_marked_as_baseline_should_not_trigger_diagnostic(
[CombinatorialMemberData(nameof(ClassAbstractModifiersEnumerableLocal))] string abstractModifier,
bool useConstantsFromOtherClass,
bool useLocalConstants,
bool useInvalidFalseValue)
{
var testCode = /* lang=c#-test */ $$"""
using BenchmarkDotNet.Attributes;
| OnlyOneMethodCanBeBaseline |
csharp | abpframework__abp | templates/app-nolayers/aspnet-core/MyCompanyName.MyProjectName.Blazor.Server.Mongo/MyProjectNameGlobalFeatureConfigurator.cs | {
"start": 67,
"end": 581
} | public static class ____
{
private static readonly OneTimeRunner OneTimeRunner = new OneTimeRunner();
public static void Configure()
{
OneTimeRunner.Run(() =>
{
/* You can configure (enable/disable) global features of the used modules here.
* Please refer to the documentation to learn more about the Global Features System:
* https://docs.abp.io/en/abp/latest/Global-Features
*/
});
}
}
| MyProjectNameGlobalFeatureConfigurator |
csharp | dotnet__maui | src/Controls/src/Core/VisualElement/VisualElement.Windows.cs | {
"start": 139,
"end": 887
} | public partial class ____
{
public static void MapAccessKeyHorizontalOffset(IViewHandler handler, IView view) =>
Platform.VisualElementExtensions.UpdateAccessKey((PlatformView)handler.PlatformView, view);
public static void MapAccessKeyPlacement(IViewHandler handler, IView view) =>
Platform.VisualElementExtensions.UpdateAccessKey((PlatformView)handler.PlatformView, view);
public static void MapAccessKey(IViewHandler handler, IView view) =>
Platform.VisualElementExtensions.UpdateAccessKey((PlatformView)handler.PlatformView, view);
public static void MapAccessKeyVerticalOffset(IViewHandler handler, IView view) =>
Platform.VisualElementExtensions.UpdateAccessKey((PlatformView)handler.PlatformView, view);
}
} | VisualElement |
csharp | dotnet__BenchmarkDotNet | tests/BenchmarkDotNet.Analyzers.Tests/AnalyzerTests/BenchmarkRunner/RunAnalyzerTests.cs | {
"start": 343,
"end": 1054
} | public class ____ : AnalyzerTestFixture<RunAnalyzer>
{
[Theory, CombinatorialData]
public async Task Invoking_with_a_public_nonabstract_unsealed_nongeneric_type_argument_class_having_only_one_and_public_method_annotated_with_the_benchmark_attribute_should_not_trigger_diagnostic(
bool isGenericInvocation)
{
const string classWithOneBenchmarkMethodName = "ClassWithOneBenchmarkMethod";
var invocationExpression = isGenericInvocation ? $"<{classWithOneBenchmarkMethodName}>()" : $"(typeof({classWithOneBenchmarkMethodName}))";
var testCode = /* lang=c#-test */ $$"""
using BenchmarkDotNet.Running;
| General |
csharp | unoplatform__uno | src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Controls/Grid.cs | {
"start": 261,
"end": 4747
} | public partial class ____ : global::Microsoft.UI.Xaml.Controls.Panel
{
// Skipping already declared property RowSpacing
// Skipping already declared property Padding
// Skipping already declared property CornerRadius
// Skipping already declared property ColumnSpacing
// Skipping already declared property BorderThickness
// Skipping already declared property BorderBrush
// Skipping already declared property BackgroundSizing
// Skipping already declared property ColumnDefinitions
// Skipping already declared property RowDefinitions
// Skipping already declared property BackgroundSizingProperty
// Skipping already declared property BorderBrushProperty
// Skipping already declared property BorderThicknessProperty
// Skipping already declared property ColumnProperty
// Skipping already declared property ColumnSpacingProperty
// Skipping already declared property ColumnSpanProperty
// Skipping already declared property CornerRadiusProperty
// Skipping already declared property PaddingProperty
// Skipping already declared property RowProperty
// Skipping already declared property RowSpacingProperty
// Skipping already declared property RowSpanProperty
// Skipping already declared method Microsoft.UI.Xaml.Controls.Grid.Grid()
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.Grid()
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.RowDefinitions.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.ColumnDefinitions.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.BackgroundSizing.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.BackgroundSizing.set
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.BorderBrush.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.BorderBrush.set
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.BorderThickness.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.BorderThickness.set
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.CornerRadius.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.CornerRadius.set
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.Padding.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.Padding.set
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.RowSpacing.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.RowSpacing.set
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.ColumnSpacing.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.ColumnSpacing.set
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.BackgroundSizingProperty.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.BorderBrushProperty.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.BorderThicknessProperty.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.CornerRadiusProperty.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.PaddingProperty.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.RowSpacingProperty.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.ColumnSpacingProperty.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.RowProperty.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.GetRow(Microsoft.UI.Xaml.FrameworkElement)
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.SetRow(Microsoft.UI.Xaml.FrameworkElement, int)
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.ColumnProperty.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.GetColumn(Microsoft.UI.Xaml.FrameworkElement)
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.SetColumn(Microsoft.UI.Xaml.FrameworkElement, int)
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.RowSpanProperty.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.GetRowSpan(Microsoft.UI.Xaml.FrameworkElement)
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.SetRowSpan(Microsoft.UI.Xaml.FrameworkElement, int)
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.ColumnSpanProperty.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.GetColumnSpan(Microsoft.UI.Xaml.FrameworkElement)
// Forced skipping of method Microsoft.UI.Xaml.Controls.Grid.SetColumnSpan(Microsoft.UI.Xaml.FrameworkElement, int)
}
}
| Grid |
csharp | dotnet__efcore | test/EFCore.Analyzers.Tests/StringInterpolationInRawQueriesAnalyzerTests.cs | {
"start": 2784,
"end": 3086
} | class ____
{
void M(MyDbContext db)
{
{{call}}"FooBar WHERE Id = 1");
}
}
""");
[Theory]
[MemberData(nameof(DoNotReportData))]
public Task Constant_string_with_parameters_do_not_report(string call)
=> Verify.VerifyAnalyzerAsync(
$$"""
{{MyDbContext}}
| C |
csharp | dotnet__aspire | tests/Aspire.Hosting.Tests/ExternalServiceTests.cs | {
"start": 379,
"end": 20547
} | public class ____(ITestOutputHelper testOutputHelper)
{
[Fact]
public void AddExternalServiceWithString()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
var externalService = builder.AddExternalService("nuget", "https://nuget.org/");
Assert.Equal("nuget", externalService.Resource.Name);
Assert.Equal("https://nuget.org/", externalService.Resource.Uri?.ToString());
Assert.Null(externalService.Resource.UrlParameter);
}
[Fact]
public void AddExternalServiceWithUri()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
var uri = new Uri("https://nuget.org/");
var externalService = builder.AddExternalService("nuget", uri);
Assert.Equal("nuget", externalService.Resource.Name);
Assert.Equal("https://nuget.org/", externalService.Resource.Uri?.ToString());
Assert.Null(externalService.Resource.UrlParameter);
}
[Fact]
public void AddExternalServiceWithParameter()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
var urlParam = builder.AddParameter("nuget-url");
var externalService = builder.AddExternalService("nuget", urlParam);
Assert.Equal("nuget", externalService.Resource.Name);
Assert.Null(externalService.Resource.Uri);
Assert.NotNull(externalService.Resource.UrlParameter);
Assert.Equal("nuget-url", externalService.Resource.UrlParameter.Name);
}
[Theory]
[InlineData("not-a-url")]
[InlineData("")]
[InlineData("https://example.com/path")]
[InlineData("https://example.com/path?query=value")]
[InlineData("https://example.com#fragment")]
public void AddExternalServiceThrowsWithInvalidUrl(string invalidUrl)
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
var ex = Assert.Throws<ArgumentException>(() => builder.AddExternalService("nuget", invalidUrl));
Assert.Contains("invalid", ex.Message, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void AddExternalServiceThrowsWithRelativeUri()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
var relativeUri = new Uri("/relative", UriKind.Relative);
var ex = Assert.Throws<ArgumentException>(() => builder.AddExternalService("nuget", relativeUri));
Assert.Contains("absolute", ex.Message, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public void AddExternalServiceThrowsWithUriWithPath()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
var uriWithPath = new Uri("https://api.example.com/api/v1");
var ex = Assert.Throws<ArgumentException>(() => builder.AddExternalService("nuget", uriWithPath));
Assert.Contains("absolute path must be \"/\"", ex.Message);
}
[Theory]
[InlineData("https://nuget.org/")]
[InlineData("http://localhost/")]
[InlineData("https://example.com:8080/")]
public void AddExternalServiceAcceptsValidUrls(string validUrl)
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
var externalService = builder.AddExternalService("nuget", validUrl);
Assert.Equal("nuget", externalService.Resource.Name);
Assert.Equal(validUrl, externalService.Resource.Uri?.ToString());
}
[Fact]
public async Task ExternalServiceWithHttpsCanBeReferenced()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
var externalService = builder.AddExternalService("nuget", "https://nuget.org/");
var project = builder.AddProject<TestProject>("project")
.WithReference(externalService);
// Call environment variable callbacks.
var config = await EnvironmentVariableEvaluator.GetEnvironmentVariablesAsync(project.Resource, DistributedApplicationOperation.Run, TestServiceProvider.Instance).DefaultTimeout();
// Check that service discovery information was injected with https scheme
Assert.Contains(config, kvp => kvp.Key == "services__nuget__https__0" && kvp.Value == "https://nuget.org/");
Assert.Contains(config, kvp => kvp.Key == "NUGET" && kvp.Value == "https://nuget.org/");
}
[Fact]
public async Task ExternalServiceWithHttpCanBeReferenced()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
var externalService = builder.AddExternalService("nuget", "http://nuget.org/");
var project = builder.AddProject<TestProject>("project")
.WithReference(externalService);
// Call environment variable callbacks.
var config = await EnvironmentVariableEvaluator.GetEnvironmentVariablesAsync(project.Resource, DistributedApplicationOperation.Run, TestServiceProvider.Instance).DefaultTimeout();
// Check that service discovery information was injected with http scheme
Assert.Contains(config, kvp => kvp.Key == "services__nuget__http__0" && kvp.Value == "http://nuget.org/");
Assert.Contains(config, kvp => kvp.Key == "NUGET" && kvp.Value == "http://nuget.org/");
}
[Fact]
public async Task ExternalServiceWithParameterCanBeReferencedInRunMode()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
builder.Configuration["Parameters:nuget-url"] = "https://nuget.org/";
var urlParam = builder.AddParameter("nuget-url");
var externalService = builder.AddExternalService("nuget", urlParam);
var project = builder.AddProject<TestProject>("project")
.WithReference(externalService);
// Call environment variable callbacks.
var config = await EnvironmentVariableEvaluator.GetEnvironmentVariablesAsync(project.Resource, DistributedApplicationOperation.Run, TestServiceProvider.Instance).DefaultTimeout();
// Check that service discovery information was injected with the correct scheme from parameter value
Assert.Contains(config, kvp => kvp.Key == "services__nuget__https__0" && kvp.Value == "https://nuget.org/");
Assert.Contains(config, kvp => kvp.Key == "NUGET_HTTPS" && kvp.Value == "https://nuget.org/");
}
[Fact]
public async Task ExternalServiceWithParameterCanBeReferencedInPublishMode()
{
using var builder = TestDistributedApplicationBuilder.Create(DistributedApplicationOperation.Publish).WithTestAndResourceLogging(testOutputHelper);
var urlParam = builder.AddParameter("nuget-url");
var externalService = builder.AddExternalService("nuget", urlParam);
var project = builder.AddProject<TestProject>("project")
.WithReference(externalService);
var app = builder.Build();
// Call environment variable callbacks.
var config = await EnvironmentVariableEvaluator.GetEnvironmentVariablesAsync(project.Resource, DistributedApplicationOperation.Publish, app.Services).DefaultTimeout();
// In publish mode, scheme defaults to "default" since we can't validate the parameter value
Assert.Contains(config, kvp => kvp.Key == "services__nuget__default__0");
var urlValue = config["services__nuget__default__0"];
Assert.Equal(urlParam.Resource.ValueExpression, urlValue);
Assert.Contains(config, kvp => kvp.Key == "NUGET" && kvp.Value == urlValue);
}
[Fact]
public async Task ExternalServiceWithInvalidParameterThrowsInRunMode()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
builder.Configuration["Parameters:nuget-url"] = "invalid-url";
var urlParam = builder.AddParameter("nuget-url");
var externalService = builder.AddExternalService("nuget", urlParam);
var project = builder.AddProject<TestProject>("project")
.WithReference(externalService);
// Should throw when trying to evaluate environment variables with invalid parameter value
await Assert.ThrowsAsync<DistributedApplicationException>(async () =>
{
await EnvironmentVariableEvaluator.GetEnvironmentVariablesAsync(project.Resource, DistributedApplicationOperation.Run, TestServiceProvider.Instance).DefaultTimeout();
});
}
[Fact]
public void ExternalServiceWithHttpHealthCheck()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
var externalService = builder.AddExternalService("nuget", "https://nuget.org/")
.WithHttpHealthCheck();
// Build the app to register health checks
using var app = builder.Build();
// Verify that health check was registered
Assert.True(externalService.Resource.TryGetAnnotationsOfType<HealthCheckAnnotation>(out var healthCheckAnnotations));
Assert.NotNull(healthCheckAnnotations.FirstOrDefault(hc => hc.Key.StartsWith($"{externalService.Resource.Name}_external")));
}
[Fact]
public void ExternalServiceWithHttpHealthCheckCustomPath()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
var externalService = builder.AddExternalService("nuget", "https://nuget.org/")
.WithHttpHealthCheck("/health", 200);
// Build the app to register health checks
using var app = builder.Build();
// Verify that health check was registered
Assert.True(externalService.Resource.TryGetAnnotationsOfType<HealthCheckAnnotation>(out var healthCheckAnnotations));
Assert.NotNull(healthCheckAnnotations.FirstOrDefault(hc => hc.Key.StartsWith($"{externalService.Resource.Name}_external")));
}
[Fact]
public void ExternalServiceWithHttpHealthCheckInvalidPath()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
var externalService = builder.AddExternalService("nuget", "https://nuget.org/");
// Should throw with invalid relative path
Assert.Throws<ArgumentException>(() => externalService.WithHttpHealthCheck(path: "https://invalid.com/path"));
}
[Fact]
public void ExternalServiceResourceHasExpectedInitialState()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
var externalService = builder.AddExternalService("nuget", "https://nuget.org/");
// Verify the resource has the expected annotations
Assert.True(externalService.Resource.TryGetAnnotationsOfType<ResourceSnapshotAnnotation>(out var snapshotAnnotations));
var snapshot = Assert.Single(snapshotAnnotations);
Assert.Equal("ExternalService", snapshot.InitialSnapshot.ResourceType);
}
[Fact]
public void ExternalServiceResourceIsExcludedFromPublishingManifest()
{
//ManifestPublishingCallbackAnnotation
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
var externalService = builder.AddExternalService("nuget", "https://nuget.org/");
// Verify the resource has the expected annotations
Assert.True(externalService.Resource.TryGetAnnotationsOfType<ManifestPublishingCallbackAnnotation>(out var manifestAnnotations));
var annotation = Assert.Single(manifestAnnotations);
Assert.Equal(ManifestPublishingCallbackAnnotation.Ignore, annotation);
}
[Fact]
public void ExternalServiceUrlValidationHelper()
{
// Test the static validation helper method
Assert.True(ExternalServiceResource.UrlIsValidForExternalService("https://nuget.org/", out var uri, out var message));
Assert.Equal("https://nuget.org/", uri!.ToString());
Assert.Null(message);
Assert.False(ExternalServiceResource.UrlIsValidForExternalService("invalid-url", out var invalidUri, out var invalidMessage));
Assert.Null(invalidUri);
Assert.NotNull(invalidMessage);
Assert.Contains("absolute URI", invalidMessage);
Assert.False(ExternalServiceResource.UrlIsValidForExternalService("https://nuget.org/path", out var pathUri, out var pathMessage));
Assert.Null(pathUri);
Assert.NotNull(pathMessage);
Assert.Contains("absolute path must be \"/\"", pathMessage);
}
[Fact]
public async Task ExternalServiceWithParameterGetValueAsyncErrorMarksAsFailedToStart()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
// Create a parameter with a broken value callback
var urlParam = builder.AddParameter("failing-url", () => throw new InvalidOperationException("Parameter resolution failed"));
var externalService = builder.AddExternalService("external", urlParam);
using var app = builder.Build();
// Start the app to trigger InitializeResourceEvent
var appStartTask = app.StartAsync();
// Wait for the resource to be marked as FailedToStart
var resourceEvent = await app.ResourceNotifications.WaitForResourceAsync(
externalService.Resource.Name,
e => e.Snapshot.State?.Text == KnownResourceStates.FailedToStart
).DefaultTimeout();
// Verify the resource is in the correct state
Assert.Equal(KnownResourceStates.FailedToStart, resourceEvent.Snapshot.State?.Text);
await app.StopAsync();
await appStartTask; // Ensure start completes
}
[Fact]
public async Task ExternalServiceWithParameterInvalidUrlMarksAsFailedToStart()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
// Create a parameter that returns an invalid URL
var urlParam = builder.AddParameter("invalid-url", () => "invalid-url-not-absolute");
var externalService = builder.AddExternalService("external", urlParam);
using var app = builder.Build();
// Start the app to trigger InitializeResourceEvent
var appStartTask = app.StartAsync();
// Wait for the resource to be marked as FailedToStart
var resourceEvent = await app.ResourceNotifications.WaitForResourceAsync(
externalService.Resource.Name,
e => e.Snapshot.State?.Text == KnownResourceStates.FailedToStart
).DefaultTimeout();
// Verify the resource is in the correct state
Assert.Equal(KnownResourceStates.FailedToStart, resourceEvent.Snapshot.State?.Text);
await app.StopAsync();
await appStartTask; // Ensure start completes
}
[Fact]
public async Task ExternalServiceWithValidParameterMarksAsRunning()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
// Create a parameter that returns a valid URL
var urlParam = builder.AddParameter("valid-url", () => "https://example.com/");
var externalService = builder.AddExternalService("external", urlParam);
using var app = builder.Build();
// Start the app to trigger InitializeResourceEvent
var appStartTask = app.StartAsync();
// Wait for the resource to be marked as Running
var resourceEvent = await app.ResourceNotifications.WaitForResourceAsync(
externalService.Resource.Name,
e => e.Snapshot.State?.Text == KnownResourceStates.Running
).DefaultTimeout();
// Verify the resource is in the correct state
Assert.Equal(KnownResourceStates.Running, resourceEvent.Snapshot.State?.Text);
await app.StopAsync();
await appStartTask; // Ensure start completes
}
[Fact]
public void ExternalServiceWithParameterHttpHealthCheckRegistersCustomHealthCheck()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
var urlParam = builder.AddParameter("external-url");
var externalService = builder.AddExternalService("external", urlParam)
.WithHttpHealthCheck();
// Build the app to register health checks
using var app = builder.Build();
// Verify that health check was registered
Assert.True(externalService.Resource.TryGetAnnotationsOfType<HealthCheckAnnotation>(out var healthCheckAnnotations));
var healthCheckAnnotation = healthCheckAnnotations.FirstOrDefault(hc => hc.Key.StartsWith($"{externalService.Resource.Name}_external"));
Assert.NotNull(healthCheckAnnotation);
// Verify that the custom health check is registered in DI
var healthCheckService = app.Services.GetService<HealthCheckService>();
Assert.NotNull(healthCheckService);
}
[Fact]
public void ExternalServiceWithStaticUrlHttpHealthCheckUsesUrlGroup()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
var externalService = builder.AddExternalService("external", "https://example.com/")
.WithHttpHealthCheck();
// Build the app to register health checks
using var app = builder.Build();
// Verify that health check was registered
Assert.True(externalService.Resource.TryGetAnnotationsOfType<HealthCheckAnnotation>(out var healthCheckAnnotations));
var healthCheckAnnotation = healthCheckAnnotations.FirstOrDefault(hc => hc.Key.StartsWith($"{externalService.Resource.Name}_external"));
Assert.NotNull(healthCheckAnnotation);
// Verify that health check service is available
var healthCheckService = app.Services.GetService<HealthCheckService>();
Assert.NotNull(healthCheckService);
}
[Fact]
public async Task ExternalServiceWithParameterHttpHealthCheckResolvesUrlAsync()
{
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);
builder.Configuration["Parameters:external-url"] = "https://example.com/";
var urlParam = builder.AddParameter("external-url");
var externalService = builder.AddExternalService("external", urlParam)
.WithHttpHealthCheck("/status/200");
using var app = builder.Build();
// Get the health check service and run health checks
var healthCheckService = app.Services.GetRequiredService<HealthCheckService>();
// Find our specific health check key
Assert.True(externalService.Resource.TryGetAnnotationsOfType<HealthCheckAnnotation>(out var healthCheckAnnotations));
var healthCheckKey = healthCheckAnnotations.First(hc => hc.Key.StartsWith($"{externalService.Resource.Name}_external")).Key;
// Run the health check
var result = await healthCheckService.CheckHealthAsync(
registration => registration.Name == healthCheckKey,
CancellationToken.None).DefaultTimeout();
// The result should be healthy since we're using httpbin.org which should be accessible
// However, in a test environment this might fail due to network issues, so we just check that it ran
Assert.Contains(healthCheckKey, result.Entries.Keys);
}
[Fact]
public async Task ExternalServiceWithParameterPublishManifest()
{
using var builder = TestDistributedApplicationBuilder.Create(DistributedApplicationOperation.Publish).WithTestAndResourceLogging(testOutputHelper);
var urlParam = builder.AddParameter("external-url");
var externalService = builder.AddExternalService("external", urlParam);
var project = builder.AddProject<TestProject>("project")
.WithReference(externalService)
.WithEnvironment("EXTERNAL_SERVICE", externalService);
var manifest = await ManifestUtils.GetManifest(project.Resource);
await Verify(manifest.ToString(), extension: "json");
}
| ExternalServiceTests |
csharp | cake-build__cake | src/Cake.Core/Scripting/Processors/Loading/ILoadDirectiveProvider.cs | {
"start": 380,
"end": 1206
} | public interface ____
{
/// <summary>
/// Indicates whether or not this provider can load the specified <see cref="LoadReference"/>.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="reference">The reference to the code to load.</param>
/// <returns><c>true</c> if the provider can load the reference; otherwise <c>false</c>.</returns>
bool CanLoad(IScriptAnalyzerContext context, LoadReference reference);
/// <summary>
/// Loads the specified <see cref="LoadReference"/>.
/// </summary>
/// <param name="context">The context.</param>
/// <param name="reference">The reference to load.</param>
void Load(IScriptAnalyzerContext context, LoadReference reference);
}
} | ILoadDirectiveProvider |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ModelBuilding101ManyToManyTestBase.cs | {
"start": 30088,
"end": 30890
} | public class ____ : Context0
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
=> modelBuilder.Entity<Person>()
.HasMany(e => e.Children)
.WithMany(e => e.Parents)
.UsingEntity(
"PersonPerson",
l => l.HasOne(typeof(Person)).WithMany().HasForeignKey("ChildrenId").HasPrincipalKey(nameof(Person.Id)),
r => r.HasOne(typeof(Person)).WithMany().HasForeignKey("ParentsId").HasPrincipalKey(nameof(Person.Id)),
j => j.HasKey("ChildrenId", "ParentsId"));
}
}
[ConditionalFact]
public virtual void SelfReferencingUnidirectionalManyToManyTest()
=> Model101Test();
| Context2 |
csharp | microsoft__FASTER | cs/test/GenericLogCompactionTests.cs | {
"start": 12037,
"end": 12222
} | private class ____ : ICompactionFunctions<MyKey, MyValue>
{
public bool IsDeleted(ref MyKey key, ref MyValue value) => false;
}
| Test2CompactionFunctions |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Mutable/test/Types.Mutable.Tests/ToSyntaxNodeTests.cs | {
"start": 3461,
"end": 3880
} | enum ____ @example {
A @example
}
""";
// act
var schema = SchemaParser.Parse(Encoding.UTF8.GetBytes(sdl));
var syntaxNode = ((MutableEnumTypeDefinition)schema.Types["Example"]).ToSyntaxNode();
// assert
Assert.IsType<EnumTypeDefinitionNode>(syntaxNode);
syntaxNode.ToString().MatchInlineSnapshot(
"""
| Example |
csharp | dotnet__maui | src/Controls/tests/Xaml.UnitTests/Issues/BPNotResolvedOnSubClass.xaml.cs | {
"start": 720,
"end": 1131
} | class ____
{
[Test]
public void CorrectlyResolveBPOnSubClasses([Values] XamlInflator inflator)
{
var layout = new BPNotResolvedOnSubClass(inflator);
var style = (Style)layout.Resources["Microsoft.Maui.Controls.Button"];
Assert.NotNull(style);
var button = new Button();
button.Style = style;
Assert.AreEqual(Color.FromArgb("#dddddd"), button.GetValue(ShadowColorProperty));
}
}
}
| Tests |
csharp | dotnet__maui | src/Compatibility/Core/src/WPF/Microsoft.Windows.Shell/Standard/StreamHelper.cs | {
"start": 2018,
"end": 5141
} | class ____ to deal with the IDisposable pattern.
// Overridden implementations aren't called, but Close is as part of the Dispose call.
public override void Close()
{
if (null != _source)
{
#if FEATURE_MUTABLE_COM_STREAMS
Flush();
#endif
Utility.SafeRelease(ref _source);
}
}
public override bool CanRead
{
get
{
// For the context of this class, this should be true...
return true;
}
}
public override bool CanSeek
{
get
{
// This should be true...
return true;
}
}
public override bool CanWrite
{
get
{
#if FEATURE_MUTABLE_COM_STREAMS
// Really don't know that this is true...
return true;
#endif
return false;
}
}
public override void Flush()
{
#if FEATURE_MUTABLE_COM_STREAMS
_Validate();
// Don't have enough context of the underlying object to reliably do anything here.
try
{
_source.Commit(STGC_DEFAULT);
}
catch { }
#endif
}
public override long Length
{
get
{
_Validate();
STATSTG statstg;
_source.Stat(out statstg, STATFLAG_NONAME);
return statstg.cbSize;
}
}
public override long Position
{
get { return Seek(0, SeekOrigin.Current); }
set { Seek(value, SeekOrigin.Begin); }
}
public override int Read(byte[] buffer, int offset, int count)
{
_Validate();
IntPtr pcbRead = IntPtr.Zero;
try
{
pcbRead = Marshal.AllocHGlobal(sizeof(Int32));
// PERFORMANCE NOTE: This buffer doesn't need to be allocated if offset == 0
var tempBuffer = new byte[count];
_source.Read(tempBuffer, count, pcbRead);
Array.Copy(tempBuffer, 0, buffer, offset, Marshal.ReadInt32(pcbRead));
return Marshal.ReadInt32(pcbRead);
}
finally
{
Utility.SafeFreeHGlobal(ref pcbRead);
}
}
public override long Seek(long offset, SeekOrigin origin)
{
_Validate();
IntPtr plibNewPosition = IntPtr.Zero;
try
{
plibNewPosition = Marshal.AllocHGlobal(sizeof(Int64));
_source.Seek(offset, (int)origin, plibNewPosition);
return Marshal.ReadInt64(plibNewPosition);
}
finally
{
Utility.SafeFreeHGlobal(ref plibNewPosition);
}
}
public override void SetLength(long value)
{
throw new NotSupportedException();
#if FEATURE_MUTABLE_COM_STREAMS
_Validate();
_source.SetSize(value);
#endif
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
#if FEATURE_MUTABLE_COM_STREAMS
_Validate();
// PERFORMANCE NOTE: This buffer doesn't need to be allocated if offset == 0
byte[] tempBuffer = new byte[buffer.Length - offset];
Array.Copy(buffer, offset, tempBuffer, 0, tempBuffer.Length);
_source.Write(tempBuffer, tempBuffer.Length, IntPtr.Zero);
#endif
}
#endregion
}
// All these methods return void. Does the standard marshaller convert them to HRESULTs?
/// <summary>
/// Wraps a managed stream instance into an | seems |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.Core/src/ApplicationModels/ControllerModel.cs | {
"start": 482,
"end": 5818
} | public class ____ : ICommonModel, IFilterModel, IApiExplorerModel
{
/// <summary>
/// Initializes a new instance of <see cref="ControllerModel"/>.
/// </summary>
/// <param name="controllerType">The type of the controller.</param>
/// <param name="attributes">The attributes.</param>
public ControllerModel(
TypeInfo controllerType,
IReadOnlyList<object> attributes)
{
ArgumentNullException.ThrowIfNull(controllerType);
ArgumentNullException.ThrowIfNull(attributes);
ControllerType = controllerType;
Actions = new List<ActionModel>();
ApiExplorer = new ApiExplorerModel();
Attributes = new List<object>(attributes);
ControllerProperties = new List<PropertyModel>();
Filters = new List<IFilterMetadata>();
Properties = new Dictionary<object, object?>();
RouteValues = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
Selectors = new List<SelectorModel>();
}
/// <summary>
/// Initializes a new instance of <see cref="ControllerModel"/>.
/// </summary>
/// <param name="other">The other controller model.</param>
public ControllerModel(ControllerModel other)
{
ArgumentNullException.ThrowIfNull(other);
ControllerName = other.ControllerName;
ControllerType = other.ControllerType;
// Still part of the same application
Application = other.Application;
// These are just metadata, safe to create new collections
Attributes = new List<object>(other.Attributes);
Filters = new List<IFilterMetadata>(other.Filters);
RouteValues = new Dictionary<string, string?>(other.RouteValues, StringComparer.OrdinalIgnoreCase);
Properties = new Dictionary<object, object?>(other.Properties);
// Make a deep copy of other 'model' types.
Actions = new List<ActionModel>(other.Actions.Select(a => new ActionModel(a) { Controller = this }));
ApiExplorer = new ApiExplorerModel(other.ApiExplorer);
ControllerProperties =
new List<PropertyModel>(other.ControllerProperties.Select(p => new PropertyModel(p) { Controller = this }));
Selectors = new List<SelectorModel>(other.Selectors.Select(s => new SelectorModel(s)));
}
/// <summary>
/// The actions on this controller.
/// </summary>
public IList<ActionModel> Actions { get; }
/// <summary>
/// Gets or sets the <see cref="ApiExplorerModel"/> for this controller.
/// </summary>
/// <remarks>
/// <see cref="ControllerModel.ApiExplorer"/> allows configuration of settings for ApiExplorer
/// which apply to all actions in the controller unless overridden by <see cref="ActionModel.ApiExplorer"/>.
///
/// Settings applied by <see cref="ControllerModel.ApiExplorer"/> override settings from
/// <see cref="ApplicationModel.ApiExplorer"/>.
/// </remarks>
public ApiExplorerModel ApiExplorer { get; set; }
/// <summary>
/// Gets or sets the <see cref="ApplicationModel"/> of this controller.
/// </summary>
public ApplicationModel? Application { get; set; }
/// <summary>
/// The attributes of this controller.
/// </summary>
public IReadOnlyList<object> Attributes { get; }
MemberInfo ICommonModel.MemberInfo => ControllerType;
string ICommonModel.Name => ControllerName;
/// <summary>
/// Gets or sets the name of this controller.
/// </summary>
public string ControllerName { get; set; } = default!;
/// <summary>
/// The type of this controller.
/// </summary>
public TypeInfo ControllerType { get; }
/// <summary>
/// The properties of this controller.
/// </summary>
public IList<PropertyModel> ControllerProperties { get; }
/// <summary>
/// The filter metadata of this controller.
/// </summary>
public IList<IFilterMetadata> Filters { get; }
/// <summary>
/// Gets a collection of route values that must be present in the
/// <see cref="RouteData.Values"/> for the corresponding action to be selected.
/// </summary>
/// <remarks>
/// Entries in <see cref="RouteValues"/> can be overridden by entries in
/// <see cref="ActionModel.RouteValues"/>.
/// </remarks>
public IDictionary<string, string?> RouteValues { get; }
/// <summary>
/// Gets a set of properties associated with the controller.
/// These properties will be copied to <see cref="Abstractions.ActionDescriptor.Properties"/>.
/// </summary>
/// <remarks>
/// Entries will take precedence over entries with the same key
/// in <see cref="ApplicationModel.Properties"/>.
/// </remarks>
public IDictionary<object, object?> Properties { get; }
/// <summary>
/// The selector models of this controller.
/// </summary>
public IList<SelectorModel> Selectors { get; }
/// <summary>
/// The DisplayName of this controller.
/// </summary>
public string DisplayName
{
get
{
var controllerType = TypeNameHelper.GetTypeDisplayName(ControllerType);
var controllerAssembly = ControllerType.Assembly.GetName().Name;
return $"{controllerType} ({controllerAssembly})";
}
}
}
| ControllerModel |
csharp | nunit__nunit | src/NUnitFramework/tests/Attributes/RangeAttributeTests.cs | {
"start": 365,
"end": 23087
} | public partial class ____
{
#region Shared specs
private static IEnumerable<Type> TestedParameterTypes() => new[]
{
typeof(sbyte),
typeof(byte),
typeof(short),
typeof(ushort),
typeof(int),
typeof(uint),
typeof(long),
typeof(ulong),
typeof(float),
typeof(double),
typeof(decimal)
};
// See XML docs for the ParamAttributeTypeConversions class.
private static readonly Type[] Int32RangeConvertibleToParameterTypes = { typeof(int), typeof(sbyte), typeof(byte), typeof(short), typeof(decimal), typeof(long), typeof(double) };
private static readonly Type[] UInt32RangeConvertibleToParameterTypes = { typeof(uint) };
private static readonly Type[] Int64RangeConvertibleToParameterTypes = { typeof(long) };
private static readonly Type[] UInt64RangeConvertibleToParameterTypes = { typeof(ulong) };
private static readonly Type[] SingleRangeConvertibleToParameterTypes = { typeof(float) };
private static readonly Type[] DoubleRangeConvertibleToParameterTypes = { typeof(double), typeof(decimal) };
#endregion
[Test]
public void MultipleAttributes()
{
Test test = TestBuilder.MakeParameterizedMethodSuite(typeof(RangeTestFixture), nameof(RangeTestFixture.MethodWithMultipleRanges));
var arguments = from testCase in test.Tests select testCase.Arguments[0];
Assert.That(arguments, Is.EquivalentTo(new[] { 1, 2, 3, 10, 11, 12 }));
}
#region Forward
public static IEnumerable<RangeWithExpectedConversions> ForwardRangeCases => new[]
{
new RangeWithExpectedConversions(new RangeAttribute(11, 15), Int32RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11u, 15u), UInt32RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11L, 15L), Int64RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11UL, 15UL), UInt64RangeConvertibleToParameterTypes)
};
[Test]
public static void ForwardRange(
[ValueSource(nameof(ForwardRangeCases))] RangeWithExpectedConversions rangeWithExpectedConversions,
[ValueSource(nameof(TestedParameterTypes))] Type parameterType)
{
rangeWithExpectedConversions.AssertCoercionErrorOrMatchingSequence(
parameterType, new[] { 11, 12, 13, 14, 15 });
}
#endregion
#region Backward
public static IEnumerable<RangeWithExpectedConversions> BackwardRangeCases => new[]
{
new RangeWithExpectedConversions(new RangeAttribute(15, 11), Int32RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(15L, 11L), Int64RangeConvertibleToParameterTypes)
};
[Test]
public static void BackwardRange(
[ValueSource(nameof(BackwardRangeCases))] RangeWithExpectedConversions rangeWithExpectedConversions,
[ValueSource(nameof(TestedParameterTypes))] Type parameterType)
{
rangeWithExpectedConversions.AssertCoercionErrorOrMatchingSequence(
parameterType, new[] { 15, 14, 13, 12, 11 });
}
[Test]
public static void BackwardRangeDisallowed_UInt32()
{
Assert.That(() => new RangeAttribute(15u, 11u), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void BackwardRangeDisallowed_UInt64()
{
Assert.That(() => new RangeAttribute(15UL, 11UL), Throws.InstanceOf<ArgumentException>());
}
#endregion
#region Degenerate
public static IEnumerable<RangeWithExpectedConversions> DegenerateRangeCases => new[]
{
new RangeWithExpectedConversions(new RangeAttribute(11, 11), Int32RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11u, 11u), UInt32RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11L, 11L), Int64RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11UL, 11UL), UInt64RangeConvertibleToParameterTypes)
};
[Test]
public static void DegenerateRange(
[ValueSource(nameof(DegenerateRangeCases))] RangeWithExpectedConversions rangeWithExpectedConversions,
[ValueSource(nameof(TestedParameterTypes))] Type parameterType)
{
rangeWithExpectedConversions.AssertCoercionErrorOrMatchingSequence(
parameterType, new[] { 11 });
}
public static IEnumerable<RangeWithExpectedConversions> DegeneratePositiveStepRangeCases => new[]
{
new RangeWithExpectedConversions(new RangeAttribute(11, 11, 2), Int32RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11u, 11u, 2u), UInt32RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11L, 11L, 2L), Int64RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11UL, 11UL, 2UL), UInt64RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11f, 11f, 2f), SingleRangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11d, 11d, 2d), DoubleRangeConvertibleToParameterTypes)
};
[Test]
public static void DegeneratePositiveStepRangeDisallowed_Int32(
[ValueSource(nameof(DegeneratePositiveStepRangeCases))] RangeWithExpectedConversions rangeWithExpectedConversions,
[ValueSource(nameof(TestedParameterTypes))] Type parameterType)
{
rangeWithExpectedConversions.AssertCoercionErrorOrMatchingSequence(
parameterType, new[] { 11 });
}
public static IEnumerable<RangeWithExpectedConversions> DegenerateNegativeStepRangeCases => new[]
{
new RangeWithExpectedConversions(new RangeAttribute(11, 11, -2), Int32RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11L, 11L, -2L), Int64RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11f, 11f, -2f), SingleRangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11d, 11d, -2d), DoubleRangeConvertibleToParameterTypes)
};
[Test]
public static void DegenerateNegativeStepRange(
[ValueSource(nameof(DegenerateNegativeStepRangeCases))] RangeWithExpectedConversions rangeWithExpectedConversions,
[ValueSource(nameof(TestedParameterTypes))] Type parameterType)
{
rangeWithExpectedConversions.AssertCoercionErrorOrMatchingSequence(
parameterType, new[] { 11 });
}
[Test]
public static void DegenerateZeroStepRangeDisallowed_Int32()
{
Assert.That(() => new RangeAttribute(11, 11, 0), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void DegenerateZeroStepRangeDisallowed_Int64()
{
Assert.That(() => new RangeAttribute(11L, 11L, 0L), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void DegenerateZeroStepRangeDisallowed_Single()
{
Assert.That(() => new RangeAttribute(11f, 11f, 0f), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void DegenerateZeroStepRangeDisallowed_Double()
{
Assert.That(() => new RangeAttribute(11d, 11d, 0d), Throws.InstanceOf<ArgumentException>());
}
#endregion
#region Forward step
public static IEnumerable<RangeWithExpectedConversions> ForwardStepRangeCases => new[]
{
new RangeWithExpectedConversions(new RangeAttribute(11, 15, 2), Int32RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11u, 15u, 2u), UInt32RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11L, 15L, 2L), Int64RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11UL, 15UL, 2UL), UInt64RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11f, 15f, 2f), SingleRangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(11d, 15d, 2d), DoubleRangeConvertibleToParameterTypes)
};
[Test]
public static void ForwardStepRange(
[ValueSource(nameof(ForwardStepRangeCases))] RangeWithExpectedConversions rangeWithExpectedConversions,
[ValueSource(nameof(TestedParameterTypes))] Type parameterType)
{
rangeWithExpectedConversions.AssertCoercionErrorOrMatchingSequence(
parameterType, new[] { 11, 13, 15 });
}
#endregion
#region Backward step
public static IEnumerable<RangeWithExpectedConversions> BackwardStepRangeCases => new[]
{
new RangeWithExpectedConversions(new RangeAttribute(15, 11, -2), Int32RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(15L, 11L, -2L), Int64RangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(15f, 11f, -2f), SingleRangeConvertibleToParameterTypes),
new RangeWithExpectedConversions(new RangeAttribute(15d, 11d, -2d), DoubleRangeConvertibleToParameterTypes)
};
[Test]
public static void BackwardStepRange(
[ValueSource(nameof(BackwardStepRangeCases))] RangeWithExpectedConversions rangeWithExpectedConversions,
[ValueSource(nameof(TestedParameterTypes))] Type parameterType)
{
rangeWithExpectedConversions.AssertCoercionErrorOrMatchingSequence(
parameterType, new[] { 15, 13, 11 });
}
#endregion
#region Zero step
[Test]
public static void ZeroStepRangeDisallowed_Int32()
{
Assert.That(() => new RangeAttribute(11, 15, 0), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void ZeroStepRangeDisallowed_UInt32()
{
Assert.That(() => new RangeAttribute(11u, 15u, 0u), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void ZeroStepRangeDisallowed_Int64()
{
Assert.That(() => new RangeAttribute(11L, 15L, 0L), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void ZeroStepRangeDisallowed_UInt64()
{
Assert.That(() => new RangeAttribute(11UL, 15UL, 0UL), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void ZeroStepRangeDisallowed_Single()
{
Assert.That(() => new RangeAttribute(11f, 15f, 0f), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void ZeroStepRangeDisallowed_Double()
{
Assert.That(() => new RangeAttribute(11d, 15d, 0d), Throws.InstanceOf<ArgumentException>());
}
#endregion
#region Opposing step
[Test]
public static void OpposingStepForwardRangeDisallowed_Int32()
{
Assert.That(() => new RangeAttribute(11, 15, -2), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void OpposingStepBackwardRangeDisallowed_Int32()
{
Assert.That(() => new RangeAttribute(15, 11, 2), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void OppositeStepForwardRangeDisallowed_Int64()
{
Assert.That(() => new RangeAttribute(11L, 15L, -2L), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void OpposingStepBackwardRangeDisallowed_Int64()
{
Assert.That(() => new RangeAttribute(15L, 11L, 2L), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void OppositeStepForwardRangeDisallowed_Single()
{
Assert.That(() => new RangeAttribute(11f, 15f, -2f), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void OpposingStepBackwardRangeDisallowed_Single()
{
Assert.That(() => new RangeAttribute(15f, 11f, 2f), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void OppositeForwardRangeDisallowed_Double()
{
Assert.That(() => new RangeAttribute(11d, 15d, -2d), Throws.InstanceOf<ArgumentException>());
}
[Test]
public static void OpposingStepBackwardRangeDisallowed_Double()
{
Assert.That(() => new RangeAttribute(15d, 11d, 2d), Throws.InstanceOf<ArgumentException>());
}
#endregion
// The smallest distance from MaxValue or MinValue which results in a different number,
// overcoming loss of precision.
// Calculated by hand by flipping bits. Used the round-trip format and double-checked.
private const float SingleExtremaEpsilon = 2.028241E+31f;
private const double DoubleExtremaEpsilon = 1.99584030953472E+292;
private const double LargestDoubleConvertibleToDecimal = 7.9228162514264329E+28;
private const double NextLargestDoubleConvertibleToLowerDecimal = 7.92281625142642E+28;
#region MaxValue
[Test]
public static void MaxValueRange_Byte()
{
Assert.That(
GetData(new RangeAttribute(byte.MaxValue - 2, byte.MaxValue), typeof(byte)),
Is.EqualTo(new[] { byte.MaxValue - 2, byte.MaxValue - 1, byte.MaxValue }));
}
[Test]
public static void MaxValueRange_SByte()
{
Assert.That(
GetData(new RangeAttribute(sbyte.MaxValue - 2, sbyte.MaxValue), typeof(sbyte)),
Is.EqualTo(new[] { sbyte.MaxValue - 2, sbyte.MaxValue - 1, sbyte.MaxValue }));
}
[Test]
public static void MaxValueRange_Int16()
{
Assert.That(
GetData(new RangeAttribute(short.MaxValue - 2, short.MaxValue), typeof(short)),
Is.EqualTo(new[] { short.MaxValue - 2, short.MaxValue - 1, short.MaxValue }));
}
[Test]
public static void MaxValueRange_Int32()
{
Assert.That(
GetData(new RangeAttribute(int.MaxValue - 2, int.MaxValue), typeof(int)),
Is.EqualTo(new[] { int.MaxValue - 2, int.MaxValue - 1, int.MaxValue }));
}
[Test]
public static void MaxValueRange_UInt32()
{
Assert.That(
GetData(new RangeAttribute(uint.MaxValue - 2, uint.MaxValue), typeof(uint)),
Is.EqualTo(new[] { uint.MaxValue - 2, uint.MaxValue - 1, uint.MaxValue }));
}
[Test]
public static void MaxValueRange_Int64()
{
Assert.That(
GetData(new RangeAttribute(long.MaxValue - 2, long.MaxValue), typeof(long)),
Is.EqualTo(new[] { long.MaxValue - 2, long.MaxValue - 1, long.MaxValue }));
}
[Test]
public static void MaxValueRange_UInt64()
{
Assert.That(
GetData(new RangeAttribute(ulong.MaxValue - 2, ulong.MaxValue), typeof(ulong)),
Is.EqualTo(new[] { ulong.MaxValue - 2, ulong.MaxValue - 1, ulong.MaxValue }));
}
[Test]
public static void MaxValueRange_Single()
{
Assert.That(
GetData(new RangeAttribute(float.MaxValue - SingleExtremaEpsilon * 2, float.MaxValue, SingleExtremaEpsilon), typeof(float)),
Is.EqualTo(new[] { float.MaxValue - SingleExtremaEpsilon * 2, float.MaxValue - SingleExtremaEpsilon, float.MaxValue }));
}
[Test]
public static void MaxValueRangeLosingPrecision_Single()
{
Assert.That(() => GetData(new RangeAttribute(float.MaxValue - SingleExtremaEpsilon, float.MaxValue, SingleExtremaEpsilon / 2), typeof(float)),
Throws.InstanceOf<ArithmeticException>());
}
[Test]
public static void MaxValueRange_Double()
{
Assert.That(
GetData(new RangeAttribute(double.MaxValue - DoubleExtremaEpsilon * 2, double.MaxValue, DoubleExtremaEpsilon), typeof(double)),
Is.EqualTo(new[] { double.MaxValue - DoubleExtremaEpsilon * 2, double.MaxValue - DoubleExtremaEpsilon, double.MaxValue }));
}
[Test]
public static void MaxValueRangeLosingPrecision_Double()
{
Assert.That(() => GetData(new RangeAttribute(double.MaxValue - DoubleExtremaEpsilon, double.MaxValue, DoubleExtremaEpsilon / 2), typeof(double)),
Throws.InstanceOf<ArithmeticException>());
}
[Test]
public static void MaxValueRange_Decimal()
{
const decimal fromDecimal = (decimal)NextLargestDoubleConvertibleToLowerDecimal;
const decimal toDecimal = (decimal)LargestDoubleConvertibleToDecimal;
const double step = (double)((toDecimal - fromDecimal) / 2);
Assert.That(
GetData(new RangeAttribute(NextLargestDoubleConvertibleToLowerDecimal, LargestDoubleConvertibleToDecimal, step), typeof(decimal)),
Is.EqualTo(new[]
{
fromDecimal,
fromDecimal + (decimal)step,
fromDecimal + (decimal)step * 2
}));
}
[Test]
public static void MaxValueRangeLosingPrecision_Decimal()
{
Assert.That(() => GetData(new RangeAttribute(NextLargestDoubleConvertibleToLowerDecimal, LargestDoubleConvertibleToDecimal, 0.1), typeof(decimal)),
Throws.InstanceOf<ArithmeticException>());
}
#endregion
#region MinValue
[Test]
public static void MinValueRange_Byte()
{
Assert.That(
GetData(new RangeAttribute(byte.MinValue + 2, byte.MinValue), typeof(byte)),
Is.EqualTo(new[] { byte.MinValue + 2, byte.MinValue + 1, byte.MinValue }));
}
[Test]
public static void MinValueRange_SByte()
{
Assert.That(
GetData(new RangeAttribute(sbyte.MinValue + 2, sbyte.MinValue), typeof(sbyte)),
Is.EqualTo(new[] { sbyte.MinValue + 2, sbyte.MinValue + 1, sbyte.MinValue }));
}
[Test]
public static void MinValueRange_Int16()
{
Assert.That(
GetData(new RangeAttribute(short.MinValue + 2, short.MinValue), typeof(short)),
Is.EqualTo(new[] { short.MinValue + 2, short.MinValue + 1, short.MinValue }));
}
[Test]
public static void MinValueRange_Int32()
{
Assert.That(
GetData(new RangeAttribute(int.MinValue + 2, int.MinValue), typeof(int)),
Is.EqualTo(new[] { int.MinValue + 2, int.MinValue + 1, int.MinValue }));
}
[Test]
public static void MinValueRange_Int64()
{
Assert.That(
GetData(new RangeAttribute(long.MinValue + 2, long.MinValue), typeof(long)),
Is.EqualTo(new[] { long.MinValue + 2, long.MinValue + 1, long.MinValue }));
}
[Test]
public static void MinValueRange_Single()
{
Assert.That(
GetData(new RangeAttribute(float.MinValue + SingleExtremaEpsilon * 2, float.MinValue, -SingleExtremaEpsilon), typeof(float)),
Is.EqualTo(new[] { float.MinValue + SingleExtremaEpsilon * 2, float.MinValue + SingleExtremaEpsilon, float.MinValue }));
}
[Test]
public static void MinValueRangeLosingPrecision_Single()
{
Assert.That(() => GetData(new RangeAttribute(float.MinValue + SingleExtremaEpsilon, float.MinValue, -SingleExtremaEpsilon / 2), typeof(float)),
Throws.InstanceOf<ArithmeticException>());
}
[Test]
public static void MinValueRange_Double()
{
Assert.That(
GetData(new RangeAttribute(double.MinValue + DoubleExtremaEpsilon * 2, double.MinValue, -DoubleExtremaEpsilon), typeof(double)),
Is.EqualTo(new[] { double.MinValue + DoubleExtremaEpsilon * 2, double.MinValue + DoubleExtremaEpsilon, double.MinValue }));
}
[Test]
public static void MinValueRangeLosingPrecision_Double()
{
Assert.That(() => GetData(new RangeAttribute(double.MinValue + DoubleExtremaEpsilon, double.MinValue, -DoubleExtremaEpsilon / 2), typeof(double)),
Throws.InstanceOf<ArithmeticException>());
}
[Test]
public static void MinValueRange_Decimal()
{
const decimal fromDecimal = -(decimal)NextLargestDoubleConvertibleToLowerDecimal;
const decimal toDecimal = -(decimal)LargestDoubleConvertibleToDecimal;
const double step = (double)((toDecimal - fromDecimal) / 2);
Assert.That(
GetData(new RangeAttribute(-NextLargestDoubleConvertibleToLowerDecimal, -LargestDoubleConvertibleToDecimal, step), typeof(decimal)),
Is.EqualTo(new[]
{
fromDecimal,
fromDecimal + (decimal)step,
fromDecimal + (decimal)step * 2
}));
}
[Test]
public static void MinValueRangeLosingPrecision_Decimal()
{
Assert.That(() => GetData(new RangeAttribute(-NextLargestDoubleConvertibleToLowerDecimal, -LargestDoubleConvertibleToDecimal, -0.1), typeof(decimal)),
Throws.InstanceOf<ArithmeticException>());
}
#endregion
private static object[] GetData(RangeAttribute rangeAttribute, Type parameterType)
{
return rangeAttribute.GetData(new StubParameterInfo(parameterType)).Cast<object>().ToArray();
}
| RangeAttributeTests |
csharp | Tyrrrz__DiscordChatExporter | DiscordChatExporter.Core/Markdown/Parsing/StringSegment.cs | {
"start": 111,
"end": 616
} | record ____ StringSegment(string Source, int StartIndex, int Length)
{
public int EndIndex => StartIndex + Length;
public StringSegment(string target)
: this(target, 0, target.Length) { }
public StringSegment Relocate(int newStartIndex, int newLength) =>
new(Source, newStartIndex, newLength);
public StringSegment Relocate(Capture capture) => Relocate(capture.Index, capture.Length);
public override string ToString() => Source.Substring(StartIndex, Length);
}
| struct |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Data/test/Data.Sorting.Tests/SortAttributeTests.cs | {
"start": 2560,
"end": 3045
} | public class ____
{
[UseSorting(Type = typeof(FooSortType))]
public IEnumerable<Foo> Foos { get; } = new[]
{
new Foo { Bar = "aa", Baz = 1, Qux = 1 },
new Foo { Bar = "ba", Baz = 1 },
new Foo { Bar = "ca", Baz = 2 },
new Foo { Bar = "ab", Baz = 2 },
new Foo { Bar = "ac", Baz = 2 },
new Foo { Bar = "ad", Baz = 2 },
new Foo { Bar = null!, Baz = 0 }
};
}
| Query2 |
csharp | DuendeSoftware__IdentityServer | identity-server/src/Storage/Models/PushedAuthorizationRequest.cs | {
"start": 244,
"end": 1349
} | public class ____
{
/// <summary>
/// The hash of the identifier within this pushed request's request_uri
/// value. Request URIs that IdentityServer produces take the form
/// urn:ietf:params:oauth:request_uri:{ReferenceValue}.
/// </summary>
public string ReferenceValueHash { get; set; }
/// <summary>
/// The UTC time at which this pushed request will expire. The Pushed
/// request will be used throughout the authentication process, beginning
/// when it is passed to the authorization endpoint by the client, and then
/// subsequently after user interaction, such as login and/or consent occur.
/// If the expiration time is exceeded before a response to the client can
/// be produced, IdentityServer will raise an error, and the user will be
/// redirected to the IdentityServer error page.
/// </summary>
public DateTime ExpiresAtUtc { get; set; }
/// <summary>
/// The data protected content of the pushed authorization request.
/// </summary>
public string Parameters { get; set; }
}
| PushedAuthorizationRequest |
csharp | microsoft__garnet | libs/storage/Tsavorite/cs/test/StateMachineDriverTests.cs | {
"start": 13185,
"end": 16575
} | public class ____ : StateMachineDriverTestsBase
{
[SetUp]
public void Setup() => BaseSetup();
[TearDown]
public void TearDown() => BaseTearDown();
protected override void OperationThread(int thread_id, bool useTimingFuzzing, TsavoriteKV<long, long, LongStoreFunctions, LongAllocator> store)
{
using var s = store.NewSession<long, long, Empty, SumFunctions>(new SumFunctions(thread_id, useTimingFuzzing));
var lc = s.LockableContext;
var r = new Random(thread_id);
ClassicAssert.IsTrue(numKeys > 1);
long key1 = 0, key2 = 0;
long input = 1;
var v1count = new long[numKeys];
var v2count = new long[numKeys];
while (!opsDone)
{
// Generate input for transaction
key1 = r.Next(numKeys);
do
{
key2 = r.Next(numKeys);
} while (key2 == key1);
var exclusiveVec = new FixedLengthLockableKeyStruct<long>[] {
new(key1, LockType.Exclusive, lc),
new(key2, LockType.Exclusive, lc)
};
var txnVersion = store.stateMachineDriver.AcquireTransactionVersion();
// Start transaction, session does not acquire version in this call
lc.BeginLockable();
// Lock keys, session acquires version in this call
lc.Lock<FixedLengthLockableKeyStruct<long>>(exclusiveVec);
txnVersion = store.stateMachineDriver.VerifyTransactionVersion(txnVersion);
lc.LocksAcquired(txnVersion);
// Run transaction
_ = lc.RMW(ref key1, ref input);
_ = lc.RMW(ref key2, ref input);
// Unlock keys
lc.Unlock<FixedLengthLockableKeyStruct<long>>(exclusiveVec);
// End transaction
lc.EndLockable();
store.stateMachineDriver.EndTransaction(txnVersion);
// Update expected counts for the old and new version of store
if (txnVersion == currentIteration + 1)
{
v1count[key1]++;
v1count[key2]++;
}
v2count[key1]++;
v2count[key2]++;
}
// Update the global expected counts
for (int i = 0; i < numKeys; i++)
{
_ = Interlocked.Add(ref expectedV1Count[i], v1count[i]);
_ = Interlocked.Add(ref expectedV2Count[i], v2count[i]);
}
}
[Test]
public async ValueTask CheckpointVersionSwitchTxnTest(
[Values(CheckpointType.Snapshot, CheckpointType.FoldOver)] CheckpointType checkpointType,
[Values(1L << 13, 1L << 16)] long indexSize,
[Values] bool useTimingFuzzing)
=> await DoCheckpointVersionSwitchEquivalenceCheck(checkpointType, indexSize, useTimingFuzzing);
[Test]
public async ValueTask GrowIndexVersionSwitchTxnTest(
[Values(1L << 13, 1L << 16)] long indexSize,
[Values] bool useTimingFuzzing)
=> await DoGrowIndexVersionSwitchEquivalenceCheck(indexSize, useTimingFuzzing);
}
} | CheckpointVersionSwitchTxn |
csharp | fluentassertions__fluentassertions | Src/FluentAssertions/Equivalency/Steps/EnumerableEquivalencyValidatorExtensions.cs | {
"start": 130,
"end": 2372
} | internal static class ____
{
public static Continuation AssertEitherCollectionIsNotEmpty<T>(this AssertionChain assertionChain,
ICollection<object> subject,
ICollection<T> expectation)
{
return assertionChain
.WithExpectation("Expected {context:subject} to be a collection with {0} item(s){reason}", expectation.Count,
chain => chain
.ForCondition(subject.Count > 0 || expectation.Count == 0)
.FailWith(", but found an empty collection.")
.Then
.ForCondition(subject.Count == 0 || expectation.Count > 0)
.FailWith($", but {{0}}{Environment.NewLine}contains {{1}} item(s).",
subject,
subject.Count));
}
public static Continuation AssertCollectionHasEnoughItems<T>(this AssertionChain assertionChain, ICollection<object> subject,
ICollection<T> expectation)
{
return assertionChain
.WithExpectation("Expected {context:subject} to be a collection with {0} item(s){reason}", expectation.Count,
chain => chain
.ForCondition(subject.Count >= expectation.Count)
.FailWith($", but {{0}}{Environment.NewLine}contains {{1}} item(s) less than{Environment.NewLine}{{2}}.",
subject,
expectation.Count - subject.Count,
expectation));
}
public static Continuation AssertCollectionHasNotTooManyItems<T>(this AssertionChain assertionChain,
ICollection<object> subject,
ICollection<T> expectation)
{
return assertionChain
.WithExpectation("Expected {context:subject} to be a collection with {0} item(s){reason}", expectation.Count,
chain => chain
.ForCondition(subject.Count <= expectation.Count)
.FailWith($", but {{0}}{Environment.NewLine}contains {{1}} item(s) more than{Environment.NewLine}{{2}}.",
subject,
subject.Count - expectation.Count,
expectation));
}
}
| EnumerableEquivalencyValidatorExtensions |
csharp | grandnode__grandnode2 | src/Core/Grand.Domain/Customers/CustomerProductPrice.cs | {
"start": 36,
"end": 209
} | public class ____ : BaseEntity
{
public string CustomerId { get; set; }
public string ProductId { get; set; }
public double Price { get; set; }
} | CustomerProductPrice |
csharp | dotnet__maui | src/Compatibility/Core/src/iOS/Renderers/DatePickerRenderer.cs | {
"start": 396,
"end": 869
} | internal class ____ : UITextField
{
public NoCaretField() : base(new RectangleF())
{
SpellCheckingType = UITextSpellCheckingType.No;
AutocorrectionType = UITextAutocorrectionType.No;
AutocapitalizationType = UITextAutocapitalizationType.None;
}
public override RectangleF GetCaretRectForPosition(UITextPosition position)
{
return new RectangleF();
}
}
[System.Obsolete(Compatibility.Hosting.MauiAppBuilderExtensions.UseMapperInstead)]
| NoCaretField |
csharp | abpframework__abp | modules/setting-management/src/Volo.Abp.SettingManagement.Web/Pages/SettingManagement/Components/TimeZoneSettingGroup/TimeZoneSettingGroupViewComponent.cs | {
"start": 194,
"end": 622
} | public class ____ : AbpViewComponent
{
public TimeZoneSettingGroupViewComponent(ITimeZoneSettingsAppService timeZoneSettingsAppService)
{
ObjectMapperContext = typeof(AbpSettingManagementWebModule);
}
public virtual async Task<IViewComponentResult> InvokeAsync()
{
return View("~/Pages/SettingManagement/Components/TimeZoneSettingGroup/Default.cshtml");
}
}
| TimeZoneSettingGroupViewComponent |
csharp | MassTransit__MassTransit | tests/MassTransit.Tests/SagaStateMachineTests/CatchInitial_Specs.cs | {
"start": 488,
"end": 1226
} | public class ____ :
MassTransitStateMachine<SomeState>
{
public SomeStateMachine()
{
InstanceState(x => x.CurrentState);
Initially(
When(SomeEvent)
.Activity(x => x.OfType<FailureActivity>())
.TransitionTo(Active)
.Catch<Exception>(c => c
.Activity(x => x.OfType<BadThingHappenedActivity>())
.Finalize())
);
SetCompletedWhenFinalized();
}
public Event<SomeEvent> SomeEvent { get; }
public State Active { get; }
}
| SomeStateMachine |
csharp | ServiceStack__ServiceStack.Text | tests/ServiceStack.Text.Tests/Utils/DateTimeSerializerTests.cs | {
"start": 204,
"end": 13632
} | public class ____
: TestBase
{
public void PrintFormats(DateTime dateTime)
{
Log("dateTime.ToShortDateString(): " + dateTime.ToString("d"));
Log("dateTime.ToLongDateString(): " + dateTime.ToString("D"));
Log("dateTime.ToShortTimeString(): " + dateTime.ToString("t"));
Log("dateTime.ToLongTimeString(): " + dateTime.ToString("T"));
Log("dateTime.ToString(): " + dateTime.ToString());
Log("DateTimeSerializer.ToShortestXsdDateTimeString(dateTime): " + DateTimeSerializer.ToShortestXsdDateTimeString(dateTime));
Log("DateTimeSerializer.ToDateTimeString(dateTime): " + DateTimeSerializer.ToDateTimeString(dateTime));
Log("DateTimeSerializer.ToXsdDateTimeString(dateTime): " + DateTimeSerializer.ToXsdDateTimeString(dateTime));
Log("\n");
}
public void PrintFormats(TimeSpan timeSpan)
{
Log("DateTimeSerializer.ToXsdTimeSpanString(timeSpan): " + DateTimeSerializer.ToXsdTimeSpanString(timeSpan));
Log("\n");
}
[Test]
public void PrintDate()
{
PrintFormats(DateTime.Now);
PrintFormats(DateTime.UtcNow);
PrintFormats(new DateTime(1979, 5, 9));
PrintFormats(new DateTime(1979, 5, 9, 0, 0, 1));
PrintFormats(new DateTime(1979, 5, 9, 0, 0, 0, 1));
PrintFormats(new DateTime(2010, 10, 20, 10, 10, 10, 1));
PrintFormats(new DateTime(2010, 11, 22, 11, 11, 11, 1));
}
[Test]
public void PrintTimeSpan()
{
PrintFormats(new TimeSpan());
PrintFormats(new TimeSpan(1));
PrintFormats(new TimeSpan(1, 2, 3));
PrintFormats(new TimeSpan(1, 2, 3, 4));
}
[Test]
public void ToShortestXsdDateTimeString_works()
{
var shortDate = new DateTime(1979, 5, 9);
const string shortDateString = "1979-05-09";
var shortDateTime = new DateTime(1979, 5, 9, 0, 0, 1, DateTimeKind.Utc);
var shortDateTimeString = shortDateTime.Equals(shortDateTime.ToStableUniversalTime())
? "1979-05-09T00:00:01Z"
: "1979-05-08T23:00:01Z";
var longDateTime = new DateTime(1979, 5, 9, 0, 0, 0, 1, DateTimeKind.Utc);
var longDateTimeString = longDateTime.Equals(longDateTime.ToStableUniversalTime())
? "1979-05-09T00:00:00.001Z"
: "1979-05-08T23:00:00.001Z";
Assert.That(DateTimeSerializer.ToShortestXsdDateTimeString(shortDate), Is.EqualTo(shortDateString));
Assert.That(DateTimeSerializer.ToShortestXsdDateTimeString(shortDateTime), Is.EqualTo(shortDateTimeString));
Assert.That(DateTimeSerializer.ToShortestXsdDateTimeString(longDateTime), Is.EqualTo(longDateTimeString).
Or.EqualTo("1979-05-09T00:00:00.0010000Z")); //.NET Core
}
[Test]
public void CanDeserializeDateTimeOffsetWithTimeSpanIsZero()
{
var expectedValue = new DateTimeOffset(2012, 6, 27, 11, 26, 04, 524, TimeSpan.Zero);
var s = DateTimeSerializer.ToWcfJsonDateTimeOffset(expectedValue);
Assert.AreEqual("\\/Date(1340796364524)\\/", s);
var afterValue = DateTimeSerializer.ParseWcfJsonDateOffset(s);
Assert.AreEqual(expectedValue, afterValue);
}
[Test]
[Ignore("TODO: add reason")]
public void Utc_Local_Equals()
{
var now = DateTime.Now;
var utcNow = now.ToStableUniversalTime();
Assert.That(now.Ticks, Is.EqualTo(utcNow.Ticks), "Ticks are different");
Assert.That(now, Is.EqualTo(utcNow), "DateTimes are different");
}
[Test]
public void ParseShortestXsdDateTime_works()
{
DateTime shortDate = DateTimeSerializer.ParseShortestXsdDateTime("2011-8-4");
Assert.That(shortDate, Is.EqualTo(new DateTime(2011, 8, 4)), "Month and day without leading 0");
shortDate = DateTimeSerializer.ParseShortestXsdDateTime("2011-8-05");
Assert.That(shortDate, Is.EqualTo(new DateTime(2011, 8, 5)), "Month without leading 0");
shortDate = DateTimeSerializer.ParseShortestXsdDateTime("2011-09-4");
Assert.That(shortDate, Is.EqualTo(new DateTime(2011, 9, 4)), "Day without leading 0");
}
[Test]
public void ParseRFC1123DateTime_works()
{
DateTime rfc1123Date = DateTimeSerializer.ParseRFC1123DateTime("Tue, 12 Nov 2013 14:32:07 GMT");
Assert.That(rfc1123Date, Is.EqualTo(new DateTime(2013, 11, 12, 14, 32, 07)));
}
[Test]
public void TestSqlServerDateTime()
{
var result = TypeSerializer.DeserializeFromString<DateTime>("2010-06-01 21:52:59.280");
Assert.That(result, Is.Not.Null);
}
[Test]
public void DateTimeWithoutMilliseconds_should_always_be_deserialized_correctly_by_TypeSerializer()
{
var dateWithoutMillisecondsUtc = new DateTime(2013, 4, 9, 15, 20, 0, DateTimeKind.Utc);
var dateWithoutMillisecondsLocal = new DateTime(2013, 4, 9, 15, 20, 0, DateTimeKind.Local);
var dateWithoutMillisecondsUnspecified = new DateTime(2013, 4, 9, 15, 20, 0, DateTimeKind.Unspecified);
string serialized = null;
DateTime deserialized;
serialized = TypeSerializer.SerializeToString(dateWithoutMillisecondsUtc);
deserialized = TypeSerializer.DeserializeFromString<DateTime>(serialized);
Assert.AreEqual(dateWithoutMillisecondsUtc.ToLocalTime(), deserialized);
serialized = TypeSerializer.SerializeToString(dateWithoutMillisecondsLocal);
deserialized = TypeSerializer.DeserializeFromString<DateTime>(serialized);
Assert.AreEqual(dateWithoutMillisecondsLocal, deserialized);
serialized = TypeSerializer.SerializeToString(dateWithoutMillisecondsUnspecified);
deserialized = TypeSerializer.DeserializeFromString<DateTime>(serialized);
Assert.AreEqual(dateWithoutMillisecondsUnspecified, deserialized);
}
[Test, Ignore("Don't pre-serialize into Utc")]
public void UtcDateTime_Is_Deserialized_As_Kind_Utc()
{
//Serializing UTC
var utcNow = new DateTime(2012, 1, 8, 12, 17, 1, 538, DateTimeKind.Utc);
Assert.That(utcNow.Kind, Is.EqualTo(DateTimeKind.Utc));
var serialized = JsonSerializer.SerializeToString(utcNow);
//Deserializing UTC?
var deserialized = JsonSerializer.DeserializeFromString<DateTime>(serialized);
Assert.That(deserialized.Kind, Is.EqualTo(DateTimeKind.Utc)); //fails -> is DateTimeKind.Local
}
/// <summary>
/// These timestamp strings were pulled from SQLite columns written via OrmLite using SQlite.1.88
/// Most of the time, timestamps correctly use the 'T' separator between the date and time,
/// but under some (still unknown) scnearios, SQLite will write timestamps using a space instead of a 'T'.
/// If that happens, OrmLite will fail to read the row, complaining that: The string '...' is not a valid Xsd value.
/// </summary>
private static string[] _problematicXsdStrings = new[] {
"2013-10-10 20:04:04.8773249Z",
"2013-10-10 20:04:04Z",
};
[Test]
[TestCase(0)]
[TestCase(1)]
public void CanParseProblematicXsdStrings(int whichString)
{
var xsdString = _problematicXsdStrings[whichString];
var dateTime = DateTimeSerializer.ParseShortestXsdDateTime(xsdString);
Assert.That(dateTime.Kind, Is.EqualTo(DateTimeKind.Local));
}
[Test]
public void CanParseLongAndShortXsdStrings()
{
var shortXsdString = "2013-10-10T13:40:50Z";
var longXsdString = shortXsdString.Substring(0, shortXsdString.Length - 1) + ".0000000" +
shortXsdString.Substring(shortXsdString.Length - 1);
var dateTimeShort = DateTimeSerializer.ParseShortestXsdDateTime(shortXsdString);
var dateTimeLong = DateTimeSerializer.ParseShortestXsdDateTime(longXsdString);
Assert.That(dateTimeShort.Ticks, Is.EqualTo(dateTimeLong.Ticks));
Assert.That(dateTimeShort.Kind, Is.EqualTo(dateTimeLong.Kind));
}
internal static readonly DateTime[] DateTimeTests = new[] {
DateTime.Now,
DateTime.UtcNow,
new DateTime(1979, 5, 9),
new DateTime(1972, 3, 24, 0, 0, 0, DateTimeKind.Local),
new DateTime(1972, 4, 24),
new DateTime(1979, 5, 9, 0, 0, 1),
new DateTime(1979, 5, 9, 0, 0, 0, 1),
new DateTime(2010, 10, 20, 10, 10, 10, 1),
new DateTime(2010, 11, 22, 11, 11, 11, 1),
new DateTime(622119282055250000),
new DateTime(622119282050000001, DateTimeKind.Utc),
};
[Test]
[TestCase(0)]
[TestCase(1)]
[TestCase(2)]
//[TestCase(3)] //.NET Date BUG see: Test_MS_Dates
[TestCase(4)]
[TestCase(5)]
[TestCase(6)]
[TestCase(7)]
[TestCase(8)]
[TestCase(9)]
[TestCase(10)]
public void AssertDateIsEqual(int whichDate)
{
DateTime dateTime = DateTimeTests[whichDate];
//Don't test short dates without time to UTC as you lose precision
var shortDateStr = dateTime.ToString(DateTimeSerializer.ShortDateTimeFormat);
var shortDateTimeStr = dateTime.ToStableUniversalTime().ToString(DateTimeSerializer.XsdDateTimeFormatSeconds);
var longDateTimeStr = DateTimeSerializer.ToXsdDateTimeString(dateTime);
var shortestDateStr = DateTimeSerializer.ToShortestXsdDateTimeString(dateTime);
Log("{0} | {1} | {2} [{3}]",
shortDateStr, shortDateTimeStr, longDateTimeStr, shortestDateStr);
var shortDate = DateTimeSerializer.ParseShortestXsdDateTime(shortDateStr);
var shortDateTime = DateTimeSerializer.ParseShortestXsdDateTime(shortDateTimeStr);
var longDateTime = DateTimeSerializer.ParseShortestXsdDateTime(longDateTimeStr);
Assert.That(shortDate, Is.EqualTo(dateTime.Date));
var shortDateTimeUtc = shortDateTime.ToStableUniversalTime();
Assert.That(shortDateTimeUtc, Is.EqualTo(
new DateTime(
shortDateTimeUtc.Year, shortDateTimeUtc.Month, shortDateTimeUtc.Day,
shortDateTimeUtc.Hour, shortDateTimeUtc.Minute, shortDateTimeUtc.Second,
shortDateTimeUtc.Millisecond, DateTimeKind.Utc)));
AssertDatesAreEqual(longDateTime.ToStableUniversalTime(), dateTime.ToStableUniversalTime());
var toDateTime = DateTimeSerializer.ParseShortestXsdDateTime(shortestDateStr);
AssertDatesAreEqual(toDateTime, dateTime, "shortestDate");
Assert.That(toDateTime.ToStableUniversalTime().TimeOfDay.TotalSeconds, Is.EqualTo(dateTime.ToStableUniversalTime().TimeOfDay.TotalSeconds), "shortestDate: Fractional seconds differ");
var unixTime = dateTime.ToUnixTimeMs();
var fromUnixTime = DateTimeExtensions.FromUnixTimeMs(unixTime);
AssertDatesAreEqual(fromUnixTime, dateTime, "unixTimeMs");
var wcfDateString = DateTimeSerializer.ToWcfJsonDate(dateTime);
var wcfDate = DateTimeSerializer.ParseWcfJsonDate(wcfDateString);
AssertDatesAreEqual(wcfDate, dateTime, "wcf date");
}
private void AssertDatesAreEqual(DateTime toDateTime, DateTime dateTime, string which = null)
{
Assert.That(toDateTime.ToStableUniversalTime().RoundToMs(), Is.EqualTo(dateTime.ToStableUniversalTime().RoundToMs()), which);
}
[Test]
public void Can_Serialize_new_DateTime()
{
var newDateTime = new DateTime();
var convertedUnixTimeMs = newDateTime.ToUnixTimeMs();
Assert.That(convertedUnixTimeMs.FromUnixTimeMs(), Is.EqualTo(newDateTime));
}
[Explicit("Test .NET Date Serialization behavior")]
[TestCase(0)]
[TestCase(1)]
[TestCase(2)]
[TestCase(3)]
[TestCase(4)]
[TestCase(5)]
[TestCase(6)]
[TestCase(7)]
[TestCase(8)]
public void Test_MS_Dates(int whichDate)
{
var dateTime = DateTimeTests[whichDate];
var dateTimeStr = XmlConvert.ToString(dateTime.ToStableUniversalTime(), XmlDateTimeSerializationMode.Utc);
dateTimeStr.Print(); //1972-03-24T05:00:00Z
var fromStr = DateTime.Parse(dateTimeStr);
fromStr.ToString().Print();
AssertDatesAreEqual(fromStr, dateTime);
}
[Test]
public void Can_serialize_MaxDateTime()
{
var maxDate = DateTime.MaxValue.ToUnixTime();
var minDate = DateTime.MinValue.ToUnixTime();
}
}
| DateTimeSerializerTests |
csharp | grandnode__grandnode2 | src/Web/Grand.Web.Admin/Models/Settings/CustomerSettingsModel.cs | {
"start": 197,
"end": 424
} | public class ____ : BaseModel
{
public CustomersSettingsModel CustomerSettings { get; set; } = new();
public AddressSettingsModel AddressSettings { get; set; } = new();
#region Nested classes
| CustomerSettingsModel |
csharp | OrchardCMS__OrchardCore | src/OrchardCore.Modules/OrchardCore.Roles/ViewModels/RolesViewModel.cs | {
"start": 87,
"end": 179
} | public class ____
{
public List<RoleEntry> RoleEntries { get; set; } = [];
}
| RolesViewModel |
csharp | microsoft__garnet | libs/cluster/Server/Replication/PrimaryOps/DisklessReplication/ReplicationSnapshotIterator.cs | {
"start": 7632,
"end": 8796
} | class ____(SnapshotIteratorManager snapshotIteratorManager) :
IStreamingSnapshotIteratorFunctions<SpanByte, SpanByte>
{
readonly SnapshotIteratorManager snapshotIteratorManager = snapshotIteratorManager;
long targetVersion;
public bool OnStart(Guid checkpointToken, long currentVersion, long targetVersion)
{
this.targetVersion = targetVersion;
return snapshotIteratorManager.OnStart(checkpointToken, currentVersion, targetVersion, isMainStore: true);
}
public bool Reader(ref SpanByte key, ref SpanByte value, RecordMetadata recordMetadata, long numberOfRecords)
=> snapshotIteratorManager.Reader(ref key, ref value, recordMetadata, numberOfRecords);
public void OnException(Exception exception, long numberOfRecords)
=> snapshotIteratorManager.logger?.LogError(exception, $"{nameof(MainStoreSnapshotIterator)}");
public void OnStop(bool completed, long numberOfRecords)
=> snapshotIteratorManager.OnStop(completed, numberOfRecords, isMainStore: true, targetVersion);
}
internal sealed unsafe | MainStoreSnapshotIterator |
csharp | dotnet__efcore | test/EFCore.SqlServer.FunctionalTests/Query/Translations/Temporal/DateTimeTranslationsSqlServerTest.cs | {
"start": 273,
"end": 11275
} | public class ____ : DateTimeTranslationsTestBase<BasicTypesQuerySqlServerFixture>
{
public DateTimeTranslationsSqlServerTest(BasicTypesQuerySqlServerFixture fixture, ITestOutputHelper testOutputHelper)
: base(fixture)
{
Fixture.TestSqlLoggerFactory.Clear();
Fixture.TestSqlLoggerFactory.SetTestOutputHelper(testOutputHelper);
}
public override async Task Now()
{
await base.Now();
AssertSql(
"""
@myDatetime='2015-04-10T00:00:00.0000000' (DbType = DateTime)
SELECT [b].[Id], [b].[Bool], [b].[Byte], [b].[ByteArray], [b].[DateOnly], [b].[DateTime], [b].[DateTimeOffset], [b].[Decimal], [b].[Double], [b].[Enum], [b].[FlagsEnum], [b].[Float], [b].[Guid], [b].[Int], [b].[Long], [b].[Short], [b].[String], [b].[TimeOnly], [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE GETDATE() <> @myDatetime
""");
}
public override async Task UtcNow()
{
await base.UtcNow();
AssertSql(
"""
@myDatetime='2015-04-10T00:00:00.0000000' (DbType = DateTime)
SELECT [b].[Id], [b].[Bool], [b].[Byte], [b].[ByteArray], [b].[DateOnly], [b].[DateTime], [b].[DateTimeOffset], [b].[Decimal], [b].[Double], [b].[Enum], [b].[FlagsEnum], [b].[Float], [b].[Guid], [b].[Int], [b].[Long], [b].[Short], [b].[String], [b].[TimeOnly], [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE GETUTCDATE() <> @myDatetime
""");
}
public override async Task Today()
{
await base.Today();
AssertSql(
"""
SELECT [b].[Id], [b].[Bool], [b].[Byte], [b].[ByteArray], [b].[DateOnly], [b].[DateTime], [b].[DateTimeOffset], [b].[Decimal], [b].[Double], [b].[Enum], [b].[FlagsEnum], [b].[Float], [b].[Guid], [b].[Int], [b].[Long], [b].[Short], [b].[String], [b].[TimeOnly], [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE [b].[DateTime] = CONVERT(date, GETDATE())
""");
}
public override async Task Date()
{
await base.Date();
AssertSql(
"""
@myDatetime='1998-05-04T00:00:00.0000000'
SELECT [b].[Id], [b].[Bool], [b].[Byte], [b].[ByteArray], [b].[DateOnly], [b].[DateTime], [b].[DateTimeOffset], [b].[Decimal], [b].[Double], [b].[Enum], [b].[FlagsEnum], [b].[Float], [b].[Guid], [b].[Int], [b].[Long], [b].[Short], [b].[String], [b].[TimeOnly], [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE CONVERT(date, [b].[DateTime]) = @myDatetime
""");
}
public override async Task AddYear()
{
await base.AddYear();
AssertSql(
"""
SELECT [b].[Id], [b].[Bool], [b].[Byte], [b].[ByteArray], [b].[DateOnly], [b].[DateTime], [b].[DateTimeOffset], [b].[Decimal], [b].[Double], [b].[Enum], [b].[FlagsEnum], [b].[Float], [b].[Guid], [b].[Int], [b].[Long], [b].[Short], [b].[String], [b].[TimeOnly], [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE DATEPART(year, DATEADD(year, CAST(1 AS int), [b].[DateTime])) = 1999
""");
}
public override async Task Year()
{
await base.Year();
AssertSql(
"""
SELECT [b].[Id], [b].[Bool], [b].[Byte], [b].[ByteArray], [b].[DateOnly], [b].[DateTime], [b].[DateTimeOffset], [b].[Decimal], [b].[Double], [b].[Enum], [b].[FlagsEnum], [b].[Float], [b].[Guid], [b].[Int], [b].[Long], [b].[Short], [b].[String], [b].[TimeOnly], [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE DATEPART(year, [b].[DateTime]) = 1998
""");
}
public override async Task Month()
{
await base.Month();
AssertSql(
"""
SELECT [b].[Id], [b].[Bool], [b].[Byte], [b].[ByteArray], [b].[DateOnly], [b].[DateTime], [b].[DateTimeOffset], [b].[Decimal], [b].[Double], [b].[Enum], [b].[FlagsEnum], [b].[Float], [b].[Guid], [b].[Int], [b].[Long], [b].[Short], [b].[String], [b].[TimeOnly], [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE DATEPART(month, [b].[DateTime]) = 5
""");
}
public override async Task DayOfYear()
{
await base.DayOfYear();
AssertSql(
"""
SELECT [b].[Id], [b].[Bool], [b].[Byte], [b].[ByteArray], [b].[DateOnly], [b].[DateTime], [b].[DateTimeOffset], [b].[Decimal], [b].[Double], [b].[Enum], [b].[FlagsEnum], [b].[Float], [b].[Guid], [b].[Int], [b].[Long], [b].[Short], [b].[String], [b].[TimeOnly], [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE DATEPART(dayofyear, [b].[DateTime]) = 124
""");
}
public override async Task Day()
{
await base.Day();
AssertSql(
"""
SELECT [b].[Id], [b].[Bool], [b].[Byte], [b].[ByteArray], [b].[DateOnly], [b].[DateTime], [b].[DateTimeOffset], [b].[Decimal], [b].[Double], [b].[Enum], [b].[FlagsEnum], [b].[Float], [b].[Guid], [b].[Int], [b].[Long], [b].[Short], [b].[String], [b].[TimeOnly], [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE DATEPART(day, [b].[DateTime]) = 4
""");
}
public override async Task Hour()
{
await base.Hour();
AssertSql(
"""
SELECT [b].[Id], [b].[Bool], [b].[Byte], [b].[ByteArray], [b].[DateOnly], [b].[DateTime], [b].[DateTimeOffset], [b].[Decimal], [b].[Double], [b].[Enum], [b].[FlagsEnum], [b].[Float], [b].[Guid], [b].[Int], [b].[Long], [b].[Short], [b].[String], [b].[TimeOnly], [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE DATEPART(hour, [b].[DateTime]) = 15
""");
}
public override async Task Minute()
{
await base.Minute();
AssertSql(
"""
SELECT [b].[Id], [b].[Bool], [b].[Byte], [b].[ByteArray], [b].[DateOnly], [b].[DateTime], [b].[DateTimeOffset], [b].[Decimal], [b].[Double], [b].[Enum], [b].[FlagsEnum], [b].[Float], [b].[Guid], [b].[Int], [b].[Long], [b].[Short], [b].[String], [b].[TimeOnly], [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE DATEPART(minute, [b].[DateTime]) = 30
""");
}
public override async Task Second()
{
await base.Second();
AssertSql(
"""
SELECT [b].[Id], [b].[Bool], [b].[Byte], [b].[ByteArray], [b].[DateOnly], [b].[DateTime], [b].[DateTimeOffset], [b].[Decimal], [b].[Double], [b].[Enum], [b].[FlagsEnum], [b].[Float], [b].[Guid], [b].[Int], [b].[Long], [b].[Short], [b].[String], [b].[TimeOnly], [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE DATEPART(second, [b].[DateTime]) = 10
""");
}
public override async Task Millisecond()
{
await base.Millisecond();
AssertSql(
"""
SELECT [b].[Id], [b].[Bool], [b].[Byte], [b].[ByteArray], [b].[DateOnly], [b].[DateTime], [b].[DateTimeOffset], [b].[Decimal], [b].[Double], [b].[Enum], [b].[FlagsEnum], [b].[Float], [b].[Guid], [b].[Int], [b].[Long], [b].[Short], [b].[String], [b].[TimeOnly], [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE DATEPART(millisecond, [b].[DateTime]) = 123
""");
}
public override async Task TimeOfDay()
{
await base.TimeOfDay();
AssertSql(
"""
SELECT [b].[Id], [b].[Bool], [b].[Byte], [b].[ByteArray], [b].[DateOnly], [b].[DateTime], [b].[DateTimeOffset], [b].[Decimal], [b].[Double], [b].[Enum], [b].[FlagsEnum], [b].[Float], [b].[Guid], [b].[Int], [b].[Long], [b].[Short], [b].[String], [b].[TimeOnly], [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE CONVERT(time, [b].[DateTime]) = '00:00:00'
""");
}
public override Task subtract_and_TotalDays()
=> AssertTranslationFailed(() => base.subtract_and_TotalDays());
public override async Task Parse_with_constant()
{
await base.Parse_with_constant();
AssertSql(
"""
SELECT [b].[Id], [b].[Bool], [b].[Byte], [b].[ByteArray], [b].[DateOnly], [b].[DateTime], [b].[DateTimeOffset], [b].[Decimal], [b].[Double], [b].[Enum], [b].[FlagsEnum], [b].[Float], [b].[Guid], [b].[Int], [b].[Long], [b].[Short], [b].[String], [b].[TimeOnly], [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE [b].[DateTime] = '1998-05-04T15:30:10.0000000'
""");
}
public override async Task Parse_with_parameter()
{
await base.Parse_with_parameter();
AssertSql(
"""
@Parse='1998-05-04T15:30:10.0000000'
SELECT [b].[Id], [b].[Bool], [b].[Byte], [b].[ByteArray], [b].[DateOnly], [b].[DateTime], [b].[DateTimeOffset], [b].[Decimal], [b].[Double], [b].[Enum], [b].[FlagsEnum], [b].[Float], [b].[Guid], [b].[Int], [b].[Long], [b].[Short], [b].[String], [b].[TimeOnly], [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE [b].[DateTime] = @Parse
""");
}
public override async Task New_with_constant()
{
await base.New_with_constant();
AssertSql(
"""
SELECT [b].[Id], [b].[Bool], [b].[Byte], [b].[ByteArray], [b].[DateOnly], [b].[DateTime], [b].[DateTimeOffset], [b].[Decimal], [b].[Double], [b].[Enum], [b].[FlagsEnum], [b].[Float], [b].[Guid], [b].[Int], [b].[Long], [b].[Short], [b].[String], [b].[TimeOnly], [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE [b].[DateTime] = '1998-05-04T15:30:10.0000000'
""");
}
public override async Task New_with_parameters()
{
await base.New_with_parameters();
AssertSql(
"""
@p='1998-05-04T15:30:10.0000000'
SELECT [b].[Id], [b].[Bool], [b].[Byte], [b].[ByteArray], [b].[DateOnly], [b].[DateTime], [b].[DateTimeOffset], [b].[Decimal], [b].[Double], [b].[Enum], [b].[FlagsEnum], [b].[Float], [b].[Guid], [b].[Int], [b].[Long], [b].[Short], [b].[String], [b].[TimeOnly], [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE [b].[DateTime] = @p
""");
}
[ConditionalFact]
public virtual async Task Now_has_proper_type_mapping_for_constant_comparison()
{
await AssertQuery(
ss => ss.Set<BasicTypesEntity>().Where(x => DateTime.Now > new DateTime(2025, 1, 1)));
AssertSql(
"""
SELECT [b].[Id], [b].[Bool], [b].[Byte], [b].[ByteArray], [b].[DateOnly], [b].[DateTime], [b].[DateTimeOffset], [b].[Decimal], [b].[Double], [b].[Enum], [b].[FlagsEnum], [b].[Float], [b].[Guid], [b].[Int], [b].[Long], [b].[Short], [b].[String], [b].[TimeOnly], [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE GETDATE() > '2025-01-01T00:00:00.000'
""");
}
[ConditionalFact]
public virtual async Task UtcNow_has_proper_type_mapping_for_constant_comparison()
{
await AssertQuery(
ss => ss.Set<BasicTypesEntity>().Where(x => DateTime.UtcNow > new DateTime(2025, 1, 1)));
AssertSql(
"""
SELECT [b].[Id], [b].[Bool], [b].[Byte], [b].[ByteArray], [b].[DateOnly], [b].[DateTime], [b].[DateTimeOffset], [b].[Decimal], [b].[Double], [b].[Enum], [b].[FlagsEnum], [b].[Float], [b].[Guid], [b].[Int], [b].[Long], [b].[Short], [b].[String], [b].[TimeOnly], [b].[TimeSpan]
FROM [BasicTypesEntities] AS [b]
WHERE GETUTCDATE() > '2025-01-01T00:00:00.000'
""");
}
[ConditionalFact]
public virtual void Check_all_tests_overridden()
=> TestHelpers.AssertAllMethodsOverridden(GetType());
private void AssertSql(params string[] expected)
=> Fixture.TestSqlLoggerFactory.AssertBaseline(expected);
}
| DateTimeTranslationsSqlServerTest |
csharp | mongodb__mongo-csharp-driver | tests/MongoDB.Driver.TestHelpers/Core/EventCapturer.cs | {
"start": 847,
"end": 935
} | public interface ____
{
object Format(object @event);
}
| IEventFormatter |
csharp | dotnet__efcore | test/EFCore.Relational.Specification.Tests/Query/TPCFiltersInheritanceQueryTestBase.cs | {
"start": 247,
"end": 441
} | public abstract class ____<TFixture>(TFixture fixture) : FiltersInheritanceQueryTestBase<TFixture>(fixture)
where TFixture : TPCInheritanceQueryFixture, new();
| TPCFiltersInheritanceQueryTestBase |
csharp | DuendeSoftware__IdentityServer | identity-server/src/IdentityServer/Validation/Contexts/CustomBackchannelAuthenticationRequestValidationContext.cs | {
"start": 246,
"end": 816
} | public class ____
{
/// <summary>
/// Creates a new instance of the <see cref="CustomBackchannelAuthenticationRequestValidationContext"/>
/// </summary>
public CustomBackchannelAuthenticationRequestValidationContext(BackchannelAuthenticationRequestValidationResult validatedRequest) => ValidationResult = validatedRequest;
/// <summary>
/// Gets or sets the CIBA validation result.
/// </summary>
public BackchannelAuthenticationRequestValidationResult ValidationResult { get; set; }
}
| CustomBackchannelAuthenticationRequestValidationContext |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.AppExtensions/AppExtensionPackageUpdatedEventArgs.cs | {
"start": 313,
"end": 2801
} | public partial class ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal AppExtensionPackageUpdatedEventArgs()
{
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public string AppExtensionName
{
get
{
throw new global::System.NotImplementedException("The member string AppExtensionPackageUpdatedEventArgs.AppExtensionName is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20AppExtensionPackageUpdatedEventArgs.AppExtensionName");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.Collections.Generic.IReadOnlyList<global::Windows.ApplicationModel.AppExtensions.AppExtension> Extensions
{
get
{
throw new global::System.NotImplementedException("The member IReadOnlyList<AppExtension> AppExtensionPackageUpdatedEventArgs.Extensions is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IReadOnlyList%3CAppExtension%3E%20AppExtensionPackageUpdatedEventArgs.Extensions");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.ApplicationModel.Package Package
{
get
{
throw new global::System.NotImplementedException("The member Package AppExtensionPackageUpdatedEventArgs.Package is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=Package%20AppExtensionPackageUpdatedEventArgs.Package");
}
}
#endif
// Forced skipping of method Windows.ApplicationModel.AppExtensions.AppExtensionPackageUpdatedEventArgs.AppExtensionName.get
// Forced skipping of method Windows.ApplicationModel.AppExtensions.AppExtensionPackageUpdatedEventArgs.Package.get
// Forced skipping of method Windows.ApplicationModel.AppExtensions.AppExtensionPackageUpdatedEventArgs.Extensions.get
}
}
| AppExtensionPackageUpdatedEventArgs |
csharp | Xabaril__AspNetCore.Diagnostics.HealthChecks | test/HealthChecks.Uris.Tests/Functional/UrisHealthcheckTests2.cs | {
"start": 5324,
"end": 5453
} | internal class ____
{
public string HeaderName = "X-API-KEY";
public string HeaderValue = "my-api-key";
}
| ApiKeyConfiguration |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs | {
"start": 370057,
"end": 370277
} | public class ____
{
public int Id { get; set; }
public RelatedEntity1696 ParentEntity { get; set; }
public IEnumerable<RelatedEntity1698> ChildEntities { get; set; }
}
| RelatedEntity1697 |
csharp | ServiceStack__ServiceStack | ServiceStack.Text/tests/ServiceStack.Text.Tests/JsonTests/PropertyConventionTests.cs | {
"start": 1745,
"end": 2910
} | public class ____
{
public string SnippetFormat { get; set; }
public int Total { get; set; }
public int Start { get; set; }
public int PageLength { get; set; }
}
[Test]
public void Can_deserialize_hyphens()
{
var json = @"{
""snippet-format"":""raw"",
""total"":1,
""start"":1,
""page-length"":200
}";
var map = JsonObject.Parse(json);
Assert.That(map["snippet-format"], Is.EqualTo("raw"));
Assert.That(map["total"], Is.EqualTo("1"));
Assert.That(map["start"], Is.EqualTo("1"));
Assert.That(map["page-length"], Is.EqualTo("200"));
JsConfig.PropertyConvention = PropertyConvention.Lenient;
var dto = json.FromJson<Hyphens>();
Assert.That(dto.SnippetFormat, Is.EqualTo("raw"));
Assert.That(dto.Total, Is.EqualTo(1));
Assert.That(dto.Start, Is.EqualTo(1));
Assert.That(dto.PageLength, Is.EqualTo(200));
JsConfig.Reset();
}
}
} | Hyphens |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/TypedFilterTests.cs | {
"start": 525,
"end": 824
} | private class ____ : ITypedFilter<Dto>
{
public TypedRequestFilter(IDependency dependency) => Dependency = dependency;
public IDependency Dependency { get; }
public void Invoke(IRequest req, IResponse res, Dto dto) => dto.RequestFilter = true;
}
| TypedRequestFilter |
csharp | dotnet__extensions | test/Generators/Microsoft.Gen.Logging/Unit/ParserTests.LogMethod.cs | {
"start": 3943,
"end": 4249
} | partial class ____
{
public ILogger<int> Logger { get; set; } = null!;
public ILogger /*2+*/_logger2/*-2*/;
[LoggerMessage(0, LogLevel.Debug, ""M1"")]
public partial void M1();
}
| E |
csharp | abpframework__abp | modules/account/src/Volo.Abp.Account.Web/Pages/Account/ResetPassword.cshtml.cs | {
"start": 351,
"end": 2956
} | public class ____ : AccountPageModel
{
[Required]
[HiddenInput]
[BindProperty(SupportsGet = true)]
public Guid UserId { get; set; }
[Required]
[HiddenInput]
[BindProperty(SupportsGet = true)]
public string ResetToken { get; set; }
[HiddenInput]
[BindProperty(SupportsGet = true)]
public string ReturnUrl { get; set; }
[HiddenInput]
[BindProperty(SupportsGet = true)]
public string ReturnUrlHash { get; set; }
[Required]
[BindProperty]
[DataType(DataType.Password)]
[DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxPasswordLength))]
[DisableAuditing]
public string Password { get; set; }
[Required]
[BindProperty]
[DataType(DataType.Password)]
[DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxPasswordLength))]
[DisableAuditing]
public string ConfirmPassword { get; set; }
public bool InvalidToken { get; set; }
public virtual async Task<IActionResult> OnGetAsync()
{
ValidateModel();
InvalidToken = !await AccountAppService.VerifyPasswordResetTokenAsync(
new VerifyPasswordResetTokenInput
{
UserId = UserId,
ResetToken = ResetToken
}
);
return Page();
}
public virtual async Task<IActionResult> OnPostAsync()
{
try
{
ValidateModel();
await AccountAppService.ResetPasswordAsync(
new ResetPasswordDto
{
UserId = UserId,
ResetToken = ResetToken,
Password = Password
}
);
}
catch (AbpIdentityResultException e)
{
if (!string.IsNullOrWhiteSpace(e.Message))
{
Alerts.Warning(GetLocalizeExceptionMessage(e));
return Page();
}
throw;
}
catch (AbpValidationException e)
{
return Page();
}
//TODO: Try to automatically login!
return RedirectToPage("./ResetPasswordConfirmation", new {
returnUrl = ReturnUrl,
returnUrlHash = ReturnUrlHash
});
}
protected override void ValidateModel()
{
if (!Equals(Password, ConfirmPassword))
{
ModelState.AddModelError("ConfirmPassword",
L["'{0}' and '{1}' do not match.", "ConfirmPassword", "Password"]);
}
base.ValidateModel();
}
}
| ResetPasswordModel |
csharp | pythonnet__pythonnet | src/runtime/Native/PyBufferInterface.cs | {
"start": 177,
"end": 890
} | internal struct ____ {
public IntPtr buf;
public IntPtr obj; /* owned reference */
/// <summary>Buffer size in bytes</summary>
[MarshalAs(UnmanagedType.SysInt)]
public nint len;
[MarshalAs(UnmanagedType.SysInt)]
public nint itemsize; /* This is Py_ssize_t so it can be
pointed to by strides in simple case.*/
[MarshalAs(UnmanagedType.Bool)]
public bool _readonly;
public int ndim;
[MarshalAs(UnmanagedType.LPStr)]
public string? format;
public IntPtr shape;
public IntPtr strides;
public IntPtr suboffsets;
public IntPtr _internal;
}
| Py_buffer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.