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 | mysql-net__MySqlConnector | src/MySqlConnector.Logging.log4net/Log4netLoggerProvider.cs | {
"start": 138,
"end": 528
} | public sealed class ____ : IMySqlConnectorLoggerProvider
{
public IMySqlConnectorLogger CreateLogger(string name) => new Log4netLogger(LogManager.GetLogger(s_loggerAssembly, "MySqlConnector." + name));
private static readonly Assembly s_loggerAssembly = typeof(Log4netLogger).GetTypeInfo().Assembly;
private static readonly Type s_loggerType = typeof(Log4netLogger);
| Log4netLoggerProvider |
csharp | dotnet__aspire | src/Aspire.Hosting.Azure.AppService/AzureAppServiceComputeResourceExtensions.cs | {
"start": 394,
"end": 1797
} | public static class ____
{
/// <summary>
/// Publishes the specified compute resource as an Azure App Service.
/// </summary>
/// <typeparam name="T">The type of the compute resource.</typeparam>
/// <param name="builder">The compute resource builder.</param>
/// <param name="configure">The configuration action for the App Service WebSite resource.</param>
/// <returns>The updated compute resource builder.</returns>
/// <remarks>
/// <example>
/// <code>
/// builder.AddProject<Projects.Api>("name").PublishAsAzureAppServiceWebsite((infrastructure, app) =>
/// {
/// // Configure the App Service WebSite resource here
/// });
/// </code>
/// </example>
/// </remarks>
public static IResourceBuilder<T> PublishAsAzureAppServiceWebsite<T>(this IResourceBuilder<T> builder, Action<AzureResourceInfrastructure, WebSite> configure)
where T : IComputeResource
{
ArgumentNullException.ThrowIfNull(builder);
ArgumentNullException.ThrowIfNull(configure);
if (!builder.ApplicationBuilder.ExecutionContext.IsPublishMode)
{
return builder;
}
builder.ApplicationBuilder.AddAzureAppServiceInfrastructureCore();
return builder.WithAnnotation(new AzureAppServiceWebsiteCustomizationAnnotation(configure));
}
}
| AzureAppServiceComputeResourceExtensions |
csharp | bitwarden__server | test/IntegrationTestCommon/Factories/IdentityApplicationFactory.cs | {
"start": 521,
"end": 9266
} | public class ____ : WebApplicationFactoryBase<Startup>
{
public const string DefaultDeviceIdentifier = "92b9d953-b9b6-4eaf-9d3e-11d57144dfeb";
public const string DefaultUserEmail = "DefaultEmail@bitwarden.com";
public const string DefaultUserPasswordHash = "default_password_hash";
/// <summary>
/// A dictionary to store registration tokens for email verification. We cannot substitute the IMailService more than once, so
/// we capture the email tokens for new user registration in the constructor. The email must be unique otherwise an error will be thrown.
/// </summary>
public ConcurrentDictionary<string, string> RegistrationTokens { get; private set; } = new ConcurrentDictionary<string, string>();
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
// This allows us to use the official registration flow
SubstituteService<IMailService>(service =>
{
service.SendRegistrationVerificationEmailAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>())
.ReturnsForAnyArgs(Task.CompletedTask)
.AndDoes(call =>
{
if (!RegistrationTokens.TryAdd(call.ArgAt<string>(0), call.ArgAt<string>(1)))
{
throw new InvalidOperationException("This email was already registered for new user registration.");
}
});
});
base.ConfigureWebHost(builder);
}
public async Task<HttpContext> PostRegisterSendEmailVerificationAsync(RegisterSendVerificationEmailRequestModel model)
{
return await Server.PostAsync("/accounts/register/send-verification-email", JsonContent.Create(model));
}
public async Task<HttpContext> PostRegisterFinishAsync(RegisterFinishRequestModel model)
{
return await Server.PostAsync("/accounts/register/finish", JsonContent.Create(model));
}
public async Task<HttpContext> PostRegisterVerificationEmailClicked(RegisterVerificationEmailClickedRequestModel model)
{
return await Server.PostAsync("/accounts/register/verification-email-clicked", JsonContent.Create(model));
}
public async Task<(string Token, string RefreshToken)> TokenFromPasswordAsync(
string username,
string password,
string deviceIdentifier = DefaultDeviceIdentifier,
string clientId = "web",
DeviceType deviceType = DeviceType.FirefoxBrowser,
string deviceName = "firefox")
{
var context = await ContextFromPasswordAsync(
username, password, deviceIdentifier, clientId, deviceType, deviceName);
using var body = await AssertHelper.AssertResponseTypeIs<JsonDocument>(context);
var root = body.RootElement;
return (root.GetProperty("access_token").GetString(), root.GetProperty("refresh_token").GetString());
}
public async Task<HttpContext> ContextFromPasswordAsync(
string username,
string password,
string deviceIdentifier = DefaultDeviceIdentifier,
string clientId = "web",
DeviceType deviceType = DeviceType.FirefoxBrowser,
string deviceName = "firefox")
{
var context = await Server.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "scope", "api offline_access" },
{ "client_id", clientId },
{ "deviceType", ((int)deviceType).ToString() },
{ "deviceIdentifier", deviceIdentifier },
{ "deviceName", deviceName },
{ "grant_type", "password" },
{ "username", username },
{ "password", password },
}));
return context;
}
public async Task<HttpContext> ContextFromPasswordWithTwoFactorAsync(
string username,
string password,
string deviceIdentifier = DefaultDeviceIdentifier,
string clientId = "web",
DeviceType deviceType = DeviceType.FirefoxBrowser,
string deviceName = "firefox",
string twoFactorProviderType = "Email",
string twoFactorToken = "two-factor-token")
{
var context = await Server.PostAsync("/connect/token", new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "scope", "api offline_access" },
{ "client_id", clientId },
{ "deviceType", ((int)deviceType).ToString() },
{ "deviceIdentifier", deviceIdentifier },
{ "deviceName", deviceName },
{ "grant_type", "password" },
{ "username", username },
{ "password", password },
{ "TwoFactorToken", twoFactorToken },
{ "TwoFactorProvider", twoFactorProviderType },
{ "TwoFactorRemember", "1" },
}));
return context;
}
public async Task<string> TokenFromAccessTokenAsync(Guid clientId, string clientSecret,
DeviceType deviceType = DeviceType.SDK)
{
var context = await ContextFromAccessTokenAsync(clientId, clientSecret, deviceType);
using var body = await AssertHelper.AssertResponseTypeIs<JsonDocument>(context);
var root = body.RootElement;
return root.GetProperty("access_token").GetString();
}
public async Task<HttpContext> ContextFromAccessTokenAsync(Guid clientId, string clientSecret,
DeviceType deviceType = DeviceType.SDK)
{
var context = await Server.PostAsync("/connect/token",
new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "scope", "api.secrets" },
{ "client_id", clientId.ToString() },
{ "client_secret", clientSecret },
{ "grant_type", "client_credentials" },
{ "deviceType", ((int)deviceType).ToString() }
}));
return context;
}
public async Task<string> TokenFromOrganizationApiKeyAsync(string clientId, string clientSecret,
DeviceType deviceType = DeviceType.FirefoxBrowser)
{
var context = await ContextFromOrganizationApiKeyAsync(clientId, clientSecret, deviceType);
using var body = await AssertHelper.AssertResponseTypeIs<JsonDocument>(context);
var root = body.RootElement;
return root.GetProperty("access_token").GetString();
}
public async Task<HttpContext> ContextFromOrganizationApiKeyAsync(string clientId, string clientSecret,
DeviceType deviceType = DeviceType.FirefoxBrowser)
{
var context = await Server.PostAsync("/connect/token",
new FormUrlEncodedContent(new Dictionary<string, string>
{
{ "scope", "api.organization" },
{ "client_id", clientId },
{ "client_secret", clientSecret },
{ "grant_type", "client_credentials" },
{ "deviceType", ((int)deviceType).ToString() }
}));
return context;
}
/// <summary>
/// Registers a new user to the Identity Application Factory based on the RegisterFinishRequestModel
/// </summary>
/// <param name="requestModel">RegisterFinishRequestModel needed to seed data to the test user</param>
/// <param name="marketingEmails">optional parameter that is tracked during the inital steps of registration.</param>
/// <returns>returns the newly created user</returns>
public async Task<User> RegisterNewIdentityFactoryUserAsync(
RegisterFinishRequestModel requestModel,
bool marketingEmails = true)
{
var sendVerificationEmailReqModel = new RegisterSendVerificationEmailRequestModel
{
Email = requestModel.Email,
Name = "name",
ReceiveMarketingEmails = marketingEmails
};
var sendEmailVerificationResponseHttpContext = await PostRegisterSendEmailVerificationAsync(sendVerificationEmailReqModel);
Assert.Equal(StatusCodes.Status204NoContent, sendEmailVerificationResponseHttpContext.Response.StatusCode);
Assert.NotNull(RegistrationTokens[requestModel.Email]);
// Now we call the finish registration endpoint with the email verification token
requestModel.EmailVerificationToken = RegistrationTokens[requestModel.Email];
var postRegisterFinishHttpContext = await PostRegisterFinishAsync(requestModel);
Assert.Equal(StatusCodes.Status200OK, postRegisterFinishHttpContext.Response.StatusCode);
var database = GetDatabaseContext();
var user = await database.Users
.SingleAsync(u => u.Email == requestModel.Email);
Assert.NotNull(user);
return user;
}
}
| IdentityApplicationFactory |
csharp | files-community__Files | src/Files.App/Data/Items/ListedItem.cs | {
"start": 17508,
"end": 19583
} | public partial class ____ : ListedItem, IGitItem
{
private volatile int statusPropertiesInitialized = 0;
public bool StatusPropertiesInitialized
{
get => statusPropertiesInitialized == 1;
set => Interlocked.Exchange(ref statusPropertiesInitialized, value ? 1 : 0);
}
private volatile int commitPropertiesInitialized = 0;
public bool CommitPropertiesInitialized
{
get => commitPropertiesInitialized == 1;
set => Interlocked.Exchange(ref commitPropertiesInitialized, value ? 1 : 0);
}
private Style? _UnmergedGitStatusIcon;
public Style? UnmergedGitStatusIcon
{
get => _UnmergedGitStatusIcon;
set => SetProperty(ref _UnmergedGitStatusIcon, value);
}
private string? _UnmergedGitStatusName;
public string? UnmergedGitStatusName
{
get => _UnmergedGitStatusName;
set => SetProperty(ref _UnmergedGitStatusName, value);
}
private DateTimeOffset? _GitLastCommitDate;
public DateTimeOffset? GitLastCommitDate
{
get => _GitLastCommitDate;
set
{
SetProperty(ref _GitLastCommitDate, value);
GitLastCommitDateHumanized = value is DateTimeOffset dto ? dateTimeFormatter.ToShortLabel(dto) : "";
}
}
private string? _GitLastCommitDateHumanized;
public string? GitLastCommitDateHumanized
{
get => _GitLastCommitDateHumanized;
set => SetProperty(ref _GitLastCommitDateHumanized, value);
}
private string? _GitLastCommitMessage;
public string? GitLastCommitMessage
{
get => _GitLastCommitMessage;
set => SetProperty(ref _GitLastCommitMessage, value);
}
private string? _GitCommitAuthor;
public string? GitLastCommitAuthor
{
get => _GitCommitAuthor;
set => SetProperty(ref _GitCommitAuthor, value);
}
private string? _GitLastCommitSha;
public string? GitLastCommitSha
{
get => _GitLastCommitSha;
set => SetProperty(ref _GitLastCommitSha, value);
}
private string? _GitLastCommitFullSha;
public string? GitLastCommitFullSha
{
get => _GitLastCommitFullSha;
set => SetProperty(ref _GitLastCommitFullSha, value);
}
}
public sealed | GitItem |
csharp | EventStore__EventStore | src/KurrentDB.Core/Messages/HttpMessage.cs | {
"start": 404,
"end": 467
} | partial class ____ {
[DerivedMessage]
public abstract | HttpMessage |
csharp | DuendeSoftware__IdentityServer | identity-server/hosts/UI/EntityFramework/Pages/Admin/ApiScopes/ApiScopeRepository.cs | {
"start": 585,
"end": 697
} | public class ____ : ApiScopeSummaryModel
{
public string? UserClaims { get; set; } = default!;
}
| ApiScopeModel |
csharp | dotnet__efcore | test/EFCore.Cosmos.FunctionalTests/Types/CosmosTemporalTypeTest.cs | {
"start": 371,
"end": 782
} | public class ____ : CosmosTypeFixtureBase<DateTime>
{
public override DateTime Value { get; } = new DateTime(2020, 1, 5, 12, 30, 45, DateTimeKind.Unspecified);
public override DateTime OtherValue { get; } = new DateTime(2022, 5, 3, 0, 0, 0, DateTimeKind.Unspecified);
protected override ITestStoreFactory TestStoreFactory => CosmosTestStoreFactory.Instance;
}
}
| DateTimeTypeFixture |
csharp | MonoGame__MonoGame | Tools/MonoGame.Effect.Compiler/Effect/MojoShader.cs | {
"start": 54375,
"end": 54583
} | public struct ____ {
/// MOJOSHADER_irExprInfo
public MOJOSHADER_irExprInfo info;
/// int
public int index;
}
[StructLayout(LayoutKind.Sequential)]
| MOJOSHADER_irTemp |
csharp | AvaloniaUI__Avalonia | src/Avalonia.Themes.Fluent/FluentTheme.xaml.cs | {
"start": 185,
"end": 349
} | public enum ____
{
Normal,
Compact
}
/// <summary>
/// Includes the fluent theme in an application.
/// </summary>
| DensityStyle |
csharp | microsoft__semantic-kernel | dotnet/test/VectorData/CosmosNoSql.ConformanceTests/TypeTests/CosmosNoSqlDataTypeTests.cs | {
"start": 1132,
"end": 1622
} | class ____ : DataTypeTests<string, DataTypeTests<string>.DefaultRecord>.Fixture
{
public override TestStore TestStore => CosmosNoSqlTestStore.Instance;
public override Type[] UnsupportedDefaultTypes { get; } =
[
typeof(byte),
typeof(short),
typeof(decimal),
typeof(Guid),
typeof(DateTime),
#if NET8_0_OR_GREATER
typeof(DateOnly),
typeof(TimeOnly)
#endif
];
}
}
| Fixture |
csharp | StackExchange__StackExchange.Redis | src/StackExchange.Redis/ResultProcessor.cs | {
"start": 103349,
"end": 105683
} | private static class ____
{
internal static readonly CommandBytes
Name = "name",
Consumers = "consumers",
Pending = "pending",
Idle = "idle",
LastDeliveredId = "last-delivered-id",
EntriesRead = "entries-read",
Lag = "lag",
IP = "ip",
Port = "port";
internal static bool TryRead(Sequence<RawResult> pairs, in CommandBytes key, ref long value)
{
var len = pairs.Length / 2;
for (int i = 0; i < len; i++)
{
if (pairs[i * 2].IsEqual(key) && pairs[(i * 2) + 1].TryGetInt64(out var tmp))
{
value = tmp;
return true;
}
}
return false;
}
internal static bool TryRead(Sequence<RawResult> pairs, in CommandBytes key, ref long? value)
{
var len = pairs.Length / 2;
for (int i = 0; i < len; i++)
{
if (pairs[i * 2].IsEqual(key) && pairs[(i * 2) + 1].TryGetInt64(out var tmp))
{
value = tmp;
return true;
}
}
return false;
}
internal static bool TryRead(Sequence<RawResult> pairs, in CommandBytes key, ref int value)
{
long tmp = default;
if (TryRead(pairs, key, ref tmp))
{
value = checked((int)tmp);
return true;
}
return false;
}
internal static bool TryRead(Sequence<RawResult> pairs, in CommandBytes key, [NotNullWhen(true)] ref string? value)
{
var len = pairs.Length / 2;
for (int i = 0; i < len; i++)
{
if (pairs[i * 2].IsEqual(key))
{
value = pairs[(i * 2) + 1].GetString()!;
return true;
}
}
return false;
}
}
| KeyValuePairParser |
csharp | EventStore__EventStore | src/KurrentDB.SourceGenerators.Tests/Messaging/Cases/Message.cs | {
"start": 464,
"end": 626
} | enum ____ {
None,
Abstract,
AbstractWithGroup,
FileScopedNamespace,
Impartial,
ImpartialNested,
Nested,
NestedDerived,
Simple,
}
}
| TestMessageGroup |
csharp | DuendeSoftware__IdentityServer | identity-server/test/IdentityServer.IntegrationTests/Clients/Setup/Users.cs | {
"start": 275,
"end": 3290
} | internal static class ____
{
public static List<TestUser> Get()
{
var users = new List<TestUser>
{
new TestUser{SubjectId = "818727", Username = "alice", Password = "alice",
Claims = new Claim[]
{
new Claim(JwtClaimTypes.Name, "Alice Smith"),
new Claim(JwtClaimTypes.GivenName, "Alice"),
new Claim(JwtClaimTypes.FamilyName, "Smith"),
new Claim(JwtClaimTypes.Email, "AliceSmith@example.com"),
new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
new Claim(JwtClaimTypes.Role, "Admin"),
new Claim(JwtClaimTypes.Role, "Geek"),
new Claim(JwtClaimTypes.WebSite, "http://alice.example.com"),
new Claim(JwtClaimTypes.Address, @"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }", IdentityServerConstants.ClaimValueTypes.Json)
}
},
new TestUser{SubjectId = "88421113", Username = "bob", Password = "bob",
Claims = new Claim[]
{
new Claim(JwtClaimTypes.Name, "Bob Smith"),
new Claim(JwtClaimTypes.GivenName, "Bob"),
new Claim(JwtClaimTypes.FamilyName, "Smith"),
new Claim(JwtClaimTypes.Email, "BobSmith@example.com"),
new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
new Claim(JwtClaimTypes.Role, "Developer"),
new Claim(JwtClaimTypes.Role, "Geek"),
new Claim(JwtClaimTypes.WebSite, "http://bob.example.com"),
new Claim(JwtClaimTypes.Address, @"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }", IdentityServerConstants.ClaimValueTypes.Json)
}
},
new TestUser{SubjectId = "88421113", Username = "bob_no_password",
Claims = new Claim[]
{
new Claim(JwtClaimTypes.Name, "Bob Smith"),
new Claim(JwtClaimTypes.GivenName, "Bob"),
new Claim(JwtClaimTypes.FamilyName, "Smith"),
new Claim(JwtClaimTypes.Email, "BobSmith@example.com"),
new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
new Claim(JwtClaimTypes.Role, "Developer"),
new Claim(JwtClaimTypes.Role, "Geek"),
new Claim(JwtClaimTypes.WebSite, "http://bob.example.com"),
new Claim(JwtClaimTypes.Address, @"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }", IdentityServerConstants.ClaimValueTypes.Json)
}
}
};
return users;
}
}
| Users |
csharp | JamesNK__Newtonsoft.Json | Src/Newtonsoft.Json.Tests/LinqToSql/Department.cs | {
"start": 1430,
"end": 1529
} | public partial class ____
{
[JsonConverter(typeof(DepartmentConverter))]
| Department |
csharp | LibreHardwareMonitor__LibreHardwareMonitor | LibreHardwareMonitorLib/Hardware/Cpu/Amd17Cpu.cs | {
"start": 20038,
"end": 22873
} | private class ____
{
private DateTime _sampleTime = new(0);
private DateTime _lastSampleTime = new(0);
private ulong _mperf = 0;
private ulong _aperf = 0;
private ulong _mperfLast = 0;
private ulong _aperfLast = 0;
private ulong _mperfDelta = 0;
private ulong _aperfDelta = 0;
private CpuId _cpuId;
private Amd17Cpu _cpu;
public CpuId Cpu { get { return _cpuId; } }
public TimeSpan SampleDuration { get; private set; }= TimeSpan.Zero;
public double EffectiveClock { get; private set; } = 0;
public ulong MperfDelta { get { return _mperfDelta; } }
public ulong AperfDelta { get { return _aperfDelta; } }
public CpuThread(Amd17Cpu cpu, CpuId cpuId)
{
_cpu = cpu;
_cpuId = cpuId;
}
public void ReadPerformanceCounter()
{
ThreadAffinity.Set(Cpu.Affinity);
_sampleTime = DateTime.UtcNow;
// performance counter
// MSRC000_00E7, P0 state counter
_cpu._pawnModule.ReadMsr(MSR_MPERF_RO, out ulong edxeax);
_mperf = edxeax;
// MSRC000_00E8, C0 state counter
_cpu._pawnModule.ReadMsr(MSR_APERF_RO, out edxeax);
_aperf = edxeax;
}
public void UpdateMeasurements()
{
if (_mperf < _mperfLast || _aperf < _aperfLast)
{
// current measurment is invalid when _mperf or _aperf overflow
_lastSampleTime = new(0);
}
if (_lastSampleTime.Ticks == 0)
{
_lastSampleTime = _sampleTime;
_mperfLast = _mperf;
_aperfLast = _aperf;
_mperfDelta = 0;
_aperfDelta = 0;
return;
}
SampleDuration = _sampleTime - _lastSampleTime;
_lastSampleTime = _sampleTime;
_mperfDelta = _mperf - _mperfLast;
_aperfDelta = _aperf - _aperfLast;
_mperfLast = _mperf;
_aperfLast = _aperf;
if (_mperfDelta > 20000e6)
_mperfDelta = 0;
if (_aperfDelta > 20000e6)
_aperfDelta = 0;
if(_aperfDelta == 0 || _mperfDelta == 0)
{
//overflow possible, numbers are > 20 GHz
_lastSampleTime = new(0);
return;
}
//effective clock
double freq = (double)_aperfDelta / (SampleDuration.TotalMilliseconds * 1000.0);
EffectiveClock = Math.Round(freq);
}
public bool HasValidCounters()
{
return _mperfDelta > 0 && _aperfDelta > 0 && SampleDuration.Ticks > 0;
}
}
| CpuThread |
csharp | GtkSharp__GtkSharp | Source/Tools/GapiCodegen/GObjectVM.cs | {
"start": 13281,
"end": 13389
} | class ____ not supported yet ");
is_valid = false;
break;
}
}
return is_valid;
}
}
}
| is |
csharp | domaindrivendev__Swashbuckle.AspNetCore | test/WebSites/NswagClientExample/Controllers/SystemTextJsonAnimalsController.cs | {
"start": 200,
"end": 610
} | public class ____ : ControllerBase
{
[HttpPost]
[Produces("application/json")]
public void CreateAnimal([Required]SystemTextJsonAnimal animal)
{
throw new NotImplementedException();
}
}
[JsonPolymorphic(TypeDiscriminatorPropertyName = "animalType")]
[JsonDerivedType(typeof(SystemTextJsonCat), "Cat")]
[JsonDerivedType(typeof(SystemTextJsonDog), "Dog")]
| SystemTextJsonAnimalsController |
csharp | nopSolutions__nopCommerce | src/Presentation/Nop.Web/Areas/Admin/Validators/Catalog/ProductAttributeValidator.cs | {
"start": 219,
"end": 621
} | public partial class ____ : BaseNopValidator<ProductAttributeModel>
{
public ProductAttributeValidator(ILocalizationService localizationService)
{
RuleFor(x => x.Name).NotEmpty().WithMessageAwait(localizationService.GetResourceAsync("Admin.Catalog.Attributes.ProductAttributes.Fields.Name.Required"));
SetDatabaseValidationRules<ProductAttribute>();
}
} | ProductAttributeValidator |
csharp | dotnetcore__FreeSql | Providers/FreeSql.Provider.ShenTong/Curd/ShenTongSelect.cs | {
"start": 21047,
"end": 21618
} | class ____ T11 : class
{
public ShenTongSelect(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression, object dywhere) : base(orm, commonUtils, commonExpression, dywhere) { }
public override string ToSql(string field = null) => ShenTongSelect<T1>.ToSqlStatic(_commonUtils, _commonExpression, _select, _distinct, field ?? this.GetAllFieldExpressionTreeLevel2().Field, _join, _where, _groupby, _having, _orderby, _skip, _limit, _tables, this.GetTableRuleUnions(), _aliasRule, _tosqlAppendContent, _whereGlobalFilter, _orm);
}
| where |
csharp | MapsterMapper__Mapster | src/Mapster/TypeAdapterBuilder.cs | {
"start": 204,
"end": 5495
} | public class ____<TSource> : ITypeAdapterBuilder<TSource>
{
TSource Source { get; }
TSource IAdapterBuilder<TSource>.Source => Source;
TypeAdapterConfig Config { get; set; }
TypeAdapterConfig IAdapterBuilder.Config => Config;
private Dictionary<string, object>? _parameters;
Dictionary<string, object> Parameters => _parameters ??= new Dictionary<string, object>();
Dictionary<string, object> IAdapterBuilder.Parameters => Parameters;
bool IAdapterBuilder.HasParameter => _parameters != null && _parameters.Count > 0;
internal TypeAdapterBuilder(TSource source, TypeAdapterConfig config)
{
Source = source;
Config = config;
}
/// <summary>
/// Allow you to keep config and mapping inline.
/// </summary>
/// <param name="action"></param>
/// <param name="key1"></param>
/// <param name="key2"></param>
/// <returns></returns>
[SuppressMessage("ReSharper", "ExplicitCallerInfoArgument")]
public ITypeAdapterBuilder<TSource> ForkConfig(Action<TypeAdapterConfig> action,
#if !NET40
[CallerFilePath]
#endif
string key1 = "",
#if !NET40
[CallerLineNumber]
#endif
int key2 = 0)
{
Config = Config.Fork(action, key1, key2);
return this;
}
/// <summary>
/// Passing runtime value.
/// </summary>
/// <param name="name">Parameter name.</param>
/// <param name="value">Parameter value</param>
/// <returns></returns>
public ITypeAdapterBuilder<TSource> AddParameters(string name, object value)
{
Parameters.Add(name, value);
return this;
}
private MapContextScope CreateMapContextScope()
{
var scope = new MapContextScope();
var parameters = scope.Context.Parameters;
foreach (var kvp in Parameters)
{
parameters[kvp.Key] = kvp.Value;
}
return scope;
}
MapContextScope IAdapterBuilder.CreateMapContextScope() => CreateMapContextScope();
/// <summary>
/// Mapping to new type using in adapter builder scenario.
/// </summary>
/// <typeparam name="TDestination">Destination type to adopt.</typeparam>
/// <returns></returns>
public TDestination AdaptToType<TDestination>()
{
if (_parameters == null)
return Map<TDestination>();
using (CreateMapContextScope())
{
return Map<TDestination>();
}
}
/// <summary>
/// Perform mapping to type of destination in adapter builder scenario.
/// </summary>
/// <typeparam name="TDestination">Destination type to map.</typeparam>
/// <returns></returns>
private TDestination Map<TDestination>()
{
var fn = Config.GetMapFunction<TSource, TDestination>();
return fn(Source);
}
/// <summary>
/// Mapping to existing object in adapter builder scenario.
/// </summary>
/// <typeparam name="TDestination">Destination type to adopt.</typeparam>
/// <param name="destination"></param>
/// <returns></returns>
public TDestination AdaptTo<TDestination>(TDestination destination)
{
if (_parameters == null)
return MapToTarget(destination);
using (CreateMapContextScope())
{
return MapToTarget(destination);
}
}
private TDestination MapToTarget<TDestination>(TDestination destination)
{
var fn = Config.GetMapToTargetFunction<TSource, TDestination>();
return fn(Source, destination);
}
/// <summary>
/// Get mapping expression.
/// </summary>
/// <typeparam name="TDestination">Destination type to create map expression.</typeparam>
/// <returns></returns>
public Expression<Func<TSource, TDestination>> CreateMapExpression<TDestination>()
{
var tuple = new TypeTuple(typeof(TSource), typeof(TDestination));
return (Expression<Func<TSource, TDestination>>) Config.CreateMapExpression(tuple, MapType.Map);
}
/// <summary>
/// Get mapping to existing object expression.
/// </summary>
/// <typeparam name="TDestination">Destination type to create map to target expression.</typeparam>
/// <returns></returns>
public Expression<Func<TSource, TDestination, TDestination>> CreateMapToTargetExpression<TDestination>()
{
var tuple = new TypeTuple(typeof(TSource), typeof(TDestination));
return (Expression<Func<TSource, TDestination, TDestination>>) Config.CreateMapExpression(tuple, MapType.MapToTarget);
}
/// <summary>
/// Get mapping from queryable expression.
/// </summary>
/// <typeparam name="TDestination">Destination type to create projection expression.</typeparam>
/// <returns></returns>
public Expression<Func<TSource, TDestination>> CreateProjectionExpression<TDestination>()
{
var tuple = new TypeTuple(typeof(TSource), typeof(TDestination));
return (Expression<Func<TSource, TDestination>>) Config.CreateMapExpression(tuple, MapType.Projection);
}
}
}
| TypeAdapterBuilder |
csharp | unoplatform__uno | src/SamplesApp/UITests.Shared/Windows_Devices/Midi/MidiDeviceInput.xaml.cs | {
"start": 1045,
"end": 9309
} | partial class ____ : UserControl
{
/// <summary>
/// Collection of active MidiInPorts
/// </summary>
private readonly List<MidiInPort> _midiInPorts;
/// <summary>
/// Device watcher for MIDI in ports
/// </summary>
private readonly MidiDeviceWatcher _midiInDeviceWatcher;
/// <summary>
/// Constructor: Start the device watcher
/// </summary>
public MidiDeviceInput()
{
InitializeComponent();
rootGrid.DataContext = this;
// Initialize the list of active MIDI input devices
_midiInPorts = new List<MidiInPort>();
// Set up the MIDI input device watcher
_midiInDeviceWatcher = new MidiDeviceWatcher(MidiInPort.GetDeviceSelector(), UnitTestDispatcherCompat.From(this), inputDevices, InputDevices);
// Start watching for devices
_midiInDeviceWatcher.Start();
Unloaded += MidiDeviceInput_Unloaded;
}
public ObservableCollection<string> InputDevices { get; } = new ObservableCollection<string>();
public ObservableCollection<string> InputDeviceMessages { get; } = new ObservableCollection<string>();
private void MidiDeviceInput_Unloaded(object sender, RoutedEventArgs e)
{
// Stop the input device watcher
_midiInDeviceWatcher.Stop();
// Close all MidiInPorts
foreach (MidiInPort inPort in _midiInPorts)
{
inPort.Dispose();
}
_midiInPorts.Clear();
}
/// <summary>
/// Change the input MIDI device from which to receive messages
/// </summary>
/// <param name="sender">Element that fired the event</param>
/// <param name="e">Event arguments</param>
private async void inputDevices_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Get the selected input MIDI device
int selectedInputDeviceIndex = (sender as ListView).SelectedIndex;
// Try to create a MidiInPort
if (selectedInputDeviceIndex < 0)
{
// Clear input device messages
InputDeviceMessages.Clear();
InputDeviceMessages.Add("Select a MIDI input device to be able to see its messages");
inputDeviceMessages.IsEnabled = false;
NotifyUser("Select a MIDI input device to be able to see its messages");
return;
}
DeviceInformationCollection devInfoCollection = _midiInDeviceWatcher.GetDeviceInformationCollection();
if (devInfoCollection == null)
{
InputDeviceMessages.Clear();
InputDeviceMessages.Add("Device not found!");
inputDeviceMessages.IsEnabled = false;
NotifyUser("Device not found!");
return;
}
DeviceInformation devInfo = devInfoCollection[selectedInputDeviceIndex];
if (devInfo == null)
{
InputDeviceMessages.Clear();
InputDeviceMessages.Add("Device not found!");
inputDeviceMessages.IsEnabled = false;
NotifyUser("Device not found!");
return;
}
var currentMidiInputDevice = await MidiInPort.FromIdAsync(devInfo.Id);
if (currentMidiInputDevice == null)
{
NotifyUser("Unable to create MidiInPort from input device");
return;
}
// We have successfully created a MidiInPort; add the device to the list of active devices, and set up message receiving
if (!_midiInPorts.Contains(currentMidiInputDevice))
{
_midiInPorts.Add(currentMidiInputDevice);
currentMidiInputDevice.MessageReceived += MidiInputDevice_MessageReceived;
}
// Clear any previous input messages
InputDeviceMessages.Clear();
inputDeviceMessages.IsEnabled = true;
NotifyUser("Input Device selected successfully! Waiting for messages...");
}
/// <summary>
/// Display the received MIDI message in a readable format
/// </summary>
/// <param name="sender">Element that fired the event</param>
/// <param name="args">The received message</param>
private async void MidiInputDevice_MessageReceived(MidiInPort sender, MidiMessageReceivedEventArgs args)
{
IMidiMessage receivedMidiMessage = args.Message;
// Build the received MIDI message into a readable format
StringBuilder outputMessage = new StringBuilder();
outputMessage.Append(receivedMidiMessage.Timestamp.ToString()).Append(", Type: ").Append(receivedMidiMessage.Type);
// Add MIDI message parameters to the output, depending on the type of message
switch (receivedMidiMessage.Type)
{
case MidiMessageType.NoteOff:
var noteOffMessage = (MidiNoteOffMessage)receivedMidiMessage;
outputMessage.Append(", Channel: ").Append(noteOffMessage.Channel).Append(", Note: ").Append(noteOffMessage.Note).Append(", Velocity: ").Append(noteOffMessage.Velocity);
break;
case MidiMessageType.NoteOn:
var noteOnMessage = (MidiNoteOnMessage)receivedMidiMessage;
outputMessage.Append(", Channel: ").Append(noteOnMessage.Channel).Append(", Note: ").Append(noteOnMessage.Note).Append(", Velocity: ").Append(noteOnMessage.Velocity);
break;
case MidiMessageType.PolyphonicKeyPressure:
var polyphonicKeyPressureMessage = (MidiPolyphonicKeyPressureMessage)receivedMidiMessage;
outputMessage.Append(", Channel: ").Append(polyphonicKeyPressureMessage.Channel).Append(", Note: ").Append(polyphonicKeyPressureMessage.Note).Append(", Pressure: ").Append(polyphonicKeyPressureMessage.Pressure);
break;
case MidiMessageType.ControlChange:
var controlChangeMessage = (MidiControlChangeMessage)receivedMidiMessage;
outputMessage.Append(", Channel: ").Append(controlChangeMessage.Channel).Append(", Controller: ").Append(controlChangeMessage.Controller).Append(", Value: ").Append(controlChangeMessage.ControlValue);
break;
case MidiMessageType.ProgramChange:
var programChangeMessage = (MidiProgramChangeMessage)receivedMidiMessage;
outputMessage.Append(", Channel: ").Append(programChangeMessage.Channel).Append(", Program: ").Append(programChangeMessage.Program);
break;
case MidiMessageType.ChannelPressure:
var channelPressureMessage = (MidiChannelPressureMessage)receivedMidiMessage;
outputMessage.Append(", Channel: ").Append(channelPressureMessage.Channel).Append(", Pressure: ").Append(channelPressureMessage.Pressure);
break;
case MidiMessageType.PitchBendChange:
var pitchBendChangeMessage = (MidiPitchBendChangeMessage)receivedMidiMessage;
outputMessage.Append(", Channel: ").Append(pitchBendChangeMessage.Channel).Append(", Bend: ").Append(pitchBendChangeMessage.Bend);
break;
case MidiMessageType.SystemExclusive:
var systemExclusiveMessage = (MidiSystemExclusiveMessage)receivedMidiMessage;
outputMessage.Append(", ");
// Read the SysEx bufffer
var sysExDataReader = DataReader.FromBuffer(systemExclusiveMessage.RawData);
while (sysExDataReader.UnconsumedBufferLength > 0)
{
byte byteRead = sysExDataReader.ReadByte();
// Pad with leading zero if necessary
outputMessage.Append(byteRead.ToString("X2", CultureInfo.InvariantCulture)).Append(' ');
}
break;
case MidiMessageType.MidiTimeCode:
var timeCodeMessage = (MidiTimeCodeMessage)receivedMidiMessage;
outputMessage.Append(", FrameType: ").Append(timeCodeMessage.FrameType).Append(", Values: ").Append(timeCodeMessage.Values);
break;
case MidiMessageType.SongPositionPointer:
var songPositionPointerMessage = (MidiSongPositionPointerMessage)receivedMidiMessage;
outputMessage.Append(", Beats: ").Append(songPositionPointerMessage.Beats);
break;
case MidiMessageType.SongSelect:
var songSelectMessage = (MidiSongSelectMessage)receivedMidiMessage;
outputMessage.Append(", Song: ").Append(songSelectMessage.Song);
break;
case MidiMessageType.None:
throw new InvalidOperationException();
}
// Skip TimingClock and ActiveSensing messages to avoid overcrowding the list. Commment this check out to see all messages
if ((receivedMidiMessage.Type != MidiMessageType.TimingClock) && (receivedMidiMessage.Type != MidiMessageType.ActiveSensing))
{
// Use the Dispatcher to update the messages on the UI thread
await UnitTestDispatcherCompat.From(this).RunAsync(UnitTestDispatcherCompat.Priority.Normal, () =>
{
InputDeviceMessages.Insert(0, outputMessage.ToString());
NotifyUser("Message received successfully!");
});
}
}
private void NotifyUser(string message)
{
statusBlock.Text = message;
}
}
}
| MidiDeviceInput |
csharp | dotnet__maui | src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue1908.cs | {
"start": 116,
"end": 511
} | public class ____ : _IssuesUITest
{
public Issue1908(TestDevice testDevice) : base(testDevice)
{
}
public override string Issue => "Image reuse";
[Test]
[Category(UITestCategories.Image)]
[Category(UITestCategories.Compatibility)]
public void Issue1908Test()
{
App.WaitForElement("OASIS1");
App.WaitForElement("OASIS2");
App.WaitForElement("OASIS1");
}
}
}
| Issue1908 |
csharp | microsoft__garnet | libs/storage/Tsavorite/cs/test/ObjectRecoveryTest2.cs | {
"start": 5921,
"end": 6609
} | public class ____ : BinaryObjectSerializer<MyKey>
{
public override void Serialize(ref MyKey key)
{
var bytes = System.Text.Encoding.UTF8.GetBytes(key.name);
writer.Write(4 + bytes.Length);
writer.Write(key.key);
writer.Write(bytes);
}
public override void Deserialize(out MyKey key)
{
key = new MyKey();
var size = reader.ReadInt32();
key.key = reader.ReadInt32();
var bytes = new byte[size - 4];
_ = reader.Read(bytes, 0, size - 4);
key.name = System.Text.Encoding.UTF8.GetString(bytes);
}
}
| MyKeySerializer |
csharp | VerifyTests__Verify | src/ModuleInitDocs/AutoVerify.cs | {
"start": 1,
"end": 61
} | public class ____
{
#region StaticAutoVerify
| AutoVerify |
csharp | mysql-net__MySqlConnector | src/MySqlConnector/ColumnReaders/BinaryFloatColumnReader.cs | {
"start": 120,
"end": 391
} | internal sealed class ____ : ColumnReader
{
public static BinaryFloatColumnReader Instance { get; } = new();
public override object ReadValue(ReadOnlySpan<byte> data, ColumnDefinitionPayload columnDefinition) =>
MemoryMarshal.Read<float>(data);
}
| BinaryFloatColumnReader |
csharp | AutoMapper__AutoMapper | src/IntegrationTests/ValueTransformerTests.cs | {
"start": 6842,
"end": 7016
} | public class ____
{
[Key]
public int Id { get; set; }
public int Value { get; set; }
}
| Source |
csharp | cake-build__cake | src/Cake.Common.Tests/Unit/Build/AppVeyor/Data/AppVeyorCommitInfoTests.cs | {
"start": 1204,
"end": 1636
} | public sealed class ____
{
[Fact]
public void Should_Return_Correct_Value()
{
// Given
var info = new AppVeyorInfoFixture().CreateCommitInfo();
// When
var result = info.ExtendedMessage;
// Then
Assert.Equal("Testing stuff.", result);
}
}
| TheExtendedMessageProperty |
csharp | dotnet__aspnetcore | src/Hosting/Abstractions/src/IApplicationLifetime.cs | {
"start": 642,
"end": 1545
} | public interface ____
{
/// <summary>
/// Triggered when the application host has fully started and is about to wait
/// for a graceful shutdown.
/// </summary>
CancellationToken ApplicationStarted { get; }
/// <summary>
/// Triggered when the application host is performing a graceful shutdown.
/// Requests may still be in flight. Shutdown will block until this event completes.
/// </summary>
CancellationToken ApplicationStopping { get; }
/// <summary>
/// Triggered when the application host is performing a graceful shutdown.
/// All requests should be complete at this point. Shutdown will block
/// until this event completes.
/// </summary>
CancellationToken ApplicationStopped { get; }
/// <summary>
/// Requests termination of the current application.
/// </summary>
void StopApplication();
}
| IApplicationLifetime |
csharp | microsoft__PowerToys | src/settings-ui/Settings.UI/SettingsXAML/Controls/Dashboard/ShortcutConflictControl.xaml.cs | {
"start": 697,
"end": 5515
} | partial class ____ : UserControl, INotifyPropertyChanged
{
private static readonly ResourceLoader ResourceLoader = Helpers.ResourceLoaderInstance.ResourceLoader;
private static bool _telemetryEventSent;
public static readonly DependencyProperty AllHotkeyConflictsDataProperty =
DependencyProperty.Register(
nameof(AllHotkeyConflictsData),
typeof(AllHotkeyConflictsData),
typeof(ShortcutConflictControl),
new PropertyMetadata(null, OnAllHotkeyConflictsDataChanged));
public AllHotkeyConflictsData AllHotkeyConflictsData
{
get => (AllHotkeyConflictsData)GetValue(AllHotkeyConflictsDataProperty);
set => SetValue(AllHotkeyConflictsDataProperty, value);
}
public int ConflictCount
{
get
{
if (AllHotkeyConflictsData == null)
{
return 0;
}
int count = 0;
if (AllHotkeyConflictsData.InAppConflicts != null)
{
foreach (var inAppConflict in AllHotkeyConflictsData.InAppConflicts)
{
if (!inAppConflict.ConflictIgnored)
{
count++;
}
}
}
if (AllHotkeyConflictsData.SystemConflicts != null)
{
foreach (var systemConflict in AllHotkeyConflictsData.SystemConflicts)
{
if (!systemConflict.ConflictIgnored)
{
count++;
}
}
}
return count;
}
}
public string ConflictText
{
get
{
var count = ConflictCount;
return count switch
{
0 => ResourceLoader.GetString("ShortcutConflictControl_NoConflictsFound"),
1 => ResourceLoader.GetString("ShortcutConflictControl_SingleConflictFound"),
_ => string.Format(
System.Globalization.CultureInfo.CurrentCulture,
ResourceLoader.GetString("ShortcutConflictControl_MultipleConflictsFound"),
count),
};
}
}
public bool HasConflicts => ConflictCount > 0;
private static void OnAllHotkeyConflictsDataChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is ShortcutConflictControl control)
{
control.UpdateProperties();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void UpdateProperties()
{
OnPropertyChanged(nameof(ConflictCount));
OnPropertyChanged(nameof(ConflictText));
OnPropertyChanged(nameof(HasConflicts));
// Update visibility based on conflict count
if (HasConflicts)
{
VisualStateManager.GoToState(this, "ConflictState", true);
}
else
{
VisualStateManager.GoToState(this, "NoConflictState", true);
}
if (!_telemetryEventSent && HasConflicts)
{
// Log telemetry event when conflicts are detected
PowerToysTelemetry.Log.WriteEvent(new ShortcutConflictDetectedEvent()
{
ConflictCount = ConflictCount,
});
_telemetryEventSent = true;
}
}
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public ShortcutConflictControl()
{
InitializeComponent();
DataContext = this;
UpdateProperties();
}
private void ShortcutConflictBtn_Click(object sender, RoutedEventArgs e)
{
if (AllHotkeyConflictsData == null)
{
return;
}
// Log telemetry event when user clicks the shortcut conflict button
PowerToysTelemetry.Log.WriteEvent(new ShortcutConflictControlClickedEvent()
{
ConflictCount = this.ConflictCount,
});
// Create and show the new window instead of dialog
var conflictWindow = new ShortcutConflictWindow();
// Show the window
conflictWindow.Activate();
}
}
}
| ShortcutConflictControl |
csharp | microsoft__PowerToys | src/modules/cmdpal/ext/Microsoft.CmdPal.Ext.Calc/Helper/ISettingsInterface.cs | {
"start": 270,
"end": 500
} | public interface ____
{
public CalculateEngine.TrigMode TrigUnit { get; }
public bool InputUseEnglishFormat { get; }
public bool OutputUseEnglishFormat { get; }
public bool CloseOnEnter { get; }
}
| ISettingsInterface |
csharp | nopSolutions__nopCommerce | src/Presentation/Nop.Web/Models/Catalog/PriceRangeModel.cs | {
"start": 133,
"end": 454
} | public partial record ____ : BaseNopModel
{
#region Properties
/// <summary>
/// Gets or sets the "from" price
/// </summary>
public decimal? From { get; set; }
/// <summary>
/// Gets or sets the "to" price
/// </summary>
public decimal? To { get; set; }
#endregion
} | PriceRangeModel |
csharp | dotnet__efcore | src/EFCore.Relational/Metadata/Conventions/RelationalPropertyJsonPropertyNameAttributeConvention.cs | {
"start": 549,
"end": 1974
} | public class ____ : PropertyAttributeConventionBase<JsonPropertyNameAttribute>
{
/// <summary>
/// Creates a new instance of <see cref="RelationalPropertyJsonPropertyNameAttributeConvention" />.
/// </summary>
/// <param name="dependencies">Parameter object containing dependencies for this convention.</param>
/// <param name="relationalDependencies"> Parameter object containing relational dependencies for this convention.</param>
public RelationalPropertyJsonPropertyNameAttributeConvention(
ProviderConventionSetBuilderDependencies dependencies,
RelationalConventionSetBuilderDependencies relationalDependencies)
: base(dependencies)
=> RelationalDependencies = relationalDependencies;
/// <summary>
/// Relational provider-specific dependencies for this service.
/// </summary>
protected virtual RelationalConventionSetBuilderDependencies RelationalDependencies { get; }
/// <inheritdoc />
protected override void ProcessPropertyAdded(
IConventionPropertyBuilder propertyBuilder,
JsonPropertyNameAttribute attribute,
MemberInfo clrMember,
IConventionContext context)
{
if (!string.IsNullOrWhiteSpace(attribute.Name))
{
propertyBuilder.HasJsonPropertyName(attribute.Name, fromDataAnnotation: true);
}
}
}
| RelationalPropertyJsonPropertyNameAttributeConvention |
csharp | cake-build__cake | src/Cake.Frosting/FrostingTaskTeardown.cs | {
"start": 293,
"end": 357
} | class ____ the teardown logic of a task.
/// </summary>
| for |
csharp | NLog__NLog | tests/NLog.UnitTests/LayoutRenderers/CallSiteTests.cs | {
"start": 47364,
"end": 52295
} | private class ____
{
public async Task AsyncMethod5(LogFactory logFactory)
{
await AMinimalAsyncMethod();
var logger = logFactory.GetCurrentClassLogger();
logger.Debug("dude");
}
private async Task AMinimalAsyncMethod()
{
await Task.Delay(1); // Ensure it always becomes async, and it is not inlined
}
}
private async Task AMinimalAsyncMethod()
{
await Task.Delay(1); // Ensure it always becomes async, and it is not inlined
}
#if NET35
[Fact(Skip = "NET35 not supporting async callstack")]
#elif MONO
[Fact(Skip = "Not working under MONO - not sure if unit test is wrong, or the code")]
#else
[Fact]
#endif
public void LogAfterTaskRunAwait_CleanNamesOfAsyncContinuationsIsTrue_ShouldCleanMethodName()
{
// name of the logging method
const string callsiteMethodName = nameof(LogAfterTaskRunAwait_CleanNamesOfAsyncContinuationsIsTrue_ShouldCleanMethodName);
var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:classname=false:cleannamesofasynccontinuations=true}' /></targets>
<rules>
<logger name='*' levels='Debug' writeTo='debug' />
</rules>
</nlog>").LogFactory;
Task.Run(async () =>
{
await AMinimalAsyncMethod();
var logger = logFactory.GetCurrentClassLogger();
logger.Debug("dude");
}).Wait();
logFactory.AssertDebugLastMessage(callsiteMethodName);
}
#if NET35
[Fact(Skip = "NET35 not supporting async callstack")]
#elif MONO
[Fact(Skip = "Not working under MONO - not sure if unit test is wrong, or the code")]
#else
[Fact]
#endif
public void LogAfterTaskRunAwait_CleanNamesOfAsyncContinuationsIsTrue_ShouldCleanClassName()
{
// full name of the logging method
string callsiteMethodFullName = $"{GetType()}.{nameof(LogAfterTaskRunAwait_CleanNamesOfAsyncContinuationsIsTrue_ShouldCleanClassName)}";
var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:classname=true:includenamespace=true:cleannamesofasynccontinuations=true:cleanNamesOfAnonymousDelegates=true}' /></targets>
<rules>
<logger name='*' levels='Debug' writeTo='debug' />
</rules>
</nlog>").LogFactory;
Task.Run(async () =>
{
await AMinimalAsyncMethod();
var logger = logFactory.GetCurrentClassLogger();
logger.Debug("dude");
}).Wait();
logFactory.AssertDebugLastMessage(callsiteMethodFullName);
new InnerClassAsyncMethod6().AsyncMethod6a(logFactory).Wait();
logFactory.AssertDebugLastMessage($"{typeof(InnerClassAsyncMethod6).ToString()}.AsyncMethod6a");
new InnerClassAsyncMethod6().AsyncMethod6b(logFactory);
logFactory.AssertDebugLastMessage($"{typeof(InnerClassAsyncMethod6).ToString()}.AsyncMethod6b");
}
#if NET35
[Fact(Skip = "NET35 not supporting async callstack")]
#elif MONO
[Fact(Skip = "Not working under MONO - not sure if unit test is wrong, or the code")]
#else
[Fact]
#endif
public void LogAfterTaskRunAwait_CleanNamesOfAsyncContinuationsIsFalse_ShouldNotCleanNames()
{
#if !NETFRAMEWORK
if (IsLinux())
{
Console.WriteLine("[SKIP] LogAfterTaskRunAwait_CleanNamesOfAsyncContinuationsIsFalse_ShouldNotCleanNames because unstable with NET8");
return;
}
#endif
var logFactory = new LogFactory().Setup().LoadConfigurationFromXml(@"
<nlog>
<targets><target name='debug' type='Debug' layout='${callsite:includenamespace=true:cleannamesofasynccontinuations=false}' /></targets>
<rules>
<logger name='*' levels='Debug' writeTo='debug' />
</rules>
</nlog>").LogFactory;
Task.Run(async () =>
{
await AMinimalAsyncMethod();
var logger = logFactory.GetCurrentClassLogger();
logger.Debug("dude");
}).Wait();
logFactory.AssertDebugLastMessageContains("NLog.UnitTests.LayoutRenderers.CallSiteTests");
logFactory.AssertDebugLastMessageContains("MoveNext");
}
| InnerClassAsyncMethod5 |
csharp | dotnet__maui | src/Compatibility/Core/src/MacOS/Extensions/NSImageExtensions.cs | {
"start": 204,
"end": 807
} | public static class ____
{
public static NSImage ResizeTo(this NSImage self, CoreGraphics.CGSize newSize)
{
if (self == null)
return null;
self.ResizingMode = NSImageResizingMode.Stretch;
var resizedImage = new NSImage(newSize);
resizedImage.LockFocus();
self.Size = newSize;
NSGraphicsContext.CurrentContext.ImageInterpolation = NSImageInterpolation.High;
self.Draw(CoreGraphics.CGPoint.Empty, new CoreGraphics.CGRect(0, 0, newSize.Width, newSize.Height),
NSCompositingOperation.Copy, 1.0f);
resizedImage.UnlockFocus();
return resizedImage;
}
}
} | NSImageExtensions |
csharp | dotnet__aspnetcore | src/Identity/Core/src/SignInManager.cs | {
"start": 63523,
"end": 63692
} | internal sealed class ____
{
public required TUser User { get; init; }
public string? LoginProvider { get; init; }
}
| TwoFactorAuthenticationInfo |
csharp | dotnet__orleans | src/api/Orleans.Transactions.TestKit.Base/Orleans.Transactions.TestKit.Base.cs | {
"start": 180682,
"end": 182588
} | partial class ____ : global::Orleans.TransactionTaskRequest
{
public global::Orleans.Transactions.Abstractions.ITransactionCommitOperation<global::Orleans.Transactions.TestKit.IRemoteCommitService> arg0;
public Invokable_ITransactionCommitterTestGrain_GrainReference_C44BE2A4(global::Orleans.Serialization.Serializer<global::Orleans.Transactions.OrleansTransactionAbortedException> base0, System.IServiceProvider base1) : base(default(Serialization.Serializer<Transactions.OrleansTransactionAbortedException>)!, default!) { }
public override void Dispose() { }
public override string GetActivityName() { throw null; }
public override object GetArgument(int index) { throw null; }
public override int GetArgumentCount() { throw null; }
public override string GetInterfaceName() { throw null; }
public override System.Type GetInterfaceType() { throw null; }
public override System.Reflection.MethodInfo GetMethod() { throw null; }
public override string GetMethodName() { throw null; }
public override object GetTarget() { throw null; }
protected override System.Threading.Tasks.Task InvokeInner() { throw null; }
public override void SetArgument(int index, object value) { }
public override void SetTarget(global::Orleans.Serialization.Invocation.ITargetHolder holder) { }
}
[System.CodeDom.Compiler.GeneratedCode("OrleansCodeGen", "9.0.0.0")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[global::Orleans.CompoundTypeAlias(new[] { "inv", typeof(global::Orleans.Runtime.GrainReference), typeof(global::Orleans.Transactions.TestKit.ITransactionCoordinatorGrain), "2760260D" })]
public sealed | Invokable_ITransactionCommitterTestGrain_GrainReference_C44BE2A4 |
csharp | dotnet__orleans | test/Grains/TestGrains/DeadlockGrain.cs | {
"start": 3495,
"end": 5950
} | public class ____ : Grain, ICallChainReentrancyGrain
{
private TaskCompletionSource _unblocker = new(TaskCreationOptions.RunContinuationsAsynchronously);
private string Id => this.GetPrimaryKeyString();
public async Task CallChain(ICallChainObserver observer, List<(string TargetGrain, ReentrancyCallType CallType)> callChain, int callIndex, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
await observer.OnEnter(Id, callIndex);
try
{
if (callChain.Count == 0)
{
return;
}
var op = callChain[0];
var target = GrainFactory.GetGrain<ICallChainReentrancyGrain>(op.TargetGrain);
var newChain = callChain.Skip(1).ToList();
var nextCallIndex = callIndex + 1;
switch (op.CallType)
{
case ReentrancyCallType.Regular:
await Task.WhenAny(_unblocker.Task, target.CallChain(observer, newChain, nextCallIndex, cancellationToken));
break;
case ReentrancyCallType.AllowCallChainReentrancy:
{
using var _ = RequestContext.AllowCallChainReentrancy();
await Task.WhenAny(_unblocker.Task, target.CallChain(observer, newChain, nextCallIndex, cancellationToken));
break;
}
case ReentrancyCallType.SuppressCallChainReentrancy:
{
using var _ = RequestContext.SuppressCallChainReentrancy();
await Task.WhenAny(_unblocker.Task, target.CallChain(observer, newChain, nextCallIndex, cancellationToken));
break;
}
}
}
finally
{
await observer.OnExit(Id, callIndex);
}
}
public Task UnblockWaiters(CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
_unblocker?.SetResult();
_unblocker = new(TaskCreationOptions.RunContinuationsAsynchronously);
return Task.CompletedTask;
}
}
}
| CallChainReentrancyGrain |
csharp | MassTransit__MassTransit | tests/MassTransit.Tests/Middleware/Agents/Agent_Specs.cs | {
"start": 5479,
"end": 6798
} | class ____ :
SimpleContext
{
readonly SimpleContext _context;
public ActiveSimpleContext(SimpleContext context, CancellationToken cancellationToken)
{
CancellationToken = cancellationToken;
_context = context;
}
public CancellationToken CancellationToken { get; }
bool PipeContext.HasPayloadType(Type payloadType)
{
return _context.HasPayloadType(payloadType);
}
bool PipeContext.TryGetPayload<TPayload>(out TPayload payload)
{
return _context.TryGetPayload(out payload);
}
TPayload PipeContext.GetOrAddPayload<TPayload>(PayloadFactory<TPayload> payloadFactory)
{
return _context.GetOrAddPayload(payloadFactory);
}
T PipeContext.AddOrUpdatePayload<T>(PayloadFactory<T> addFactory, UpdatePayloadFactory<T> updateFactory)
{
return _context.AddOrUpdatePayload(addFactory, updateFactory);
}
string SimpleContext.Value => _context.Value;
void SimpleContext.Invalidate()
{
_context.Invalidate();
}
}
| ActiveSimpleContext |
csharp | ServiceStack__ServiceStack.OrmLite | src/ServiceStack.OrmLite/OrmLiteReadExpressionsApiAsync.cs | {
"start": 339,
"end": 15777
} | public static class ____
{
/// <summary>
/// Returns results from using a LINQ Expression. E.g:
/// <para>db.Select<Person>(x => x.Age > 40)</para>
/// </summary>
public static Task<List<T>> SelectAsync<T>(this IDbConnection dbConn, Expression<Func<T, bool>> predicate, CancellationToken token = default)
{
return dbConn.Exec(dbCmd => dbCmd.SelectAsync(predicate, token));
}
/// <summary>
/// Returns results from using an SqlExpression lambda. E.g:
/// <para>db.Select(db.From<Person>().Where(x => x.Age > 40))</para>
/// </summary>
public static Task<List<T>> SelectAsync<T>(this IDbConnection dbConn, SqlExpression<T> expression, CancellationToken token = default)
{
return dbConn.Exec(dbCmd => dbCmd.SelectAsync(expression, token));
}
/// <summary>
/// Project results from a number of joined tables into a different model
/// </summary>
public static Task<List<Into>> SelectAsync<Into, From>(this IDbConnection dbConn, SqlExpression<From> expression, CancellationToken token = default)
{
return dbConn.Exec(dbCmd => dbCmd.SelectAsync<Into, From>(expression, token));
}
/// <summary>
/// Returns results from using an SqlExpression lambda. E.g:
/// <para>db.SelectAsync(db.From<Person>().Where(x => x.Age > 40))</para>
/// </summary>
public static Task<List<T>> SelectAsync<T>(this IDbConnection dbConn, ISqlExpression expression, CancellationToken token = default) => dbConn.Exec(dbCmd => dbCmd.SqlListAsync<T>(expression.SelectInto<T>(QueryType.Select), expression.Params, token));
public static Task<List<Tuple<T, T2>>> SelectMultiAsync<T, T2>(this IDbConnection dbConn, SqlExpression<T> expression, CancellationToken token = default) => dbConn.Exec(dbCmd => dbCmd.SelectMultiAsync<T, T2>(expression, token));
public static Task<List<Tuple<T, T2, T3>>> SelectMultiAsync<T, T2, T3>(this IDbConnection dbConn, SqlExpression<T> expression, CancellationToken token = default) => dbConn.Exec(dbCmd => dbCmd.SelectMultiAsync<T, T2, T3>(expression, token));
public static Task<List<Tuple<T, T2, T3, T4>>> SelectMultiAsync<T, T2, T3, T4>(this IDbConnection dbConn, SqlExpression<T> expression, CancellationToken token = default) => dbConn.Exec(dbCmd => dbCmd.SelectMultiAsync<T, T2, T3, T4>(expression, token));
public static Task<List<Tuple<T, T2, T3, T4, T5>>> SelectMultiAsync<T, T2, T3, T4, T5>(this IDbConnection dbConn, SqlExpression<T> expression, CancellationToken token = default) => dbConn.Exec(dbCmd => dbCmd.SelectMultiAsync<T, T2, T3, T4, T5>(expression, token));
public static Task<List<Tuple<T, T2, T3, T4, T5, T6>>> SelectMultiAsync<T, T2, T3, T4, T5, T6>(this IDbConnection dbConn, SqlExpression<T> expression, CancellationToken token = default) => dbConn.Exec(dbCmd => dbCmd.SelectMultiAsync<T, T2, T3, T4, T5, T6>(expression, token));
public static Task<List<Tuple<T, T2, T3, T4, T5, T6, T7>>> SelectMultiAsync<T, T2, T3, T4, T5, T6, T7>(this IDbConnection dbConn, SqlExpression<T> expression, CancellationToken token = default) => dbConn.Exec(dbCmd => dbCmd.SelectMultiAsync<T, T2, T3, T4, T5, T6, T7>(expression, token));
public static Task<List<Tuple<T, T2, T3, T4, T5, T6, T7, T8>>> SelectMultiAsync<T, T2, T3, T4, T5, T6, T7, T8>(this IDbConnection dbConn, SqlExpression<T> expression, CancellationToken token = default) => dbConn.Exec(dbCmd => dbCmd.SelectMultiAsync<T, T2, T3, T4, T5, T6, T7, T8>(expression, token));
public static Task<List<Tuple<T, T2>>> SelectMultiAsync<T, T2>(this IDbConnection dbConn, SqlExpression<T> expression, string[] tableSelects, CancellationToken token = default) => dbConn.Exec(dbCmd => dbCmd.SelectMultiAsync<T, T2>(expression, tableSelects, token));
public static Task<List<Tuple<T, T2, T3>>> SelectMultiAsync<T, T2, T3>(this IDbConnection dbConn, SqlExpression<T> expression, string[] tableSelects, CancellationToken token = default) => dbConn.Exec(dbCmd => dbCmd.SelectMultiAsync<T, T2, T3>(expression, tableSelects, token));
public static Task<List<Tuple<T, T2, T3, T4>>> SelectMultiAsync<T, T2, T3, T4>(this IDbConnection dbConn, SqlExpression<T> expression, string[] tableSelects, CancellationToken token = default) => dbConn.Exec(dbCmd => dbCmd.SelectMultiAsync<T, T2, T3, T4>(expression, tableSelects, token));
public static Task<List<Tuple<T, T2, T3, T4, T5>>> SelectMultiAsync<T, T2, T3, T4, T5>(this IDbConnection dbConn, SqlExpression<T> expression, string[] tableSelects, CancellationToken token = default) => dbConn.Exec(dbCmd => dbCmd.SelectMultiAsync<T, T2, T3, T4, T5>(expression, tableSelects, token));
public static Task<List<Tuple<T, T2, T3, T4, T5, T6>>> SelectMultiAsync<T, T2, T3, T4, T5, T6>(this IDbConnection dbConn, SqlExpression<T> expression, string[] tableSelects, CancellationToken token = default) => dbConn.Exec(dbCmd => dbCmd.SelectMultiAsync<T, T2, T3, T4, T5, T6>(expression, tableSelects, token));
public static Task<List<Tuple<T, T2, T3, T4, T5, T6, T7>>> SelectMultiAsync<T, T2, T3, T4, T5, T6, T7>(this IDbConnection dbConn, SqlExpression<T> expression, string[] tableSelects, CancellationToken token = default) => dbConn.Exec(dbCmd => dbCmd.SelectMultiAsync<T, T2, T3, T4, T5, T6, T7>(expression, tableSelects, token));
public static Task<List<Tuple<T, T2, T3, T4, T5, T6, T7, T8>>> SelectMultiAsync<T, T2, T3, T4, T5, T6, T7, T8>(this IDbConnection dbConn, SqlExpression<T> expression, string[] tableSelects, CancellationToken token = default) => dbConn.Exec(dbCmd => dbCmd.SelectMultiAsync<T, T2, T3, T4, T5, T6, T7, T8>(expression, tableSelects, token));
/// <summary>
/// Returns a single result from using a LINQ Expression. E.g:
/// <para>db.Single<Person>(x => x.Age == 42)</para>
/// </summary>
public static Task<T> SingleAsync<T>(this IDbConnection dbConn, Expression<Func<T, bool>> predicate, CancellationToken token = default)
{
return dbConn.Exec(dbCmd => dbCmd.SingleAsync(predicate, token));
}
/// <summary>
/// Returns results from using an SqlExpression lambda. E.g:
/// <para>db.SingleAsync<Person>(x => x.Age > 40)</para>
/// </summary>
public static Task<T> SingleAsync<T>(this IDbConnection dbConn, SqlExpression<T> expression, CancellationToken token = default)
{
return dbConn.Exec(dbCmd => dbCmd.SingleAsync(expression, token));
}
/// <summary>
/// Returns results from using an SqlExpression lambda. E.g:
/// <para>db.SingleAsync(db.From<Person>().Where(x => x.Age > 40))</para>
/// </summary>
public static Task<T> SingleAsync<T>(this IDbConnection dbConn, ISqlExpression expression, CancellationToken token = default)
{
return dbConn.Exec(dbCmd => dbCmd.SingleAsync<T>(expression.SelectInto<T>(QueryType.Single), expression.Params, token));
}
/// <summary>
/// Returns a scalar result from using an SqlExpression lambda. E.g:
/// <para>db.Scalar<Person, int>(x => Sql.Max(x.Age))</para>
/// </summary>
public static Task<TKey> ScalarAsync<T, TKey>(this IDbConnection dbConn, Expression<Func<T, object>> field, CancellationToken token = default)
{
return dbConn.Exec(dbCmd => dbCmd.ScalarAsync<T, TKey>(field, token));
}
/// <summary>
/// Returns a scalar result from using an SqlExpression lambda. E.g:
/// <para>db.Scalar<Person, int>(x => Sql.Max(x.Age), , x => x.Age < 50)</para>
/// </summary>
public static Task<TKey> ScalarAsync<T, TKey>(this IDbConnection dbConn,
Expression<Func<T, object>> field, Expression<Func<T, bool>> predicate, CancellationToken token = default)
{
return dbConn.Exec(dbCmd => dbCmd.ScalarAsync<T, TKey>(field, predicate, token));
}
/// <summary>
/// Returns the count of rows that match the LINQ expression, E.g:
/// <para>db.Count<Person>(x => x.Age < 50)</para>
/// </summary>
public static Task<long> CountAsync<T>(this IDbConnection dbConn, Expression<Func<T, bool>> expression, CancellationToken token = default)
{
return dbConn.Exec(dbCmd => dbCmd.CountAsync(expression, token));
}
/// <summary>
/// Returns the count of rows that match the supplied SqlExpression, E.g:
/// <para>db.Count(db.From<Person>().Where(x => x.Age < 50))</para>
/// </summary>
public static Task<long> CountAsync<T>(this IDbConnection dbConn, SqlExpression<T> expression, CancellationToken token = default)
{
return dbConn.Exec(dbCmd => dbCmd.CountAsync(expression, token));
}
public static Task<long> CountAsync<T>(this IDbConnection dbConn, CancellationToken token = default)
{
var expression = dbConn.GetDialectProvider().SqlExpression<T>();
return dbConn.Exec(dbCmd => dbCmd.CountAsync(expression, token));
}
/// <summary>
/// Return the number of rows returned by the supplied expression
/// </summary>
public static Task<long> RowCountAsync<T>(this IDbConnection dbConn, SqlExpression<T> expression, CancellationToken token = default)
{
return dbConn.Exec(dbCmd => dbCmd.RowCountAsync(expression, token));
}
/// <summary>
/// Return the number of rows returned by the supplied sql
/// </summary>
public static Task<long> RowCountAsync(this IDbConnection dbConn, string sql, object anonType = null, CancellationToken token = default)
{
return dbConn.Exec(dbCmd => dbCmd.RowCountAsync(sql, anonType, token));
}
/// <summary>
/// Returns results with references from using a LINQ Expression. E.g:
/// <para>db.LoadSelectAsync<Person>(x => x.Age > 40)</para>
/// </summary>
public static Task<List<T>> LoadSelectAsync<T>(this IDbConnection dbConn, Expression<Func<T, bool>> predicate, string[] include = null, CancellationToken token = default)
{
return dbConn.Exec(dbCmd => dbCmd.LoadSelectAsync(predicate, include, token));
}
/// <summary>
/// Returns results with references from using a LINQ Expression. E.g:
/// <para>db.LoadSelectAsync<Person>(x => x.Age > 40, include: x => new { x.PrimaryAddress })</para>
/// </summary>
public static Task<List<T>> LoadSelectAsync<T>(this IDbConnection dbConn, Expression<Func<T, bool>> predicate, Expression<Func<T, object>> include)
{
return dbConn.Exec(dbCmd => dbCmd.LoadSelectAsync(predicate, include.GetFieldNames()));
}
/// <summary>
/// Returns results with references from using an SqlExpression lambda. E.g:
/// <para>db.LoadSelectAsync(db.From<Person>().Where(x => x.Age > 40))</para>
/// </summary>
public static Task<List<T>> LoadSelectAsync<T>(this IDbConnection dbConn, SqlExpression<T> expression, string[] include = null, CancellationToken token = default)
{
return dbConn.Exec(dbCmd => dbCmd.LoadSelectAsync(expression, include, token));
}
/// <summary>
/// Returns results with references from using an SqlExpression lambda. E.g:
/// <para>db.LoadSelectAsync(db.From<Person>().Where(x => x.Age > 40), include:q.OnlyFields)</para>
/// </summary>
public static Task<List<T>> LoadSelectAsync<T>(this IDbConnection dbConn, SqlExpression<T> expression, IEnumerable<string> include, CancellationToken token = default)
{
return dbConn.Exec(dbCmd => dbCmd.LoadSelectAsync(expression, include, token));
}
/// <summary>
/// Project results with references from a number of joined tables into a different model
/// </summary>
public static Task<List<Into>> LoadSelectAsync<Into, From>(this IDbConnection dbConn, SqlExpression<From> expression, string[] include = null, CancellationToken token = default)
{
return dbConn.Exec(dbCmd => dbCmd.LoadSelectAsync<Into, From>(expression, include, token));
}
/// <summary>
/// Project results with references from a number of joined tables into a different model
/// </summary>
public static Task<List<Into>> LoadSelectAsync<Into, From>(this IDbConnection dbConn, SqlExpression<From> expression, IEnumerable<string> include, CancellationToken token = default)
{
return dbConn.Exec(dbCmd => dbCmd.LoadSelectAsync<Into, From>(expression, include, token));
}
/// <summary>
/// Project results with references from a number of joined tables into a different model
/// </summary>
public static Task<List<Into>> LoadSelectAsync<Into, From>(this IDbConnection dbConn, SqlExpression<From> expression, Expression<Func<Into, object>> include)
{
return dbConn.Exec(dbCmd => dbCmd.LoadSelectAsync<Into, From>(expression, include.GetFieldNames()));
}
/// <summary>
/// Return ADO.NET reader.GetSchemaTable() in a DataTable
/// </summary>
/// <param name="dbConn"></param>
/// <param name="sql"></param>
/// <returns></returns>
public static Task<DataTable> GetSchemaTableAsync(this IDbConnection dbConn, string sql, CancellationToken token=default) =>
dbConn.Exec(dbCmd => dbCmd.GetSchemaTableAsync(sql, token));
/// <summary>
/// Get Table Column Schemas for specified table
/// </summary>
public static Task<ColumnSchema[]> GetTableColumnsAsync<T>(this IDbConnection dbConn, CancellationToken token=default) =>
dbConn.Exec(dbCmd => dbCmd.GetTableColumnsAsync(typeof(T), token));
/// <summary>
/// Get Table Column Schemas for specified table
/// </summary>
public static Task<ColumnSchema[]> GetTableColumnsAsync(this IDbConnection dbConn, Type type, CancellationToken token=default) =>
dbConn.Exec(dbCmd => dbCmd.GetTableColumnsAsync(type, token));
/// <summary>
/// Get Table Column Schemas for result-set return from specified sql
/// </summary>
public static Task<ColumnSchema[]> GetTableColumnsAsync(this IDbConnection dbConn, string sql, CancellationToken token=default) =>
dbConn.Exec(dbCmd => dbCmd.GetTableColumnsAsync(sql, token));
public static Task EnableForeignKeysCheckAsync(this IDbConnection dbConn, CancellationToken token=default) =>
dbConn.Exec(dbCmd => dbConn.GetDialectProvider().EnableForeignKeysCheckAsync(dbCmd, token));
public static Task DisableForeignKeysCheckAsync(this IDbConnection dbConn, CancellationToken token=default) =>
dbConn.Exec(dbCmd => dbConn.GetDialectProvider().DisableForeignKeysCheckAsync(dbCmd, token));
}
}
#endif | OrmLiteReadExpressionsApiAsync |
csharp | dotnet__aspnetcore | src/Mvc/Mvc.Core/src/ModelBinding/Metadata/IMetadataDetailsProvider.cs | {
"start": 239,
"end": 504
} | interface ____ a provider of metadata details about model objects. Implementations should
/// implement one or more of <see cref="IBindingMetadataProvider"/>, <see cref="IDisplayMetadataProvider"/>,
/// and <see cref="IValidationMetadataProvider"/>.
/// </summary>
| for |
csharp | microsoft__semantic-kernel | dotnet/src/Plugins/Plugins.UnitTests/Web/Tavily/TavilyTextSearchTests.cs | {
"start": 435,
"end": 15544
} | public sealed class ____ : IDisposable
{
/// <summary>
/// Initializes a new instance of the <see cref="TavilyTextSearchTests"/> class.
/// </summary>
public TavilyTextSearchTests()
{
this._messageHandlerStub = new MultipleHttpMessageHandlerStub();
this._httpClient = new HttpClient(this._messageHandlerStub, disposeHandler: false);
this._kernel = new Kernel();
}
[Fact]
public void AddTavilyTextSearchSucceeds()
{
// Arrange
var builder = Kernel.CreateBuilder();
// Act
builder.AddTavilyTextSearch(apiKey: "ApiKey");
var kernel = builder.Build();
// Assert
Assert.IsType<TavilyTextSearch>(kernel.Services.GetRequiredService<ITextSearch>());
}
[Fact]
public async Task SearchReturnsSuccessfullyAsync()
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(WhatIsTheSKResponseJson));
// Create an ITextSearch instance using Tavily search
var textSearch = new TavilyTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient });
// Act
KernelSearchResults<string> result = await textSearch.SearchAsync("What is the Semantic Kernel?", new() { Top = 4, Skip = 0 });
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Results);
var resultList = await result.Results.ToListAsync();
Assert.NotNull(resultList);
Assert.Equal(4, resultList.Count);
foreach (var stringResult in resultList)
{
Assert.NotEmpty(stringResult);
}
}
[Fact]
public async Task GetTextSearchResultsReturnsSuccessfullyAsync()
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(WhatIsTheSKResponseJson));
// Create an ITextSearch instance using Tavily search
var textSearch = new TavilyTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient });
// Act
KernelSearchResults<TextSearchResult> result = await textSearch.GetTextSearchResultsAsync("What is the Semantic Kernel?", new() { Top = 4, Skip = 0 });
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Results);
var resultList = await result.Results.ToListAsync();
Assert.NotNull(resultList);
Assert.Equal(4, resultList.Count);
foreach (var textSearchResult in resultList)
{
Assert.NotNull(textSearchResult.Name);
Assert.NotNull(textSearchResult.Value);
Assert.NotNull(textSearchResult.Link);
}
}
[Fact]
public async Task GetSearchResultsReturnsSuccessfullyAsync()
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(WhatIsTheSKResponseJson));
// Create an ITextSearch instance using Tavily search
var textSearch = new TavilyTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient, IncludeRawContent = true });
// Act
KernelSearchResults<object> result = await textSearch.GetSearchResultsAsync("What is the Semantic Kernel?", new() { Top = 4, Skip = 0 });
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Results);
var resultList = await result.Results.ToListAsync();
Assert.NotNull(resultList);
Assert.Equal(4, resultList.Count);
foreach (TavilySearchResult searchResult in resultList)
{
Assert.NotNull(searchResult.Title);
Assert.NotNull(searchResult.Url);
Assert.NotNull(searchResult.Content);
Assert.NotNull(searchResult.RawContent);
Assert.True(searchResult.Score > 0);
}
}
[Fact]
public async Task SearchWithCustomStringMapperReturnsSuccessfullyAsync()
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(WhatIsTheSKResponseJson));
// Create an ITextSearch instance using Tavily search
var textSearch = new TavilyTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient, StringMapper = new TestTextSearchStringMapper() });
// Act
KernelSearchResults<string> result = await textSearch.SearchAsync("What is the Semantic Kernel?", new() { Top = 4, Skip = 0 });
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Results);
var resultList = await result.Results.ToListAsync();
Assert.NotNull(resultList);
Assert.Equal(4, resultList.Count);
foreach (var stringResult in resultList)
{
Assert.NotEmpty(stringResult);
var searchResult = JsonSerializer.Deserialize<TavilySearchResult>(stringResult);
Assert.NotNull(searchResult);
}
}
[Fact]
public async Task GetTextSearchResultsWithCustomResultMapperReturnsSuccessfullyAsync()
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(WhatIsTheSKResponseJson));
// Create an ITextSearch instance using Tavily search
var textSearch = new TavilyTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient, ResultMapper = new TestTextSearchResultMapper() });
// Act
KernelSearchResults<TextSearchResult> result = await textSearch.GetTextSearchResultsAsync("What is the Semantic Kernel?", new() { Top = 4, Skip = 0 });
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Results);
var resultList = await result.Results.ToListAsync();
Assert.NotNull(resultList);
Assert.Equal(4, resultList.Count);
foreach (var textSearchResult in resultList)
{
Assert.NotNull(textSearchResult);
Assert.Equal(textSearchResult.Name, textSearchResult.Name?.ToUpperInvariant());
Assert.Equal(textSearchResult.Value, textSearchResult.Value?.ToUpperInvariant());
Assert.Equal(textSearchResult.Link, textSearchResult.Link?.ToUpperInvariant());
}
}
[Fact]
public async Task SearchWithAnswerReturnsSuccessfullyAsync()
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(WhatIsTheSKResponseJson));
// Create an ITextSearch instance using Tavily search
var textSearch = new TavilyTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient, IncludeAnswer = true });
// Act
KernelSearchResults<string> result = await textSearch.SearchAsync("What is the Semantic Kernel?", new() { Top = 4, Skip = 0 });
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Results);
var resultList = await result.Results.ToListAsync();
Assert.NotNull(resultList);
Assert.Equal(5, resultList.Count);
foreach (var stringResult in resultList)
{
Assert.NotEmpty(stringResult);
}
}
[Fact]
public async Task SearchWithImagesReturnsSuccessfullyAsync()
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(WhatIsTheSKResponseJson));
// Create an ITextSearch instance using Tavily search
var textSearch = new TavilyTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient, IncludeImages = true });
// Act
KernelSearchResults<string> result = await textSearch.SearchAsync("What is the Semantic Kernel?", new() { Top = 4, Skip = 0 });
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Results);
var resultList = await result.Results.ToListAsync();
Assert.NotNull(resultList);
Assert.Equal(9, resultList.Count);
foreach (var stringResult in resultList)
{
Assert.NotEmpty(stringResult);
}
}
[Fact]
public async Task GetTextSearchResultsWithAnswerReturnsSuccessfullyAsync()
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(WhatIsTheSKResponseJson));
// Create an ITextSearch instance using Tavily search
var textSearch = new TavilyTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient, IncludeAnswer = true });
// Act
KernelSearchResults<TextSearchResult> result = await textSearch.GetTextSearchResultsAsync("What is the Semantic Kernel?", new() { Top = 4, Skip = 0 });
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Results);
var resultList = await result.Results.ToListAsync();
Assert.NotNull(resultList);
Assert.Equal(4, resultList.Count);
foreach (var textSearchResult in resultList)
{
Assert.NotNull(textSearchResult.Name);
Assert.NotNull(textSearchResult.Value);
Assert.NotNull(textSearchResult.Link);
}
}
[Fact]
public async Task GetTextSearchResultsWithImagesReturnsSuccessfullyAsync()
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(WhatIsTheSKResponseJson));
// Create an ITextSearch instance using Tavily search
var textSearch = new TavilyTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient, IncludeImages = true, IncludeImageDescriptions = true });
// Act
KernelSearchResults<TextSearchResult> result = await textSearch.GetTextSearchResultsAsync("What is the Semantic Kernel?", new() { Top = 4, Skip = 0 });
// Assert
Assert.NotNull(result);
Assert.NotNull(result.Results);
var resultList = await result.Results.ToListAsync();
Assert.NotNull(resultList);
Assert.Equal(9, resultList.Count);
foreach (var textSearchResult in resultList)
{
Assert.NotNull(textSearchResult.Name);
Assert.NotNull(textSearchResult.Value);
Assert.NotNull(textSearchResult.Link);
}
}
[Theory]
[InlineData("topic", "general", "{\"query\":\"What is the Semantic Kernel?\",\"topic\":\"general\",\"max_results\":4}")]
[InlineData("topic", "news", "{\"query\":\"What is the Semantic Kernel?\",\"topic\":\"news\",\"max_results\":4}")]
[InlineData("time_range", "day", "{\"query\":\"What is the Semantic Kernel?\",\"max_results\":4,\"time_range\":\"day\"}")]
[InlineData("time_range", "week", "{\"query\":\"What is the Semantic Kernel?\",\"max_results\":4,\"time_range\":\"week\"}")]
[InlineData("time_range", "month", "{\"query\":\"What is the Semantic Kernel?\",\"max_results\":4,\"time_range\":\"month\"}")]
[InlineData("time_range", "year", "{\"query\":\"What is the Semantic Kernel?\",\"max_results\":4,\"time_range\":\"year\"}")]
[InlineData("time_range", "d", "{\"query\":\"What is the Semantic Kernel?\",\"max_results\":4,\"time_range\":\"d\"}")]
[InlineData("time_range", "w", "{\"query\":\"What is the Semantic Kernel?\",\"max_results\":4,\"time_range\":\"w\"}")]
[InlineData("time_range", "m", "{\"query\":\"What is the Semantic Kernel?\",\"max_results\":4,\"time_range\":\"m\"}")]
[InlineData("time_range", "y", "{\"query\":\"What is the Semantic Kernel?\",\"max_results\":4,\"time_range\":\"y\"}")]
[InlineData("days", 5, "{\"query\":\"What is the Semantic Kernel?\",\"max_results\":4,\"days\":5}")]
[InlineData("include_domain", "devblogs.microsoft.com", "{\"query\":\"What is the Semantic Kernel?\",\"max_results\":4,\"include_domains\":[\"devblogs.microsoft.com\"]}")]
[InlineData("exclude_domain", "devblogs.microsoft.com", "{\"query\":\"What is the Semantic Kernel?\",\"max_results\":4,\"exclude_domains\":[\"devblogs.microsoft.com\"]}")]
public async Task BuildsCorrectRequestForEqualityFilterAsync(string paramName, object paramValue, string request)
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(SiteFilterDevBlogsResponseJson));
// Create an ITextSearch instance using Tavily search
var textSearch = new TavilyTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient });
// Act
TextSearchOptions searchOptions = new() { Top = 4, Skip = 0, Filter = new TextSearchFilter().Equality(paramName, paramValue) };
KernelSearchResults<object> result = await textSearch.GetSearchResultsAsync("What is the Semantic Kernel?", searchOptions);
// Assert
var requestContents = this._messageHandlerStub.RequestContents;
Assert.Single(requestContents);
Assert.NotNull(requestContents[0]);
var actualRequest = Encoding.UTF8.GetString(requestContents[0]!);
Assert.Equal(request, Encoding.UTF8.GetString(requestContents[0]!));
}
[Theory]
[InlineData("fooBar", "baz")]
public async Task DoesNotBuildRequestForInvalidQueryParameterAsync(string paramName, object paramValue)
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(SiteFilterDevBlogsResponseJson));
TextSearchOptions searchOptions = new() { Top = 4, Skip = 0, Filter = new TextSearchFilter().Equality(paramName, paramValue) };
// Create an ITextSearch instance using Tavily search
var textSearch = new TavilyTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient });
// Act && Assert
var e = await Assert.ThrowsAsync<ArgumentException>(async () => await textSearch.GetSearchResultsAsync("What is the Semantic Kernel?", searchOptions));
Assert.Equal("Unknown equality filter clause field name 'fooBar', must be one of topic,time_range,days,include_domain,exclude_domain (Parameter 'searchOptions')", e.Message);
}
[Fact]
public async Task DoesNotBuildRequestForInvalidQueryAsync()
{
// Arrange
this._messageHandlerStub.AddJsonResponse(File.ReadAllText(SiteFilterDevBlogsResponseJson));
// Create an ITextSearch instance using Tavily search
var textSearch = new TavilyTextSearch(apiKey: "ApiKey", options: new() { HttpClient = this._httpClient });
// Act && Assert
var e = await Assert.ThrowsAsync<ArgumentNullException>(async () => await textSearch.GetSearchResultsAsync(null!));
Assert.Equal("Value cannot be null. (Parameter 'query')", e.Message);
}
/// <inheritdoc/>
public void Dispose()
{
this._messageHandlerStub.Dispose();
this._httpClient.Dispose();
GC.SuppressFinalize(this);
}
#region private
private const string WhatIsTheSKResponseJson = "./TestData/tavily_what_is_the_semantic_kernel.json";
private const string SiteFilterDevBlogsResponseJson = "./TestData/tavily_site_filter_devblogs_microsoft.com.json";
private readonly MultipleHttpMessageHandlerStub _messageHandlerStub;
private readonly HttpClient _httpClient;
private readonly Kernel _kernel;
/// <summary>
/// Test mapper which converts a TavilyWebPage search result to a string using JSON serialization.
/// </summary>
| TavilyTextSearchTests |
csharp | grandnode__grandnode2 | src/Web/Grand.Web.Admin/Controllers/CollectionController.cs | {
"start": 902,
"end": 18019
} | public class ____ : BaseAdminController
{
#region Constructors
public CollectionController(
ICollectionViewModelService collectionViewModelService,
ICollectionService collectionService,
IContextAccessor contextAccessor,
IStoreService storeService,
ILanguageService languageService,
ITranslationService translationService,
IGroupService groupService,
IPictureViewModelService pictureViewModelService)
{
_collectionViewModelService = collectionViewModelService;
_collectionService = collectionService;
_contextAccessor = contextAccessor;
_storeService = storeService;
_languageService = languageService;
_translationService = translationService;
_groupService = groupService;
_pictureViewModelService = pictureViewModelService;
}
#endregion
#region Utilities
protected async Task<(bool allow, string message)> CheckAccessToCollection(Collection collection)
{
if (collection == null) return (false, "Collection not exists");
if (await _groupService.IsStaff(_contextAccessor.WorkContext.CurrentCustomer))
if (!(!collection.LimitedToStores ||
(collection.Stores.Contains(_contextAccessor.WorkContext.CurrentCustomer.StaffStoreId) &&
collection.LimitedToStores)))
return (false, "This is not your collection");
return (true, null);
}
#endregion
#region Fields
private readonly ICollectionViewModelService _collectionViewModelService;
private readonly ICollectionService _collectionService;
private readonly IContextAccessor _contextAccessor;
private readonly IStoreService _storeService;
private readonly ILanguageService _languageService;
private readonly ITranslationService _translationService;
private readonly IGroupService _groupService;
private readonly IPictureViewModelService _pictureViewModelService;
#endregion
#region List
public IActionResult Index()
{
return RedirectToAction("List");
}
public async Task<IActionResult> List()
{
var storeId = _contextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var model = new CollectionListModel();
model.AvailableStores.Add(new SelectListItem
{ Text = _translationService.GetResource("Admin.Common.All"), Value = "" });
foreach (var s in (await _storeService.GetAllStores()).Where(x =>
x.Id == storeId || string.IsNullOrWhiteSpace(storeId)))
model.AvailableStores.Add(new SelectListItem { Text = s.Shortcut, Value = s.Id });
return View(model);
}
[PermissionAuthorizeAction(PermissionActionName.List)]
[HttpPost]
public async Task<IActionResult> List(DataSourceRequest command, CollectionListModel model)
{
if (await _groupService.IsStaff(_contextAccessor.WorkContext.CurrentCustomer))
model.SearchStoreId = _contextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var collections = await _collectionService.GetAllCollections(model.SearchCollectionName,
model.SearchStoreId, command.Page - 1, command.PageSize, true);
var gridModel = new DataSourceResult {
Data = collections.Select(x => x.ToModel()),
Total = collections.TotalCount
};
return Json(gridModel);
}
#endregion
#region Create / Edit / Delete
[PermissionAuthorizeAction(PermissionActionName.Create)]
public async Task<IActionResult> Create([FromServices] CatalogSettings catalogSettings)
{
var model = new CollectionModel();
//locales
await AddLocales(_languageService, model.Locales);
//layouts
await _collectionViewModelService.PrepareLayoutsModel(model);
//discounts
await _collectionViewModelService.PrepareDiscountModel(model, null, true);
//default values
model.PageSize = catalogSettings.DefaultCollectionPageSize;
model.PageSizeOptions = catalogSettings.DefaultCollectionPageSizeOptions;
model.Published = true;
model.AllowCustomersToSelectPageSize = true;
//sort options
_collectionViewModelService.PrepareSortOptionsModel(model);
return View(model);
}
[PermissionAuthorizeAction(PermissionActionName.Edit)]
[HttpPost]
[ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]
public async Task<IActionResult> Create(CollectionModel model, bool continueEditing)
{
if (ModelState.IsValid)
{
if (await _groupService.IsStaff(_contextAccessor.WorkContext.CurrentCustomer))
model.Stores = [_contextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
var collection = await _collectionViewModelService.InsertCollectionModel(model);
Success(_translationService.GetResource("Admin.Catalog.Collections.Added"));
return continueEditing ? RedirectToAction("Edit", new { id = collection.Id }) : RedirectToAction("List");
}
//If we got this far, something failed, redisplay form
//layouts
await _collectionViewModelService.PrepareLayoutsModel(model);
//discounts
await _collectionViewModelService.PrepareDiscountModel(model, null, true);
//sort options
_collectionViewModelService.PrepareSortOptionsModel(model);
return View(model);
}
[PermissionAuthorizeAction(PermissionActionName.Preview)]
public async Task<IActionResult> Edit(string id)
{
var collection = await _collectionService.GetCollectionById(id);
if (collection == null)
//No collection found with the specified id
return RedirectToAction("List");
if (await _groupService.IsStaff(_contextAccessor.WorkContext.CurrentCustomer))
{
if (!collection.LimitedToStores || (collection.LimitedToStores &&
collection.Stores.Contains(_contextAccessor.WorkContext.CurrentCustomer.StaffStoreId) &&
collection.Stores.Count > 1))
{
Warning(_translationService.GetResource("Admin.Catalog.Collections.Permissions"));
}
else
{
if (!collection.AccessToEntityByStore(_contextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("List");
}
}
var model = collection.ToModel();
//locales
await AddLocales(_languageService, model.Locales, (locale, languageId) =>
{
locale.Name = collection.GetTranslation(x => x.Name, languageId, false);
locale.Description = collection.GetTranslation(x => x.Description, languageId, false);
locale.BottomDescription = collection.GetTranslation(x => x.BottomDescription, languageId, false);
locale.MetaKeywords = collection.GetTranslation(x => x.MetaKeywords, languageId, false);
locale.MetaDescription = collection.GetTranslation(x => x.MetaDescription, languageId, false);
locale.MetaTitle = collection.GetTranslation(x => x.MetaTitle, languageId, false);
locale.SeName = collection.GetSeName(languageId, false);
});
//layouts
await _collectionViewModelService.PrepareLayoutsModel(model);
//discounts
await _collectionViewModelService.PrepareDiscountModel(model, collection, false);
//sort options
_collectionViewModelService.PrepareSortOptionsModel(model);
return View(model);
}
[PermissionAuthorizeAction(PermissionActionName.Edit)]
[HttpPost]
[ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]
public async Task<IActionResult> Edit(CollectionModel model, bool continueEditing)
{
var collection = await _collectionService.GetCollectionById(model.Id);
if (collection == null)
//No collection found with the specified id
return RedirectToAction("List");
if (await _groupService.IsStaff(_contextAccessor.WorkContext.CurrentCustomer))
if (!collection.AccessToEntityByStore(_contextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("Edit", new { id = collection.Id });
if (ModelState.IsValid)
{
if (await _groupService.IsStaff(_contextAccessor.WorkContext.CurrentCustomer))
model.Stores = [_contextAccessor.WorkContext.CurrentCustomer.StaffStoreId];
collection = await _collectionViewModelService.UpdateCollectionModel(collection, model);
Success(_translationService.GetResource("Admin.Catalog.Collections.Updated"));
if (continueEditing)
{
//selected tab
await SaveSelectedTabIndex();
return RedirectToAction("Edit", new { id = collection.Id });
}
return RedirectToAction("List");
}
//If we got this far, something failed, redisplay form
//layouts
await _collectionViewModelService.PrepareLayoutsModel(model);
//discounts
await _collectionViewModelService.PrepareDiscountModel(model, collection, true);
//sort options
_collectionViewModelService.PrepareSortOptionsModel(model);
return View(model);
}
[PermissionAuthorizeAction(PermissionActionName.Delete)]
[HttpPost]
public async Task<IActionResult> Delete(string id)
{
var collection = await _collectionService.GetCollectionById(id);
if (collection == null)
//No collection found with the specified id
return RedirectToAction("List");
if (await _groupService.IsStaff(_contextAccessor.WorkContext.CurrentCustomer))
if (!collection.AccessToEntityByStore(_contextAccessor.WorkContext.CurrentCustomer.StaffStoreId))
return RedirectToAction("Edit", new { id = collection.Id });
if (ModelState.IsValid)
{
await _collectionViewModelService.DeleteCollection(collection);
Success(_translationService.GetResource("Admin.Catalog.Collections.Deleted"));
return RedirectToAction("List");
}
Error(ModelState);
return RedirectToAction("Edit", new { id = collection.Id });
}
#endregion
#region Picture
[PermissionAuthorizeAction(PermissionActionName.Preview)]
public async Task<IActionResult> PicturePopup(string collectionId)
{
var collection = await _collectionService.GetCollectionById(collectionId);
if (collection == null)
return Content("Collection not exist");
if (string.IsNullOrEmpty(collection.PictureId))
return Content("Picture not exist");
var permission = await CheckAccessToCollection(collection);
if (!permission.allow)
return Content(permission.message);
return View("Partials/PicturePopup",
await _pictureViewModelService.PreparePictureModel(collection.PictureId, collection.Id));
}
[PermissionAuthorizeAction(PermissionActionName.Edit)]
[HttpPost]
public async Task<IActionResult> PicturePopup(PictureModel model)
{
if (ModelState.IsValid)
{
var collection = await _collectionService.GetCollectionById(model.ObjectId);
if (collection == null)
throw new ArgumentException("No collection found with the specified id");
var permission = await CheckAccessToCollection(collection);
if (!permission.allow)
return Content(permission.message);
if (string.IsNullOrEmpty(collection.PictureId))
throw new ArgumentException("No picture found with the specified id");
if (collection.PictureId != model.Id)
throw new ArgumentException("Picture ident doesn't fit with collection");
await _pictureViewModelService.UpdatePicture(model);
return Content("");
}
Error(ModelState);
return View("Partials/PicturePopup", model);
}
#endregion
#region Export / Import
[PermissionAuthorizeAction(PermissionActionName.Export)]
public async Task<IActionResult> ExportXlsx([FromServices] IExportManager<Collection> exportManager)
{
try
{
var bytes = await exportManager.Export(await _collectionService.GetAllCollections(showHidden: true,
storeId: _contextAccessor.WorkContext.CurrentCustomer.StaffStoreId));
return File(bytes, "text/xls", "collections.xlsx");
}
catch (Exception exc)
{
Error(exc);
return RedirectToAction("List");
}
}
[PermissionAuthorizeAction(PermissionActionName.Import)]
[HttpPost]
public async Task<IActionResult> ImportFromXlsx(IFormFile importexcelfile,
[FromServices] IImportManager<CollectionDto> importManager)
{
try
{
if (importexcelfile is { Length: > 0 })
{
await importManager.Import(importexcelfile.OpenReadStream());
}
else
{
Error(_translationService.GetResource("Admin.Common.UploadFile"));
return RedirectToAction("List");
}
Success(_translationService.GetResource("Admin.Catalog.Collection.Imported"));
return RedirectToAction("List");
}
catch (Exception exc)
{
Error(exc);
return RedirectToAction("List");
}
}
#endregion
#region Products
[PermissionAuthorizeAction(PermissionActionName.Preview)]
[HttpPost]
public async Task<IActionResult> ProductList(DataSourceRequest command, string collectionId)
{
var collection = await _collectionService.GetCollectionById(collectionId);
var permission = await CheckAccessToCollection(collection);
if (!permission.allow)
return ErrorForKendoGridJson(permission.message);
var (collectionProductModels, totalCount) =
await _collectionViewModelService.PrepareCollectionProductModel(collectionId, _contextAccessor.StoreContext.CurrentStore.Id,
command.Page, command.PageSize);
var gridModel = new DataSourceResult {
Data = collectionProductModels.ToList(),
Total = totalCount
};
return Json(gridModel);
}
[PermissionAuthorizeAction(PermissionActionName.Edit)]
[HttpPost]
public async Task<IActionResult> ProductUpdate(CollectionModel.CollectionProductModel model)
{
if (ModelState.IsValid)
{
await _collectionViewModelService.ProductUpdate(model);
return new JsonResult("");
}
return ErrorForKendoGridJson(ModelState);
}
[PermissionAuthorizeAction(PermissionActionName.Edit)]
[HttpPost]
public async Task<IActionResult> ProductDelete(CollectionModel.CollectionProductModel model)
{
if (ModelState.IsValid)
{
await _collectionViewModelService.ProductDelete(model.Id, model.ProductId);
return new JsonResult("");
}
return ErrorForKendoGridJson(ModelState);
}
[PermissionAuthorizeAction(PermissionActionName.Edit)]
public async Task<IActionResult> ProductAddPopup(string collectionId)
{
var model = await _collectionViewModelService.PrepareAddCollectionProductModel(_contextAccessor.WorkContext.CurrentCustomer
.StaffStoreId);
model.CollectionId = collectionId;
return View(model);
}
[PermissionAuthorizeAction(PermissionActionName.Edit)]
[HttpPost]
public async Task<IActionResult> ProductAddPopupList(DataSourceRequest command,
CollectionModel.AddCollectionProductModel model)
{
if (await _groupService.IsStaff(_contextAccessor.WorkContext.CurrentCustomer))
model.SearchStoreId = _contextAccessor.WorkContext.CurrentCustomer.StaffStoreId;
var products = await _collectionViewModelService.PrepareProductModel(model, command.Page, command.PageSize);
var gridModel = new DataSourceResult {
Data = products.products.ToList(),
Total = products.totalCount
};
return Json(gridModel);
}
[PermissionAuthorizeAction(PermissionActionName.Edit)]
[HttpPost]
public async Task<IActionResult> ProductAddPopup(CollectionModel.AddCollectionProductModel model)
{
if (ModelState.IsValid)
{
if (model.SelectedProductIds != null) await _collectionViewModelService.InsertCollectionProductModel(model);
return Content("");
}
Error(ModelState);
return View(model);
}
#endregion
} | CollectionController |
csharp | xunit__xunit | src/xunit.v3.runner.common/Messages/BaseMessages/MessageSinkMessage.cs | {
"start": 565,
"end": 1751
} | public partial class ____ : IJsonDeserializable
{
/// <summary>
/// Empty traits, to be used to initialize traits values in messages.
/// </summary>
protected static IReadOnlyDictionary<string, IReadOnlyCollection<string>> EmptyTraits = new Dictionary<string, IReadOnlyCollection<string>>();
/// <summary>
/// Gets the string value that message properties will return, when a value was not provided
/// during deserialization.
/// </summary>
public const string UnsetStringPropertyValue = "<unset>";
/// <summary>
/// Override to deserialize the values in the dictionary into the message.
/// </summary>
/// <param name="root">The root of the JSON object</param>
protected abstract void Deserialize(IReadOnlyDictionary<string, object?> root);
/// <inheritdoc/>
public void FromJson(IReadOnlyDictionary<string, object?> root) =>
Deserialize(root);
// We don't want to do object validation on this side, because these messages are meant to be
// able to contain deserializations for both backward and forward compatible versions of the
// message, so throwing when properties are missing isn't appropriate.
static void ValidateObjectState()
{ }
}
| MessageSinkMessage |
csharp | unoplatform__uno | src/Uno.UI.Tests/BinderTests/Given_Binder.cs | {
"start": 41802,
"end": 42642
} | public partial class ____ : FrameworkElement
{
public DependencyObject SubProperty
{
get { return (DependencyObject)GetValue(SubPropertyProperty); }
set { SetValue(SubPropertyProperty, value); }
}
public static readonly DependencyProperty SubPropertyProperty =
DependencyProperty.Register("SubProperty", typeof(DependencyObject), typeof(UIDependencyObject), new PropertyMetadata(null));
public int MyValue
{
get { return (int)GetValue(MyValueProperty); }
set { SetValue(MyValueProperty, value); }
}
// Using a DependencyProperty as the backing store for MyValue. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyValueProperty =
DependencyProperty.Register("MyValue", typeof(int), typeof(UIDependencyObject), new PropertyMetadata(-1));
}
| UIDependencyObject |
csharp | dotnet__efcore | test/EFCore.Tests/Metadata/Conventions/ServicePropertyDiscoveryConventionTest.cs | {
"start": 7688,
"end": 7790
} | private class ____ : Blog
{
public ILazyLoader? Loader { get; set; }
}
| BlogOneService |
csharp | jellyfin__jellyfin | MediaBrowser.Model/Session/PlaybackStopInfo.cs | {
"start": 207,
"end": 1997
} | public class ____
{
/// <summary>
/// Gets or sets the item.
/// </summary>
/// <value>The item.</value>
public BaseItemDto Item { get; set; }
/// <summary>
/// Gets or sets the item identifier.
/// </summary>
/// <value>The item identifier.</value>
public Guid ItemId { get; set; }
/// <summary>
/// Gets or sets the session id.
/// </summary>
/// <value>The session id.</value>
public string SessionId { get; set; }
/// <summary>
/// Gets or sets the media version identifier.
/// </summary>
/// <value>The media version identifier.</value>
public string MediaSourceId { get; set; }
/// <summary>
/// Gets or sets the position ticks.
/// </summary>
/// <value>The position ticks.</value>
public long? PositionTicks { get; set; }
/// <summary>
/// Gets or sets the live stream identifier.
/// </summary>
/// <value>The live stream identifier.</value>
public string LiveStreamId { get; set; }
/// <summary>
/// Gets or sets the play session identifier.
/// </summary>
/// <value>The play session identifier.</value>
public string PlaySessionId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="PlaybackStopInfo"/> is failed.
/// </summary>
/// <value><c>true</c> if failed; otherwise, <c>false</c>.</value>
public bool Failed { get; set; }
public string NextMediaType { get; set; }
public string PlaylistItemId { get; set; }
public QueueItem[] NowPlayingQueue { get; set; }
}
}
| PlaybackStopInfo |
csharp | dotnet__orleans | test/Extensions/AWSUtils.Tests/StorageTests/DynamoDBStorageProviderTests.cs | {
"start": 761,
"end": 13340
} | public class ____
{
private readonly IProviderRuntime providerRuntime;
private readonly ITestOutputHelper output;
private readonly Dictionary<string, string> providerCfgProps = new Dictionary<string, string>();
private readonly TestEnvironmentFixture fixture;
public DynamoDBStorageProviderTests(ITestOutputHelper output, TestEnvironmentFixture fixture)
{
this.output = output;
this.fixture = fixture;
providerCfgProps["DataConnectionString"] = $"Service={AWSTestConstants.DynamoDbService}";
this.providerRuntime = new ClientProviderRuntime(
fixture.InternalGrainFactory,
fixture.Services,
fixture.Services.GetRequiredService<ClientGrainContext>());
}
[SkippableTheory, TestCategory("Functional")]
[InlineData(null, false)]
[InlineData(null, true)]
[InlineData(400_000, false)]
[InlineData(400_000, true)]
public async Task PersistenceProvider_DynamoDB_WriteRead(int? stringLength, bool useJson)
{
var testName = string.Format("{0}({1} = {2}, {3} = {4})",
nameof(PersistenceProvider_DynamoDB_WriteRead),
nameof(stringLength), stringLength == null ? "default" : stringLength.ToString(),
nameof(useJson), useJson);
var grainState = TestStoreGrainState.NewRandomState(stringLength);
EnsureEnvironmentSupportsState(grainState);
var store = await InitDynamoDBGrainStorage(useJson);
await Test_PersistenceProvider_WriteRead(testName, store, grainState);
}
[SkippableTheory, TestCategory("Functional")]
[InlineData(null, false, false)]
[InlineData(null, true, false)]
[InlineData(400_000, false, false)]
[InlineData(400_000, true, false)]
public async Task PersistenceProvider_DynamoDB_WriteClearRead(int? stringLength, bool useJson, bool useFallback)
{
var testName = string.Format("{0}({1} = {2}, {3} = {4}, {5} = {6})",
nameof(PersistenceProvider_DynamoDB_WriteClearRead),
nameof(stringLength), stringLength == null ? "default" : stringLength.ToString(),
nameof(useJson), useJson,
nameof(useFallback), useFallback);
var grainState = TestStoreGrainState.NewRandomState(stringLength);
EnsureEnvironmentSupportsState(grainState);
var store = await InitDynamoDBGrainStorage(useJson, useFallback);
await Test_PersistenceProvider_WriteClearRead(testName, store, grainState);
}
[SkippableTheory, TestCategory("Functional")]
[InlineData(null, true, false)]
[InlineData(null, false, true)]
[InlineData(400_000, true, false)]
[InlineData(400_000, false, true)]
public async Task PersistenceProvider_DynamoDB_ChangeReadFormat(int? stringLength, bool useJsonForWrite, bool useJsonForRead)
{
var testName = string.Format("{0}({1} = {2}, {3} = {4}, {5} = {6})",
nameof(PersistenceProvider_DynamoDB_ChangeReadFormat),
nameof(stringLength), stringLength == null ? "default" : stringLength.ToString(),
nameof(useJsonForWrite), useJsonForWrite,
nameof(useJsonForRead), useJsonForRead);
var grainState = TestStoreGrainState.NewRandomState(stringLength);
EnsureEnvironmentSupportsState(grainState);
var grainId = GrainId.Create("test", Guid.NewGuid().ToString("N"));
var store = await InitDynamoDBGrainStorage(useJsonForWrite);
grainState = await Test_PersistenceProvider_WriteRead(testName, store,
grainState, grainId);
store = await InitDynamoDBGrainStorage(useJsonForRead);
await Test_PersistenceProvider_Read(testName, store, grainState, grainId);
}
[SkippableTheory, TestCategory("Functional")]
[InlineData(null, true, false)]
[InlineData(null, false, true)]
[InlineData(100_000, true, false)]
[InlineData(100_000, false, true)]
public async Task PersistenceProvider_DynamoDB_ChangeWriteFormat(int? stringLength, bool useJsonForFirstWrite, bool useJsonForSecondWrite)
{
var testName = string.Format("{0}({1}={2},{3}={4},{5}={6})",
nameof(PersistenceProvider_DynamoDB_ChangeWriteFormat),
nameof(stringLength), stringLength == null ? "default" : stringLength.ToString(),
"json1stW", useJsonForFirstWrite,
"json2ndW", useJsonForSecondWrite);
var grainState = TestStoreGrainState.NewRandomState(stringLength);
EnsureEnvironmentSupportsState(grainState);
var grainId = GrainId.Create("test", Guid.NewGuid().ToString("N"));
var store = await InitDynamoDBGrainStorage(useJsonForFirstWrite);
await Test_PersistenceProvider_WriteRead(testName, store, grainState, grainId);
grainState = TestStoreGrainState.NewRandomState(stringLength);
grainState.ETag = "*";
store = await InitDynamoDBGrainStorage(useJsonForSecondWrite);
await Test_PersistenceProvider_WriteRead(testName, store, grainState, grainId);
}
[SkippableTheory, TestCategory("Functional")]
[InlineData(null, false)]
[InlineData(null, true)]
[InlineData(400_000, false)]
[InlineData(400_000, true)]
public async Task DynamoDBStorage_ConvertToFromStorageFormat(int? stringLength, bool useJson)
{
var testName = string.Format("{0}({1} = {2}, {3} = {4})",
nameof(DynamoDBStorage_ConvertToFromStorageFormat),
nameof(stringLength), stringLength == null ? "default" : stringLength.ToString(),
nameof(useJson), useJson);
var state = TestStoreGrainState.NewRandomState(stringLength);
EnsureEnvironmentSupportsState(state);
var storage = await InitDynamoDBGrainStorage(useJson);
var initialState = state.State;
var entity = new GrainStateRecord();
storage.ConvertToStorageFormat(initialState, entity);
var convertedState = storage.ConvertFromStorageFormat<TestStoreGrainState>(entity);
Assert.NotNull(convertedState);
Assert.Equal(initialState.A, convertedState.A);
Assert.Equal(initialState.B, convertedState.B);
Assert.Equal(initialState.C, convertedState.C);
}
private async Task<DynamoDBGrainStorage> InitDynamoDBGrainStorage(DynamoDBStorageOptions options)
{
DynamoDBGrainStorage store = ActivatorUtilities.CreateInstance<DynamoDBGrainStorage>(this.providerRuntime.ServiceProvider, "StorageProviderTests", options);
ISiloLifecycleSubject lifecycle = ActivatorUtilities.CreateInstance<SiloLifecycleSubject>(this.providerRuntime.ServiceProvider, NullLogger<SiloLifecycleSubject>.Instance);
store.Participate(lifecycle);
await lifecycle.OnStart();
return store;
}
private Task<DynamoDBGrainStorage> InitDynamoDBGrainStorage(bool useJson = false, bool useFallback = true)
{
var options = new DynamoDBStorageOptions
{
Service = AWSTestConstants.DynamoDbService,
};
var jsonOptions = this.providerRuntime.ServiceProvider.GetService<IOptions<OrleansJsonSerializerOptions>>();
var binarySerializer = new OrleansGrainStorageSerializer(this.providerRuntime.ServiceProvider.GetRequiredService<Serializer>());
var jsonSerializer = new JsonGrainStorageSerializer(new OrleansJsonSerializer(jsonOptions));
if (useFallback)
options.GrainStorageSerializer = useJson
? new GrainStorageSerializer(jsonSerializer, binarySerializer)
: new GrainStorageSerializer(binarySerializer, jsonSerializer);
else
options.GrainStorageSerializer = useJson ? jsonSerializer : binarySerializer;
return InitDynamoDBGrainStorage(options);
}
private async Task Test_PersistenceProvider_Read(string grainTypeName, IGrainStorage store,
GrainState<TestStoreGrainState> grainState = null, GrainId grainId = default)
{
var reference = grainId.IsDefault ? GrainId.Create("test", Guid.NewGuid().ToString("N")) : grainId;
if (grainState == null)
{
grainState = new GrainState<TestStoreGrainState>(new TestStoreGrainState());
}
var storedGrainState = new GrainState<TestStoreGrainState>(new TestStoreGrainState());
Stopwatch sw = new Stopwatch();
sw.Start();
await store.ReadStateAsync(grainTypeName, reference, storedGrainState);
TimeSpan readTime = sw.Elapsed;
this.output.WriteLine("{0} - Read time = {1}", store.GetType().FullName, readTime);
var storedState = storedGrainState.State;
Assert.Equal(grainState.State.A, storedState.A);
Assert.Equal(grainState.State.B, storedState.B);
Assert.Equal(grainState.State.C, storedState.C);
}
private async Task<GrainState<TestStoreGrainState>> Test_PersistenceProvider_WriteRead(string grainTypeName,
IGrainStorage store, GrainState<TestStoreGrainState> grainState = null, GrainId grainId = default)
{
var reference = grainId.IsDefault ? GrainId.Create("test", Guid.NewGuid().ToString("N")) : grainId;
if (grainState == null)
{
grainState = TestStoreGrainState.NewRandomState();
}
Stopwatch sw = new Stopwatch();
sw.Start();
await store.WriteStateAsync(grainTypeName, reference, grainState);
TimeSpan writeTime = sw.Elapsed;
sw.Restart();
var storedGrainState = new GrainState<TestStoreGrainState>
{
State = new TestStoreGrainState()
};
await store.ReadStateAsync(grainTypeName, reference, storedGrainState);
TimeSpan readTime = sw.Elapsed;
this.output.WriteLine("{0} - Write time = {1} Read time = {2}", store.GetType().FullName, writeTime, readTime);
Assert.Equal(grainState.State.A, storedGrainState.State.A);
Assert.Equal(grainState.State.B, storedGrainState.State.B);
Assert.Equal(grainState.State.C, storedGrainState.State.C);
return storedGrainState;
}
private async Task<GrainState<TestStoreGrainState>> Test_PersistenceProvider_WriteClearRead(string grainTypeName,
IGrainStorage store, GrainState<TestStoreGrainState> grainState = null, GrainId grainId = default)
{
var reference = grainId.IsDefault ? GrainId.Create("test", Guid.NewGuid().ToString("N")) : grainId;
if (grainState == null)
{
grainState = TestStoreGrainState.NewRandomState();
}
Stopwatch sw = new Stopwatch();
sw.Start();
await store.WriteStateAsync(grainTypeName, reference, grainState);
TimeSpan writeTime = sw.Elapsed;
sw.Restart();
await store.ClearStateAsync(grainTypeName, reference, grainState);
var storedGrainState = new GrainState<TestStoreGrainState>
{
State = new TestStoreGrainState()
};
await store.ReadStateAsync(grainTypeName, reference, storedGrainState);
TimeSpan readTime = sw.Elapsed;
this.output.WriteLine("{0} - Write time = {1} Read time = {2}", store.GetType().FullName, writeTime, readTime);
Assert.NotNull(storedGrainState.State);
Assert.Equal(default, storedGrainState.State.A);
Assert.Equal(default, storedGrainState.State.B);
Assert.Equal(default, storedGrainState.State.C);
return storedGrainState;
}
private static void EnsureEnvironmentSupportsState(GrainState<TestStoreGrainState> grainState)
{
if (!AWSTestConstants.IsDynamoDbAvailable)
throw new SkipException("Unable to connect to DynamoDB simulator");
}
}
}
| DynamoDBStorageProviderTests |
csharp | kgrzybek__modular-monolith-with-ddd | src/Modules/Payments/Application/Subscriptions/ExpireSubscriptionPayments/ExpireSubscriptionPaymentsCommandHandler.cs | {
"start": 506,
"end": 2461
} | internal class ____ : ICommandHandler<ExpireSubscriptionPaymentsCommand>
{
private readonly ISqlConnectionFactory _sqlConnectionFactory;
private readonly ICommandsScheduler _commandsScheduler;
public ExpireSubscriptionPaymentsCommandHandler(
ISqlConnectionFactory sqlConnectionFactory,
ICommandsScheduler commandsScheduler)
{
_sqlConnectionFactory = sqlConnectionFactory;
_commandsScheduler = commandsScheduler;
}
public async Task Handle(ExpireSubscriptionPaymentsCommand request, CancellationToken cancellationToken)
{
const string sql = """
SELECT
[SubscriptionPayment].PaymentId
FROM [payments].[SubscriptionPayments] AS [SubscriptionPayment]
WHERE
[SubscriptionPayment].Date > @Date
AND [SubscriptionPayment].[Status] = @Status
""";
var connection = _sqlConnectionFactory.GetOpenConnection();
var timeForPayment = TimeSpan.FromMinutes(20);
var date = SystemClock.Now.Add(timeForPayment);
var expiredSubscriptionPaymentsIds =
await connection.QueryAsync<Guid>(sql, new
{
Date = date,
Status = SubscriptionPaymentStatus.WaitingForPayment.Code
});
var expiredSubscriptionsPaymentsIdsList = expiredSubscriptionPaymentsIds.AsList();
foreach (var subscriptionPaymentId in expiredSubscriptionsPaymentsIdsList)
{
await _commandsScheduler.EnqueueAsync(
new ExpireSubscriptionPaymentCommand(subscriptionPaymentId));
}
}
}
} | ExpireSubscriptionPaymentsCommandHandler |
csharp | EventStore__EventStore | src/KurrentDB.Transport.Tcp/TcpConfiguration.cs | {
"start": 218,
"end": 626
} | public static class ____ {
public const int SocketCloseTimeoutSecs = 1;
public const int AcceptBacklogCount = 128;
public const int ConcurrentAccepts = 1;
public const int AcceptPoolSize = ConcurrentAccepts * 2;
public const int ConnectPoolSize = 32;
public const int SendReceivePoolSize = 512;
public const int BufferChunksCount = 512;
public const int SocketBufferSize = 8 * 1024;
}
| TcpConfiguration |
csharp | nopSolutions__nopCommerce | src/Presentation/Nop.Web/Areas/Admin/Components/MetaTagGeneratorViewComponent.cs | {
"start": 320,
"end": 1275
} | public partial class ____ : NopViewComponent
{
#region Filds
protected readonly ArtificialIntelligenceSettings _artificialIntelligenceSettings;
#endregion
#region Ctor
public MetaTagsGeneratorViewComponent(ArtificialIntelligenceSettings artificialIntelligenceSettings)
{
_artificialIntelligenceSettings = artificialIntelligenceSettings;
}
#endregion
#region Methods
public IViewComponentResult Invoke(MetaTagsGeneratorModel model)
{
if (!_artificialIntelligenceSettings.Enabled)
return Content(string.Empty);
if (!_artificialIntelligenceSettings.AllowMetaTitleGeneration &&
!_artificialIntelligenceSettings.AllowMetaKeywordsGeneration &&
!_artificialIntelligenceSettings.AllowMetaDescriptionGeneration)
{
return Content(string.Empty);
}
return View(model);
}
#endregion
} | MetaTagsGeneratorViewComponent |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL/Utilities/Visitors/ISchemaNodeVisitor.cs | {
"start": 2477,
"end": 3586
} | interface ____ type.
/// </summary>
void VisitInterfaceFieldArgumentDefinition(QueryArgument argument, FieldType field, IInterfaceGraphType type, ISchema schema);
/// <summary>
/// Visits directive argument.
/// </summary>
void VisitDirectiveArgumentDefinition(QueryArgument argument, Directive directive, ISchema schema);
/// <summary>
/// Visits registered within the schema <see cref="IInterfaceGraphType"/>.
/// </summary>
void VisitInterface(IInterfaceGraphType type, ISchema schema);
/// <summary>
/// Visits registered within the schema <see cref="UnionGraphType"/>.
/// </summary>
void VisitUnion(UnionGraphType type, ISchema schema);
/// <summary>
/// Visits registered within the schema <see cref="EnumerationGraphType"/>.
/// </summary>
void VisitEnum(EnumerationGraphType type, ISchema schema);
/// <summary>
/// Visits value of registered within the schema <see cref="EnumerationGraphType"/>.
/// </summary>
void VisitEnumValue(EnumValueDefinition value, EnumerationGraphType type, ISchema schema);
}
| graph |
csharp | bitwarden__server | test/Infrastructure.EFIntegration.Test/Repositories/EqualityComparers/CollectionCompare.cs | {
"start": 147,
"end": 460
} | public class ____ : IEqualityComparer<Collection>
{
public bool Equals(Collection x, Collection y)
{
return x.Name == y.Name &&
x.ExternalId == y.ExternalId;
}
public int GetHashCode([DisallowNull] Collection obj)
{
return base.GetHashCode();
}
}
| CollectionCompare |
csharp | unoplatform__uno | src/Uno.UI.RuntimeTests/IntegrationTests/common/ComboBoxHelper.cs | {
"start": 592,
"end": 5675
} | public enum ____
{
Mouse,
Touch,
Keyboard,
Gamepad,
Programmatic
};
public static async Task FocusComboBoxIfNecessary(ComboBox comboBox)
{
var comboBoxGotFocusEvent = new Event();
var gotFocusRegistration = CreateSafeEventRegistration<ComboBox, RoutedEventHandler>("GotFocus");
gotFocusRegistration.Attach(comboBox, (s, e) =>
{
LOG_OUTPUT("[ComboBox]: Got Focus Event Fired.");
comboBoxGotFocusEvent.Set();
});
bool alreadyHasFocus = false;
await RunOnUIThread(() =>
{
alreadyHasFocus = comboBox.FocusState != FocusState.Unfocused;
comboBox.Focus(FocusState.Keyboard);
});
if (!alreadyHasFocus)
{
await comboBoxGotFocusEvent.WaitForDefault();
}
}
public static async Task OpenComboBox(ComboBox comboBox, OpenMethod openMethod)
{
var comboBoxOpenedEvent = new Event();
var openedRegistration = CreateSafeEventRegistration<ComboBox, EventHandler<object>>("DropDownOpened");
openedRegistration.Attach(comboBox, (s, e) => { comboBoxOpenedEvent.Set(); });
if (openMethod == OpenMethod.Mouse)
{
TestServices.InputHelper.LeftMouseClick(comboBox);
}
else if (openMethod == OpenMethod.Touch)
{
TestServices.InputHelper.Tap(comboBox);
}
else if (openMethod == OpenMethod.Keyboard)
{
await FocusComboBoxIfNecessary(comboBox);
await TestServices.KeyboardHelper.PressKeySequence(" ");
}
else if (openMethod == OpenMethod.Gamepad)
{
await FocusComboBoxIfNecessary(comboBox);
await CommonInputHelper.Accept(InputDevice.Gamepad);
}
else if (openMethod == OpenMethod.Programmatic)
{
await RunOnUIThread(() =>
{
comboBox.IsDropDownOpen = true;
});
}
await TestServices.WindowHelper.WaitForIdle();
await comboBoxOpenedEvent.WaitForDefault();
}
public static async Task CloseComboBox(ComboBox comboBox)
{
await CloseComboBox(comboBox, CloseMethod.Programmatic);
}
public static async Task CloseComboBox(ComboBox comboBox, CloseMethod closeMethod)
{
var dropDownClosedEvent = new Event();
var dropDownClosedRegistration = CreateSafeEventRegistration<ComboBox, EventHandler<object>>("DropDownClosed");
dropDownClosedRegistration.Attach(comboBox, (s, e) => { dropDownClosedEvent.Set(); });
if (closeMethod == CloseMethod.Touch || closeMethod == CloseMethod.Mouse)
{
Rect dropdownBounds = await GetBoundsOfOpenDropdown(comboBox);
int outsideBuffer = 10; // Tap at least this far away from the dropdown in order to ensure that it closes.
var closeTapPoint = new Point(dropdownBounds.X + dropdownBounds.Width + outsideBuffer, dropdownBounds.Y + dropdownBounds.Height + outsideBuffer);
if (closeMethod == CloseMethod.Touch)
{
TestServices.InputHelper.Tap(closeTapPoint);
}
else
{
TestServices.InputHelper.LeftMouseClick(closeTapPoint);
}
}
else if (closeMethod == CloseMethod.Keyboard)
{
await CommonInputHelper.Cancel(InputDevice.Keyboard);
}
else if (closeMethod == CloseMethod.Gamepad)
{
await CommonInputHelper.Cancel(InputDevice.Gamepad);
}
else if (closeMethod == CloseMethod.Programmatic)
{
await RunOnUIThread(() =>
{
comboBox.IsDropDownOpen = false;
});
}
await dropDownClosedEvent.WaitForDefault();
await TestServices.WindowHelper.WaitForIdle();
dropDownClosedRegistration.Detach();
}
private static async Task<Rect> GetBoundsOfOpenDropdown(DependencyObject element)
{
Rect dropdownBounds = new();
await RunOnUIThread(async () =>
{
var dropdownScrollViewer = (ScrollViewer)(TreeHelper.GetVisualChildByNameFromOpenPopups("ScrollViewer", element));
Assert.IsNotNull(dropdownScrollViewer, "DropDown not found.");
dropdownBounds = await ControlHelper.GetBounds(dropdownScrollViewer);
LOG_OUTPUT("dropdownBounds: (%f, %f, %f, %f)", dropdownBounds.X, dropdownBounds.Y, dropdownBounds.Width, dropdownBounds.Height);
});
await TestServices.WindowHelper.WaitForIdle();
return dropdownBounds;
}
// Verify the selected Index on the ComboBox.
public static async Task VerifySelectedIndex(ComboBox comboBox, int expected)
{
await SelectorHelper.VerifySelectedIndex(comboBox, expected);
}
// Uses touch to select the ComboBoxItem with the specified index.
// Note: The function does not currently scroll the popup, so it won't work if the item to be selected
// is not immediately visible.
public static async Task SelectItemWithTap(ComboBox comboBox, int index)
{
await OpenComboBox(comboBox, OpenMethod.Touch);
await TestServices.WindowHelper.WaitForIdle();
Event selectionChangedEvent = new();
var selectionChangedRegistration = CreateSafeEventRegistration<ComboBox, SelectionChangedEventHandler>("SelectionChanged");
selectionChangedRegistration.Attach(comboBox, (s, e) => selectionChangedEvent.Set());
ComboBoxItem comboBoxItemToSelect = null;
await RunOnUIThread(() =>
{
comboBoxItemToSelect = (ComboBoxItem)comboBox.ContainerFromIndex(index);
THROW_IF_NULL(comboBoxItemToSelect);
});
TestServices.InputHelper.Tap(comboBoxItemToSelect);
await selectionChangedEvent.WaitForDefault();
}
}
| CloseMethod |
csharp | dotnet__maui | src/Controls/tests/Xaml.UnitTests/Issues/Gh7494.xaml.cs | {
"start": 881,
"end": 1190
} | public class ____ : ContentView
{
public static readonly BindableProperty TitleProperty = BindableProperty.Create(nameof(Title), typeof(string), typeof(Gh7494Content), default(string));
public string Title
{
get => (string)GetValue(TitleProperty);
set => SetValue(TitleProperty, value);
}
}
| Gh7494Content |
csharp | EventStore__EventStore | src/KurrentDB.Core.XUnit.Tests/TransactionLog/Chunks/TFChunkTrackerTests.cs | {
"start": 638,
"end": 5301
} | public sealed class ____ : IDisposable {
const long WriterCheckpoint = 4_500;
const int ChunkSize = 1_000;
private readonly TFChunkTracker _sut;
private readonly TestMeterListener<long> _listener;
private readonly TestMeterListener<double> _doubleListener;
private readonly FakeClock _clock = new();
public TFChunkTrackerTests() {
var meter = new Meter($"{typeof(TFChunkTrackerTests)}");
_listener = new TestMeterListener<long>(meter);
_doubleListener = new TestMeterListener<double>(meter);
var byteMetric = new CounterMetric(meter, "eventstore-io", unit: "bytes", legacyNames: false);
var eventMetric = new CounterMetric(meter, "eventstore-io", unit: "events", legacyNames: false);
var writerCheckpoint = new InMemoryCheckpoint(WriterCheckpoint);
var readTag = new KeyValuePair<string, object>("activity", "read");
_sut = new TFChunkTracker(
readDistribution: new LogicalChunkReadDistributionMetric(meter, "chunk-read-distribution", writerCheckpoint, ChunkSize),
readDurationMetric: new DurationMetric(meter, "record-read-duration", legacyNames: false, _clock),
readBytes: new CounterSubMetric(byteMetric, [readTag]),
readEvents: new CounterSubMetric(eventMetric, [readTag]));
}
public void Dispose() {
_listener.Dispose();
_doubleListener.Dispose();
}
[Fact]
public void can_observe_prepare_log() {
var prepare = CreatePrepare(
data: new byte[5],
meta: new byte[5]);
_sut.OnRead(_clock.Now, prepare, Source.Unknown);
_listener.Observe();
AssertEventsRead(1);
AssertBytesRead(10);
}
[Fact]
public void disregard_system_log() {
var system = CreateSystemRecord();
_sut.OnRead(_clock.Now, system, Source.Unknown);
_listener.Observe();
AssertEventsRead(0);
AssertBytesRead(0);
}
[Fact]
public void disregard_commit_log() {
var system = CreateCommit();
_sut.OnRead(_clock.Now, system, Source.Unknown);
_listener.Observe();
AssertEventsRead(0);
AssertBytesRead(0);
}
[Theory]
[InlineData(Source.ChunkCache)]
public void records_record_read_duration(Source source) {
var prepare = CreatePrepare(
data: new byte[5],
meta: new byte[5]);
var start = _clock.Now;
_clock.AdvanceSeconds(3);
// when
_sut.OnRead(start, prepare, source);
// then
_doubleListener.Observe();
var actual = _doubleListener.RetrieveMeasurements("record-read-duration-seconds");
Assert.Collection(
actual,
m => {
Assert.Equal(3, m.Value);
Assert.Collection(
m.Tags,
t => {
Assert.Equal("source", t.Key);
Assert.Equal(source, t.Value);
},
t => {
Assert.Equal("user", t.Key);
Assert.Equal("", t.Value);
});
});
}
[Theory]
[InlineData(5_500, -1)]
[InlineData(4_501, 0)]
[InlineData(4_500, 0)]
[InlineData(4_000, 0)]
[InlineData(3_999, 1)]
[InlineData(3_000, 1)]
[InlineData(2_000, 2)]
[InlineData(1_000, 3)]
[InlineData(999, 4)]
[InlineData(1, 4)]
[InlineData(0, 4)]
public void records_read_distribution(long logPosition, long expectedChunk) {
_sut.OnRead(
_clock.Now,
CreatePrepare(data: new byte[5], meta: new byte[5], logPosition: logPosition),
Source.Unknown);
_listener.Observe();
var actual = _listener.RetrieveMeasurements("chunk-read-distribution");
Assert.Collection(
actual,
m => {
Assert.Equal(expectedChunk, m.Value);
Assert.Empty(m.Tags);
});
}
private void AssertEventsRead(long? expectedEventsRead) =>
AssertMeasurements("eventstore-io-events", expectedEventsRead);
private void AssertBytesRead(long? expectedBytesRead) =>
AssertMeasurements("eventstore-io-bytes", expectedBytesRead);
private void AssertMeasurements(string instrumentName, long? expectedValue) {
var actual = _listener.RetrieveMeasurements(instrumentName);
if (expectedValue is null) {
Assert.Empty(actual);
} else {
Assert.Collection(
actual,
m => {
Assert.Equal(expectedValue, m.Value);
Assert.Collection(m.Tags.ToArray(), t => {
Assert.Equal("activity", t.Key);
Assert.Equal("read", t.Value);
});
});
}
}
private static PrepareLogRecord CreatePrepare(byte[] data, byte[] meta, long logPosition = 42) {
return new PrepareLogRecord(logPosition, Guid.NewGuid(), Guid.NewGuid(), 42, 42, "tests", null, 42, DateTime.Now,
PrepareFlags.Data, "type-test", null, data, meta);
}
private static SystemLogRecord CreateSystemRecord() {
return new SystemLogRecord(42, DateTime.Now, SystemRecordType.Epoch, SystemRecordSerialization.Binary, Array.Empty<byte>());
}
private static CommitLogRecord CreateCommit() {
return new CommitLogRecord(42, Guid.NewGuid(), 42, DateTime.Now, 42);
}
}
| TFChunkTrackerTests |
csharp | fluentassertions__fluentassertions | Tests/FluentAssertions.Specs/CultureAwareTesting/CulturedFactAttribute.cs | {
"start": 217,
"end": 537
} | public sealed class ____ : FactAttribute
{
#pragma warning disable CA1019 // Define accessors for attribute arguments
// ReSharper disable once UnusedParameter.Local
public CulturedFactAttribute(params string[] _) { }
#pragma warning restore CA1019 // Define accessors for attribute arguments
}
| CulturedFactAttribute |
csharp | EventStore__EventStore | src/KurrentDB.BufferManagement.Tests/BufferPoolTests.cs | {
"start": 1313,
"end": 2537
} | public class ____ : has_buffer_manager_fixture {
[Test]
public void an_index_under_zero_throws_an_argument_exception() {
BufferPool pool = new BufferPool(12, BufferManager);
Assert.Throws<ArgumentException>(() => pool[-1] = 4);
}
[Test]
public void data_that_has_been_set_can_read() {
BufferPool pool = new BufferPool(1, BufferManager);
pool[3] = 5;
Assert.AreEqual(5, pool[3]);
}
[Test]
public void length_is_updated_when_index_higher_than_count_set() {
BufferPool pool = new BufferPool(1, BufferManager);
Assert.AreEqual(0, pool.Length);
pool[3] = 5;
Assert.AreEqual(4, pool.Length);
}
[Test]
public void a_write_will_automatically_grow_the_buffer_pool() {
BufferPool pool = new BufferPool(1, BufferManager);
int initialCapacity = pool.Capacity;
pool[initialCapacity + 14] = 5;
Assert.AreEqual(initialCapacity * 2, pool.Capacity);
}
[Test]
public void a_write_past_end_will_check_out_a_buffer_from_the_buffer_pool() {
BufferPool pool = new BufferPool(1, BufferManager);
int initial = BufferManager.AvailableBuffers;
pool[pool.Capacity + 14] = 5;
Assert.AreEqual(initial - 1, BufferManager.AvailableBuffers);
}
}
[TestFixture]
| when_changing_data_in_a_bufferpool_via_indexer |
csharp | AvaloniaUI__Avalonia | src/Windows/Avalonia.Win32/DirectX/DirectXStructs.cs | {
"start": 4890,
"end": 5129
} | internal struct ____
{
public DXGI_RATIONAL RefreshRate;
public DXGI_MODE_SCANLINE_ORDER ScanlineOrdering;
public DXGI_MODE_SCALING Scaling;
public int Windowed;
}
| DXGI_SWAP_CHAIN_FULLSCREEN_DESC |
csharp | dotnet__efcore | src/EFCore.Design/Design/Internal/AppServiceProviderFactory.cs | {
"start": 728,
"end": 4825
} | public class ____
{
private readonly Assembly _startupAssembly;
private readonly IOperationReporter _reporter;
/// <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 AppServiceProviderFactory(Assembly startupAssembly, IOperationReporter reporter)
{
_startupAssembly = startupAssembly;
_reporter = reporter;
}
/// <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 virtual IServiceProvider Create(string[] args)
{
_reporter.WriteVerbose(DesignStrings.FindingServiceProvider(_startupAssembly.GetName().Name));
return CreateFromHosting(args)
?? CreateEmptyServiceProvider();
}
private IServiceProvider? CreateFromHosting(string[] args)
{
_reporter.WriteVerbose(DesignStrings.FindingHostingServices);
var serviceProviderFactory = HostFactoryResolver.ResolveServiceProviderFactory(_startupAssembly);
if (serviceProviderFactory == null)
{
_reporter.WriteVerbose(DesignStrings.NoCreateHostBuilder);
return null;
}
try
{
var services = serviceProviderFactory(args);
if (services == null)
{
_reporter.WriteWarning(DesignStrings.MalformedCreateHostBuilder);
return null;
}
_reporter.WriteVerbose(DesignStrings.UsingHostingServices);
return services.CreateScope().ServiceProvider;
}
catch (Exception ex)
{
if (ex is TargetInvocationException)
{
ex = ex.InnerException!;
}
_reporter.WriteVerbose(ex.ToString());
_reporter.WriteWarning(DesignStrings.InvokeCreateHostBuilderFailed(ex.Message));
return null;
}
}
private IServiceProvider CreateEmptyServiceProvider()
{
_reporter.WriteVerbose(DesignStrings.NoServiceProvider);
return new ServiceCollection().BuildServiceProvider();
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public static void SetEnvironment(IOperationReporter reporter)
{
var aspnetCoreEnvironment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var dotnetEnvironment = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT");
var environment = aspnetCoreEnvironment
?? dotnetEnvironment
?? "Development";
if (aspnetCoreEnvironment == null)
{
Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", environment);
}
if (dotnetEnvironment == null)
{
Environment.SetEnvironmentVariable("DOTNET_ENVIRONMENT", environment);
}
reporter.WriteVerbose(DesignStrings.UsingEnvironment(environment));
}
}
| AppServiceProviderFactory |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Fusion-vnext/src/Fusion.Execution/Execution/Nodes/OperationCompiler.cs | {
"start": 12272,
"end": 13124
} | private class ____ : SyntaxWalker<IncludeConditionCollection>
{
public static readonly IncludeConditionVisitor Instance = new();
protected override ISyntaxVisitorAction Enter(
FieldNode node,
IncludeConditionCollection context)
{
if (IncludeCondition.TryCreate(node, out var condition))
{
context.Add(condition);
}
return base.Enter(node, context);
}
protected override ISyntaxVisitorAction Enter(
InlineFragmentNode node,
IncludeConditionCollection context)
{
if (IncludeCondition.TryCreate(node, out var condition))
{
context.Add(condition);
}
return base.Enter(node, context);
}
}
| IncludeConditionVisitor |
csharp | SixLabors__ImageSharp | src/ImageSharp/PixelFormats/PixelImplementations/PixelOperations/A8.PixelOperations.cs | {
"start": 207,
"end": 333
} | public partial struct ____
{
/// <summary>
/// Provides optimized overrides for bulk operations.
/// </summary>
| A8 |
csharp | dotnet__machinelearning | docs/samples/Microsoft.ML.Samples/Dynamic/Trainers/BinaryClassification/LdSvm.cs | {
"start": 176,
"end": 4117
} | public static class ____
{
public static void Example()
{
// Create a new context for ML.NET operations. It can be used for
// exception tracking and logging, as a catalog of available operations
// and as the source of randomness. Setting the seed to a fixed number
// in this example to make outputs deterministic.
var mlContext = new MLContext(seed: 0);
// Create a list of training data points.
var dataPoints = GenerateRandomDataPoints(1000);
// Convert the list of data points to an IDataView object, which is
// consumable by ML.NET API.
var trainingData = mlContext.Data.LoadFromEnumerable(dataPoints);
// Define the trainer.
var pipeline = mlContext.BinaryClassification.Trainers
.LdSvm();
// Train the model.
var model = pipeline.Fit(trainingData);
// Create testing data. Use different random seed to make it different
// from training data.
var testData = mlContext.Data
.LoadFromEnumerable(GenerateRandomDataPoints(500, seed: 123));
// Run the model on test data set.
var transformedTestData = model.Transform(testData);
// Convert IDataView object to a list.
var predictions = mlContext.Data
.CreateEnumerable<Prediction>(transformedTestData,
reuseRowObject: false).ToList();
// Print 5 predictions.
foreach (var p in predictions.Take(5))
Console.WriteLine($"Label: {p.Label}, "
+ $"Prediction: {p.PredictedLabel}");
// Expected output:
// Label: True, Prediction: True
// Label: False, Prediction: True
// Label: True, Prediction: True
// Label: True, Prediction: True
// Label: False, Prediction: False
// Evaluate the overall metrics.
var metrics = mlContext.BinaryClassification
.EvaluateNonCalibrated(transformedTestData);
PrintMetrics(metrics);
// Expected output:
// Accuracy: 0.82
// AUC: 0.85
// F1 Score: 0.81
// Negative Precision: 0.82
// Negative Recall: 0.82
// Positive Precision: 0.81
// Positive Recall: 0.81
// TEST POSITIVE RATIO: 0.4760 (238.0/(238.0+262.0))
// Confusion table
// ||======================
// PREDICTED || positive | negative | Recall
// TRUTH ||======================
// positive || 192 | 46 | 0.8067
// negative || 46 | 216 | 0.8244
// ||======================
// Precision || 0.8067 | 0.8244 |
}
private static IEnumerable<DataPoint> GenerateRandomDataPoints(int count,
int seed = 0)
{
var random = new Random(seed);
float randomFloat() => (float)random.NextDouble();
for (int i = 0; i < count; i++)
{
var label = randomFloat() > 0.5f;
yield return new DataPoint
{
Label = label,
// Create random features that are correlated with the label.
// For data points with false label, the feature values are
// slightly increased by adding a constant.
Features = Enumerable.Repeat(label, 50)
.Select(x => x ? randomFloat() : randomFloat() +
0.1f).ToArray()
};
}
}
// Example with label and 50 feature values. A data set is a collection of
// such examples.
| LdSvm |
csharp | dotnet__extensions | src/LegacySupport/ObsoleteAttribute/ObsoleteAttribute.cs | {
"start": 1116,
"end": 1594
} | internal sealed class ____ : Attribute
{
public ObsoleteAttribute()
{
}
public ObsoleteAttribute(string? message)
{
Message = message;
}
public ObsoleteAttribute(string? message, bool error)
{
Message = message;
IsError = error;
}
public string? Message { get; }
public bool IsError { get; }
public string? DiagnosticId { get; set; }
public string? UrlFormat { get; set; }
}
#endif
| ObsoleteAttribute |
csharp | unoplatform__uno | src/Uno.UI.Tests/Windows_UI_Xaml_Markup/XamlReaderTests/TestCodedResourceDictionary.cs | {
"start": 226,
"end": 371
} | public class ____ : ResourceDictionary
{
public TestCodedResourceDictionary()
{
this["c1"] = Colors.Red;
}
}
}
| TestCodedResourceDictionary |
csharp | MassTransit__MassTransit | tests/MassTransit.RabbitMqTransport.Tests/ErrorQueue_Specs.cs | {
"start": 351,
"end": 4292
} | public class ____ :
RabbitMqTestFixture
{
[Test]
public async Task Should_have_the_correlation_id()
{
ConsumeContext<PingMessage> context = await _errorHandler;
Assert.That(context.CorrelationId, Is.EqualTo(_correlationId));
}
[Test]
public async Task Should_have_the_error_queue_header()
{
ConsumeContext<PingMessage> context = await _errorHandler;
Assert.That(context.ReceiveContext.TransportHeaders.Get(MessageHeaders.FaultInputAddress, (Uri)null), Is.EqualTo(InputQueueAddress));
}
[Test]
public async Task Should_have_the_exception()
{
ConsumeContext<PingMessage> context = await _errorHandler;
Assert.That(context.ReceiveContext.TransportHeaders.Get("MT-Fault-Message", (string)null), Is.EqualTo("This is fine, forcing death"));
}
[Test]
public async Task Should_have_the_host_machine_name()
{
ConsumeContext<PingMessage> context = await _errorHandler;
Assert.That(context.ReceiveContext.TransportHeaders.Get("MT-Host-MachineName", (string)null), Is.EqualTo(HostMetadataCache.Host.MachineName));
}
[Test]
public async Task Should_have_the_original_destination_address()
{
ConsumeContext<PingMessage> context = await _errorHandler;
Assert.That(context.DestinationAddress, Is.EqualTo(InputQueueAddress));
}
[Test]
public async Task Should_have_the_original_fault_address()
{
ConsumeContext<PingMessage> context = await _errorHandler;
Assert.That(context.FaultAddress, Is.EqualTo(BusAddress));
}
[Test]
public async Task Should_have_the_original_response_address()
{
ConsumeContext<PingMessage> context = await _errorHandler;
Assert.That(context.ResponseAddress, Is.EqualTo(BusAddress));
}
[Test]
public async Task Should_have_the_original_source_address()
{
ConsumeContext<PingMessage> context = await _errorHandler;
Assert.That(context.SourceAddress, Is.EqualTo(BusAddress));
}
[Test]
public async Task Should_have_the_reason()
{
ConsumeContext<PingMessage> context = await _errorHandler;
Assert.That(context.ReceiveContext.TransportHeaders.Get(MessageHeaders.Reason, (string)null), Is.EqualTo("fault"));
}
[Test]
public async Task Should_move_the_message_to_the_error_queue()
{
await _errorHandler;
}
Task<ConsumeContext<PingMessage>> _errorHandler;
readonly Guid? _correlationId = NewId.NextGuid();
[OneTimeSetUp]
public async Task Setup()
{
await InputQueueSendEndpoint.Send(new PingMessage(), Pipe.Execute<SendContext<PingMessage>>(context =>
{
context.CorrelationId = _correlationId;
context.ResponseAddress = Bus.Address;
context.FaultAddress = Bus.Address;
}));
}
protected override void ConfigureRabbitMqBus(IRabbitMqBusFactoryConfigurator configurator)
{
var queueName = configurator.SendTopology.ErrorQueueNameFormatter.FormatErrorQueueName(RabbitMqTestHarness.InputQueueName);
configurator.ReceiveEndpoint(queueName, x =>
{
x.PurgeOnStartup = true;
_errorHandler = Handled<PingMessage>(x);
});
}
protected override void ConfigureRabbitMqReceiveEndpoint(IRabbitMqReceiveEndpointConfigurator configurator)
{
Handler<PingMessage>(configurator, context => throw new SerializationException("This is fine, forcing death"));
}
}
[TestFixture]
| A_serialization_exception |
csharp | dotnet__aspnetcore | src/SignalR/common/Shared/TestCertificates.cs | {
"start": 295,
"end": 1644
} | internal static class ____
{
internal static X509Certificate2 GetTestCert()
{
bool useRSA = false;
if (OperatingSystem.IsWindows())
{
// Detect Win10+
var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
var major = key.GetValue("CurrentMajorVersionNumber") as int?;
var minor = key.GetValue("CurrentMinorVersionNumber") as int?;
if (major.HasValue && minor.HasValue)
{
useRSA = true;
}
}
else
{
useRSA = true;
}
if (useRSA)
{
// RSA cert, won't work on Windows 8.1 & Windows 2012 R2 using HTTP2, and ECC won't work in some Node environments
var certPath = Path.Combine(Path.GetDirectoryName(Assembly.GetCallingAssembly().Location), "TestCertificates", "testCert.pfx");
return new X509Certificate2(certPath, "testPassword");
}
else
{
// ECC cert, works on Windows 8.1 & Windows 2012 R2 using HTTP2
var certPath = Path.Combine(Path.GetDirectoryName(Assembly.GetCallingAssembly().Location), "TestCertificates", "testCertECC.pfx");
return new X509Certificate2(certPath, "testPassword");
}
}
}
| TestCertificateHelper |
csharp | bitwarden__server | src/Core/Utilities/KdfSettingsValidator.cs | {
"start": 142,
"end": 1958
} | public static class ____
{
public static IEnumerable<ValidationResult> Validate(KdfType kdfType, int kdfIterations, int? kdfMemory, int? kdfParallelism)
{
switch (kdfType)
{
case KdfType.PBKDF2_SHA256:
if (!AuthConstants.PBKDF2_ITERATIONS.InsideRange(kdfIterations))
{
yield return new ValidationResult($"KDF iterations must be between {AuthConstants.PBKDF2_ITERATIONS.Min} and {AuthConstants.PBKDF2_ITERATIONS.Max}.");
}
break;
case KdfType.Argon2id:
if (!AuthConstants.ARGON2_ITERATIONS.InsideRange(kdfIterations))
{
yield return new ValidationResult($"Argon2 iterations must be between {AuthConstants.ARGON2_ITERATIONS.Min} and {AuthConstants.ARGON2_ITERATIONS.Max}.");
}
else if (!kdfMemory.HasValue || !AuthConstants.ARGON2_MEMORY.InsideRange(kdfMemory.Value))
{
yield return new ValidationResult($"Argon2 memory must be between {AuthConstants.ARGON2_MEMORY.Min}mb and {AuthConstants.ARGON2_MEMORY.Max}mb.");
}
else if (!kdfParallelism.HasValue || !AuthConstants.ARGON2_PARALLELISM.InsideRange(kdfParallelism.Value))
{
yield return new ValidationResult($"Argon2 parallelism must be between {AuthConstants.ARGON2_PARALLELISM.Min} and {AuthConstants.ARGON2_PARALLELISM.Max}.");
}
break;
default:
break;
}
}
public static IEnumerable<ValidationResult> Validate(KdfSettings settings)
{
return Validate(settings.KdfType, settings.Iterations, settings.Memory, settings.Parallelism);
}
}
| KdfSettingsValidator |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL.Tests/Initialization/SchemaInitializationTests.cs | {
"start": 140,
"end": 3869
} | public class ____ : SchemaInitializationTestBase
{
[Fact]
public void EmptyQuerySchema_Should_Throw()
{
ShouldThrow<EmptyQuerySchema, InvalidOperationException>("An Object type 'Empty' must define one or more fields.");
}
[Fact]
public void SchemaWithDuplicateFields_Should_Throw()
{
ShouldThrow<SchemaWithDuplicateFields, InvalidOperationException>("The field 'field' must have a unique name within Object type 'Dup'; no two fields may share the same name.");
}
[Fact]
public void SchemaWithDuplicateArguments_Should_Throw()
{
ShouldThrow<SchemaWithDuplicateArguments, InvalidOperationException>("The argument 'arg' must have a unique name within field 'Dup.field'; no two field arguments may share the same name.");
}
[Fact]
public void SchemaWithDuplicateArgumentsInDirective_Should_Throw()
{
ShouldThrow<SchemaWithDuplicateArgumentsInDirective, InvalidOperationException>("The argument 'arg' must have a unique name within directive 'my'; no two directive arguments may share the same name.");
}
[Fact]
public void EmptyInterfaceSchema_Should_Throw()
{
ShouldThrow<EmptyInterfaceSchema, InvalidOperationException>("An Interface type 'Empty' must define one or more fields.");
}
[Fact]
public void SchemaWithDuplicateInterfaceFields_Should_Throw()
{
ShouldThrow<SchemaWithDuplicateInterfaceFields, InvalidOperationException>("The field 'field' must have a unique name within Interface type 'Dup'; no two fields may share the same name.");
}
[Fact]
public void SchemaWithDeprecatedAppliedDirective_Should_Not_Throw()
{
ShouldNotThrow<SchemaWithDeprecatedAppliedDirective>();
}
[Fact]
public void SchemaWithNullDirectiveArgumentWhenShouldBeNonNull_Should_Throw()
{
ShouldThrow<SchemaWithNullDirectiveArgumentWhenShouldBeNonNull, InvalidOperationException>("Directive 'test' applied to field 'MyQuery.field' explicitly specifies 'null' value for required argument 'arg'. The value must be non-null.");
}
[Fact]
public void SchemaWithArgumentsOnInputField_Should_Throw()
{
ShouldThrow<SchemaWithArgumentsOnInputField, InvalidOperationException>("The field 'id' of an Input Object type 'MyInput' must not have any arguments specified.");
}
[Fact]
public void SchemaWithNotFullSpecifiedResolvedType_Should_Throw()
{
var ex = ShouldThrowMultiple<SchemaWithNotFullSpecifiedResolvedType>();
ex.InnerExceptions.Count.ShouldBe(2);
ex.InnerExceptions[0].ShouldBeOfType<InvalidOperationException>().Message.ShouldBe("The field 'in' of an Input Object type 'InputString' must have non-null 'ResolvedType' property for all types in the chain.");
ex.InnerExceptions[1].ShouldBeOfType<InvalidOperationException>().Message.ShouldBe("The field 'not' of an Input Object type 'InputString' must have non-null 'ResolvedType' property for all types in the chain.");
}
// https://github.com/graphql-dotnet/graphql-dotnet/pull/2707/files#r757949833
[Fact]
public void SchemaWithInvalidDefault_Should_Throw()
{
ShouldThrow<SchemaWithInvalidDefault1, InvalidOperationException>("The default value of argument 'argOne' of field 'Object.field' is invalid.");
ShouldThrow<SchemaWithInvalidDefault2, InvalidOperationException>("The default value of argument 'argOne' of field 'Object.field' is invalid.");
}
[Fact]
public void SchemaWithEnumWithoutValues_Should_Throw()
{
ShouldThrow<SchemaWithEnumWithoutValues1, InvalidOperationException>("An Enum type 'EnumWithoutValues' must define one or more unique | SchemaInitializationTests |
csharp | reactiveui__Akavache | src/Samples/GetAndFetchLatestPatterns.cs | {
"start": 18264,
"end": 21225
} | public static class ____
{
/// <summary>
/// ❌ DON'T: Await GetAndFetchLatest - you'll only get the first result.
/// </summary>
public static async Task IncorrectAwaiting()
{
// This only gets the cached data (if available) and misses the fresh data!
var data = await CacheDatabase.LocalMachine
.GetAndFetchLatest("key", () => FetchDataFromApi())
.FirstAsync();
Console.WriteLine("Only got first result - missing fresh data!");
}
/// <summary>
/// ❌ DON'T: Mix separate cached retrieval with GetAndFetchLatest.
/// </summary>
public static void IncorrectSeparateRetrieval()
{
// This creates unnecessary complexity and potential race conditions
var cached = CacheDatabase.LocalMachine.GetObject<string>("key")
.FirstOrDefaultAsync();
CacheDatabase.LocalMachine.GetAndFetchLatest("key", () => FetchDataFromApi())
.Subscribe(fresh => { /* handle fresh data */ });
// Now you have to manually coordinate cached and fresh data!
}
/// <summary>
/// ❌ DON'T: Clear collections in subscriber - will clear twice!
/// </summary>
public static void IncorrectCollectionClearing()
{
var items = new List<string>();
CacheDatabase.LocalMachine.GetAndFetchLatest("items", () => FetchDataFromApi())
.Subscribe(data =>
{
items.Clear(); // This will clear both cached and fresh data!
items.AddRange(data);
});
}
/// <summary>
/// ✅ CORRECT: Use the simple replacement pattern instead.
/// </summary>
public static void CorrectApproach()
{
var items = new List<string>();
CacheDatabase.LocalMachine.GetAndFetchLatest("items", () => FetchDataFromApi())
.Subscribe(data =>
{
// Simply replace the entire collection - works for both calls
items = data.ToList();
UpdateUI(items);
});
}
private static IObservable<List<string>> FetchDataFromApi()
{
return Observable.Return(new List<string> { "item1", "item2", "item3" });
}
private static void UpdateUI(List<string> items)
{
Console.WriteLine($"UI updated with {items.Count} items");
}
}
}
#region Supporting Types
| AntiPatterns |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/StoreGeneratedTestBase.cs | {
"start": 80040,
"end": 80127
} | public record ____
{
public int Value { get; set; }
}
| WrappedIntRecord |
csharp | MassTransit__MassTransit | src/MassTransit/Middleware/CircuitBreaker/CircuitBreakerEventExtensions.cs | {
"start": 1048,
"end": 1287
} | class ____ :
CircuitBreakerOpened
{
public Opened(Exception exception)
{
Exception = exception;
}
public Exception Exception { get; }
}
}
}
| Opened |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Controls/SwipeControl/SwipeControl.cs | {
"start": 918,
"end": 65850
} | public partial class ____ : ContentControl
{
// Change to 'true' to turn on debugging outputs in Output window
//bool SwipeControlTrace.s_IsDebugOutputEnabled = false;
//bool SwipeControlTrace.s_IsVerboseDebugOutputEnabled = false;
private const double c_epsilon = 0.0001;
private const float c_ThresholdValue = 100.0f;
private const float c_MinimumCloseVelocity = 31.0f;
[ThreadStatic]
static WeakReference<SwipeControl> s_lastInteractedWithSwipeControl = null;
public SwipeControl()
{
s_lastInteractedWithSwipeControl ??= new WeakReference<SwipeControl>(null);
this.SetDefaultStyleKey();
Loaded += UnfinalizeOnLoad;
Unloaded += FinalizeOnUnload;
}
#if HAS_UNO
// [BEGIN] Uno workaround:
// + we make sure to un-subscribe from events on unload to avoid leaks
// + we must not use finalizer on uno (invoked from a bg thread)
private static void UnfinalizeOnLoad(object sender, RoutedEventArgs routedEventArgs)
=> ((SwipeControl)sender).SwipeControl_Unfinalizer();
private static void FinalizeOnUnload(object sender, RoutedEventArgs routedEventArgs)
=> ((SwipeControl)sender).SwipeControl_Finalizer();
private void SwipeControl_Unfinalizer()
{
if (_isReady)
{
DetachEventHandlers(); // Do not double subscribe
AttachEventHandlers(isUnoUnfinalizer: true);
}
}
#endif
private void SwipeControl_Finalizer()
//~SwipeControl()
// [END] Uno workaround
{
DetachEventHandlers();
if (s_lastInteractedWithSwipeControl.TryGetTarget(out var lastInteractedWithSwipeControl))
{
if (lastInteractedWithSwipeControl == this)
{
s_lastInteractedWithSwipeControl.SetTarget(null);
var globalTestHooks = SwipeTestHooks.GetGlobalTestHooks();
if (globalTestHooks is { })
{
globalTestHooks.NotifyLastInteractedWithSwipeControlChanged();
}
}
}
}
#region ISwipeControl
public async void Close()
{
//CheckThread();
try
{
if (m_isOpen && !m_lastActionWasClosing && !m_isInteracting)
{
m_lastActionWasClosing = true;
//Uno workaround:
m_isInteracting = true;
_desiredPosition = Vector2.Zero;
UpdateStackPanelDesiredPosition();
// This delay is to allow users to see the fully open state before it closes back.
await Task.Delay(TimeSpan.FromSeconds(0.250));
await AnimateTransforms(false, 0d);
OnSwipeManipulationCompleted(this, null);
//if (!m_isIdle)
//{
// Vector3 initialPosition = default;
// switch (m_createdContent)
// {
// case CreatedContent.Left:
// initialPosition.X = (float)(-m_swipeContentStackPanel.ActualWidth);
// break;
// case CreatedContent.Top:
// initialPosition.Y = (float)(-m_swipeContentStackPanel.ActualHeight);
// break;
// case CreatedContent.Right:
// initialPosition.X = (float)(m_swipeContentStackPanel.ActualWidth);
// break;
// case CreatedContent.Bottom:
// initialPosition.Y = (float)(m_swipeContentStackPanel.ActualHeight);
// break;
// case CreatedContent.None:
// break;
// default:
// global::System.Diagnostics.Debug.Assert(false);
// break;
// }
//m_interactionTracker.TryUpdatePosition(initialPosition);
//}
//Vector3 addedVelocity = default;
//switch (m_createdContent)
//{
// case CreatedContent.Left:
// addedVelocity.X = c_MinimumCloseVelocity;
// break;
// case CreatedContent.Top:
// addedVelocity.Y = c_MinimumCloseVelocity;
// break;
// case CreatedContent.Right:
// addedVelocity.X = -c_MinimumCloseVelocity;
// break;
// case CreatedContent.Bottom:
// addedVelocity.Y = -c_MinimumCloseVelocity;
// break;
// case CreatedContent.None:
// break;
// default:
// global::System.Diagnostics.Debug.Assert(false);
// break;
//}
//m_interactionTracker.TryUpdatePositionWithAdditionalVelocity(addedVelocity);
}
}
catch (Exception ex)
{
Application.Current.RaiseRecoverableUnhandledException(ex);
}
}
#endregion
#region FrameworkElementOverrides
protected override void OnApplyTemplate()
{
ThrowIfHasVerticalAndHorizontalContent(setIsHorizontal: true);
DetachEventHandlers();
GetTemplateParts();
EnsureClip();
AttachEventHandlers();
_isReady = true;
}
private void OnPropertyChanged(DependencyPropertyChangedEventArgs args)
{
DependencyProperty property = args.Property;
if (property == LeftItemsProperty)
{
OnLeftItemsCollectionChanged(args);
}
if (property == RightItemsProperty)
{
OnRightItemsCollectionChanged(args);
}
if (property == TopItemsProperty)
{
OnTopItemsCollectionChanged(args);
}
if (property == BottomItemsProperty)
{
OnBottomItemsCollectionChanged(args);
}
}
//Swipe control is usually placed in a list view item. When this is the case the swipe item needs to be the same size as the list view item.
//This is to ensure that swiping from anywhere on the list view item causes pointer pressed events in the SwipeControl. Without this measure
//override it is usually not the case that swipe control will fill the available space. This is because list view item is a content control
//and those by convension only provide it's children space for at most their desired size. However list view item itself will take up a different
//ammount of space. In the past we solved this issue by requiring the list view item to have the HorizontalContentAlignment and VerticalContentAlignment
//set to stretch. This property changes the measure cycle to give as much space as possible to the list view items children. Instead we can
//just do this ourselves in this measure override and prevent the confusing need for properties set on the parent of swipe control to use it at all.
protected override Size MeasureOverride(Size availableSize)
{
base.MeasureOverride(availableSize);
m_rootGrid.Measure(availableSize);
Size contentDesiredSize = m_rootGrid.DesiredSize;
if (!double.IsInfinity(availableSize.Width))
{
contentDesiredSize.Width = availableSize.Width;
}
if (!double.IsInfinity(availableSize.Height))
{
contentDesiredSize.Height = availableSize.Height;
}
return contentDesiredSize;
}
#endregion
#region IInteractionTrackerOwner
// Uno workaround: Interaction tracker is not supported yet, use Manipulation events instead
#if false
void CustomAnimationStateEntered(
InteractionTracker sender,
InteractionTrackerCustomAnimationStateEnteredArgs args)
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
m_isInteracting = true;
if (m_isIdle)
{
m_isIdle = false;
if (var globalTestHooks = SwipeTestHooks.GetGlobalTestHooks())
{
globalTestHooks.NotifyIdleStatusChanged(this);
}
}
}
void RequestIgnored(
InteractionTracker sender,
InteractionTrackerRequestIgnoredArgs args)
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
}
void IdleStateEntered(
InteractionTracker sender,
InteractionTrackerIdleStateEnteredArgs args)
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
m_isInteracting = false;
UpdateIsOpen(m_interactionTracker.Position() != float3.zero());
if (m_isOpen)
{
if (m_currentItems && m_currentItems.Mode == SwipeMode.Execute && m_currentItems.Size() > 0)
{
var swipeItem = (SwipeItem)(m_currentItems.GetAt(0));
get_self<SwipeItem>(swipeItem).InvokeSwipe(this);
}
}
else
{
if (var swipeContentStackPanel = m_swipeContentStackPanel)
{
swipeContentStackPanel.Background(null);
if (var swipeContentStackPanelChildren = swipeContentStackPanel.Children)
{
swipeContentStackPanelChildren.Clear();
}
}
if (var swipeContentRoot = m_swipeContentRoot)
{
swipeContentRoot.Background(null);
}
m_currentItems.set(null);
m_createdContent = CreatedContent.None;
}
if (!m_isIdle)
{
m_isIdle = true;
if (var globalTestHooks = SwipeTestHooks.GetGlobalTestHooks())
{
globalTestHooks.NotifyIdleStatusChanged(this);
}
}
}
void InteractingStateEntered(
InteractionTracker sender,
InteractionTrackerInteractingStateEnteredArgs args)
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
if (m_isIdle)
{
m_isIdle = false;
if (var globalTestHooks = SwipeTestHooks.GetGlobalTestHooks())
{
globalTestHooks.NotifyIdleStatusChanged(this);
}
}
m_lastActionWasClosing = false;
m_lastActionWasOpening = false;
m_isInteracting = true;
//Once the user has started interacting with a SwipeControl in the closed state we are free to unblock contents.
//Contents of items opposite the currently opened ones will not be created.
if (!m_isOpen)
{
m_blockNearContent = false;
m_blockFarContent = false;
m_interactionTracker.Properties.InsertBoolean(s_blockNearContentPropertyName, false);
m_interactionTracker.Properties.InsertBoolean(s_blockFarContentPropertyName, false);
}
}
void InertiaStateEntered(
InteractionTracker sender,
InteractionTrackerInertiaStateEnteredArgs & args)
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
m_isInteracting = false;
if (m_isIdle)
{
m_isIdle = false;
if (var globalTestHooks = SwipeTestHooks.GetGlobalTestHooks())
{
globalTestHooks.NotifyIdleStatusChanged(this);
}
}
//It is possible that the user has flicked from a negative position to a position that would result in the interaction
//tracker coming to rest at the positive open position (or vise versa). The != zero check does not account for this.
//Instead we check to ensure that the current position and the ModifiedRestingPosition have the same sign (multiply to a positive number)
//If they do not then we are in this situation and want the end result of the interaction to be the closed state, so close without any animation and return
//to prevent further processing of this inertia state.
var flickToOppositeSideCheck = m_interactionTracker.Position() * args.ModifiedRestingPosition().Value();
if (m_isHorizontal ? flickToOppositeSideCheck.x < 0 : flickToOppositeSideCheck.y < 0)
{
CloseWithoutAnimation();
return;
}
UpdateIsOpen(args.ModifiedRestingPosition().Value() != float3.zero());
// If the user has panned the interaction tracker past 0 in the opposite direction of the previously
// opened swipe items then when we set m_isOpen to true the animations will snap to that value.
// To avoid this we block that side of the animation until the interacting state is entered.
if (m_isOpen)
{
switch (m_createdContent)
{
case CreatedContent.Bottom:
case CreatedContent.Right:
m_blockNearContent = true;
m_blockFarContent = false;
m_interactionTracker.Properties.InsertBoolean(s_blockNearContentPropertyName, true);
m_interactionTracker.Properties.InsertBoolean(s_blockFarContentPropertyName, false);
break;
case CreatedContent.Top:
case CreatedContent.Left:
m_blockNearContent = false;
m_blockFarContent = true;
m_interactionTracker.Properties.InsertBoolean(s_blockNearContentPropertyName, false);
m_interactionTracker.Properties.InsertBoolean(s_blockFarContentPropertyName, true);
break;
case CreatedContent.None:
m_blockNearContent = false;
m_blockFarContent = false;
m_interactionTracker.Properties.InsertBoolean(s_blockNearContentPropertyName, false);
m_interactionTracker.Properties.InsertBoolean(s_blockFarContentPropertyName, false);
break;
default:
assert(false);
}
}
}
void ValuesChanged(
InteractionTracker sender,
InteractionTrackerValuesChangedArgs & args)
{
SWIPECONTROL_TRACE_VERBOSE(this/*, TRACE_MSG_METH, METH_NAME, this*/);
var lastInteractedWithSwipeControl = s_lastInteractedWithSwipeControl;
if (m_isInteracting && (!lastInteractedWithSwipeControl || lastInteractedWithSwipeControl != this))
{
if (lastInteractedWithSwipeControl)
{
lastInteractedWithSwipeControl.CloseIfNotRemainOpenExecuteItem();
}
s_lastInteractedWithSwipeControl = get_weak();
if (var globalTestHooks = SwipeTestHooks.GetGlobalTestHooks())
{
globalTestHooks.NotifyLastInteractedWithSwipeControlChanged();
}
}
float value = 0.0f;
if (m_isHorizontal)
{
value = args.Position().x;
if (!m_blockNearContent && m_createdContent != CreatedContent.Left && value < -c_epsilon)
{
CreateLeftContent();
}
else if (!m_blockFarContent && m_createdContent != CreatedContent.Right && value > c_epsilon)
{
CreateRightContent();
}
}
else
{
value = args.Position().y;
if (!m_blockNearContent && m_createdContent != CreatedContent.Top && value < -c_epsilon)
{
CreateTopContent();
}
else if (!m_blockFarContent && m_createdContent != CreatedContent.Bottom && value > c_epsilon)
{
CreateBottomContent();
}
}
UpdateThresholdReached(value);
}
#endif
#endregion
#region TestHookHelpers
internal static SwipeControl GetLastInteractedWithSwipeControl()
{
if (s_lastInteractedWithSwipeControl.TryGetTarget(out var lastInteractedWithSwipeControl))
{
return lastInteractedWithSwipeControl;
}
return null;
}
internal bool GetIsOpen()
{
return m_isOpen;
}
internal bool GetIsIdle()
{
return m_isIdle;
}
#endregion
private void OnLeftItemsCollectionChanged(DependencyPropertyChangedEventArgs args)
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
if (args.OldValue is { })
{
var observableVector = args.NewValue as IObservableVector<SwipeItem>;
observableVector.VectorChanged -= OnLeftItemsChanged;
}
if (args.NewValue is { })
{
ThrowIfHasVerticalAndHorizontalContent();
var observableVector = args.NewValue as IObservableVector<SwipeItem>;
observableVector.VectorChanged += OnLeftItemsChanged;
}
//if (m_interactionTracker is {})
//{
// m_interactionTracker.Properties.InsertBoolean(s_hasLeftContentPropertyName, args.NewValue is {} && (args.NewValue as IObservableVector<SwipeItem>).Count > 0);
//}
// Uno workaround:
_hasLeftContent = args.NewValue is { } && (args.NewValue as IObservableVector<SwipeItem>).Count > 0;
if (m_createdContent == CreatedContent.Left)
{
CreateLeftContent();
}
}
private void OnRightItemsCollectionChanged(DependencyPropertyChangedEventArgs args)
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
if (args.OldValue is { })
{
var observableVector = args.OldValue as IObservableVector<SwipeItem>;
observableVector.VectorChanged -= OnRightItemsChanged;
}
if (args.NewValue is { })
{
ThrowIfHasVerticalAndHorizontalContent();
var observableVector = args.NewValue as IObservableVector<SwipeItem>;
observableVector.VectorChanged += OnRightItemsChanged;
}
//if (m_interactionTracker is {})
//{
// m_interactionTracker.Properties.InsertBoolean(s_hasRightContentPropertyName, args.NewValue is {} && (args.NewValue as IObservableVector<SwipeItem>).Count > 0);
//}
// Uno workaround:
_hasRightContent = args.NewValue is { } && (args.NewValue as IObservableVector<SwipeItem>).Count > 0;
if (m_createdContent == CreatedContent.Right)
{
CreateRightContent();
}
}
private void OnTopItemsCollectionChanged(DependencyPropertyChangedEventArgs args)
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
if (args.OldValue is { })
{
var observableVector = args.OldValue as IObservableVector<SwipeItem>;
observableVector.VectorChanged -= OnTopItemsChanged;
}
if (args.NewValue is { })
{
ThrowIfHasVerticalAndHorizontalContent();
var observableVector = args.NewValue as IObservableVector<SwipeItem>;
observableVector.VectorChanged += OnTopItemsChanged;
}
//if (m_interactionTracker is {})
//{
// m_interactionTracker.Properties.InsertBoolean(s_hasTopContentPropertyName, args.NewValue is {} && (args.NewValue as IObservableVector<SwipeItem>).Count > 0);
//}
// Uno workaround:
_hasTopContent = args.NewValue is { } && (args.NewValue as IObservableVector<SwipeItem>).Count > 0;
if (m_createdContent == CreatedContent.Top)
{
CreateTopContent();
}
}
private void OnBottomItemsCollectionChanged(DependencyPropertyChangedEventArgs args)
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
if (args.OldValue is { })
{
var observableVector = args.OldValue as IObservableVector<SwipeItem>;
observableVector.VectorChanged -= OnBottomItemsChanged;
}
if (args.NewValue is { })
{
ThrowIfHasVerticalAndHorizontalContent();
var observableVector = args.NewValue as IObservableVector<SwipeItem>;
observableVector.VectorChanged += OnBottomItemsChanged;
}
//if (m_interactionTracker is {})
//{
// m_interactionTracker.Properties.InsertBoolean(s_hasBottomContentPropertyName, args.NewValue is {} && (args.NewValue as IObservableVector<SwipeItem>).Count > 0);
//}
// Uno workaround:
_hasBottomContent = args.NewValue is { } && (args.NewValue as IObservableVector<SwipeItem>).Count > 0;
if (m_createdContent == CreatedContent.Bottom)
{
CreateBottomContent();
}
}
private void OnLoaded(object sender, RoutedEventArgs args)
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
if (!m_hasInitialLoadedEventFired)
{
m_hasInitialLoadedEventFired = true;
InitializeInteractionTracker();
TryGetSwipeVisuals();
}
//If the swipe control has been added to the tree for a subsequent time, for instance when a list view item has been recycled,
//Ensure that we are in the closed interaction tracker state.
CloseWithoutAnimation();
}
private void AttachEventHandlers(bool isUnoUnfinalizer = false)
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
//global::System.Diagnostics.Debug.Assert(m_loadedToken.value == 0);
if (isUnoUnfinalizer) // Uno workaround: We detach from event on unload and re-attach on loaded
{
OnLoaded(this, null);
}
else
{
Loaded += OnLoaded;
m_hasInitialLoadedEventFired = false;
}
//global::System.Diagnostics.Debug.Assert(m_onSizeChangedToken.value == 0);
SizeChanged += OnSizeChanged;
//global::System.Diagnostics.Debug.Assert(m_onSwipeContentStackPanelSizeChangedToken.value == 0);
m_swipeContentStackPanel.SizeChanged += OnSwipeContentStackPanelSizeChanged;
// also get any action from any inside button, or a clickable/tappable control
if (m_onPointerPressedEventHandler is null)
{
m_onPointerPressedEventHandler = OnPointerPressedEvent;
AddHandler(UIElement.PointerPressedEvent, m_onPointerPressedEventHandler, true);
}
//global::System.Diagnostics.Debug.Assert(m_inputEaterTappedToken.value == 0);
m_inputEater.Tapped += InputEaterGridTapped;
// Uno workaround:
UnoAttachEventHandlers();
}
private void DetachEventHandlers()
{
SWIPECONTROL_TRACE_INFO(null/*, TRACE_MSG_METH, METH_NAME, this*/);
Loaded -= OnLoaded;
SizeChanged -= OnSizeChanged;
// Uno workaround: Add null check because m_swipeContentStackPanel is set later.
if (m_swipeContentStackPanel != null)
{
m_swipeContentStackPanel.SizeChanged -= OnSwipeContentStackPanelSizeChanged;
}
if (m_onPointerPressedEventHandler is { })
{
RemoveHandler(UIElement.PointerPressedEvent, m_onPointerPressedEventHandler);
m_onPointerPressedEventHandler = null;
}
if (m_inputEater is { })
{
m_inputEater.Tapped -= InputEaterGridTapped;
}
DetachDismissingHandlers();
// Uno workaround:
UnoDetachEventHandlers();
}
private void OnSizeChanged(object sender, SizeChangedEventArgs args)
{
EnsureClip();
foreach (var uiElement in m_swipeContentStackPanel.GetChildren())
{
AppBarButton appBarButton = uiElement as AppBarButton;
if (appBarButton is { })
{
if (m_isHorizontal)
{
appBarButton.Height = ActualHeight;
if (m_currentItems is { } && m_currentItems.Mode == SwipeMode.Execute)
{
appBarButton.Width = ActualWidth;
}
}
else
{
appBarButton.Width = ActualWidth;
if (m_currentItems is { } && m_currentItems.Mode == SwipeMode.Execute)
{
appBarButton.Height = ActualHeight;
}
}
}
}
}
private void OnSwipeContentStackPanelSizeChanged(object sender, SizeChangedEventArgs args)
{
//if (m_interactionTracker is {})
//{
// m_interactionTracker.MinPosition = new Vector3(
// (float)-args.NewSize.Width, (float)-args.NewSize.Height, 0.0f
// );
// m_interactionTracker.MaxPosition = new Vector3(
// (float)args.NewSize.Width, (float)args.NewSize.Height, 0.0f
// );
// ConfigurePositionInertiaRestingValues();
//}
}
private void OnPointerPressedEvent(
object sender,
PointerRoutedEventArgs args)
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
if (args.Pointer.PointerDeviceType == PointerDeviceType.Touch /*&& m_visualInteractionSource is {}*/)
{
if (m_currentItems is { } &&
m_currentItems.Mode == SwipeMode.Execute &&
m_currentItems.Size > 0 &&
m_currentItems.GetAt(0).BehaviorOnInvoked == SwipeBehaviorOnInvoked.RemainOpen &&
m_isOpen)
{
//If the swipe control is currently open on an Execute item's who's behaviorOnInvoked property is set to RemainOpen
//we don't want to allow the user interaction to effect the swipe control anymore, so don't redirect the manipulation
//to the interaction tracker.
return;
}
//try
//{
// m_visualInteractionSource.TryRedirectForManipulation(args.GetCurrentPoint(this));
//}
//catch (Exception e)
//{
// // Swallowing Access Denied error because of InteractionTracker bug 17434718 which has been
// // causing crashes at least in RS3, RS4 and RS5.
// if (e.to_abi() != E_ACCESSDENIED)
// {
// throw;
// }
//}
}
}
private void InputEaterGridTapped(object sender, TappedRoutedEventArgs args)
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
if (m_isOpen)
{
CloseIfNotRemainOpenExecuteItem();
args.Handled = true;
}
}
private void AttachDismissingHandlers()
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
DetachDismissingHandlers();
//if (UIElement10 uiElement10 = this)
//{
var xamlRoot = this.XamlRoot;
if (xamlRoot is { })
{
if (xamlRoot.Content is { } xamlRootContent)
{
var handler = new PointerEventHandler((_, args) =>
{
DismissSwipeOnAnExternalTap(args.GetCurrentPoint(null).Position);
});
xamlRootContent.AddHandler(PointerPressedEvent, handler, true);
m_xamlRootPointerPressedEventRevoker = Disposable.Create(() => xamlRootContent.RemoveHandler(PointerPressedEvent, handler));
var keyHandler = new KeyEventHandler((_, arg) =>
{
CloseIfNotRemainOpenExecuteItem();
});
xamlRootContent.AddHandler(KeyDownEvent, keyHandler, true);
m_xamlRootKeyDownEventRevoker = Disposable.Create(() => xamlRootContent.RemoveHandler(KeyDownEvent, keyHandler));
}
xamlRoot.Changed += CurrentXamlRootChanged;
m_xamlRootChangedRevoker = Disposable.Create(() => xamlRoot.Changed -= CurrentXamlRootChanged);
}
//}
//else
//{
// if (var currentWindow = Window.Current())
// {
// if (var coreWindow = currentWindow.CoreWindow())
// {
// m_coreWindowPointerPressedRevoker = coreWindow.PointerPressed(auto_revoke, {
// this, DismissSwipeOnAnExternalCoreWindowTap
// });
// m_coreWindowKeyDownRevoker = coreWindow.KeyDown(auto_revoke, {
// this, DismissSwipeOnCoreWindowKeyDown
// });
// m_windowMinimizeRevoker = coreWindow.VisibilityChanged(auto_revoke, {
// this, CurrentWindowVisibilityChanged
// });
// m_windowSizeChangedRevoker = currentWindow.SizeChanged(auto_revoke, {
// this, CurrentWindowSizeChanged
// });
// }
// }
//}
if (CoreWindow.GetForCurrentThreadSafe() is { } coreWindow)
{
if (coreWindow.Dispatcher is { } dispatcher)
{
dispatcher.AcceleratorKeyActivated += DismissSwipeOnAcceleratorKeyActivator;
m_acceleratorKeyActivatedRevoker = Disposable.Create(() => dispatcher.AcceleratorKeyActivated -= DismissSwipeOnAcceleratorKeyActivator);
}
}
}
private void DetachDismissingHandlers()
{
SWIPECONTROL_TRACE_INFO(null/*, TRACE_MSG_METH, METH_NAME, this*/);
m_xamlRootPointerPressedEventRevoker?.Dispose();
m_xamlRootKeyDownEventRevoker?.Dispose();
m_xamlRootChangedRevoker?.Dispose();
m_acceleratorKeyActivatedRevoker?.Dispose();
//m_coreWindowPointerPressedRevoker?.Dispose();
//m_coreWindowKeyDownRevoker?.Dispose();
//m_windowMinimizeRevoker?.Dispose();
//m_windowSizeChangedRevoker?.Dispose();
}
private void DismissSwipeOnAcceleratorKeyActivator(CoreDispatcher sender, AcceleratorKeyEventArgs args)
{
CloseIfNotRemainOpenExecuteItem();
}
private void CurrentXamlRootChanged(XamlRoot sender, XamlRootChangedEventArgs args)
{
CloseIfNotRemainOpenExecuteItem();
}
#if false
private void DismissSwipeOnCoreWindowKeyDown(CoreWindow sender, KeyEventArgs args)
{
CloseIfNotRemainOpenExecuteItem();
}
private void CurrentWindowSizeChanged(DependencyObject sender, WindowSizeChangedEventArgs args)
{
CloseIfNotRemainOpenExecuteItem();
}
private void CurrentWindowVisibilityChanged(CoreWindow sender, VisibilityChangedEventArgs args)
{
CloseIfNotRemainOpenExecuteItem();
}
private void DismissSwipeOnAnExternalCoreWindowTap(CoreWindow sender, PointerEventArgs args)
{
DismissSwipeOnAnExternalTap(args.CurrentPoint.RawPosition);
}
#endif
private void DismissSwipeOnAnExternalTap(Point tapPoint)
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
GeneralTransform transform = TransformToVisual(null);
Point p = Point.Zero;
// start of the swipe control
var transformedElementOrigin = transform.TransformPoint(p);
// If point is not within the item's bounds, close it.
if (tapPoint.X < transformedElementOrigin.X || tapPoint.Y < transformedElementOrigin.Y ||
(tapPoint.X - transformedElementOrigin.X) > ActualWidth ||
(tapPoint.Y - transformedElementOrigin.Y) > ActualHeight)
{
CloseIfNotRemainOpenExecuteItem();
}
}
private void GetTemplateParts()
{
m_rootGrid = GetTemplateChild<Grid>(s_rootGridName);
m_inputEater = GetTemplateChild<Grid>(s_inputEaterName);
m_content = GetTemplateChild<Grid>(s_ContentRootName);
m_swipeContentRoot = GetTemplateChild<Grid>(s_swipeContentRootName);
m_swipeContentStackPanel = GetTemplateChild<StackPanel>(s_swipeContentStackPanelName);
//Before RS5 these elements were not in the template but were instead created in code behind when the swipe content was created.
//Post RS5 the code behind expects these elements to always be in the tree.
if (m_swipeContentRoot is null)
{
Grid swipeContentRoot = new Grid();
swipeContentRoot.Name = "SwipeContentRoot";
m_swipeContentRoot = swipeContentRoot;
m_rootGrid.Children.Insert(0, swipeContentRoot);
}
if (m_swipeContentStackPanel is null)
{
StackPanel swipeContentStackPanel = new StackPanel();
swipeContentStackPanel.Name("SwipeContentStackPanel");
m_swipeContentStackPanel = swipeContentStackPanel;
m_swipeContentRoot.Children.Add(swipeContentStackPanel);
}
m_swipeContentStackPanel.Orientation = m_isHorizontal ? Orientation.Horizontal : Orientation.Vertical;
var lookedUpStyle = SharedHelpers.FindInApplicationResources(s_swipeItemStyleName, null);
if (lookedUpStyle is { })
{
m_swipeItemStyle = lookedUpStyle as Style;
}
}
//* Uno workaround: Animation are not yet supported by composition API, we are using XAML animation instead.
#if false
void InitializeInteractionTracker()
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
IInteractionTrackerOwner interactionTrackerOwner = this;
if (!m_compositor)
{
m_compositor.set(ElementCompositionPreview.GetElementVisual(m_rootGrid).Compositor());
}
m_visualInteractionSource.set(VisualInteractionSource.Create(FindVisualInteractionSourceVisual()));
m_visualInteractionSource.IsPositionXRailsEnabled(m_isHorizontal);
m_visualInteractionSource.IsPositionYRailsEnabled(!m_isHorizontal);
m_visualInteractionSource.ManipulationRedirectionMode(VisualInteractionSourceRedirectionMode.CapableTouchpadOnly);
m_visualInteractionSource.PositionXSourceMode(m_isHorizontal ? InteractionSourceMode.EnabledWithInertia : InteractionSourceMode.Disabled);
m_visualInteractionSource.PositionYSourceMode(!m_isHorizontal ? InteractionSourceMode.EnabledWithInertia : InteractionSourceMode.Disabled);
if (m_isHorizontal)
{
m_visualInteractionSource.PositionXChainingMode(InteractionChainingMode.Never);
}
else
{
m_visualInteractionSource.PositionYChainingMode(InteractionChainingMode.Never);
}
m_interactionTracker.set(InteractionTracker.CreateWithOwner(m_compositor, interactionTrackerOwner));
m_interactionTracker.InteractionSources().Add(m_visualInteractionSource);
m_interactionTracker.Properties.InsertBoolean(s_isFarOpenPropertyName, false);
m_interactionTracker.Properties.InsertBoolean(s_isNearOpenPropertyName, false);
m_interactionTracker.Properties.InsertBoolean(s_blockNearContentPropertyName, false);
m_interactionTracker.Properties.InsertBoolean(s_blockFarContentPropertyName, false);
m_interactionTracker.Properties.InsertBoolean(s_hasLeftContentPropertyName, LeftItems() && LeftItems().Size() > 0);
m_interactionTracker.Properties.InsertBoolean(s_hasRightContentPropertyName, RightItems() && RightItems().Size() > 0);
m_interactionTracker.Properties.InsertBoolean(s_hasTopContentPropertyName, TopItems() && TopItems().Size() > 0);
m_interactionTracker.Properties.InsertBoolean(s_hasBottomContentPropertyName, BottomItems() && BottomItems().Size() > 0);
m_interactionTracker.MaxPosition({
std.numeric_limits<float>.infinity(), std.numeric_limits<float>.infinity(), 0.0f
});
m_interactionTracker.MinPosition({
-1.0f * std.numeric_limits<float>.infinity(), -1.0f * std.numeric_limits<float>.infinity(), 0.0f
});
// Create and initialize the Swipe animations:
// If the swipe control is already opened it should not be possible to open the opposite side's items, without first closing the swipe control.
// This prevents the user from flicking the swipe control closed and accidently opening the other due to inertia.
// To acheive this we insert the isFarOpen and isNearOpen boolean properties on the interaction tracker and alter the expression output based on these.
// The opened state is maintained in the interaction trackers IdleStateEntered handler, this means we need to ensure this state is entered each time the swipe control
// is opened or closed.
// A more readable version of the expression:
/ m_swipeAnimation.set(m_compositor.CreateExpressionAnimation("isHorizontal ?"
"Vector3(tracker.isFarOpen || tracker.blockNearContent ? Clamp(-tracker.Position.X, -this.Target.Size.X, 0) :"
"tracker.isNearOpen || tracker.blockFarContent ? Clamp(-tracker.Position.X, 0, this.Target.Size.X) :"
"Clamp(-tracker.Position.X, (tracker.hasRightContent ? -10000 : 0), (tracker.hasLeftContent ? 10000 : 0)), 0, 0) :"
"Vector3(0, tracker.isFarOpen || tracker.blockNearContent ? Clamp(-tracker.Position.Y, -this.Target.Size.Y, 0) :"
"tracker.isNearOpen || tracker.blockFarContent ? Clamp(-tracker.Position.Y, 0, this.Target.Size.Y) :"
"Clamp(-tracker.Position.Y, (tracker.hasBottomContent ? -10000 : 0), (tracker.hasTopContent ? 10000 : 0)), 0)"));
*/
m_swipeAnimation.set(m_compositor.CreateExpressionAnimation(isHorizontalPropertyName() + " ?"
"Vector3(" + trackerPropertyName() + "." + isFarOpenPropertyName() + " || " + trackerPropertyName() + "." + blockNearContentPropertyName() + " ? Clamp(-" + trackerPropertyName() + ".Position.X, -this.Target.Size.X, 0) :"
+ trackerPropertyName() + "." + isNearOpenPropertyName() + " || " + trackerPropertyName() + "." + blockFarContentPropertyName() + " ? Clamp(-" + trackerPropertyName() + ".Position.X, 0, this.Target.Size.X) :"
"Clamp(-" + trackerPropertyName() + ".Position.X, (" + trackerPropertyName() + "." + hasRightContentPropertyName() + " ? -10000 : 0), (" + trackerPropertyName() + "." + hasLeftContentPropertyName() + " ? 10000 : 0)), 0, 0) :"
"Vector3(0, " + trackerPropertyName() + "." + isFarOpenPropertyName() + " || " + trackerPropertyName() + "." + blockNearContentPropertyName() + " ? Clamp(-" + trackerPropertyName() + ".Position.Y, -this.Target.Size.Y, 0) :"
+ trackerPropertyName() + "." + isNearOpenPropertyName() + " || " + trackerPropertyName() + "." + blockFarContentPropertyName() + " ? Clamp(-" + trackerPropertyName() + ".Position.Y, 0, this.Target.Size.Y) :"
"Clamp(-" + trackerPropertyName() + ".Position.Y, (" + trackerPropertyName() + "." + hasBottomContentPropertyName() + " ? -10000 : 0), (" + trackerPropertyName() + "." + hasTopContentPropertyName() + " ? 10000 : 0)), 0)"));
m_swipeAnimation.SetReferenceParameter(s_trackerPropertyName, m_interactionTracker);
m_swipeAnimation.SetBooleanParameter(s_isHorizontalPropertyName, m_isHorizontal);
if (IsTranslationFacadeAvailableForSwipeControl(m_content))
{
m_swipeAnimation.Target(s_translationPropertyName);
}
//A more readable version of the expression:
/ m_executeExpressionAnimation.set(m_compositor.CreateExpressionAnimation("(foregroundVisual." + GetAnimationTarget() + " * 0.5) + (isHorizontal ?"
"Vector3((isNearContent ? -0.5, 0.5) * this.Target.Size.X, 0, 0) : "
"Vector3(0, (isNearContent ? -0.5, 0.5) * this.Target.Size.Y, 0))"));
*/
m_executeExpressionAnimation.set(m_compositor.CreateExpressionAnimation("(" + foregroundVisualPropertyName() + "." + GetAnimationTarget(m_swipeContentStackPanel) + " * 0.5) + (" + isHorizontalPropertyName() + " ? "
"Vector3((" + isNearContentPropertyName() + " ? -0.5 : 0.5) * this.Target.Size.X, 0, 0) : "
"Vector3(0, (" + isNearContentPropertyName() + " ? -0.5 : 0.5) * this.Target.Size.Y, 0))"));
m_executeExpressionAnimation.SetBooleanParameter(s_isHorizontalPropertyName, m_isHorizontal);
if (IsTranslationFacadeAvailableForSwipeControl(m_swipeContentStackPanel))
{
m_executeExpressionAnimation.Target(s_translationPropertyName);
}
//A more readable version of the expression:
/ m_clipExpressionAnimation.set(m_compositor.CreateExpressionAnimation(L"isHorizontal ?
Max(swipeRootVisual.Size.X + (isNearContent ? tracker.Position.X : -tracker.Position.X), 0) :
Max(swipeRootVisual.Size.Y + (isNearContent ? tracker.Position.Y : -tracker.Position.Y), 0)"));*/
m_clipExpressionAnimation.set(m_compositor.CreateExpressionAnimation(isHorizontalPropertyName() + " ? "
"Max(" + swipeRootVisualPropertyName() + ".Size.X + (" + isNearContentPropertyName() + " ? " + trackerPropertyName() + ".Position.X : -" + trackerPropertyName() + ".Position.X) , 0) : "
"Max(" + swipeRootVisualPropertyName() + ".Size.Y + (" + isNearContentPropertyName() + " ? " + trackerPropertyName() + ".Position.Y : -" + trackerPropertyName() + ".Position.Y) , 0)"));
m_clipExpressionAnimation.SetReferenceParameter(s_trackerPropertyName, m_interactionTracker);
m_clipExpressionAnimation.SetBooleanParameter(s_isHorizontalPropertyName, m_isHorizontal);
}
void ConfigurePositionInertiaRestingValues()
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
if (m_isHorizontal)
{
IVector<InteractionTrackerInertiaModifier> xModifiers = new Vector<InteractionTrackerInertiaModifier>();
ExpressionAnimation leftCondition = m_compositor.CreateExpressionAnimation("this.Target." + hasLeftContentPropertyName() + " && !this.Target." + isFarOpenPropertyName() + " && this.Target.NaturalRestingPosition.x <= -1 * (this.Target." + isNearOpenPropertyName() + " ? " + swipeContentSizeParameterName() + " : min(" + swipeContentSizeParameterName() + ", " + maxThresholdPropertyName() + "))");
leftCondition.SetScalarParameter(s_swipeContentSizeParameterName, (float)(m_swipeContentStackPanel.ActualWidth));
leftCondition.SetScalarParameter(s_maxThresholdPropertyName, c_ThresholdValue);
ExpressionAnimation leftRestingPoint = m_compositor.CreateExpressionAnimation("-" + swipeContentSizeParameterName());
leftRestingPoint.SetScalarParameter(s_swipeContentSizeParameterName, (float)(m_swipeContentStackPanel.ActualWidth));
InteractionTrackerInertiaRestingValue leftOpen = InteractionTrackerInertiaRestingValue.Create(m_compositor);
leftOpen.Condition(leftCondition);
leftOpen.RestingValue(leftRestingPoint);
xModifiers.Append(leftOpen);
ExpressionAnimation rightCondition = m_compositor.CreateExpressionAnimation("this.Target." + hasRightContentPropertyName() + " && !this.Target." + isNearOpenPropertyName() + " && this.Target.NaturalRestingPosition.x >= (this.Target." + isFarOpenPropertyName() + " ? " + swipeContentSizeParameterName() + " : min(" + swipeContentSizeParameterName() + ", " + maxThresholdPropertyName() + "))");
rightCondition.SetScalarParameter(s_swipeContentSizeParameterName, (float)(m_swipeContentStackPanel.ActualWidth));
rightCondition.SetScalarParameter(s_maxThresholdPropertyName, c_ThresholdValue);
ExpressionAnimation rightRestingValue = m_compositor.CreateExpressionAnimation(s_swipeContentSizeParameterName);
rightRestingValue.SetScalarParameter(s_swipeContentSizeParameterName, (float)(m_swipeContentStackPanel.ActualWidth));
InteractionTrackerInertiaRestingValue rightOpen = InteractionTrackerInertiaRestingValue.Create(m_compositor);
rightOpen.Condition(rightCondition);
rightOpen.RestingValue(rightRestingValue);
xModifiers.Append(rightOpen);
ExpressionAnimation condition = m_compositor.CreateExpressionAnimation("true");
ExpressionAnimation restingValue = m_compositor.CreateExpressionAnimation("0");
InteractionTrackerInertiaRestingValue neutralX = InteractionTrackerInertiaRestingValue.Create(m_compositor);
neutralX.Condition(condition);
neutralX.RestingValue(restingValue);
xModifiers.Append(neutralX);
m_interactionTracker.ConfigurePositionXInertiaModifiers(xModifiers);
}
else
{
IVector<InteractionTrackerInertiaModifier> yModifiers = new Vector<InteractionTrackerInertiaModifier>();
ExpressionAnimation topCondition = m_compositor.CreateExpressionAnimation("this.Target." + hasTopContentPropertyName() + " && !this.Target." + isFarOpenPropertyName() + " && this.Target.NaturalRestingPosition.y <= -1 * (this.Target." + isNearOpenPropertyName() + " ? " + swipeContentSizeParameterName() + " : min(" + swipeContentSizeParameterName() + ", " + maxThresholdPropertyName() + "))");
topCondition.SetScalarParameter(s_swipeContentSizeParameterName, (float)(m_swipeContentStackPanel.ActualHeight));
topCondition.SetScalarParameter(s_maxThresholdPropertyName, c_ThresholdValue);
ExpressionAnimation topRestingValue = m_compositor.CreateExpressionAnimation("-" + swipeContentSizeParameterName());
topRestingValue.SetScalarParameter(s_swipeContentSizeParameterName, (float)(m_swipeContentStackPanel.ActualHeight));
InteractionTrackerInertiaRestingValue topOpen = InteractionTrackerInertiaRestingValue.Create(m_compositor);
topOpen.Condition(topCondition);
topOpen.RestingValue(topRestingValue);
yModifiers.Append(topOpen);
ExpressionAnimation bottomCondition = m_compositor.CreateExpressionAnimation("this.Target." + hasBottomContentPropertyName() + " && !this.Target." + isNearOpenPropertyName() + " && this.Target.NaturalRestingPosition.y >= (this.Target." + isFarOpenPropertyName() + " ? " + swipeContentSizeParameterName() + " : min(" + swipeContentSizeParameterName() + ", " + maxThresholdPropertyName() + "))");
bottomCondition.SetScalarParameter(s_swipeContentSizeParameterName, (float)(m_swipeContentStackPanel.ActualHeight));
bottomCondition.SetScalarParameter(s_maxThresholdPropertyName, c_ThresholdValue);
ExpressionAnimation bottomRestingValue = m_compositor.CreateExpressionAnimation(s_swipeContentSizeParameterName);
bottomRestingValue.SetScalarParameter(s_swipeContentSizeParameterName, (float)(m_swipeContentStackPanel.ActualHeight));
InteractionTrackerInertiaRestingValue bottomOpen = InteractionTrackerInertiaRestingValue.Create(m_compositor);
bottomOpen.Condition(bottomCondition);
bottomOpen.RestingValue(bottomRestingValue);
yModifiers.Append(bottomOpen);
ExpressionAnimation condition = m_compositor.CreateExpressionAnimation("true");
ExpressionAnimation restingValue = m_compositor.CreateExpressionAnimation("0");
InteractionTrackerInertiaRestingValue neutralY = InteractionTrackerInertiaRestingValue.Create(m_compositor);
neutralY.Condition(condition);
neutralY.RestingValue(restingValue);
yModifiers.Append(neutralY);
m_interactionTracker.ConfigurePositionYInertiaModifiers(yModifiers);
}
}
Visual FindVisualInteractionSourceVisual()
{
Visual visualInteractionSource = null;
// Don't walk up the tree too far largely as an optimization for when SwipeControl isn't used
// with a list. The general-case when using swipe with a ListView will probably have the
// LVIP as the visual parent of the SwipeControl but enabling checking for a few more
// levels above that could enable more complex list item templates where SwipeControl
// isn't the root element.
int maxSteps = 5;
int steps = 0;
var current = VisualTreeHelper.GetParent(this);
while (current && steps < maxSteps)
{
if (var lvip = current.try_as<ListViewItemPresenter>())
{
visualInteractionSource = ElementCompositionPreview.GetElementVisual(lvip);
break;
}
current = VisualTreeHelper.GetParent(current);
++steps;
}
if (!visualInteractionSource)
{
visualInteractionSource = ElementCompositionPreview.GetElementVisual(this);
}
return visualInteractionSource;
}
#endif
private void EnsureClip()
{
float width = (float)(ActualWidth);
float height = (float)(ActualHeight);
Rect rect = new Rect(0.0f, 0.0f, width, height);
Microsoft.UI.Xaml.Media.RectangleGeometry rectangleGeometry = new RectangleGeometry();
rectangleGeometry.Rect = rect;
Clip = rectangleGeometry;
}
private void CloseWithoutAnimation()
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
bool wasIdle = m_isIdle;
//m_interactionTracker.TryUpdatePosition(new Vector3(
// 0.0f, 0.0f, 0.0f
//));
// Uno workaround:
_desiredPosition = Vector2.Zero;
UpdateStackPanelDesiredPosition();
UpdateTransforms();
if (wasIdle)
{
IdleStateEntered(null, null);
}
}
private void CloseIfNotRemainOpenExecuteItem()
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
if (m_currentItems is { } &&
m_currentItems.Mode == SwipeMode.Execute &&
m_currentItems.Size > 0 &&
m_currentItems.GetAt(0).BehaviorOnInvoked == SwipeBehaviorOnInvoked.RemainOpen &&
m_isOpen)
{
//If we have a Mode set to Execute, and an item with BehaviorOnInvoked set to RemainOpen, we do not want to close, so no-op
return;
}
Close();
}
private void CreateLeftContent()
{
var items = LeftItems;
if (items is { })
{
m_createdContent = CreatedContent.Left;
CreateContent(items);
}
}
private void CreateRightContent()
{
var items = RightItems;
if (items is { })
{
m_createdContent = CreatedContent.Right;
CreateContent(items);
}
}
private void CreateBottomContent()
{
var items = BottomItems;
if (items is { })
{
m_createdContent = CreatedContent.Bottom;
CreateContent(items);
}
}
private void CreateTopContent()
{
var items = TopItems;
if (items is { })
{
m_createdContent = CreatedContent.Top;
CreateContent(items);
}
}
private void CreateContent(SwipeItems items)
{
if (m_swipeContentStackPanel is { } && m_swipeContentStackPanel.Children is { })
{
m_swipeContentStackPanel.Children.Clear();
}
m_currentItems = items;
if (m_currentItems is { })
{
AlignStackPanel();
PopulateContentItems();
SetupExecuteExpressionAnimation();
SetupClipAnimation();
UpdateColors();
}
}
private void AlignStackPanel()
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
if (m_currentItems.Size > 0)
{
switch (m_currentItems.Mode)
{
case SwipeMode.Execute:
{
if (m_isHorizontal)
{
m_swipeContentStackPanel.HorizontalAlignment = HorizontalAlignment.Stretch;
m_swipeContentStackPanel.VerticalAlignment = VerticalAlignment.Center;
}
else
{
m_swipeContentStackPanel.HorizontalAlignment = HorizontalAlignment.Center;
m_swipeContentStackPanel.VerticalAlignment = VerticalAlignment.Stretch;
}
break;
}
case SwipeMode.Reveal:
{
if (m_isHorizontal)
{
var swipeContentStackPanelHorizontalAlignment = m_createdContent == CreatedContent.Left ? HorizontalAlignment.Left :
m_createdContent == CreatedContent.Right ? HorizontalAlignment.Right :
HorizontalAlignment.Stretch;
m_swipeContentStackPanel.HorizontalAlignment = swipeContentStackPanelHorizontalAlignment;
m_swipeContentStackPanel.VerticalAlignment = VerticalAlignment.Center;
}
else
{
var swipeContentStackPanelVerticalAlignment = m_createdContent == CreatedContent.Top ? VerticalAlignment.Top :
m_createdContent == CreatedContent.Bottom ? VerticalAlignment.Bottom :
VerticalAlignment.Stretch;
m_swipeContentStackPanel.HorizontalAlignment = HorizontalAlignment.Center;
m_swipeContentStackPanel.VerticalAlignment = swipeContentStackPanelVerticalAlignment;
}
break;
}
default:
global::System.Diagnostics.Debug.Assert(false);
break;
}
}
}
private void PopulateContentItems()
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
foreach (var swipeItem in m_currentItems)
{
m_swipeContentStackPanel.Children.Add(GetSwipeItemButton(swipeItem));
}
TryGetSwipeVisuals();
}
private void SetupExecuteExpressionAnimation()
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
//if (IsTranslationFacadeAvailableForSwipeControl(m_swipeContentStackPanel))
//{
// m_swipeContentStackPanel.StopAnimation(m_executeExpressionAnimation);
// m_swipeContentStackPanel.Translation = new Vector3(
// 0.0f, 0.0f, 0.0f
// );
//}
//else if (m_swipeContentVisual is { })
//{
// m_swipeContentVisual.StopAnimation(GetAnimationTarget(m_swipeContentStackPanel));
// m_swipeContentVisual.Properties.InsertVector3(GetAnimationTarget(m_swipeContentStackPanel), new Vector3(
// 0.0f, 0.0f, 0.0f
// ));
//}
if (m_currentItems.Mode == SwipeMode.Execute)
{
//global::System.Diagnostics.Debug.Assert((m_createdContent != CreatedContent.None));
//m_executeExpressionAnimation.SetBooleanParameter(s_isNearContentPropertyName, m_createdContent == CreatedContent.Left || m_createdContent == CreatedContent.Top);
//if (IsTranslationFacadeAvailableForSwipeControl(m_swipeContentStackPanel))
//{
// m_swipeContentStackPanel.StartAnimation(m_executeExpressionAnimation);
//}
//if (m_swipeContentVisual is {})
//{
// m_swipeContentVisual.StartAnimation(GetAnimationTarget(m_swipeContentStackPanel), m_executeExpressionAnimation);
//}
}
}
private void SetupClipAnimation()
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
//if (m_insetClip is null)
//{
// m_insetClip = m_compositor.CreateInsetClip();
// m_swipeContentRootVisual.Clip = m_insetClip;
//}
//else
//{
// m_insetClip.StopAnimation(s_leftInsetTargetName);
// m_insetClip.StopAnimation(s_rightInsetTargetName);
// m_insetClip.StopAnimation(s_topInsetTargetName);
// m_insetClip.StopAnimation(s_bottomInsetTargetName);
// m_insetClip.LeftInset = 0.0f;
// m_insetClip.RightInset = 0.0f;
// m_insetClip.TopInset = 0.0f;
// m_insetClip.BottomInset = 0.0f;
//}
//m_clipExpressionAnimation.SetBooleanParameter(s_isNearContentPropertyName, m_createdContent == CreatedContent.Left || m_createdContent == CreatedContent.Top);
//if (m_createdContent == CreatedContent.None)
//{
// //If we have no created content then we don't need to start the clip animation yet.
// return;
//}
//m_insetClip.StartAnimation(DirectionToInset(m_createdContent), m_clipExpressionAnimation);
}
private void UpdateColors()
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
if (m_currentItems.Mode == SwipeMode.Execute)
{
UpdateColorsIfExecuteItem();
}
else
{
UpdateColorsIfRevealItems();
}
}
AppBarButton GetSwipeItemButton(SwipeItem swipeItem)
{
AppBarButton itemAsButton = new AppBarButton();
swipeItem.GenerateControl(itemAsButton, m_swipeItemStyle);
if (swipeItem.Background is null)
{
var lookedUpBrush = SharedHelpers.FindInApplicationResources(m_currentItems.Mode == SwipeMode.Reveal ? s_swipeItemBackgroundResourceName : m_thresholdReached ? s_executeSwipeItemPostThresholdBackgroundResourceName : s_executeSwipeItemPreThresholdBackgroundResourceName);
if (lookedUpBrush is { })
{
itemAsButton.Background = lookedUpBrush as Brush;
}
}
if (swipeItem.Foreground is null)
{
var lookedUpBrush = SharedHelpers.FindInApplicationResources(m_currentItems.Mode == SwipeMode.Reveal ? s_swipeItemForegroundResourceName : m_thresholdReached ? s_executeSwipeItemPostThresholdForegroundResourceName : s_executeSwipeItemPreThresholdForegroundResourceName);
if (lookedUpBrush is { })
{
itemAsButton.Foreground = lookedUpBrush as Brush;
}
}
if (m_isHorizontal)
{
itemAsButton.Height = ActualHeight;
if (m_currentItems.Mode == SwipeMode.Execute)
{
itemAsButton.Width = ActualWidth;
}
}
else
{
itemAsButton.Width = (ActualWidth);
if (m_currentItems.Mode == SwipeMode.Execute)
{
itemAsButton.Height = (ActualHeight);
}
}
return itemAsButton;
}
private void UpdateColorsIfExecuteItem()
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
if (m_currentItems is null || m_currentItems.Mode != SwipeMode.Execute)
{
return;
}
SwipeItem swipeItem = null;
if (m_currentItems.Size > 0)
{
swipeItem = m_currentItems.GetAt(0);
}
UpdateExecuteBackgroundColor(swipeItem);
UpdateExecuteForegroundColor(swipeItem);
}
private void UpdateExecuteBackgroundColor(SwipeItem swipeItem)
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
Brush background = null;
if (!m_thresholdReached)
{
var lookedUpBackgroundBrush = SharedHelpers.FindInApplicationResources(s_executeSwipeItemPreThresholdBackgroundResourceName);
if (lookedUpBackgroundBrush is { })
{
background = lookedUpBackgroundBrush as Brush;
}
}
else
{
var lookedUpBackgroundBrush = SharedHelpers.FindInApplicationResources(s_executeSwipeItemPostThresholdBackgroundResourceName);
if (lookedUpBackgroundBrush is { })
{
background = lookedUpBackgroundBrush as Brush;
}
}
if (swipeItem is { } && swipeItem.Background is { })
{
background = swipeItem.Background;
}
m_swipeContentStackPanel.Background = background;
m_swipeContentRoot.Background = null;
}
private void UpdateExecuteForegroundColor(SwipeItem swipeItem)
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
if (m_swipeContentStackPanel.Children.Count > 0)
{
if (m_swipeContentStackPanel.Children[0] is AppBarButton appBarButton)
{
Brush foreground = null;
if (!m_thresholdReached)
{
var lookedUpForegroundBrush = SharedHelpers.FindInApplicationResources(s_executeSwipeItemPreThresholdForegroundResourceName);
if (lookedUpForegroundBrush is { })
{
foreground = lookedUpForegroundBrush as Brush;
}
}
else
{
var lookedUpForegroundBrush = SharedHelpers.FindInApplicationResources(s_executeSwipeItemPostThresholdForegroundResourceName);
if (lookedUpForegroundBrush is { })
{
foreground = lookedUpForegroundBrush as Brush;
}
}
if (swipeItem is { } && swipeItem.Foreground is { })
{
foreground = swipeItem.Foreground;
}
appBarButton.Foreground = foreground;
appBarButton.Background = new SolidColorBrush(Colors.Transparent);
}
}
}
private void UpdateColorsIfRevealItems()
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
if (m_currentItems.Mode != SwipeMode.Reveal)
{
return;
}
Brush rootGridBackground = null;
var lookedUpBrush = SharedHelpers.FindInApplicationResources(s_swipeItemBackgroundResourceName);
if (lookedUpBrush is { })
{
rootGridBackground = lookedUpBrush as Brush;
}
if (m_currentItems.Size > 0)
{
switch (m_createdContent)
{
case CreatedContent.Left:
case CreatedContent.Top:
{
var itemBackground = m_currentItems.GetAt((uint)m_swipeContentStackPanel.Children.Count - 1).Background;
if (itemBackground != null)
{
rootGridBackground = itemBackground;
}
break;
}
case CreatedContent.Right:
case CreatedContent.Bottom:
{
var itemBackground = m_currentItems.GetAt(0).Background;
if (itemBackground != null)
{
rootGridBackground = itemBackground;
}
break;
}
case CreatedContent.None:
{
break;
}
default:
global::System.Diagnostics.Debug.Assert(false);
break;
}
}
m_swipeContentRoot.Background = rootGridBackground;
m_swipeContentStackPanel.Background = null;
}
private void OnLeftItemsChanged(IObservableVector<SwipeItem> sender, IVectorChangedEventArgs args)
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
ThrowIfHasVerticalAndHorizontalContent();
//if (m_interactionTracker is {})
//{
// m_interactionTracker.Properties.InsertBoolean(s_hasLeftContentPropertyName, sender.Count > 0);
//}
// Uno workaround:
_hasLeftContent = sender.Count > 0;
if (m_createdContent == CreatedContent.Left)
{
CreateLeftContent();
}
}
private void OnRightItemsChanged(IObservableVector<SwipeItem> sender, IVectorChangedEventArgs args)
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
ThrowIfHasVerticalAndHorizontalContent();
//if (m_interactionTracker is {})
//{
// m_interactionTracker.Properties.InsertBoolean(s_hasRightContentPropertyName, sender.Count > 0);
//}
// Uno workaround:
_hasRightContent = sender.Count > 0;
if (m_createdContent == CreatedContent.Right)
{
CreateRightContent();
}
}
private void OnTopItemsChanged(IObservableVector<SwipeItem> sender, IVectorChangedEventArgs args)
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
ThrowIfHasVerticalAndHorizontalContent();
//if (m_interactionTracker is {})
//{
// m_interactionTracker.Properties.InsertBoolean(s_hasTopContentPropertyName, sender.Count > 0);
//}
// Uno workaround:
_hasTopContent = sender.Count > 0;
if (m_createdContent == CreatedContent.Top)
{
CreateTopContent();
}
}
private void OnBottomItemsChanged(IObservableVector<SwipeItem> sender, IVectorChangedEventArgs args)
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
ThrowIfHasVerticalAndHorizontalContent();
//if (m_interactionTracker is {})
//{
// m_interactionTracker.Properties.InsertBoolean(s_hasBottomContentPropertyName, sender.Count > 0);
//}
// Uno workaround:
_hasBottomContent = sender.Count > 0;
if (m_createdContent == CreatedContent.Bottom)
{
CreateBottomContent();
}
}
private void TryGetSwipeVisuals()
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
//if (IsTranslationFacadeAvailableForSwipeControl(m_content))
//{
// m_swipeAnimation.Target = GetAnimationTarget(m_content);
// m_content.StartAnimation(m_swipeAnimation);
//}
//else
//{
// var mainContentVisual = ElementCompositionPreview.GetElementVisual(m_content);
// if (mainContentVisual is {} && m_mainContentVisual != mainContentVisual)
// {
// m_mainContentVisual = mainContentVisual;
// if (DownlevelHelper.SetIsTranslationEnabledExists())
// {
// ElementCompositionPreview.SetIsTranslationEnabled(m_content, true);
// mainContentVisual.Properties.InsertVector3(s_translationPropertyName, new Vector3(
// 0.0f, 0.0f, 0.0f
// ));
// }
// mainContentVisual.StartAnimation(GetAnimationTarget(m_content), m_swipeAnimation);
// m_executeExpressionAnimation.SetReferenceParameter(s_foregroundVisualPropertyName, mainContentVisual);
// }
//}
//if (IsTranslationFacadeAvailableForSwipeControl(m_swipeContentStackPanel))
//{
// m_swipeAnimation.Target = GetAnimationTarget(m_swipeContentStackPanel);
//}
//else
//{
// var swipeContentVisual = ElementCompositionPreview.GetElementVisual(m_swipeContentStackPanel);
// if (swipeContentVisual is {} && m_swipeContentVisual != swipeContentVisual)
// {
// m_swipeContentVisual = swipeContentVisual;
// if (DownlevelHelper.SetIsTranslationEnabledExists())
// {
// ElementCompositionPreview.SetIsTranslationEnabled(m_swipeContentStackPanel, true);
// swipeContentVisual.Properties.InsertVector3(s_translationPropertyName, new Vector3(
// 0.0f, 0.0f, 0.0f
// ));
// }
// ConfigurePositionInertiaRestingValues();
// }
//}
//var swipeContentRootVisual = ElementCompositionPreview.GetElementVisual(m_swipeContentRoot);
//if (swipeContentRootVisual is {} && m_swipeContentRootVisual != swipeContentRootVisual)
//{
// m_swipeContentRootVisual = swipeContentRootVisual;
// m_clipExpressionAnimation.SetReferenceParameter(s_swipeRootVisualPropertyName, swipeContentRootVisual);
// if (m_insetClip is {})
// {
// swipeContentRootVisual.Clip = m_insetClip;
// }
//}
}
private void UpdateIsOpen(bool isOpen)
{
SWIPECONTROL_TRACE_INFO(this/*, TRACE_MSG_METH, METH_NAME, this*/);
if (isOpen)
{
if (!m_isOpen)
{
m_isOpen = true;
m_lastActionWasOpening = true;
switch (m_createdContent)
{
case CreatedContent.Right:
case CreatedContent.Bottom:
//m_interactionTracker.Properties.InsertBoolean(s_isFarOpenPropertyName, true);
//m_interactionTracker.Properties.InsertBoolean(s_isNearOpenPropertyName, false);
// Uno workaround:
_isFarOpen = true;
_isNearOpen = false;
break;
case CreatedContent.Left:
case CreatedContent.Top:
//m_interactionTracker.Properties.InsertBoolean(s_isFarOpenPropertyName, false);
//m_interactionTracker.Properties.InsertBoolean(s_isNearOpenPropertyName, true);
// Uno workaround:
_isFarOpen = false;
_isNearOpen = true;
break;
case CreatedContent.None:
//m_interactionTracker.Properties.InsertBoolean(s_isFarOpenPropertyName, false);
//m_interactionTracker.Properties.InsertBoolean(s_isNearOpenPropertyName, false);
// Uno workaround:
_isFarOpen = false;
_isNearOpen = false;
break;
default:
global::System.Diagnostics.Debug.Assert(false);
break;
}
if (m_currentItems.Mode != SwipeMode.Execute)
{
AttachDismissingHandlers();
}
var globalTestHooks = SwipeTestHooks.GetGlobalTestHooks();
if (globalTestHooks is { })
{
globalTestHooks.NotifyOpenedStatusChanged(this);
}
}
}
else
{
if (m_isOpen)
{
m_isOpen = false;
m_lastActionWasClosing = true;
DetachDismissingHandlers();
//m_interactionTracker.Properties.InsertBoolean(s_isFarOpenPropertyName, false);
//m_interactionTracker.Properties.InsertBoolean(s_isNearOpenPropertyName, false);
// Uno workaround:
_isFarOpen = false;
_isNearOpen = false;
var globalTestHooks = SwipeTestHooks.GetGlobalTestHooks();
if (globalTestHooks is { })
{
globalTestHooks.NotifyOpenedStatusChanged(this);
}
}
}
}
private void UpdateThresholdReached(float value)
{
SWIPECONTROL_TRACE_VERBOSE(this/*, TRACE_MSG_METH, METH_NAME, this*/);
bool oldValue = m_thresholdReached;
float effectiveStackPanelSize = (float)((m_isHorizontal ? m_swipeContentStackPanel.ActualWidth : m_swipeContentStackPanel.ActualHeight) - 1);
if (!m_isOpen || m_lastActionWasOpening)
{
//If we are opening new swipe items then we need to scroll open c_ThresholdValue
m_thresholdReached = Math.Abs(value) > Math.Min(effectiveStackPanelSize, c_ThresholdValue);
}
else
{
//If we already have an open swipe item then swiping it closed by any amount will close it.
m_thresholdReached = Math.Abs(value) < effectiveStackPanelSize;
}
if (m_thresholdReached != oldValue)
{
UpdateColorsIfExecuteItem();
}
}
private void ThrowIfHasVerticalAndHorizontalContent(bool setIsHorizontal = false)
{
bool hasLeftContent = LeftItems is { } && LeftItems.Size > 0;
bool hasRightContent = RightItems is { } && RightItems.Size > 0;
bool hasTopContent = TopItems is { } && TopItems.Size > 0;
bool hasBottomContent = BottomItems is { } && BottomItems.Size > 0;
if (setIsHorizontal)
{
m_isHorizontal = hasLeftContent || hasRightContent || !(hasTopContent || hasBottomContent);
}
if (this.Template is { })
{
if (m_isHorizontal && (hasTopContent || hasBottomContent))
{
throw new ArgumentException("This SwipeControl is horizontal and can not have vertical items.");
}
if (!m_isHorizontal && (hasLeftContent || hasRightContent))
{
throw new ArgumentException("This SwipeControl is vertical and can not have horizontal items.");
}
}
else
{
if ((hasLeftContent || hasRightContent) && (hasTopContent || hasBottomContent))
{
throw new ArgumentException("SwipeControl can't have both horizontal items and vertical items set at the same time.");
}
}
}
#if false
private string GetAnimationTarget(UIElement child)
{
if (DownlevelHelper.SetIsTranslationEnabledExists() || SharedHelpers.IsTranslationFacadeAvailable(child))
{
return s_translationPropertyName;
}
else
{
return s_offsetPropertyName;
}
}
private SwipeControl GetThis()
{
return this;
}
private bool IsTranslationFacadeAvailableForSwipeControl(UIElement element)
{
//For now Facade's are causing more issues than they are worth for swipe control. Revist this
//when we have a little more time.
//There are concerns about swipe consumers having taken a dependency on the ElementCompositionPreview
//Api's that this is exclusive with and also the target property of the swipe expression animations
//is not resolving with the use of Facade's
return false;
//return SharedHelpers.IsTranslationFacadeAvailable(element);
}
private string DirectionToInset(CreatedContent createdContent)
{
switch (createdContent)
{
case CreatedContent.Right:
return s_leftInsetTargetName;
case CreatedContent.Left:
return s_rightInsetTargetName;
case CreatedContent.Bottom:
return s_topInsetTargetName;
case CreatedContent.Top:
return s_bottomInsetTargetName;
case CreatedContent.None:
return "";
default:
global::System.Diagnostics.Debug.Assert(false);
return "";
}
}
#endif
}
}
| SwipeControl |
csharp | nunit__nunit | src/NUnitFramework/framework/Constraints/DelayedConstraint.cs | {
"start": 394,
"end": 627
} | public class ____ : PrefixConstraint
{
/// <summary>
/// Allows only changing the time dimension of delay interval and setting a polling interval of a DelayedConstraint
/// </summary>
| DelayedConstraint |
csharp | bitwarden__server | src/Infrastructure.EntityFramework/Repositories/OrganizationConnectionRepository.cs | {
"start": 259,
"end": 2241
} | public class ____ : Repository<OrganizationConnection, Models.OrganizationConnection, Guid>, IOrganizationConnectionRepository
{
public OrganizationConnectionRepository(IServiceScopeFactory serviceScopeFactory,
IMapper mapper)
: base(serviceScopeFactory, mapper, context => context.OrganizationConnections)
{
}
public async Task<OrganizationConnection?> GetByIdOrganizationIdAsync(Guid id, Guid organizationId)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var connection = await dbContext.OrganizationConnections
.FirstOrDefaultAsync(oc => oc.Id == id && oc.OrganizationId == organizationId);
return Mapper.Map<OrganizationConnection>(connection);
}
}
public async Task<ICollection<OrganizationConnection>> GetByOrganizationIdTypeAsync(Guid organizationId, OrganizationConnectionType type)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var connections = await dbContext.OrganizationConnections
.Where(oc => oc.OrganizationId == organizationId && oc.Type == type)
.ToListAsync();
return Mapper.Map<List<OrganizationConnection>>(connections);
}
}
public async Task<ICollection<OrganizationConnection>> GetEnabledByOrganizationIdTypeAsync(Guid organizationId, OrganizationConnectionType type)
{
using (var scope = ServiceScopeFactory.CreateScope())
{
var dbContext = GetDatabaseContext(scope);
var connections = await dbContext.OrganizationConnections
.Where(oc => oc.OrganizationId == organizationId && oc.Type == type && oc.Enabled)
.ToListAsync();
return Mapper.Map<List<OrganizationConnection>>(connections);
}
}
}
| OrganizationConnectionRepository |
csharp | Cysharp__UniTask | src/UniTask/Assets/Plugins/UniTask/Runtime/Linq/GroupBy.cs | {
"start": 17412,
"end": 18366
} | internal sealed class ____<TSource, TKey, TElement> : IUniTaskAsyncEnumerable<IGrouping<TKey, TElement>>
{
readonly IUniTaskAsyncEnumerable<TSource> source;
readonly Func<TSource, TKey> keySelector;
readonly Func<TSource, TElement> elementSelector;
readonly IEqualityComparer<TKey> comparer;
public GroupBy(IUniTaskAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey> comparer)
{
this.source = source;
this.keySelector = keySelector;
this.elementSelector = elementSelector;
this.comparer = comparer;
}
public IUniTaskAsyncEnumerator<IGrouping<TKey, TElement>> GetAsyncEnumerator(CancellationToken cancellationToken = default)
{
return new _GroupBy(source, keySelector, elementSelector, comparer, cancellationToken);
}
| GroupBy |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.UI.ViewManagement/ActivationViewSwitcher.cs | {
"start": 300,
"end": 2584
} | public partial class ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal ActivationViewSwitcher()
{
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.Foundation.IAsyncAction ShowAsStandaloneAsync(int viewId)
{
throw new global::System.NotImplementedException("The member IAsyncAction ActivationViewSwitcher.ShowAsStandaloneAsync(int viewId) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IAsyncAction%20ActivationViewSwitcher.ShowAsStandaloneAsync%28int%20viewId%29");
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.Foundation.IAsyncAction ShowAsStandaloneAsync(int viewId, global::Windows.UI.ViewManagement.ViewSizePreference sizePreference)
{
throw new global::System.NotImplementedException("The member IAsyncAction ActivationViewSwitcher.ShowAsStandaloneAsync(int viewId, ViewSizePreference sizePreference) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IAsyncAction%20ActivationViewSwitcher.ShowAsStandaloneAsync%28int%20viewId%2C%20ViewSizePreference%20sizePreference%29");
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public bool IsViewPresentedOnActivationVirtualDesktop(int viewId)
{
throw new global::System.NotImplementedException("The member bool ActivationViewSwitcher.IsViewPresentedOnActivationVirtualDesktop(int viewId) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20ActivationViewSwitcher.IsViewPresentedOnActivationVirtualDesktop%28int%20viewId%29");
}
#endif
}
}
| ActivationViewSwitcher |
csharp | dotnet__aspire | src/Aspire.Hosting.Kubernetes/Resources/NodeSelectorTermV1.cs | {
"start": 711,
"end": 1899
} | public sealed class ____
{
/// <summary>
/// Gets the list of match expressions that are used to define the conditions for node selection.
/// </summary>
/// <remarks>
/// MatchExpressions is a collection of node selector requirements, each specifying a key, an operator,
/// and an optional set of values. This allows defining complex rules for selecting nodes based on
/// their labels or attributes.
/// </remarks>
[YamlMember(Alias = "matchExpressions")]
public List<NodeSelectorRequirementV1> MatchExpressions { get; } = [];
/// <summary>
/// A collection of node selector requirements used to match fields in a Kubernetes node's metadata.
/// </summary>
/// <remarks>
/// MatchFields contains a list of criteria that define field-based conditions
/// for selecting nodes in Kubernetes. Each condition is represented by an instance
/// of <see cref="NodeSelectorRequirementV1"/>, which specifies a key, operator,
/// and optional set of values used for evaluation.
/// </remarks>
[YamlMember(Alias = "matchFields")]
public List<NodeSelectorRequirementV1> MatchFields { get; } = [];
}
| NodeSelectorTermV1 |
csharp | OrchardCMS__OrchardCore | src/OrchardCore.Modules/OrchardCore.Admin/Startup.cs | {
"start": 3432,
"end": 3768
} | public sealed class ____ : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.AddSiteSettingsPropertyDeploymentStep<AdminSettings, DeploymentStartup>(S => S["Admin settings"], S => S["Exports the admin settings."]);
}
}
[RequireFeatures("OrchardCore.Liquid")]
| DeploymentStartup |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.Appointments/AppointmentWeekOfMonth.cs | {
"start": 275,
"end": 946
} | public enum ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
First = 0,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Second = 1,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Third = 2,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Fourth = 3,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Last = 4,
#endif
}
#endif
}
| AppointmentWeekOfMonth |
csharp | dotnet__maui | src/Controls/tests/TestCases.HostApp/Issues/Issue26065.xaml.cs | {
"start": 238,
"end": 575
} | public partial class ____ : ContentPage
{
public Issue26065()
{
InitializeComponent();
BindingContext = new BookViewModel();
}
private void Button_Clicked(object sender, EventArgs e)
{
if (collView.ItemsLayout is LinearItemsLayout linearItemsLayout)
{
linearItemsLayout.ItemSpacing = 20;
}
}
}
| Issue26065 |
csharp | NEventStore__NEventStore | src/NEventStore/Persistence/InMemory/InMemoryPersistenceEngine.cs | {
"start": 14892,
"end": 15491
} | private class ____ : Commit
{
public InMemoryCommit(
string bucketId,
string streamId,
int streamRevision,
Guid commitId,
int commitSequence,
DateTime commitStamp,
Int64 checkpointToken,
IDictionary<string, object> headers,
ICollection<EventMessage> events)
: base(bucketId, streamId, streamRevision, commitId, commitSequence, commitStamp, checkpointToken, headers, events)
{ }
}
| InMemoryCommit |
csharp | ChilliCream__graphql-platform | src/StrawberryShake/Client/test/Core.Tests/Json/JsonErrorParserTests.cs | {
"start": 58,
"end": 7854
} | public class ____
{
[Fact]
public void Error_With_Message()
{
// arrange
var result = JsonDocument.Parse(@" [ { ""message"": ""errors"" } ] ");
// act
var errors = JsonErrorParser.ParseErrors(result.RootElement);
// assert
Assert.Collection(errors!, error => Assert.Equal("errors", error.Message));
}
[Fact]
public void Error_Has_No_Message()
{
// arrange
var result = JsonDocument.Parse("[{ }]");
// act
var errors = JsonErrorParser.ParseErrors(result.RootElement);
// assert
Assert.Collection(
errors!,
error => Assert.Equal(
"The error format is invalid and was missing the property `message`.",
error.Message));
}
[Fact]
public void Error_With_Path()
{
// arrange
var result = JsonDocument.Parse(
"""
[
{
"message": "errors",
"path": [ 1, "foo", 2, "bar" ]
}
]
""");
// act
var errors = JsonErrorParser.ParseErrors(result.RootElement);
// assert
Assert.Collection(
errors!,
error =>
{
Assert.Equal("errors", error.Message);
Assert.Collection(
error.Path!,
element => Assert.Equal(1, Assert.IsType<int>(element)),
element => Assert.Equal("foo", Assert.IsType<string>(element)),
element => Assert.Equal(2, Assert.IsType<int>(element)),
element => Assert.Equal("bar", Assert.IsType<string>(element)));
});
}
[Fact]
public void Error_With_Path_With_Invalid_Path_Value()
{
// arrange
var result = JsonDocument.Parse(
"""
[
{
"message": "errors",
"path": [ true ]
}
]
""");
// act
var errors = JsonErrorParser.ParseErrors(result.RootElement);
// assert
Assert.Collection(
errors!,
error =>
{
Assert.Equal("errors", error.Message);
Assert.Collection(
error.Path!,
element => Assert.Equal(
"NOT_SUPPORTED_VALUE",
Assert.IsType<string>(element)));
});
}
[Fact]
public void Error_With_Locations()
{
// arrange
var result = JsonDocument.Parse(
"""
[
{
"message": "errors",
"locations": [ { "line": 1, "column": 5 } ]
}
]
""");
// act
var errors = JsonErrorParser.ParseErrors(result.RootElement);
// assert
Assert.Collection(
errors!,
error =>
{
Assert.Equal("errors", error.Message);
Assert.Collection(
error.Locations!,
location =>
{
Assert.Equal(1, location.Line);
Assert.Equal(5, location.Column);
});
});
}
[Fact]
public void Error_With_Extensions()
{
// arrange
var result = JsonDocument.Parse(
"""
[
{
"message": "errors",
"extensions":
{
"s": "abc",
"i": 5,
"f": 1.5,
"true": true,
"false": false,
"null": null,
"il": [ 1, 2, 3 ],
"sl": [ "a", "b" ],
"ol": [ { "s": "abc" } ]
}
}
]
""");
// act
var errors = JsonErrorParser.ParseErrors(result.RootElement);
// assert
Assert.Collection(
errors!,
error =>
{
Assert.Equal("errors", error.Message);
error.Extensions.MatchSnapshot();
});
}
[Fact]
public void Error_With_Extensions_Code()
{
// arrange
var result = JsonDocument.Parse(
"""
[
{
"message": "errors",
"extensions":
{
"code": "CS1234"
}
}
]
""");
// act
var errors = JsonErrorParser.ParseErrors(result.RootElement);
// assert
Assert.Collection(
errors!,
error =>
{
Assert.Equal("errors", error.Message);
Assert.Equal("CS1234", error.Code);
error.Extensions.MatchSnapshot();
});
}
[Fact]
public void Error_With_Code()
{
// arrange
var result = JsonDocument.Parse(
"""
[
{
"message": "errors",
"code": "CS1234"
}
]
""");
// act
var errors = JsonErrorParser.ParseErrors(result.RootElement);
// assert
Assert.Collection(
errors!,
error =>
{
Assert.Equal("errors", error.Message);
Assert.Equal("CS1234", error.Code);
});
}
[Fact]
public void Error_With_Root_Code_Takes_Preference()
{
// arrange
var result = JsonDocument.Parse(
"""
[
{
"message": "errors",
"code": "CSROOT",
"extensions":
{
"code": "CS1234"
}
}
]
""");
// act
var errors = JsonErrorParser.ParseErrors(result.RootElement);
// assert
Assert.Collection(
errors!,
error =>
{
Assert.Equal("errors", error.Message);
Assert.Equal("CSROOT", error.Code);
error.Extensions.MatchSnapshot();
});
}
[Fact]
public void Parsing_Error()
{
// arrange
var result = JsonDocument.Parse(
"""
[
{
"message": "errors",
"locations": [ { "column": 5 } ]
},
{
"message": "errors",
"locations": [ { "column": 5 } ]
}
]
""");
// act
var errors = JsonErrorParser.ParseErrors(result.RootElement);
// assert
Assert.Collection(
errors!,
error =>
{
Assert.Equal("Error parsing a server error.", error.Message);
Assert.NotNull(error.Exception);
},
error =>
{
Assert.Equal("Error parsing a server error.", error.Message);
Assert.NotNull(error.Exception);
});
}
[Fact]
public void Parsing_Errors_Is_Null()
{
// arrange
var result = JsonDocument.Parse("null");
// act
var errors = JsonErrorParser.ParseErrors(result.RootElement);
// assert
Assert.Null(errors);
}
}
| JsonErrorParserTests |
csharp | OrchardCMS__OrchardCore | src/OrchardCore/OrchardCore.DisplayManagement.Liquid/LiquidHttpContextAccessor.cs | {
"start": 70,
"end": 193
} | class ____ allows modules to extend the `HttpContext` property in the current Liquid scope.
/// </summary>
[Obsolete("This | that |
csharp | xunit__xunit | src/xunit.v3.core.tests/Framework/TheoryDiscovererTests.cs | {
"start": 16558,
"end": 17621
} | class ____
{
[Theory(Skip = "I have data")]
[InlineData(42)]
[InlineData(2112)]
public void TestMethod(int _) { }
}
[Fact]
public async ValueTask TheoryWithSerializableInputDataThatIsntSerializableAfterConversion_YieldsSingleTheoryTestCase()
{
TestContextInternal.Current.DiagnosticMessageSink = SpyMessageSink.Capture();
var discoverer = new TheoryDiscoverer();
var testMethod = TestData.XunitTestMethod<ClassWithExplicitConvertedData>(nameof(ClassWithExplicitConvertedData.ParameterDeclaredExplicitConversion));
var factAttribute = testMethod.FactAttributes.FirstOrDefault() ?? throw new InvalidOperationException("Could not find fact attribute");
var testCases = await discoverer.Discover(discoveryOptions, testMethod, factAttribute);
var testCase = Assert.Single(testCases);
Assert.IsType<XunitDelayEnumeratedTheoryTestCase>(testCase);
Assert.Equal($"{typeof(ClassWithExplicitConvertedData).FullName}.{nameof(ClassWithExplicitConvertedData.ParameterDeclaredExplicitConversion)}", testCase.TestCaseDisplayName);
}
| SkippedWithData |
csharp | protobuf-net__protobuf-net | src/Examples/Issues/SO7727355.cs | {
"start": 601,
"end": 823
} | public abstract class ____ : EntityBaseTest
{
[ProtoMember(2)]
public string Prop2 { get; set; }
}
[ProtoContract, ProtoInclude(10, typeof(WebEntityTest))]
| WebEntityTest |
csharp | Cysharp__UniTask | src/UniTask/Assets/Plugins/UniTask/Runtime/Triggers/MonoBehaviourMessagesTriggers.cs | {
"start": 138200,
"end": 138543
} | public partial class ____<T> : IAsyncOnPointerExitHandler
{
UniTask<PointerEventData> IAsyncOnPointerExitHandler.OnPointerExitAsync()
{
core.Reset();
return new UniTask<PointerEventData>((IUniTaskSource<PointerEventData>)(object)this, core.Version);
}
}
public static | AsyncTriggerHandler |
csharp | smartstore__Smartstore | src/Smartstore.Core/Catalog/Rules/ProductRuleEvaluatorTask.cs | {
"start": 383,
"end": 5880
} | public partial class ____ : ITask
{
protected readonly SmartDbContext _db;
protected readonly IRuleService _ruleService;
protected readonly IProductRuleProvider _productRuleProvider;
public ProductRuleEvaluatorTask(
SmartDbContext db,
IRuleService ruleService,
IRuleProviderFactory ruleProviderFactory)
{
_db = db;
_ruleService = ruleService;
_productRuleProvider = ruleProviderFactory.GetProvider<IProductRuleProvider>(RuleScope.Product);
}
public async Task Run(TaskExecutionContext ctx, CancellationToken cancelToken = default)
{
var count = 0;
var numDeleted = 0;
var numAdded = 0;
var numCategories = 0;
var pageSize = 500;
var pageIndex = -1;
var categoryIds = ctx.Parameters.TryGetValue("CategoryIds", out string value) ? value.ToIntArray() : null;
// Hooks are enabled because search index needs to be updated.
using (var scope = new DbContextScope(_db, autoDetectChanges: false, minHookImportance: HookImportance.Normal, deferCommit: true))
{
// Delete existing system mappings.
var deleteQuery = _db.ProductCategories.Where(x => x.IsSystemMapping);
if (categoryIds != null)
{
deleteQuery = deleteQuery.Where(x => categoryIds.Contains(x.CategoryId));
}
var mappingsPager = new FastPager<ProductCategory>(deleteQuery, 500);
while ((await mappingsPager.ReadNextPageAsync<ProductCategory>(cancelToken)).Out(out var mappings))
{
_db.ProductCategories.RemoveRange(mappings);
await scope.CommitAsync(cancelToken);
numDeleted += mappings.Count;
}
// Insert new product category mappings.
var categoryQuery = _db.Categories
.Include(x => x.RuleSets)
.ThenInclude(x => x.Rules)
.AsSplitQuery()
.AsNoTracking();
if (categoryIds != null)
{
categoryQuery = categoryQuery.Where(x => categoryIds.Contains(x.Id));
}
var categories = await categoryQuery
.Where(x => x.RuleSets.Any(y => y.IsActive))
.ToListAsync(cancelToken);
numCategories = categories.Count;
foreach (var category in categories)
{
var ruleSetProductIds = new HashSet<int>();
await ctx.SetProgressAsync(++count, categories.Count, $"Add product mappings for category \"{category.Name.NaIfEmpty()}\".");
// Execute active rule sets and collect product ids.
foreach (var ruleSet in category.RuleSets.Where(x => x.IsActive))
{
if (cancelToken.IsCancellationRequested)
return;
var expressionGroup = await _ruleService.CreateExpressionGroupAsync(ruleSet, _productRuleProvider);
if (expressionGroup is SearchFilterExpression expression)
{
pageIndex = -1;
while (true)
{
// Do not touch searchResult.Hits. We only need the product identifiers.
var searchResult = await _productRuleProvider.SearchAsync([expression], ++pageIndex, pageSize);
ruleSetProductIds.AddRange(searchResult.HitsEntityIds);
if (pageIndex >= (searchResult.TotalHitsCount / pageSize))
{
break;
}
}
}
}
// Add mappings.
if (ruleSetProductIds.Count > 0)
{
foreach (var chunk in ruleSetProductIds.Chunk(500))
{
if (cancelToken.IsCancellationRequested)
return;
foreach (var productId in chunk)
{
_db.ProductCategories.Add(new ProductCategory
{
ProductId = productId,
CategoryId = category.Id,
IsSystemMapping = true
});
++numAdded;
}
await scope.CommitAsync(cancelToken);
}
DetachEntities();
}
}
}
Debug.WriteLineIf(numDeleted > 0 || numAdded > 0, $"Deleted {numDeleted} and added {numAdded} product mappings for {numCategories} categories.");
DetachEntities();
void DetachEntities()
{
CommonHelper.TryAction(() => _db.DetachEntities<ProductCategory>());
}
}
}
}
| ProductRuleEvaluatorTask |
csharp | dotnet__maui | src/Controls/samples/Controls.Sample/Pages/Controls/CollectionViewGalleries/SelectionGalleries/MultipleBoundSelection.xaml.cs | {
"start": 255,
"end": 1042
} | public partial class ____ : ContentPage
{
BoundSelectionModel _vm;
public MultipleBoundSelection()
{
_vm = new BoundSelectionModel();
BindingContext = _vm;
InitializeComponent();
}
private void ClearAndAdd(object sender, EventArgs e)
{
_vm.SelectedItems!.Clear();
_vm.SelectedItems!.Add(_vm.Items![1]);
_vm.SelectedItems!.Add(_vm.Items![2]);
}
private void ResetClicked(object sender, EventArgs e)
{
_vm.SelectedItems = new ObservableCollection<object>
{
_vm.Items![1],
_vm.Items![2]
};
}
private void DirectUpdateClicked(object sender, EventArgs e)
{
CollectionView.SelectedItems.Clear();
CollectionView.SelectedItems.Add(_vm.Items![0]);
CollectionView.SelectedItems.Add(_vm.Items![3]);
}
}
} | MultipleBoundSelection |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Gaming.Input.Custom/IHidGameControllerInputSink.cs | {
"start": 302,
"end": 620
} | public partial interface ____ : global::Windows.Gaming.Input.Custom.IGameControllerInputSink
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
void OnInputReportReceived(ulong timestamp, byte reportId, byte[] reportBuffer);
#endif
}
}
| IHidGameControllerInputSink |
csharp | dotnet__aspnetcore | src/Http/Http.Results/test/EmptyResultTests.cs | {
"start": 237,
"end": 1536
} | public class ____
{
[Fact]
public async Task EmptyResult_DoesNothing()
{
// Arrange
var emptyResult = EmptyHttpResult.Instance;
// Act
var httpContext = GetHttpContext();
var memoryStream = httpContext.Response.Body as MemoryStream;
await emptyResult.ExecuteAsync(httpContext);
// Assert
Assert.Equal(StatusCodes.Status200OK, httpContext.Response.StatusCode);
Assert.Equal(0, memoryStream.Length);
}
[Fact]
public async Task ExecuteAsync_ThrowsArgumentNullException_WhenHttpContextIsNull()
{
// Arrange
var result = EmptyHttpResult.Instance;
HttpContext httpContext = null;
// Act & Assert
await Assert.ThrowsAsync<ArgumentNullException>("httpContext", () => result.ExecuteAsync(httpContext));
}
private static HttpContext GetHttpContext()
{
var httpContext = new DefaultHttpContext();
httpContext.Request.PathBase = new PathString("");
httpContext.Response.Body = new MemoryStream();
httpContext.RequestServices = CreateServices();
return httpContext;
}
private static IServiceProvider CreateServices()
{
return new ServiceCollection().BuildServiceProvider();
}
}
| EmptyResultTests |
csharp | dotnet__extensions | test/Generators/Microsoft.Gen.Logging/TestClasses/LogPropertiesOmitParameterNameExtensions.cs | {
"start": 1263,
"end": 1560
} | internal static class ____
{
public static void ProvideProperties(ITagCollector list, MyProps? param)
{
list.Add(nameof(MyProps.P0), param?.P0);
list.Add("Custom_property_name", param?.P1);
}
}
}
}
| MyPropsProvider |
csharp | dotnet__aspnetcore | src/Identity/test/Identity.FunctionalTests/Pages/Account/Manage/SetPassword.cs | {
"start": 263,
"end": 909
} | public class ____ : DefaultUIPage
{
private readonly IHtmlFormElement _setPasswordForm;
public SetPassword(HttpClient client, IHtmlDocument setPassword, DefaultUIContext context)
: base(client, setPassword, context)
{
_setPasswordForm = HtmlAssert.HasForm("#set-password-form", setPassword);
}
public async Task<SetPassword> SetPasswordAsync(string newPassword)
{
await Client.SendAsync(_setPasswordForm, new Dictionary<string, string>
{
["Input_NewPassword"] = newPassword,
["Input_ConfirmPassword"] = newPassword
});
return this;
}
}
| SetPassword |
csharp | unoplatform__uno | src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/CommandBar/CommandBarTitle.cs | {
"start": 293,
"end": 1407
} | public partial class ____ : Control
{
public CommandBarTitle()
{
this.DefaultStyleKey = typeof(CommandBarTitle);
}
public string MainTitle
{
get { return (string)GetValue(MainTitleProperty); }
set { SetValue(MainTitleProperty, value); }
}
public static DependencyProperty MainTitleProperty { get; } =
DependencyProperty.Register("MainTitle", typeof(string), typeof(CommandBarTitle), new PropertyMetadata(string.Empty));
public string SubTitle1
{
get { return (string)GetValue(SubTitle1Property); }
set { SetValue(SubTitle1Property, value); }
}
public static DependencyProperty SubTitle1Property { get; } =
DependencyProperty.Register("SubTitle1", typeof(string), typeof(CommandBarTitle), new PropertyMetadata(string.Empty));
public string SubTitle2
{
get { return (string)GetValue(SubTitle2Property); }
set { SetValue(SubTitle2Property, value); }
}
public static DependencyProperty SubTitle2Property { get; } =
DependencyProperty.Register("SubTitle2", typeof(string), typeof(CommandBarTitle), new PropertyMetadata(string.Empty));
}
}
| CommandBarTitle |
csharp | NSubstitute__NSubstitute | tests/NSubstitute.Specs/PropertyHelperSpecs.cs | {
"start": 3329,
"end": 3614
} | public class ____
{
public string SomeProperty { get; set; }
public void SomeMethod() { }
public string WriteOnlyProperty { set { } }
public string this[int i] { get { return ""; } set { } }
}
}
} | ClassToTestPropertyHelper |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 354420,
"end": 354757
} | public partial interface ____ : ICreateClientCommandMutation_CreateClient_Client_Versions
{
}
/// <summary>
/// An edge in a connection.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| ICreateClientCommandMutation_CreateClient_Client_Versions_ClientVersionConnection |
csharp | EventStore__EventStore | src/KurrentDB.Core/Services/Transport/Http/Authentication/PasswordChangeNotificationReader.cs | {
"start": 3368,
"end": 4067
} | private class ____ {
#pragma warning disable 649
public string LoginName;
#pragma warning restore 649
}
private void PublishPasswordChangeNotificationFrom(ResolvedEvent @event) {
var data = @event.Event.Data;
try {
var notification = data.ParseJson<Notification>();
_publisher.Publish(new InternalAuthenticationProviderMessages.ResetPasswordCache(notification.LoginName));
} catch (JsonException ex) {
_log.Error("Failed to de-serialize event #{eventNumber}. Error: '{e}'", @event.OriginalEventNumber, ex.Message);
}
}
public void Handle(SystemMessage.SystemStart message) => Start();
public void Handle(SystemMessage.BecomeShutdown message) => _stopped = true;
}
| Notification |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Core/src/Types/Configuration/TypeInitializer.cs | {
"start": 27720,
"end": 28085
} | struct ____(
ITypeCompletionContext context,
RegisteredType type,
OperationType kind)
{
public ITypeCompletionContext Context { get; } = context;
public RegisteredType Type { get; } = type;
public OperationType Kind { get; } = kind;
public bool IsInitialized { get; } = true;
}
| RegisteredRootType |
csharp | dotnet__efcore | src/EFCore/Diagnostics/ISingletonInterceptor.cs | {
"start": 222,
"end": 497
} | interface ____ all Entity Framework interceptors that are registered as <see cref="ServiceLifetime.Singleton" />
/// services. This means a single instance is used by many <see cref="DbContext" /> instances.
/// The implementation must be thread-safe.
/// </summary>
| for |
csharp | ChilliCream__graphql-platform | src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs | {
"start": 880730,
"end": 881440
} | public partial interface ____
{
/// <summary>
/// A list of edges.
/// </summary>
public global::System.Collections.Generic.IReadOnlyList<global::ChilliCream.Nitro.CommandLine.Cloud.Client.IListClientCommandQuery_Node_Clients_Edges>? Edges { get; }
/// <summary>
/// Information to aid in pagination.
/// </summary>
public global::ChilliCream.Nitro.CommandLine.Cloud.Client.IListClientCommandQuery_Node_Clients_PageInfo PageInfo { get; }
}
/// <summary>
/// A connection to a list of items.
/// </summary>
[global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
| IListClientCommandQuery_Node_Clients |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.