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
ChilliCream__graphql-platform
src/HotChocolate/Fusion-vnext/test/Fusion.Tests.Shared/AutomaticMockingTests.cs
{ "start": 66481, "end": 67807 }
interface ____ { id: ID! } type Product implements Node { id: ID! name: String! } """; const string request = """ query { node(id: "5") { id ... on Product { name } } } """; // act var result = await ExecuteRequestAgainstSchemaAsync(request, schema); // assert result.MatchInlineSnapshot( """ { "errors": [ { "message": "Unexpected Execution Error", "locations": [ { "line": 2, "column": 3 } ], "path": [ "node" ] } ], "data": { "node": null } } """); } #endregion #region nodes [Fact] public async Task NodesField() { // arrange const string schema = """ type Query { nodes(ids: [ID!]!): [Node]! }
Node
csharp
cake-build__cake
src/Cake.Frosting/FrostingTaskTeardown.cs
{ "start": 357, "end": 480 }
public abstract class ____ : FrostingTaskTeardown<ICakeContext> { } /// <summary> /// Base
FrostingTaskTeardown
csharp
dotnet__machinelearning
src/Microsoft.ML.StandardTrainers/Standard/LogisticRegression/MulticlassLogisticRegression.cs
{ "start": 6676, "end": 7103 }
class ____ Regression"; internal const string ShortName = "mlr"; /// <summary> /// <see cref="Options"/> for <see cref="LbfgsMaximumEntropyMulticlassTrainer"/> as used in /// <see cref="Microsoft.ML.StandardTrainersCatalog.LbfgsMaximumEntropy(MulticlassClassificationCatalog.MulticlassClassificationTrainers, LbfgsMaximumEntropyMulticlassTrainer.Options)"/>. /// </summary>
Logistic
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/UseCases/JwtAuthProviderNoCookiesTests.cs
{ "start": 7879, "end": 22425 }
class ____() : AppSelfHostBase(nameof(JwtAuthProviderTests), typeof(JwtServices).Assembly) { public virtual JwtAuthProvider JwtAuthProvider { get; set; } public override void Configure(Container container) { var dbFactory = new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider); container.Register<IDbConnectionFactory>(dbFactory); container.Register<IAuthRepository>(c => new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>()) { UseDistinctRoleTables = true }); //Create UserAuth RDBMS Tables container.Resolve<IAuthRepository>().InitSchema(); //Also store User Sessions in SQL Server container.RegisterAs<OrmLiteCacheClient, ICacheClient>(); container.Resolve<ICacheClient>().InitSchema(); // just for testing, create a privateKeyXml on every instance Plugins.Add(new AuthFeature(() => new AuthUserSession(), [ new BasicAuthProvider(), new CredentialsAuthProvider(), JwtAuthProvider ])); Plugins.Add(new RegistrationFeature()); var authRepo = GetAuthRepository(); authRepo.CreateUserAuth(new UserAuth { Id = 1, UserName = Username, FirstName = "First", LastName = "Last", DisplayName = "Display", }, Password); } } protected abstract JwtAuthProvider CreateJwtAuthProvider(); protected virtual IJsonServiceClient GetClient() => new JsonServiceClient(Config.ListeningOn); protected virtual IJsonServiceClient GetClientWithBasicAuthCredentials() => new JsonServiceClient(Config.ListeningOn) { UserName = Username, Password = Password, }; protected virtual IJsonServiceClient GetClientWithRefreshToken(string refreshToken = null, string accessToken = null, bool useTokenCookie = false) { if (refreshToken == null) { refreshToken = GetRefreshToken(); } var client = GetClient(); if (client is JsonServiceClient serviceClient) { serviceClient.RefreshToken = refreshToken; if (!useTokenCookie) serviceClient.BearerToken = accessToken; return serviceClient; } if (client is JsonHttpClient httpClient) { httpClient.RefreshToken = refreshToken; if (!useTokenCookie) httpClient.BearerToken = accessToken; return httpClient; } throw new NotSupportedException(client.GetType().Name); } private static string CreateExpiredToken() { var jwtProvider = (JwtAuthProvider)AuthenticateService.GetAuthProvider(JwtAuthProviderReader.Name); jwtProvider.CreatePayloadFilter = (jwtPayload, session) => jwtPayload["exp"] = DateTime.UtcNow.AddSeconds(-1).ToUnixTime().ToString(); var token = jwtProvider.CreateJwtBearerToken(new AuthUserSession { UserAuthId = "1", DisplayName = "Test", Email = "as@if.com" }); jwtProvider.CreatePayloadFilter = null; return token; } private readonly ServiceStackHost appHost; public JwtAuthProviderNoCookiesTests() { appHost = new AppHost { JwtAuthProvider = CreateJwtAuthProvider() } .Init() .Start(Config.ListeningOn); } [OneTimeTearDown] public void OneTimeTearDown() => appHost.Dispose(); private string GetRefreshToken() { var authClient = GetClient(); var refreshToken = authClient.Send(new Authenticate { provider = "credentials", UserName = Username, Password = Password, }) .RefreshToken; return refreshToken; } [Test] public void Can_ConvertSessionToToken() { var authClient = GetClient(); var authResponse = authClient.Send(new Authenticate { provider = "credentials", UserName = Username, Password = Password, RememberMe = true, }); Assert.That(authResponse.SessionId, Is.Not.Null); Assert.That(authResponse.UserName, Is.EqualTo(Username)); Assert.That(authResponse.BearerToken, Is.Not.Null); var jwtToken = authClient.GetTokenCookie(); //From ss-tok Cookie Assert.That(jwtToken, Is.Null); var response = authClient.Send(new HelloJwt { Name = "from auth service" }); Assert.That(response.Result, Is.EqualTo("Hello, from auth service")); authClient.Send(new ConvertSessionToToken()); jwtToken = authClient.GetTokenCookie(); //From ss-tok Cookie Assert.That(jwtToken, Is.Not.Null); response = authClient.Send(new HelloJwt { Name = "from auth service" }); Assert.That(response.Result, Is.EqualTo("Hello, from auth service")); } [Test] public void Invalid_RefreshToken_throws_RefreshTokenException() { var client = GetClientWithRefreshToken("Invalid.Refresh.Token"); try { var request = new Secured { Name = "test" }; var response = client.Send(request); Assert.Fail("Should throw"); } catch (RefreshTokenException ex) { ex.Message.Print(); Assert.That(ex.StatusCode, Is.EqualTo(400)); Assert.That(ex.ErrorCode, Is.EqualTo(nameof(ArgumentException))); } } [Test] public async Task Invalid_RefreshToken_throws_RefreshTokenException_Async() { var client = GetClientWithRefreshToken("Invalid.Refresh.Token"); try { var request = new Secured { Name = "test" }; var response = await client.SendAsync(request); Assert.Fail("Should throw"); } catch (RefreshTokenException ex) { ex.Message.Print(); Assert.That(ex.StatusCode, Is.EqualTo(400)); Assert.That(ex.ErrorCode, Is.EqualTo(nameof(ArgumentException))); } catch (WebException ex) { // TODO: try to replicate CI behavior locally Assert.That(ex.Status, Is.EqualTo(WebExceptionStatus.ProtocolError)); Assert.That(((HttpWebResponse)ex.Response)!.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); } } [Test] public void Only_returns_Tokens_on_Requests_that_Authenticate_the_user() { var authClient = GetClient(); var refreshToken = authClient.Send(new Authenticate { provider = "credentials", UserName = Username, Password = Password, }).RefreshToken; Assert.That(refreshToken, Is.Not.Null); //On Auth using non IAuthWithRequest var postAuthRefreshToken = authClient.Send(new Authenticate()).RefreshToken; Assert.That(postAuthRefreshToken, Is.Null); //After Auth } [Test] public void Can_Auto_reconnect_with_just_RefreshToken() { var client = GetClientWithRefreshToken(); var request = new Secured { Name = "test" }; var response = client.Send(request); Assert.That(response.Result, Is.EqualTo(request.Name)); response = client.Send(request); Assert.That(response.Result, Is.EqualTo(request.Name)); } [Test] public void Can_Auto_reconnect_with_just_RefreshToken_with_UseTokenCookie() { var client = GetClientWithRefreshToken(useTokenCookie:true); var request = new Secured { Name = "test" }; var response = client.Send(request); Assert.That(response.Result, Is.EqualTo(request.Name)); response = client.Send(request); Assert.That(response.Result, Is.EqualTo(request.Name)); } [Test] public void Can_Auto_reconnect_with_RefreshToken_after_expired_token() { var client = GetClientWithRefreshToken(GetRefreshToken(), CreateExpiredToken()); var request = new Secured { Name = "test" }; var response = client.Send(request); Assert.That(response.Result, Is.EqualTo(request.Name)); response = client.Send(request); Assert.That(response.Result, Is.EqualTo(request.Name)); } [Test] public async Task Can_Auto_reconnect_with_RefreshToken_after_expired_token_Async() { var client = GetClientWithRefreshToken(GetRefreshToken(), CreateExpiredToken()); var request = new Secured { Name = "test" }; var response = await client.SendAsync(request); Assert.That(response.Result, Is.EqualTo(request.Name)); response = await client.SendAsync(request); Assert.That(response.Result, Is.EqualTo(request.Name)); } [Test] public void Can_Auto_reconnect_with_RefreshToken_in_OnAuthenticationRequired_after_expired_token() { var client = GetClient(); if (!(client is JsonServiceClient serviceClient)) //OnAuthenticationRequired not implemented in JsonHttpClient return; var called = 0; serviceClient.BearerToken = CreateExpiredToken(); serviceClient.OnAuthenticationRequired = () => { called++; var authClient = GetClient(); serviceClient.BearerToken = authClient.Send(new GetAccessToken { RefreshToken = GetRefreshToken(), }).AccessToken; }; var request = new Secured { Name = "test" }; var response = client.Send(request); Assert.That(response.Result, Is.EqualTo(request.Name)); response = client.Send(request); Assert.That(response.Result, Is.EqualTo(request.Name)); Assert.That(called, Is.EqualTo(1)); } [Test] public void Does_return_token_on_subsequent_BasicAuth_Authentication_requests() { var client = GetClientWithBasicAuthCredentials(); var response = client.Post(new Authenticate()); Assert.That(response.BearerToken, Is.Not.Null); Assert.That(response.RefreshToken, Is.Not.Null); response = client.Post(new Authenticate()); Assert.That(response.BearerToken, Is.Not.Null); Assert.That(response.RefreshToken, Is.Not.Null); } [Test] public async Task Does_return_token_on_subsequent_BasicAuth_Authentication_requests_Async() { var client = GetClientWithBasicAuthCredentials(); var response = await client.PostAsync(new Authenticate()); Assert.That(response.BearerToken, Is.Not.Null); Assert.That(response.RefreshToken, Is.Not.Null); response = await client.PostAsync(new Authenticate()); Assert.That(response.BearerToken, Is.Not.Null); Assert.That(response.RefreshToken, Is.Not.Null); } [Test] public void Does_return_token_on_subsequent_Credentials_Authentication_requests() { var client = GetClient(); var response = client.Post(new Authenticate { provider = "credentials", UserName = Username, Password = Password, RememberMe = true, }); Assert.That(response.BearerToken, Is.Not.Null); Assert.That(response.RefreshToken, Is.Not.Null); response = client.Post(new Authenticate { provider = "credentials", UserName = Username, Password = Password, RememberMe = true, }); Assert.That(response.BearerToken, Is.Not.Null); Assert.That(response.RefreshToken, Is.Not.Null); response = client.Post(new Authenticate()); Assert.That(response.BearerToken, Is.Null); Assert.That(response.RefreshToken, Is.Null); } [Test] public void Can_validate_valid_token() { var authClient = GetClient(); var jwt = authClient.Send(new Authenticate { provider = "credentials", UserName = Username, Password = Password, }).BearerToken; var jwtProvider = AuthenticateService.GetJwtAuthProvider(); Assert.That(jwtProvider.IsJwtValid(jwt)); var jwtPayload = jwtProvider.GetValidJwtPayload(jwt); Assert.That(jwtPayload, Is.Not.Null); Assert.That(jwtPayload["preferred_username"], Is.EqualTo(Username)); } [Test] public void Does_not_validate_invalid_token() { var expiredJwt = CreateExpiredToken(); var jwtProvider = AuthenticateService.GetJwtAuthProvider(); Assert.That(jwtProvider.IsJwtValid(expiredJwt), Is.False); Assert.That(jwtProvider.GetValidJwtPayload(expiredJwt), Is.Null); } [Test] public void Does_validate_multiple_audiences() { var jwtProvider = (JwtAuthProvider)AuthenticateService.GetAuthProvider(JwtAuthProviderReader.Name); string CreateJwtWithAudiences(params string[] audiences) { var header = JwtAuthProvider.CreateJwtHeader(jwtProvider.HashAlgorithm); var body = JwtAuthProvider.CreateJwtPayload(new AuthUserSession { UserAuthId = "1", DisplayName = "Test", Email = "as@if.com", IsAuthenticated = true, }, issuer: jwtProvider.Issuer, expireIn: jwtProvider.ExpireTokensIn, audiences: audiences); var jwtToken = JwtAuthProvider.CreateJwt(header, body, jwtProvider.GetHashAlgorithm()); return jwtToken; } jwtProvider.Audiences = new List<string> { "foo", "bar" }; var jwtNoAudience = CreateJwtWithAudiences(); Assert.That(jwtProvider.IsJwtValid(jwtNoAudience)); var jwtWrongAudience = CreateJwtWithAudiences("qux"); Assert.That(!jwtProvider.IsJwtValid(jwtWrongAudience)); var jwtPartialAudienceMatch = CreateJwtWithAudiences("bar","qux"); Assert.That(jwtProvider.IsJwtValid(jwtPartialAudienceMatch)); jwtProvider.Audience = "foo"; Assert.That(!jwtProvider.IsJwtValid(jwtPartialAudienceMatch)); jwtProvider.Audience = null; Assert.That(jwtProvider.IsJwtValid(jwtPartialAudienceMatch)); } }
AppHost
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/SagaStateMachineTests/BaseClass_Specs.cs
{ "start": 260, "end": 1145 }
public class ____ { [Test] public async Task Should_initialize_all_states_and_events() { await using var provider = new ServiceCollection() .AddMassTransitTestHarness(x => { x.AddSagaStateMachine<HappyGoLuckyStateMachine, HappyGoLuckyState>(); }) .BuildServiceProvider(true); var harness = await provider.StartTestHarness(); var id = NewId.NextGuid(); await harness.Bus.Publish(new HappyEvent(id)); Assert.That(await harness.Consumed.Any<HappyEvent>()); await harness.Bus.Publish(new EndItAllEvent(id)); Assert.That(await harness.Consumed.Any<EndItAllEvent>()); } } namespace BaseStateMachineTestSubjects { using System;
Using_a_base_state_machine
csharp
dotnet__orleans
test/Analyzers.Tests/AliasClashAttributeAnalyzerTest.cs
{ "start": 5249, "end": 5818 }
public interface ____ : {{grainInterface}} { [Alias("Void")] Task Void(int a); [Alias("Void")] Task Void(long a); } """; return VerifyHasDiagnostic(code); } /// <summary> /// Verifies that the analyzer allows different aliases for different methods in the same grain interface. /// </summary> [Theory] [MemberData(nameof(GrainInterfaces))] public Task GrainInterfaceMethod_ShouldNotTriggerDiagnostic(string grainInterface) { var code = $$"""
I
csharp
unoplatform__uno
src/Uno.UI/UI/Xaml/Controls/ScrollPresenter/SnapPointWrapper.h.cs
{ "start": 572, "end": 1102 }
internal partial class ____<T> { private (double, double) m_actualApplicableZone = (double.NegativeInfinity, double.PositiveInfinity); private (double, double) m_actualImpulseApplicableZone = (double.NegativeInfinity, double.PositiveInfinity); private int m_combinationCount; private double m_ignoredValue = double.NaN; // Ignored snapping value when inertia is triggered by an impulse private ExpressionAnimation m_conditionExpressionAnimation; private ExpressionAnimation m_restingValueExpressionAnimation; }
SnapPointWrapper
csharp
nunit__nunit
src/NUnitFramework/testdata/WarningFixture.cs
{ "start": 15984, "end": 16179 }
public class ____ : WarningInSetUpOrTearDownFixture { [SetUp] public void SetUp() { Warn.Unless(2 + 2, Is.EqualTo(5)); } }
WarningInSetUpFails
csharp
dotnet__efcore
test/EFCore.SqlServer.FunctionalTests/TestUtilities/TestEnvironment.cs
{ "start": 269, "end": 14225 }
public static class ____ { public static IConfiguration Config { get; } = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config.json", optional: true) .AddJsonFile("config.test.json", optional: true) .AddEnvironmentVariables() .Build() .GetSection("Test:SqlServer"); public static string DefaultConnection { get; } = Config["DefaultConnection"] ?? "Data Source=(localdb)\\MSSQLLocalDB;Database=master;Integrated Security=True;Connect Timeout=60;ConnectRetryCount=0"; private static readonly string _dataSource = new SqlConnectionStringBuilder(DefaultConnection).DataSource; public static bool IsConfigured { get; } = !string.IsNullOrEmpty(_dataSource); public static bool IsCI { get; } = Environment.GetEnvironmentVariable("PIPELINE_WORKSPACE") != null; private static bool? _isAzureSqlDb; private static bool? _fullTextInstalled; private static bool? _supportsHiddenColumns; private static bool? _supportsSqlClr; private static bool? _supportsOnlineIndexing; private static bool? _supportsMemoryOptimizedTables; private static bool? _supportsTemporalTablesCascadeDelete; private static bool? _supportsUtf8; private static bool? _supportsJsonPathExpressions; private static bool? _isJsonTypeSupported; private static bool? _isVectorTypeSupported; private static bool? _supportsFunctions2017; private static bool? _supportsFunctions2019; private static bool? _supportsFunctions2022; private static byte? _productMajorVersion; private static int? _compatibilityLevel; private static int? _engineEdition; public static bool IsAzureSql { get { if (!IsConfigured) { return false; } if (_isAzureSqlDb.HasValue) { return _isAzureSqlDb.Value; } try { _isAzureSqlDb = GetEngineEdition() is 5 or 8; } catch (PlatformNotSupportedException) { _isAzureSqlDb = false; } return _isAzureSqlDb.Value; } } public static bool IsLocalDb { get; } = _dataSource.StartsWith("(localdb)", StringComparison.OrdinalIgnoreCase); public static bool IsFullTextSearchSupported { get { if (!IsConfigured) { return false; } if (_fullTextInstalled.HasValue) { return _fullTextInstalled.Value; } try { using var sqlConnection = new SqlConnection(SqlServerTestStore.CreateConnectionString("master")); sqlConnection.Open(); using var command = new SqlCommand( "SELECT FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')", sqlConnection); var result = (int)command.ExecuteScalar(); _fullTextInstalled = result == 1; } catch (PlatformNotSupportedException) { _fullTextInstalled = false; } return _fullTextInstalled.Value; } } public static bool IsHiddenColumnsSupported { get { if (!IsConfigured) { return false; } if (_supportsHiddenColumns.HasValue) { return _supportsHiddenColumns.Value; } try { _supportsHiddenColumns = ((GetProductMajorVersion() >= 13 && GetEngineEdition() != 6) || IsAzureSql) && GetCompatibilityLevel() >= 130; } catch (PlatformNotSupportedException) { _supportsHiddenColumns = false; } return _supportsHiddenColumns.Value; } } public static bool IsSqlClrSupported { get { if (!IsConfigured) { return false; } if (_supportsSqlClr.HasValue) { return _supportsSqlClr.Value; } try { _supportsSqlClr = GetEngineEdition() != 9; } catch (PlatformNotSupportedException) { _supportsSqlClr = false; } return _supportsSqlClr.Value; } } public static bool IsOnlineIndexingSupported { get { if (!IsConfigured) { return false; } if (_supportsOnlineIndexing.HasValue) { return _supportsOnlineIndexing.Value; } try { _supportsOnlineIndexing = GetEngineEdition() == 3 || IsAzureSql; } catch (PlatformNotSupportedException) { _supportsOnlineIndexing = false; } return _supportsOnlineIndexing.Value; } } public static bool IsMemoryOptimizedTablesSupported { get { if (!IsConfigured) { return false; } var supported = GetFlag(nameof(SqlServerCondition.SupportsMemoryOptimized)); if (supported.HasValue) { _supportsMemoryOptimizedTables = supported.Value; } if (_supportsMemoryOptimizedTables.HasValue) { return _supportsMemoryOptimizedTables.Value; } try { using var sqlConnection = new SqlConnection(SqlServerTestStore.CreateConnectionString("master")); sqlConnection.Open(); using var command = new SqlCommand( "SELECT SERVERPROPERTY('IsXTPSupported');", sqlConnection); var result = command.ExecuteScalar(); _supportsMemoryOptimizedTables = (result != null ? Convert.ToInt32(result) : 0) == 1 && !IsLocalDb; } catch (PlatformNotSupportedException) { _supportsMemoryOptimizedTables = false; } return _supportsMemoryOptimizedTables.Value; } } public static bool IsTemporalTablesCascadeDeleteSupported { get { if (!IsConfigured) { return false; } if (_supportsTemporalTablesCascadeDelete.HasValue) { return _supportsTemporalTablesCascadeDelete.Value; } try { _supportsTemporalTablesCascadeDelete = (GetProductMajorVersion() >= 14 || IsAzureSql) && GetCompatibilityLevel() >= 140; } catch (PlatformNotSupportedException) { _supportsTemporalTablesCascadeDelete = false; } return _supportsTemporalTablesCascadeDelete.Value; } } public static bool IsUtf8Supported { get { if (!IsConfigured) { return false; } if (_supportsUtf8.HasValue) { return _supportsUtf8.Value; } try { _supportsUtf8 = (GetProductMajorVersion() >= 15 || IsAzureSql) && GetCompatibilityLevel() >= 150; } catch (PlatformNotSupportedException) { _supportsUtf8 = false; } return _supportsUtf8.Value; } } public static bool SupportsJsonPathExpressions { get { if (!IsConfigured) { return false; } if (_supportsJsonPathExpressions.HasValue) { return _supportsJsonPathExpressions.Value; } try { _supportsJsonPathExpressions = (GetProductMajorVersion() >= 14 || IsAzureSql) && GetCompatibilityLevel() >= 140; } catch (PlatformNotSupportedException) { _supportsJsonPathExpressions = false; } return _supportsJsonPathExpressions.Value; } } public static bool IsFunctions2017Supported { get { if (!IsConfigured) { return false; } if (_supportsFunctions2017.HasValue) { return _supportsFunctions2017.Value; } try { _supportsFunctions2017 = (GetProductMajorVersion() >= 14 || IsAzureSql) && GetCompatibilityLevel() >= 140; } catch (PlatformNotSupportedException) { _supportsFunctions2017 = false; } return _supportsFunctions2017.Value; } } public static bool IsFunctions2019Supported { get { if (!IsConfigured) { return false; } if (_supportsFunctions2019.HasValue) { return _supportsFunctions2019.Value; } try { _supportsFunctions2019 = (GetProductMajorVersion() >= 15 || IsAzureSql) && GetCompatibilityLevel() >= 150; } catch (PlatformNotSupportedException) { _supportsFunctions2019 = false; } return _supportsFunctions2019.Value; } } public static bool IsFunctions2022Supported { get { if (!IsConfigured) { return false; } if (_supportsFunctions2022.HasValue) { return _supportsFunctions2022.Value; } try { _supportsFunctions2022 = (GetProductMajorVersion() >= 16 || IsAzureSql) && GetCompatibilityLevel() >= 160; } catch (PlatformNotSupportedException) { _supportsFunctions2022 = false; } return _supportsFunctions2022.Value; } } public static bool IsJsonTypeSupported { get { if (!IsConfigured) { return false; } if (_isJsonTypeSupported.HasValue) { return _isJsonTypeSupported.Value; } try { _isJsonTypeSupported = (GetProductMajorVersion() >= 17 || IsAzureSql) && GetCompatibilityLevel() >= 170; } catch (PlatformNotSupportedException) { _isJsonTypeSupported = false; } return _isJsonTypeSupported.Value; } } public static bool IsVectorTypeSupported { get { if (!IsConfigured) { return false; } if (_isVectorTypeSupported.HasValue) { return _isVectorTypeSupported.Value; } try { _isVectorTypeSupported = ((!IsLocalDb && GetProductMajorVersion() >= 17) || IsAzureSql) && GetCompatibilityLevel() >= 170; } catch (PlatformNotSupportedException) { _isVectorTypeSupported = false; } return _isVectorTypeSupported.Value; } } public static byte SqlServerMajorVersion => GetProductMajorVersion(); public static DbContextOptionsBuilder SetCompatibilityLevelFromEnvironment(DbContextOptionsBuilder builder) => builder.UseSqlServerCompatibilityLevel(SqlServerMajorVersion * 10); public static string? ElasticPoolName { get; } = Config["ElasticPoolName"]; public static bool? GetFlag(string key) => bool.TryParse(Config[key], out var flag) ? flag : null; public static int? GetInt(string key) => int.TryParse(Config[key], out var value) ? value : null; private static int GetEngineEdition() { if (_engineEdition.HasValue) { return _engineEdition.Value; } using var sqlConnection = new SqlConnection(SqlServerTestStore.CreateConnectionString("master")); sqlConnection.Open(); using var command = new SqlCommand( "SELECT SERVERPROPERTY('EngineEdition');", sqlConnection); _engineEdition = (int)command.ExecuteScalar(); return _engineEdition.Value; } private static byte GetProductMajorVersion() { if (_productMajorVersion.HasValue) { return _productMajorVersion.Value; } using var sqlConnection = new SqlConnection(SqlServerTestStore.CreateConnectionString("master")); sqlConnection.Open(); using var command = new SqlCommand( "SELECT SERVERPROPERTY('ProductVersion');", sqlConnection); _productMajorVersion = (byte)Version.Parse((string)command.ExecuteScalar()).Major; return _productMajorVersion.Value; } private static int GetCompatibilityLevel() { if (_compatibilityLevel.HasValue) { return _compatibilityLevel.Value; } using var sqlConnection = new SqlConnection(SqlServerTestStore.CreateConnectionString("master")); sqlConnection.Open(); using var command = new SqlCommand( "SELECT compatibility_level FROM sys.databases WHERE [name] = 'master';", sqlConnection); _compatibilityLevel = (byte)command.ExecuteScalar(); return _compatibilityLevel.Value; } }
TestEnvironment
csharp
dotnet__aspnetcore
src/Hosting/Hosting/test/WebHostTests.cs
{ "start": 41581, "end": 43622 }
public class ____ : IServer { public FakeServer() { Features = new FeatureCollection(); Features.Set<IServerAddressesFeature>(new ServerAddressesFeature()); } public IList<StartInstance> StartInstances { get; } = new List<StartInstance>(); public Func<IFeatureCollection> CreateRequestFeatures { get; set; } = NewFeatureCollection; public IFeatureCollection Features { get; } public static IFeatureCollection NewFeatureCollection() { var stub = new StubFeatures(); var features = new FeatureCollection(); features.Set<IHttpRequestFeature>(stub); features.Set<IHttpResponseFeature>(stub); return features; } public Task StartAsync<TContext>(IHttpApplication<TContext> application, CancellationToken cancellationToken) { var startInstance = new StartInstance(); StartInstances.Add(startInstance); var context = application.CreateContext(CreateRequestFeatures()); try { application.ProcessRequestAsync(context); } catch (Exception ex) { application.DisposeContext(context, ex); throw; } application.DisposeContext(context, null); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { if (StartInstances != null) { foreach (var startInstance in StartInstances) { startInstance.Stop(); } } return Task.CompletedTask; } public void Dispose() { if (StartInstances != null) { foreach (var startInstance in StartInstances) { startInstance.Dispose(); } } } }
FakeServer
csharp
MassTransit__MassTransit
src/MassTransit/Middleware/OutboxConsumeContext.cs
{ "start": 1219, "end": 1381 }
public interface ____<out TMessage> : OutboxConsumeContext, ConsumeContext<TMessage> where TMessage : class { } }
OutboxConsumeContext
csharp
graphql-dotnet__graphql-dotnet
src/GraphQL.Tests/Bugs/BugWithCustomScalarsInDirective.cs
{ "start": 835, "end": 1053 }
public class ____ : ObjectGraphType { public BugWithCustomScalarsInDirectiveQuery() { Name = "Query"; Field<StringGraphType>("str").Resolve(_ => "aaa"); } }
BugWithCustomScalarsInDirectiveQuery
csharp
AvaloniaUI__Avalonia
tests/Avalonia.RenderTests/Media/GeometryDrawingTests.cs
{ "start": 79, "end": 1287 }
public class ____ : TestBase { public GeometryDrawingTests() : base(@"Media\GeometryDrawing") { } private static GeometryDrawing CreateGeometryDrawing() { GeometryDrawing geometryDrawing = new GeometryDrawing(); EllipseGeometry ellipse = new EllipseGeometry(); ellipse.RadiusX = 100; ellipse.RadiusY = 100; geometryDrawing.Geometry = ellipse; return geometryDrawing; } [Fact] public void DrawingGeometry_WithPen() { GeometryDrawing geometryDrawing = CreateGeometryDrawing(); geometryDrawing.Pen = new Pen(new SolidColorBrush(Color.FromArgb(255, 0, 0, 0)), 10); Assert.Equal(210, geometryDrawing.GetBounds().Height); Assert.Equal(210, geometryDrawing.GetBounds().Width); } [Fact] public void DrawingGeometry_WithoutPen() { GeometryDrawing geometryDrawing = CreateGeometryDrawing(); Assert.Equal(200, geometryDrawing.GetBounds().Height); Assert.Equal(200, geometryDrawing.GetBounds().Width); } } }
GeometryDrawingTests
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/src/Types.Mutations/ThrowHelper.cs
{ "start": 94, "end": 2358 }
internal static class ____ { public static SchemaException CannotResolvePayloadType() => new( SchemaErrorBuilder.New() .SetMessage(ThrowHelper_CannotResolvePayloadType) .Build()); public static SchemaException NonMutationFields(IEnumerable<MutationContextData> unprocessed) => new( SchemaErrorBuilder.New() .SetMessage(ThrowHelper_NonMutationFields) .SetExtension("fields", unprocessed.Select(t => t.Definition.Name).ToArray()) .SetCode("") .Build()); public static ISchemaError MutationPayloadMustBeObject(ITypeDefinition type) => SchemaErrorBuilder.New() .SetMessage(ThrowHelper_MutationPayloadMustBeObject, type.Name) .SetTypeSystemObject((TypeSystemObject)type) .SetCode(ErrorCodes.Schema.MutationPayloadMustBeObject) .Build(); public static SchemaException MutationConventionDirective_In_Wrong_Location( DirectiveNode directiveNode) => new(SchemaErrorBuilder.New() .SetMessage(ThrowHelper_MutationConventionDirective_In_Wrong_Location) .SetCode(ErrorCodes.Schema.MutationConventionDirectiveWrongLocation) .AddSyntaxNode(directiveNode) .Build()); public static SchemaException DirectiveArgument_Unexpected_Value( string argumentName, string typeName) => new(SchemaErrorBuilder.New() .SetMessage(ThrowHelper_DirectiveArgument_Unexpected_Value, argumentName, typeName) .SetCode(ErrorCodes.Schema.DirectiveArgumentUnexpectedValue) .Build()); public static SchemaException UnknownDirectiveArgument( string argumentName) => new(SchemaErrorBuilder.New() .SetMessage(ThrowHelper_UnknownDirectiveArgument, argumentName) .SetCode(ErrorCodes.Schema.UnknownDirectiveArgument) .Build()); public static SchemaException MutationMustReturnValue(string memberName) => new(SchemaErrorBuilder.New() .SetMessage(ThrowHelper_MutationMustReturnValue, memberName) .SetCode(ErrorCodes.Schema.MutationMustReturnValue) .Build()); }
ThrowHelper
csharp
App-vNext__Polly
src/Polly.Core/Fallback/FallbackResiliencePipelineBuilderExtensions.cs
{ "start": 233, "end": 2138 }
public static class ____ { /// <summary> /// Adds a fallback resilience strategy with the provided options to the builder. /// </summary> /// <typeparam name="TResult">The result type.</typeparam> /// <param name="builder">The resilience pipeline builder.</param> /// <param name="options">The options to configure the fallback resilience strategy.</param> /// <returns>The builder instance with the fallback strategy added.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="builder"/> or <paramref name="options"/> is <see langword="null"/>.</exception> /// <exception cref="ValidationException">Thrown when <paramref name="options"/> are invalid.</exception> [UnconditionalSuppressMessage( "Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "All options members preserved.")] public static ResiliencePipelineBuilder<TResult> AddFallback<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TResult>( this ResiliencePipelineBuilder<TResult> builder, FallbackStrategyOptions<TResult> options) { Guard.NotNull(builder); Guard.NotNull(options); return builder.AddStrategy(context => CreateFallback(context, options), options); } private static ResilienceStrategy<TResult> CreateFallback<TResult>( StrategyBuilderContext context, FallbackStrategyOptions<TResult> options) { var handler = new FallbackHandler<TResult>( options.ShouldHandle!, options.FallbackAction!); return new FallbackResilienceStrategy<TResult>( handler, options.OnFallback, context.Telemetry); } }
FallbackResiliencePipelineBuilderExtensions
csharp
MonoGame__MonoGame
MonoGame.Framework/Platform/Web/WebGamePlatform.cs
{ "start": 510, "end": 2703 }
class ____ : GamePlatform, IHasCallback { private WebGameWindow _view; public WebGamePlatform(Game game) : base(game) { Window = new WebGameWindow(this); _view = (WebGameWindow)Window; } public virtual void Callback() { this.Game.Tick(); } public override void Exit() { } public override void RunLoop() { throw new InvalidOperationException("You can not run a synchronous loop on the web platform."); } public override void StartRunLoop() { ResetWindowBounds(); _view.window.setInterval((Action)(() => { _view.ProcessEvents(); Game.Tick(); }), 25); } public override bool BeforeUpdate(GameTime gameTime) { return true; } public override bool BeforeDraw(GameTime gameTime) { return true; } public override void EnterFullScreen() { ResetWindowBounds(); } public override void ExitFullScreen() { ResetWindowBounds(); } internal void ResetWindowBounds() { var graphicsDeviceManager = (GraphicsDeviceManager)Game.Services.GetService(typeof(IGraphicsDeviceManager)); if (graphicsDeviceManager.IsFullScreen) { } else { _view.glcanvas.style.width = graphicsDeviceManager.PreferredBackBufferWidth + "px"; _view.glcanvas.style.height = graphicsDeviceManager.PreferredBackBufferHeight + "px"; } } public override void BeginScreenDeviceChange(bool willBeFullScreen) { } public override void EndScreenDeviceChange(string screenDeviceName, int clientWidth, int clientHeight) { } public override GameRunBehavior DefaultRunBehavior { get { return GameRunBehavior.Asynchronous; } } } }
WebGamePlatform
csharp
dotnet__aspnetcore
src/Mvc/Mvc.Api.Analyzers/test/TestFiles/SymbolApiResponseMetadataProviderTest/GetResponseMetadataTests.cs
{ "start": 553, "end": 2477 }
public class ____ : ControllerBase { [Produces(typeof(Person))] public IActionResult ActionWithProducesAttribute(int id) => null; [ProducesResponseType(201)] public IActionResult ActionWithProducesResponseType_StatusCodeInConstructor() => null; [ProducesResponseType(typeof(Person), 202)] public IActionResult ActionWithProducesResponseType_StatusCodeAndTypeInConstructor() => null; [ProducesResponseType(200, StatusCode = 203)] public IActionResult ActionWithProducesResponseType_StatusCodeInConstructorAndProperty() => null; [ProducesResponseType(typeof(object), 200, Type = typeof(Person), StatusCode = 201)] public IActionResult ActionWithProducesResponseType_StatusCodeAndTypeInConstructorAndProperty() => null; [CustomResponseType(Type = typeof(Person), StatusCode = 204)] public IActionResult ActionWithCustomApiResponseMetadataProvider() => null; [Produces201ResponseType] public IActionResult ActionWithCustomProducesResponseTypeAttributeWithoutArguments() => null; [Produces201ResponseType(201)] public IActionResult ActionWithCustomProducesResponseTypeAttributeWithArguments() => null; [CustomInvalidProducesResponseType(Type = typeof(Person), StatusCode = "204")] public IActionResult ActionWithProducesResponseTypeWithIncorrectStatusCodeType() => null; [ApiConventionMethod(typeof(DefaultApiConventions), nameof(DefaultApiConventions.Find))] public IActionResult GetResponseMetadata_ReturnsValuesFromApiConventionMethodAttribute() => null; [ProducesResponseType(204)] [ApiConventionMethod(typeof(DefaultApiConventions), nameof(DefaultApiConventions.Find))] public IActionResult GetResponseMetadata_WithProducesResponseTypeAndApiConventionMethod() => null; }
GetResponseMetadata_ControllerActionWithAttributes
csharp
spectreconsole__spectre.console
src/Spectre.Console.Tests/Unit/Widgets/GridTests.cs
{ "start": 645, "end": 1953 }
public sealed class ____ { [Fact] public void Should_Throw_If_Rows_Are_Null() { // Given var grid = new Grid(); // When var result = Record.Exception(() => grid.AddRow(null!)); // Then result.ShouldBeOfType<ArgumentNullException>() .ParamName.ShouldBe("columns"); } [Fact] public void Should_Add_Empty_Items_If_User_Provides_Less_Row_Items_Than_Columns() { // Given var grid = new Grid(); grid.AddColumn(); grid.AddColumn(); // When grid.AddRow("Foo"); // Then grid.Rows.Count.ShouldBe(1); } [Fact] public void Should_Throw_If_Row_Columns_Are_Greater_Than_Number_Of_Columns() { // Given var grid = new Grid(); grid.AddColumn(); // When var result = Record.Exception(() => grid.AddRow("Foo", "Bar")); // Then result.ShouldBeOfType<InvalidOperationException>(); result.Message.ShouldBe("The number of row columns are greater than the number of grid columns."); } } [ExpectationPath("AddEmptyRow")]
TheAddRowMethod
csharp
dotnet__machinelearning
src/Microsoft.ML.Data/Commands/ShowSchemaCommand.cs
{ "start": 914, "end": 12320 }
public sealed class ____ : DataCommand.ArgumentsBase { [Argument(ArgumentType.AtMostOnce, HelpText = "Show all steps in transform chain", ShortName = "steps")] public bool ShowSteps; [Argument(ArgumentType.AtMostOnce, HelpText = "Show the metadata types", ShortName = "metaTypes")] public bool ShowMetadataTypes; // REVIEW: Support abbreviating long vector-valued metadata? [Argument(ArgumentType.AtMostOnce, HelpText = "Show the metadata types and values", ShortName = "meta,metaVals,metaValues")] public bool ShowMetadataValues; // Note that showing metadata overrides this. // REVIEW: Should we just remove this or possibly support only showing metadata of specified kinds? [Argument(ArgumentType.AtMostOnce, HelpText = "Show slot names", ShortName = "slots", Hide = true)] public bool ShowSlots; #if !CORECLR // Note that this overrides other options. [Argument(ArgumentType.AtMostOnce, HelpText = "Show JSON version of the schema", ShortName = "json", Hide = true)] public bool ShowJson; #endif } internal const string LoadName = "ShowSchema"; internal const string Summary = "Given input data, a loader, and possibly transforms, display the schema."; public ShowSchemaCommand(IHostEnvironment env, Arguments args) : base(env, args, nameof(ShowSchemaCommand)) { } public override void Run() { using (var ch = Host.Start(LoadName)) { RunCore(ch); } } private void RunCore(IChannel ch) { ILegacyDataLoader loader = CreateAndSaveLoader(); using (var schemaWriter = new StringWriter()) { RunOnData(schemaWriter, ImplOptions, loader); var str = schemaWriter.ToString(); ch.AssertNonEmpty(str); ch.Info(str); } } /// <summary> /// This shows the schema of the given <paramref name="data"/>, ignoring the data specification /// in the <paramref name="args"/> parameter. Test code invokes this, hence it is internal. /// </summary> internal static void RunOnData(TextWriter writer, Arguments args, IDataView data) { Contracts.AssertValue(writer); Contracts.AssertValue(args); Contracts.AssertValue(data); if (args.ShowSteps) { IEnumerable<IDataView> viewChainReversed = GetViewChainReversed(data); foreach (var view in viewChainReversed.Reverse()) { writer.WriteLine("---- {0} ----", view.GetType().Name); PrintSchema(writer, args, view.Schema, view as ITransposeDataView); } } else PrintSchema(writer, args, data.Schema, data as ITransposeDataView); } /// <summary> /// Returns the sequence of views passed through the transform chain, last to first. /// </summary> private static IEnumerable<IDataView> GetViewChainReversed(IDataView data) { Contracts.AssertValue(data); IDataView view = (data as LegacyCompositeDataLoader)?.View ?? data; while (view != null) { yield return view; var transform = view as IDataTransform; view = transform?.Source; } } private static void PrintSchema(TextWriter writer, Arguments args, DataViewSchema schema, ITransposeDataView transposeDataView) { Contracts.AssertValue(writer); Contracts.AssertValue(args); Contracts.AssertValue(schema); Contracts.AssertValueOrNull(transposeDataView); #if !CORECLR if (args.ShowJson) { writer.WriteLine("Json Schema not supported."); return; } #endif int colLim = schema.Count; var itw = new IndentedTextWriter(writer, " "); itw.WriteLine("{0} columns:", colLim); using (itw.Nest()) { var names = default(VBuffer<ReadOnlyMemory<char>>); for (int col = 0; col < colLim; col++) { var name = schema[col].Name; var type = schema[col].Type; var slotType = transposeDataView?.GetSlotType(col); itw.WriteLine("{0}: {1}{2}", name, type, slotType == null ? "" : " (T)"); bool metaVals = args.ShowMetadataValues; if (metaVals || args.ShowMetadataTypes) { ShowMetadata(itw, schema, col, metaVals); continue; } if (!args.ShowSlots) continue; if (!type.IsKnownSizeVector()) continue; DataViewType typeNames; if ((typeNames = schema[col].Annotations.Schema.GetColumnOrNull(AnnotationUtils.Kinds.SlotNames)?.Type) == null) continue; if (typeNames.GetVectorSize() != type.GetVectorSize() || !(typeNames.GetItemType() is TextDataViewType)) { Contracts.Assert(false, "Unexpected slot names type"); continue; } schema[col].Annotations.GetValue(AnnotationUtils.Kinds.SlotNames, ref names); if (names.Length != type.GetVectorSize()) { Contracts.Assert(false, "Unexpected length of slot names vector"); continue; } using (itw.Nest()) { bool verbose = args.Verbose ?? false; foreach (var kvp in names.Items(all: verbose)) { if (verbose || !kvp.Value.IsEmpty) itw.WriteLine("{0}:{1}", kvp.Key, kvp.Value); } } } } } private static void ShowMetadata(IndentedTextWriter itw, DataViewSchema schema, int col, bool showVals) { Contracts.AssertValue(itw); Contracts.AssertValue(schema); Contracts.Assert(0 <= col && col < schema.Count); using (itw.Nest()) { foreach (var metaColumn in schema[col].Annotations.Schema.OrderBy(mcol => mcol.Name)) { var type = metaColumn.Type; itw.Write("Metadata '{0}': {1}", metaColumn.Name, type); if (showVals) { if (!(type is VectorDataViewType vectorType)) ShowMetadataValue(itw, schema, col, metaColumn.Name, type); else ShowMetadataValueVec(itw, schema, col, metaColumn.Name, vectorType); } itw.WriteLine(); } } } private static void ShowMetadataValue(IndentedTextWriter itw, DataViewSchema schema, int col, string kind, DataViewType type) { Contracts.AssertValue(itw); Contracts.AssertValue(schema); Contracts.Assert(0 <= col && col < schema.Count); Contracts.AssertNonEmpty(kind); Contracts.AssertValue(type); Contracts.Assert(!(type is VectorDataViewType)); if (!type.IsStandardScalar() && !(type is KeyDataViewType)) { itw.Write(": Can't display value of this type"); return; } Action<IndentedTextWriter, DataViewSchema, int, string, DataViewType> del = ShowMetadataValue<int>; var meth = del.GetMethodInfo().GetGenericMethodDefinition().MakeGenericMethod(type.RawType); meth.Invoke(null, new object[] { itw, schema, col, kind, type }); } private static void ShowMetadataValue<T>(IndentedTextWriter itw, DataViewSchema schema, int col, string kind, DataViewType type) { Contracts.AssertValue(itw); Contracts.AssertValue(schema); Contracts.Assert(0 <= col && col < schema.Count); Contracts.AssertNonEmpty(kind); Contracts.AssertValue(type); Contracts.Assert(!(type is VectorDataViewType)); Contracts.Assert(type.RawType == typeof(T)); var conv = Conversions.DefaultInstance.GetStringConversion<T>(type); var value = default(T); var sb = default(StringBuilder); schema[col].Annotations.GetValue(kind, ref value); conv(in value, ref sb); itw.Write(": '{0}'", sb); } private static void ShowMetadataValueVec(IndentedTextWriter itw, DataViewSchema schema, int col, string kind, VectorDataViewType type) { Contracts.AssertValue(itw); Contracts.AssertValue(schema); Contracts.Assert(0 <= col && col < schema.Count); Contracts.AssertNonEmpty(kind); Contracts.AssertValue(type); if (!type.ItemType.IsStandardScalar() && !(type.ItemType is KeyDataViewType)) { itw.Write(": Can't display value of this type"); return; } Action<IndentedTextWriter, DataViewSchema, int, string, VectorDataViewType> del = ShowMetadataValueVec<int>; var meth = del.GetMethodInfo().GetGenericMethodDefinition().MakeGenericMethod(type.ItemType.RawType); meth.Invoke(null, new object[] { itw, schema, col, kind, type }); } private static void ShowMetadataValueVec<T>(IndentedTextWriter itw, DataViewSchema schema, int col, string kind, VectorDataViewType type) { Contracts.AssertValue(itw); Contracts.AssertValue(schema); Contracts.Assert(0 <= col && col < schema.Count); Contracts.AssertNonEmpty(kind); Contracts.AssertValue(type); Contracts.Assert(type.ItemType.RawType == typeof(T)); var conv = Conversions.DefaultInstance.GetStringConversion<T>(type.ItemType); var value = default(VBuffer<T>); schema[col].Annotations.GetValue(kind, ref value); itw.Write(": Length={0}, Count={0}", value.Length, value.GetValues().Length); using (itw.Nest()) { var sb = default(StringBuilder); int count = 0; foreach (var item in value.Items()) { if ((count % 10) == 0) itw.WriteLine(); else itw.Write(", "); var val = item.Value; conv(in val, ref sb); itw.Write("[{0}] '{1}'", item.Key, sb); count++; } } } } }
Arguments
csharp
dotnet__maui
src/Compatibility/Material/src/Tizen/MaterialActivityIndicatorRenderer.cs
{ "start": 411, "end": 721 }
public class ____ : ActivityIndicatorRenderer { protected override void OnElementChanged(ElementChangedEventArgs<ActivityIndicator> e) { if (Control == null) { SetNativeControl(new MActivityIndicator(Forms.NativeParent)); } base.OnElementChanged(e); } } }
MaterialActivityIndicatorRenderer
csharp
dotnet__maui
src/Controls/tests/TestCases.HostApp/Issues/XFIssue/Issue26534.cs
{ "start": 245, "end": 1638 }
public partial class ____ : ContentPage { public Issue26534() { Grid gridView = new Grid(); var listView = new ListView(); ObservableCollection<GroupedVeggieModel> grouped = CreateData(); listView.ItemsSource = grouped; listView.AutomationId = "listview"; listView.IsGroupingEnabled = true; listView.GroupDisplayBinding = new Binding("LongName"); listView.GroupShortNameBinding = new Binding("ShortName"); listView.ItemTemplate = new DataTemplate(typeof(TextCell)); listView.ItemTemplate.SetBinding(TextCell.TextProperty, "Name"); gridView.Children.Add(listView); Content = gridView; } static ObservableCollection<GroupedVeggieModel> CreateData() { var grouped = new ObservableCollection<GroupedVeggieModel>(); var veggieGroup = new GroupedVeggieModel() { LongName = "Vegetables", ShortName = "V" }; veggieGroup.Add(new VeggieModel() { Name = "Carrot" }); veggieGroup.Add(new VeggieModel() { Name = "Spinach" }); veggieGroup.Add(new VeggieModel() { Name = "Potato" }); var fruitGroup = new GroupedVeggieModel() { LongName = "Fruit", ShortName = "F" }; fruitGroup.Add(new VeggieModel() { Name = "Banana" }); fruitGroup.Add(new VeggieModel() { Name = "Strawberry" }); fruitGroup.Add(new VeggieModel() { Name = "Cherry" }); grouped.Add(veggieGroup); grouped.Add(fruitGroup); return grouped; }
Issue26534
csharp
dotnet__orleans
src/Orleans.Core/Manifest/GrainBindings.cs
{ "start": 388, "end": 1308 }
public class ____ { /// <summary> /// Initializes a new instance of the <see cref="GrainBindings"/> class. /// </summary> /// <param name="grainType">The grain type.</param> /// <param name="bindings">The bindings for the specified grain type.</param> public GrainBindings(GrainType grainType, ImmutableArray<ImmutableDictionary<string, string>> bindings) { this.GrainType = grainType; this.Bindings = bindings; } /// <summary> /// Gets the grain type. /// </summary> public GrainType GrainType { get; } /// <summary> /// Gets the bindings for the specified grain type. /// </summary> public ImmutableArray<ImmutableDictionary<string, string>> Bindings { get; } } /// <summary> /// Resolves bindings for grain types. /// </summary>
GrainBindings
csharp
dotnet__orleans
src/Orleans.TestingHost/TestClusterPortAllocator.cs
{ "start": 405, "end": 5164 }
public class ____ : ITestClusterPortAllocator { private bool _disposed; private readonly object _lockObj = new(); private readonly Dictionary<int, string> _allocatedPorts = []; /// <inheritdoc /> public (int, int) AllocateConsecutivePortPairs(int numPorts = 5) { // Evaluate current system tcp connections var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); var tcpConnInfoArray = ipGlobalProperties.GetActiveTcpListeners(); // each returned port in the pair will have to have at least this amount of available ports following it return (GetAvailableConsecutiveServerPorts(tcpConnInfoArray, 22300, 30000, numPorts), GetAvailableConsecutiveServerPorts(tcpConnInfoArray, 40000, 50000, numPorts)); } /// <inheritdoc /> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><see langword="true" /> to release both managed and unmanaged resources; <see langword="false" /> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (_disposed) { return; } lock (_lockObj) { if (_disposed) { return; } foreach (var pair in _allocatedPorts) { MutexManager.Instance.SignalRelease(pair.Value); } _allocatedPorts.Clear(); _disposed = true; } } /// <summary> /// Finalizes an instance of the <see cref="TestClusterPortAllocator"/> class. /// </summary> ~TestClusterPortAllocator() { Dispose(false); } private int GetAvailableConsecutiveServerPorts(IPEndPoint[] tcpConnInfoArray, int portStartRange, int portEndRange, int consecutivePortsToCheck) { const int MaxAttempts = 100; var allocations = new List<(int Port, string Mutex)>(); for (var attempts = 0; attempts < MaxAttempts; attempts++) { var basePort = Random.Shared.Next(portStartRange, portEndRange); // get ports in buckets, so we don't interfere with parallel runs of this same function basePort = basePort - basePort % consecutivePortsToCheck; var endPort = basePort + consecutivePortsToCheck; // make sure none of the ports in the sub range are in use if (tcpConnInfoArray.All(endpoint => endpoint.Port < basePort || endpoint.Port >= endPort)) { var portsAvailable = true; for (var i = 0; i < consecutivePortsToCheck; i++) { var port = basePort + i; try { using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Bind(new IPEndPoint(IPAddress.Loopback, port)); } catch (SocketException) { portsAvailable = false; break; } } if (!portsAvailable) { continue; } for (var i = 0; i < consecutivePortsToCheck; i++) { var port = basePort + i; var name = $"Global.TestCluster.{port.ToString(CultureInfo.InvariantCulture)}"; if (MutexManager.Instance.Acquire(name)) { allocations.Add((port, name)); } else { foreach (var allocation in allocations) { MutexManager.Instance.SignalRelease(allocation.Mutex); } allocations.Clear(); break; } } if (allocations.Count == 0) { // Try a different range. continue; } lock (_lockObj) { foreach (var allocation in allocations) { _allocatedPorts[allocation.Port] = allocation.Mutex; } } return basePort; } } throw new InvalidOperationException("Cannot find enough free ports to spin up a cluster"); }
TestClusterPortAllocator
csharp
protobuf-net__protobuf-net
src/protobuf-net.Core/Serializers/IProtoSerializerT.cs
{ "start": 11202, "end": 11567 }
public interface ____<[DynamicallyAccessedMembers(DynamicAccess.ContractType)] T> { /// <summary> /// Gets the actual serializer for the type /// </summary> public ISerializer<T> Serializer { get; } } /// <summary> /// Abstract API capable of measuring values without writing them /// </summary>
ISerializerProxy
csharp
unoplatform__uno
src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Controls/TextCompositionEndedEventArgs.cs
{ "start": 301, "end": 1800 }
public partial class ____ { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ internal TextCompositionEndedEventArgs() { } #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 int Length { get { throw new global::System.NotImplementedException("The member int TextCompositionEndedEventArgs.Length is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=int%20TextCompositionEndedEventArgs.Length"); } } #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 int StartIndex { get { throw new global::System.NotImplementedException("The member int TextCompositionEndedEventArgs.StartIndex is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=int%20TextCompositionEndedEventArgs.StartIndex"); } } #endif // Forced skipping of method Microsoft.UI.Xaml.Controls.TextCompositionEndedEventArgs.StartIndex.get // Forced skipping of method Microsoft.UI.Xaml.Controls.TextCompositionEndedEventArgs.Length.get } }
TextCompositionEndedEventArgs
csharp
dotnet__orleans
test/Orleans.CodeGenerator.Tests/snapshots/OrleansSourceGeneratorTests.TestBasicClassWithDifferentAccessModifiers.verified.cs
{ "start": 5173, "end": 6853 }
public sealed class ____ : global::Orleans.Serialization.Cloning.IDeepCopier<global::TestProject.PublicDemoData>, global::Orleans.Serialization.Cloning.IBaseCopier<global::TestProject.PublicDemoData> { [global::System.Runtime.CompilerServices.MethodImplAttribute(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public global::TestProject.PublicDemoData DeepCopy(global::TestProject.PublicDemoData original, global::Orleans.Serialization.Cloning.CopyContext context) { if (context.TryGetCopy(original, out global::TestProject.PublicDemoData existing)) return existing; if (original.GetType() != typeof(global::TestProject.PublicDemoData)) return context.DeepCopy(original); var result = new global::TestProject.PublicDemoData(); context.RecordCopy(original, result); DeepCopy(original, result, context); return result; } [global::System.Runtime.CompilerServices.MethodImplAttribute(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void DeepCopy(global::TestProject.PublicDemoData input, global::TestProject.PublicDemoData output, global::Orleans.Serialization.Cloning.CopyContext context) { output.Value = input.Value; } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("OrleansCodeGen", "10.0.0.0"), global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never), global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute]
Copier_PublicDemoData
csharp
MiniProfiler__dotnet
tests/MiniProfiler.Tests/ProtobufSerializationTests.cs
{ "start": 104, "end": 1406 }
public class ____ : BaseTest { public ProtobufSerializationTests(ITestOutputHelper output) : base(output) { } [Fact] public void Simple() { var mp = GetBasicProfiler(); mp.Increment(); // 1 ms mp.Stop(); var mp1 = MiniProfiler.Current; Assert.NotNull(mp1); var ms = new MemoryStream(); ProtoBuf.Serializer.Serialize(ms, mp1); ms.Position = 0; var mp2 = ProtoBuf.Serializer.Deserialize<MiniProfiler>(ms); AssertProfilersAreEqual(mp1, mp2); } [Fact] public void CustomTimings() { var mp = GetBasicProfiler(); mp.Increment(); // 1 ms using (mp.Step("Child one")) { mp.Increment(); using (mp.CustomTiming("http", "GET http://google.com")) { mp.Increment(); } } mp.Stop(); var ms = new MemoryStream(); ProtoBuf.Serializer.Serialize(ms, mp); ms.Position = 0; var mp2 = ProtoBuf.Serializer.Deserialize<MiniProfiler>(ms); AssertProfilersAreEqual(mp, mp2); } } }
ProtobufSerializationTests
csharp
EventStore__EventStore
src/KurrentDB.Core/Messages/TcpClientMessageDto.cs
{ "start": 9897, "end": 10985 }
partial class ____ { public CreatePersistentSubscription(string subscriptionGroupName, string eventStreamId, bool resolveLinkTos, long startFrom, int messageTimeoutMilliseconds, bool recordStatistics, int liveBufferSize, int readBatchSize, int bufferSize, int maxRetryCount, bool preferRoundRobin, int checkpointAfterTime, int checkpointMaxCount, int checkpointMinCount, int subscriberMaxCount, string namedConsumerStrategy) { SubscriptionGroupName = subscriptionGroupName; EventStreamId = eventStreamId; ResolveLinkTos = resolveLinkTos; StartFrom = startFrom; MessageTimeoutMilliseconds = messageTimeoutMilliseconds; RecordStatistics = recordStatistics; LiveBufferSize = liveBufferSize; ReadBatchSize = readBatchSize; BufferSize = bufferSize; MaxRetryCount = maxRetryCount; PreferRoundRobin = preferRoundRobin; CheckpointAfterTime = checkpointAfterTime; CheckpointMaxCount = checkpointMaxCount; CheckpointMinCount = checkpointMinCount; SubscriberMaxCount = subscriberMaxCount; NamedConsumerStrategy = namedConsumerStrategy; } }
CreatePersistentSubscription
csharp
dotnet__efcore
test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs
{ "start": 119718, "end": 119935 }
public class ____ { public int Id { get; set; } public RelatedEntity552 ParentEntity { get; set; } public IEnumerable<RelatedEntity554> ChildEntities { get; set; } }
RelatedEntity553
csharp
dotnet__orleans
src/api/Orleans.Serialization/Orleans.Serialization.cs
{ "start": 249820, "end": 251629 }
partial class ____<T> : global::Orleans.Serialization.Codecs.IFieldCodec<global::Orleans.Serialization.Codecs.ImmutableListSurrogate<T>>, global::Orleans.Serialization.Codecs.IFieldCodec, global::Orleans.Serialization.Serializers.IValueSerializer<global::Orleans.Serialization.Codecs.ImmutableListSurrogate<T>>, global::Orleans.Serialization.Serializers.IValueSerializer { public Codec_ImmutableListSurrogate(global::Orleans.Serialization.Serializers.ICodecProvider codecProvider) { } public void Deserialize<TReaderInput>(ref global::Orleans.Serialization.Buffers.Reader<TReaderInput> reader, scoped ref global::Orleans.Serialization.Codecs.ImmutableListSurrogate<T> instance) { } public global::Orleans.Serialization.Codecs.ImmutableListSurrogate<T> ReadValue<TReaderInput>(ref global::Orleans.Serialization.Buffers.Reader<TReaderInput> reader, global::Orleans.Serialization.WireProtocol.Field field) { throw null; } public void Serialize<TBufferWriter>(ref global::Orleans.Serialization.Buffers.Writer<TBufferWriter> writer, scoped ref global::Orleans.Serialization.Codecs.ImmutableListSurrogate<T> instance) where TBufferWriter : System.Buffers.IBufferWriter<byte> { } public void WriteField<TBufferWriter>(ref global::Orleans.Serialization.Buffers.Writer<TBufferWriter> writer, uint fieldIdDelta, System.Type expectedType, global::Orleans.Serialization.Codecs.ImmutableListSurrogate<T> value) where TBufferWriter : System.Buffers.IBufferWriter<byte> { } } [System.CodeDom.Compiler.GeneratedCode("OrleansCodeGen", "9.0.0.0")] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public sealed
Codec_ImmutableListSurrogate
csharp
dotnet__aspire
src/Aspire.Dashboard/ConsoleLogs/UrlParser.cs
{ "start": 335, "end": 2637 }
partial class ____ { private static readonly Regex s_urlRegEx = GenerateUrlRegEx(); public static bool TryParse(string? text, Func<string, string>? nonMatchFragmentCallback, [NotNullWhen(true)] out string? modifiedText) { if (text is not null) { var urlMatch = s_urlRegEx.Match(text); StringBuilder? builder = null; var nextCharIndex = 0; while (urlMatch.Success) { builder ??= new StringBuilder(text.Length * 2); if (urlMatch.Index > 0) { AppendNonMatchFragment(builder, nonMatchFragmentCallback, text[(nextCharIndex)..urlMatch.Index]); } var urlStart = urlMatch.Index; nextCharIndex = urlMatch.Index + urlMatch.Length; var url = text[urlStart..nextCharIndex]; builder.Append(CultureInfo.InvariantCulture, $"<a target=\"_blank\" href=\"{url}\" rel=\"noopener noreferrer nofollow\">{WebUtility.HtmlEncode(url)}</a>"); urlMatch = urlMatch.NextMatch(); } if (builder?.Length > 0) { if (nextCharIndex < text.Length) { AppendNonMatchFragment(builder, nonMatchFragmentCallback, text[(nextCharIndex)..]); } modifiedText = builder.ToString(); return true; } } modifiedText = null; return false; static void AppendNonMatchFragment(StringBuilder stringBuilder, Func<string, string>? nonMatchFragmentCallback, string text) { if (nonMatchFragmentCallback != null) { text = nonMatchFragmentCallback(text); } stringBuilder.Append(text); } } // Regular expression that detects http/https URLs in a log entry // Based on the RegEx used by GitHub to detect links in content. [GeneratedRegex( @"((?<!\+)https?:\/\/(?:www\.)?(?:[-\p{L}.]+?[.@][a-zA-Z\d]{2,}|localhost)(?:[-\w\p{L}.:%+~#*$!?&/=@]*(?:,(?!\s))*?)*)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture)] public static partial Regex GenerateUrlRegEx(); }
UrlParser
csharp
scriban__scriban
src/Scriban/ScribanAsync.generated.cs
{ "start": 91405, "end": 91962 }
partial class ____ { public override async ValueTask<object> EvaluateAsync(TemplateContext context) { if (Operator == ScriptUnaryOperator.FunctionAlias) { return await context.EvaluateAsync(Right, true).ConfigureAwait(false); } var value = await context.EvaluateAsync(Right).ConfigureAwait(false); return Evaluate(context, Right.Span, Operator, value); } } #if SCRIBAN_PUBLIC public #else internal #endif abstract
ScriptUnaryExpression
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.Common/Script/ScriptScopeContext.cs
{ "start": 177, "end": 1193 }
public struct ____ { public PageResult PageResult { get; } public SharpPage Page => PageResult.Page; public SharpCodePage CodePage => PageResult.CodePage; public ScriptContext Context => PageResult.Context; public Dictionary<string, object> ScopedParams { get; internal set; } public Stream OutputStream { get; } public ScriptScopeContext(PageResult pageResult, Stream outputStream, Dictionary<string, object> scopedParams) { PageResult = pageResult; ScopedParams = scopedParams ?? new Dictionary<string, object>(); OutputStream = outputStream; } public ScriptScopeContext(ScriptContext context, Dictionary<string, object> scopedParams) { PageResult = new PageResult(context.EmptyPage); OutputStream = null; ScopedParams = scopedParams; } public ScriptScopeContext Clone() { return new ScriptScopeContext(PageResult, OutputStream, new Dictionary<string, object>(ScopedParams)); } }
ScriptScopeContext
csharp
dotnetcore__FreeSql
FreeSql.Tests/FreeSql.Tests/Issues/283.cs
{ "start": 150, "end": 6658 }
public class ____ { [Fact] public void SelectTest() { IFreeSql db = g.sqlserver; db.Transaction(() => { db.Delete<BuildDictionary>().Where("1=1").ExecuteAffrows(); db.Delete<Build2>().Where("1=1").ExecuteAffrows(); var dictionaries = new BuildDictionary[] { new BuildDictionary { Type = 1, Code = 'A', Name = "办公建筑" }, new BuildDictionary { Type = 1, Code = 'B', Name = "商场建筑" }, new BuildDictionary { Type = 1, Code = 'C', Name = "宾馆饭店建筑" }, new BuildDictionary { Type = 1, Code = 'D', Name = "文化教育建筑" }, new BuildDictionary { Type = 1, Code = 'E', Name = "医疗卫生建筑" }, new BuildDictionary { Type = 1, Code = 'F', Name = "体育建筑" }, new BuildDictionary { Type = 1, Code = 'G', Name = "综合建筑" }, new BuildDictionary { Type = 1, Code = 'Z', Name = "其他建筑" }, new BuildDictionary { Type = 2, Code = 'A', Name = "结构建筑" }, new BuildDictionary { Type = 2, Code = 'B', Name = "框剪结构" }, new BuildDictionary { Type = 2, Code = 'C', Name = "剪力墙结构" }, new BuildDictionary { Type = 2, Code = 'D', Name = "砖混结构" }, new BuildDictionary { Type = 2, Code = 'E', Name = "钢结构" }, new BuildDictionary { Type = 2, Code = 'F', Name = "筒体结构" }, new BuildDictionary { Type = 2, Code = 'G', Name = "木结构" }, new BuildDictionary { Type = 2, Code = 'Z', Name = "其他" }, new BuildDictionary { Type = 3, Code = 'A', Name = "集中式全空气系统" }, new BuildDictionary { Type = 3, Code = 'B', Name = "风机盘管+新风系统" }, new BuildDictionary { Type = 3, Code = 'C', Name = "分体式空调或 VRV 的局部式机组系统" }, new BuildDictionary { Type = 3, Code = 'Z', Name = "其他" }, new BuildDictionary { Type = 4, Code = 'A', Name = "散热器采暖" }, new BuildDictionary { Type = 4, Code = 'B', Name = "地板辐射采暖" }, new BuildDictionary { Type = 4, Code = 'C', Name = "电辐射采暖" }, new BuildDictionary { Type = 4, Code = 'D', Name = "空调系统集中供暖" }, new BuildDictionary { Type = 4, Code = 'Z', Name = "其他" }, new BuildDictionary { Type = 5, Code = 'A', Name = "砖" }, new BuildDictionary { Type = 5, Code = 'B', Name = "建筑砌块" }, new BuildDictionary { Type = 5, Code = 'C', Name = "板材墙体" }, new BuildDictionary { Type = 5, Code = 'D', Name = "复合墙板和墙体" }, new BuildDictionary { Type = 5, Code = 'E', Name = "玻璃幕墙" }, new BuildDictionary { Type = 5, Code = 'Z', Name = "其他" }, new BuildDictionary { Type = 6, Code = 'A', Name = "内保温" }, new BuildDictionary { Type = 6, Code = 'B', Name = "外保温" }, new BuildDictionary { Type = 6, Code = 'C', Name = "夹芯保温" }, new BuildDictionary { Type = 6, Code = 'Z', Name = "其他" }, new BuildDictionary { Type = 7, Code = 'A', Name = "单玻单层窗" }, new BuildDictionary { Type = 7, Code = 'B', Name = "单玻双层窗" }, new BuildDictionary { Type = 7, Code = 'C', Name = "单玻单层窗+单玻双层窗" }, new BuildDictionary { Type = 7, Code = 'D', Name = "中空双层玻璃窗" }, new BuildDictionary { Type = 7, Code = 'E', Name = "中空三层玻璃窗" }, new BuildDictionary { Type = 7, Code = 'F', Name = "中空充惰性气体" }, new BuildDictionary { Type = 7, Code = 'Z', Name = "其他" }, new BuildDictionary { Type = 8, Code = 'A', Name = "普通玻璃" }, new BuildDictionary { Type = 8, Code = 'B', Name = "镀膜玻璃" }, new BuildDictionary { Type = 8, Code = 'C', Name = "Low-e 玻璃" }, new BuildDictionary { Type = 8, Code = 'Z', Name = "其他" }, new BuildDictionary { Type = 9, Code = 'A', Name = "钢窗" }, new BuildDictionary { Type = 9, Code = 'B', Name = "铝合金" }, new BuildDictionary { Type = 9, Code = 'C', Name = "木窗" }, new BuildDictionary { Type = 9, Code = 'D', Name = "断热窗框" }, new BuildDictionary { Type = 9, Code = 'E', Name = "塑钢" }, new BuildDictionary { Type = 9, Code = 'Z', Name = "其他" }, }; db.Insert(dictionaries).ExecuteAffrows(); Build2 build = new Build2 { ID = 1, Name = "建筑 1", BuildFunctionCode = 'A', BuildStructureCode = 'A', AirTypeCode = 'A', HeatTypeCode = 'A', WallMaterialTypeCode = 'A', WallWarmTypeCode = 'A', WallWindowsTypeCode = 'A', GlassTypeCode = 'A', WinFrameMaterialCode = 'A' }; db.Insert(build).ExecuteAffrows(); }); Build2 build = db.Select<Build2>() .InnerJoin(a => a.BuildFunctionCode == a.BuildFunction.Code && a.BuildFunction.Type == 1) .InnerJoin(a => a.BuildStructureCode == a.BuildStructure.Code && a.BuildStructure.Type == 2) .InnerJoin(a => a.AirTypeCode == a.AirType.Code && a.AirType.Type == 3) .InnerJoin(a => a.HeatTypeCode == a.HeatType.Code && a.HeatType.Type == 4) .InnerJoin(a => a.WallMaterialTypeCode == a.WallMaterialType.Code && a.WallMaterialType.Type == 5) .InnerJoin(a => a.WallWarmTypeCode == a.WallWarmType.Code && a.WallWarmType.Type == 6) .InnerJoin(a => a.WallWindowsTypeCode == a.WallWindowsType.Code && a.WallWindowsType.Type == 7) .InnerJoin(a => a.GlassTypeCode == a.GlassType.Code && a.GlassType.Type == 8) .InnerJoin(a => a.WinFrameMaterialCode == a.WinFrameMaterial.Code && a.WinFrameMaterial.Type == 9) .Where(a => a.ID == 1) .ToOne(); Assert.NotNull(build); } [Table(Name = "F_Build2")]
_283
csharp
dotnet__aspnetcore
src/Middleware/Diagnostics/test/FunctionalTests/ExceptionHandlerSampleTest.cs
{ "start": 241, "end": 1034 }
public class ____ : IClassFixture<TestFixture<ExceptionHandlerSample.Startup>> { public ExceptionHandlerSampleTest(TestFixture<ExceptionHandlerSample.Startup> fixture) { Client = fixture.Client; } public HttpClient Client { get; } [Fact] public async Task ExceptionHandlerPage_ShowsError() { // Arrange var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/throw"); // Act var response = await Client.SendAsync(request); // Assert var body = await response.Content.ReadAsStringAsync(); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); Assert.Contains("we encountered an un-expected issue with your application.", body); } }
ExceptionHandlerSampleTest
csharp
MonoGame__MonoGame
MonoGame.Framework.Content.Pipeline/Utilities/Vector4Converter.cs
{ "start": 555, "end": 2518 }
class ____ : IVector4Converter<byte>, IVector4Converter<short>, IVector4Converter<int>, IVector4Converter<float>, IVector4Converter<Color>, IVector4Converter<Vector4> { Vector4 IVector4Converter<byte>.ToVector4(byte value) { var f = (float)value / (float)byte.MaxValue; return new Vector4(f, 0f, 0f, 1f); } Vector4 IVector4Converter<short>.ToVector4(short value) { var f = (float)value / (float)short.MaxValue; return new Vector4(f, 0f, 0f, 1f); } Vector4 IVector4Converter<int>.ToVector4(int value) { var f = (float)value / (float)int.MaxValue; return new Vector4(f, 0f, 0f, 1f); } Vector4 IVector4Converter<float>.ToVector4(float value) { return new Vector4(value, 0f, 0f, 1f); } Vector4 IVector4Converter<Color>.ToVector4(Color value) { return value.ToVector4(); } Vector4 IVector4Converter<Vector4>.ToVector4(Vector4 value) { return value; } byte IVector4Converter<byte>.FromVector4(Vector4 value) { return (byte)(value.X * (float)byte.MaxValue); } short IVector4Converter<short>.FromVector4(Vector4 value) { return (short)(value.X * (float)short.MaxValue); } int IVector4Converter<int>.FromVector4(Vector4 value) { return (int)(value.X * (float)int.MaxValue); } float IVector4Converter<float>.FromVector4(Vector4 value) { return value.X; } Color IVector4Converter<Color>.FromVector4(Vector4 value) { return new Color(value); } Vector4 IVector4Converter<Vector4>.FromVector4(Vector4 value) { return value; } } }
Vector4Converter
csharp
dotnet__machinelearning
src/Microsoft.ML.Data/Transforms/ValueToKeyMappingTransformerImpl.cs
{ "start": 429, "end": 749 }
partial class ____ { /// <summary> /// These are objects shared by both the scalar and vector implementations of <see cref="Trainer"/> /// to accumulate individual scalar objects, and facilitate the creation of a <see cref="TermMap"/>. /// </summary>
ValueToKeyMappingTransformer
csharp
dotnet__orleans
test/Grains/TestGrainInterfaces/IKeyExtensionTestGrain.cs
{ "start": 43, "end": 223 }
public interface ____ : IGrainWithGuidCompoundKey { Task<IKeyExtensionTestGrain> GetGrainReference(); Task<string> GetActivationId(); } }
IKeyExtensionTestGrain
csharp
icsharpcode__ILSpy
ICSharpCode.ILSpyX/TreeView/PlatformAbstractions/ITreeNodeImagesProvider.cs
{ "start": 62, "end": 138 }
public interface ____ { object Assembly { get; } } }
ITreeNodeImagesProvider
csharp
smartstore__Smartstore
src/Smartstore.Core/Platform/DataExchange/Domain/ExportEnums.cs
{ "start": 452, "end": 684 }
public enum ____ { TierPrice = 0, ProductVariantAttributeValue, ProductVariantAttributeCombination } /// <summary> /// Represents export deployment types. /// </summary>
RelatedEntityType
csharp
NLog__NLog
src/NLog/ILogger.cs
{ "start": 1844, "end": 69162 }
public partial interface ____ #pragma warning disable CS0618 // Type or member is obsolete : ISuppress , ILoggerBase #pragma warning restore CS0618 // Type or member is obsolete { /// <summary> /// Gets a value indicating whether logging is enabled for the <c>Trace</c> level. /// </summary> /// <returns>A value of <see langword="true" /> if logging is enabled for the <c>Trace</c> level, otherwise it returns <see langword="false" />.</returns> bool IsTraceEnabled { get; } /// <summary> /// Gets a value indicating whether logging is enabled for the <c>Debug</c> level. /// </summary> /// <returns>A value of <see langword="true" /> if logging is enabled for the <c>Debug</c> level, otherwise it returns <see langword="false" />.</returns> bool IsDebugEnabled { get; } /// <summary> /// Gets a value indicating whether logging is enabled for the <c>Info</c> level. /// </summary> /// <returns>A value of <see langword="true" /> if logging is enabled for the <c>Info</c> level, otherwise it returns <see langword="false" />.</returns> bool IsInfoEnabled { get; } /// <summary> /// Gets a value indicating whether logging is enabled for the <c>Warn</c> level. /// </summary> /// <returns>A value of <see langword="true" /> if logging is enabled for the <c>Warn</c> level, otherwise it returns <see langword="false" />.</returns> bool IsWarnEnabled { get; } /// <summary> /// Gets a value indicating whether logging is enabled for the <c>Error</c> level. /// </summary> /// <returns>A value of <see langword="true" /> if logging is enabled for the <c>Error</c> level, otherwise it returns <see langword="false" />.</returns> bool IsErrorEnabled { get; } /// <summary> /// Gets a value indicating whether logging is enabled for the <c>Fatal</c> level. /// </summary> /// <returns>A value of <see langword="true" /> if logging is enabled for the <c>Fatal</c> level, otherwise it returns <see langword="false" />.</returns> bool IsFatalEnabled { get; } #region Trace() overloads /// <overloads> /// Writes the diagnostic message at the <c>Trace</c> level using the specified format provider and format parameters. /// </overloads> /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="value">The value to be written.</param> void Trace<T>(T? value); /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">The value to be written.</param> void Trace<T>(IFormatProvider? formatProvider, T? value); /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level. /// </summary> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> void Trace(LogMessageGenerator messageFunc); /// <summary> /// Writes the diagnostic message and exception at the <c>Trace</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> void Trace(Exception? exception, [Localizable(false)] string message); /// <summary> /// Writes the diagnostic message and exception at the <c>Trace</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Trace(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message and exception at the <c>Trace</c> level. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Trace(Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified parameters and formatting them with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Trace(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level. /// </summary> /// <param name="message">Log message.</param> void Trace([Localizable(false)] string message); /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified parameters. /// </summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Trace([Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Obsolete and replaced by <see cref="Trace(Exception, string)"/> - Writes the diagnostic message and exception at the <c>Trace</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks> [Obsolete("Use Trace(Exception exception, string message) method instead. Marked obsolete with v4.3.11")] [EditorBrowsable(EditorBrowsableState.Never)] void Trace([Localizable(false)] string message, Exception? exception); /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified parameter and formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [MessageTemplateFormatMethod("message")] void Trace<TArgument>(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified parameter. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [MessageTemplateFormatMethod("message")] void Trace<TArgument>([Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified arguments formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [MessageTemplateFormatMethod("message")] void Trace<TArgument1, TArgument2>(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified parameters. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [MessageTemplateFormatMethod("message")] void Trace<TArgument1, TArgument2>([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified arguments formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [MessageTemplateFormatMethod("message")] void Trace<TArgument1, TArgument2, TArgument3>(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); /// <summary> /// Writes the diagnostic message at the <c>Trace</c> level using the specified parameters. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [MessageTemplateFormatMethod("message")] void Trace<TArgument1, TArgument2, TArgument3>([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); /// <summary> /// Obsolete and replaced by <see cref="Trace(Exception, string)"/> - Writes the diagnostic message and exception at the <c>Trace</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks> [Obsolete("Use Trace(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] void TraceException([Localizable(false)] string message, Exception? exception); #endregion #region Debug() overloads /// <overloads> /// Writes the diagnostic message at the <c>Debug</c> level using the specified format provider and format parameters. /// </overloads> /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="value">The value to be written.</param> void Debug<T>(T? value); /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">The value to be written.</param> void Debug<T>(IFormatProvider? formatProvider, T? value); /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// </summary> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> void Debug(LogMessageGenerator messageFunc); /// <summary> /// Writes the diagnostic message and exception at the <c>Debug</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> void Debug(Exception? exception, [Localizable(false)] string message); /// <summary> /// Writes the diagnostic message and exception at the <c>Debug</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Debug(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message and exception at the <c>Debug</c> level. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Debug(Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters and formatting them with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Debug(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level. /// </summary> /// <param name="message">Log message.</param> void Debug([Localizable(false)] string message); /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// </summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Debug([Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameter and formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [MessageTemplateFormatMethod("message")] void Debug<TArgument>(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameter. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [MessageTemplateFormatMethod("message")] void Debug<TArgument>([Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified arguments formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [MessageTemplateFormatMethod("message")] void Debug<TArgument1, TArgument2>(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [MessageTemplateFormatMethod("message")] void Debug<TArgument1, TArgument2>([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified arguments formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [MessageTemplateFormatMethod("message")] void Debug<TArgument1, TArgument2, TArgument3>(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); /// <summary> /// Writes the diagnostic message at the <c>Debug</c> level using the specified parameters. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [MessageTemplateFormatMethod("message")] void Debug<TArgument1, TArgument2, TArgument3>([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); /// <summary> /// Obsolete and replaced by <see cref="Debug(Exception, string)"/> - Writes the diagnostic message and exception at the <c>Debug</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks> [Obsolete("Use Debug(Exception exception, string message) method instead. Marked obsolete with v4.3.11")] [EditorBrowsable(EditorBrowsableState.Never)] void Debug([Localizable(false)] string message, Exception exception); /// <summary> /// Obsolete and replaced by <see cref="Debug(Exception, string)"/> - Writes the diagnostic message and exception at the <c>Debug</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks> [Obsolete("Use Debug(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] void DebugException([Localizable(false)] string message, Exception? exception); #endregion #region Info() overloads /// <overloads> /// Writes the diagnostic message at the <c>Info</c> level using the specified format provider and format parameters. /// </overloads> /// <summary> /// Writes the diagnostic message at the <c>Info</c> level. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="value">The value to be written.</param> void Info<T>(T? value); /// <summary> /// Writes the diagnostic message at the <c>Info</c> level. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">The value to be written.</param> void Info<T>(IFormatProvider? formatProvider, T? value); /// <summary> /// Writes the diagnostic message at the <c>Info</c> level. /// </summary> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> void Info(LogMessageGenerator messageFunc); /// <summary> /// Writes the diagnostic message and exception at the <c>Info</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> void Info(Exception? exception, [Localizable(false)] string message); /// <summary> /// Writes the diagnostic message and exception at the <c>Info</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Info(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message and exception at the <c>Info</c> level. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Info(Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified parameters and formatting them with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Info(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message at the <c>Info</c> level. /// </summary> /// <param name="message">Log message.</param> void Info([Localizable(false)] string message); /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified parameters. /// </summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Info([Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified parameter and formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [MessageTemplateFormatMethod("message")] void Info<TArgument>(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified parameter. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [MessageTemplateFormatMethod("message")] void Info<TArgument>([Localizable(false)][StructuredMessageTemplate] string message, TArgument argument); /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified arguments formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [MessageTemplateFormatMethod("message")] void Info<TArgument1, TArgument2>(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified parameters. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [MessageTemplateFormatMethod("message")] void Info<TArgument1, TArgument2>([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified arguments formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [MessageTemplateFormatMethod("message")] void Info<TArgument1, TArgument2, TArgument3>(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); /// <summary> /// Writes the diagnostic message at the <c>Info</c> level using the specified parameters. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [MessageTemplateFormatMethod("message")] void Info<TArgument1, TArgument2, TArgument3>([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); /// <summary> /// Obsolete and replaced by <see cref="Info(Exception, string)"/> - Writes the diagnostic message and exception at the <c>Info</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks> [Obsolete("Use Info(Exception exception, string message) method instead. Marked obsolete with v4.3.11")] [EditorBrowsable(EditorBrowsableState.Never)] void Info([Localizable(false)] string message, Exception? exception); /// <summary> /// Obsolete and replaced by <see cref="Info(Exception, string)"/> - Writes the diagnostic message and exception at the <c>Info</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks> [Obsolete("Use Info(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] void InfoException([Localizable(false)] string message, Exception? exception); #endregion #region Warn() overloads /// <overloads> /// Writes the diagnostic message at the <c>Warn</c> level using the specified format provider and format parameters. /// </overloads> /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="value">The value to be written.</param> void Warn<T>(T? value); /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">The value to be written.</param> void Warn<T>(IFormatProvider? formatProvider, T? value); /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level. /// </summary> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> void Warn(LogMessageGenerator messageFunc); /// <summary> /// Writes the diagnostic message and exception at the <c>Warn</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> void Warn(Exception? exception, [Localizable(false)] string message); /// <summary> /// Writes the diagnostic message and exception at the <c>Warn</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Warn(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message and exception at the <c>Warn</c> level. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Warn(Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified parameters and formatting them with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Warn(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level. /// </summary> /// <param name="message">Log message.</param> void Warn([Localizable(false)] string message); /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified parameters. /// </summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Warn([Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified parameter and formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [MessageTemplateFormatMethod("message")] void Warn<TArgument>(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified parameter. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [MessageTemplateFormatMethod("message")] void Warn<TArgument>([Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified arguments formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [MessageTemplateFormatMethod("message")] void Warn<TArgument1, TArgument2>(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified parameters. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [MessageTemplateFormatMethod("message")] void Warn<TArgument1, TArgument2>([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified arguments formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [MessageTemplateFormatMethod("message")] void Warn<TArgument1, TArgument2, TArgument3>(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); /// <summary> /// Writes the diagnostic message at the <c>Warn</c> level using the specified parameters. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [MessageTemplateFormatMethod("message")] void Warn<TArgument1, TArgument2, TArgument3>([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); /// <summary> /// Obsolete and replaced by <see cref="Warn(Exception, string)"/> - Writes the diagnostic message and exception at the <c>Warn</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks> [Obsolete("Use Warn(Exception exception, string message) method instead. Marked obsolete with v4.3.11")] [EditorBrowsable(EditorBrowsableState.Never)] void Warn([Localizable(false)] string message, Exception? exception); /// <summary> /// Obsolete and replaced by <see cref="Warn(Exception, string)"/> - Writes the diagnostic message and exception at the <c>Warn</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks> [Obsolete("Use Warn(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] void WarnException([Localizable(false)] string message, Exception? exception); #endregion #region Error() overloads /// <overloads> /// Writes the diagnostic message at the <c>Error</c> level using the specified format provider and format parameters. /// </overloads> /// <summary> /// Writes the diagnostic message at the <c>Error</c> level. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="value">The value to be written.</param> void Error<T>(T? value); /// <summary> /// Writes the diagnostic message at the <c>Error</c> level. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">The value to be written.</param> void Error<T>(IFormatProvider? formatProvider, T? value); /// <summary> /// Writes the diagnostic message at the <c>Error</c> level. /// </summary> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> void Error(LogMessageGenerator messageFunc); /// <summary> /// Writes the diagnostic message and exception at the <c>Error</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> void Error(Exception? exception, [Localizable(false)] string message); /// <summary> /// Writes the diagnostic message and exception at the <c>Error</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Error(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message and exception at the <c>Error</c> level. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Error(Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified parameters and formatting them with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Error(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message at the <c>Error</c> level. /// </summary> /// <param name="message">Log message.</param> void Error([Localizable(false)] string message); /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified parameters. /// </summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Error([Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified parameter and formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [MessageTemplateFormatMethod("message")] void Error<TArgument>(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified parameter. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [MessageTemplateFormatMethod("message")] void Error<TArgument>([Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified arguments formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [MessageTemplateFormatMethod("message")] void Error<TArgument1, TArgument2>(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified parameters. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [MessageTemplateFormatMethod("message")] void Error<TArgument1, TArgument2>([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified arguments formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [MessageTemplateFormatMethod("message")] void Error<TArgument1, TArgument2, TArgument3>(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); /// <summary> /// Writes the diagnostic message at the <c>Error</c> level using the specified parameters. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [MessageTemplateFormatMethod("message")] void Error<TArgument1, TArgument2, TArgument3>([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); /// <summary> /// Obsolete and replaced by <see cref="Error(Exception, string)"/> - Writes the diagnostic message and exception at the <c>Error</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks> [Obsolete("Use Error(Exception exception, string message) method instead. Marked obsolete with v4.3.11")] [EditorBrowsable(EditorBrowsableState.Never)] void Error([Localizable(false)] string message, Exception? exception); /// <summary> /// Obsolete and replaced by <see cref="Error(Exception, string)"/> - Writes the diagnostic message and exception at the <c>Error</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks> [Obsolete("Use Error(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] void ErrorException([Localizable(false)] string message, Exception? exception); #endregion #region Fatal() overloads /// <overloads> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified format provider and format parameters. /// </overloads> /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="value">The value to be written.</param> void Fatal<T>(T? value); /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level. /// </summary> /// <typeparam name="T">Type of the value.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="value">The value to be written.</param> void Fatal<T>(IFormatProvider? formatProvider, T? value); /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level. /// </summary> /// <param name="messageFunc">A function returning message to be written. Function is not evaluated if logging is not enabled.</param> void Fatal(LogMessageGenerator messageFunc); /// <summary> /// Writes the diagnostic message and exception at the <c>Fatal</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> void Fatal(Exception? exception, [Localizable(false)] string message); /// <summary> /// Writes the diagnostic message and exception at the <c>Fatal</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Fatal(Exception? exception, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message and exception at the <c>Fatal</c> level. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Fatal(Exception? exception, IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified parameters and formatting them with the supplied format provider. /// </summary> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Fatal(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level. /// </summary> /// <param name="message">Log message.</param> void Fatal([Localizable(false)] string message); /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified parameters. /// </summary> /// <param name="message">A <see langword="string" /> containing format items.</param> /// <param name="args">Arguments to format.</param> [MessageTemplateFormatMethod("message")] void Fatal([Localizable(false)][StructuredMessageTemplate] string message, params object?[] args); /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified parameter and formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [MessageTemplateFormatMethod("message")] void Fatal<TArgument>(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified parameter. /// </summary> /// <typeparam name="TArgument">The type of the argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument">The argument to format.</param> [MessageTemplateFormatMethod("message")] void Fatal<TArgument>([Localizable(false)][StructuredMessageTemplate] string message, TArgument? argument); /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified arguments formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [MessageTemplateFormatMethod("message")] void Fatal<TArgument1, TArgument2>(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified parameters. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> [MessageTemplateFormatMethod("message")] void Fatal<TArgument1, TArgument2>([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2); /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified arguments formatting it with the supplied format provider. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [MessageTemplateFormatMethod("message")] void Fatal<TArgument1, TArgument2, TArgument3>(IFormatProvider? formatProvider, [Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); /// <summary> /// Writes the diagnostic message at the <c>Fatal</c> level using the specified parameters. /// </summary> /// <typeparam name="TArgument1">The type of the first argument.</typeparam> /// <typeparam name="TArgument2">The type of the second argument.</typeparam> /// <typeparam name="TArgument3">The type of the third argument.</typeparam> /// <param name="message">A <see langword="string" /> containing one format item.</param> /// <param name="argument1">The first argument to format.</param> /// <param name="argument2">The second argument to format.</param> /// <param name="argument3">The third argument to format.</param> [MessageTemplateFormatMethod("message")] void Fatal<TArgument1, TArgument2, TArgument3>([Localizable(false)][StructuredMessageTemplate] string message, TArgument1? argument1, TArgument2? argument2, TArgument3? argument3); /// <summary> /// Obsolete and replaced by <see cref="Fatal(Exception, string)"/> - Writes the diagnostic message and exception at the <c>Fatal</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks> [Obsolete("Use Fatal(Exception exception, string message) method instead. Marked obsolete with v4.3.11")] [EditorBrowsable(EditorBrowsableState.Never)] void Fatal([Localizable(false)] string message, Exception? exception); /// <summary> /// Obsolete and replaced by <see cref="Fatal(Exception, string)"/> - Writes the diagnostic message and exception at the <c>Fatal</c> level. /// </summary> /// <param name="message">A <see langword="string" /> to be written.</param> /// <param name="exception">An exception to be logged.</param> /// <remarks>This method was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks> [Obsolete("Use Fatal(Exception exception, string message) method instead. Marked obsolete with v4.3.11 (Only here because of LibLog)")] [EditorBrowsable(EditorBrowsableState.Never)] void FatalException([Localizable(false)] string message, Exception? exception); #endregion } }
ILogger
csharp
EventStore__EventStore
src/KurrentDB.Core/Bus/IHandle.cs
{ "start": 433, "end": 760 }
public interface ____<in T> : IAsyncHandle<T> where T : Message { void Handle(T message); ValueTask IAsyncHandle<T>.HandleAsync(T message, CancellationToken token) { var task = ValueTask.CompletedTask; try { Handle(message); } catch (Exception e) { task = ValueTask.FromException(e); } return task; } }
IHandle
csharp
bitwarden__server
src/Core/AdminConsole/OrganizationFeatures/Policies/Models/EmptyMetadataModel.cs
{ "start": 73, "end": 133 }
public record ____ : IPolicyMetadataModel { }
EmptyMetadataModel
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Bson/BsonUtils.cs
{ "start": 736, "end": 806 }
static class ____ BSON utility methods. /// </summary>
containing
csharp
unoplatform__uno
src/Uno.UWP/ApplicationModel/Package.Other.cs
{ "start": 192, "end": 4280 }
public partial class ____ { private const string PackageManifestName = "Package.appxmanifest"; private static Assembly? _entryAssembly; private string _displayName = ""; partial void InitializePlatform() { } internal static bool IsManifestInitialized { get; private set; } private bool GetInnerIsDevelopmentMode() => false; private DateTimeOffset GetInstallDate() => DateTimeOffset.Now; private string GetInstalledPath() { #pragma warning disable IL3000 // "Assembly.Location.get' always returns an empty string for assemblies embedded in a single-file app." // We check the return value; it should be safe to ignore this. if (_entryAssembly?.Location is { Length: > 0 } location) #pragma warning restore IL3000 { return global::System.IO.Path.GetDirectoryName(location) ?? ""; } else if (AppContext.BaseDirectory is { Length: > 0 } baseDirectory) { return global::System.IO.Path.GetDirectoryName(baseDirectory) ?? ""; } return Environment.CurrentDirectory; } public string DisplayName { get => EnsureLocalized(_displayName); private set => _displayName = value; } public Uri? Logo { get; set; } internal static void SetEntryAssembly(Assembly entryAssembly) { _entryAssembly = entryAssembly; var assemblyName = entryAssembly.GetName(); Current.Id.Name = assemblyName.Name; // Set the package name to the entry assembly name by default. if (assemblyName.Version is not null) { Current.Id.Version = new PackageVersion(assemblyName.Version); } Current.ParsePackageManifest(); IsManifestInitialized = true; } internal static string EnsureLocalized(string stringToLocalize) { if (stringToLocalize.StartsWith("ms-resource:", StringComparison.OrdinalIgnoreCase)) { var resourceKey = stringToLocalize["ms-resource:".Length..].Trim(); var resourceString = Resources.ResourceLoader.GetForViewIndependentUse().GetString(resourceKey); if (!string.IsNullOrEmpty(resourceString)) { stringToLocalize = resourceString; } } return stringToLocalize; } private void ParsePackageManifest() { if (_entryAssembly is null) { return; } if (_entryAssembly.GetManifestResourceStream(PackageManifestName) is not { } manifest) { if (this.Log().IsEnabled(Uno.Foundation.Logging.LogLevel.Debug)) { this.Log().Debug($"Skipping manifest reading, unable to find [{PackageManifestName}]"); } return; } try { var doc = new XmlDocument(); doc.Load(manifest); var nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("d", "http://schemas.microsoft.com/appx/manifest/foundation/windows10"); DisplayName = doc.SelectSingleNode("/d:Package/d:Properties/d:DisplayName", nsmgr)?.InnerText ?? ""; #if __SKIA__ Description = doc.SelectSingleNode("/d:Package/d:Properties/d:Description", nsmgr)?.InnerText ?? ""; PublisherDisplayName = doc.SelectSingleNode("/d:Package/d:Properties/d:PublisherDisplayName", nsmgr)?.InnerText ?? ""; #endif var logoUri = doc.SelectSingleNode("/d:Package/d:Properties/d:Logo", nsmgr)?.InnerText ?? ""; if (Uri.TryCreate(logoUri, UriKind.RelativeOrAbsolute, out var logo)) { Logo = logo; } var idNode = doc.SelectSingleNode("/d:Package/d:Identity", nsmgr); if (idNode is not null) { Id.Name = idNode.Attributes?.GetNamedItem("Name")?.Value ?? ""; // By default we use the entry assembly version, which is usually set by the <AssemblyDisplayVersion> MSBuild property. // If not set yet, we try to get the version from the manifest instead. if (Id.Version == default) { var versionString = idNode.Attributes?.GetNamedItem("Version")?.Value ?? ""; if (Version.TryParse(versionString, out var version)) { Id.Version = new PackageVersion(version); } } Id.Publisher = idNode.Attributes?.GetNamedItem("Publisher")?.Value ?? ""; } } catch (Exception ex) { if (this.Log().IsEnabled(Uno.Foundation.Logging.LogLevel.Error)) { this.Log().Error($"Failed to read manifest [{PackageManifestName}]", ex); } } } } #endif
Package
csharp
dotnet__maui
src/Controls/tests/TestCases.HostApp/Issues/Issue25436.xaml.cs
{ "start": 369, "end": 805 }
public class ____ : ContentPage { public Issue25436Firstpage() { var button = new Button { Text = "Click here to navigate back", VerticalOptions = LayoutOptions.Center, HorizontalOptions = LayoutOptions.Center }; button.Clicked += async (s, e) => await Shell.Current.GoToAsync("//login"); Content = button; button.AutomationId = "BackButton"; Title = "_25436 first flyout"; } }
Issue25436Firstpage
csharp
dotnet__orleans
src/Orleans.Serialization.NewtonsoftJson/NewtonsoftJsonCodecOptions.cs
{ "start": 153, "end": 804 }
public class ____ { /// <summary> /// Gets or sets the <see cref="JsonSerializerSettings"/>. /// </summary> public JsonSerializerSettings SerializerSettings { get; set; } /// <summary> /// Gets or sets a delegate used to determine if a type is supported by the JSON serializer for serialization and deserialization. /// </summary> public Func<Type, bool?> IsSerializableType { get; set; } /// <summary> /// Gets or sets a delegate used to determine if a type is supported by the JSON serializer for copying. /// </summary> public Func<Type, bool?> IsCopyableType { get; set; } }
NewtonsoftJsonCodecOptions
csharp
abpframework__abp
framework/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/Modeling/NamedEntityConfigurer.cs
{ "start": 121, "end": 682 }
public class ____ { /// <summary> /// Name of the configurer. /// </summary> public string Name { get; set; } /// <summary> /// Action to configure the given <see cref="EntityTypeBuilder"/>. /// </summary> public Action<EntityTypeBuilder> ConfigureAction { get; } public NamedEntityConfigurer(string name, Action<EntityTypeBuilder> configureAction) { Name = Check.NotNullOrEmpty(name, nameof(name)); ConfigureAction = Check.NotNull(configureAction, nameof(configureAction)); } }
NamedEntityConfigurer
csharp
App-vNext__Polly
src/Polly/Retry/AsyncRetryTResultSyntax.cs
{ "start": 125, "end": 73068 }
public static class ____ { /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}"/> that will retry once. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <returns>The policy instance.</returns> public static AsyncRetryPolicy<TResult> RetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder) => policyBuilder.RetryAsync(1); /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will retry <paramref name="retryCount" /> times. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="retryCount">The retry count.</param> /// <returns>The policy instance.</returns> public static AsyncRetryPolicy<TResult> RetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, int retryCount) => policyBuilder.RetryAsync(retryCount, static (_, _) => { }); /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will retry once /// calling <paramref name="onRetry" /> on retry with the handled exception or result and retry count. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="onRetry">The action to call on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetry"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> RetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Action<DelegateResult<TResult>, int> onRetry) => #pragma warning disable 1998 // async method has no awaits, will run synchronously policyBuilder.RetryAsync(1, onRetryAsync: async (outcome, i, _) => onRetry(outcome, i)); #pragma warning restore 1998 /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will retry once /// calling <paramref name="onRetryAsync" /> on retry with the handled exception or result and retry count. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> RetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Func<DelegateResult<TResult>, int, Task> onRetryAsync) => policyBuilder.RetryAsync(1, onRetryAsync: (outcome, i, _) => onRetryAsync(outcome, i)); /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will retry <paramref name="retryCount" /> times /// calling <paramref name="onRetry" /> on each retry with the handled exception or result and retry count. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="retryCount">The retry count.</param> /// <param name="onRetry">The action to call on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentOutOfRangeException">retryCount;Value must be greater than or equal to zero.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetry"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> RetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, int retryCount, Action<DelegateResult<TResult>, int> onRetry) { if (onRetry == null) { throw new ArgumentNullException(nameof(onRetry)); } #pragma warning disable 1998 // async method has no awaits, will run synchronously return policyBuilder.RetryAsync(retryCount, onRetryAsync: async (outcome, i, _) => onRetry(outcome, i)); #pragma warning restore 1998 } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will retry <paramref name="retryCount" /> times /// calling <paramref name="onRetryAsync" /> on each retry with the handled exception or result and retry count. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="retryCount">The retry count.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentOutOfRangeException">retryCount;Value must be greater than or equal to zero.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> RetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, int retryCount, Func<DelegateResult<TResult>, int, Task> onRetryAsync) { if (onRetryAsync == null) { throw new ArgumentNullException(nameof(onRetryAsync)); } return policyBuilder.RetryAsync(retryCount, onRetryAsync: (outcome, i, _) => onRetryAsync(outcome, i)); } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}"/> that will retry once /// calling <paramref name="onRetry"/> on retry with the handled exception or result, retry count and context data. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="onRetry">The action to call on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetry"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> RetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Action<DelegateResult<TResult>, int, Context> onRetry) => policyBuilder.RetryAsync(1, onRetry); /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}"/> that will retry once /// calling <paramref name="onRetryAsync"/> on retry with the handled exception or result, retry count and context data. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> RetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Func<DelegateResult<TResult>, int, Context, Task> onRetryAsync) => policyBuilder.RetryAsync(1, onRetryAsync); /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}"/> that will retry <paramref name="retryCount"/> times /// calling <paramref name="onRetry"/> on each retry with the handled exception or result, retry count and context data. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="retryCount">The retry count.</param> /// <param name="onRetry">The action to call on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentOutOfRangeException">retryCount;Value must be greater than zero.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetry"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> RetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, int retryCount, Action<DelegateResult<TResult>, int, Context> onRetry) { if (onRetry == null) { throw new ArgumentNullException(nameof(onRetry)); } #pragma warning disable 1998 // async method has no awaits, will run synchronously return policyBuilder.RetryAsync(retryCount, onRetryAsync: async (outcome, i, ctx) => onRetry(outcome, i, ctx)); #pragma warning restore 1998 } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}"/> that will retry <paramref name="retryCount"/> times /// calling <paramref name="onRetryAsync"/> on each retry with the handled exception or result, retry count and context data. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="retryCount">The retry count.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentOutOfRangeException">retryCount;Value must be greater than zero.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> RetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, int retryCount, Func<DelegateResult<TResult>, int, Context, Task> onRetryAsync) { if (retryCount < 0) { throw new ArgumentOutOfRangeException(nameof(retryCount), "Value must be greater than or equal to zero."); } if (onRetryAsync == null) { throw new ArgumentNullException(nameof(onRetryAsync)); } return new AsyncRetryPolicy<TResult>( policyBuilder, (outcome, _, i, ctx) => onRetryAsync(outcome, i, ctx), retryCount); } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will retry indefinitely until the action succeeds. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <returns>The policy instance.</returns> public static AsyncRetryPolicy<TResult> RetryForeverAsync<TResult>(this PolicyBuilder<TResult> policyBuilder) => policyBuilder.RetryForeverAsync(static _ => { }); /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will retry indefinitely /// calling <paramref name="onRetry" /> on each retry with the handled exception or result. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="onRetry">The action to call on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetry"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> RetryForeverAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Action<DelegateResult<TResult>> onRetry) { if (onRetry == null) { throw new ArgumentNullException(nameof(onRetry)); } #pragma warning disable 1998 // async method has no awaits, will run synchronously return policyBuilder.RetryForeverAsync( onRetryAsync: async (DelegateResult<TResult> outcome, Context _) => onRetry(outcome)); #pragma warning restore 1998 } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will retry indefinitely /// calling <paramref name="onRetry" /> on each retry with the handled exception or result and retry count. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="onRetry">The action to call on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetry"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> RetryForeverAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Action<DelegateResult<TResult>, int> onRetry) { if (onRetry == null) { throw new ArgumentNullException(nameof(onRetry)); } #pragma warning disable 1998 // async method has no awaits, will run synchronously return policyBuilder.RetryForeverAsync( onRetryAsync: async (outcome, i, _) => onRetry(outcome, i)); #pragma warning restore 1998 } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will retry indefinitely /// calling <paramref name="onRetryAsync" /> on each retry with the handled exception or result. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> RetryForeverAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Func<DelegateResult<TResult>, Task> onRetryAsync) { if (onRetryAsync == null) { throw new ArgumentNullException(nameof(onRetryAsync)); } return policyBuilder.RetryForeverAsync(onRetryAsync: (DelegateResult<TResult> outcome, Context _) => onRetryAsync(outcome)); } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will retry indefinitely /// calling <paramref name="onRetryAsync" /> on each retry with the handled exception or result and retry count. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> RetryForeverAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Func<DelegateResult<TResult>, int, Task> onRetryAsync) { if (onRetryAsync == null) { throw new ArgumentNullException(nameof(onRetryAsync)); } return policyBuilder.RetryForeverAsync(onRetryAsync: (outcome, i, _) => onRetryAsync(outcome, i)); } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}"/> that will retry indefinitely /// calling <paramref name="onRetry"/> on each retry with the handled exception or result and context data. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="onRetry">The action to call on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetry"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> RetryForeverAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Action<DelegateResult<TResult>, Context> onRetry) { if (onRetry == null) { throw new ArgumentNullException(nameof(onRetry)); } #pragma warning disable 1998 // async method has no awaits, will run synchronously return policyBuilder.RetryForeverAsync( onRetryAsync: async (outcome, ctx) => onRetry(outcome, ctx)); #pragma warning restore 1998 } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}"/> that will retry indefinitely /// calling <paramref name="onRetry"/> on each retry with the handled exception or result, retry count and context data. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="onRetry">The action to call on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetry"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> RetryForeverAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Action<DelegateResult<TResult>, int, Context> onRetry) { if (onRetry == null) { throw new ArgumentNullException(nameof(onRetry)); } #pragma warning disable 1998 // async method has no awaits, will run synchronously return policyBuilder.RetryForeverAsync( onRetryAsync: async (outcome, i, ctx) => onRetry(outcome, i, ctx)); #pragma warning restore 1998 } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}"/> that will retry indefinitely /// calling <paramref name="onRetryAsync"/> on each retry with the handled exception or result and context data. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> RetryForeverAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Func<DelegateResult<TResult>, Context, Task> onRetryAsync) { if (onRetryAsync == null) { throw new ArgumentNullException(nameof(onRetryAsync)); } return new AsyncRetryPolicy<TResult>( policyBuilder, (outcome, _, _, ctx) => onRetryAsync(outcome, ctx)); } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}"/> that will retry indefinitely /// calling <paramref name="onRetryAsync"/> on each retry with the handled exception or result, retry count and context data. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> RetryForeverAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Func<DelegateResult<TResult>, int, Context, Task> onRetryAsync) { if (onRetryAsync == null) { throw new ArgumentNullException(nameof(onRetryAsync)); } return new AsyncRetryPolicy<TResult>( policyBuilder, (outcome, _, i, ctx) => onRetryAsync(outcome, i, ctx)); } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}"/> that will wait and retry <paramref name="retryCount"/> times. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider"/> with /// the current retry number (1 for first retry, 2 for second etc). /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="retryCount">The retry count.</param> /// <param name="sleepDurationProvider">The function that provides the duration to wait for a particular retry attempt.</param> /// <returns>The policy instance.</returns> public static AsyncRetryPolicy<TResult> WaitAndRetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, int retryCount, Func<int, TimeSpan> sleepDurationProvider) => policyBuilder.WaitAndRetryAsync(retryCount, sleepDurationProvider, EmptyAction); /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will wait and retry <paramref name="retryCount" /> times /// calling <paramref name="onRetry" /> on each retry with the handled exception or result and the current sleep duration. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc). /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="retryCount">The retry count.</param> /// <param name="sleepDurationProvider">The function that provides the duration to wait for a particular retry attempt.</param> /// <param name="onRetry">The action to call on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentOutOfRangeException">retryCount;Value must be greater than or equal to zero.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> or <paramref name="onRetry"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryAsync<TResult>( this PolicyBuilder<TResult> policyBuilder, int retryCount, Func<int, TimeSpan> sleepDurationProvider, Action<DelegateResult<TResult>, TimeSpan> onRetry) { if (onRetry == null) { throw new ArgumentNullException(nameof(onRetry)); } #pragma warning disable 1998 // async method has no awaits, will run synchronously return policyBuilder.WaitAndRetryAsync( retryCount, sleepDurationProvider, onRetryAsync: async (outcome, span, _, _) => onRetry(outcome, span)); #pragma warning restore 1998 } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will wait and retry <paramref name="retryCount" /> times /// calling <paramref name="onRetryAsync" /> on each retry with the handled exception or result and the current sleep duration. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc). /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="retryCount">The retry count.</param> /// <param name="sleepDurationProvider">The function that provides the duration to wait for a particular retry attempt.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentOutOfRangeException">retryCount;Value must be greater than or equal to zero.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> or <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, int retryCount, Func<int, TimeSpan> sleepDurationProvider, Func<DelegateResult<TResult>, TimeSpan, Task> onRetryAsync) { if (onRetryAsync == null) { throw new ArgumentNullException(nameof(onRetryAsync)); } #pragma warning disable 1998 // async method has no awaits, will run synchronously return policyBuilder.WaitAndRetryAsync( retryCount, sleepDurationProvider, onRetryAsync: (outcome, span, _, _) => onRetryAsync(outcome, span)); #pragma warning restore 1998 } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will wait and retry <paramref name="retryCount" /> times /// calling <paramref name="onRetry" /> on each retry with the handled exception or result, the current sleep duration and context data. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc). /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="retryCount">The retry count.</param> /// <param name="sleepDurationProvider">The function that provides the duration to wait for a particular retry attempt.</param> /// <param name="onRetry">The action to call on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentOutOfRangeException">retryCount;Value must be greater than or equal to zero.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> or <paramref name="onRetry"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, int retryCount, Func<int, TimeSpan> sleepDurationProvider, Action<DelegateResult<TResult>, TimeSpan, Context> onRetry) { if (onRetry == null) { throw new ArgumentNullException(nameof(onRetry)); } #pragma warning disable 1998 // async method has no awaits, will run synchronously return policyBuilder.WaitAndRetryAsync( retryCount, sleepDurationProvider, onRetryAsync: async (outcome, span, _, ctx) => onRetry(outcome, span, ctx)); #pragma warning restore 1998 } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will wait and retry <paramref name="retryCount" /> times /// calling <paramref name="onRetryAsync" /> on each retry with the handled exception or result, the current sleep duration and context data. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc). /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="retryCount">The retry count.</param> /// <param name="sleepDurationProvider">The function that provides the duration to wait for a particular retry attempt.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentOutOfRangeException">retryCount;Value must be greater than or equal to zero.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> or <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, int retryCount, Func<int, TimeSpan> sleepDurationProvider, Func<DelegateResult<TResult>, TimeSpan, Context, Task> onRetryAsync) { if (onRetryAsync == null) { throw new ArgumentNullException(nameof(onRetryAsync)); } return policyBuilder.WaitAndRetryAsync( retryCount, sleepDurationProvider, onRetryAsync: (outcome, timespan, _, ctx) => onRetryAsync(outcome, timespan, ctx)); } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will wait and retry <paramref name="retryCount" /> times /// calling <paramref name="onRetry" /> on each retry with the handled exception or result, the current sleep duration, retry count, and context data. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc). /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="retryCount">The retry count.</param> /// <param name="sleepDurationProvider">The function that provides the duration to wait for a particular retry attempt.</param> /// <param name="onRetry">The action to call on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentOutOfRangeException">retryCount;Value must be greater than or equal to zero.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> or <paramref name="onRetry"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, int retryCount, Func<int, TimeSpan> sleepDurationProvider, Action<DelegateResult<TResult>, TimeSpan, int, Context> onRetry) { if (onRetry == null) { throw new ArgumentNullException(nameof(onRetry)); } #pragma warning disable 1998 // async method has no awaits, will run synchronously return policyBuilder.WaitAndRetryAsync( retryCount, sleepDurationProvider, onRetryAsync: async (outcome, timespan, i, ctx) => onRetry(outcome, timespan, i, ctx)); #pragma warning restore 1998 } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will wait and retry <paramref name="retryCount" /> times /// calling <paramref name="onRetryAsync" /> on each retry with the handled exception or result, the current sleep duration, retry count, and context data. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc). /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="retryCount">The retry count.</param> /// <param name="sleepDurationProvider">The function that provides the duration to wait for a particular retry attempt.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentOutOfRangeException">retryCount;Value must be greater than or equal to zero.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> or <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryAsync<TResult>( this PolicyBuilder<TResult> policyBuilder, int retryCount, Func<int, TimeSpan> sleepDurationProvider, Func<DelegateResult<TResult>, TimeSpan, int, Context, Task> onRetryAsync) { if (retryCount < 0) { throw new ArgumentOutOfRangeException(nameof(retryCount), "Value must be greater than or equal to zero."); } if (sleepDurationProvider == null) { throw new ArgumentNullException(nameof(sleepDurationProvider)); } if (onRetryAsync == null) { throw new ArgumentNullException(nameof(onRetryAsync)); } IEnumerable<TimeSpan> sleepDurations = Enumerable.Range(1, retryCount) .Select(sleepDurationProvider); return new AsyncRetryPolicy<TResult>( policyBuilder, onRetryAsync, retryCount, sleepDurationsEnumerable: sleepDurations); } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will wait and retry <paramref name="retryCount" /> times /// calling <paramref name="onRetry" /> on each retry with the handled exception or result, the current sleep duration and context data. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc) and execution context. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="retryCount">The retry count.</param> /// <param name="sleepDurationProvider">The function that provides the duration to wait for a particular retry attempt.</param> /// <param name="onRetry">The action to call on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentOutOfRangeException">retryCount;Value must be greater than or equal to zero.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> or <paramref name="onRetry"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryAsync<TResult>( this PolicyBuilder<TResult> policyBuilder, int retryCount, Func<int, Context, TimeSpan> sleepDurationProvider, Action<DelegateResult<TResult>, TimeSpan, Context> onRetry) { if (onRetry == null) { throw new ArgumentNullException(nameof(onRetry)); } #pragma warning disable 1998 // async method has no awaits, will run synchronously return policyBuilder.WaitAndRetryAsync( retryCount, sleepDurationProvider, onRetryAsync: async (outcome, span, _, ctx) => onRetry(outcome, span, ctx)); #pragma warning restore 1998 } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will wait and retry <paramref name="retryCount" /> times /// calling <paramref name="onRetryAsync" /> on each retry with the handled exception or result, the current sleep duration and context data. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc) and execution context. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="retryCount">The retry count.</param> /// <param name="sleepDurationProvider">The function that provides the duration to wait for a particular retry attempt.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentOutOfRangeException">retryCount;Value must be greater than or equal to zero.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> or <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, int retryCount, Func<int, Context, TimeSpan> sleepDurationProvider, Func<DelegateResult<TResult>, TimeSpan, Context, Task> onRetryAsync) { if (onRetryAsync == null) { throw new ArgumentNullException(nameof(onRetryAsync)); } return policyBuilder.WaitAndRetryAsync( retryCount, sleepDurationProvider, onRetryAsync: (outcome, timespan, _, ctx) => onRetryAsync(outcome, timespan, ctx)); } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will wait and retry <paramref name="retryCount" /> times /// calling <paramref name="onRetry" /> on each retry with the handled exception or result, the current sleep duration, retry count, and context data. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc) and execution context. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="retryCount">The retry count.</param> /// <param name="sleepDurationProvider">The function that provides the duration to wait for a particular retry attempt.</param> /// <param name="onRetry">The action to call on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentOutOfRangeException">retryCount;Value must be greater than or equal to zero.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> or <paramref name="onRetry"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, int retryCount, Func<int, Context, TimeSpan> sleepDurationProvider, Action<DelegateResult<TResult>, TimeSpan, int, Context> onRetry) { if (onRetry == null) { throw new ArgumentNullException(nameof(onRetry)); } #pragma warning disable 1998 // async method has no awaits, will run synchronously return policyBuilder.WaitAndRetryAsync( retryCount, sleepDurationProvider, onRetryAsync: async (outcome, timespan, i, ctx) => onRetry(outcome, timespan, i, ctx)); #pragma warning restore 1998 } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will wait and retry <paramref name="retryCount" /> times /// calling <paramref name="onRetryAsync" /> on each retry with the handled exception or result, the current sleep duration, retry count, and context data. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc) and execution context. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="retryCount">The retry count.</param> /// <param name="sleepDurationProvider">The function that provides the duration to wait for a particular retry attempt.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentOutOfRangeException">retryCount;Value must be greater than or equal to zero.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> or <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryAsync<TResult>( this PolicyBuilder<TResult> policyBuilder, int retryCount, Func<int, Context, TimeSpan> sleepDurationProvider, Func<DelegateResult<TResult>, TimeSpan, int, Context, Task> onRetryAsync) { if (sleepDurationProvider == null) { throw new ArgumentNullException(nameof(sleepDurationProvider)); } return policyBuilder.WaitAndRetryAsync( retryCount, (i, _, ctx) => sleepDurationProvider(i, ctx), onRetryAsync); } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will wait and retry <paramref name="retryCount" /> times /// calling <paramref name="onRetryAsync" /> on each retry with the handled exception or result, the current sleep duration, retry count, and context data. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc), result of previous execution, and execution context. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="retryCount">The retry count.</param> /// <param name="sleepDurationProvider">The function that provides the duration to wait for a particular retry attempt.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentOutOfRangeException">retryCount;Value must be greater than or equal to zero.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> or <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryAsync<TResult>( this PolicyBuilder<TResult> policyBuilder, int retryCount, Func<int, DelegateResult<TResult>, Context, TimeSpan> sleepDurationProvider, Func<DelegateResult<TResult>, TimeSpan, int, Context, Task> onRetryAsync) { if (retryCount < 0) { throw new ArgumentOutOfRangeException(nameof(retryCount), "Value must be greater than or equal to zero."); } if (sleepDurationProvider == null) { throw new ArgumentNullException(nameof(sleepDurationProvider)); } if (onRetryAsync == null) { throw new ArgumentNullException(nameof(onRetryAsync)); } return new AsyncRetryPolicy<TResult>( policyBuilder, onRetryAsync, retryCount, sleepDurationProvider: sleepDurationProvider); } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will wait and retry as many times as there are provided /// <paramref name="sleepDurations" /> /// On each retry, the duration to wait is the current <paramref name="sleepDurations" /> item. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="sleepDurations">The sleep durations to wait for on each retry.</param> /// <returns>The policy instance.</returns> public static AsyncRetryPolicy<TResult> WaitAndRetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, IEnumerable<TimeSpan> sleepDurations) => policyBuilder.WaitAndRetryAsync(sleepDurations, EmptyAction); /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will wait and retry as many times as there are provided /// <paramref name="sleepDurations" /> /// calling <paramref name="onRetry" /> on each retry with the handled exception or result and the current sleep duration. /// On each retry, the duration to wait is the current <paramref name="sleepDurations" /> item. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="sleepDurations">The sleep durations to wait for on each retry.</param> /// <param name="onRetry">The action to call on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurations"/> or <paramref name="onRetry"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, IEnumerable<TimeSpan> sleepDurations, Action<DelegateResult<TResult>, TimeSpan> onRetry) { if (onRetry == null) { throw new ArgumentNullException(nameof(onRetry)); } #pragma warning disable 1998 // async method has no awaits, will run synchronously return policyBuilder.WaitAndRetryAsync( sleepDurations, onRetryAsync: async (outcome, timespan, _, _) => onRetry(outcome, timespan)); #pragma warning restore 1998 } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will wait and retry as many times as there are provided /// <paramref name="sleepDurations" /> /// calling <paramref name="onRetryAsync" /> on each retry with the handled exception or result and the current sleep duration. /// On each retry, the duration to wait is the current <paramref name="sleepDurations" /> item. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="sleepDurations">The sleep durations to wait for on each retry.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurations"/> or <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, IEnumerable<TimeSpan> sleepDurations, Func<DelegateResult<TResult>, TimeSpan, Task> onRetryAsync) { if (onRetryAsync == null) { throw new ArgumentNullException(nameof(onRetryAsync)); } return policyBuilder.WaitAndRetryAsync( sleepDurations, onRetryAsync: (outcome, timespan, _, _) => onRetryAsync(outcome, timespan)); } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will wait and retry as many times as there are provided /// <paramref name="sleepDurations" /> /// calling <paramref name="onRetry" /> on each retry with the handled exception or result, the current sleep duration and context data. /// On each retry, the duration to wait is the current <paramref name="sleepDurations" /> item. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="sleepDurations">The sleep durations to wait for on each retry.</param> /// <param name="onRetry">The action to call on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurations"/> or <paramref name="onRetry"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, IEnumerable<TimeSpan> sleepDurations, Action<DelegateResult<TResult>, TimeSpan, Context> onRetry) { if (onRetry == null) { throw new ArgumentNullException(nameof(onRetry)); } #pragma warning disable 1998 // async method has no awaits, will run synchronously return policyBuilder.WaitAndRetryAsync( sleepDurations, onRetryAsync: async (outcome, timespan, _, ctx) => onRetry(outcome, timespan, ctx)); #pragma warning restore 1998 } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will wait and retry as many times as there are provided /// <paramref name="sleepDurations" /> /// calling <paramref name="onRetryAsync" /> on each retry with the handled exception or result, the current sleep duration and context data. /// On each retry, the duration to wait is the current <paramref name="sleepDurations" /> item. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="sleepDurations">The sleep durations to wait for on each retry.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurations"/> or <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, IEnumerable<TimeSpan> sleepDurations, Func<DelegateResult<TResult>, TimeSpan, Context, Task> onRetryAsync) { if (onRetryAsync == null) { throw new ArgumentNullException(nameof(onRetryAsync)); } return policyBuilder.WaitAndRetryAsync( sleepDurations, onRetryAsync: (outcome, timespan, _, ctx) => onRetryAsync(outcome, timespan, ctx)); } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will wait and retry as many times as there are provided /// <paramref name="sleepDurations" /> /// calling <paramref name="onRetry" /> on each retry with the handled exception or result, the current sleep duration, retry count, and context data. /// On each retry, the duration to wait is the current <paramref name="sleepDurations" /> item. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="sleepDurations">The sleep durations to wait for on each retry.</param> /// <param name="onRetry">The action to call on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurations"/> or <paramref name="onRetry"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, IEnumerable<TimeSpan> sleepDurations, Action<DelegateResult<TResult>, TimeSpan, int, Context> onRetry) { if (onRetry == null) { throw new ArgumentNullException(nameof(onRetry)); } #pragma warning disable 1998 // async method has no awaits, will run synchronously return policyBuilder.WaitAndRetryAsync( sleepDurations, onRetryAsync: async (outcome, timespan, i, ctx) => onRetry(outcome, timespan, i, ctx)); #pragma warning restore 1998 } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}" /> that will wait and retry as many times as there are provided /// <paramref name="sleepDurations" /> /// calling <paramref name="onRetryAsync" /> on each retry with the handled exception or result, the current sleep duration, retry count, and context data. /// On each retry, the duration to wait is the current <paramref name="sleepDurations" /> item. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="sleepDurations">The sleep durations to wait for on each retry.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurations"/> or <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, IEnumerable<TimeSpan> sleepDurations, Func<DelegateResult<TResult>, TimeSpan, int, Context, Task> onRetryAsync) { if (sleepDurations == null) { throw new ArgumentNullException(nameof(sleepDurations)); } if (onRetryAsync == null) { throw new ArgumentNullException(nameof(onRetryAsync)); } return new AsyncRetryPolicy<TResult>( policyBuilder, onRetryAsync, sleepDurationsEnumerable: sleepDurations); } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}"/> that will wait and retry indefinitely until the action succeeds. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc). /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="sleepDurationProvider">The function that provides the duration to wait for a particular retry attempt.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryForeverAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Func<int, TimeSpan> sleepDurationProvider) => policyBuilder.WaitAndRetryForeverAsync(sleepDurationProvider, EmptyAction); /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}"/> that will wait and retry indefinitely until the action succeeds. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc). /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="sleepDurationProvider">The function that provides the duration to wait for a particular retry attempt.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryForeverAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Func<int, Context, TimeSpan> sleepDurationProvider) => policyBuilder.WaitAndRetryForeverAsync(sleepDurationProvider, static (_, _, _) => { }); /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}"/> that will wait and retry indefinitely until the action succeeds, /// calling <paramref name="onRetry"/> on each retry with the handled exception or result. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc). /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="sleepDurationProvider">A function providing the duration to wait before retrying.</param> /// <param name="onRetry">The action to call on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetry"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryForeverAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Func<int, TimeSpan> sleepDurationProvider, Action<DelegateResult<TResult>, TimeSpan> onRetry) { if (sleepDurationProvider == null) { throw new ArgumentNullException(nameof(sleepDurationProvider)); } if (onRetry == null) { throw new ArgumentNullException(nameof(onRetry)); } return policyBuilder.WaitAndRetryForeverAsync( (retryCount, _) => sleepDurationProvider(retryCount), (outcome, timespan, _) => onRetry(outcome, timespan)); } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}"/> that will wait and retry indefinitely until the action succeeds, /// calling <paramref name="onRetry"/> on each retry with the handled exception or result. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc). /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="sleepDurationProvider">A function providing the duration to wait before retrying.</param> /// <param name="onRetry">The action to call on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetry"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryForeverAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Func<int, TimeSpan> sleepDurationProvider, Action<DelegateResult<TResult>, int, TimeSpan> onRetry) { if (sleepDurationProvider == null) { throw new ArgumentNullException(nameof(sleepDurationProvider)); } if (onRetry == null) { throw new ArgumentNullException(nameof(onRetry)); } return policyBuilder.WaitAndRetryForeverAsync( (retryCount, _) => sleepDurationProvider(retryCount), (outcome, i, timespan, _) => onRetry(outcome, i, timespan)); } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}"/> that will wait and retry indefinitely until the action succeeds, /// calling <paramref name="onRetryAsync"/> on each retry with the handled exception or result. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc). /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="sleepDurationProvider">A function providing the duration to wait before retrying.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryForeverAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Func<int, TimeSpan> sleepDurationProvider, Func<DelegateResult<TResult>, TimeSpan, Task> onRetryAsync) { if (sleepDurationProvider == null) { throw new ArgumentNullException(nameof(sleepDurationProvider)); } if (onRetryAsync == null) { throw new ArgumentNullException(nameof(onRetryAsync)); } return policyBuilder.WaitAndRetryForeverAsync( (retryCount, _) => sleepDurationProvider(retryCount), (outcome, timespan, _) => onRetryAsync(outcome, timespan)); } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}"/> that will wait and retry indefinitely until the action succeeds, /// calling <paramref name="onRetryAsync"/> on each retry with the handled exception or result and retry count. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc). /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="sleepDurationProvider">A function providing the duration to wait before retrying.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryForeverAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Func<int, TimeSpan> sleepDurationProvider, Func<DelegateResult<TResult>, int, TimeSpan, Task> onRetryAsync) { if (sleepDurationProvider == null) { throw new ArgumentNullException(nameof(sleepDurationProvider)); } if (onRetryAsync == null) { throw new ArgumentNullException(nameof(onRetryAsync)); } return policyBuilder.WaitAndRetryForeverAsync( (retryCount, _) => sleepDurationProvider(retryCount), (outcome, i, timespan, _) => onRetryAsync(outcome, i, timespan)); } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}"/> that will wait and retry indefinitely until the action succeeds, /// calling <paramref name="onRetry"/> on each retry with the handled exception or result and execution context. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc) and execution context. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="sleepDurationProvider">A function providing the duration to wait before retrying.</param> /// <param name="onRetry">The action to call on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetry"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryForeverAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Func<int, Context, TimeSpan> sleepDurationProvider, Action<DelegateResult<TResult>, TimeSpan, Context> onRetry) { if (onRetry == null) { throw new ArgumentNullException(nameof(onRetry)); } #pragma warning disable 1998 // async method has no awaits, will run synchronously return policyBuilder.WaitAndRetryForeverAsync( sleepDurationProvider, async (outcome, timespan, ctx) => onRetry(outcome, timespan, ctx)); #pragma warning restore 1998 } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}"/> that will wait and retry indefinitely until the action succeeds, /// calling <paramref name="onRetry"/> on each retry with the handled exception or result and execution context. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc) and execution context. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="sleepDurationProvider">A function providing the duration to wait before retrying.</param> /// <param name="onRetry">The action to call on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetry"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryForeverAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Func<int, Context, TimeSpan> sleepDurationProvider, Action<DelegateResult<TResult>, int, TimeSpan, Context> onRetry) { if (onRetry == null) { throw new ArgumentNullException(nameof(onRetry)); } #pragma warning disable 1998 // async method has no awaits, will run synchronously return policyBuilder.WaitAndRetryForeverAsync( sleepDurationProvider, async (outcome, i, timespan, ctx) => onRetry(outcome, i, timespan, ctx)); #pragma warning restore 1998 } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}"/> that will wait and retry indefinitely until the action succeeds, /// calling <paramref name="onRetryAsync"/> on each retry with the handled exception or result and execution context. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc) and execution context. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="sleepDurationProvider">A function providing the duration to wait before retrying.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryForeverAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Func<int, Context, TimeSpan> sleepDurationProvider, Func<DelegateResult<TResult>, TimeSpan, Context, Task> onRetryAsync) { if (sleepDurationProvider == null) { throw new ArgumentNullException(nameof(sleepDurationProvider)); } return policyBuilder.WaitAndRetryForeverAsync( (i, _, ctx) => sleepDurationProvider(i, ctx), onRetryAsync); } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}"/> that will wait and retry indefinitely until the action succeeds, /// calling <paramref name="onRetryAsync"/> on each retry with the handled exception or result, retry count and execution context. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc) and execution context. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="sleepDurationProvider">A function providing the duration to wait before retrying.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryForeverAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Func<int, Context, TimeSpan> sleepDurationProvider, Func<DelegateResult<TResult>, int, TimeSpan, Context, Task> onRetryAsync) { if (sleepDurationProvider == null) { throw new ArgumentNullException(nameof(sleepDurationProvider)); } return policyBuilder.WaitAndRetryForeverAsync( (i, _, ctx) => sleepDurationProvider(i, ctx), onRetryAsync); } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}"/> that will wait and retry indefinitely until the action succeeds, /// calling <paramref name="onRetryAsync"/> on each retry with the handled exception or result and execution context. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc), previous execution result and execution context. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="sleepDurationProvider">A function providing the duration to wait before retrying.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryForeverAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Func<int, DelegateResult<TResult>, Context, TimeSpan> sleepDurationProvider, Func<DelegateResult<TResult>, TimeSpan, Context, Task> onRetryAsync) { if (sleepDurationProvider == null) { throw new ArgumentNullException(nameof(sleepDurationProvider)); } if (onRetryAsync == null) { throw new ArgumentNullException(nameof(onRetryAsync)); } return new AsyncRetryPolicy<TResult>( policyBuilder, (outcome, timespan, _, ctx) => onRetryAsync(outcome, timespan, ctx), sleepDurationProvider: sleepDurationProvider); } /// <summary> /// Builds an <see cref="AsyncRetryPolicy{TResult}"/> that will wait and retry indefinitely until the action succeeds, /// calling <paramref name="onRetryAsync"/> on each retry with the handled exception or result, retry count and execution context. /// On each retry, the duration to wait is calculated by calling <paramref name="sleepDurationProvider" /> with /// the current retry number (1 for first retry, 2 for second etc), previous execution result and execution context. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="policyBuilder">The policy builder.</param> /// <param name="sleepDurationProvider">A function providing the duration to wait before retrying.</param> /// <param name="onRetryAsync">The action to call asynchronously on each retry.</param> /// <returns>The policy instance.</returns> /// <exception cref="ArgumentNullException">Thrown when <paramref name="sleepDurationProvider"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentNullException">Thrown when <paramref name="onRetryAsync"/> is <see langword="null"/>.</exception> public static AsyncRetryPolicy<TResult> WaitAndRetryForeverAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, Func<int, DelegateResult<TResult>, Context, TimeSpan> sleepDurationProvider, Func<DelegateResult<TResult>, int, TimeSpan, Context, Task> onRetryAsync) { if (sleepDurationProvider == null) { throw new ArgumentNullException(nameof(sleepDurationProvider)); } if (onRetryAsync == null) { throw new ArgumentNullException(nameof(onRetryAsync)); } return new AsyncRetryPolicy<TResult>( policyBuilder, (exception, timespan, i, ctx) => onRetryAsync(exception, i, timespan, ctx), sleepDurationProvider: sleepDurationProvider); } private static void EmptyAction<T>(DelegateResult<T> result, TimeSpan retryAfter) { // No-op } }
AsyncRetryTResultSyntax
csharp
dotnet__efcore
test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs
{ "start": 61779, "end": 61996 }
public class ____ { public int Id { get; set; } public RelatedEntity285 ParentEntity { get; set; } public IEnumerable<RelatedEntity287> ChildEntities { get; set; } }
RelatedEntity286
csharp
microsoft__FASTER
cs/playground/AsyncStress/SerializedUpdaters.cs
{ "start": 662, "end": 1750 }
internal struct ____ : IUpdater<FasterKV<SpanByte, SpanByte>.UpsertAsyncResult<SpanByte, SpanByteAndMemory, Empty>> { public Status Update(ClientSession<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, Empty, SpanByteFunctions> session, ref SpanByte key, ref SpanByte value) => session.Upsert(ref key, ref value); public ValueTask<FasterKV<SpanByte, SpanByte>.UpsertAsyncResult<SpanByte, SpanByteAndMemory, Empty>> UpdateAsync(ClientSession<SpanByte, SpanByte, SpanByte, SpanByteAndMemory, Empty, SpanByteFunctions> session, ref SpanByte key, ref SpanByte value) => session.UpsertAsync(ref key, ref value); public async ValueTask<int> CompleteAsync(FasterKV<SpanByte, SpanByte>.UpsertAsyncResult<SpanByte, SpanByteAndMemory, Empty> result) { var numPending = 0; for (; result.Status.IsPending; ++numPending) result = await result.CompleteAsync().ConfigureAwait(false); return numPending; } }
UpsertUpdater
csharp
AvaloniaUI__Avalonia
src/Avalonia.Controls/SplitView/SplitViewDisplayMode.cs
{ "start": 140, "end": 983 }
public enum ____ { /// <summary> /// Pane is displayed next to content, and does not auto collapse /// when tapped outside /// </summary> Inline, /// <summary> /// Pane is displayed next to content. When collapsed, pane is still /// visible according to CompactPaneLength. Pane does not auto collapse /// when tapped outside /// </summary> CompactInline, /// <summary> /// Pane is displayed above content. Pane collapses when tapped outside /// </summary> Overlay, /// <summary> /// Pane is displayed above content. When collapsed, pane is still /// visible according to CompactPaneLength. Pane collapses when tapped outside /// </summary> CompactOverlay } }
SplitViewDisplayMode
csharp
bchavez__Bogus
Source/Bogus/Tokenizer.cs
{ "start": 252, "end": 6907 }
public static class ____ { public static ILookup<string, MustashMethod> MustashMethods; static Tokenizer() { RegisterMustashMethods(typeof(Faker)); } public static void RegisterMustashMethods(Type type) { MustashMethods = type.GetProperties() .Where(p => p.IsDefined(typeof(RegisterMustasheMethodsAttribute), true)) .SelectMany(p => { return p.PropertyType.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) .Where(mi => mi.GetGenericArguments().Length == 0) .Select(mi => { var category = DataSet.ResolveCategory(p.PropertyType); var methodName = mi.Name; var mm = new MustashMethod { Name = $"{category}.{methodName}".ToUpperInvariant(), Method = mi, OptionalArgs = mi.GetParameters().Where(pi => pi.IsOptional).Select(_ => Type.Missing).ToArray() }; return mm; }); }) .ToLookup(mm => mm.Name); } public static string Parse(string str, params object[] dataSets) { //Recursive base case. If there are no more {{ }} handle bars, //return. var start = str.IndexOf("{{", StringComparison.Ordinal); var end = str.IndexOf("}}", StringComparison.Ordinal); if( start == -1 && end == -1 ) { return str; } //We have some handlebars to process. Get the method name and arguments. ParseMustashText(str, start, end, out var methodName, out var arguments); if( !MustashMethods.Contains(methodName) ) { throw new ArgumentException($"Unknown method {methodName} can't be found."); } //At this point, we have a methodName like: RANDOMIZER.NUMBER //and if the dataset was registered with RegisterMustasheMethodsAttribute //we should be able to extract the dataset given it's methodName. var dataSet = FindDataSetWithMethod(dataSets, methodName); //Considering arguments, lets get the best method overload //that maps to a registered MustashMethod. var mm = FindMustashMethod(methodName, arguments); var providedArgumentList = ConvertStringArgumentsToObjects(arguments, mm); var optionalArgs = mm.OptionalArgs.Take(mm.Method.GetParameters().Length - providedArgumentList.Length); var argumentList = providedArgumentList.Concat(optionalArgs).ToArray(); //make the actual invocation. var fakeVal = mm.Method.Invoke(dataSet, argumentList).ToString(); var sb = new StringBuilder(); sb.Append(str, 0, start); sb.Append(fakeVal); sb.Append(str.Substring(end + 2)); return Parse(sb.ToString(), dataSets); } private static object FindDataSetWithMethod(object[] dataSets, string methodName) { var dataSetType = MustashMethods[methodName].First().Method.DeclaringType; var ds = dataSets.FirstOrDefault(o => o.GetType() == dataSetType); if( ds == null ) { throw new ArgumentException($"Can't parse {methodName} because the dataset was not provided in the {nameof(dataSets)} parameter.", nameof(dataSets)); } return ds; } private static void ParseMustashText(string str, int start, int end, out string methodName, out string[] arguments) { var methodCall = str.Substring(start + 2, end - start - 2) .Replace("}}", "") .Replace("{{", ""); var argumentsStart = methodCall.IndexOf("(", StringComparison.Ordinal); if (argumentsStart != -1) { var argumentsString = GetArgumentsString(methodCall, argumentsStart); methodName = methodCall.Substring(0, argumentsStart).Trim(); arguments = argumentsString.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray(); } else { methodName = methodCall; arguments = new string[0]; } methodName = methodName.ToUpperInvariant(); } private static MustashMethod FindMustashMethod(string methodName, string[] arguments) { var selection = from mm in MustashMethods[methodName] orderby mm.Method.GetParameters().Count(pi => pi.IsOptional) - arguments.Length where mm.Method.GetParameters().Length >= arguments.Length where mm.OptionalArgs.Length + arguments.Length >= mm.Method.GetParameters().Length select mm; var found = selection.FirstOrDefault(); return found ?? throw new ArgumentException($"Cannot find a method '{methodName}' that could accept {arguments.Length} arguments"); } private static object[] ConvertStringArgumentsToObjects(string[] parameters, MustashMethod mm) { try { return mm.Method.GetParameters() .Zip(parameters, GetValueForParameter) .ToArray(); } catch (OverflowException ex) { throw new ArgumentOutOfRangeException($"One of the arguments for {mm.Name} is out of supported range. Argument list: {string.Join(",", parameters)}", ex); } catch (Exception ex) when (ex is InvalidCastException or FormatException) { throw new ArgumentException($"One of the arguments for {mm.Name} cannot be converted to target type. Argument list: {string.Join(",", parameters)}", ex); } catch (Exception ex) { throw new ArgumentException($"Cannot parse arguments for {mm.Name}. Argument list: {string.Join(",", parameters)}", ex); } } private static object GetValueForParameter(ParameterInfo parameterInfo, string parameterValue) { var type = Nullable.GetUnderlyingType(parameterInfo.ParameterType) ?? parameterInfo.ParameterType; if( typeof(Enum).IsAssignableFrom(type)) return Enum.Parse(type, parameterValue); if( typeof(TimeSpan) == type ) return TimeSpan.Parse(parameterValue); return Convert.ChangeType(parameterValue, type); } private static string GetArgumentsString(string methodCall, int parametersStart) { var parametersEnd = methodCall.IndexOf(')'); if( parametersEnd == -1 ) { throw new ArgumentException($"The method call '{methodCall}' is missing a terminating ')' character."); } return methodCall.Substring(parametersStart + 1, parametersEnd - parametersStart - 1); } } [AttributeUsage(AttributeTargets.Property)]
Tokenizer
csharp
EventStore__EventStore
src/KurrentDB.Projections.Core.Tests/Services/feed_reader/feed_reader.cs
{ "start": 4979, "end": 5864 }
public class ____ : FeedReaderSpecification { protected override QuerySourcesDefinition GivenQuerySource() { return new QuerySourcesDefinition { AllStreams = true, AllEvents = true }; } protected override void When() { _feedReader.Start(); } [Test] public void publishes_subscribe_message() { var subscribe = _consumer.HandledMessages.OfType<ReaderSubscriptionManagement.Subscribe>().ToArray(); Assert.AreEqual(1, subscribe.Length); } [Test] public void subscribes_to_a_finite_number_of_events() { var subscribe = _consumer.HandledMessages.OfType<ReaderSubscriptionManagement.Subscribe>().Single(); Assert.NotNull(subscribe.Options); Assert.NotNull(subscribe.Options.StopAfterNEvents); Assert.Less(0, subscribe.Options.StopAfterNEvents); Assert.IsTrue(subscribe.Options.StopOnEof); } } [TestFixture]
when_starting
csharp
dotnet__aspnetcore
src/Mvc/Mvc.Core/src/Formatters/MediaType.cs
{ "start": 453, "end": 12055 }
struct ____ { private static readonly StringSegment QualityParameter = new StringSegment("q"); private readonly ReadOnlyMediaTypeHeaderValue _mediaTypeHeaderValue; /// <summary> /// Initializes a <see cref="MediaType"/> instance. /// </summary> /// <param name="mediaType">The <see cref="string"/> with the media type.</param> public MediaType(string mediaType) : this(mediaType, 0, mediaType.Length) { } /// <summary> /// Initializes a <see cref="MediaType"/> instance. /// </summary> /// <param name="mediaType">The <see cref="StringSegment"/> with the media type.</param> public MediaType(StringSegment mediaType) : this(mediaType.Buffer ?? string.Empty, mediaType.Offset, mediaType.Length) { } /// <summary> /// Initializes a <see cref="MediaTypeParameterParser"/> instance. /// </summary> /// <param name="mediaType">The <see cref="string"/> with the media type.</param> /// <param name="offset">The offset in the <paramref name="mediaType"/> where the parsing starts.</param> /// <param name="length">The length of the media type to parse if provided.</param> public MediaType(string mediaType, int offset, int? length) { ArgumentNullException.ThrowIfNull(mediaType); if (offset < 0 || offset >= mediaType.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (length != null) { if (length < 0 || length > mediaType.Length) { throw new ArgumentOutOfRangeException(nameof(length)); } if (offset > mediaType.Length - length) { throw new ArgumentException(Resources.FormatArgument_InvalidOffsetLength(nameof(offset), nameof(length))); } } _mediaTypeHeaderValue = new ReadOnlyMediaTypeHeaderValue(mediaType, offset, length); } /// <summary> /// Gets the type of the <see cref="MediaType"/>. /// </summary> /// <example> /// For the media type <c>"application/json"</c>, this property gives the value <c>"application"</c>. /// </example> public StringSegment Type => _mediaTypeHeaderValue.Type; /// <summary> /// Gets whether this <see cref="MediaType"/> matches all types. /// </summary> public bool MatchesAllTypes => _mediaTypeHeaderValue.MatchesAllTypes; /// <summary> /// Gets the subtype of the <see cref="MediaType"/>. /// </summary> /// <example> /// For the media type <c>"application/vnd.example+json"</c>, this property gives the value /// <c>"vnd.example+json"</c>. /// </example> public StringSegment SubType => _mediaTypeHeaderValue.SubType; /// <summary> /// Gets the subtype of the <see cref="MediaType"/>, excluding any structured syntax suffix. /// </summary> /// <example> /// For the media type <c>"application/vnd.example+json"</c>, this property gives the value /// <c>"vnd.example"</c>. /// </example> public StringSegment SubTypeWithoutSuffix => _mediaTypeHeaderValue.SubTypeWithoutSuffix; /// <summary> /// Gets the structured syntax suffix of the <see cref="MediaType"/> if it has one. /// </summary> /// <example> /// For the media type <c>"application/vnd.example+json"</c>, this property gives the value /// <c>"json"</c>. /// </example> public StringSegment SubTypeSuffix => _mediaTypeHeaderValue.SubTypeSuffix; /// <summary> /// Gets whether this <see cref="MediaType"/> matches all subtypes. /// </summary> /// <example> /// For the media type <c>"application/*"</c>, this property is <c>true</c>. /// </example> /// <example> /// For the media type <c>"application/json"</c>, this property is <c>false</c>. /// </example> public bool MatchesAllSubTypes => _mediaTypeHeaderValue.MatchesAllSubTypes; /// <summary> /// Gets whether this <see cref="MediaType"/> matches all subtypes, ignoring any structured syntax suffix. /// </summary> /// <example> /// For the media type <c>"application/*+json"</c>, this property is <c>true</c>. /// </example> /// <example> /// For the media type <c>"application/vnd.example+json"</c>, this property is <c>false</c>. /// </example> public bool MatchesAllSubTypesWithoutSuffix => _mediaTypeHeaderValue.MatchesAllSubTypesWithoutSuffix; /// <summary> /// Gets the <see cref="System.Text.Encoding"/> of the <see cref="MediaType"/> if it has one. /// </summary> public Encoding? Encoding => _mediaTypeHeaderValue.Encoding; /// <summary> /// Gets the charset parameter of the <see cref="MediaType"/> if it has one. /// </summary> public StringSegment Charset => _mediaTypeHeaderValue.Charset; /// <summary> /// Determines whether the current <see cref="MediaType"/> contains a wildcard. /// </summary> /// <returns> /// <c>true</c> if this <see cref="MediaType"/> contains a wildcard; otherwise <c>false</c>. /// </returns> public bool HasWildcard => _mediaTypeHeaderValue.HasWildcard; /// <summary> /// Determines whether the current <see cref="MediaType"/> is a subset of the <paramref name="set"/> /// <see cref="MediaType"/>. /// </summary> /// <param name="set">The set <see cref="MediaType"/>.</param> /// <returns> /// <c>true</c> if this <see cref="MediaType"/> is a subset of <paramref name="set"/>; otherwise <c>false</c>. /// </returns> public bool IsSubsetOf(MediaType set) => _mediaTypeHeaderValue.IsSubsetOf(set._mediaTypeHeaderValue); /// <summary> /// Gets the parameter <paramref name="parameterName"/> of the media type. /// </summary> /// <param name="parameterName">The name of the parameter to retrieve.</param> /// <returns> /// The <see cref="StringSegment"/>for the given <paramref name="parameterName"/> if found; otherwise /// <c>null</c>. /// </returns> public StringSegment GetParameter(string parameterName) => _mediaTypeHeaderValue.GetParameter(parameterName); /// <summary> /// Gets the parameter <paramref name="parameterName"/> of the media type. /// </summary> /// <param name="parameterName">The name of the parameter to retrieve.</param> /// <returns> /// The <see cref="StringSegment"/>for the given <paramref name="parameterName"/> if found; otherwise /// <c>null</c>. /// </returns> public StringSegment GetParameter(StringSegment parameterName) => _mediaTypeHeaderValue.GetParameter(parameterName); /// <summary> /// Replaces the encoding of the given <paramref name="mediaType"/> with the provided /// <paramref name="encoding"/>. /// </summary> /// <param name="mediaType">The media type whose encoding will be replaced.</param> /// <param name="encoding">The encoding that will replace the encoding in the <paramref name="mediaType"/>. /// </param> /// <returns>A media type with the replaced encoding.</returns> public static string ReplaceEncoding(string mediaType, Encoding encoding) { return ReplaceEncoding(new StringSegment(mediaType), encoding); } /// <summary> /// Replaces the encoding of the given <paramref name="mediaType"/> with the provided /// <paramref name="encoding"/>. /// </summary> /// <param name="mediaType">The media type whose encoding will be replaced.</param> /// <param name="encoding">The encoding that will replace the encoding in the <paramref name="mediaType"/>. /// </param> /// <returns>A media type with the replaced encoding.</returns> public static string ReplaceEncoding(StringSegment mediaType, Encoding encoding) { var parsedMediaType = new MediaType(mediaType); var charset = parsedMediaType.GetParameter("charset"); if (charset.HasValue && charset.Equals(encoding.WebName, StringComparison.OrdinalIgnoreCase)) { return mediaType.Value ?? string.Empty; } if (!charset.HasValue) { return CreateMediaTypeWithEncoding(mediaType, encoding); } var charsetOffset = charset.Offset - mediaType.Offset; var restOffset = charsetOffset + charset.Length; var restLength = mediaType.Length - restOffset; var finalLength = charsetOffset + encoding.WebName.Length + restLength; var builder = new StringBuilder(mediaType.Buffer, mediaType.Offset, charsetOffset, finalLength); builder.Append(encoding.WebName); builder.Append(mediaType.Buffer, restOffset, restLength); return builder.ToString(); } /// <summary> /// Get an encoding for a mediaType. /// </summary> /// <param name="mediaType">The mediaType.</param> /// <returns>The encoding.</returns> public static Encoding? GetEncoding(string mediaType) { return GetEncoding(new StringSegment(mediaType)); } /// <summary> /// Get an encoding for a mediaType. /// </summary> /// <param name="mediaType">The mediaType.</param> /// <returns>The encoding.</returns> public static Encoding? GetEncoding(StringSegment mediaType) { var parsedMediaType = new MediaType(mediaType); return parsedMediaType.Encoding; } /// <summary> /// Creates an <see cref="MediaTypeSegmentWithQuality"/> containing the media type in <paramref name="mediaType"/> /// and its associated quality. /// </summary> /// <param name="mediaType">The media type to parse.</param> /// <param name="start">The position at which the parsing starts.</param> /// <returns>The parsed media type with its associated quality.</returns> public static MediaTypeSegmentWithQuality CreateMediaTypeSegmentWithQuality(string mediaType, int start) { var parsedMediaType = new ReadOnlyMediaTypeHeaderValue(mediaType, start, length: null); // Short-circuit use of the MediaTypeParameterParser if constructor detected an invalid type or subtype. // Parser would set ParsingFailed==true in this case. But, we handle invalid parameters as a separate case. if (parsedMediaType.Type.Equals(default(StringSegment)) || parsedMediaType.SubType.Equals(default(StringSegment))) { return default(MediaTypeSegmentWithQuality); } var quality = 1.0d; var parser = parsedMediaType.ParameterParser; while (parser.ParseNextParameter(out var parameter)) { if (parameter.HasName(QualityParameter)) { // If media type contains two `q` values i.e. it's invalid in an uncommon way, pick last value. quality = double.Parse( parameter.Value.AsSpan(), NumberStyles.AllowDecimalPoint, NumberFormatInfo.InvariantInfo); } } // We check if the parsed media type has a value at this stage when we have iterated // over all the parameters and we know if the parsing was successful. if (parser.ParsingFailed) { return default(MediaTypeSegmentWithQuality); } return new MediaTypeSegmentWithQuality( new StringSegment(mediaType, start, parser.CurrentOffset - start), quality); } private static string CreateMediaTypeWithEncoding(StringSegment mediaType, Encoding encoding) { return $"{mediaType.Value}; charset={encoding.WebName}"; }
MediaType
csharp
cake-build__cake
src/Cake.Common/Tools/VSTest/VSTestSettings.cs
{ "start": 391, "end": 4619 }
public sealed class ____ : ToolSettings { /// <summary> /// Gets or sets the settings filename to be used to control additional settings such as data collectors. /// </summary> public FilePath SettingsFile { get; set; } /// <summary> /// Gets or sets a value indicating whether the tests are executed in parallel. By default up to all available cores on the machine may be used. The number of cores to use may be configured using a settings file. /// </summary> public bool Parallel { get; set; } /// <summary> /// Gets or sets a value indicating whether to enable data diagnostic adapter 'CodeCoverage' in the test run. Default settings are used if not specified using settings file. /// </summary> public bool EnableCodeCoverage { get; set; } /// <summary> /// Gets or sets a value indicating whether to run tests within the vstest.console.exe process. /// This makes vstest.console.exe process less likely to be stopped on an error in the tests, but tests might run slower. /// Defaults to <c>false</c>. /// </summary> /// <value> /// <c>true</c> if running in isolation; otherwise, <c>false</c>. /// </value> public bool InIsolation { get; set; } /// <summary> /// Gets or sets a value overriding whether VSTest will use or skip the VSIX extensions installed (if any) in the test run. /// </summary> public bool? UseVsixExtensions { get; set; } /// <summary> /// Gets or sets a value that makes VSTest use custom test adapters from a given path (if any) in the test run. /// </summary> public DirectoryPath TestAdapterPath { get; set; } /// <summary> /// Gets or sets the target platform architecture to be used for test execution. /// </summary> public VSTestPlatform PlatformArchitecture { get; set; } /// <summary> /// Gets or sets the target .NET Framework version to be used for test execution. /// </summary> public VSTestFrameworkVersion FrameworkVersion { get; set; } /// <summary> /// Gets or sets an expression to run only tests that match, of the format &lt;property&gt;Operator&lt;value&gt;[|&amp;&lt;Expression&gt;] /// where Operator is one of =, != or ~ (Operator ~ has 'contains' /// semantics and is applicable for string properties like DisplayName). /// Parenthesis () can be used to group sub-expressions. /// Examples: Priority=1 /// (FullyQualifiedName~Nightly|Name=MyTestMethod). /// </summary> public string TestCaseFilter { get; set; } /// <summary> /// Gets or sets a path which makes VSTest write diagnosis trace logs to specified file. /// </summary> public FilePath Diag { get; set; } /// <summary> /// Gets or sets the result directory. /// Test results directory will be created in specified path if not exists. /// VSTest.Console.exe flag <see href="https://docs.microsoft.com/en-us/visualstudio/test/vstest-console-options#ResultDirectory">/ResultsDirectory</see>. /// </summary> public DirectoryPath ResultsDirectory { get; set; } /// <summary> /// Gets or sets the name of your logger. Possible values: /// - A blank string (or null): no logger /// - "trx": Visual Studio's built-in logger /// - "AppVeyor": AppVeyor's custom logger which is available only when building your solution on the AppVeyor platform /// - any custom value: the name of your custom logger. /// </summary> public string Logger { get; set; } /// <summary> /// Gets or sets a value indicating whether tools from a preview edition of Visual Studio should be used. /// <para> /// If set to <c>true</c>, VSTest from a Preview edition /// (e.g. Visual Studio 2022 Preview) will be considered to be used. /// </para> /// </summary> public bool AllowPreviewVersion { get; set; } = false; } }
VSTestSettings
csharp
dotnet__efcore
test/EFCore.Specification.Tests/Query/NorthwindNavigationsQueryTestBase.cs
{ "start": 330, "end": 36957 }
public abstract class ____<TFixture>(TFixture fixture) : QueryTestBase<TFixture>(fixture) where TFixture : NorthwindQueryFixtureBase<NoopModelCustomizer>, new() { protected NorthwindContext CreateContext() => Fixture.CreateContext(); protected virtual void ClearLog() { } [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Join_with_nav_projected_in_subquery_when_client_eval(bool async) => AssertTranslationFailed(() => AssertQuery( async, ss => from c in ss.Set<Customer>() join o in ss.Set<Order>().Select(o => ClientProjection(o, o.Customer)) on c.CustomerID equals o.CustomerID join od in ss.Set<OrderDetail>().Select(od => ClientProjection(od, od.Product)) on o.OrderID equals od.OrderID select c)); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Join_with_nav_in_predicate_in_subquery_when_client_eval(bool async) => AssertTranslationFailed(() => AssertQuery( async, ss => from c in ss.Set<Customer>() join o in ss.Set<Order>().Where(o => ClientPredicate(o, o.Customer)) on c.CustomerID equals o.CustomerID join od in ss.Set<OrderDetail>().Where(od => ClientPredicate(od, od.Product)) on o.OrderID equals od.OrderID select c)); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Join_with_nav_in_orderby_in_subquery_when_client_eval(bool async) => AssertTranslationFailed(() => AssertQuery( async, ss => from c in ss.Set<Customer>() join o in ss.Set<Order>().OrderBy(o => ClientOrderBy(o, o.Customer)) on c.CustomerID equals o.CustomerID join od in ss.Set<OrderDetail>().OrderBy(od => ClientOrderBy(od, od.Product)) on o.OrderID equals od.OrderID select c)); private static readonly Random _randomGenerator = new(); private static T ClientProjection<T>(T t, object _) => t; private static bool ClientPredicate<T>(T t, object _) => true; private static int ClientOrderBy<T>(T t, object _) => _randomGenerator.Next(0, 20); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_Where_Navigation(bool async) => AssertQuery( async, ss => from o in ss.Set<Order>() where o.Customer.City == "Seattle" select o); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_Where_Navigation_Contains(bool async) => AssertQuery( async, ss => from o in ss.Set<Order>() where o.Customer.City.Contains("Sea") select o); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_Where_Navigation_Scalar_Equals_Navigation_Scalar(bool async) => AssertQuery( async, ss => from o1 in ss.Set<Order>().Where(o => o.OrderID < 10300) from o2 in ss.Set<Order>().Where(o => o.OrderID < 10400) where o1.Customer.City == o2.Customer.City select new { o1, o2 }, elementSorter: e => e.o1.OrderID + " " + e.o2.OrderID, elementAsserter: (e, a) => { AssertEqual(e.o1, a.o1); AssertEqual(e.o2, a.o2); }); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_Where_Navigation_Scalar_Equals_Navigation_Scalar_Projected(bool async) => AssertQuery( async, ss => from o1 in ss.Set<Order>().Where(o => o.OrderID < 10300) from o2 in ss.Set<Order>().Where(o => o.OrderID < 10400) where o1.Customer.City == o2.Customer.City select new { o1.CustomerID, C2 = o2.CustomerID }, elementSorter: e => e.CustomerID + " " + e.C2); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_Where_Navigation_Client(bool async) => AssertTranslationFailedWithDetails( () => AssertQuery( async, ss => from o in ss.Set<Order>() where o.Customer.IsLondon select o), CoreStrings.QueryUnableToTranslateMember(nameof(Customer.IsLondon), nameof(Customer))); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_Where_Navigation_Deep(bool async) => AssertQuery( async, ss => (from od in ss.Set<OrderDetail>() where od.Order.Customer.City == "Seattle" orderby od.OrderID, od.ProductID select od).Take(1)); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Take_Select_Navigation(bool async) => AssertQuery( async, ss => ss.Set<Customer>().OrderBy(c => c.CustomerID).Take(2) .Select(c => c.Orders.OrderBy(o => o.OrderID).FirstOrDefault())); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_collection_FirstOrDefault_project_single_column1(bool async) => AssertQuery( async, ss => ss.Set<Customer>().OrderBy(c => c.CustomerID).Take(2) .Select(c => c.Orders.OrderBy(o => o.OrderID).FirstOrDefault().CustomerID)); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_collection_FirstOrDefault_project_single_column2(bool async) => AssertQuery( async, ss => ss.Set<Customer>().OrderBy(c => c.CustomerID).Take(2) .Select(c => c.Orders.OrderBy(o => o.OrderID).Select(o => o.CustomerID).FirstOrDefault())); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_collection_FirstOrDefault_project_anonymous_type(bool async) => AssertQuery( async, ss => ss.Set<Customer>().Where(e => e.CustomerID.StartsWith("F")).OrderBy(c => c.CustomerID).Take(2).Select(c => c.Orders.OrderBy(o => o.OrderID).Select(o => new { o.CustomerID, o.OrderID }).FirstOrDefault()), assertOrder: true); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_collection_FirstOrDefault_project_anonymous_type_client_eval(bool async) => AssertQuery( async, ss => ss.Set<Customer>().Where(e => e.CustomerID.StartsWith("F")).OrderBy(c => c.CustomerID).Take(2).Select(c => c.Orders.OrderBy(o => o.OrderID).Select(o => new { o.CustomerID, OrderID = ClientFunction(o.OrderID, 5) }) .FirstOrDefault()), assertOrder: true); private static int ClientFunction(int a, int b) => a + b + 1; [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_collection_FirstOrDefault_project_entity(bool async) => AssertQuery( async, ss => ss.Set<Customer>().OrderBy(c => c.CustomerID).Take(2).Select(c => c.Orders.OrderBy(o => o.OrderID).FirstOrDefault())); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Skip_Select_Navigation(bool async) => AssertQuery( async, ss => ss.Set<Customer>().OrderBy(c => c.CustomerID) .Skip(20) .Select(c => c.Orders.OrderBy(o => o.OrderID).FirstOrDefault()), assertOrder: true); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_Where_Navigation_Null(bool async) => AssertQuery( async, ss => from e in ss.Set<Employee>() where e.Manager == null select e); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_Where_Navigation_Null_Reverse(bool async) => AssertQuery( async, ss => from e in ss.Set<Employee>() where null == e.Manager select e); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_Where_Navigation_Null_Deep(bool async) => AssertQuery( async, ss => from e in ss.Set<Employee>() where e.Manager.Manager == null select e); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_Where_Navigation_Equals_Navigation(bool async) => AssertQuery( async, ss => from o1 in ss.Set<Order>() from o2 in ss.Set<Order>() where o1.CustomerID.StartsWith("A") where o2.CustomerID.StartsWith("A") where o1.Customer == o2.Customer select new { o1, o2 }, elementSorter: e => e.o1.OrderID + " " + e.o2.OrderID); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_Where_Navigation_Included(bool async) => AssertQuery( async, ss => from o in ss.Set<Order>().Include(o => o.Customer) where o.Customer.City == "Seattle" select o, elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude<Order>(o => o.Customer))); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Include_with_multiple_optional_navigations(bool async) { var expectedIncludes = new IExpectedInclude[] { new ExpectedInclude<OrderDetail>(od => od.Order), new ExpectedInclude<Order>(o => o.Customer, "Order") }; return AssertQuery( async, ss => ss.Set<OrderDetail>() .Include(od => od.Order.Customer) .Where(od => od.Order.Customer.City == "London"), elementAsserter: (e, a) => AssertInclude(e, a, expectedIncludes)); } [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_count_plus_sum(bool async) => AssertQuery( async, ss => ss.Set<Order>().Select(o => new { Total = o.OrderDetails.Sum(od => od.Quantity) + o.OrderDetails.Count() }), elementSorter: e => e.Total); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Singleton_Navigation_With_Member_Access(bool async) => AssertQuery( async, ss => from o in ss.Set<Order>() where o.Customer.City == "Seattle" where o.Customer.Phone != "555 555 5555" select new { B = o.Customer.City }, elementSorter: e => e.B); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_Singleton_Navigation_With_Member_Access(bool async) => AssertQuery( async, ss => from o in ss.Set<Order>() where o.Customer.City == "Seattle" where o.Customer.Phone != "555 555 5555" select new { A = o.Customer, B = o.Customer.City }, elementSorter: e => e.A + " " + e.B); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_Where_Navigation_Multiple_Access(bool async) => AssertQuery( async, ss => from o in ss.Set<Order>() where o.Customer.City == "Seattle" && o.Customer.Phone != "555 555 5555" select o); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_Navigation(bool async) => AssertQuery( async, ss => from o in ss.Set<Order>() select o.Customer); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_Navigations(bool async) => AssertQuery( async, ss => from o in ss.Set<Order>() select new { A = o.Customer, B = o.Customer }, elementSorter: e => e.A.CustomerID, elementAsserter: (e, a) => { AssertEqual(e.A, a.A); AssertEqual(e.B, a.B); }); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_Navigations_Where_Navigations(bool async) => AssertQuery( async, ss => from o in ss.Set<Order>() where o.Customer.City == "Seattle" where o.Customer.Phone != "555 555 5555" select new { A = o.Customer, B = o.Customer }, elementSorter: e => e.A.CustomerID, elementAsserter: (e, a) => { AssertEqual(e.A, a.A); AssertEqual(e.B, a.B); }); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_collection_navigation_simple(bool async) => AssertQuery( async, ss => from c in ss.Set<Customer>() where c.CustomerID.StartsWith("A") orderby c.CustomerID select new { c.CustomerID, c.Orders }, elementSorter: e => e.CustomerID, elementAsserter: (e, a) => { Assert.Equal(e.CustomerID, a.CustomerID); AssertCollection(e.Orders, a.Orders); }); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_collection_navigation_simple2(bool async) => AssertQuery( async, ss => from c in ss.Set<Customer>() where c.CustomerID.StartsWith("A") orderby c.CustomerID select new { c.CustomerID, c.Orders.Count }, elementSorter: e => e.CustomerID, elementAsserter: (e, a) => { Assert.Equal(e.CustomerID, a.CustomerID); Assert.Equal(e.Count, a.Count); }); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_collection_navigation_simple_followed_by_ordering_by_scalar(bool async) => AssertQuery( async, ss => (from c in ss.Set<Customer>() where c.CustomerID.StartsWith("A") orderby c.CustomerID select new { c.CustomerID, c.Orders }).OrderBy(e => e.CustomerID), elementAsserter: (e, a) => { Assert.Equal(e.CustomerID, a.CustomerID); AssertCollection(e.Orders, a.Orders); }, assertOrder: true); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_collection_navigation_multi_part(bool async) => AssertQuery( async, ss => from o in ss.Set<Order>() where o.CustomerID == "ALFKI" select new { o.OrderID, o.Customer.Orders }, elementSorter: e => e.OrderID, elementAsserter: (e, a) => { Assert.Equal(e.OrderID, a.OrderID); AssertCollection(e.Orders, a.Orders); }); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_collection_navigation_multi_part2(bool async) => AssertQuery( async, ss => from od in ss.Set<OrderDetail>() orderby od.OrderID, od.ProductID where od.Order.CustomerID == "ALFKI" || od.Order.CustomerID == "ANTON" select new { od.Order.Customer.Orders }, assertOrder: true, elementAsserter: (e, a) => AssertCollection(e.Orders, a.Orders)); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_select_nav_prop_any(bool async) => AssertQuery( async, ss => from c in ss.Set<Customer>() select new { Any = c.Orders.Any() }, ss => from c in ss.Set<Customer>() select new { Any = (c.Orders ?? new List<Order>()).Any() }, elementSorter: e => e.Any); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_select_nav_prop_predicate(bool async) => AssertQueryScalar( async, ss => ss.Set<Customer>().Select(c => c.Orders.Count > 0), ss => ss.Set<Customer>().Select(c => (c.Orders ?? new List<Order>()).Count > 0)); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_where_nav_prop_any(bool async) => AssertQuery( async, ss => from c in ss.Set<Customer>() where c.Orders.Any() select c, ss => from c in ss.Set<Customer>() where (c.Orders ?? new List<Order>()).Any() select c); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_where_nav_prop_any_predicate(bool async) => AssertQuery( async, ss => from c in ss.Set<Customer>() where c.Orders.Any(o => o.OrderID > 0) select c, ss => from c in ss.Set<Customer>() where (c.Orders ?? new List<Order>()).Any(o => o.OrderID > 0) select c); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_select_nav_prop_all(bool async) => AssertQuery( async, ss => from c in ss.Set<Customer>() select new { All = c.Orders.All(o => o.CustomerID == "ALFKI") }, ss => from c in ss.Set<Customer>() select new { All = (c.Orders ?? new List<Order>()).All(o => o.CustomerID == "ALFKI") }, elementSorter: e => e.All); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_select_nav_prop_all_client(bool async) => AssertTranslationFailedWithDetails( () => AssertQuery( async, ss => from c in ss.Set<Customer>() orderby c.CustomerID select new { All = c.Orders.All(o => o.ShipCity == "London") }, ss => from c in ss.Set<Customer>() orderby c.CustomerID select new { All = (c.Orders ?? new List<Order>()).All(o => false) }, assertOrder: true), CoreStrings.QueryUnableToTranslateMember(nameof(Order.ShipCity), nameof(Order))); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_where_nav_prop_all(bool async) => AssertQuery( async, ss => from c in ss.Set<Customer>() where c.Orders.All(o => o.CustomerID == "ALFKI") select c, ss => from c in ss.Set<Customer>() where (c.Orders ?? new List<Order>()).All(o => o.CustomerID == "ALFKI") select c); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_where_nav_prop_all_client(bool async) => AssertTranslationFailedWithDetails( () => AssertQuery( async, ss => from c in ss.Set<Customer>() orderby c.CustomerID where c.Orders.All(o => o.ShipCity == "London") select c), CoreStrings.QueryUnableToTranslateMember(nameof(Order.ShipCity), nameof(Order))); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_select_nav_prop_count(bool async) => AssertQuery( async, ss => from c in ss.Set<Customer>() select new { c.Orders.Count }, ss => from c in ss.Set<Customer>() select new { (c.Orders ?? new List<Order>()).Count }, elementSorter: e => e.Count); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_where_nav_prop_count(bool async) => AssertQuery( async, ss => from c in ss.Set<Customer>() where c.Orders.Count() > 5 select c, ss => from c in ss.Set<Customer>() where (c.Orders ?? new List<Order>()).Count() > 5 select c); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_where_nav_prop_count_reverse(bool async) => AssertQuery( async, ss => from c in ss.Set<Customer>() where 5 < c.Orders.Count() select c, ss => from c in ss.Set<Customer>() where 5 < (c.Orders ?? new List<Order>()).Count() select c); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_orderby_nav_prop_count(bool async) => AssertQuery( async, ss => from c in ss.Set<Customer>() orderby c.Orders.Count(), c.CustomerID select c, ss => from c in ss.Set<Customer>() orderby (c.Orders ?? new List<Order>()).Count(), c.CustomerID select c, assertOrder: true); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_select_nav_prop_long_count(bool async) => AssertQuery( async, ss => from c in ss.Set<Customer>() select new { C = c.Orders.LongCount() }, ss => from c in ss.Set<Customer>() select new { C = (c.Orders ?? new List<Order>()).LongCount() }, elementSorter: e => e.C); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Select_multiple_complex_projections(bool async) => AssertQuery( async, ss => from o in ss.Set<Order>() where o.CustomerID.StartsWith("A") select new { collection1 = o.OrderDetails.Count(), scalar1 = o.OrderDate, any = o.OrderDetails.Select(od => od.UnitPrice).Any(up => up > 10), conditional = o.CustomerID == "ALFKI" ? "50" : "10", scalar2 = (int?)o.OrderID, all = o.OrderDetails.All(od => od.OrderID == 42), collection2 = o.OrderDetails.LongCount() }, elementSorter: e => e.scalar2); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_select_nav_prop_sum(bool async) => AssertQuery( async, ss => from c in ss.Set<Customer>() select new { Sum = c.Orders.Sum(o => o.OrderID) }, ss => from c in ss.Set<Customer>() select new { Sum = (c.Orders ?? new List<Order>()).Sum(o => o.OrderID) }, elementSorter: e => e.Sum); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_select_nav_prop_sum_plus_one(bool async) => AssertQuery( async, ss => from c in ss.Set<Customer>() select new { Sum = c.Orders.Sum(o => o.OrderID) + 1 }, ss => from c in ss.Set<Customer>() select new { Sum = (c.Orders ?? new List<Order>()).Sum(o => o.OrderID) + 1 }, elementSorter: e => e.Sum); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_where_nav_prop_sum(bool async) => AssertQuery( async, ss => from c in ss.Set<Customer>() where c.Orders.Sum(o => o.OrderID) > 1000 select c, ss => from c in ss.Set<Customer>() where (c.Orders ?? new List<Order>()).Sum(o => o.OrderID) > 1000 select c); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_select_nav_prop_first_or_default(bool async) => AssertQuery( async, ss => from c in ss.Set<Customer>() orderby c.CustomerID select new { First = c.Orders.OrderBy(o => o.OrderID).FirstOrDefault() }, ss => from c in ss.Set<Customer>() orderby c.CustomerID select new { First = (c.Orders ?? new List<Order>()).FirstOrDefault() }, assertOrder: true); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_select_nav_prop_first_or_default_then_nav_prop(bool async) { var orderIds = new[] { 10643, 10692, 10702, 10835, 10952, 11011 }; return AssertQuery( async, ss => from c in ss.Set<Customer>().Where(e => e.CustomerID.StartsWith("A")) orderby c.CustomerID select new { c.Orders.Where(e => orderIds.Contains(e.OrderID)).FirstOrDefault().Customer }, ss => from c in ss.Set<Customer>().Where(e => e.CustomerID.StartsWith("A")) orderby c.CustomerID select new { #pragma warning disable RCS1146 // Use conditional access. Customer = c.Orders != null && c.Orders.Where(e => orderIds.Contains(e.OrderID)).Any() #pragma warning restore RCS1146 // Use conditional access. ? c.Orders.Where(e => orderIds.Contains(e.OrderID)).First().Customer : null }, assertOrder: true, elementAsserter: (e, a) => AssertEqual(e.Customer, a.Customer)); } [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_select_nav_prop_first_or_default_then_nav_prop_nested(bool async) => AssertQuery( async, ss => ss.Set<Customer>().Where(e => e.CustomerID.StartsWith("A")) .Select(c => ss.Set<Order>().FirstOrDefault(o => o.CustomerID == "ALFKI").Customer.City)); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_select_nav_prop_single_or_default_then_nav_prop_nested(bool async) => AssertQuery( async, ss => ss.Set<Customer>().Where(e => e.CustomerID.StartsWith("A")) .Select(c => ss.Set<Order>().SingleOrDefault(o => o.OrderID == 10643).Customer.City)); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_select_nav_prop_first_or_default_then_nav_prop_nested_using_property_method(bool async) => AssertQuery( async, ss => ss.Set<Customer>().Where(e => e.CustomerID.StartsWith("A")) .Select(c => EF.Property<string>( EF.Property<Customer>( ss.Set<Order>().FirstOrDefault(oo => oo.CustomerID == "ALFKI"), "Customer"), "City")), ss => ss.Set<Customer>().Where(c => c.CustomerID.StartsWith("A")) .Select(c => ss.Set<Order>().FirstOrDefault(o => o.CustomerID == "ALFKI").Customer != null ? ss.Set<Order>().FirstOrDefault(o => o.CustomerID == "ALFKI").Customer.City : null) ); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Collection_select_nav_prop_first_or_default_then_nav_prop_nested_with_orderby(bool async) => AssertQuery( async, ss => ss.Set<Customer>().Where(e => e.CustomerID.StartsWith("A")) .Select(c => ss.Set<Order>().OrderBy(o => o.CustomerID).FirstOrDefault(o => o.CustomerID == "ALFKI").Customer.City)); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Navigation_fk_based_inside_contains(bool async) => AssertQuery( async, ss => from o in ss.Set<Order>() where new[] { "ALFKI" }.Contains(o.Customer.CustomerID) select o); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Navigation_inside_contains(bool async) => AssertQuery( async, ss => from o in ss.Set<Order>() where new[] { "Novigrad", "Seattle" }.Contains(o.Customer.City) select o); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Navigation_inside_contains_nested(bool async) => AssertQuery( async, ss => from od in ss.Set<OrderDetail>() where new[] { "Novigrad", "Seattle" }.Contains(od.Order.Customer.City) select od); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Navigation_from_join_clause_inside_contains(bool async) => AssertQuery( async, ss => from od in ss.Set<OrderDetail>() join o in ss.Set<Order>() on od.OrderID equals o.OrderID where new[] { "USA", "Redania" }.Contains(o.Customer.Country) select od); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual async Task Where_subquery_on_navigation(bool async) // Complex entity equality. Issue #15260. => Assert.Equal( CoreStrings.EntityEqualityOnCompositeKeyEntitySubqueryNotSupported("Equals", nameof(OrderDetail)), (await Assert.ThrowsAsync<InvalidOperationException>(() => AssertQuery( async, ss => from p in ss.Set<Product>() where p.OrderDetails.Contains( ss.Set<OrderDetail>().OrderByDescending(o => o.OrderID).ThenBy(o => o.ProductID) .FirstOrDefault(orderDetail => orderDetail.Quantity == 1)) select p))).Message); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual async Task Where_subquery_on_navigation2(bool async) // Complex entity equality. Issue #15260. => Assert.Equal( CoreStrings.EntityEqualityOnCompositeKeyEntitySubqueryNotSupported("Equals", nameof(OrderDetail)), (await Assert.ThrowsAsync<InvalidOperationException>(() => AssertQuery( async, ss => from p in ss.Set<Product>() where p.OrderDetails.Contains( ss.Set<OrderDetail>().OrderByDescending(o => o.OrderID).ThenBy(o => o.ProductID).FirstOrDefault()) select p))).Message); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Where_subquery_on_navigation_client_eval(bool async) => AssertQuery( async, ss => from c in ss.Set<Customer>() orderby c.CustomerID where c.Orders.Select(o => o.OrderID).Contains( ss.Set<Order>().OrderByDescending(o => ClientMethod(o.OrderID)).Select(o => o.OrderID).FirstOrDefault()) select c); // ReSharper disable once MemberCanBeMadeStatic.Local private static int ClientMethod(int argument) => argument; [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Navigation_in_subquery_referencing_outer_query(bool async) => AssertQuery( async, ss => from o in ss.Set<Order>() // ReSharper disable once UseMethodAny.0 where (from od in ss.Set<OrderDetail>() where o.Customer.Country == od.Order.Customer.Country select od).Count() > 0 where o.OrderID == 10643 || o.OrderID == 10692 select o); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Navigation_in_subquery_referencing_outer_query_with_client_side_result_operator_and_count(bool async) => AssertQuery( async, ss => from o in ss.Set<Order>() where o.OrderID == 10643 || o.OrderID == 10692 // ReSharper disable once UseMethodAny.0 where (from od in ss.Set<OrderDetail>() where o.Customer.Country == od.Order.Customer.Country select od).Distinct().Count() > 0 select o); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Project_single_scalar_value_subquery_is_properly_inlined(bool async) => AssertQuery( async, ss => from c in ss.Set<Customer>() select new { c.CustomerID, OrderId = c.Orders.OrderBy(o => o.OrderID).Select(o => (int?)o.OrderID).FirstOrDefault() }, ss => from c in ss.Set<Customer>() select new { c.CustomerID, OrderId = c.Orders.OrderBy(o => o.OrderID).Select(o => (int?)o.OrderID).FirstOrDefault() }, elementSorter: e => e.CustomerID); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Project_single_entity_value_subquery_works(bool async) => AssertQuery( async, ss => from c in ss.Set<Customer>() where c.CustomerID.StartsWith("A") orderby c.CustomerID select new { c.CustomerID, Order = c.Orders.OrderBy(o => o.OrderID).FirstOrDefault() }, assertOrder: true); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Project_single_scalar_value_subquery_in_query_with_optional_navigation_works(bool async) => AssertQuery( async, ss => (from o in ss.Set<Order>() orderby o.OrderID select new { o.OrderID, OrderDetail = o.OrderDetails.OrderBy(od => od.OrderID).ThenBy(od => od.ProductID).Select(od => od.OrderID) .FirstOrDefault(), o.Customer.City }).Take(3), assertOrder: true); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task GroupJoin_with_complex_subquery_and_LOJ_gets_flattened(bool async) => AssertQuery( async, ss => from c in ss.Set<Customer>() join subquery in from od in ss.Set<OrderDetail>() join o in ss.Set<Order>() on od.OrderID equals 10260 join c2 in ss.Set<Customer>() on o.CustomerID equals c2.CustomerID select c2 on c.CustomerID equals subquery.CustomerID into result from subquery in result.DefaultIfEmpty() select c); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task GroupJoin_with_complex_subquery_and_LOJ_gets_flattened2(bool async) => AssertQuery( async, ss => from c in ss.Set<Customer>() join subquery in from od in ss.Set<OrderDetail>() join o in ss.Set<Order>() on od.OrderID equals 10260 join c2 in ss.Set<Customer>() on o.CustomerID equals c2.CustomerID select c2 on c.CustomerID equals subquery.CustomerID into result from subquery in result.DefaultIfEmpty() select c.CustomerID); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Navigation_with_collection_with_nullable_type_key(bool async) => AssertQuery( async, ss => ss.Set<Order>().Where(o => o.Customer.Orders.Count(oo => oo.OrderID > 10260) > 30)); [ConditionalTheory, MemberData(nameof(IsAsyncData))] public virtual Task Multiple_include_with_multiple_optional_navigations(bool async) => AssertQuery( async, ss => ss.Set<OrderDetail>() .Include(od => od.Order.Customer) .Include(od => od.Product) .Where(od => od.Order.Customer.City == "London"));
NorthwindNavigationsQueryTestBase
csharp
RicoSuter__NSwag
src/NSwag.CodeGeneration/Models/IOperationModel.cs
{ "start": 506, "end": 762 }
public interface ____ { /// <summary>Gets the responses.</summary> IEnumerable<ResponseModelBase> Responses { get; } /// <summary>Gets Swagger operation's mime type.</summary> string Produces { get; } } }
IOperationModel
csharp
ChilliCream__graphql-platform
src/HotChocolate/Mutable/src/Types.Mutable/Collections/OutputFieldDefinitionCollection.cs
{ "start": 79, "end": 1092 }
public sealed class ____ : FieldDefinitionCollection<MutableOutputFieldDefinition> , IReadOnlyFieldDefinitionCollection<IOutputFieldDefinition> { public OutputFieldDefinitionCollection(ITypeSystemMember declaringMember) : base(declaringMember) { } IOutputFieldDefinition IReadOnlyList<IOutputFieldDefinition>.this[int index] => this[index]; IOutputFieldDefinition IReadOnlyFieldDefinitionCollection<IOutputFieldDefinition>.this[string name] => this[name]; bool IReadOnlyFieldDefinitionCollection<IOutputFieldDefinition>.TryGetField( string name, [NotNullWhen(true)] out IOutputFieldDefinition? field) { if (TryGetField(name, out var outputField)) { field = outputField; return true; } field = null; return false; } IEnumerator<IOutputFieldDefinition> IEnumerable<IOutputFieldDefinition>.GetEnumerator() => GetEnumerator(); }
OutputFieldDefinitionCollection
csharp
kgrzybek__modular-monolith-with-ddd
src/Modules/Payments/Infrastructure/AggregateStore/ICheckpointStore.cs
{ "start": 87, "end": 281 }
public interface ____ { long? GetCheckpoint(SubscriptionCode subscriptionCode); Task StoreCheckpoint(SubscriptionCode subscriptionCode, long checkpoint); } }
ICheckpointStore
csharp
smartstore__Smartstore
src/Smartstore.Modules/Smartstore.WebApi/Controllers/Content/MediaFoldersController.cs
{ "start": 568, "end": 11635 }
public class ____ : WebApiController<MediaFolder> { private readonly IFolderService _folderService; private readonly IMediaService _mediaService; public MediaFoldersController(IFolderService folderService, IMediaService mediaService) { _folderService = folderService; _mediaService = mediaService; } [HttpGet("MediaFolders")] [ProducesResponseType(typeof(IEnumerable<FolderNodeInfo>), Status200OK)] public IActionResult Get() { try { var node = _folderService.GetRootNode(); if (node == null) { return NotFound($"Cannot find {nameof(MediaFolder)} root entity."); } // We cannot apply any ODataQueryOptions because we have no MediaFolder entity anymore. var nodes = node.FlattenNodes(false); var folders = nodes.Select(Convert); return Ok(folders); } catch (Exception ex) { return ErrorResult(ex); } } [HttpGet("MediaFolders({key})"), ApiQueryable] public IActionResult Get(int key) { try { var node = _folderService.GetNodeById(key); if (node == null) { return NotFound(key); } return Ok(Convert(node)); } catch (Exception ex) { return ErrorResult(ex); } } [HttpPost, ApiExplorerSettings(IgnoreApi = true)] public IActionResult Post() { return Forbidden(); } [HttpPut, ApiExplorerSettings(IgnoreApi = true)] public IActionResult Put() { return Forbidden(); } [HttpPatch, ApiExplorerSettings(IgnoreApi = true)] public IActionResult Patch() { return Forbidden(); } [HttpDelete, ApiExplorerSettings(IgnoreApi = true)] public IActionResult Delete() { // Insufficient endpoint. Parameters required but ODataActionParameters not possible here. // Query string parameters less good because not part of the EDM. return Forbidden($"Use endpoint \"{nameof(DeleteFolder)}\" instead."); } #region Actions and functions /// <summary> /// Gets a value indicating whether a folder exists. /// </summary> /// <param name="path" example="content/my-folder">The path of the folder.</param> [HttpPost("MediaFolders/FolderExists")] [Consumes(Json), Produces(Json)] [ProducesResponseType(typeof(bool), Status200OK)] public IActionResult FolderExists([FromODataBody, Required] string path) { try { var folderExists = _mediaService.FolderExists(path); return Ok(folderExists); } catch (Exception ex) { return ErrorResult(ex); } } /// <summary> /// Checks the uniqueness of a folder name. /// </summary> /// <param name="path" example="content/my-folder">The path of the folder.</param> [HttpPost("MediaFolders/CheckUniqueFolderName")] [Consumes(Json), Produces(Json)] [ProducesResponseType(typeof(CheckUniquenessResult), Status200OK)] public IActionResult CheckUniqueFolderName([FromODataBody, Required] string path) { try { var success = _folderService.CheckUniqueFolderName(path, out var newPath); return Ok(new CheckUniquenessResult { Result = success, NewPath = newPath }); } catch (Exception ex) { return ErrorResult(ex); } } /// <summary> /// Gets the root folder node. /// </summary> [HttpGet("MediaFolders/GetRootNode")] [Produces(Json)] [ProducesResponseType(typeof(FolderNodeInfo), Status200OK)] public IActionResult GetRootNode() { try { var node = _folderService.GetRootNode(); if (node == null) { return NotFound($"Cannot find {nameof(MediaFolder)} root entity."); } return Ok(Convert(node)); } catch (Exception ex) { return ErrorResult(ex); } } /// <summary> /// Gets a folder node by path. /// </summary> /// <param name="path" example="content/my-folder">The path of the folder.</param> [HttpPost("MediaFolders/GetNodeByPath")] [Consumes(Json), Produces(Json)] [ProducesResponseType(typeof(FolderNodeInfo), Status200OK)] [ProducesResponseType(Status404NotFound)] public IActionResult GetNodeByPath([FromODataBody, Required] string path) { try { var node = _folderService.GetNodeByPath(path); if (node == null) { return NotFound($"Cannot find {nameof(MediaFolder)} entity with path {path.NaIfEmpty()}."); } return Ok(Convert(node)); } catch (Exception ex) { return ErrorResult(ex); } } /// <summary> /// Creates a folder. /// </summary> /// <param name="path" example="content/my-folder">The path of the folder.</param> [HttpPost("MediaFolders/CreateFolder")] [Permission(Permissions.Media.Update)] [Consumes(Json), Produces(Json)] [ProducesResponseType(typeof(FolderNodeInfo), Status201Created)] public async Task<IActionResult> CreateFolder([FromODataBody, Required] string path) { try { var result = await _mediaService.CreateFolderAsync(path); var url = BuildUrl(result.Id); return Created(url, Convert(result.Node)); } catch (Exception ex) { return ErrorResult(ex); } } /// <summary> /// Moves a folder. /// </summary> /// <param name="path" example="content/my-folder">The path of the folder.</param> /// <param name="destinationPath" example="content/my-renamed-folder">The destination folder path.</param> [HttpPost("MediaFolders/MoveFolder")] [Permission(Permissions.Media.Update)] [Consumes(Json), Produces(Json)] [ProducesResponseType(typeof(FolderNodeInfo), Status200OK)] public async Task<IActionResult> MoveFolder( [FromODataBody, Required] string path, [FromODataBody, Required] string destinationPath) { try { var result = await _mediaService.MoveFolderAsync(path, destinationPath); return Ok(Convert(result.Node)); } catch (Exception ex) { return ErrorResult(ex); } } /// <summary> /// Copies a folder. /// </summary> /// <param name="path" example="content/my-folder">The path of the folder.</param> /// <param name="destinationPath" example="content/my-new-folder">The destination folder path.</param> /// <param name="duplicateEntryHandling" example="0">A value indicating how to proceed if the destination folder already exists.</param> [HttpPost("MediaFolders/CopyFolder")] [Permission(Permissions.Media.Update)] [Consumes(Json), Produces(Json)] [ProducesResponseType(typeof(MediaFolderOperationResult), Status200OK)] public async Task<IActionResult> CopyFolder( [FromODataBody, Required] string path, [FromODataBody, Required] string destinationPath, [FromODataBody] DuplicateEntryHandling duplicateEntryHandling = DuplicateEntryHandling.Skip) { try { var result = await _mediaService.CopyFolderAsync(path, destinationPath, duplicateEntryHandling); var opResult = new MediaFolderOperationResult { FolderId = result.Folder.Id, Folder = Convert(result.Folder.Node), DuplicateFiles = result.DuplicateFiles .Select(x => new MediaFolderOperationResult.DuplicateFileInfo { SourceFileId = x.SourceFile.Id, DestinationFileId = x.DestinationFile.Id, //SourceFile = Convert(x.SourceFile), //DestinationFile = Convert(x.DestinationFile), UniquePath = x.UniquePath }) .ToList() }; return Ok(opResult); } catch (Exception ex) { return ErrorResult(ex); } } /// <summary> /// Deletes a folder. /// </summary> /// <param name="path" example="content/my-folder">The path of the folder.</param> /// <param name="fileHandling" example="0">A value indicating how to proceed with the files of the deleted folder.</param> [HttpPost("MediaFolders/DeleteFolder")] [Permission(Permissions.Media.Delete)] [Consumes(Json), Produces(Json)] [ProducesResponseType(typeof(MediaFolderDeleteResult), Status200OK)] public async Task<IActionResult> DeleteFolder( [FromODataBody, Required] string path, [FromODataBody] FileHandling fileHandling = FileHandling.SoftDelete) { try { var result = await _mediaService.DeleteFolderAsync(path, fileHandling); var opResult = new MediaFolderDeleteResult { DeletedFileNames = result.DeletedFileNames, DeletedFolderIds = result.DeletedFolderIds }; return Ok(opResult); } catch (Exception ex) { return ErrorResult(ex); } } #endregion private static FolderNodeInfo Convert(TreeNode<MediaFolderNode> node) { if (node == null) { return null; } var item = MiniMapper.Map<MediaFolderNode, FolderNodeInfo>(node.Value, CultureInfo.InvariantCulture); item.HasChildren = node.HasChildren; return item; } } }
MediaFoldersController
csharp
dotnetcore__WTM
src/WalkingTec.Mvvm.Mvc/BaseApiController.cs
{ "start": 775, "end": 12354 }
public abstract class ____ : ControllerBase, IBaseController { [JsonIgnore] [BindNever] public WTMContext Wtm { get; set; } [JsonIgnore] [BindNever] public Configs ConfigInfo { get => Wtm?.ConfigInfo; } [JsonIgnore] [BindNever] public GlobalData GlobaInfo { get => Wtm?.GlobaInfo; } [JsonIgnore] [BindNever] public IDistributedCache Cache { get => Wtm?.Cache; } [JsonIgnore] [BindNever] public string CurrentCS { get => Wtm?.CurrentCS; } [JsonIgnore] [BindNever] public DBTypeEnum? CurrentDbType { get => Wtm?.CurrentDbType; } [JsonIgnore] [BindNever] public IDataContext DC { get => Wtm?.DC; } [JsonIgnore] [BindNever] public string BaseUrl { get => Wtm?.BaseUrl; } [JsonIgnore] [BindNever] public IStringLocalizer Localizer { get => Wtm?.Localizer; } //-------------------------------------------方法------------------------------------// //#region CreateVM ///// <summary> ///// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel ///// </summary> ///// <param name="VMType">The type of the viewmodel</param> ///// <param name="Id">If the viewmodel is a BaseCRUDVM, the data having this id will be fetched</param> ///// <param name="Ids">If the viewmodel is a BatchVM, the BatchVM's Ids property will be assigned</param> ///// <param name="values">properties of the viewmodel that you want to assign values</param> ///// <param name="passInit">if true, the viewmodel will not call InitVM internally</param> ///// <returns>ViewModel</returns> //[NonAction] //private BaseVM CreateVM(Type VMType, object Id = null, object[] Ids = null, Dictionary<string, object> values = null, bool passInit = false) //{ // //通过反射创建ViewModel并赋值 // var ctor = VMType.GetConstructor(Type.EmptyTypes); // BaseVM rv = ctor.Invoke(null) as BaseVM; // rv.Wtm = Wtm; // rv.FC = new Dictionary<string, object>(); // rv.CreatorAssembly = this.GetType().AssemblyQualifiedName; // rv.ControllerName = this.GetType().FullName; // if (HttpContext != null && HttpContext.Request != null) // { // try // { // if (Request.QueryString != QueryString.Empty) // { // foreach (var key in Request.Query.Keys) // { // if (rv.FC.Keys.Contains(key) == false) // { // rv.FC.Add(key, Request.Query[key]); // } // } // } // var f = HttpContext.Request.Form; // foreach (var key in f.Keys) // { // if (rv.FC.Keys.Contains(key) == false) // { // rv.FC.Add(key, f[key]); // } // } // } // catch { } // } // //如果传递了默认值,则给vm赋值 // if (values != null) // { // foreach (var v in values) // { // PropertyHelper.SetPropertyValue(rv, v.Key, v.Value, null, false); // } // } // //如果ViewModel T继承自BaseCRUDVM<>且Id有值,那么自动调用ViewModel的GetById方法 // if (Id != null && rv is IBaseCRUDVM<TopBasePoco> cvm) // { // cvm.SetEntityById(Id); // } // //如果ViewModel T继承自IBaseBatchVM<BaseVM>,则自动为其中的ListVM和EditModel初始化数据 // if (rv is IBaseBatchVM<BaseVM> temp) // { // temp.Ids = new string[] { }; // if (Ids != null) // { // var tempids = new List<string>(); // foreach (var iid in Ids) // { // tempids.Add(iid.ToString()); // } // temp.Ids = tempids.ToArray(); // } // if (temp.ListVM != null) // { // temp.ListVM.CopyContext(rv); // temp.ListVM.Ids = Ids == null ? new List<string>() : temp.Ids.ToList(); // temp.ListVM.SearcherMode = ListVMSearchModeEnum.Batch; // temp.ListVM.NeedPage = false; // } // if (temp.LinkedVM != null) // { // temp.LinkedVM.CopyContext(rv); // } // if (temp.ListVM != null) // { // //绑定ListVM的OnAfterInitList事件,当ListVM的InitList完成时,自动将操作列移除 // temp.ListVM.OnAfterInitList += (self) => // { // self.RemoveActionColumn(); // self.RemoveAction(); // if (temp.ErrorMessage.Count > 0) // { // self.AddErrorColumn(); // } // }; // if (temp.ListVM.Searcher != null) // { // var searcher = temp.ListVM.Searcher; // searcher.CopyContext(rv); // if (passInit == false) // { // searcher.DoInit(); // } // } // } // temp.LinkedVM?.DoInit(); // //temp.ListVM?.DoSearch(); // } // //如果ViewModel是ListVM,则初始化Searcher并调用Searcher的InitVM方法 // if (rv is IBasePagedListVM<TopBasePoco, ISearcher> lvm) // { // var searcher = lvm.Searcher; // searcher.CopyContext(rv); // if (passInit == false) // { // //获取保存在Cookie中的搜索条件的值,并自动给Searcher中的对应字段赋值 // string namePre = ConfigInfo.CookiePre + "`Searcher" + "`" + rv.VMFullName + "`"; // Type searcherType = searcher.GetType(); // var pros = searcherType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance).ToList(); // pros.Add(searcherType.GetProperty("IsValid")); // searcher.DoInit(); // } // } // if (rv is IBaseImport<BaseTemplateVM> tvm) // { // var template = tvm.Template; // template.CopyContext(rv); // template.DoInit(); // } // //自动调用ViewMode的InitVM方法 // if (passInit == false) // { // rv.DoInit(); // } // return rv; //} ///// <summary> ///// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel ///// </summary> ///// <typeparam name="T">The type of the viewmodel</typeparam> ///// <param name="Id">If the viewmodel is a BaseCRUDVM, the data having this id will be fetched</param> ///// <param name="Ids">If the viewmodel is a BatchVM, the BatchVM's Ids property will be assigned</param> ///// <param name="values">use Lambda to set viewmodel's properties,use && for multiply properties, for example Wtm.CreateVM<Test>(values: x=>x.Field1=='a' && x.Field2 == 'b'); will set viewmodel's Field1 to 'a' and Field2 to 'b'</param> ///// <param name="passInit">if true, the viewmodel will not call InitVM internally</param> ///// <returns>ViewModel</returns> //[NonAction] //public T Wtm.CreateVM<T>(object Id = null, object[] Ids = null, Expression<Func<T, object>> values = null, bool passInit = false) where T : BaseVM //{ // SetValuesParser p = new SetValuesParser(); // var dir = p.Parse(values); // return CreateVM(typeof(T), Id, Ids, dir, passInit) as T; //} ///// <summary> ///// Create a ViewModel, and pass Session,cache,dc...etc to the viewmodel ///// </summary> ///// <param name="VmFullName">the fullname of the viewmodel's type</param> ///// <param name="Id">If the viewmodel is a BaseCRUDVM, the data having this id will be fetched</param> ///// <param name="Ids">If the viewmodel is a BatchVM, the BatchVM's Ids property will be assigned</param> ///// <param name="passInit">if true, the viewmodel will not call InitVM internally</param> ///// <returns>ViewModel</returns> //[NonAction] //public BaseVM CreateVM(string VmFullName, object Id = null, object[] Ids = null, bool passInit = false) //{ // return CreateVM(Type.GetType(VmFullName), Id, Ids, null, passInit); //} //#endregion #region ReInit model [NonAction] private void SetReInit(ModelStateDictionary msd, BaseVM model) { var reinit = model.GetType().GetTypeInfo().GetCustomAttributes(typeof(ReInitAttribute), false).Cast<ReInitAttribute>().SingleOrDefault(); if (ModelState.IsValid) { if (reinit != null && (reinit.ReInitMode == ReInitModes.SUCCESSONLY || reinit.ReInitMode == ReInitModes.ALWAYS)) { model.DoReInit(); } } else { if (reinit == null || (reinit.ReInitMode == ReInitModes.FAILEDONLY || reinit.ReInitMode == ReInitModes.ALWAYS)) { model.DoReInit(); } } } #endregion #region Validate model [NonAction] public Dictionary<string, string> RedoValidation(object item) { Dictionary<string, string> rv = new Dictionary<string, string>(); TryValidateModel(item); foreach (var e in ControllerContext.ModelState) { if (e.Value.ValidationState == ModelValidationState.Invalid) { rv.Add(e.Key, e.Value.Errors.Select(x => x.ErrorMessage).ToSepratedString()); } } return rv; } #endregion #region update viewmodel /// <summary> /// Set viewmodel's properties to the matching items posted by user /// </summary> /// <param name="vm">ViewModel</param> /// <param name="prefix">prefix</param> /// <returns>true if success</returns> [NonAction] public bool RedoUpdateModel(object vm, string prefix = null) { try { BaseVM bvm = vm as BaseVM; foreach (var item in bvm.FC.Keys) { PropertyHelper.SetPropertyValue(vm, item, bvm.FC[item], prefix, true); } return true; } catch { return false; } } #endregion protected JsonResult JsonMore(object data, int statusCode = StatusCodes.Status200OK, string msg = "success") { return new JsonResult(new JsonResultT<object> { Msg = msg, Code = statusCode, Data = data }); } } }
BaseApiController
csharp
ServiceStack__ServiceStack
ServiceStack.OrmLite/tests/ServiceStack.OrmLite.Tests/SchemaTests.cs
{ "start": 291, "end": 724 }
public class ____(DialectContext context) : OrmLiteProvidersTestBase(context) { [OneTimeSetUp] public void OneTimeSetup() { // sqlite doesn't support schemas if (DialectFeatures.SchemaSupport) { using (var db = OpenDbConnection()) { db.CreateSchema<TestWithSchema>(); db.CreateSchema("SchemaTest"); } } }
SchemaTests
csharp
dotnet__efcore
test/EFCore.SqlServer.HierarchyId.Tests/SqlServerHierarchyIdApiConsistencyTest.cs
{ "start": 254, "end": 802 }
public class ____( SqlServerHierarchyIdApiConsistencyTest.SqlServerHierarchyIdApiConsistencyFixture fixture) : ApiConsistencyTestBase< SqlServerHierarchyIdApiConsistencyTest.SqlServerHierarchyIdApiConsistencyFixture>(fixture) { protected override void AddServices(ServiceCollection serviceCollection) => serviceCollection.AddEntityFrameworkSqlServerHierarchyId(); protected override Assembly TargetAssembly => typeof(SqlServerHierarchyIdServiceCollectionExtensions).Assembly;
SqlServerHierarchyIdApiConsistencyTest
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Bson.Tests/Serialization/Conventions/ObjectSerializerAllowedTypesConventionTests.cs
{ "start": 964, "end": 17230 }
private class ____ { public object ObjectProp { get; set; } public object[] ArrayOfObjectProp { get; set; } public object[][] ArrayOfArrayOfObjectProp { get; set; } public TestClass RecursiveProp { get; set; } } [Fact] public void Apply_should_configure_serializer_when_building_with_constructor_single_delegate() { var allowedDelegate = (Type t) => t.Name.Contains("t"); var subject = new ObjectSerializerAllowedTypesConvention(allowedDelegate); subject.AllowDefaultFrameworkTypes.Should().BeTrue(); var memberMap = CreateMemberMap(c => c.ObjectProp); subject.Apply(memberMap); var serializer = (ObjectSerializer)memberMap.GetSerializer(); // Allowed type allowedDelegate(typeof(TestClass)).Should().BeTrue(); serializer.AllowedDeserializationTypes(typeof(TestClass)).Should().BeTrue(); serializer.AllowedSerializationTypes(typeof(TestClass)).Should().BeTrue(); // Not allowed type allowedDelegate(typeof(EnumSerializer)).Should().BeFalse(); serializer.AllowedDeserializationTypes(typeof(EnumSerializer)).Should().BeFalse(); serializer.AllowedSerializationTypes(typeof(EnumSerializer)).Should().BeFalse(); } [Fact] public void Apply_should_configure_serializer_when_building_with_constructor_double_delegate() { var allowedDeserializationDelegate = (Type t) => t.Name.Contains("t"); var allowedSerializationDelegate = (Type t) => t.Name.Contains("n"); var subject = new ObjectSerializerAllowedTypesConvention(allowedDeserializationDelegate, allowedSerializationDelegate); subject.AllowDefaultFrameworkTypes.Should().BeTrue(); var memberMap = CreateMemberMap(c => c.ObjectProp); subject.Apply(memberMap); var serializer = (ObjectSerializer)memberMap.GetSerializer(); // Deserialization allowedDeserializationDelegate(typeof(TestClass)).Should().BeTrue(); allowedDeserializationDelegate(typeof(EnumSerializer)).Should().BeFalse(); serializer.AllowedDeserializationTypes(typeof(TestClass)).Should().BeTrue(); serializer.AllowedDeserializationTypes(typeof(EnumSerializer)).Should().BeFalse(); // Serialization allowedSerializationDelegate(typeof(TestClass)).Should().BeFalse(); allowedSerializationDelegate(typeof(EnumSerializer)).Should().BeTrue(); serializer.AllowedSerializationTypes(typeof(TestClass)).Should().BeFalse(); serializer.AllowedSerializationTypes(typeof(EnumSerializer)).Should().BeTrue(); } [Fact] public void Apply_should_configure_serializer_when_building_with_constructor_single_enumerable() { var allowedTypes = new[] { typeof(TestClass) }; var subject = new ObjectSerializerAllowedTypesConvention(allowedTypes); subject.AllowDefaultFrameworkTypes.Should().BeTrue(); var memberMap = CreateMemberMap(c => c.ObjectProp); subject.Apply(memberMap); var serializer = (ObjectSerializer)memberMap.GetSerializer(); // Allowed type serializer.AllowedDeserializationTypes(typeof(TestClass)).Should().BeTrue(); serializer.AllowedSerializationTypes(typeof(TestClass)).Should().BeTrue(); // Not allowed type serializer.AllowedDeserializationTypes(typeof(EnumSerializer)).Should().BeFalse(); serializer.AllowedSerializationTypes(typeof(EnumSerializer)).Should().BeFalse(); } [Fact] public void Apply_should_configure_serializer_when_building_with_constructor_double_enumerable() { var allowedDeserializableTypes = new[] { typeof(TestClass) }; var allowedSerializableTypes = new[] { typeof(EnumSerializer) }; var subject = new ObjectSerializerAllowedTypesConvention(allowedDeserializableTypes, allowedSerializableTypes); subject.AllowDefaultFrameworkTypes.Should().BeTrue(); var memberMap = CreateMemberMap(c => c.ObjectProp); subject.Apply(memberMap); var serializer = (ObjectSerializer)memberMap.GetSerializer(); // Deserialization serializer.AllowedDeserializationTypes(typeof(TestClass)).Should().BeTrue(); serializer.AllowedDeserializationTypes(typeof(EnumSerializer)).Should().BeFalse(); // Serialization serializer.AllowedSerializationTypes(typeof(TestClass)).Should().BeFalse(); serializer.AllowedSerializationTypes(typeof(EnumSerializer)).Should().BeTrue(); } [Fact] public void Apply_should_configure_serializer_when_building_with_constructor_no_arguments() { var subject = new ObjectSerializerAllowedTypesConvention(); subject.AllowDefaultFrameworkTypes.Should().BeTrue(); var memberMap = CreateMemberMap(c => c.ObjectProp); subject.Apply(memberMap); var serializer = (ObjectSerializer)memberMap.GetSerializer(); // Type in default framework types serializer.AllowedDeserializationTypes(typeof(long)).Should().BeTrue(); serializer.AllowedSerializationTypes(typeof(long)).Should().BeTrue(); // Type not in default framework types serializer.AllowedDeserializationTypes(typeof(EnumSerializer)).Should().BeFalse(); serializer.AllowedSerializationTypes(typeof(EnumSerializer)).Should().BeFalse(); } [Fact] public void Apply_should_configure_serializer_when_building_with_constructor_assemblies() { var subject = new ObjectSerializerAllowedTypesConvention(Assembly.GetAssembly(typeof(TestClass)), Assembly.GetAssembly(typeof(System.Linq.Enumerable))); subject.AllowDefaultFrameworkTypes.Should().BeTrue(); var memberMap = CreateMemberMap(c => c.ObjectProp); subject.Apply(memberMap); var serializer = (ObjectSerializer)memberMap.GetSerializer(); // Types in input assemblies serializer.AllowedDeserializationTypes(typeof(TestClass)).Should().BeTrue(); serializer.AllowedSerializationTypes(typeof(TestClass)).Should().BeTrue(); serializer.AllowedDeserializationTypes(typeof(System.Linq.Enumerable)).Should().BeTrue(); serializer.AllowedSerializationTypes(typeof(System.Linq.Enumerable)).Should().BeTrue(); // Type not in input assemblies serializer.AllowedDeserializationTypes(typeof(EnumSerializer)).Should().BeFalse(); serializer.AllowedSerializationTypes(typeof(EnumSerializer)).Should().BeFalse(); } [Fact] public void Apply_should_configure_serializer_when_building_without_default_types() { var subject = new ObjectSerializerAllowedTypesConvention { AllowDefaultFrameworkTypes = false }; subject.AllowDefaultFrameworkTypes.Should().BeFalse(); var memberMap = CreateMemberMap(c => c.ObjectProp); subject.Apply(memberMap); var serializer = (ObjectSerializer)memberMap.GetSerializer(); // Default framework type serializer.AllowedDeserializationTypes(typeof(long)).Should().BeFalse(); serializer.AllowedSerializationTypes(typeof(long)).Should().BeFalse(); } [Fact] public void Apply_should_configure_serializer_when_building_with_default_types() { var subject = new ObjectSerializerAllowedTypesConvention { AllowDefaultFrameworkTypes = true }; subject.AllowDefaultFrameworkTypes.Should().BeTrue(); var memberMap = CreateMemberMap(c => c.ObjectProp); subject.Apply(memberMap); var serializer = (ObjectSerializer)memberMap.GetSerializer(); // Default framework type serializer.AllowedDeserializationTypes(typeof(long)).Should().BeTrue(); serializer.AllowedSerializationTypes(typeof(long)).Should().BeTrue(); } [Fact] public void Apply_should_configure_serializer_when_member_is_a_collection() { var subject = new ObjectSerializerAllowedTypesConvention(Assembly.GetExecutingAssembly()); var memberMap = CreateMemberMap(c => c.ArrayOfObjectProp); subject.Apply(memberMap); var serializer = (IChildSerializerConfigurable)memberMap.GetSerializer(); var childSerializer = (ObjectSerializer)serializer.ChildSerializer; // Type in assembly childSerializer.AllowedDeserializationTypes(typeof(TestClass)).Should().BeTrue(); childSerializer.AllowedSerializationTypes(typeof(TestClass)).Should().BeTrue(); // Type not in assembly childSerializer.AllowedDeserializationTypes(typeof(EnumSerializer)).Should().BeFalse(); childSerializer.AllowedSerializationTypes(typeof(EnumSerializer)).Should().BeFalse(); } [Fact] public void Apply_should_configure_serializer_when_member_is_a_nested_collection() { var subject = new ObjectSerializerAllowedTypesConvention(Assembly.GetExecutingAssembly()); var memberMap = CreateMemberMap(c => c.ArrayOfArrayOfObjectProp); subject.Apply(memberMap); var serializer = (IChildSerializerConfigurable)memberMap.GetSerializer(); var childSerializer = (ObjectSerializer)((IChildSerializerConfigurable)serializer.ChildSerializer).ChildSerializer; // Type in assembly childSerializer.AllowedDeserializationTypes(typeof(TestClass)).Should().BeTrue(); childSerializer.AllowedSerializationTypes(typeof(TestClass)).Should().BeTrue(); // Type not in assembly childSerializer.AllowedDeserializationTypes(typeof(EnumSerializer)).Should().BeFalse(); childSerializer.AllowedSerializationTypes(typeof(EnumSerializer)).Should().BeFalse(); } [Fact] public void Apply_should_configure_serializer_when_using_static_AllowAllTypes() { var subject = ObjectSerializerAllowedTypesConvention.AllowAllTypes; subject.AllowDefaultFrameworkTypes.Should().BeTrue(); var memberMap = CreateMemberMap(c => c.ObjectProp); subject.Apply(memberMap); var serializer = (ObjectSerializer)memberMap.GetSerializer(); serializer.AllowedDeserializationTypes(typeof(TestClass)).Should().BeTrue(); serializer.AllowedSerializationTypes(typeof(TestClass)).Should().BeTrue(); serializer.AllowedDeserializationTypes(typeof(long)).Should().BeTrue(); serializer.AllowedSerializationTypes(typeof(long)).Should().BeTrue(); serializer.AllowedDeserializationTypes(typeof(EnumSerializer)).Should().BeTrue(); serializer.AllowedSerializationTypes(typeof(EnumSerializer)).Should().BeTrue(); } [Fact] public void Apply_should_configure_serializer_when_using_static_AllowNoTypes() { var subject = ObjectSerializerAllowedTypesConvention.AllowNoTypes; subject.AllowDefaultFrameworkTypes.Should().BeFalse(); var memberMap = CreateMemberMap(c => c.ObjectProp); subject.Apply(memberMap); var serializer = (ObjectSerializer)memberMap.GetSerializer(); serializer.AllowedDeserializationTypes(typeof(TestClass)).Should().BeFalse(); serializer.AllowedSerializationTypes(typeof(TestClass)).Should().BeFalse(); serializer.AllowedDeserializationTypes(typeof(long)).Should().BeFalse(); serializer.AllowedSerializationTypes(typeof(long)).Should().BeFalse(); serializer.AllowedDeserializationTypes(typeof(EnumSerializer)).Should().BeFalse(); serializer.AllowedSerializationTypes(typeof(EnumSerializer)).Should().BeFalse(); } [Fact] public void Apply_should_configure_serializer_when_using_static_AllowOnlyDefaultFrameworkTypes() { var subject = ObjectSerializerAllowedTypesConvention.AllowOnlyDefaultFrameworkTypes; subject.AllowDefaultFrameworkTypes.Should().BeTrue(); var memberMap = CreateMemberMap(c => c.ObjectProp); subject.Apply(memberMap); var serializer = (ObjectSerializer)memberMap.GetSerializer(); serializer.AllowedDeserializationTypes(typeof(TestClass)).Should().BeFalse(); serializer.AllowedSerializationTypes(typeof(TestClass)).Should().BeFalse(); serializer.AllowedDeserializationTypes(typeof(long)).Should().BeTrue(); serializer.AllowedSerializationTypes(typeof(long)).Should().BeTrue(); serializer.AllowedDeserializationTypes(typeof(EnumSerializer)).Should().BeFalse(); serializer.AllowedSerializationTypes(typeof(EnumSerializer)).Should().BeFalse(); } [Fact] public void Apply_should_configure_serializer_when_using_static_AllowAllCallingAssemblyAndDefaultFrameworkTypes() { var subject = ObjectSerializerAllowedTypesConvention.GetAllowAllCallingAssemblyAndDefaultFrameworkTypesConvention(); subject.AllowDefaultFrameworkTypes.Should().BeTrue(); var memberMap = CreateMemberMap(c => c.ObjectProp); subject.Apply(memberMap); var serializer = (ObjectSerializer)memberMap.GetSerializer(); serializer.AllowedDeserializationTypes(typeof(TestClass)).Should().BeTrue(); serializer.AllowedSerializationTypes(typeof(TestClass)).Should().BeTrue(); serializer.AllowedDeserializationTypes(typeof(long)).Should().BeTrue(); serializer.AllowedSerializationTypes(typeof(long)).Should().BeTrue(); serializer.AllowedDeserializationTypes(typeof(EnumSerializer)).Should().BeFalse(); serializer.AllowedSerializationTypes(typeof(EnumSerializer)).Should().BeFalse(); } [Fact] public void Convention_should_be_applied_during_automapping() { var conventionName = Guid.NewGuid().ToString(); var subject = new ObjectSerializerAllowedTypesConvention(Assembly.GetExecutingAssembly()); ConventionRegistry.Register(conventionName, new ConventionPack {subject}, t => t == typeof(TestClass)); var classMap = new BsonClassMap<TestClass>(cm => cm.AutoMap()); var memberMap = classMap.GetMemberMap("ObjectProp"); var serializer = memberMap.GetSerializer(); serializer.Should().BeOfType<ObjectSerializer>(); var typedSerializer = (ObjectSerializer)serializer; // Type in assembly typedSerializer.AllowedDeserializationTypes(typeof(TestClass)).Should().BeTrue(); typedSerializer.AllowedSerializationTypes(typeof(TestClass)).Should().BeTrue(); // Type not in assembly typedSerializer.AllowedDeserializationTypes(typeof(EnumSerializer)).Should().BeFalse(); typedSerializer.AllowedSerializationTypes(typeof(EnumSerializer)).Should().BeFalse(); ConventionRegistry.Remove(conventionName); } [Fact] public void Convention_should_work_with_recursive_type() { var pack = new ConventionPack { new ObjectSerializerAllowedTypesConvention() }; ConventionRegistry.Register("objectRecursive", pack, t => t == typeof(TestClass)); _ = new BsonClassMap<TestClass>(cm => cm.AutoMap()).Freeze(); ConventionRegistry.Remove("enumRecursive"); } // private methods private static BsonMemberMap CreateMemberMap<TMember>(Expression<Func<TestClass, TMember>> member) { var classMap = new BsonClassMap<TestClass>(); return classMap.MapMember(member); } } }
TestClass
csharp
unoplatform__uno
src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml/Thickness.cs
{ "start": 252, "end": 645 }
public partial struct ____ { // Forced skipping of method Microsoft.UI.Xaml.Thickness.Thickness() // Skipping already declared field Microsoft.UI.Xaml.Thickness.Left // Skipping already declared field Microsoft.UI.Xaml.Thickness.Top // Skipping already declared field Microsoft.UI.Xaml.Thickness.Right // Skipping already declared field Microsoft.UI.Xaml.Thickness.Bottom } }
Thickness
csharp
dotnet__efcore
test/EFCore.Specification.Tests/JsonTypesTestBase.cs
{ "start": 15875, "end": 16420 }
protected class ____ { public Enum32 Enum32 { get; set; } } [ConditionalTheory, InlineData((long)Enum64.Min, """{"Prop":-9223372036854775808}"""), InlineData((long)Enum64.Max, """{"Prop":9223372036854775807}"""), InlineData((long)Enum64.Default, """{"Prop":0}"""), InlineData((long)Enum64.One, """{"Prop":1}""")] public virtual Task Can_read_write_long_enum_JSON_values(Enum64 value, string json) => Can_read_and_write_JSON_value<Enum64Type, Enum64>(nameof(Enum64Type.Enum64), value, json);
Enum32Type
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.UI.Composition/ExpressionAnimation.cs
{ "start": 297, "end": 1446 }
public partial class ____ : global::Windows.UI.Composition.CompositionAnimation { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ internal ExpressionAnimation() { } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public string Expression { get { throw new global::System.NotImplementedException("The member string ExpressionAnimation.Expression is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20ExpressionAnimation.Expression"); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.UI.Composition.ExpressionAnimation", "string ExpressionAnimation.Expression"); } } #endif // Forced skipping of method Windows.UI.Composition.ExpressionAnimation.Expression.get // Forced skipping of method Windows.UI.Composition.ExpressionAnimation.Expression.set } }
ExpressionAnimation
csharp
dotnet__aspire
src/Aspire.Dashboard/Otlp/Model/OtlpSpan.cs
{ "start": 9843, "end": 10023 }
public record ____ FieldValues(string? Value1, string? Value2 = null) { public static implicit operator FieldValues(string? value) => new FieldValues(value); } }
struct
csharp
pythonnet__pythonnet
src/testing/indexertest.cs
{ "start": 4657, "end": 4928 }
public class ____ : IndexerBase { public DoubleIndexerTest() : base() { } public string this[double index] { get { return GetValue(index); } set { t[index] = value; } } }
DoubleIndexerTest
csharp
ServiceStack__ServiceStack
ServiceStack.OrmLite/tests/ServiceStack.OrmLite.Oracle.Tests/OracleParamTests.cs
{ "start": 45125, "end": 45264 }
public class ____ { public int Id { get; set; } public byte[] Data { get; set; } }
ParamByteBo
csharp
ChilliCream__graphql-platform
src/HotChocolate/Fusion-vnext/test/Fusion.AspNetCore.Tests/SharedPathTests.cs
{ "start": 19088, "end": 19184 }
public class ____ { public string Schema3 => "schema3"; } } }
Viewer
csharp
dotnet__aspnetcore
src/Grpc/Interop/test/InteropTests/Helpers/ClientProcess.cs
{ "start": 280, "end": 2663 }
public class ____ : IDisposable { private readonly Process _process; private readonly ProcessEx _processEx; private readonly TaskCompletionSource _startTcs; private readonly StringBuilder _output; private readonly object _outputLock = new object(); public ClientProcess(ITestOutputHelper output, string path, string serverPort, string testCase) { _output = new StringBuilder(); _process = new Process(); _process.StartInfo = new ProcessStartInfo { RedirectStandardOutput = true, RedirectStandardError = true, FileName = "dotnet", Arguments = @$"{path} --use_tls false --server_port {serverPort} --client_type httpclient --test_case {testCase}" }; _process.EnableRaisingEvents = true; _process.OutputDataReceived += Process_OutputDataReceived; _process.ErrorDataReceived += Process_ErrorDataReceived; output.WriteLine($"Starting process: {ProcessDebugHelper.GetDebugCommand(_process.StartInfo)}"); _process.Start(); _processEx = new ProcessEx(output, _process, timeout: Timeout.InfiniteTimeSpan); _startTcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); } public Task WaitForReadyAsync() => _startTcs.Task; public Task WaitForExitAsync() => _processEx.Exited; public int ExitCode => _process.ExitCode; public bool IsReady => _startTcs.Task.IsCompletedSuccessfully; public string GetOutput() { lock (_outputLock) { return _output.ToString(); } } private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e) { var data = e.Data; if (data != null) { if (data.Contains("Application started.")) { _startTcs.TrySetResult(); } lock (_outputLock) { _output.AppendLine(data); } } } private void Process_ErrorDataReceived(object sender, DataReceivedEventArgs e) { var data = e.Data; if (data != null) { lock (_outputLock) { _output.AppendLine("ERROR: " + data); } } } public void Dispose() { _processEx.Dispose(); } }
ClientProcess
csharp
dotnetcore__Util
test/Util.Domain.Tests/Compare/KeyListComparatorTest.cs
{ "start": 209, "end": 3157 }
public class ____ { /// <summary> /// 键列表比较器 /// </summary> private readonly KeyListComparator<Guid> _comparator; /// <summary> /// 测试初始化 /// </summary> public KeyListComparatorTest() { _comparator = new KeyListComparator<Guid>(); } /// <summary> /// 测试列表比较 - 验证集合为空 /// </summary> [Fact] public void TestCompare_Validate() { var list = new List<Guid>(); AssertHelper.Throws<ArgumentNullException>( () => { _comparator.Compare( null, list ); } ); AssertHelper.Throws<ArgumentNullException>( () => { _comparator.Compare( list, null ); } ); AssertHelper.Throws<ArgumentNullException>( () => { list.Compare( null ); } ); } /// <summary> /// 测试列表比较 - 获取创建列表 /// </summary> [Fact] public void TestCompare_CreateList() { var id = Guid.NewGuid(); var newList = new List<Guid> { id }; var result = _comparator.Compare( newList, new List<Guid>() ); Assert.Single( result.CreateList ); Assert.Equal( id, result.CreateList[0] ); } /// <summary> /// 测试列表比较 - 获取删除列表 /// </summary> [Fact] public void TestCompare_DeleteList() { var id = Guid.NewGuid(); var originalList = new List<Guid> { id }; var result = _comparator.Compare( new List<Guid>(), originalList ); Assert.Empty( result.CreateList ); Assert.Single( result.DeleteList ); Assert.Equal( id, result.DeleteList[0] ); } /// <summary> /// 测试列表比较 - 获取更新列表 /// </summary> [Fact] public void TestCompare_UpdateList() { var id = Guid.NewGuid(); var newList = new List<Guid> { id }; var originalList = new List<Guid> { id }; var result = _comparator.Compare( newList, originalList ); Assert.Empty( result.CreateList ); Assert.Empty( result.DeleteList ); Assert.Single( result.UpdateList ); Assert.Equal( id, result.UpdateList[0] ); } /// <summary> /// 测试列表比较 /// </summary> [Fact] public void TestCompare() { var id = Guid.NewGuid(); var id2 = Guid.NewGuid(); var id3 = Guid.NewGuid(); var id4 = Guid.NewGuid(); var newList = new List<Guid> { id,id2,id3 }; var originalList = new List<Guid> { id2,id3,id4 }; var result = newList.Compare( originalList ); Assert.Single( result.CreateList ); Assert.Equal( id, result.CreateList[0] ); Assert.Single( result.DeleteList ); Assert.Equal( id4, result.DeleteList[0] ); Assert.Equal( 2, result.UpdateList.Count ); Assert.Equal( id2, result.UpdateList[0] ); Assert.Equal( id3, result.UpdateList[1] ); } }
KeyListComparatorTest
csharp
dotnet__BenchmarkDotNet
src/BenchmarkDotNet/Exporters/FullNameProvider.cs
{ "start": 337, "end": 7102 }
public static class ____ { private static readonly IReadOnlyDictionary<Type, string> Aliases = new Dictionary<Type, string> { { typeof(byte), "byte" }, { typeof(sbyte), "sbyte" }, { typeof(short), "short" }, { typeof(ushort), "ushort" }, { typeof(int), "int" }, { typeof(uint), "uint" }, { typeof(long), "long" }, { typeof(ulong), "ulong" }, { typeof(float), "float" }, { typeof(double), "double" }, { typeof(decimal), "decimal" }, { typeof(object), "object" }, { typeof(bool), "bool" }, { typeof(char), "char" }, { typeof(string), "string" }, { typeof(byte?), "byte?" }, { typeof(sbyte?), "sbyte?" }, { typeof(short?), "short?" }, { typeof(ushort?), "ushort?" }, { typeof(int?), "int?" }, { typeof(uint?), "uint?" }, { typeof(long?), "long?" }, { typeof(ulong?), "ulong?" }, { typeof(float?), "float?" }, { typeof(double?), "double?" }, { typeof(decimal?), "decimal?" }, { typeof(bool?), "bool?" }, { typeof(char?), "char?" } }; [PublicAPI("used by the dotnet/performance repository")] public static string GetBenchmarkName(BenchmarkCase benchmarkCase) { var type = benchmarkCase.Descriptor.Type; // we can't just use type.FullName because we need sth different for generics (it reports SimpleGeneric`1[[System.Int32, mscorlib, Version=4.0.0.0) var name = new StringBuilder(); if (!string.IsNullOrEmpty(type.Namespace)) name.Append(type.Namespace).Append('.'); name.Append(GetNestedTypes(type)); name.Append(GetTypeName(type)).Append('.'); name.Append(GetMethodName(benchmarkCase)); return name.ToString(); } private static string GetNestedTypes(Type type) { string nestedTypes = ""; Type child = type, parent = type.DeclaringType; while (child.IsNested && parent != null) { nestedTypes = parent.Name + "+" + nestedTypes; child = parent; parent = parent.DeclaringType; } return nestedTypes; } internal static string GetTypeName(Type type) { if (!type.IsGenericType) return type.Name; string mainName = type.Name.Substring(0, type.Name.IndexOf('`')); string args = string.Join(", ", type.GetGenericArguments().Select(GetTypeName).ToArray()); return $"{mainName}<{args}>"; } internal static string GetMethodName(BenchmarkCase benchmarkCase) { var name = new StringBuilder(benchmarkCase.Descriptor.WorkloadMethod.Name); if (benchmarkCase.HasParameters) name.Append(GetBenchmarkParameters(benchmarkCase.Descriptor.WorkloadMethod, benchmarkCase.Parameters)); return name.ToString(); } private static string GetBenchmarkParameters(MethodInfo method, ParameterInstances benchmarkParameters) { var methodArguments = method.GetParameters(); var benchmarkParams = benchmarkParameters.Items.Where(parameter => !parameter.IsArgument).ToArray(); var parametersBuilder = new StringBuilder(methodArguments.Length * 20).Append('('); for (int i = 0; i < methodArguments.Length; i++) { if (i > 0) parametersBuilder.Append(", "); parametersBuilder.Append(methodArguments[i].Name).Append(':').Append(' '); parametersBuilder.Append(GetArgument(benchmarkParameters.GetArgument(methodArguments[i].Name).Value, methodArguments[i].ParameterType)); } for (int i = 0; i < benchmarkParams.Length; i++) { var parameter = benchmarkParams[i]; if (methodArguments.Length > 0 || i > 0) parametersBuilder.Append(", "); parametersBuilder.Append(parameter.Name).Append(':').Append(' '); parametersBuilder.Append(GetArgument(parameter.Value, parameter.Definition.ParameterType)); } return parametersBuilder.Append(')').ToString(); } private static string GetArgument(object argumentValue, Type argumentType) { switch (argumentValue) { case null: return "null"; case IParam iparam: return GetArgument(iparam.Value, argumentType); case object[] array when array.Length == 1: return GetArgument(array[0], argumentType); case string text: return text.EscapeSpecialCharacters(true); case char character: return character.EscapeSpecialCharacter(true); case DateTime time: return time.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"); case Type type: return $"typeof({GetTypeArgumentName(type)})"; } if (argumentType != null && argumentType.IsArray) return GetArray((IEnumerable)argumentValue); return argumentValue.ToString(); } // it's not generic so I can't simply use .Skip and all other LINQ goodness private static string GetArray(IEnumerable collection) { var buffer = new StringBuilder().Append('['); int index = 0; foreach (var item in collection) { if (index > 0) buffer.Append(", "); if (index > 4) { buffer.Append("..."); // [0, 1, 2, 3, 4, ...] break; } buffer.Append(GetArgument(item, item?.GetType())); ++index; } buffer.Append(']'); return buffer.ToString(); } private static string GetTypeArgumentName(Type type) { if (Aliases.TryGetValue(type, out string alias)) return alias; if (type.IsNullable()) return $"{GetTypeArgumentName(Nullable.GetUnderlyingType(type))}?"; if (!string.IsNullOrEmpty(type.Namespace)) return $"{type.Namespace}.{GetTypeName(type)}"; return GetTypeName(type); } } }
FullNameProvider
csharp
Humanizr__Humanizer
src/Humanizer/Truncation/DynamicLengthAndPreserveWordsTruncator.cs
{ "start": 353, "end": 3789 }
class ____ : ITruncator { [return: NotNullIfNotNull(nameof(value))] public string? Truncate(string? value, int length, string? truncationString, TruncateFrom truncateFrom = TruncateFrom.Right) { if (value == null) { return null; } if (value.Length == 0) { return value; } // For this scenario we expect a single-character delimiter. // If truncation string is null, treat it as empty. truncationString ??= string.Empty; // If the delimiter itself is longer than the allowed length, fall back to a basic substring. if (truncationString.Length > length) { return truncateFrom == TruncateFrom.Right ? value[..length] : value[^length..]; } // If the whole string fits, return it. if (value.Length <= length) { return value; } return truncateFrom == TruncateFrom.Right ? TruncateFromRight(value, length, truncationString) : TruncateFromLeft(value, length, truncationString); } static string TruncateFromLeft(string value, int length, string truncationString) { // For left truncation, the final output is: delimiter + substring. // Determine how many characters (after the delimiter) are allowed. var allowedContentLength = length - truncationString.Length; if (allowedContentLength <= 0) { return truncationString; } // We'll scan backward from the end of the string for a whitespace boundary // such that the substring (after trimming) is no longer than allowedContentLength. var candidateStart = value.Length; for (var i = value.Length - 1; i >= 0; i--) { if (char.IsWhiteSpace(value[i])) { candidateStart = i + 1; var candidateLength = value.Length - candidateStart; if (candidateLength <= allowedContentLength) { break; } } } var candidate = value[candidateStart..].TrimStart(); // If the candidate word is too long (i.e. would be partial) or empty, return just the delimiter. if (candidate.Length > allowedContentLength || candidate.Length == 0) { return truncationString; } return truncationString + candidate; } static string TruncateFromRight(string value, int length, string truncationString) { var effectiveLength = length - truncationString.Length; if (effectiveLength <= 0) { return truncationString; } // If the cutoff falls in the middle of a word, backtrack to the last space. if (effectiveLength < value.Length && !char.IsWhiteSpace(value[effectiveLength])) { var lastSpace = value.LastIndexOf(' ', effectiveLength); if (lastSpace > 0) { effectiveLength = lastSpace; } else { return truncationString; } } var prefix = value[..effectiveLength].TrimEnd(); if (prefix.Length == 0) { return truncationString; } return prefix + truncationString; } }
DynamicLengthAndPreserveWordsTruncator
csharp
microsoft__PowerToys
src/modules/registrypreview/RegistryPreviewUILib/Controls/HexBox/DataFormat.cs
{ "start": 588, "end": 854 }
public enum ____ { /// <summary> /// Display the data in decimal format. /// </summary> Decimal, /// <summary> /// Display the data in hexadecimal format. /// </summary> Hexadecimal, } }
DataFormat
csharp
ServiceStack__ServiceStack
ServiceStack.Text/src/ServiceStack.Text/Diagnostics.cs
{ "start": 188, "end": 494 }
public class ____ { private static readonly Diagnostics Instance = new(); private Diagnostics(){} private bool includeStackTrace; public static bool IncludeStackTrace { get => Instance.includeStackTrace; set => Instance.includeStackTrace = value; }
Diagnostics
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/src/Types/Types/Descriptors/Contracts/IObjectTypeDescriptor~1.cs
{ "start": 2645, "end": 2820 }
interface ____.</typeparam> IObjectTypeDescriptor<TRuntimeType> Implements<TInterface>() where TInterface : InterfaceType; /// <summary> /// Specifies an
type
csharp
dotnet__maui
src/Controls/tests/TestCases.HostApp/Issues/Issue2004.cs
{ "start": 3196, "end": 6321 }
public class ____ : ContentPage { public AddressListView() { ListView listView = new ListView() { RowHeight = 75 }; listView.SetBinding(ListView.ItemsSourceProperty, "UnitList"); listView.ItemTemplate = new DataTemplate(() => { ViewCell cell = new ViewCell(); cell.View = new AddressListItemView(); return cell; }); Content = new StackLayout() { Children = { new StackLayout() { Orientation = StackOrientation.Horizontal, Padding = 4, Children = { new StackLayout() { Children = { new Label() { Text = "SortText", HorizontalOptions = LayoutOptions.Center } } } } }, listView } }; BindingContext = this; } protected override void OnAppearing() { base.OnAppearing(); UnitList = null; NotifyPropertyChanged(() => UnitList); SelectedAddress = null; LoadAddresses(); } string _selectedAddress; public string SelectedAddress { get => _selectedAddress; set { if (_selectedAddress != value) { _selectedAddress = value; NotifyPropertyChanged(() => SelectedAddress); if (SelectedAddress != null) { LoadUnitsByAddress(_selectedAddress); NotifyPropertyChanged(() => UnitList); } } } } List<string> _streeAddresses; private List<string> _unitList; public List<string> StreetAddresses { get { return _streeAddresses; } set { _streeAddresses = value; NotifyPropertyChanged(); } } public void LoadAddresses() { StreetAddresses = Enumerable.Range(1, 10).Select(x => x.ToString()).ToList(); SelectedAddress = StreetAddresses.First(); } public void LoadUnitsByAddress(string address) { if (string.IsNullOrEmpty(address)) { UnitList?.Clear(); return; } UnitList = Enumerable.Range(1, 10).Select(x => x.ToString()).ToList(); } public List<string> UnitList { get { return _unitList; } set { _unitList = value; } } public virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = null) { OnPropertyChanged(propertyName); } protected virtual void NotifyPropertyChanged<T>(Expression<Func<T>> propertyExpression) { string propertyName = GetPropertyName(propertyExpression); OnPropertyChanged(propertyName); } private string GetPropertyName<T>(Expression<Func<T>> propertyExpression) { if (propertyExpression == null) { throw new ArgumentNullException("propertyExpression"); } if (propertyExpression.Body.NodeType != ExpressionType.MemberAccess) { throw new ArgumentException("Should be a member access lambda expression", "propertyExpression"); } var memberExpression = (MemberExpression)propertyExpression.Body; return memberExpression.Member.Name; } }
AddressListView
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp.ZeroCore.NHibernate/Zero/FluentMigrator/Migrations/_20150811_02_CreateAbpAuditLogsTable.cs
{ "start": 140, "end": 1058 }
public class ____ : AutoReversingMigration { public override void Up() { Create.Table("AbpAuditLogs") .WithIdAsInt64() .WithTenantIdAsNullable() .WithNullableUserId() .WithColumn("ServiceName").AsString(256).Nullable() .WithColumn("MethodName").AsString(256).Nullable() .WithColumn("Parameters").AsString(1024).Nullable() .WithColumn("ExecutionTime").AsDateTime().NotNullable() .WithColumn("ExecutionDuration").AsInt32().NotNullable() .WithColumn("ClientIpAddress").AsString(64).Nullable() .WithColumn("ClientName").AsString(128).Nullable() .WithColumn("BrowserInfo").AsString(256).Nullable() .WithColumn("Exception").AsString(2000).Nullable(); } } }
_20150811_02_CreateAbpAuditLogsTable
csharp
bitwarden__server
src/Infrastructure.EntityFramework/Models/CollectionGroup.cs
{ "start": 167, "end": 333 }
public class ____ : Core.Entities.CollectionGroup { public virtual Collection Collection { get; set; } public virtual Group Group { get; set; } }
CollectionGroup
csharp
dotnet__maui
src/Controls/tests/SourceGen.UnitTests/InitializeComponent/CircularReferenceExtension.cs
{ "start": 286, "end": 1263 }
public class ____ : SourceGenXamlInitializeComponentTestBase { [Fact] public async Task CircularReferenceWithCustomViewExpandableContent() { // Test based on https://github.com/dotnet/maui/issues/32623 // // This test reproduces the infinite loop that occurs when x:Reference is used // inside nested DataTemplates within a custom control's property, creating a // context chain where the buggy code (line 524: context.ParentContext) would // repeatedly assign the same parent context instead of walking up the chain. var expanderViewXaml = """ <?xml version="1.0" encoding="UTF-8"?> <ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Test.ExpanderView"> </ContentView> """; var expanderViewCode = """ using System; using Microsoft.Maui.Controls; using Microsoft.Maui.Controls.Xaml; namespace Test; [XamlProcessing(XamlInflator.SourceGen)]
CircularReferenceExtension
csharp
jellyfin__jellyfin
MediaBrowser.Controller/Sorting/IBaseItemComparer.cs
{ "start": 224, "end": 410 }
public interface ____ : IComparer<BaseItem?> { /// <summary> /// Gets the comparer type. /// </summary> ItemSortBy Type { get; } } }
IBaseItemComparer
csharp
ChilliCream__graphql-platform
src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs
{ "start": 1279033, "end": 1279583 }
public partial interface ____ { public global::System.String ReferenceId { get; } public global::ChilliCream.Nitro.CommandLine.Cloud.Client.ICreateEnvironmentCommandMutation_PushWorkspaceChanges_Changes_Error? Error { get; } public global::ChilliCream.Nitro.CommandLine.Cloud.Client.ICreateEnvironmentCommandMutation_PushWorkspaceChanges_Changes_Result? Result { get; } } [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
ICreateEnvironmentCommandMutation_PushWorkspaceChanges_Changes
csharp
abpframework__abp
modules/blogging/src/Volo.Blogging.Web/BloggingUrlOptions.cs
{ "start": 930, "end": 1297 }
public class ____ { /// <summary> /// Determines whether to enable single blog mode by removing the blog name from the routing. /// When enabled, only a single blog is allowed within the module. /// </summary> public bool Enabled { get; set; } public string BlogName { get; set; } } }
SingleBlogModeOptions
csharp
duplicati__duplicati
Duplicati/WebserverCore/Abstractions/ISettingsService.cs
{ "start": 1228, "end": 2615 }
public interface ____ { /// <summary> /// Gets the current server settings. /// </summary> /// <returns>The current server settings.</returns> ServerSettings GetSettings(); /// <summary> /// Gets the current server settings with sensitive information masked. /// </summary> /// <returns>A dictionary of settings with sensitive information masked.</returns> Dictionary<string, string> GetSettingsMasked(); /// <summary> /// Patches the server settings with the provided values, ignoring any sensitive information. /// </summary> /// <param name="values">A dictionary of values to patch the settings with.</param> void PatchSettingsMasked(Dictionary<string, object?>? values); /// <summary> /// Gets a specific setting value, masking sensitive information if necessary. /// </summary> /// <param name="key">The key of the setting to retrieve.</param> /// <returns>The value of the setting, or null if not found.</returns> string? GetSettingMasked(string key); /// <summary> /// Patches a specific setting with a masked value, ignoring any sensitive information. /// </summary> /// <param name="key">The key of the setting to patch.</param> /// <param name="value">The masked value to set for the setting.</param> void PatchSettingMasked(string key, string value); }
ISettingsService
csharp
bitwarden__server
src/Infrastructure.EntityFramework/Billing/Models/OrganizationInstallation.cs
{ "start": 288, "end": 512 }
public class ____ : Core.Billing.Organizations.Entities.OrganizationInstallation { public virtual Installation Installation { get; set; } public virtual Organization Organization { get; set; } }
OrganizationInstallation
csharp
microsoft__semantic-kernel
dotnet/src/VectorData/Milvus/MilvusMemoryStore.cs
{ "start": 15342, "end": 17475 }
record ____ records) { var metadata = record.Metadata; if (idString.Length > 0) { idString.Append(','); } idString.Append('"').Append(metadata.Id).Append('"'); isReferenceData.Add(metadata.IsReference); externalSourceNameData.Add(metadata.ExternalSourceName); idData.Add(record.Metadata.Id); descriptionData.Add(metadata.Description); textData.Add(metadata.Text); additionalMetadataData.Add(metadata.AdditionalMetadata); embeddingData.Add(record.Embedding); keyData.Add(record.Key); timestampData.Add(record.Timestamp?.ToString(CultureInfo.InvariantCulture) ?? string.Empty); } MilvusCollection collection = this.Client.GetCollection(collectionName); FieldData[] fieldData = [ FieldData.Create(IdFieldName, idData), FieldData.CreateFloatVector(EmbeddingFieldName, embeddingData), FieldData.Create(IsReferenceFieldName, isReferenceData, isDynamic: true), FieldData.Create(ExternalSourceNameFieldName, externalSourceNameData, isDynamic: true), FieldData.Create(DescriptionFieldName, descriptionData, isDynamic: true), FieldData.Create(TextFieldName, textData, isDynamic: true), FieldData.Create(AdditionalMetadataFieldName, additionalMetadataData, isDynamic: true), FieldData.Create(KeyFieldName, keyData, isDynamic: true), FieldData.Create(TimestampFieldName, timestampData, isDynamic: true) ]; MutationResult result = await collection.UpsertAsync(fieldData, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var id in result.Ids.StringIds!) { yield return id; } } /// <inheritdoc /> public async Task<MemoryRecord?> GetAsync( string collectionName, string key, bool withEmbedding = false, CancellationToken cancellationToken = default) { await foreach (MemoryRecord
in
csharp
MonoGame__MonoGame
MonoGame.Framework/Platform/Graphics/OpenGL.cs
{ "start": 3144, "end": 3259 }
internal enum ____ { Renderbuffer = 0x8D41, RenderbufferExt = 0x8D41, }
RenderbufferTarget
csharp
unoplatform__uno
src/Uno.UWP/ApplicationModel/Contacts/ContactPicker.Interop.wasm.cs
{ "start": 187, "end": 526 }
partial class ____ { private const string JsType = "globalThis.Windows.ApplicationModel.Contacts.ContactPicker"; [JSImport($"{JsType}.isSupported")] internal static partial bool IsSupported(); [JSImport($"{JsType}.pickContacts")] internal static partial Task<string> PickContactsAsync(bool multiple); } } }
NativeMethods
csharp
PrismLibrary__Prism
src/Prism.Core/Navigation/Regions/RegionViewRegistryExtensions.cs
{ "start": 216, "end": 1628 }
public static class ____ { /// <summary> /// Registers a delegate that can be used to retrieve the content associated with a region name. /// </summary> /// <param name="viewRegistry">The <see cref="IRegionViewRegistry"/> instance.</param> /// <param name="regionName">Region name to which the <paramref name="getContentDelegate"/> will be registered.</param> /// <param name="getContentDelegate">Delegate used to retrieve the content associated with the <paramref name="regionName"/>.</param> public static void RegisterViewWithRegion(this IRegionViewRegistry viewRegistry, string regionName, Func<object> getContentDelegate) => viewRegistry.RegisterViewWithRegion(regionName, _ => getContentDelegate()); /// <summary> /// Returns the contents associated with a region name. /// </summary> /// <param name="viewRegistry">The current <see cref="IRegionViewRegistry"/> instance.</param> /// <param name="regionName">Region name for which contents are requested.</param> /// <returns>Collection of contents associated with the <paramref name="regionName"/>.</returns> public static IEnumerable<object> GetContents(this IRegionViewRegistry viewRegistry, string regionName) => viewRegistry.GetContents(regionName, ContainerLocator.Container); } }
RegionViewRegistryExtensions
csharp
bitwarden__server
src/Core/Settings/GlobalSettings.cs
{ "start": 26694, "end": 26914 }
public class ____ { public int CiphersLimit { get; set; } public int CollectionRelationshipsLimit { get; set; } public int CollectionsLimit { get; set; } }
ImportCiphersLimitationSettings
csharp
unoplatform__uno
src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml/AdaptiveTrigger.cs
{ "start": 252, "end": 1276 }
public partial class ____ : global::Microsoft.UI.Xaml.StateTriggerBase { // Skipping already declared property MinWindowWidth // Skipping already declared property MinWindowHeight // Skipping already declared property MinWindowHeightProperty // Skipping already declared property MinWindowWidthProperty // Skipping already declared method Microsoft.UI.Xaml.AdaptiveTrigger.AdaptiveTrigger() // Forced skipping of method Microsoft.UI.Xaml.AdaptiveTrigger.AdaptiveTrigger() // Forced skipping of method Microsoft.UI.Xaml.AdaptiveTrigger.MinWindowWidth.get // Forced skipping of method Microsoft.UI.Xaml.AdaptiveTrigger.MinWindowWidth.set // Forced skipping of method Microsoft.UI.Xaml.AdaptiveTrigger.MinWindowHeight.get // Forced skipping of method Microsoft.UI.Xaml.AdaptiveTrigger.MinWindowHeight.set // Forced skipping of method Microsoft.UI.Xaml.AdaptiveTrigger.MinWindowWidthProperty.get // Forced skipping of method Microsoft.UI.Xaml.AdaptiveTrigger.MinWindowHeightProperty.get } }
AdaptiveTrigger
csharp
MassTransit__MassTransit
tests/MassTransit.Analyzers.Tests/Helpers/CodeFixVerifier.Helper.cs
{ "start": 517, "end": 4085 }
partial class ____ : DiagnosticVerifier { /// <summary> /// Apply the inputted CodeAction to the inputted document. /// Meant to be used to apply codefixes. /// </summary> /// <param name="document">The Document to apply the fix on</param> /// <param name="codeAction">A CodeAction that will be applied to the Document.</param> /// <returns>A Document with the changes from the CodeAction</returns> static Document ApplyFix(Document document, CodeAction codeAction) { ImmutableArray<CodeActionOperation> operations = codeAction.GetOperationsAsync(CancellationToken.None).Result; var solution = operations.OfType<ApplyChangesOperation>().Single().ChangedSolution; return solution.GetDocument(document.Id); } /// <summary> /// Compare two collections of Diagnostics,and return a list of any new diagnostics that appear only in the second collection. /// Note: Considers Diagnostics to be the same if they have the same Ids. In the case of multiple diagnostics with the same Id in a row, /// this method may not necessarily return the new one. /// </summary> /// <param name="diagnostics">The Diagnostics that existed in the code before the CodeFix was applied</param> /// <param name="newDiagnostics">The Diagnostics that exist in the code after the CodeFix was applied</param> /// <returns> /// A list of Diagnostics that only surfaced in the code after the CodeFix was applied /// </returns> static IEnumerable<Diagnostic> GetNewDiagnostics(IEnumerable<Diagnostic> diagnostics, IEnumerable<Diagnostic> newDiagnostics) { Diagnostic[] oldArray = diagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray(); Diagnostic[] newArray = newDiagnostics.OrderBy(d => d.Location.SourceSpan.Start).ToArray(); var oldIndex = 0; var newIndex = 0; while (newIndex < newArray.Length) { if (oldIndex < oldArray.Length && oldArray[oldIndex].Id == newArray[newIndex].Id) { ++oldIndex; ++newIndex; } else yield return newArray[newIndex++]; } } /// <summary> /// Get the existing compiler diagnostics on the inputted document. /// </summary> /// <param name="document">The Document to run the compiler diagnostic analyzers on</param> /// <returns>The compiler diagnostics that were found in the code</returns> static IEnumerable<Diagnostic> GetCompilerDiagnostics(Document document) { return document.GetSemanticModelAsync().Result.GetDiagnostics(); } /// <summary> /// Given a document, turn it into a string based on the syntax root /// </summary> /// <param name="document">The Document to be converted to a string</param> /// <returns>A string containing the syntax of the Document after formatting</returns> static string GetStringFromDocument(Document document) { var simplifiedDoc = Simplifier.ReduceAsync(document, Simplifier.Annotation).Result; var root = simplifiedDoc.GetSyntaxRootAsync().Result; root = Formatter.Format(root, Formatter.Annotation, simplifiedDoc.Project.Solution.Workspace); return root.GetText().ToString(); } } }
CodeFixVerifier
csharp
dotnet__efcore
test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs
{ "start": 76101, "end": 76318 }
public class ____ { public int Id { get; set; } public RelatedEntity351 ParentEntity { get; set; } public IEnumerable<RelatedEntity353> ChildEntities { get; set; } }
RelatedEntity352
csharp
dotnet__extensions
test/Libraries/Microsoft.Extensions.Diagnostics.ResourceMonitoring.Kubernetes.Tests/Windows/AcceptanceTest.cs
{ "start": 804, "end": 8162 }
public class ____ { [Fact] public async Task WindowsContainerSnapshotProvider_MeasuredWithKubernetesMetadata() { const ulong LimitsMemory = 2_000; const ulong LimitsCpu = 2_000; // 2 cores in millicores const ulong RequestsMemory = 1_000; const ulong RequestsCpu = 1_000; // 1 core in millicores using var environmentSetup = new TestKubernetesEnvironmentSetup(); environmentSetup.SetupKubernetesEnvironment( "ACCEPTANCE_TEST_", LimitsMemory, LimitsCpu, RequestsMemory, RequestsCpu); var logger = new FakeLogger<WindowsContainerSnapshotProvider>(); var memoryInfoMock = new Mock<IMemoryInfo>(); var systemInfoMock = new Mock<ISystemInfo>(); var jobHandleMock = new Mock<IJobHandle>(); var processInfoMock = new Mock<IProcessInfo>(); var memStatus = new MEMORYSTATUSEX { TotalPhys = 3000UL }; memoryInfoMock.Setup(m => m.GetMemoryStatus()).Returns(() => memStatus); var sysInfo = new SYSTEM_INFO { NumberOfProcessors = 2 }; systemInfoMock.Setup(s => s.GetSystemInfo()).Returns(() => sysInfo); // Setup CPU accounting info with initial and updated values JOBOBJECT_BASIC_ACCOUNTING_INFORMATION initialAccountingInfo = new() { TotalKernelTime = 1000, TotalUserTime = 1000 }; JOBOBJECT_BASIC_ACCOUNTING_INFORMATION updatedAccountingInfo = new() { TotalKernelTime = 1500, // 500 ticks increase TotalUserTime = 1500 // 500 ticks increase }; var accountingCallCount = 0; jobHandleMock.Setup(j => j.GetBasicAccountingInfo()) .Returns(() => { accountingCallCount++; return accountingCallCount <= 1 ? initialAccountingInfo : updatedAccountingInfo; }); var cpuLimit = new JOBOBJECT_CPU_RATE_CONTROL_INFORMATION { CpuRate = 10_000 }; jobHandleMock.Setup(j => j.GetJobCpuLimitInfo()).Returns(() => cpuLimit); var limitInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION { JobMemoryLimit = new UIntPtr(LimitsMemory) }; jobHandleMock.Setup(j => j.GetExtendedLimitInfo()).Returns(() => limitInfo); ulong initialAppMemoryUsage = 200UL; ulong initialContainerMemoryUsage = 400UL; ulong updatedAppMemoryUsage = 600UL; ulong updatedContainerMemoryUsage = 1200UL; var processMemoryCallCount = 0; processInfoMock.Setup(p => p.GetCurrentProcessMemoryUsage()) .Returns(() => { processMemoryCallCount++; return processMemoryCallCount <= 1 ? initialAppMemoryUsage : updatedAppMemoryUsage; }); var containerMemoryCallCount = 0; processInfoMock.Setup(p => p.GetMemoryUsage()) .Returns(() => { containerMemoryCallCount++; return containerMemoryCallCount <= 1 ? initialContainerMemoryUsage : updatedContainerMemoryUsage; }); var fakeClock = new FakeTimeProvider(); using var meter = new Meter(nameof(WindowsContainerSnapshotProvider_MeasuredWithKubernetesMetadata)); var meterFactoryMock = new Mock<IMeterFactory>(); meterFactoryMock.Setup(x => x.Create(It.IsAny<MeterOptions>())).Returns(meter); using var containerCpuLimitMetricCollector = new MetricCollector<double>(meter, ResourceUtilizationInstruments.ContainerCpuLimitUtilization, fakeClock); using var containerMemoryLimitMetricCollector = new MetricCollector<double>(meter, ResourceUtilizationInstruments.ContainerMemoryLimitUtilization, fakeClock); using var containerCpuRequestMetricCollector = new MetricCollector<double>(meter, ResourceUtilizationInstruments.ContainerCpuRequestUtilization, fakeClock); using var containerMemoryRequestMetricCollector = new MetricCollector<double>(meter, ResourceUtilizationInstruments.ContainerMemoryRequestUtilization, fakeClock); var options = new ResourceMonitoringOptions { MemoryConsumptionRefreshInterval = TimeSpan.FromMilliseconds(2), CpuConsumptionRefreshInterval = TimeSpan.FromMilliseconds(2), UseZeroToOneRangeForMetrics = false }; var kubernetesMetadata = new KubernetesMetadata { LimitsMemory = LimitsMemory, LimitsCpu = LimitsCpu, RequestsMemory = RequestsMemory, RequestsCpu = RequestsCpu }; var kubernetesResourceQuotaProvider = new KubernetesResourceQuotaProvider(kubernetesMetadata); var snapshotProvider = new WindowsContainerSnapshotProvider( processInfoMock.Object, logger, meterFactoryMock.Object, () => jobHandleMock.Object, fakeClock, options, kubernetesResourceQuotaProvider); // Initial state containerCpuLimitMetricCollector.RecordObservableInstruments(); containerMemoryLimitMetricCollector.RecordObservableInstruments(); containerCpuRequestMetricCollector.RecordObservableInstruments(); containerMemoryRequestMetricCollector.RecordObservableInstruments(); Assert.NotNull(containerCpuLimitMetricCollector.LastMeasurement?.Value); Assert.NotNull(containerMemoryLimitMetricCollector.LastMeasurement?.Value); Assert.NotNull(containerCpuRequestMetricCollector.LastMeasurement?.Value); Assert.NotNull(containerMemoryRequestMetricCollector.LastMeasurement?.Value); // Initial CPU metrics should be NaN as no time has passed for calculation Assert.True(double.IsNaN(containerCpuLimitMetricCollector.LastMeasurement.Value)); Assert.True(double.IsNaN(containerCpuRequestMetricCollector.LastMeasurement.Value)); // Container memory: 400 bytes / 2000 bytes limit = 20% Assert.Equal(20, containerMemoryLimitMetricCollector.LastMeasurement.Value); // Container memory: 400 bytes / 1000 bytes request = 40% Assert.Equal(40, containerMemoryRequestMetricCollector.LastMeasurement.Value); // Advance time to trigger refresh fakeClock.Advance(options.MemoryConsumptionRefreshInterval); containerCpuLimitMetricCollector.RecordObservableInstruments(); containerMemoryLimitMetricCollector.RecordObservableInstruments(); containerCpuRequestMetricCollector.RecordObservableInstruments(); containerMemoryRequestMetricCollector.RecordObservableInstruments(); // CPU: 1000 ticks increase over 2ms = 2.5% utilization against 2 core limit Assert.Equal(2.5, containerCpuLimitMetricCollector.LastMeasurement.Value); // CPU: 2.5% of 2 cores against 1 core request = 5% Assert.Equal(5, containerCpuRequestMetricCollector.LastMeasurement.Value); // Container memory: 1200 bytes / 2000 bytes limit = 60% Assert.Equal(60, containerMemoryLimitMetricCollector.LastMeasurement.Value); // Container memory: 1200 bytes / 1000 bytes request = 120%, but Min() to 100% Assert.Equal(100, containerMemoryRequestMetricCollector.LastMeasurement.Value); await Task.CompletedTask; } }
AcceptanceTest
csharp
dotnetcore__Util
src/Util.Ui/Razor/Internal/IPartViewPathFinder.cs
{ "start": 79, "end": 347 }
public interface ____ { /// <summary> /// 查找分部视图的路径 /// </summary> /// <param name="viewPath">主视图路径</param> /// <param name="partViewName">分部视图名称, partial 标签的 name 属性</param> string Find( string viewPath, string partViewName ); }
IPartViewPathFinder
csharp
dotnet__maui
src/Controls/src/Core/Handlers/Items2/iOS/HeightConstrainedTemplatedCell2.cs
{ "start": 158, "end": 1344 }
partial class ____ : TemplatedCell2 { [Export("initWithFrame:")] [Microsoft.Maui.Controls.Internals.Preserve(Conditional = true)] public HeightConstrainedTemplatedCell2(CGRect frame) : base(frame) { } // public override void ConstrainTo(CGSize constraint) // { // ClearConstraints(); // ConstrainedDimension = constraint.Height; // } // protected override (bool, Size) NeedsContentSizeUpdate(Size currentSize) // { // if (PlatformHandler?.VirtualView == null) // { // return (false, currentSize); // } // // var bounds = PlatformHandler.VirtualView.Frame; // // if (bounds.Width <= 0 || bounds.Height <= 0) // { // return (false, currentSize); // } // // var desiredBounds = PlatformHandler.VirtualView.Measure(double.PositiveInfinity, bounds.Height); // // if (desiredBounds.Width == currentSize.Width) // { // // Nothing in the cell needs more room, so leave it as it is // return (false, currentSize); // } // // // Keep the current height in the updated content size // desiredBounds.Height = bounds.Height; // // return (true, desiredBounds); // } } }
HeightConstrainedTemplatedCell2
csharp
abpframework__abp
modules/openiddict/app/OpenIddict.Demo.Server/EntityFrameworkCore/ServerDataSeedContributor.cs
{ "start": 248, "end": 9387 }
public class ____ : IDataSeedContributor, ITransientDependency { private readonly ICurrentTenant _currentTenant; private readonly IOpenIddictApplicationManager _applicationManager; private readonly IOpenIddictScopeManager _scopeManager; public ServerDataSeedContributor( ICurrentTenant currentTenant, IOpenIddictApplicationManager applicationManager, IOpenIddictScopeManager scopeManager) { _currentTenant = currentTenant; _applicationManager = applicationManager; _scopeManager = scopeManager; } public async Task SeedAsync(DataSeedContext context) { if (await _scopeManager.FindByNameAsync("AbpAPI") == null) { await _scopeManager.CreateAsync(new OpenIddictScopeDescriptor() { Name = "AbpAPI", DisplayName = "Abp API access", DisplayNames = { [CultureInfo.GetCultureInfo("zh-Hans")] = "演示 API 访问", [CultureInfo.GetCultureInfo("tr")] = "API erişimi" }, Resources = { "AbpAPIResource" } }); } if (await _applicationManager.FindByClientIdAsync("AbpApp") == null) { await _applicationManager.CreateAsync(new OpenIddictApplicationDescriptor { ApplicationType = OpenIddictConstants.ApplicationTypes.Web, ClientId = "AbpApp", ClientSecret = "1q2w3e*", ClientType = OpenIddictConstants.ClientTypes.Confidential, ConsentType = OpenIddictConstants.ConsentTypes.Explicit, DisplayName = "Abp Application", PostLogoutRedirectUris = { new Uri("https://localhost:44302/signout-callback-oidc"), new Uri("http://localhost:4200") }, RedirectUris = { new Uri("https://localhost:44302/signin-oidc"), new Uri("http://localhost:4200") }, Permissions = { OpenIddictConstants.Permissions.Endpoints.Authorization, OpenIddictConstants.Permissions.Endpoints.Token, OpenIddictConstants.Permissions.Endpoints.DeviceAuthorization, OpenIddictConstants.Permissions.Endpoints.Introspection, OpenIddictConstants.Permissions.Endpoints.Revocation, OpenIddictConstants.Permissions.Endpoints.EndSession, OpenIddictConstants.Permissions.Endpoints.PushedAuthorization, OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode, OpenIddictConstants.Permissions.GrantTypes.Implicit, OpenIddictConstants.Permissions.GrantTypes.Password, OpenIddictConstants.Permissions.GrantTypes.RefreshToken, OpenIddictConstants.Permissions.GrantTypes.DeviceCode, OpenIddictConstants.Permissions.GrantTypes.ClientCredentials, OpenIddictConstants.Permissions.GrantTypes.TokenExchange, OpenIddictConstants.Permissions.Prefixes.GrantType + MyTokenExtensionGrant.ExtensionGrantName, OpenIddictConstants.Permissions.ResponseTypes.Code, OpenIddictConstants.Permissions.ResponseTypes.CodeIdToken, OpenIddictConstants.Permissions.ResponseTypes.CodeIdTokenToken, OpenIddictConstants.Permissions.ResponseTypes.CodeToken, OpenIddictConstants.Permissions.ResponseTypes.IdToken, OpenIddictConstants.Permissions.ResponseTypes.IdTokenToken, OpenIddictConstants.Permissions.ResponseTypes.None, OpenIddictConstants.Permissions.ResponseTypes.Token, OpenIddictConstants.Permissions.Scopes.Roles, OpenIddictConstants.Permissions.Scopes.Profile, OpenIddictConstants.Permissions.Scopes.Email, OpenIddictConstants.Permissions.Scopes.Address, OpenIddictConstants.Permissions.Scopes.Phone, OpenIddictConstants.Permissions.Prefixes.Scope + "AbpAPI" }, Settings = { // Use a shorter access token lifetime for tokens issued to the Postman application. [OpenIddictConstants.Settings.TokenLifetimes.AccessToken] = TimeSpan.FromMinutes(5).ToString("c", CultureInfo.InvariantCulture) } }); } if (await _applicationManager.FindByClientIdAsync("AbpBlazorWASMApp") == null) { await _applicationManager.CreateAsync(new OpenIddictApplicationDescriptor { ApplicationType = OpenIddictConstants.ApplicationTypes.Web, ClientId = "AbpBlazorWASMApp", ClientType = OpenIddictConstants.ClientTypes.Public, ConsentType = OpenIddictConstants.ConsentTypes.Explicit, DisplayName = "Abp Blazor WASM Application", PostLogoutRedirectUris = { new Uri("https://localhost:44304/authentication/logout-callback") }, RedirectUris = { new Uri("https://localhost:44304/authentication/login-callback") }, Permissions = { OpenIddictConstants.Permissions.Endpoints.Authorization, OpenIddictConstants.Permissions.Endpoints.Token, OpenIddictConstants.Permissions.Endpoints.DeviceAuthorization, OpenIddictConstants.Permissions.Endpoints.Introspection, OpenIddictConstants.Permissions.Endpoints.Revocation, OpenIddictConstants.Permissions.Endpoints.EndSession, OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode, OpenIddictConstants.Permissions.GrantTypes.Implicit, OpenIddictConstants.Permissions.GrantTypes.Password, OpenIddictConstants.Permissions.GrantTypes.RefreshToken, OpenIddictConstants.Permissions.GrantTypes.DeviceCode, OpenIddictConstants.Permissions.GrantTypes.ClientCredentials, OpenIddictConstants.Permissions.ResponseTypes.Code, OpenIddictConstants.Permissions.ResponseTypes.CodeIdToken, OpenIddictConstants.Permissions.ResponseTypes.CodeIdTokenToken, OpenIddictConstants.Permissions.ResponseTypes.CodeToken, OpenIddictConstants.Permissions.ResponseTypes.IdToken, OpenIddictConstants.Permissions.ResponseTypes.IdTokenToken, OpenIddictConstants.Permissions.ResponseTypes.None, OpenIddictConstants.Permissions.ResponseTypes.Token, OpenIddictConstants.Permissions.Scopes.Roles, OpenIddictConstants.Permissions.Scopes.Profile, OpenIddictConstants.Permissions.Scopes.Email, OpenIddictConstants.Permissions.Scopes.Address, OpenIddictConstants.Permissions.Scopes.Phone, OpenIddictConstants.Permissions.Prefixes.Scope + "AbpAPI" } }); } if (await _applicationManager.FindByClientIdAsync("Swagger") == null) { await _applicationManager.CreateAsync(new OpenIddictApplicationDescriptor { ApplicationType = OpenIddictConstants.ApplicationTypes.Web, ClientId = "Swagger", ClientType = OpenIddictConstants.ClientTypes.Public, ConsentType = OpenIddictConstants.ConsentTypes.Explicit, DisplayName = "Abp Swagger Application", RedirectUris = { new Uri("https://localhost:44303/swagger/oauth2-redirect.html") }, Permissions = { OpenIddictConstants.Permissions.Endpoints.Authorization, OpenIddictConstants.Permissions.Endpoints.Token, OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode, OpenIddictConstants.Permissions.ResponseTypes.Code, OpenIddictConstants.Permissions.Prefixes.Scope + "AbpAPI" }, Settings = { // Use a shorter access token lifetime for tokens issued to the Postman application. [OpenIddictConstants.Settings.TokenLifetimes.AccessToken] = TimeSpan.FromMinutes(5).ToString("c", CultureInfo.InvariantCulture) } }); } } }
ServerDataSeedContributor